text
stringlengths
54
60.6k
<commit_before>#include "json-to-value.hh" #include <variant> #include <nlohmann/json.hpp> #include <nlohmann/detail/exceptions.hpp> using json = nlohmann::json; using std::unique_ptr; namespace nix { // for more information, refer to // https://github.com/nlohmann/json/blob/master/include/nlohmann/detail/input/json_sax.hpp class JSONSax : nlohmann::json_sax<json> { class JSONState { protected: unique_ptr<JSONState> parent; Value * v; public: virtual unique_ptr<JSONState> resolve(EvalState &) { throw std::logic_error("tried to close toplevel json parser state"); }; explicit JSONState(unique_ptr<JSONState>&& p) : parent(std::move(p)), v(nullptr) {}; explicit JSONState(Value* v) : v(v) {}; JSONState(JSONState& p) = delete; Value& value(EvalState & state) { if (v == nullptr) v = state.allocValue(); return *v; }; virtual ~JSONState() {}; virtual void add() {}; }; class JSONObjectState : public JSONState { using JSONState::JSONState; ValueMap attrs = ValueMap(); virtual unique_ptr<JSONState> resolve(EvalState & state) override { Value& v = parent->value(state); state.mkAttrs(v, attrs.size()); for (auto & i : attrs) v.attrs->push_back(Attr(i.first, i.second)); return std::move(parent); } virtual void add() override { v = nullptr; }; public: void key(string_t& name, EvalState & state) { attrs[state.symbols.create(name)] = &value(state); } }; class JSONListState : public JSONState { ValueVector values = ValueVector(); virtual unique_ptr<JSONState> resolve(EvalState & state) override { Value& v = parent->value(state); state.mkList(v, values.size()); for (size_t n = 0; n < values.size(); ++n) { v.listElems()[n] = values[n]; } return std::move(parent); } virtual void add() override { values.push_back(v); v = nullptr; }; public: JSONListState(unique_ptr<JSONState>&& p, std::size_t reserve) : JSONState(std::move(p)) { values.reserve(reserve); } }; EvalState & state; unique_ptr<JSONState> rs; template<typename T, typename... Args> inline bool handle_value(T f, Args... args) { f(rs->value(state), args...); rs->add(); return true; } public: JSONSax(EvalState & state, Value & v) : state(state), rs(new JSONState(&v)) {}; bool null() { return handle_value(mkNull); } bool boolean(bool val) { return handle_value(mkBool, val); } bool number_integer(number_integer_t val) { return handle_value(mkInt, val); } bool number_unsigned(number_unsigned_t val) { return handle_value(mkInt, val); } bool number_float(number_float_t val, const string_t& s) { return handle_value(mkFloat, val); } bool string(string_t& val) { return handle_value<void(Value&, const char*)>(mkString, val.c_str()); } bool start_object(std::size_t len) { rs = std::make_unique<JSONObjectState>(std::move(rs)); return true; } bool key(string_t& name) { dynamic_cast<JSONObjectState*>(rs.get())->key(name, state); return true; } bool end_object() { rs = rs->resolve(state); rs->add(); return true; } bool end_array() { return end_object(); } bool start_array(size_t len) { rs = std::make_unique<JSONListState>(std::move(rs), len != std::numeric_limits<size_t>::max() ? len : 128); return true; } bool parse_error(std::size_t, const std::string&, const nlohmann::detail::exception& ex) { throw JSONParseError(ex.what()); } }; void parseJSON(EvalState & state, const string & s_, Value & v) { JSONSax parser(state, v); bool res = json::sax_parse(s_, &parser); if (!res) throw JSONParseError("Invalid JSON Value"); } } <commit_msg>Fix build<commit_after>#include "json-to-value.hh" #include <variant> #include <nlohmann/json.hpp> using json = nlohmann::json; using std::unique_ptr; namespace nix { // for more information, refer to // https://github.com/nlohmann/json/blob/master/include/nlohmann/detail/input/json_sax.hpp class JSONSax : nlohmann::json_sax<json> { class JSONState { protected: unique_ptr<JSONState> parent; Value * v; public: virtual unique_ptr<JSONState> resolve(EvalState &) { throw std::logic_error("tried to close toplevel json parser state"); }; explicit JSONState(unique_ptr<JSONState>&& p) : parent(std::move(p)), v(nullptr) {}; explicit JSONState(Value* v) : v(v) {}; JSONState(JSONState& p) = delete; Value& value(EvalState & state) { if (v == nullptr) v = state.allocValue(); return *v; }; virtual ~JSONState() {}; virtual void add() {}; }; class JSONObjectState : public JSONState { using JSONState::JSONState; ValueMap attrs = ValueMap(); virtual unique_ptr<JSONState> resolve(EvalState & state) override { Value& v = parent->value(state); state.mkAttrs(v, attrs.size()); for (auto & i : attrs) v.attrs->push_back(Attr(i.first, i.second)); return std::move(parent); } virtual void add() override { v = nullptr; }; public: void key(string_t& name, EvalState & state) { attrs[state.symbols.create(name)] = &value(state); } }; class JSONListState : public JSONState { ValueVector values = ValueVector(); virtual unique_ptr<JSONState> resolve(EvalState & state) override { Value& v = parent->value(state); state.mkList(v, values.size()); for (size_t n = 0; n < values.size(); ++n) { v.listElems()[n] = values[n]; } return std::move(parent); } virtual void add() override { values.push_back(v); v = nullptr; }; public: JSONListState(unique_ptr<JSONState>&& p, std::size_t reserve) : JSONState(std::move(p)) { values.reserve(reserve); } }; EvalState & state; unique_ptr<JSONState> rs; template<typename T, typename... Args> inline bool handle_value(T f, Args... args) { f(rs->value(state), args...); rs->add(); return true; } public: JSONSax(EvalState & state, Value & v) : state(state), rs(new JSONState(&v)) {}; bool null() { return handle_value(mkNull); } bool boolean(bool val) { return handle_value(mkBool, val); } bool number_integer(number_integer_t val) { return handle_value(mkInt, val); } bool number_unsigned(number_unsigned_t val) { return handle_value(mkInt, val); } bool number_float(number_float_t val, const string_t& s) { return handle_value(mkFloat, val); } bool string(string_t& val) { return handle_value<void(Value&, const char*)>(mkString, val.c_str()); } bool start_object(std::size_t len) { rs = std::make_unique<JSONObjectState>(std::move(rs)); return true; } bool key(string_t& name) { dynamic_cast<JSONObjectState*>(rs.get())->key(name, state); return true; } bool end_object() { rs = rs->resolve(state); rs->add(); return true; } bool end_array() { return end_object(); } bool start_array(size_t len) { rs = std::make_unique<JSONListState>(std::move(rs), len != std::numeric_limits<size_t>::max() ? len : 128); return true; } bool parse_error(std::size_t, const std::string&, const nlohmann::detail::exception& ex) { throw JSONParseError(ex.what()); } }; void parseJSON(EvalState & state, const string & s_, Value & v) { JSONSax parser(state, v); bool res = json::sax_parse(s_, &parser); if (!res) throw JSONParseError("Invalid JSON Value"); } } <|endoftext|>
<commit_before>const char* VERTEX_Z_PASS_SRC = "#version 330 core\n" "layout(location=0) in vec3 position;" "layout(location=1) in vec3 normal;" "layout(location=2) in vec2 texCoords;" "uniform mat4 model;" "uniform mat4 view;" "uniform mat4 projection;" "void main()" "{" " gl_Position = projection * view * model * vec4(position, 1.0);" "}"; const char* FRAGMENT_Z_PASS_SRC = "#version 330 core\n" "void main()" "{" "}"; const char* VERTEX_LIGHT_SRC = "#version 330 core\n" "layout(location=0) in vec3 position;" "layout(location=1) in vec3 normal;" "layout(location=2) in vec2 texCoords;" "out vec3 fNormal;" "out vec3 fPosition;" "out vec2 fTexCoords;" "uniform mat4 model;" "uniform mat4 view;" "uniform mat4 projection;" "void main()" "{" " gl_Position = projection * view * model * vec4(position, 1.0);" " fPosition = (model * vec4(position, 1.0)).xyz;" " fNormal = mat3(transpose(inverse(model))) * normal;" " fTexCoords = texCoords;" "}"; const char* FRAGMENT_LIGHT_SRC = "#version 330 core\n" "in vec3 fNormal;" "in vec3 fPosition;" "in vec2 fTexCoords;" "out vec4 outputColor;" "uniform vec3 lightPosition;" "uniform vec3 lightColor;" "uniform vec3 lightAtt;" "uniform vec3 viewPos;" "uniform samplerCube depthMap;" "uniform float far_plane;" "vec3 sampleOffsetDirections[4] = vec3[]" "(" " vec3(1, 1, 1), vec3( 1, -1, 1), vec3(-1, -1, 1), vec3(-1, 1, 1)" ");" "float ShadowCalculation(vec3 fragPos)" "{" " vec3 fragToLight = fragPos - lightPosition;" " float currentDepth = length(fragToLight);" " float shadow = 0.0;" " float bias = 0.5;" " int samples = 4;" " float viewDistance = length(viewPos - lightPosition);" " float diskRadius = 0.05;" " for (int i = 0; i < samples; ++i)" " {" " float closestDepth = texture(depthMap, fragToLight + sampleOffsetDirections[i] * diskRadius).r;" " closestDepth *= far_plane;" " if(currentDepth - bias > closestDepth) shadow += 1.0;" " }" " shadow /= float(samples);" " return shadow;" "}" "void main()" "{" " vec3 ambient = vec3(0.1, 0.1, 0.1);" " float dist = length(lightPosition - fPosition);" " float attenuation = 1.0f / (lightAtt.x + lightAtt.y * dist + lightAtt.z * dist * dist);" " float shadow = ShadowCalculation(fPosition);" " outputColor = vec4(ambient + (1.0 - shadow) * lightColor * attenuation, 1.0);" "}"; const char* VERTEX_SHADOW_SRC = "#version 330 core\n" "layout(location=0) in vec3 position;" "uniform mat4 model;" "void main()" "{" " gl_Position = model * vec4(position, 1.0);" "}"; const char* GEOM_SHADOW_SRC = "#version 330 core\n" "layout(triangles) in;" "layout(triangle_strip, max_vertices=18) out;" // 18 = 6 * 3 "uniform mat4 shadowMatrices[6];" // One matrix per face "out vec4 fPosition;" "void main()" "{" " for(int face = 0; face < 6; ++face)" // 6 faces " {" " gl_Layer = face;" // gl_Layer is built in: which cubemap part " for(int i = 0; i < 3; ++i)" // 3 vertices per face " {" " fPosition = gl_in[i].gl_Position;" " gl_Position = shadowMatrices[face] * fPosition;" " EmitVertex();" " }" " EndPrimitive();" " }" "}"; const char* FRAGMENT_SHADOW_SRC = "#version 330 core\n" "in vec4 fPosition;" "uniform vec3 lightPos;" "uniform float far_plane;" // camera frustum "void main()" "{" " float dist = length(fPosition.xyz - lightPos);" " dist = dist / far_plane;" // Linearize " gl_FragDepth = dist;" "}"; <commit_msg>Point shadows optimisation: hard shadows<commit_after>const char* VERTEX_Z_PASS_SRC = "#version 330 core\n" "layout(location=0) in vec3 position;" "layout(location=1) in vec3 normal;" "layout(location=2) in vec2 texCoords;" "uniform mat4 model;" "uniform mat4 view;" "uniform mat4 projection;" "void main()" "{" " gl_Position = projection * view * model * vec4(position, 1.0);" "}"; const char* FRAGMENT_Z_PASS_SRC = "#version 330 core\n" "void main()" "{" "}"; const char* VERTEX_LIGHT_SRC = "#version 330 core\n" "layout(location=0) in vec3 position;" "layout(location=1) in vec3 normal;" "layout(location=2) in vec2 texCoords;" "out vec3 fNormal;" "out vec3 fPosition;" "out vec2 fTexCoords;" "uniform mat4 model;" "uniform mat4 view;" "uniform mat4 projection;" "void main()" "{" " gl_Position = projection * view * model * vec4(position, 1.0);" " fPosition = (model * vec4(position, 1.0)).xyz;" " fNormal = mat3(transpose(inverse(model))) * normal;" " fTexCoords = texCoords;" "}"; const char* FRAGMENT_LIGHT_SRC = "#version 330 core\n" "in vec3 fNormal;" "in vec3 fPosition;" "in vec2 fTexCoords;" "out vec4 outputColor;" "uniform vec3 lightPosition;" "uniform vec3 lightColor;" "uniform vec3 lightAtt;" "uniform vec3 viewPos;" "uniform samplerCube depthMap;" "uniform float far_plane;" "float ShadowCalculation(vec3 fragPos)" "{" " vec3 fragToLight = fragPos - lightPosition;" " float currentDepth = length(fragToLight);" " float closestDepth = texture(depthMap, fragToLight).r * far_plane;" " float bias = 0.05;" " return currentDepth - bias > closestDepth ? 1.0 : 0.0;" "}" "void main()" "{" " vec3 ambient = vec3(0.1, 0.1, 0.1);" " float dist = length(lightPosition - fPosition);" " float attenuation = 1.0f / (lightAtt.x + lightAtt.y * dist + lightAtt.z * dist * dist);" " float shadow = ShadowCalculation(fPosition);" " outputColor = vec4(ambient + (1.0 - shadow) * lightColor * attenuation, 1.0);" "}"; const char* VERTEX_SHADOW_SRC = "#version 330 core\n" "layout(location=0) in vec3 position;" "uniform mat4 model;" "void main()" "{" " gl_Position = model * vec4(position, 1.0);" "}"; const char* GEOM_SHADOW_SRC = "#version 330 core\n" "layout(triangles) in;" "layout(triangle_strip, max_vertices=18) out;" // 18 = 6 * 3 "uniform mat4 shadowMatrices[6];" // One matrix per face "out vec4 fPosition;" "void main()" "{" " for(int face = 0; face < 6; ++face)" // 6 faces " {" " gl_Layer = face;" // gl_Layer is built in: which cubemap part " for(int i = 0; i < 3; ++i)" // 3 vertices per face " {" " fPosition = gl_in[i].gl_Position;" " gl_Position = shadowMatrices[face] * fPosition;" " EmitVertex();" " }" " EndPrimitive();" " }" "}"; const char* FRAGMENT_SHADOW_SRC = "#version 330 core\n" "in vec4 fPosition;" "uniform vec3 lightPos;" "uniform float far_plane;" // camera frustum "void main()" "{" " float dist = length(fPosition.xyz - lightPos);" " dist = dist / far_plane;" // Linearize " gl_FragDepth = dist;" "}"; <|endoftext|>
<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <algorithm> #include <memory> #include <set> #include <string> #include <unordered_map> #include <utility> #include <vector> #include "tensorflow/contrib/lite/toco/allocate_transient_arrays.h" #include "tensorflow/contrib/lite/toco/model.h" #include "tensorflow/contrib/lite/toco/model_flags.pb.h" #include "tensorflow/contrib/lite/toco/tooling_util.h" #include "tensorflow/core/platform/logging.h" namespace toco { namespace { // The life span of an array. struct ArrayLifespan { // If true, the array is persistent state (as in a RNN). In that case, // its allocation is permanent and the first_op, last_op members are // unused. (The term 'transient' is a misnomer and we should think in // terms of 'workspace' instead). bool persistent = false; // Index of the first op addressing that array. The array must be allocated // just before executing this op. std::size_t first_op = 0; // Index of the last op addressing that array. We want to deallocate the array // immediately after executing this op. std::size_t last_op = 0; }; bool StartsAt(const ArrayLifespan& lifespan, std::size_t op_index) { return !lifespan.persistent && lifespan.first_op == op_index; } bool EndsAt(const ArrayLifespan& lifespan, std::size_t op_index) { return !lifespan.persistent && lifespan.last_op == op_index; } // Helper function for ComputeArrayLifespans: updates one ArrayLifespan for // one array for one op. void UpdateArrayLifespan( const string& array_name, std::size_t op_index, std::unordered_map<string, ArrayLifespan>* array_lifespans) { if (array_lifespans->count(array_name)) { auto& lifespan = array_lifespans->at(array_name); if (!lifespan.persistent) { lifespan.first_op = std::min(lifespan.first_op, op_index); lifespan.last_op = std::max(lifespan.last_op, op_index); } } else { ArrayLifespan lifespan; lifespan.first_op = op_index; lifespan.last_op = op_index; (*array_lifespans)[array_name] = lifespan; } } // Computes the ArrayLifespan for each array. void ComputeArrayLifespans( const Model& model, std::unordered_map<string, ArrayLifespan>* array_lifespans) { CHECK(array_lifespans->empty()); for (const auto& rnn_state : model.flags.rnn_states()) { ArrayLifespan lifespan; lifespan.persistent = true; (*array_lifespans)[rnn_state.state_array()] = lifespan; } for (std::size_t op_index = 0; op_index < model.operators.size(); op_index++) { const auto& op = model.operators[op_index]; for (const auto& input : op->inputs) { UpdateArrayLifespan(input, op_index, array_lifespans); } for (const auto& output : op->outputs) { UpdateArrayLifespan(output, op_index, array_lifespans); } } } inline bool operator==(const Alloc& a, const Alloc& b) { CHECK(a.start != b.start || a.end == b.end); return a.start == b.start; } // Helper to keep track of total allocation size and of currently live // allocations, and containing the core allocation routine. class Allocator { public: Allocator() : total_size_(0) {} // Core allocation routine. void Allocate(std::size_t size, Alloc* result) { // Naive algorithm: pick the first gap between live allocations, // that is wide enough for the new array. std::size_t pos = 0; for (const auto& a : live_allocs_) { if (a.start >= pos + size) { result->start = pos; result->end = pos + size; live_allocs_.insert(*result); return; } pos = a.end; } // No sufficiently wide gap was found before an existing live allocation, // so we allocate the new array at the end of the allocation space. // We may then have to grow total_size_. total_size_ = std::max(total_size_, pos + size); result->start = pos; result->end = pos + size; live_allocs_.insert(*result); } void Deallocate(const Alloc& a) { auto iter = std::lower_bound(live_allocs_.begin(), live_allocs_.end(), a); CHECK(iter != live_allocs_.end()); CHECK(*iter == a); live_allocs_.erase(iter); } std::size_t total_size() const { return total_size_; } private: std::size_t total_size_; std::set<Alloc> live_allocs_; }; // Returns the required transient allocation size (in bytes) for a given array, // or 0 if it's not a transient array. std::size_t TransientArraySize(const Model& model, const string& array_name, std::size_t transient_data_alignment) { if (!IsAllocatableTransientArray(model, array_name)) { return 0; } const auto& array = &model.GetArray(array_name); CHECK(array->has_shape()) << "Array '" << array_name << "' doesn't have a shape"; if (array->data_type == ArrayDataType::kNone) { // Catch a typical issue at the moment with RNN states for (const auto& rnn_state : model.flags.rnn_states()) { if (rnn_state.state_array() == array_name) { LOG(FATAL) << "A RNN state array, " << array_name << ", still does not " << "have a known data type after all graph transformations have " << "run."; } } LOG(FATAL) << "An array, " << array_name << ", still does not " << "have a known data type after all graph transformations have " << "run."; } const std::size_t elem_size = ElementSize(array->data_type); const std::size_t raw_size = elem_size * RequiredBufferSizeForShape(array->shape()); const std::size_t rounded_size = RoundUpToNextMultipleOf(raw_size, transient_data_alignment); return rounded_size; } // Allocates an array: call this for every array just before the first // op where it is used. void AllocateTransientArray(const Model& model, const string& array_name, Allocator* allocator, std::size_t transient_data_alignment) { if (!IsAllocatableTransientArray(model, array_name)) { return; } const std::size_t size = TransientArraySize(model, array_name, transient_data_alignment); const auto& array = &model.GetArray(array_name); CHECK(!array->alloc); allocator->Allocate(size, &array->GetOrCreateAlloc()); } // Deallocates an array: call this for every array just after the last // op where it is used. void DeallocateTransientArray(const Model& model, const string& array_name, Allocator* allocator) { if (!IsAllocatableTransientArray(model, array_name)) { return; } const auto& array = &model.GetArray(array_name); CHECK(!!array->alloc); allocator->Deallocate(*array->alloc); } } // namespace void AllocateTransientArrays(Model* model, std::size_t transient_data_alignment) { // Precompute the lifespans for all arrays. std::unordered_map<string, ArrayLifespan> array_lifespans; ComputeArrayLifespans(*model, &array_lifespans); // In case of variable batch, our convention will be to compute the // allocations for batch==1, then let the inference code multiply all // the offsets by the actual runtime batch size. Conveniently, // the variable_batch and batch flags are mutually exclusive, and the default // value of batch is 1, so we have nothing special to do here. Let us // just guard this assumption with a CHECK: bool batchless_input_shapes = true; for (const auto& input_array : model->flags.input_arrays()) { if (!input_array.has_shape() || input_array.shape().dims().empty() || input_array.shape().dims(0) != 1) { batchless_input_shapes = false; break; } } CHECK(!model->flags.variable_batch() || batchless_input_shapes); Allocator allocator; // Construct a sorted map of array names, so that other layout engines can // match exactly. std::map<string, const Array*> ordered_arrays_map; for (const auto& pair : model->GetArrayMap()) { ordered_arrays_map[pair.first] = pair.second.get(); } // Allocate persistent arrays (like RNN states). For them, 'transient' // is a misnormer, should read 'workspace'. for (const auto& array_pair : ordered_arrays_map) { const string& array_name = array_pair.first; auto it = array_lifespans.find(array_name); if (it != array_lifespans.end() && it->second.persistent) { AllocateTransientArray(*model, array_name, &allocator, transient_data_alignment); } } for (std::size_t op_index = 0; op_index < model->operators.size(); op_index++) { const auto& op = model->operators[op_index]; // Allocate those arrays whose lifespan starts exactly here. std::vector<string> arrays_to_allocate; for (const auto& input : op->inputs) { if (StartsAt(array_lifespans[input], op_index)) { if (std::find(arrays_to_allocate.begin(), arrays_to_allocate.end(), input) == arrays_to_allocate.end()) { arrays_to_allocate.push_back(input); } } } for (const auto& output : op->outputs) { if (StartsAt(array_lifespans[output], op_index)) { if (std::find(arrays_to_allocate.begin(), arrays_to_allocate.end(), output) == arrays_to_allocate.end()) { arrays_to_allocate.push_back(output); } } } for (const string& array : arrays_to_allocate) { AllocateTransientArray(*model, array, &allocator, transient_data_alignment); } // Deallocate those arrays whose lifespan ends exactly here. std::vector<string> arrays_to_deallocate; for (const auto& input : op->inputs) { if (EndsAt(array_lifespans[input], op_index)) { if (std::find(arrays_to_deallocate.begin(), arrays_to_deallocate.end(), input) == arrays_to_deallocate.end()) { arrays_to_deallocate.push_back(input); } } } for (const auto& output : op->outputs) { if (EndsAt(array_lifespans[output], op_index)) { if (std::find(arrays_to_deallocate.begin(), arrays_to_deallocate.end(), output) == arrays_to_deallocate.end()) { arrays_to_deallocate.push_back(output); } } } for (const string& array : arrays_to_deallocate) { DeallocateTransientArray(*model, array, &allocator); } } // Just out of curiosity (not used in the actual allocation process) // evaluate the optimal total allocated size. // First, compute the size of persistent arrays. std::size_t optimal_transient_alloc_size = 0; std::size_t persistent_alloc_size = 0; for (const auto& array_pair : ordered_arrays_map) { const string& array_name = array_pair.first; auto it = array_lifespans.find(array_name); if (it != array_lifespans.end() && it->second.persistent) { persistent_alloc_size += TransientArraySize(*model, array_name, transient_data_alignment); } } for (const auto& op : model->operators) { // for each operator, compute the sum of the sizes of the array that must // be live during the execution of this operator, plus the size of // persistent arrays that must be live at all times. std::size_t size = persistent_alloc_size; for (const auto& input : op->inputs) { if (!array_lifespans[input].persistent) { size += TransientArraySize(*model, input, transient_data_alignment); } } for (const auto& output : op->outputs) { if (!array_lifespans[output].persistent) { size += TransientArraySize(*model, output, transient_data_alignment); } } // The optimal total size is the maximum of all operator-specific sizes. optimal_transient_alloc_size = std::max(optimal_transient_alloc_size, size); } model->transient_data_size = allocator.total_size(); model->transient_data_alignment = transient_data_alignment; CHECK_GE(model->transient_data_size, optimal_transient_alloc_size); LOG(INFO) << "Total transient array allocated size: " << model->transient_data_size << " bytes, " << "theoretical optimal value: " << optimal_transient_alloc_size << " bytes."; CheckInvariants(*model); } } // namespace toco <commit_msg>Fix up the support for the case where a given array name occurs multiple times in the inputs/outputs list of an op. The (non-essential) computation of the optimal workspace size had not been updated for that case, causing it to fail on a simple test case. Moreover, the initial implementation had some redundant usage of std::find that this CL moves to a shared helper function.<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <algorithm> #include <memory> #include <set> #include <string> #include <unordered_map> #include <utility> #include <vector> #include "tensorflow/contrib/lite/toco/allocate_transient_arrays.h" #include "tensorflow/contrib/lite/toco/model.h" #include "tensorflow/contrib/lite/toco/model_flags.pb.h" #include "tensorflow/contrib/lite/toco/tooling_util.h" #include "tensorflow/core/platform/logging.h" namespace toco { namespace { // The life span of an array. struct ArrayLifespan { // If true, the array is persistent state (as in a RNN). In that case, // its allocation is permanent and the first_op, last_op members are // unused. (The term 'transient' is a misnomer and we should think in // terms of 'workspace' instead). bool persistent = false; // Index of the first op addressing that array. The array must be allocated // just before executing this op. std::size_t first_op = 0; // Index of the last op addressing that array. We want to deallocate the array // immediately after executing this op. std::size_t last_op = 0; }; bool StartsAt(const ArrayLifespan& lifespan, std::size_t op_index) { return !lifespan.persistent && lifespan.first_op == op_index; } bool EndsAt(const ArrayLifespan& lifespan, std::size_t op_index) { return !lifespan.persistent && lifespan.last_op == op_index; } // Helper function for ComputeArrayLifespans: updates one ArrayLifespan for // one array for one op. void UpdateArrayLifespan( const string& array_name, std::size_t op_index, std::unordered_map<string, ArrayLifespan>* array_lifespans) { if (array_lifespans->count(array_name)) { auto& lifespan = array_lifespans->at(array_name); if (!lifespan.persistent) { lifespan.first_op = std::min(lifespan.first_op, op_index); lifespan.last_op = std::max(lifespan.last_op, op_index); } } else { ArrayLifespan lifespan; lifespan.first_op = op_index; lifespan.last_op = op_index; (*array_lifespans)[array_name] = lifespan; } } // Computes the ArrayLifespan for each array. void ComputeArrayLifespans( const Model& model, std::unordered_map<string, ArrayLifespan>* array_lifespans) { CHECK(array_lifespans->empty()); for (const auto& rnn_state : model.flags.rnn_states()) { ArrayLifespan lifespan; lifespan.persistent = true; (*array_lifespans)[rnn_state.state_array()] = lifespan; } for (std::size_t op_index = 0; op_index < model.operators.size(); op_index++) { const auto& op = model.operators[op_index]; for (const auto& input : op->inputs) { UpdateArrayLifespan(input, op_index, array_lifespans); } for (const auto& output : op->outputs) { UpdateArrayLifespan(output, op_index, array_lifespans); } } } inline bool operator==(const Alloc& a, const Alloc& b) { CHECK(a.start != b.start || a.end == b.end); return a.start == b.start; } // Helper to keep track of total allocation size and of currently live // allocations, and containing the core allocation routine. class Allocator { public: Allocator() : total_size_(0) {} // Core allocation routine. void Allocate(std::size_t size, Alloc* result) { // Naive algorithm: pick the first gap between live allocations, // that is wide enough for the new array. std::size_t pos = 0; for (const auto& a : live_allocs_) { if (a.start >= pos + size) { result->start = pos; result->end = pos + size; live_allocs_.insert(*result); return; } pos = a.end; } // No sufficiently wide gap was found before an existing live allocation, // so we allocate the new array at the end of the allocation space. // We may then have to grow total_size_. total_size_ = std::max(total_size_, pos + size); result->start = pos; result->end = pos + size; live_allocs_.insert(*result); } void Deallocate(const Alloc& a) { auto iter = std::lower_bound(live_allocs_.begin(), live_allocs_.end(), a); CHECK(iter != live_allocs_.end()); CHECK(*iter == a); live_allocs_.erase(iter); } std::size_t total_size() const { return total_size_; } private: std::size_t total_size_; std::set<Alloc> live_allocs_; }; // Returns the required transient allocation size (in bytes) for a given array, // or 0 if it's not a transient array. std::size_t TransientArraySize(const Model& model, const string& array_name, std::size_t transient_data_alignment) { if (!IsAllocatableTransientArray(model, array_name)) { return 0; } const auto& array = &model.GetArray(array_name); CHECK(array->has_shape()) << "Array '" << array_name << "' doesn't have a shape"; if (array->data_type == ArrayDataType::kNone) { // Catch a typical issue at the moment with RNN states for (const auto& rnn_state : model.flags.rnn_states()) { if (rnn_state.state_array() == array_name) { LOG(FATAL) << "A RNN state array, " << array_name << ", still does not " << "have a known data type after all graph transformations have " << "run."; } } LOG(FATAL) << "An array, " << array_name << ", still does not " << "have a known data type after all graph transformations have " << "run."; } const std::size_t elem_size = ElementSize(array->data_type); const std::size_t raw_size = elem_size * RequiredBufferSizeForShape(array->shape()); const std::size_t rounded_size = RoundUpToNextMultipleOf(raw_size, transient_data_alignment); return rounded_size; } // Allocates an array: call this for every array just before the first // op where it is used. void AllocateTransientArray(const Model& model, const string& array_name, Allocator* allocator, std::size_t transient_data_alignment) { if (!IsAllocatableTransientArray(model, array_name)) { return; } const std::size_t size = TransientArraySize(model, array_name, transient_data_alignment); const auto& array = &model.GetArray(array_name); CHECK(!array->alloc); allocator->Allocate(size, &array->GetOrCreateAlloc()); } // Deallocates an array: call this for every array just after the last // op where it is used. void DeallocateTransientArray(const Model& model, const string& array_name, Allocator* allocator) { if (!IsAllocatableTransientArray(model, array_name)) { return; } const auto& array = &model.GetArray(array_name); CHECK(!!array->alloc); allocator->Deallocate(*array->alloc); } void PushBackIfNotFound(const string& s, std::vector<string>* v) { if (std::find(v->begin(), v->end(), s) == v->end()) { v->push_back(s); } } } // namespace void AllocateTransientArrays(Model* model, std::size_t transient_data_alignment) { // Precompute the lifespans for all arrays. std::unordered_map<string, ArrayLifespan> array_lifespans; ComputeArrayLifespans(*model, &array_lifespans); // In case of variable batch, our convention will be to compute the // allocations for batch==1, then let the inference code multiply all // the offsets by the actual runtime batch size. Conveniently, // the variable_batch and batch flags are mutually exclusive, and the default // value of batch is 1, so we have nothing special to do here. Let us // just guard this assumption with a CHECK: bool batchless_input_shapes = true; for (const auto& input_array : model->flags.input_arrays()) { if (!input_array.has_shape() || input_array.shape().dims().empty() || input_array.shape().dims(0) != 1) { batchless_input_shapes = false; break; } } CHECK(!model->flags.variable_batch() || batchless_input_shapes); Allocator allocator; // Construct a sorted map of array names, so that other layout engines can // match exactly. std::map<string, const Array*> ordered_arrays_map; for (const auto& pair : model->GetArrayMap()) { ordered_arrays_map[pair.first] = pair.second.get(); } // Allocate persistent arrays (like RNN states). For them, 'transient' // is a misnormer, should read 'workspace'. for (const auto& array_pair : ordered_arrays_map) { const string& array_name = array_pair.first; auto it = array_lifespans.find(array_name); if (it != array_lifespans.end() && it->second.persistent) { AllocateTransientArray(*model, array_name, &allocator, transient_data_alignment); } } for (std::size_t op_index = 0; op_index < model->operators.size(); op_index++) { const auto& op = model->operators[op_index]; // Allocate those arrays whose lifespan starts exactly here. std::vector<string> arrays_to_allocate; for (const auto& input : op->inputs) { if (StartsAt(array_lifespans[input], op_index)) { PushBackIfNotFound(input, &arrays_to_allocate); } } for (const auto& output : op->outputs) { if (StartsAt(array_lifespans[output], op_index)) { PushBackIfNotFound(output, &arrays_to_allocate); } } for (const string& array : arrays_to_allocate) { AllocateTransientArray(*model, array, &allocator, transient_data_alignment); } // Deallocate those arrays whose lifespan ends exactly here. std::vector<string> arrays_to_deallocate; for (const auto& input : op->inputs) { if (EndsAt(array_lifespans[input], op_index)) { PushBackIfNotFound(input, &arrays_to_deallocate); } } for (const auto& output : op->outputs) { if (EndsAt(array_lifespans[output], op_index)) { PushBackIfNotFound(output, &arrays_to_deallocate); } } for (const string& array : arrays_to_deallocate) { DeallocateTransientArray(*model, array, &allocator); } } // Just out of curiosity (not used in the actual allocation process) // evaluate the optimal total allocated size. // First, compute the size of persistent arrays. std::size_t optimal_transient_alloc_size = 0; std::size_t persistent_alloc_size = 0; for (const auto& array_pair : ordered_arrays_map) { const string& array_name = array_pair.first; auto it = array_lifespans.find(array_name); if (it != array_lifespans.end() && it->second.persistent) { persistent_alloc_size += TransientArraySize(*model, array_name, transient_data_alignment); } } for (const auto& op : model->operators) { // for each operator, compute the sum of the sizes of the array that must // be live during the execution of this operator, plus the size of // persistent arrays that must be live at all times. std::vector<string> non_persistent_edges; for (const auto& input : op->inputs) { if (!array_lifespans[input].persistent) { PushBackIfNotFound(input, &non_persistent_edges); } } for (const auto& output : op->outputs) { if (!array_lifespans[output].persistent) { PushBackIfNotFound(output, &non_persistent_edges); } } std::size_t size = persistent_alloc_size; for (const string& edge : non_persistent_edges) { size += TransientArraySize(*model, edge, transient_data_alignment); } // The optimal total size is the maximum of all operator-specific sizes. optimal_transient_alloc_size = std::max(optimal_transient_alloc_size, size); } model->transient_data_size = allocator.total_size(); model->transient_data_alignment = transient_data_alignment; CHECK_GE(model->transient_data_size, optimal_transient_alloc_size); LOG(INFO) << "Total transient array allocated size: " << model->transient_data_size << " bytes, " << "theoretical optimal value: " << optimal_transient_alloc_size << " bytes."; CheckInvariants(*model); } } // namespace toco <|endoftext|>
<commit_before>#include <algorithm> #define NOMINMAX // Para que nadie nos redefina min max #include <sstream> #include "game_window.h" #include "../parser_yaml/parser_yaml.h" using namespace std; bool GameWindow::sdlInitialized = false; bool GameWindow::initialize() { Logger::getInstance()->writeInformation("Initializing graphics"); if (GameWindow::sdlInitialized) { Logger::getInstance()->writeWarning("SDL already initialized"); } else { atexit(SDL_Quit); if( SDL_Init( SDL_INIT_VIDEO ) < 0 ) { Logger::getInstance()->writeError("SDL could not initialize!"); Logger::getInstance()->writeError(SDL_GetError()); GameWindow::sdlInitialized = false; } else { GameWindow::sdlInitialized = true; } } return GameWindow::sdlInitialized; } GameWindow::GameWindow(Game& owner, Player& player, ParserYAML& parser) : AClient(owner, player), board(player.board), ancho_pantalla(parser.getPantalla().ancho), alto_pantalla(parser.getPantalla().alto), margen_pantalla(parser.getPantalla().margen_scroll), scroll_speed(parser.getPantalla().velocidad_scroll) { GameWindow::initialize(); window = SDL_CreateWindow(("Trabajo Práctico 7542: " + owner.getBoard()->name).c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, ancho_pantalla, alto_pantalla, SDL_WINDOW_SHOWN); Logger::getInstance()->writeInformation("Creating renderer"); renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED ); SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); // Color: negro opaco SDL_RenderClear(renderer); // Limpio pantalla inicialmente SDL_RenderPresent( renderer ); addSpriteSheet(ENTIDAD_DEFAULT_NOMBRE, ENTIDAD_DEFAULT_IMAGEN, ENTIDAD_DEFAULT_PIXEL_REF_X, ENTIDAD_DEFAULT_PIXEL_REF_Y, ENTIDAD_DEFAULT_ALTO_SPRITE, ENTIDAD_DEFAULT_ANCHO_SPRITE, ENTIDAD_DEFAULT_CANTIDAD_SPRITES, ENTIDAD_DEFAULT_FPS, ENTIDAD_DEFAULT_DELAY); addSpriteSheet(TERRENO_DEFAULT_NOMBRE, TERRENO_DEFAULT_IMAGEN, TERRENO_DEFAULT_PIXEL_REF_X, TERRENO_DEFAULT_PIXEL_REF_Y, TERRENO_DEFAULT_ALTO_SPRITE, TERRENO_DEFAULT_ANCHO_SPRITE, TERRENO_DEFAULT_CANTIDAD_SPRITES, TERRENO_DEFAULT_FPS, TERRENO_DEFAULT_DELAY); addSpriteSheet(PROTAGONISTA_DEFAULT_NOMBRE, PROTAGONISTA_DEFAULT_IMAGEN, PROTAGONISTA_DEFAULT_PIXEL_REF_X, PROTAGONISTA_DEFAULT_PIXEL_REF_Y, PROTAGONISTA_DEFAULT_ALTO_SPRITE, PROTAGONISTA_DEFAULT_ANCHO_SPRITE, PROTAGONISTA_DEFAULT_CANTIDAD_SPRITES, PROTAGONISTA_DEFAULT_FPS, PROTAGONISTA_DEFAULT_DELAY); auto tp = parser.getPantalla(); auto tc = parser.getConfiguracion(); for(auto& t : parser.getTiposEntidades()) { addSpriteSheet(t.nombre, t.imagen, t.pixel_ref_x, t.pixel_ref_y, t.alto_sprite, t.ancho_sprite, t.cantidad_sprites, t.fps, t.delay); } for(auto& t : parser.getTiposTerrenos()) { addSpriteSheet(t.nombre, t.imagen, t.pixel_ref_x, t.pixel_ref_y, t.alto_sprite, t.ancho_sprite, t.cantidad_sprites, t.fps, t.delay); } for (auto& t : parser.getTiposRecursos()) { addSpriteSheet(t.nombre, t.imagen, t.pixel_ref_x, t.pixel_ref_y, t.alto_sprite, t.ancho_sprite, t.cantidad_sprites, t.fps, t.delay); } focus(); selection = nullptr; } GameWindow::~GameWindow() { spriteSheets.clear(); Logger::getInstance()->writeInformation("Destroying renderer"); if (renderer) { SDL_DestroyRenderer(renderer); renderer = nullptr; } Logger::getInstance()->writeInformation("Destroying window"); if (window) { SDL_DestroyWindow(window); window = nullptr; } else { Logger::getInstance()->writeWarning("Window never initialized"); } } bool GameWindow::canDraw(Entity& entity) { if (!(&entity)) { return false; } SDL_Rect screenRect = {0, 0, ancho_pantalla, alto_pantalla}; auto it = spriteSheets.find(entity.name); if (it == spriteSheets.end()) { Logger::getInstance()->writeWarning("No existe SpriteSheet para este tipo de entidad" + entity.name); return false; } auto candidate = it->second->targetRect(entity); return SDL_HasIntersection(&screenRect, &candidate); } void GameWindow::render() { // Dibujar SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); SDL_RenderClear(renderer); // Dibujamos el terreno r2 margin(1,1), ul = screenToBoardPosition({0, 0}) - margin, // Upper Left ur = screenToBoardPosition({ancho_pantalla, 0}) - margin, // Upper Right bl = screenToBoardPosition({0, alto_pantalla}) + margin, // Bottom Left br = screenToBoardPosition({ancho_pantalla, alto_pantalla}) + margin; // Bottom Right double ud = ul.x + ul.y - 2, // Upper diagonal bd = bl.x + bl.y + 2, // Bottom diagonal ld = ul.x - ul.y - 2, // Left diagonal rd = ur.x - ur.y + 2; // Right diagonal for (size_t x = max(0.0, ul.x), maxx = min(((double)board.sizeX), br.x); x < maxx; x++) { if (x >= board.sizeX) { break; } for (size_t y = max(max(max(0.0, ur.y), ud - x), x - rd), maxy = min(min(min(((double)board.sizeY), bl.y), bd - x), x - ld); y < maxy; y++) { if (y >= board.sizeY) { break; } Entity & tile = board.getTerrain(x, y); if (&tile) { if (canDraw(tile)) { spriteSheets[tile.name]->render(tile, renderer); } } } } // Seleccionamos entidades que se pisan con la pantalla auto entities = board.selectEntities([this](shared_ptr<Entity> e) { return canDraw(*e);}); // Ordenamos las entidades por oclusión sort(entities.begin(), entities.end(), [](shared_ptr<Entity> a, shared_ptr<Entity> b) { return (a->size.x == a->size.y && b->size.x == b->size.y) ? (a->getPosition().x + a->getPosition().y + a->size.x < b->getPosition().x + b->getPosition().y + b->size.x) : ((a->getPosition().x + a->size.x < b->getPosition().x) || (a->getPosition().y + a->size.y < b->getPosition().y)) && !((b->getPosition().x + b->size.x <= a->getPosition().x) || (b->getPosition().y + b->size.y <= a->getPosition().y)); }); for(auto& e : entities) { auto it = spriteSheets.find(e->name); if(it == spriteSheets.end()){ Logger::getInstance()->writeWarning("No existe SpriteSheet para este tipo de entidad" + e->name); continue; } it->second->render(*e, renderer); } if (getSelection()) { Uint8 q = 255; SDL_SetRenderDrawColor(renderer, q, q, q, q); r2 p = getSelection()->getPosition(); r2 s = getSelection()->size; SDL_Point points[] = { boardToScreenPosition(p), boardToScreenPosition(p + r2(s.x, 0)), boardToScreenPosition(p + s), boardToScreenPosition(p + r2(0, s.y)), boardToScreenPosition(p) }; SDL_RenderDrawLines(renderer, points, 5); } SDL_RenderPresent(renderer); return; } void GameWindow::update(){ for(auto & kv : spriteSheets) { kv.second->update(); } processInput(); render(); return; } void GameWindow::addSpriteSheet(string name, string pPath, int pixelRefX, int pixelRefY, int altoSprite, int anchoSprite, int cantSprites, double fps, double delay) { auto it = spriteSheets.find(name); if(it != spriteSheets.end()) Logger::getInstance()->writeError("Ya existe un spriteSheet para el tipo de entidad con nombre " + name); else{ spriteSheets[name] = make_shared<SpriteSheet>(pPath, pixelRefX, pixelRefY, altoSprite, anchoSprite, cantSprites, fps, delay, *this); Logger::getInstance()->writeInformation("Se agrega spriteSheet para el tipo de entidad con nombre " + name); } } r2 GameWindow::screenToBoardPosition(SDL_Point screenPos) { double XsTerm = (double)((double)screenPos.x - ancho_pantalla/2)/(double)TILE_WIDTH_DEFAULT; double YsTerm = (double)((double)screenPos.y - alto_pantalla/2)/(double)TILE_HEIGHT_DEFAULT; return focusPosition + r2(XsTerm + YsTerm + .5, -XsTerm + YsTerm + .5); } SDL_Point GameWindow::boardToScreenPosition(r2 boardPos) { boardPos -= focusPosition; SDL_Point ret = { (int)((boardPos.x - boardPos.y) * TILE_WIDTH_DEFAULT / 2) + (ancho_pantalla) / 2, (int)((boardPos.x + boardPos.y) * TILE_HEIGHT_DEFAULT / 2) + (alto_pantalla - TILE_HEIGHT_DEFAULT) / 2}; return ret; } void GameWindow::processInput(){ SDL_GetMouseState(&mouse.x, &mouse.y); scroll(); // Procesar input del usuario while(SDL_PollEvent(EventHandler::getInstance()->getEvent())) { auto & e = *(EventHandler::getInstance()->getEvent()); switch(e.type) { case SDL_QUIT: owner.exit(); break; case SDL_KEYDOWN: Logger::getInstance()->writeInformation("Teclado"); switch(e.key.keysym.sym) { case SDLK_r: owner.restart(); break; case SDLK_SPACE: focus(); break; } break; case SDL_MOUSEBUTTONUP: ostringstream oss; oss << "Mouse en " << mouse.x << "," << mouse.y; // Conversion de coordenadas en pantalla a coordenadas mapa auto mouseBoard = screenToBoardPosition(mouse); oss << "; mapa: " << mouseBoard.x << "," << mouseBoard.y; Logger::getInstance()->writeInformation(oss.str().c_str()); if( EventHandler::getInstance()->getEvent()->button.button == SDL_BUTTON_LEFT ) { Logger::getInstance()->writeInformation("Boton Izquierdo"); boardMouse = screenToBoardPosition(mouse); setSelection(); if (selectionController()) { if (!(SDL_GetModState()&KMOD_SHIFT)) { getSelection()->unsetTarget(); } getSelection()->addTarget(mouseBoard); } } if( EventHandler::getInstance()->getEvent()->button.button == SDL_BUTTON_RIGHT) { Logger::getInstance()->writeInformation("Boton derecho"); } break; } } } void GameWindow::scroll(){ double ds = (double)scroll_speed * (double)(board.dt) / 1000.0; //deltascroll r2 df; if(mouse.x <= margen_pantalla) { auto dsi = interpolate(mouse.x, 0, margen_pantalla, ds, 0); df += {-dsi, dsi}; Logger::getInstance()->writeInformation("Scrolleando hacia la izquierda"); } if(mouse.x >= ancho_pantalla - margen_pantalla){ auto dsi = interpolate(mouse.x, ancho_pantalla - margen_pantalla, ancho_pantalla, 0, ds); df += {dsi, -dsi}; Logger::getInstance()->writeInformation("Scrolleando hacia la derecha"); } if(mouse.y <= margen_pantalla) { auto dsi = interpolate(mouse.y, 0, margen_pantalla, ds, 0); df += {-dsi, -dsi}; Logger::getInstance()->writeInformation("Scrolleando hacia arriba"); } if(mouse.y >= alto_pantalla - margen_pantalla) { auto dsi = interpolate(mouse.y, alto_pantalla - margen_pantalla, alto_pantalla, 0, ds); df += {dsi, dsi}; Logger::getInstance()->writeInformation("Scrolleando hacia abajo"); } focus(focusPosition + df); } void GameWindow::focus(r2 newFocus) { focusPosition.x = clip(newFocus.x, 0, board.sizeX - 1); focusPosition.y = clip(newFocus.y, 0, board.sizeY - 1); } void GameWindow::focus() { auto protagonist = getSelection(); if (protagonist) { focus(protagonist->getPosition()); } } r2 GameWindow::getFocus() { return focusPosition; } shared_ptr<Entity> GameWindow::getSelection() { return selection; } void GameWindow::setSelection() { shared_ptr<Entity> s = board.findEntity(rectangle(r2(floor(boardMouse.x), floor(boardMouse.y)),r2(1,1))); if (s) selection = s; } bool GameWindow::selectionController() { return selection != nullptr && selection->owner.name == player.name; } <commit_msg>Separo right click para target, s para parar<commit_after>#include <algorithm> #define NOMINMAX // Para que nadie nos redefina min max #include <sstream> #include "game_window.h" #include "../parser_yaml/parser_yaml.h" using namespace std; bool GameWindow::sdlInitialized = false; bool GameWindow::initialize() { Logger::getInstance()->writeInformation("Initializing graphics"); if (GameWindow::sdlInitialized) { Logger::getInstance()->writeWarning("SDL already initialized"); } else { atexit(SDL_Quit); if( SDL_Init( SDL_INIT_VIDEO ) < 0 ) { Logger::getInstance()->writeError("SDL could not initialize!"); Logger::getInstance()->writeError(SDL_GetError()); GameWindow::sdlInitialized = false; } else { GameWindow::sdlInitialized = true; } } return GameWindow::sdlInitialized; } GameWindow::GameWindow(Game& owner, Player& player, ParserYAML& parser) : AClient(owner, player), board(player.board), ancho_pantalla(parser.getPantalla().ancho), alto_pantalla(parser.getPantalla().alto), margen_pantalla(parser.getPantalla().margen_scroll), scroll_speed(parser.getPantalla().velocidad_scroll) { GameWindow::initialize(); window = SDL_CreateWindow(("Trabajo Práctico 7542: " + owner.getBoard()->name).c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, ancho_pantalla, alto_pantalla, SDL_WINDOW_SHOWN); Logger::getInstance()->writeInformation("Creating renderer"); renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED ); SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); // Color: negro opaco SDL_RenderClear(renderer); // Limpio pantalla inicialmente SDL_RenderPresent( renderer ); addSpriteSheet(ENTIDAD_DEFAULT_NOMBRE, ENTIDAD_DEFAULT_IMAGEN, ENTIDAD_DEFAULT_PIXEL_REF_X, ENTIDAD_DEFAULT_PIXEL_REF_Y, ENTIDAD_DEFAULT_ALTO_SPRITE, ENTIDAD_DEFAULT_ANCHO_SPRITE, ENTIDAD_DEFAULT_CANTIDAD_SPRITES, ENTIDAD_DEFAULT_FPS, ENTIDAD_DEFAULT_DELAY); addSpriteSheet(TERRENO_DEFAULT_NOMBRE, TERRENO_DEFAULT_IMAGEN, TERRENO_DEFAULT_PIXEL_REF_X, TERRENO_DEFAULT_PIXEL_REF_Y, TERRENO_DEFAULT_ALTO_SPRITE, TERRENO_DEFAULT_ANCHO_SPRITE, TERRENO_DEFAULT_CANTIDAD_SPRITES, TERRENO_DEFAULT_FPS, TERRENO_DEFAULT_DELAY); addSpriteSheet(PROTAGONISTA_DEFAULT_NOMBRE, PROTAGONISTA_DEFAULT_IMAGEN, PROTAGONISTA_DEFAULT_PIXEL_REF_X, PROTAGONISTA_DEFAULT_PIXEL_REF_Y, PROTAGONISTA_DEFAULT_ALTO_SPRITE, PROTAGONISTA_DEFAULT_ANCHO_SPRITE, PROTAGONISTA_DEFAULT_CANTIDAD_SPRITES, PROTAGONISTA_DEFAULT_FPS, PROTAGONISTA_DEFAULT_DELAY); auto tp = parser.getPantalla(); auto tc = parser.getConfiguracion(); for(auto& t : parser.getTiposEntidades()) { addSpriteSheet(t.nombre, t.imagen, t.pixel_ref_x, t.pixel_ref_y, t.alto_sprite, t.ancho_sprite, t.cantidad_sprites, t.fps, t.delay); } for(auto& t : parser.getTiposTerrenos()) { addSpriteSheet(t.nombre, t.imagen, t.pixel_ref_x, t.pixel_ref_y, t.alto_sprite, t.ancho_sprite, t.cantidad_sprites, t.fps, t.delay); } for (auto& t : parser.getTiposRecursos()) { addSpriteSheet(t.nombre, t.imagen, t.pixel_ref_x, t.pixel_ref_y, t.alto_sprite, t.ancho_sprite, t.cantidad_sprites, t.fps, t.delay); } focus(); } GameWindow::~GameWindow() { spriteSheets.clear(); Logger::getInstance()->writeInformation("Destroying renderer"); if (renderer) { SDL_DestroyRenderer(renderer); renderer = nullptr; } Logger::getInstance()->writeInformation("Destroying window"); if (window) { SDL_DestroyWindow(window); window = nullptr; } else { Logger::getInstance()->writeWarning("Window never initialized"); } selection = nullptr; } bool GameWindow::canDraw(Entity& entity) { if (!(&entity)) { return false; } SDL_Rect screenRect = {0, 0, ancho_pantalla, alto_pantalla}; auto it = spriteSheets.find(entity.name); if (it == spriteSheets.end()) { Logger::getInstance()->writeWarning("No existe SpriteSheet para este tipo de entidad" + entity.name); return false; } auto candidate = it->second->targetRect(entity); return SDL_HasIntersection(&screenRect, &candidate); } void GameWindow::render() { // Dibujar SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); SDL_RenderClear(renderer); // Dibujamos el terreno r2 margin(1,1), ul = screenToBoardPosition({0, 0}) - margin, // Upper Left ur = screenToBoardPosition({ancho_pantalla, 0}) - margin, // Upper Right bl = screenToBoardPosition({0, alto_pantalla}) + margin, // Bottom Left br = screenToBoardPosition({ancho_pantalla, alto_pantalla}) + margin; // Bottom Right double ud = ul.x + ul.y - 2, // Upper diagonal bd = bl.x + bl.y + 2, // Bottom diagonal ld = ul.x - ul.y - 2, // Left diagonal rd = ur.x - ur.y + 2; // Right diagonal for (size_t x = max(0.0, ul.x), maxx = min(((double)board.sizeX), br.x); x < maxx; x++) { if (x >= board.sizeX) { break; } for (size_t y = max(max(max(0.0, ur.y), ud - x), x - rd), maxy = min(min(min(((double)board.sizeY), bl.y), bd - x), x - ld); y < maxy; y++) { if (y >= board.sizeY) { break; } Entity & tile = board.getTerrain(x, y); if (&tile) { if (canDraw(tile)) { spriteSheets[tile.name]->render(tile, renderer); } } } } // Seleccionamos entidades que se pisan con la pantalla auto entities = board.selectEntities([this](shared_ptr<Entity> e) { return canDraw(*e);}); // Ordenamos las entidades por oclusión sort(entities.begin(), entities.end(), [](shared_ptr<Entity> a, shared_ptr<Entity> b) { return (a->size.x == a->size.y && b->size.x == b->size.y) ? (a->getPosition().x + a->getPosition().y + a->size.x < b->getPosition().x + b->getPosition().y + b->size.x) : ((a->getPosition().x + a->size.x < b->getPosition().x) || (a->getPosition().y + a->size.y < b->getPosition().y)) && !((b->getPosition().x + b->size.x <= a->getPosition().x) || (b->getPosition().y + b->size.y <= a->getPosition().y)); }); for(auto& e : entities) { auto it = spriteSheets.find(e->name); if(it == spriteSheets.end()){ Logger::getInstance()->writeWarning("No existe SpriteSheet para este tipo de entidad" + e->name); continue; } it->second->render(*e, renderer); } if (getSelection()) { Uint8 q = 255; SDL_SetRenderDrawColor(renderer, q, q, q, q); r2 p = getSelection()->getPosition(); r2 s = getSelection()->size; SDL_Point points[] = { boardToScreenPosition(p), boardToScreenPosition(p + r2(s.x, 0)), boardToScreenPosition(p + s), boardToScreenPosition(p + r2(0, s.y)), boardToScreenPosition(p)}; SDL_RenderDrawLines(renderer, points, 5); } SDL_RenderPresent(renderer); return; } void GameWindow::update(){ for(auto & kv : spriteSheets) { kv.second->update(); } processInput(); render(); return; } void GameWindow::addSpriteSheet(string name, string pPath, int pixelRefX, int pixelRefY, int altoSprite, int anchoSprite, int cantSprites, double fps, double delay) { auto it = spriteSheets.find(name); if(it != spriteSheets.end()) Logger::getInstance()->writeError("Ya existe un spriteSheet para el tipo de entidad con nombre " + name); else{ spriteSheets[name] = make_shared<SpriteSheet>(pPath, pixelRefX, pixelRefY, altoSprite, anchoSprite, cantSprites, fps, delay, *this); Logger::getInstance()->writeInformation("Se agrega spriteSheet para el tipo de entidad con nombre " + name); } } r2 GameWindow::screenToBoardPosition(SDL_Point screenPos) { double XsTerm = (double)((double)screenPos.x - ancho_pantalla/2)/(double)TILE_WIDTH_DEFAULT; double YsTerm = (double)((double)screenPos.y - alto_pantalla/2)/(double)TILE_HEIGHT_DEFAULT; return focusPosition + r2(XsTerm + YsTerm + .5, -XsTerm + YsTerm + .5); } SDL_Point GameWindow::boardToScreenPosition(r2 boardPos) { boardPos -= focusPosition; SDL_Point ret = { (int)((boardPos.x - boardPos.y) * TILE_WIDTH_DEFAULT / 2) + (ancho_pantalla) / 2, (int)((boardPos.x + boardPos.y) * TILE_HEIGHT_DEFAULT / 2) + (alto_pantalla - TILE_HEIGHT_DEFAULT) / 2}; return ret; } void GameWindow::processInput(){ SDL_GetMouseState(&mouse.x, &mouse.y); scroll(); // Procesar input del usuario while(SDL_PollEvent(EventHandler::getInstance()->getEvent())) { auto & e = *(EventHandler::getInstance()->getEvent()); switch(e.type) { case SDL_QUIT: owner.exit(); break; case SDL_KEYDOWN: Logger::getInstance()->writeInformation("Teclado"); switch(e.key.keysym.sym) { case SDLK_r: owner.restart(); break; case SDLK_s: if (selectionController()) { getSelection()->unsetTarget(); } break; case SDLK_SPACE: focus(); break; } break; case SDL_MOUSEBUTTONUP: ostringstream oss; oss << "Mouse en " << mouse.x << "," << mouse.y; // Conversion de coordenadas en pantalla a coordenadas mapa auto mouseBoard = screenToBoardPosition(mouse); oss << "; mapa: " << mouseBoard.x << "," << mouseBoard.y; Logger::getInstance()->writeInformation(oss.str().c_str()); if( EventHandler::getInstance()->getEvent()->button.button == SDL_BUTTON_LEFT ) { Logger::getInstance()->writeInformation("Boton Izquierdo"); boardMouse = screenToBoardPosition(mouse); setSelection(); } if( EventHandler::getInstance()->getEvent()->button.button == SDL_BUTTON_RIGHT) { Logger::getInstance()->writeInformation("Boton derecho"); if (selectionController()) { if (!(SDL_GetModState()&KMOD_SHIFT)) { getSelection()->unsetTarget(); } getSelection()->addTarget(mouseBoard); } } break; } } } void GameWindow::scroll(){ double ds = (double)scroll_speed * (double)(board.dt) / 1000.0; //deltascroll r2 df; if(mouse.x <= margen_pantalla) { auto dsi = interpolate(mouse.x, 0, margen_pantalla, ds, 0); df += {-dsi, dsi}; Logger::getInstance()->writeInformation("Scrolleando hacia la izquierda"); } if(mouse.x >= ancho_pantalla - margen_pantalla){ auto dsi = interpolate(mouse.x, ancho_pantalla - margen_pantalla, ancho_pantalla, 0, ds); df += {dsi, -dsi}; Logger::getInstance()->writeInformation("Scrolleando hacia la derecha"); } if(mouse.y <= margen_pantalla) { auto dsi = interpolate(mouse.y, 0, margen_pantalla, ds, 0); df += {-dsi, -dsi}; Logger::getInstance()->writeInformation("Scrolleando hacia arriba"); } if(mouse.y >= alto_pantalla - margen_pantalla) { auto dsi = interpolate(mouse.y, alto_pantalla - margen_pantalla, alto_pantalla, 0, ds); df += {dsi, dsi}; Logger::getInstance()->writeInformation("Scrolleando hacia abajo"); } focus(focusPosition + df); } void GameWindow::focus(r2 newFocus) { focusPosition.x = clip(newFocus.x, 0, board.sizeX - 1); focusPosition.y = clip(newFocus.y, 0, board.sizeY - 1); } void GameWindow::focus() { auto protagonist = getSelection(); if (protagonist) { focus(protagonist->getPosition()); } } r2 GameWindow::getFocus() { return focusPosition; } shared_ptr<Entity> GameWindow::getSelection() { return selection; } void GameWindow::setSelection() { selection = board.findEntity(rectangle({floor(boardMouse.x), floor(boardMouse.y)}, {1,1})); } bool GameWindow::selectionController() { return selection != nullptr && selection->owner.name == player.name; } <|endoftext|>
<commit_before>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. */ #include <numeric> #include <thread> #include <adios2.h> #include <adios2/common/ADIOSMacros.h> #include <adios2/helper/adiosFunctions.h> #include <gtest/gtest.h> using namespace adios2; size_t print_lines = 0; size_t to_print_lines = 10; template <class T> void GenData(std::vector<std::complex<T>> &data, const size_t step) { for (size_t i = 0; i < data.size(); ++i) { data[i] = {static_cast<T>(i + 10000 + step * 100), static_cast<T>(i + 10000)}; } } template <class T> void GenData(std::vector<T> &data, const size_t step) { for (size_t i = 0; i < data.size(); ++i) { data[i] = i + 10000 + step * 100; } } template <class T> void PrintData(const T *data, const size_t size, const size_t step) { std::cout << "Step: " << step << " ["; size_t printsize = 32; if (size < printsize) { printsize = size; } for (size_t i = 0; i < printsize; ++i) { std::cout << data[i] << " "; } std::cout << "]" << std::endl; } template <class T> void VerifyData(const std::complex<T> *data, const size_t size, size_t step) { std::vector<std::complex<T>> tmpdata(size); GenData(tmpdata, step); for (size_t i = 0; i < size; ++i) { ASSERT_EQ(data[i], tmpdata[i]); } } template <class T> void VerifyData(const T *data, const size_t size, size_t step) { std::vector<T> tmpdata(size); GenData(tmpdata, step); for (size_t i = 0; i < size; ++i) { ASSERT_EQ(data[i], tmpdata[i]); } } template <class T> void VerifyData(const std::vector<T> &data, const size_t step) { VerifyData(data.data(), data.size(), step); } void DataManWriter(const Dims &shape, const Dims &start, const Dims &count, const size_t steps, const adios2::Params &engineParams) { size_t datasize = std::accumulate(count.begin(), count.end(), 1, std::multiplies<size_t>()); adios2::ADIOS adios; adios2::IO dataManIO = adios.DeclareIO("WAN"); dataManIO.SetEngine("DataMan"); dataManIO.SetParameters(engineParams); std::vector<char> myChars(datasize); std::vector<unsigned char> myUChars(datasize); std::vector<short> myShorts(datasize); std::vector<unsigned short> myUShorts(datasize); std::vector<int> myInts(datasize); std::vector<unsigned int> myUInts(datasize); std::vector<float> myFloats(datasize); std::vector<double> myDoubles(datasize); std::vector<std::complex<float>> myComplexes(datasize); std::vector<std::complex<double>> myDComplexes(datasize); auto bpChars = dataManIO.DefineVariable<char>("bpChars", shape, start, count); auto bpUChars = dataManIO.DefineVariable<unsigned char>("bpUChars", shape, start, count); auto bpShorts = dataManIO.DefineVariable<short>("bpShorts", shape, start, count); auto bpUShorts = dataManIO.DefineVariable<unsigned short>( "bpUShorts", shape, start, count); auto bpInts = dataManIO.DefineVariable<int>("bpInts", shape, start, count); auto bpUInts = dataManIO.DefineVariable<unsigned int>("bpUInts", shape, start, count); auto bpFloats = dataManIO.DefineVariable<float>("bpFloats", shape, start, count); auto bpDoubles = dataManIO.DefineVariable<double>("bpDoubles", shape, start, count); auto bpComplexes = dataManIO.DefineVariable<std::complex<float>>( "bpComplexes", shape, start, count); auto bpDComplexes = dataManIO.DefineVariable<std::complex<double>>( "bpDComplexes", shape, start, count); auto bpUInt64s = dataManIO.DefineVariable<uint64_t>("bpUInt64s"); dataManIO.DefineAttribute<int>("AttInt", 110); adios2::Engine dataManWriter = dataManIO.Open("stream", adios2::Mode::Write); for (uint64_t i = 0; i < steps; ++i) { dataManWriter.BeginStep(); GenData(myChars, i); GenData(myUChars, i); GenData(myShorts, i); GenData(myUShorts, i); GenData(myInts, i); GenData(myUInts, i); GenData(myFloats, i); GenData(myDoubles, i); GenData(myComplexes, i); GenData(myDComplexes, i); dataManWriter.Put(bpChars, myChars.data(), adios2::Mode::Sync); dataManWriter.Put(bpUChars, myUChars.data(), adios2::Mode::Sync); dataManWriter.Put(bpShorts, myShorts.data(), adios2::Mode::Sync); dataManWriter.Put(bpUShorts, myUShorts.data(), adios2::Mode::Sync); dataManWriter.Put(bpInts, myInts.data(), adios2::Mode::Sync); dataManWriter.Put(bpUInts, myUInts.data(), adios2::Mode::Sync); dataManWriter.Put(bpFloats, myFloats.data(), adios2::Mode::Sync); dataManWriter.Put(bpDoubles, myDoubles.data(), adios2::Mode::Sync); dataManWriter.Put(bpComplexes, myComplexes.data(), adios2::Mode::Sync); dataManWriter.Put(bpDComplexes, myDComplexes.data(), adios2::Mode::Sync); dataManWriter.Put(bpUInt64s, i); dataManWriter.EndStep(); } dataManWriter.Close(); } void DataManReader(const Dims &shape, const Dims &start, const Dims &count, const size_t steps, const adios2::Params &engineParams) { size_t datasize = std::accumulate(count.begin(), count.end(), 1, std::multiplies<size_t>()); adios2::ADIOS adios; adios2::IO dataManIO = adios.DeclareIO("WAN"); dataManIO.SetEngine("DataMan"); dataManIO.SetParameters(engineParams); adios2::Engine dataManReader = dataManIO.Open("stream", adios2::Mode::Read); std::vector<char> myChars(datasize); std::vector<unsigned char> myUChars(datasize); std::vector<short> myShorts(datasize); std::vector<unsigned short> myUShorts(datasize); std::vector<int> myInts(datasize); std::vector<unsigned int> myUInts(datasize); std::vector<float> myFloats(datasize); std::vector<double> myDoubles(datasize); std::vector<std::complex<float>> myComplexes(datasize); std::vector<std::complex<double>> myDComplexes(datasize); bool received_steps = false; size_t currentStep; while (true) { adios2::StepStatus status = dataManReader.BeginStep(StepMode::Read, 5); if (status == adios2::StepStatus::OK) { received_steps = true; const auto &vars = dataManIO.AvailableVariables(); ASSERT_EQ(vars.size(), 11); currentStep = dataManReader.CurrentStep(); adios2::Variable<char> bpChars = dataManIO.InquireVariable<char>("bpChars"); adios2::Variable<unsigned char> bpUChars = dataManIO.InquireVariable<unsigned char>("bpUChars"); adios2::Variable<short> bpShorts = dataManIO.InquireVariable<short>("bpShorts"); adios2::Variable<unsigned short> bpUShorts = dataManIO.InquireVariable<unsigned short>("bpUShorts"); adios2::Variable<int> bpInts = dataManIO.InquireVariable<int>("bpInts"); adios2::Variable<unsigned int> bpUInts = dataManIO.InquireVariable<unsigned int>("bpUInts"); adios2::Variable<float> bpFloats = dataManIO.InquireVariable<float>("bpFloats"); adios2::Variable<double> bpDoubles = dataManIO.InquireVariable<double>("bpDoubles"); adios2::Variable<std::complex<float>> bpComplexes = dataManIO.InquireVariable<std::complex<float>>("bpComplexes"); adios2::Variable<std::complex<double>> bpDComplexes = dataManIO.InquireVariable<std::complex<double>>("bpDComplexes"); adios2::Variable<uint64_t> bpUInt64s = dataManIO.InquireVariable<uint64_t>("bpUInt64s"); auto charsBlocksInfo = dataManReader.AllStepsBlocksInfo(bpChars); bpChars.SetSelection({start, count}); bpUChars.SetSelection({start, count}); bpShorts.SetSelection({start, count}); bpUShorts.SetSelection({start, count}); bpInts.SetSelection({start, count}); bpUInts.SetSelection({start, count}); bpFloats.SetSelection({start, count}); bpDoubles.SetSelection({start, count}); bpComplexes.SetSelection({start, count}); bpDComplexes.SetSelection({start, count}); dataManReader.Get(bpChars, myChars.data(), adios2::Mode::Sync); dataManReader.Get(bpUChars, myUChars.data(), adios2::Mode::Sync); dataManReader.Get(bpShorts, myShorts.data(), adios2::Mode::Sync); dataManReader.Get(bpUShorts, myUShorts.data(), adios2::Mode::Sync); dataManReader.Get(bpInts, myInts.data(), adios2::Mode::Sync); dataManReader.Get(bpUInts, myUInts.data(), adios2::Mode::Sync); dataManReader.Get(bpFloats, myFloats.data(), adios2::Mode::Sync); dataManReader.Get(bpDoubles, myDoubles.data(), adios2::Mode::Sync); dataManReader.Get(bpComplexes, myComplexes.data(), adios2::Mode::Sync); dataManReader.Get(bpDComplexes, myDComplexes.data(), adios2::Mode::Sync); uint64_t stepValue; dataManReader.Get(bpUInt64s, &stepValue, adios2::Mode::Sync); ASSERT_EQ(currentStep, stepValue); VerifyData(myChars, currentStep); VerifyData(myUChars, currentStep); VerifyData(myShorts, currentStep); VerifyData(myUShorts, currentStep); VerifyData(myInts, currentStep); VerifyData(myUInts, currentStep); VerifyData(myFloats, currentStep); VerifyData(myDoubles, currentStep); VerifyData(myComplexes, currentStep); VerifyData(myDComplexes, currentStep); dataManReader.EndStep(); } else if (status == adios2::StepStatus::EndOfStream) { break; } else if (status == adios2::StepStatus::NotReady) { continue; } } if (received_steps) { auto attInt = dataManIO.InquireAttribute<int>("AttInt"); ASSERT_EQ(110, attInt.Data()[0]); ASSERT_NE(111, attInt.Data()[0]); } dataManReader.Close(); } class DataManEngineTest : public ::testing::Test { public: DataManEngineTest() = default; }; #ifdef ADIOS2_HAVE_ZEROMQ TEST_F(DataManEngineTest, 1DSuperLarge) { // set parameters Dims shape = {5000000}; Dims start = {0}; Dims count = {5000000}; size_t steps = 10; // run workflow adios2::Params readerEngineParams = {{"IPAddress", "127.0.0.1"}, {"Port", "13480"}, {"MaxStepBufferSize", "500000000"}, {"TransportMode", "reliable"}}; auto r = std::thread(DataManReader, shape, start, count, steps, readerEngineParams); adios2::Params writerEngineParams = {{"IPAddress", "127.0.0.1"}, {"Port", "13480"}, {"TransportMode", "reliable"}}; auto w = std::thread(DataManWriter, shape, start, count, steps, writerEngineParams); w.join(); r.join(); } #endif // ZEROMQ int main(int argc, char **argv) { int result; ::testing::InitGoogleTest(&argc, argv); result = RUN_ALL_TESTS(); return result; } <commit_msg>reduced buffer size<commit_after>/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. */ #include <numeric> #include <thread> #include <adios2.h> #include <adios2/common/ADIOSMacros.h> #include <adios2/helper/adiosFunctions.h> #include <gtest/gtest.h> using namespace adios2; size_t print_lines = 0; size_t to_print_lines = 10; template <class T> void GenData(std::vector<std::complex<T>> &data, const size_t step) { for (size_t i = 0; i < data.size(); ++i) { data[i] = {static_cast<T>(i + 10000 + step * 100), static_cast<T>(i + 10000)}; } } template <class T> void GenData(std::vector<T> &data, const size_t step) { for (size_t i = 0; i < data.size(); ++i) { data[i] = i + 10000 + step * 100; } } template <class T> void PrintData(const T *data, const size_t size, const size_t step) { std::cout << "Step: " << step << " ["; size_t printsize = 32; if (size < printsize) { printsize = size; } for (size_t i = 0; i < printsize; ++i) { std::cout << data[i] << " "; } std::cout << "]" << std::endl; } template <class T> void VerifyData(const std::complex<T> *data, const size_t size, size_t step) { std::vector<std::complex<T>> tmpdata(size); GenData(tmpdata, step); for (size_t i = 0; i < size; ++i) { ASSERT_EQ(data[i], tmpdata[i]); } } template <class T> void VerifyData(const T *data, const size_t size, size_t step) { std::vector<T> tmpdata(size); GenData(tmpdata, step); for (size_t i = 0; i < size; ++i) { ASSERT_EQ(data[i], tmpdata[i]); } } template <class T> void VerifyData(const std::vector<T> &data, const size_t step) { VerifyData(data.data(), data.size(), step); } void DataManWriter(const Dims &shape, const Dims &start, const Dims &count, const size_t steps, const adios2::Params &engineParams) { size_t datasize = std::accumulate(count.begin(), count.end(), 1, std::multiplies<size_t>()); adios2::ADIOS adios; adios2::IO dataManIO = adios.DeclareIO("WAN"); dataManIO.SetEngine("DataMan"); dataManIO.SetParameters(engineParams); std::vector<char> myChars(datasize); std::vector<unsigned char> myUChars(datasize); std::vector<short> myShorts(datasize); std::vector<unsigned short> myUShorts(datasize); std::vector<int> myInts(datasize); std::vector<unsigned int> myUInts(datasize); std::vector<float> myFloats(datasize); std::vector<double> myDoubles(datasize); std::vector<std::complex<float>> myComplexes(datasize); std::vector<std::complex<double>> myDComplexes(datasize); auto bpChars = dataManIO.DefineVariable<char>("bpChars", shape, start, count); auto bpUChars = dataManIO.DefineVariable<unsigned char>("bpUChars", shape, start, count); auto bpShorts = dataManIO.DefineVariable<short>("bpShorts", shape, start, count); auto bpUShorts = dataManIO.DefineVariable<unsigned short>( "bpUShorts", shape, start, count); auto bpInts = dataManIO.DefineVariable<int>("bpInts", shape, start, count); auto bpUInts = dataManIO.DefineVariable<unsigned int>("bpUInts", shape, start, count); auto bpFloats = dataManIO.DefineVariable<float>("bpFloats", shape, start, count); auto bpDoubles = dataManIO.DefineVariable<double>("bpDoubles", shape, start, count); auto bpComplexes = dataManIO.DefineVariable<std::complex<float>>( "bpComplexes", shape, start, count); auto bpDComplexes = dataManIO.DefineVariable<std::complex<double>>( "bpDComplexes", shape, start, count); auto bpUInt64s = dataManIO.DefineVariable<uint64_t>("bpUInt64s"); dataManIO.DefineAttribute<int>("AttInt", 110); adios2::Engine dataManWriter = dataManIO.Open("stream", adios2::Mode::Write); for (uint64_t i = 0; i < steps; ++i) { dataManWriter.BeginStep(); GenData(myChars, i); GenData(myUChars, i); GenData(myShorts, i); GenData(myUShorts, i); GenData(myInts, i); GenData(myUInts, i); GenData(myFloats, i); GenData(myDoubles, i); GenData(myComplexes, i); GenData(myDComplexes, i); dataManWriter.Put(bpChars, myChars.data(), adios2::Mode::Sync); dataManWriter.Put(bpUChars, myUChars.data(), adios2::Mode::Sync); dataManWriter.Put(bpShorts, myShorts.data(), adios2::Mode::Sync); dataManWriter.Put(bpUShorts, myUShorts.data(), adios2::Mode::Sync); dataManWriter.Put(bpInts, myInts.data(), adios2::Mode::Sync); dataManWriter.Put(bpUInts, myUInts.data(), adios2::Mode::Sync); dataManWriter.Put(bpFloats, myFloats.data(), adios2::Mode::Sync); dataManWriter.Put(bpDoubles, myDoubles.data(), adios2::Mode::Sync); dataManWriter.Put(bpComplexes, myComplexes.data(), adios2::Mode::Sync); dataManWriter.Put(bpDComplexes, myDComplexes.data(), adios2::Mode::Sync); dataManWriter.Put(bpUInt64s, i); dataManWriter.EndStep(); } dataManWriter.Close(); } void DataManReader(const Dims &shape, const Dims &start, const Dims &count, const size_t steps, const adios2::Params &engineParams) { size_t datasize = std::accumulate(count.begin(), count.end(), 1, std::multiplies<size_t>()); adios2::ADIOS adios; adios2::IO dataManIO = adios.DeclareIO("WAN"); dataManIO.SetEngine("DataMan"); dataManIO.SetParameters(engineParams); adios2::Engine dataManReader = dataManIO.Open("stream", adios2::Mode::Read); std::vector<char> myChars(datasize); std::vector<unsigned char> myUChars(datasize); std::vector<short> myShorts(datasize); std::vector<unsigned short> myUShorts(datasize); std::vector<int> myInts(datasize); std::vector<unsigned int> myUInts(datasize); std::vector<float> myFloats(datasize); std::vector<double> myDoubles(datasize); std::vector<std::complex<float>> myComplexes(datasize); std::vector<std::complex<double>> myDComplexes(datasize); bool received_steps = false; size_t currentStep; while (true) { adios2::StepStatus status = dataManReader.BeginStep(StepMode::Read, 5); if (status == adios2::StepStatus::OK) { received_steps = true; const auto &vars = dataManIO.AvailableVariables(); ASSERT_EQ(vars.size(), 11); currentStep = dataManReader.CurrentStep(); adios2::Variable<char> bpChars = dataManIO.InquireVariable<char>("bpChars"); adios2::Variable<unsigned char> bpUChars = dataManIO.InquireVariable<unsigned char>("bpUChars"); adios2::Variable<short> bpShorts = dataManIO.InquireVariable<short>("bpShorts"); adios2::Variable<unsigned short> bpUShorts = dataManIO.InquireVariable<unsigned short>("bpUShorts"); adios2::Variable<int> bpInts = dataManIO.InquireVariable<int>("bpInts"); adios2::Variable<unsigned int> bpUInts = dataManIO.InquireVariable<unsigned int>("bpUInts"); adios2::Variable<float> bpFloats = dataManIO.InquireVariable<float>("bpFloats"); adios2::Variable<double> bpDoubles = dataManIO.InquireVariable<double>("bpDoubles"); adios2::Variable<std::complex<float>> bpComplexes = dataManIO.InquireVariable<std::complex<float>>("bpComplexes"); adios2::Variable<std::complex<double>> bpDComplexes = dataManIO.InquireVariable<std::complex<double>>("bpDComplexes"); adios2::Variable<uint64_t> bpUInt64s = dataManIO.InquireVariable<uint64_t>("bpUInt64s"); auto charsBlocksInfo = dataManReader.AllStepsBlocksInfo(bpChars); bpChars.SetSelection({start, count}); bpUChars.SetSelection({start, count}); bpShorts.SetSelection({start, count}); bpUShorts.SetSelection({start, count}); bpInts.SetSelection({start, count}); bpUInts.SetSelection({start, count}); bpFloats.SetSelection({start, count}); bpDoubles.SetSelection({start, count}); bpComplexes.SetSelection({start, count}); bpDComplexes.SetSelection({start, count}); dataManReader.Get(bpChars, myChars.data(), adios2::Mode::Sync); dataManReader.Get(bpUChars, myUChars.data(), adios2::Mode::Sync); dataManReader.Get(bpShorts, myShorts.data(), adios2::Mode::Sync); dataManReader.Get(bpUShorts, myUShorts.data(), adios2::Mode::Sync); dataManReader.Get(bpInts, myInts.data(), adios2::Mode::Sync); dataManReader.Get(bpUInts, myUInts.data(), adios2::Mode::Sync); dataManReader.Get(bpFloats, myFloats.data(), adios2::Mode::Sync); dataManReader.Get(bpDoubles, myDoubles.data(), adios2::Mode::Sync); dataManReader.Get(bpComplexes, myComplexes.data(), adios2::Mode::Sync); dataManReader.Get(bpDComplexes, myDComplexes.data(), adios2::Mode::Sync); uint64_t stepValue; dataManReader.Get(bpUInt64s, &stepValue, adios2::Mode::Sync); ASSERT_EQ(currentStep, stepValue); VerifyData(myChars, currentStep); VerifyData(myUChars, currentStep); VerifyData(myShorts, currentStep); VerifyData(myUShorts, currentStep); VerifyData(myInts, currentStep); VerifyData(myUInts, currentStep); VerifyData(myFloats, currentStep); VerifyData(myDoubles, currentStep); VerifyData(myComplexes, currentStep); VerifyData(myDComplexes, currentStep); dataManReader.EndStep(); } else if (status == adios2::StepStatus::EndOfStream) { break; } else if (status == adios2::StepStatus::NotReady) { continue; } } if (received_steps) { auto attInt = dataManIO.InquireAttribute<int>("AttInt"); ASSERT_EQ(110, attInt.Data()[0]); ASSERT_NE(111, attInt.Data()[0]); } dataManReader.Close(); } class DataManEngineTest : public ::testing::Test { public: DataManEngineTest() = default; }; #ifdef ADIOS2_HAVE_ZEROMQ TEST_F(DataManEngineTest, 1DSuperLarge) { // set parameters Dims shape = {2000000}; Dims start = {0}; Dims count = {2000000}; size_t steps = 10; // run workflow adios2::Params readerEngineParams = {{"IPAddress", "127.0.0.1"}, {"Port", "13480"}, {"MaxStepBufferSize", "200000000"}, {"TransportMode", "reliable"}}; auto r = std::thread(DataManReader, shape, start, count, steps, readerEngineParams); adios2::Params writerEngineParams = {{"IPAddress", "127.0.0.1"}, {"Port", "13480"}, {"TransportMode", "reliable"}}; auto w = std::thread(DataManWriter, shape, start, count, steps, writerEngineParams); w.join(); r.join(); } #endif // ZEROMQ int main(int argc, char **argv) { int result; ::testing::InitGoogleTest(&argc, argv); result = RUN_ALL_TESTS(); return result; } <|endoftext|>
<commit_before>/* * This file is part of the UnTech Editor Suite. * Copyright (c) 2016 - 2020, Marcus Rowe <[email protected]>. * Distributed under The MIT License: https://opensource.org/licenses/MIT */ #include "scenes-editor-editor.h" #include "gui/imgui.h" #include "gui/list-helpers.h" #include "models/resources/scene-bgmode.hpp" namespace UnTech::Gui { const char* bgModeItems[] = { "Mode 0", "Mode 1", "Mode 1 (bg3 priotity)", "Mode 2", "Mode 3", "Mode 4", }; const char* layerTypeItems[] = { "None", "Background Image", "MetaTile Tileset", "Text Console", }; ScenesEditor::ScenesEditor(ItemIndex itemIndex) : AbstractEditor(itemIndex) { } bool ScenesEditor::loadDataFromProject(const Project::ProjectFile& projectFile) { _scenes = projectFile.resourceScenes; return true; } void ScenesEditor::commitPendingChanges(Project::ProjectFile& projectFile) { projectFile.resourceScenes = _scenes; } void ScenesEditor::editorOpened() { } void ScenesEditor::editorClosed() { } void ScenesEditor::settingsWindow() { if (ImGui::Begin("Scene Settings")) { ImGui::SetWindowSize(ImVec2(1000, 400), ImGuiCond_FirstUseEver); ListButtons(&_settingsSel, &_scenes.settings, 128); ImGui::BeginChild("Scroll"); ImGui::Columns(7); ImGui::Separator(); ImGui::NextColumn(); ImGui::Text("Name"); ImGui::NextColumn(); ImGui::Text("BG Mode"); ImGui::NextColumn(); ImGui::Text("Layer 0 Type"); ImGui::NextColumn(); ImGui::Text("Layer 1 Type"); ImGui::NextColumn(); ImGui::Text("Layer 2 Type"); ImGui::NextColumn(); ImGui::Text("Layer 3 Type"); ImGui::NextColumn(); ImGui::Separator(); for (unsigned i = 0; i < _scenes.settings.size(); i++) { auto& sceneSettings = _scenes.settings.at(i); bool edited = false; ImGui::PushID(i); ImGui::Selectable(&_settingsSel, i); ImGui::NextColumn(); ImGui::SetNextItemWidth(-1); ImGui::InputIdstring("##Name", &sceneSettings.name); edited |= ImGui::IsItemDeactivatedAfterEdit(); ImGui::NextColumn(); ImGui::SetNextItemWidth(-1); edited |= ImGui::EnumCombo("##BgMode", &sceneSettings.bgMode, bgModeItems, IM_ARRAYSIZE(bgModeItems)); ImGui::NextColumn(); static const std::array<const char*, 4> layerLabels = { "##LT0", "##LT1", "##LT2", "##LT3" }; for (unsigned l = 0; l < sceneSettings.layerTypes.size(); l++) { ImGui::SetNextItemWidth(-1); edited |= ImGui::EnumCombo(layerLabels.at(l), &sceneSettings.layerTypes.at(l), layerTypeItems, IM_ARRAYSIZE(layerTypeItems)); ImGui::NextColumn(); } if (edited) { ImGui::LogText("Edited Secene Settings"); this->pendingChanges = true; } ImGui::PopID(); } ImGui::Columns(1); ImGui::Separator(); ImGui::EndChild(); } ImGui::End(); } bool ScenesEditor::sceneLayerCombo(const char* label, idstring* value, const Project::ProjectFile& projectFile, const Resources::SceneSettingsInput& sceneSettings, const unsigned layerId) { using namespace std::string_literals; using LayerType = Resources::LayerType; const auto layer = sceneSettings.layerTypes.at(layerId); switch (layer) { case LayerType::None: { return false; } case LayerType::TextConsole: { ImGui::TextUnformatted("Text"s); return false; } case LayerType::BackgroundImage: { const unsigned bitDepth = Resources::bitDepthForLayer(sceneSettings.bgMode, layerId); bool e = ImGui::IdStringCombo(label, value, projectFile.backgroundImages, false, [&](auto& item) { return (item.bitDepth == bitDepth) ? &item.name : nullptr; }); if (ImGui::IsItemHovered()) { ImGui::SetTooltip("Background Image (%d bpp)", bitDepth); } return e; } case LayerType::MetaTileTileset: { const unsigned bitDepth = Resources::bitDepthForLayer(sceneSettings.bgMode, layerId); bool e = ImGui::IdStringCombo(label, value, projectFile.metaTileTilesets, false, [&](const MetaTiles::MetaTileTilesetInput* mt) { return (mt->animationFrames.bitDepth == bitDepth) ? &mt->name : nullptr; }); if (ImGui::IsItemHovered()) { ImGui::SetTooltip("MetaTile Tileset (%d bpp)", bitDepth); } return e; } } return false; } void ScenesEditor::scenesWindow(const Project::ProjectFile& projectFile) { if (ImGui::Begin("Scenes")) { ImGui::SetWindowSize(ImVec2(1000, 400), ImGuiCond_FirstUseEver); ListButtons(&_settingsSel, &_scenes.settings, 128); ImGui::BeginChild("Scroll"); ImGui::Columns(7); ImGui::Separator(); ImGui::NextColumn(); ImGui::Text("Name"); ImGui::NextColumn(); ImGui::Text("Scene Settings"); ImGui::NextColumn(); ImGui::Text("Layer 0"); ImGui::NextColumn(); ImGui::Text("Layer 1"); ImGui::NextColumn(); ImGui::Text("Layer 2"); ImGui::NextColumn(); ImGui::Text("Layer 3"); ImGui::NextColumn(); ImGui::Separator(); for (unsigned i = 0; i < _scenes.scenes.size(); i++) { auto& scene = _scenes.scenes.at(i); bool edited = false; ImGui::PushID(i); ImGui::Selectable(&_scenesSel, i); ImGui::NextColumn(); ImGui::SetNextItemWidth(-1); ImGui::InputIdstring("##Name", &scene.name); edited |= ImGui::IsItemDeactivatedAfterEdit(); ImGui::NextColumn(); ImGui::SetNextItemWidth(-1); edited |= ImGui::IdStringCombo("##SceneSettings", &scene.sceneSettings, _scenes.settings); ImGui::NextColumn(); const auto sceneSettings = _scenes.settings.find(scene.sceneSettings); static const std::array<const char*, 4> layerLabels = { "##LT0", "##LT1", "##LT2", "##LT3" }; for (unsigned l = 0; l < scene.layers.size(); l++) { if (sceneSettings) { ImGui::SetNextItemWidth(-1); edited |= sceneLayerCombo(layerLabels.at(l), &scene.layers.at(l), projectFile, *sceneSettings, l); } ImGui::NextColumn(); } if (edited) { ImGui::LogText("Edited Secene"); this->pendingChanges = true; } ImGui::PopID(); } ImGui::Columns(1); ImGui::Separator(); ImGui::EndChild(); } ImGui::End(); } void ScenesEditor::processGui(const Project::ProjectFile& projectFile) { settingsWindow(); scenesWindow(projectFile); UpdateSelection(&_settingsSel); UpdateSelection(&_scenesSel); } } <commit_msg>Fix Scenes list buttons changing the wrong list<commit_after>/* * This file is part of the UnTech Editor Suite. * Copyright (c) 2016 - 2020, Marcus Rowe <[email protected]>. * Distributed under The MIT License: https://opensource.org/licenses/MIT */ #include "scenes-editor-editor.h" #include "gui/imgui.h" #include "gui/list-helpers.h" #include "models/resources/scene-bgmode.hpp" namespace UnTech::Gui { const char* bgModeItems[] = { "Mode 0", "Mode 1", "Mode 1 (bg3 priotity)", "Mode 2", "Mode 3", "Mode 4", }; const char* layerTypeItems[] = { "None", "Background Image", "MetaTile Tileset", "Text Console", }; ScenesEditor::ScenesEditor(ItemIndex itemIndex) : AbstractEditor(itemIndex) { } bool ScenesEditor::loadDataFromProject(const Project::ProjectFile& projectFile) { _scenes = projectFile.resourceScenes; return true; } void ScenesEditor::commitPendingChanges(Project::ProjectFile& projectFile) { projectFile.resourceScenes = _scenes; } void ScenesEditor::editorOpened() { } void ScenesEditor::editorClosed() { } void ScenesEditor::settingsWindow() { if (ImGui::Begin("Scene Settings")) { ImGui::SetWindowSize(ImVec2(1000, 400), ImGuiCond_FirstUseEver); ListButtons(&_settingsSel, &_scenes.settings, 128); ImGui::BeginChild("Scroll"); ImGui::Columns(7); ImGui::Separator(); ImGui::NextColumn(); ImGui::Text("Name"); ImGui::NextColumn(); ImGui::Text("BG Mode"); ImGui::NextColumn(); ImGui::Text("Layer 0 Type"); ImGui::NextColumn(); ImGui::Text("Layer 1 Type"); ImGui::NextColumn(); ImGui::Text("Layer 2 Type"); ImGui::NextColumn(); ImGui::Text("Layer 3 Type"); ImGui::NextColumn(); ImGui::Separator(); for (unsigned i = 0; i < _scenes.settings.size(); i++) { auto& sceneSettings = _scenes.settings.at(i); bool edited = false; ImGui::PushID(i); ImGui::Selectable(&_settingsSel, i); ImGui::NextColumn(); ImGui::SetNextItemWidth(-1); ImGui::InputIdstring("##Name", &sceneSettings.name); edited |= ImGui::IsItemDeactivatedAfterEdit(); ImGui::NextColumn(); ImGui::SetNextItemWidth(-1); edited |= ImGui::EnumCombo("##BgMode", &sceneSettings.bgMode, bgModeItems, IM_ARRAYSIZE(bgModeItems)); ImGui::NextColumn(); static const std::array<const char*, 4> layerLabels = { "##LT0", "##LT1", "##LT2", "##LT3" }; for (unsigned l = 0; l < sceneSettings.layerTypes.size(); l++) { ImGui::SetNextItemWidth(-1); edited |= ImGui::EnumCombo(layerLabels.at(l), &sceneSettings.layerTypes.at(l), layerTypeItems, IM_ARRAYSIZE(layerTypeItems)); ImGui::NextColumn(); } if (edited) { ImGui::LogText("Edited Secene Settings"); this->pendingChanges = true; } ImGui::PopID(); } ImGui::Columns(1); ImGui::Separator(); ImGui::EndChild(); } ImGui::End(); } bool ScenesEditor::sceneLayerCombo(const char* label, idstring* value, const Project::ProjectFile& projectFile, const Resources::SceneSettingsInput& sceneSettings, const unsigned layerId) { using namespace std::string_literals; using LayerType = Resources::LayerType; const auto layer = sceneSettings.layerTypes.at(layerId); switch (layer) { case LayerType::None: { return false; } case LayerType::TextConsole: { ImGui::TextUnformatted("Text"s); return false; } case LayerType::BackgroundImage: { const unsigned bitDepth = Resources::bitDepthForLayer(sceneSettings.bgMode, layerId); bool e = ImGui::IdStringCombo(label, value, projectFile.backgroundImages, false, [&](auto& item) { return (item.bitDepth == bitDepth) ? &item.name : nullptr; }); if (ImGui::IsItemHovered()) { ImGui::SetTooltip("Background Image (%d bpp)", bitDepth); } return e; } case LayerType::MetaTileTileset: { const unsigned bitDepth = Resources::bitDepthForLayer(sceneSettings.bgMode, layerId); bool e = ImGui::IdStringCombo(label, value, projectFile.metaTileTilesets, false, [&](const MetaTiles::MetaTileTilesetInput* mt) { return (mt->animationFrames.bitDepth == bitDepth) ? &mt->name : nullptr; }); if (ImGui::IsItemHovered()) { ImGui::SetTooltip("MetaTile Tileset (%d bpp)", bitDepth); } return e; } } return false; } void ScenesEditor::scenesWindow(const Project::ProjectFile& projectFile) { if (ImGui::Begin("Scenes")) { ImGui::SetWindowSize(ImVec2(1000, 400), ImGuiCond_FirstUseEver); ListButtons(&_scenesSel, &_scenes.scenes, 128); ImGui::BeginChild("Scroll"); ImGui::Columns(7); ImGui::Separator(); ImGui::NextColumn(); ImGui::Text("Name"); ImGui::NextColumn(); ImGui::Text("Scene Settings"); ImGui::NextColumn(); ImGui::Text("Layer 0"); ImGui::NextColumn(); ImGui::Text("Layer 1"); ImGui::NextColumn(); ImGui::Text("Layer 2"); ImGui::NextColumn(); ImGui::Text("Layer 3"); ImGui::NextColumn(); ImGui::Separator(); for (unsigned i = 0; i < _scenes.scenes.size(); i++) { auto& scene = _scenes.scenes.at(i); bool edited = false; ImGui::PushID(i); ImGui::Selectable(&_scenesSel, i); ImGui::NextColumn(); ImGui::SetNextItemWidth(-1); ImGui::InputIdstring("##Name", &scene.name); edited |= ImGui::IsItemDeactivatedAfterEdit(); ImGui::NextColumn(); ImGui::SetNextItemWidth(-1); edited |= ImGui::IdStringCombo("##SceneSettings", &scene.sceneSettings, _scenes.settings); ImGui::NextColumn(); const auto sceneSettings = _scenes.settings.find(scene.sceneSettings); static const std::array<const char*, 4> layerLabels = { "##LT0", "##LT1", "##LT2", "##LT3" }; for (unsigned l = 0; l < scene.layers.size(); l++) { if (sceneSettings) { ImGui::SetNextItemWidth(-1); edited |= sceneLayerCombo(layerLabels.at(l), &scene.layers.at(l), projectFile, *sceneSettings, l); } ImGui::NextColumn(); } if (edited) { ImGui::LogText("Edited Secene"); this->pendingChanges = true; } ImGui::PopID(); } ImGui::Columns(1); ImGui::Separator(); ImGui::EndChild(); } ImGui::End(); } void ScenesEditor::processGui(const Project::ProjectFile& projectFile) { settingsWindow(); scenesWindow(projectFile); UpdateSelection(&_settingsSel); UpdateSelection(&_scenesSel); } } <|endoftext|>
<commit_before>#include "ROOT/TDataFrame.hxx" #include "TRandom.h" #include "TInterpreter.h" #include "gtest/gtest.h" using namespace ROOT::Experimental; namespace TEST_CATEGORY { int DefineFunction() { return 1; } struct DefineStruct { int operator()() { return 1; } }; void FillTree(const char *filename, const char *treeName, int nevents = 0) { TFile f(filename, "RECREATE"); TTree t(treeName, treeName); t.SetAutoFlush(1); // yes, one event per cluster: to make MT more meaningful double b1; int b2; t.Branch("b1", &b1); t.Branch("b2", &b2); for (int i = 0; i < nevents; ++i) { b1 = i; b2 = i * i; t.Fill(); } t.Write(); f.Close(); } } TEST(TEST_CATEGORY, CreateEmpty) { TDataFrame tdf(10); auto c = tdf.Count(); EXPECT_EQ(10U, *c); } TEST(TEST_CATEGORY, CreateZeroEntries) { TDataFrame tdf(0); auto c = tdf.Count(); EXPECT_EQ(0U, *c); } TEST(TEST_CATEGORY, CreateZeroEntriesWithBranches) { auto filename = "dataframe_simple_0.root"; auto treename = "t"; #ifndef testTDF_simple_0_CREATED #define testTDF_simple_0_CREATED TEST_CATEGORY::FillTree(filename, treename); #endif TDataFrame tdf(treename, filename); auto c = tdf.Count(); auto m = tdf.Mean("b1"); EXPECT_EQ(0U, *c); EXPECT_EQ(0., *m); } TEST(TEST_CATEGORY, BuildWithTDirectory) { auto filename = "dataframe_simple_1.root"; auto treename = "t"; #ifndef testTDF_simple_1_CREATED #define testTDF_simple_1_CREATED TEST_CATEGORY::FillTree(filename, treename, 50); #endif TFile f(filename); TDataFrame tdf(treename, &f); auto c = tdf.Count(); EXPECT_EQ(50U, *c); } // Jitting of column types TEST(TEST_CATEGORY, TypeGuessing) { auto filename = "dataframe_simple_2.root"; auto treename = "t"; #ifndef testTDF_simple_2_CREATED #define testTDF_simple_2_CREATED TEST_CATEGORY::FillTree(filename, treename, 50); #endif TDataFrame tdf(treename, filename, {"b1"}); auto hcompiled = tdf.Histo1D<double>(); auto hjitted = tdf.Histo1D(); EXPECT_EQ(50, hcompiled->GetEntries()); EXPECT_EQ(50, hjitted->GetEntries()); EXPECT_DOUBLE_EQ(hcompiled->GetMean(), hjitted->GetMean()); } // Define TEST(TEST_CATEGORY, Define_lambda) { TDataFrame tdf(10); auto d = tdf.Define("i", []() { return 1; }); auto m = d.Mean("i"); EXPECT_DOUBLE_EQ(1., *m); } TEST(TEST_CATEGORY, Define_function) { TDataFrame tdf(10); auto d = tdf.Define("i", TEST_CATEGORY::DefineFunction); auto m = d.Mean("i"); EXPECT_DOUBLE_EQ(1., *m); } TEST(TEST_CATEGORY, Define_functor) { TDataFrame tdf(10); TEST_CATEGORY::DefineStruct def; auto d = tdf.Define("i", def); auto m = d.Mean("i"); EXPECT_DOUBLE_EQ(1., *m); } TEST(TEST_CATEGORY, Define_jitted) { TDataFrame tdf(10); auto d = tdf.Define("i", "1"); auto m = d.Mean("i"); EXPECT_DOUBLE_EQ(1., *m); } TEST(TEST_CATEGORY, Define_jitted_complex) { // The test can be run in sequential and MT mode. #ifndef RNDM_GEN_CREATED #define RNDM_GEN_CREATED gInterpreter->ProcessLine("TRandom r;"); #endif gInterpreter->ProcessLine("r.SetSeed(1);"); TDataFrame tdf(50); auto d = tdf.Define("i", "r.Uniform(0.,8.)"); auto m = d.Max("i"); EXPECT_EQ(7.867497533559811628, *m); } // Define + Filters TEST(TEST_CATEGORY, Define_Filter) { TRandom r(1); TDataFrame tdf(50); auto d = tdf.Define("r", [&r]() { return r.Uniform(0., 8.); }); auto df = d.Filter([](double x) { return x > 5; }, {"r"}); auto m = df.Max("r"); EXPECT_EQ(7.867497533559811628, *m); } TEST(TEST_CATEGORY, Define_Filter_jitted) { TRandom r(1); TDataFrame tdf(50); auto d = tdf.Define("r", [&r]() { return r.Uniform(0., 8.); }); auto df = d.Filter("r>5"); auto m = df.Max("r"); EXPECT_EQ(7.867497533559811628, *m); } TEST(TEST_CATEGORY, Define_Filter_named) { TRandom r(1); TDataFrame tdf(50); auto d = tdf.Define("r", [&r]() { return r.Uniform(0., 8.); }); auto df = d.Filter([](double x) { return x > 5; }, {"r"}, "myFilter"); auto m = df.Max("r"); EXPECT_EQ(7.867497533559811628, *m); } TEST(TEST_CATEGORY, Define_Filter_named_jitted) { TRandom r(1); TDataFrame tdf(50); auto d = tdf.Define("r", [&r]() { return r.Uniform(0., 8.); }); auto df = d.Filter("r>5", "myFilter"); auto m = df.Max("r"); EXPECT_EQ(7.867497533559811628, *m); } // jitted Define + Filters TEST(TEST_CATEGORY, Define_jitted_Filter) { gInterpreter->ProcessLine("r.SetSeed(1);"); TDataFrame tdf(50); auto d = tdf.Define("r", "r.Uniform(0.,8.)"); auto df = d.Filter([](double x) { return x > 5; }, {"r"}); auto m = df.Max("r"); EXPECT_EQ(7.867497533559811628, *m); } TEST(TEST_CATEGORY, Define_jitted_Filter_jitted) { gInterpreter->ProcessLine("r.SetSeed(1);"); TDataFrame tdf(50); auto d = tdf.Define("r", "r.Uniform(0.,8.)"); auto df = d.Filter("r>5"); auto m = df.Max("r"); EXPECT_EQ(7.867497533559811628, *m); } TEST(TEST_CATEGORY, Define_jitted_Filter_named) { gInterpreter->ProcessLine("r.SetSeed(1);"); TDataFrame tdf(50); auto d = tdf.Define("r", "r.Uniform(0.,8.)"); auto df = d.Filter([](double x) { return x > 5; }, {"r"}, "myFilter"); auto m = df.Max("r"); EXPECT_EQ(7.867497533559811628, *m); } TEST(TEST_CATEGORY, Define_jitted_Filter_named_jitted) { gInterpreter->ProcessLine("r.SetSeed(1);"); TDataFrame tdf(50); auto d = tdf.Define("r", "r.Uniform(0.,8.)"); auto df = d.Filter("r>5", "myFilter"); auto m = df.Max("r"); EXPECT_EQ(7.867497533559811628, *m); } // This tests the interface but we need to run it both w/ and w/o implicit mt #ifdef R__USE_IMT TEST(TEST_CATEGORY, GetNSlots) { EXPECT_EQ(NSLOTS, ROOT::Internal::TDF::GetNSlots()); } #endif <commit_msg>Add Google test for snapshot action with options<commit_after>#include "ROOT/TDataFrame.hxx" #include "Compression.h" #include "TFile.h" #include "TInterpreter.h" #include "TRandom.h" #include "gtest/gtest.h" using namespace ROOT::Experimental; namespace TEST_CATEGORY { int DefineFunction() { return 1; } struct DefineStruct { int operator()() { return 1; } }; void FillTree(const char *filename, const char *treeName, int nevents = 0) { TFile f(filename, "RECREATE"); TTree t(treeName, treeName); t.SetAutoFlush(1); // yes, one event per cluster: to make MT more meaningful double b1; int b2; t.Branch("b1", &b1); t.Branch("b2", &b2); for (int i = 0; i < nevents; ++i) { b1 = i; b2 = i * i; t.Fill(); } t.Write(); f.Close(); } } TEST(TEST_CATEGORY, CreateEmpty) { TDataFrame tdf(10); auto c = tdf.Count(); EXPECT_EQ(10U, *c); } TEST(TEST_CATEGORY, CreateZeroEntries) { TDataFrame tdf(0); auto c = tdf.Count(); EXPECT_EQ(0U, *c); } TEST(TEST_CATEGORY, CreateZeroEntriesWithBranches) { auto filename = "dataframe_simple_0.root"; auto treename = "t"; #ifndef testTDF_simple_0_CREATED #define testTDF_simple_0_CREATED TEST_CATEGORY::FillTree(filename, treename); #endif TDataFrame tdf(treename, filename); auto c = tdf.Count(); auto m = tdf.Mean("b1"); EXPECT_EQ(0U, *c); EXPECT_EQ(0., *m); } TEST(TEST_CATEGORY, BuildWithTDirectory) { auto filename = "dataframe_simple_1.root"; auto treename = "t"; #ifndef testTDF_simple_1_CREATED #define testTDF_simple_1_CREATED TEST_CATEGORY::FillTree(filename, treename, 50); #endif TFile f(filename); TDataFrame tdf(treename, &f); auto c = tdf.Count(); EXPECT_EQ(50U, *c); } // Jitting of column types TEST(TEST_CATEGORY, TypeGuessing) { auto filename = "dataframe_simple_2.root"; auto treename = "t"; #ifndef testTDF_simple_2_CREATED #define testTDF_simple_2_CREATED TEST_CATEGORY::FillTree(filename, treename, 50); #endif TDataFrame tdf(treename, filename, {"b1"}); auto hcompiled = tdf.Histo1D<double>(); auto hjitted = tdf.Histo1D(); EXPECT_EQ(50, hcompiled->GetEntries()); EXPECT_EQ(50, hjitted->GetEntries()); EXPECT_DOUBLE_EQ(hcompiled->GetMean(), hjitted->GetMean()); } // Define TEST(TEST_CATEGORY, Define_lambda) { TDataFrame tdf(10); auto d = tdf.Define("i", []() { return 1; }); auto m = d.Mean("i"); EXPECT_DOUBLE_EQ(1., *m); } TEST(TEST_CATEGORY, Define_function) { TDataFrame tdf(10); auto d = tdf.Define("i", TEST_CATEGORY::DefineFunction); auto m = d.Mean("i"); EXPECT_DOUBLE_EQ(1., *m); } TEST(TEST_CATEGORY, Define_functor) { TDataFrame tdf(10); TEST_CATEGORY::DefineStruct def; auto d = tdf.Define("i", def); auto m = d.Mean("i"); EXPECT_DOUBLE_EQ(1., *m); } TEST(TEST_CATEGORY, Define_jitted) { TDataFrame tdf(10); auto d = tdf.Define("i", "1"); auto m = d.Mean("i"); EXPECT_DOUBLE_EQ(1., *m); } TEST(TEST_CATEGORY, Define_jitted_complex) { // The test can be run in sequential and MT mode. #ifndef RNDM_GEN_CREATED #define RNDM_GEN_CREATED gInterpreter->ProcessLine("TRandom r;"); #endif gInterpreter->ProcessLine("r.SetSeed(1);"); TDataFrame tdf(50); auto d = tdf.Define("i", "r.Uniform(0.,8.)"); auto m = d.Max("i"); EXPECT_EQ(7.867497533559811628, *m); } // Define + Filters TEST(TEST_CATEGORY, Define_Filter) { TRandom r(1); TDataFrame tdf(50); auto d = tdf.Define("r", [&r]() { return r.Uniform(0., 8.); }); auto df = d.Filter([](double x) { return x > 5; }, {"r"}); auto m = df.Max("r"); EXPECT_EQ(7.867497533559811628, *m); } TEST(TEST_CATEGORY, Define_Filter_jitted) { TRandom r(1); TDataFrame tdf(50); auto d = tdf.Define("r", [&r]() { return r.Uniform(0., 8.); }); auto df = d.Filter("r>5"); auto m = df.Max("r"); EXPECT_EQ(7.867497533559811628, *m); } TEST(TEST_CATEGORY, Define_Filter_named) { TRandom r(1); TDataFrame tdf(50); auto d = tdf.Define("r", [&r]() { return r.Uniform(0., 8.); }); auto df = d.Filter([](double x) { return x > 5; }, {"r"}, "myFilter"); auto m = df.Max("r"); EXPECT_EQ(7.867497533559811628, *m); } TEST(TEST_CATEGORY, Define_Filter_named_jitted) { TRandom r(1); TDataFrame tdf(50); auto d = tdf.Define("r", [&r]() { return r.Uniform(0., 8.); }); auto df = d.Filter("r>5", "myFilter"); auto m = df.Max("r"); EXPECT_EQ(7.867497533559811628, *m); } // jitted Define + Filters TEST(TEST_CATEGORY, Define_jitted_Filter) { gInterpreter->ProcessLine("r.SetSeed(1);"); TDataFrame tdf(50); auto d = tdf.Define("r", "r.Uniform(0.,8.)"); auto df = d.Filter([](double x) { return x > 5; }, {"r"}); auto m = df.Max("r"); EXPECT_EQ(7.867497533559811628, *m); } TEST(TEST_CATEGORY, Define_jitted_Filter_jitted) { gInterpreter->ProcessLine("r.SetSeed(1);"); TDataFrame tdf(50); auto d = tdf.Define("r", "r.Uniform(0.,8.)"); auto df = d.Filter("r>5"); auto m = df.Max("r"); EXPECT_EQ(7.867497533559811628, *m); } TEST(TEST_CATEGORY, Define_jitted_Filter_named) { gInterpreter->ProcessLine("r.SetSeed(1);"); TDataFrame tdf(50); auto d = tdf.Define("r", "r.Uniform(0.,8.)"); auto df = d.Filter([](double x) { return x > 5; }, {"r"}, "myFilter"); auto m = df.Max("r"); EXPECT_EQ(7.867497533559811628, *m); } TEST(TEST_CATEGORY, Define_jitted_Filter_named_jitted) { gInterpreter->ProcessLine("r.SetSeed(1);"); TDataFrame tdf(50); auto d = tdf.Define("r", "r.Uniform(0.,8.)"); auto df = d.Filter("r>5", "myFilter"); auto m = df.Max("r"); EXPECT_EQ(7.867497533559811628, *m); } TEST(TEST_CATEGORY, Snapshot_update) { using SnapshotOptions = ROOT::Experimental::TDF::SnapshotOptions; SnapshotOptions opts; opts.fMode = "UPDATE"; TDataFrame tdf1(1000); auto s1 = tdf1.Define("one", []() { return 1.0; }) .Snapshot<double>("mytree1", "snapshot_test_update.root", {"one"}); EXPECT_EQ(1000U, *s1.Count()); EXPECT_EQ(1.0, *s1.Min("one")); EXPECT_EQ(1.0, *s1.Max("one")); EXPECT_EQ(1.0, *s1.Mean("one")); TDataFrame tdf2(1000); auto s2 = tdf2.Define("two", []() { return 2.0; }) .Snapshot<double>("mytree2", "snapshot_test_update.root", {"two"}, opts); EXPECT_EQ(1000U, *s2.Count()); EXPECT_EQ(2.0, *s2.Min("two")); EXPECT_EQ(2.0, *s2.Max("two")); EXPECT_EQ(2.0, *s2.Mean("two")); TFile *f = TFile::Open("snapshot_test_update.root", "READ"); auto mytree1 = (TTree*) f->Get("mytree1"); auto mytree2 = (TTree*) f->Get("mytree2"); EXPECT_NE(nullptr, mytree1); EXPECT_NE(nullptr, mytree2); f->Close(); delete f; } TEST(TEST_CATEGORY, Snapshot_action_with_options) { using SnapshotOptions = ROOT::Experimental::TDF::SnapshotOptions; SnapshotOptions opts; opts.fAutoFlush = 10; opts.fMode = "RECREATE"; for (auto algorithm : { ROOT::kZLIB, ROOT::kLZMA, ROOT::kLZ4 }) { TDataFrame tdf(1000); opts.fCompress = ROOT::CompressionSettings(algorithm, 6); auto s = tdf.Define("one", []() { return 1.0; }) .Snapshot<double>("mytree", "snapshot_test_opts.root", {"one"}, opts); EXPECT_EQ(1000U, *s.Count()); EXPECT_EQ(1.0, *s.Min("one")); EXPECT_EQ(1.0, *s.Max("one")); EXPECT_EQ(1.0, *s.Mean("one")); TFile *f = TFile::Open("snapshot_test_opts.root", "READ"); EXPECT_EQ(algorithm, f->GetCompressionAlgorithm()); EXPECT_EQ(6, f->GetCompressionLevel()); f->Close(); delete f; } } // This tests the interface but we need to run it both w/ and w/o implicit mt #ifdef R__USE_IMT TEST(TEST_CATEGORY, GetNSlots) { EXPECT_EQ(NSLOTS, ROOT::Internal::TDF::GetNSlots()); } #endif <|endoftext|>
<commit_before>#include "network_packets.h" // -------------------- NetworkPacket -------------------------- // serialization Packet::Packet(int32_t id, uint32_t flag, int derived_size) : id(id), flag(flag) { packet_size = header_size + derived_size; packet = (char*)malloc(packet_size); std::cout << "Packet Created: size: " << packet_size << std::endl; // set packet header data uint32_t* ptr = (uint32_t*)packet; ptr[0] = packet_size; ptr[1] = id; ptr[2] = flag; } // deserialization Packet::Packet(void* buf, ssize_t size) : packet_size(size), packet(buf) { packet_size = ((uint32_t*)buf)[0]; id = ((int32_t*)buf)[1]; flag = ((uint32_t*)buf)[2]; } Packet::~Packet() { //free(packet); } int Packet::dataSize() const { return header_size; } std::ostream& Packet::print(std::ostream& stream) const { stream << "Packet" << std::endl; stream << "\tpacket_size: " << packet_size << std::endl; stream << "\tid: " << id << std::endl; stream << "\tflag: " << flag << std::endl; return stream; } std::ostream& operator<<(std::ostream& stream, const Packet &p) { return p.print(stream); } // ----------------------------- InitializationPacket ------------------ EspressoInit::EspressoInit(void* buf, ssize_t size) : Packet(buf, size) { uint32_t* base = (uint32_t*)(((uint8_t*)buf) + Packet::dataSize()); node_id = base[0]; } EspressoInit::EspressoInit(int node_id) : Packet(0, ESPRESSO_INIT, data_size), node_id(node_id) { uint32_t* base = (uint32_t*)(((uint8_t*)packet) + Packet::dataSize()); base[0] = node_id; } std::ostream& EspressoInit::print(std::ostream& stream) const { stream << "EspressoInitializationPacket" << std::endl; stream << "\tnode_id: " << node_id << std::endl; return Packet::print(stream); } std::ostream& operator<<(std::ostream& stream, const EspressoInit &p) { return p.print(stream); } // -------------------------- DecafsClientInit ----------------------- DecafsClientInit::DecafsClientInit(void* buf, ssize_t size) : Packet(buf, size) { uint32_t* base = (uint32_t*)(((uint8_t*)buf) + Packet::dataSize()); user_id = base[0]; } DecafsClientInit::DecafsClientInit(int user_id) : Packet(0, DECAFS_CLIENT_INIT, data_size), user_id(user_id) { uint32_t* base = (uint32_t*)(((uint8_t*)packet) + Packet::dataSize()); base[0] = user_id; } std::ostream& DecafsClientInit::print(std::ostream& stream) const { stream << "DecafsClientInit" << std::endl; stream << "\tuser_id: " << user_id << std::endl; return Packet::print(stream); } std::ostream& operator<<(std::ostream& stream, const DecafsClientInit &p) { return p.print(stream); } // ---------------------- FilePacket -------------------- // constructor from data // serialization FilePacket::FilePacket(uint32_t id, int flag, int derived_size, uint32_t fd, uint32_t file_id, uint32_t stripe_id, uint32_t chunk_num, uint32_t offset, int32_t count) : Packet(id, flag, derived_size + data_size), fd(fd), file_id(file_id), stripe_id(stripe_id), chunk_num(chunk_num), offset(offset), count(count) { uint32_t* base = (uint32_t*)(((uint8_t*)packet) + Packet::dataSize()); base[0] = fd; base[1] = file_id; base[2] = stripe_id; base[3] = chunk_num; base[4] = offset; base[5] = count; } // constructor from a buffer // deserialization FilePacket::FilePacket(void* buf, ssize_t size) : Packet(buf, size) { uint32_t* base = (uint32_t*)(((uint8_t*)buf) + Packet::dataSize()); fd = base[0]; file_id = base[1]; stripe_id = base[2]; chunk_num = base[3]; offset = base[4]; count = base[5]; } int FilePacket::dataSize() const { return Packet::dataSize() + data_size; } std::ostream& FilePacket::print(std::ostream& stream) const { stream << "FilePacket" << std::endl; stream << "\tfd: " << fd << std::endl; stream << "\tfile_id: " << file_id << std::endl; stream << "\tstripe_id: " << stripe_id << std::endl; stream << "\tchunk_num: " << chunk_num << std::endl; stream << "\toffset: " << offset << std::endl; stream << "\tcount: " << count << std::endl; return Packet::print(stream); } std::ostream& operator<<(std::ostream& stream, const FilePacket &packet) { return packet.print(stream); } // ---------------------- FileDataPacket ------------ FileDataPacket::FileDataPacket(void* buf, ssize_t size) : FilePacket(buf, size) { if (count > 0) { data_buffer = ((uint8_t*)buf) + FilePacket::dataSize(); } else { data_buffer = NULL; } } FileDataPacket::FileDataPacket(uint32_t id, int flag, int derived_size, uint32_t fd, uint32_t file_id, uint32_t stripe_id, uint32_t chunk_num, uint32_t offset, int32_t count, uint8_t* buf) : FilePacket(id, flag, std::max(0, count), fd, file_id, stripe_id, chunk_num, offset, count) { data_buffer = buf; uint8_t* data_loc = ((uint8_t*)packet) + FilePacket::dataSize(); if (count > 0) { memcpy(data_loc, buf, count); } // TODO do i need to free buf? // or is it the creators responsibility? } int FileDataPacket::dataSize() const { return FilePacket::dataSize() + data_size; } std::ostream& FileDataPacket::print(std::ostream& stream) const { stream << "FileDataPacket" << std::endl; stream << "data_buffer: "; stream.write((const char*)data_buffer, count); stream << std::endl; return FilePacket::print(stream); } std::ostream& operator<<(std::ostream& stream, const FileDataPacket &packet) { return packet.print(stream); } // ------------------------ ReadChunkPacket ------------------ ReadChunkRequest::ReadChunkRequest(void* buf, ssize_t packet_size) : FilePacket(buf, packet_size) { } ReadChunkRequest::ReadChunkRequest(uint32_t id, uint32_t fd, uint32_t file_id, uint32_t stripe_id, uint32_t chunk_num, uint32_t offset, int32_t count) : FilePacket(id, READ_CHUNK, 0, fd, file_id, stripe_id, chunk_num, offset, count) { } std::ostream& ReadChunkRequest::print(std::ostream& stream) const { stream << "ReadChunkRequest" << std::endl; return FilePacket::print(stream); } std::ostream& operator<<(std::ostream& stream, const ReadChunkRequest &req) { return req.print(stream); } // ------------------------ WriteChunkResponse ------------------ WriteChunkResponse::WriteChunkResponse(void* buf, ssize_t packet_size) : FilePacket(buf, packet_size) { } WriteChunkResponse::WriteChunkResponse(uint32_t id, uint32_t fd, uint32_t file_id, uint32_t stripe_id, uint32_t chunk_num, uint32_t offset, int32_t count) : FilePacket(id, WRITE_CHUNK_RESPONSE, 0, fd, file_id, stripe_id, chunk_num, offset, count) { } std::ostream& WriteChunkResponse::print(std::ostream& stream) const { stream << "WriteChunkResponse" << std::endl; return FilePacket::print(stream); } std::ostream& operator<<(std::ostream& stream, const WriteChunkResponse &req) { return req.print(stream); } // ------------------------ WriteChunkPacket --------------------------- WriteChunkRequest::WriteChunkRequest(void* buf, ssize_t packet_size) : FileDataPacket(buf, packet_size) { } WriteChunkRequest::WriteChunkRequest(uint32_t id, uint32_t fd, uint32_t file_id, uint32_t stripe_id, uint32_t chunk_num, uint32_t offset, int32_t count, uint8_t * buf) : FileDataPacket(id, WRITE_CHUNK, 0, fd, file_id, stripe_id, chunk_num, offset, count, buf) { } std::ostream& WriteChunkRequest::print(std::ostream& stream) const { stream << "WriteChunkRequest" << std::endl; return FileDataPacket::print(stream); } std::ostream& operator<<(std::ostream& stream, const WriteChunkRequest &req) { return req.print(stream); } // ------------------------ ReadChunkResponse --------------------------- ReadChunkResponse::ReadChunkResponse(void* buf, ssize_t packet_size) : FileDataPacket(buf, packet_size) { } ReadChunkResponse::ReadChunkResponse(uint32_t id, uint32_t fd, uint32_t file_id, uint32_t stripe_id, uint32_t chunk_num, uint32_t offset, int32_t count, uint8_t * buf) : FileDataPacket(id, READ_CHUNK_RESPONSE, 0, fd, file_id, stripe_id, chunk_num, offset, count, buf) { } std::ostream& ReadChunkResponse::print(std::ostream& stream) const { stream << "ReadChunkResponse" << std::endl; return FileDataPacket::print(stream); } std::ostream& operator<<(std::ostream& stream, const ReadChunkResponse &req) { return req.print(stream); } // ------------------------------- DeleteChunkPacket ----------------------------- DeleteChunkRequest::DeleteChunkRequest(void* buf, ssize_t size) : FilePacket(buf, size) { } DeleteChunkRequest::DeleteChunkRequest(uint32_t id, uint32_t file_id, uint32_t stripe_id, uint32_t chunk_num) : FilePacket(id, DELETE_CHUNK, 0, fd, file_id, stripe_id, chunk_num, -1, -1) { } std::ostream& DeleteChunkRequest::print(std::ostream& stream) const { stream << "DeleteChunkRequest" << std::endl; return FilePacket::print(stream); } std::ostream& operator<<(std::ostream& stream, const DeleteChunkRequest &req) { return req.print(stream); } // ------------------------------- DeleteChunkResponse ----------------------------- DeleteChunkResponse::DeleteChunkResponse(void* buf, ssize_t size) : FilePacket(buf, size) { } DeleteChunkResponse::DeleteChunkResponse(uint32_t id, uint32_t file_id, uint32_t stripe_id, uint32_t chunk_num) : FilePacket(id, DELETE_CHUNK_RESPONSE, 0, fd, file_id, stripe_id, chunk_num, -1, -1) { } std::ostream& DeleteChunkResponse::print(std::ostream& stream) const { stream << "DeleteChunkResponse" << std::endl; return FilePacket::print(stream); } std::ostream& operator<<(std::ostream& stream, const DeleteChunkResponse &req) { return req.print(stream); } <commit_msg>added NULL buffer protection<commit_after>#include "network_packets.h" // -------------------- NetworkPacket -------------------------- // serialization Packet::Packet(int32_t id, uint32_t flag, int derived_size) : id(id), flag(flag) { packet_size = header_size + derived_size; packet = (char*)malloc(packet_size); std::cout << "Packet Created: size: " << packet_size << std::endl; // set packet header data uint32_t* ptr = (uint32_t*)packet; ptr[0] = packet_size; ptr[1] = id; ptr[2] = flag; } // deserialization Packet::Packet(void* buf, ssize_t size) : packet_size(size), packet(buf) { packet_size = ((uint32_t*)buf)[0]; id = ((int32_t*)buf)[1]; flag = ((uint32_t*)buf)[2]; } Packet::~Packet() { //free(packet); } int Packet::dataSize() const { return header_size; } std::ostream& Packet::print(std::ostream& stream) const { stream << "Packet" << std::endl; stream << "\tpacket_size: " << packet_size << std::endl; stream << "\tid: " << id << std::endl; stream << "\tflag: " << flag << std::endl; return stream; } std::ostream& operator<<(std::ostream& stream, const Packet &p) { return p.print(stream); } // ----------------------------- InitializationPacket ------------------ EspressoInit::EspressoInit(void* buf, ssize_t size) : Packet(buf, size) { uint32_t* base = (uint32_t*)(((uint8_t*)buf) + Packet::dataSize()); node_id = base[0]; } EspressoInit::EspressoInit(int node_id) : Packet(0, ESPRESSO_INIT, data_size), node_id(node_id) { uint32_t* base = (uint32_t*)(((uint8_t*)packet) + Packet::dataSize()); base[0] = node_id; } std::ostream& EspressoInit::print(std::ostream& stream) const { stream << "EspressoInitializationPacket" << std::endl; stream << "\tnode_id: " << node_id << std::endl; return Packet::print(stream); } std::ostream& operator<<(std::ostream& stream, const EspressoInit &p) { return p.print(stream); } // -------------------------- DecafsClientInit ----------------------- DecafsClientInit::DecafsClientInit(void* buf, ssize_t size) : Packet(buf, size) { uint32_t* base = (uint32_t*)(((uint8_t*)buf) + Packet::dataSize()); user_id = base[0]; } DecafsClientInit::DecafsClientInit(int user_id) : Packet(0, DECAFS_CLIENT_INIT, data_size), user_id(user_id) { uint32_t* base = (uint32_t*)(((uint8_t*)packet) + Packet::dataSize()); base[0] = user_id; } std::ostream& DecafsClientInit::print(std::ostream& stream) const { stream << "DecafsClientInit" << std::endl; stream << "\tuser_id: " << user_id << std::endl; return Packet::print(stream); } std::ostream& operator<<(std::ostream& stream, const DecafsClientInit &p) { return p.print(stream); } // ---------------------- FilePacket -------------------- // constructor from data // serialization FilePacket::FilePacket(uint32_t id, int flag, int derived_size, uint32_t fd, uint32_t file_id, uint32_t stripe_id, uint32_t chunk_num, uint32_t offset, int32_t count) : Packet(id, flag, derived_size + data_size), fd(fd), file_id(file_id), stripe_id(stripe_id), chunk_num(chunk_num), offset(offset), count(count) { uint32_t* base = (uint32_t*)(((uint8_t*)packet) + Packet::dataSize()); base[0] = fd; base[1] = file_id; base[2] = stripe_id; base[3] = chunk_num; base[4] = offset; base[5] = count; } // constructor from a buffer // deserialization FilePacket::FilePacket(void* buf, ssize_t size) : Packet(buf, size) { uint32_t* base = (uint32_t*)(((uint8_t*)buf) + Packet::dataSize()); fd = base[0]; file_id = base[1]; stripe_id = base[2]; chunk_num = base[3]; offset = base[4]; count = base[5]; } int FilePacket::dataSize() const { return Packet::dataSize() + data_size; } std::ostream& FilePacket::print(std::ostream& stream) const { stream << "FilePacket" << std::endl; stream << "\tfd: " << fd << std::endl; stream << "\tfile_id: " << file_id << std::endl; stream << "\tstripe_id: " << stripe_id << std::endl; stream << "\tchunk_num: " << chunk_num << std::endl; stream << "\toffset: " << offset << std::endl; stream << "\tcount: " << count << std::endl; return Packet::print(stream); } std::ostream& operator<<(std::ostream& stream, const FilePacket &packet) { return packet.print(stream); } // ---------------------- FileDataPacket ------------ FileDataPacket::FileDataPacket(void* buf, ssize_t size) : FilePacket(buf, size) { if (count > 0) { data_buffer = ((uint8_t*)buf) + FilePacket::dataSize(); } else { data_buffer = NULL; } } FileDataPacket::FileDataPacket(uint32_t id, int flag, int derived_size, uint32_t fd, uint32_t file_id, uint32_t stripe_id, uint32_t chunk_num, uint32_t offset, int32_t count, uint8_t* buf) : FilePacket(id, flag, std::max(0, count), fd, file_id, stripe_id, chunk_num, offset, count) { data_buffer = buf; uint8_t* data_loc = ((uint8_t*)packet) + FilePacket::dataSize(); if (count > 0) { memcpy(data_loc, buf, count); } // TODO do i need to free buf? // or is it the creators responsibility? } int FileDataPacket::dataSize() const { return FilePacket::dataSize() + data_size; } std::ostream& FileDataPacket::print(std::ostream& stream) const { stream << "FileDataPacket" << std::endl; stream << "data_buffer: "; if (data_buffer) { stream.write((const char*)data_buffer, count); } else { stream << "<NULL>"; } stream << std::endl; return FilePacket::print(stream); } std::ostream& operator<<(std::ostream& stream, const FileDataPacket &packet) { return packet.print(stream); } // ------------------------ ReadChunkPacket ------------------ ReadChunkRequest::ReadChunkRequest(void* buf, ssize_t packet_size) : FilePacket(buf, packet_size) { } ReadChunkRequest::ReadChunkRequest(uint32_t id, uint32_t fd, uint32_t file_id, uint32_t stripe_id, uint32_t chunk_num, uint32_t offset, int32_t count) : FilePacket(id, READ_CHUNK, 0, fd, file_id, stripe_id, chunk_num, offset, count) { } std::ostream& ReadChunkRequest::print(std::ostream& stream) const { stream << "ReadChunkRequest" << std::endl; return FilePacket::print(stream); } std::ostream& operator<<(std::ostream& stream, const ReadChunkRequest &req) { return req.print(stream); } // ------------------------ WriteChunkResponse ------------------ WriteChunkResponse::WriteChunkResponse(void* buf, ssize_t packet_size) : FilePacket(buf, packet_size) { } WriteChunkResponse::WriteChunkResponse(uint32_t id, uint32_t fd, uint32_t file_id, uint32_t stripe_id, uint32_t chunk_num, uint32_t offset, int32_t count) : FilePacket(id, WRITE_CHUNK_RESPONSE, 0, fd, file_id, stripe_id, chunk_num, offset, count) { } std::ostream& WriteChunkResponse::print(std::ostream& stream) const { stream << "WriteChunkResponse" << std::endl; return FilePacket::print(stream); } std::ostream& operator<<(std::ostream& stream, const WriteChunkResponse &req) { return req.print(stream); } // ------------------------ WriteChunkPacket --------------------------- WriteChunkRequest::WriteChunkRequest(void* buf, ssize_t packet_size) : FileDataPacket(buf, packet_size) { } WriteChunkRequest::WriteChunkRequest(uint32_t id, uint32_t fd, uint32_t file_id, uint32_t stripe_id, uint32_t chunk_num, uint32_t offset, int32_t count, uint8_t * buf) : FileDataPacket(id, WRITE_CHUNK, 0, fd, file_id, stripe_id, chunk_num, offset, count, buf) { } std::ostream& WriteChunkRequest::print(std::ostream& stream) const { stream << "WriteChunkRequest" << std::endl; return FileDataPacket::print(stream); } std::ostream& operator<<(std::ostream& stream, const WriteChunkRequest &req) { return req.print(stream); } // ------------------------ ReadChunkResponse --------------------------- ReadChunkResponse::ReadChunkResponse(void* buf, ssize_t packet_size) : FileDataPacket(buf, packet_size) { } ReadChunkResponse::ReadChunkResponse(uint32_t id, uint32_t fd, uint32_t file_id, uint32_t stripe_id, uint32_t chunk_num, uint32_t offset, int32_t count, uint8_t * buf) : FileDataPacket(id, READ_CHUNK_RESPONSE, 0, fd, file_id, stripe_id, chunk_num, offset, count, buf) { } std::ostream& ReadChunkResponse::print(std::ostream& stream) const { stream << "ReadChunkResponse" << std::endl; return FileDataPacket::print(stream); } std::ostream& operator<<(std::ostream& stream, const ReadChunkResponse &req) { return req.print(stream); } // ------------------------------- DeleteChunkPacket ----------------------------- DeleteChunkRequest::DeleteChunkRequest(void* buf, ssize_t size) : FilePacket(buf, size) { } DeleteChunkRequest::DeleteChunkRequest(uint32_t id, uint32_t file_id, uint32_t stripe_id, uint32_t chunk_num) : FilePacket(id, DELETE_CHUNK, 0, fd, file_id, stripe_id, chunk_num, -1, -1) { } std::ostream& DeleteChunkRequest::print(std::ostream& stream) const { stream << "DeleteChunkRequest" << std::endl; return FilePacket::print(stream); } std::ostream& operator<<(std::ostream& stream, const DeleteChunkRequest &req) { return req.print(stream); } // ------------------------------- DeleteChunkResponse ----------------------------- DeleteChunkResponse::DeleteChunkResponse(void* buf, ssize_t size) : FilePacket(buf, size) { } DeleteChunkResponse::DeleteChunkResponse(uint32_t id, uint32_t file_id, uint32_t stripe_id, uint32_t chunk_num) : FilePacket(id, DELETE_CHUNK_RESPONSE, 0, fd, file_id, stripe_id, chunk_num, -1, -1) { } std::ostream& DeleteChunkResponse::print(std::ostream& stream) const { stream << "DeleteChunkResponse" << std::endl; return FilePacket::print(stream); } std::ostream& operator<<(std::ostream& stream, const DeleteChunkResponse &req) { return req.print(stream); } <|endoftext|>
<commit_before>#pragma once #include <vector> #include <tuple> #include <array> #include <Eigen/Dense> #include <iod/symbols.hh> #include <vpp/core/image2d.hh> #include <vpp/core/vector.hh> #include <vpp/core/liie.hh> #include <vpp/core/box_nbh2d.hh> #include <vpp/core/make_array.hh> namespace vpp { template <typename T, typename U> void euclide_distance_transform(image2d<T>& input, image2d<U>& sedt) { image2d<vshort2> R(input.domain(), _border = 1); fill_with_border(R, vshort2{0,0}); auto forward4 = [] () { return make_array(vint2{-1, -1}, vint2{-1, 0}, vint2{-1, 1}, vint2{0, -1}); }; auto backward4 = [] () { return make_array(vint2{1, 1}, vint2{1, 0}, vint2{1, -1}, vint2{0, 1}); }; fill_with_border(sedt, input.nrows() + input.ncols()); pixel_wise(input, sedt) | [] (auto& i, auto& s) { if (i == 0) s = 0; }; auto run = [&] (auto neighborhood, auto col_direction, auto row_direction1, auto row_direction2, auto spn) { row_wise(sedt, R)(col_direction) | [&] (auto sedt_row, auto R_row) { // Forward pass auto sedt_row_nbh = box_nbh2d<U, 3, 3>(sedt_row); auto R_row_nbh = box_nbh2d<vshort2, 3, 3>(R_row); pixel_wise(sedt_row_nbh, R_row_nbh)(row_direction1) | [&] (auto& sedt_nbh, auto& R_nbh) { vint2 min_rel_coord = neighborhood()[0]; int min_dist = INT_MAX; for (vint2 nc : neighborhood()) { int d = sedt_nbh(nc) + 2 * (std::abs(R_nbh(nc)[0] * nc[0]) + std::abs(R_nbh(nc)[1] * nc[1])) + nc.cwiseAbs().sum(); if (d < min_dist) { min_dist = d; min_rel_coord = nc; } } if (min_dist < sedt_nbh(0, 0)) { R_nbh(0, 0) = (R_nbh(min_rel_coord) + min_rel_coord.cast<short>()).template cast<short>(); sedt_nbh(0, 0) = min_dist; } }; // Backward pass pixel_wise(sedt_row_nbh, R_row_nbh)(row_direction2, _no_threads) | [&] (auto& sedt_nbh, auto& R_nbh) { int d = sedt_nbh(spn()) + 2 * std::abs(R_nbh(spn())[1]) + 1; if (d < sedt_nbh(0, 0)) { sedt_nbh(0, 0) = d; R_nbh(0, 0) = (R_nbh(spn()) + spn().template cast<short>()).template cast<short>(); } }; }; }; run(forward4, _top_to_bottom, _left_to_right, _right_to_left, [] () { return vint2{0, 1}; }); run(backward4, _bottom_to_top, _right_to_left, _left_to_right, [] () { return vint2{0, -1}; }); // pixel_wise(sedt) | [] (auto& p) { p/=100; }; } // template <typename T, typename U> // void euclide_distance_transform(image2d<T>& input, image2d<U>& sedt) // { // image2d<vshort2> R(input.domain(), _border = 1); // fill_with_border(R, vshort2{0,0}); // auto forward4 = [] () { return make_array(vint2{-1, -1}, vint2{-1, 0}, vint2{-1, 1}, vint2{0, -1}); }; // auto backward4 = [] () { return make_array(vint2{1, 1}, vint2{1, 0}, vint2{1, -1}, vint2{0, 1}); }; // fill_with_border(sedt, INT_MAX / 2); // pixel_wise(input, sedt) | [] (auto& i, auto& s) { if (i == 0) s = 0; }; // auto run = [&] (auto neighborhood, auto col_direction, // auto row_direction1, auto row_direction2, auto spn) { // row_wise(sedt, R)(col_direction) | [&] (auto sedt_row, auto R_row) // { // // Forward pass // auto sedt_row_nbh = box_nbh2d<int, 3, 3>(sedt_row); // auto R_row_nbh = box_nbh2d<vshort2, 3, 3>(R_row); // pixel_wise(sedt_row_nbh, R_row_nbh)(row_direction1, _no_threads) // | [&] (auto& sedt_nbh, auto& R_nbh) // { // int min_dist = INT_MAX; // for (vint2 nc : neighborhood()) // { // int d = sedt_nbh(nc) + 1; // if (d < min_dist) // min_dist = d; // } // if (min_dist < sedt_nbh(0, 0)) // sedt_nbh(0, 0) = min_dist; // }; // }; // }; // run(forward4, _top_to_bottom, _left_to_right, _right_to_left, [] () { return vint2{0, 1}; }); // run(backward4, _bottom_to_top, _right_to_left, _left_to_right, [] () { return vint2{0, -1}; }); // // pixel_wise(sedt) | [] (auto& p) { p/=100; }; // } template <unsigned N, typename F> void loop_unroll(F f, std::enable_if_t<N == 0>* = 0) { f(N); } template <unsigned N, typename F> void loop_unroll(F f, std::enable_if_t<N != 0>* = 0) { f(N); loop_unroll<N-1>(f); } template <typename T, typename U, typename F, typename FW, typename B, typename BW, int WS = 3> void generic_incremental_distance_transform(image2d<T>& input, image2d<U>& sedt, F forward, FW forward_ws, B backward, BW backward_ws, std::integral_constant<int, WS> = std::integral_constant<int, WS>()) { fill_with_border(sedt, input.nrows() + input.ncols()); pixel_wise(input, sedt) | [] (auto& i, auto& s) { if (i == 0) s = 0; }; auto run = [&] (auto neighb, auto ws, auto col_direction, auto row_direction) { auto sedt_nbh = box_nbh2d<int, WS, WS>(sedt); pixel_wise(sedt_nbh)(col_direction, row_direction) | [neighb, ws] (auto sn) { int min_dist = sn(0,0); auto nbh = neighb(); // if (neighb().size() < 6) auto it = [&] (int i) { min_dist = std::min(min_dist, ws()[i] + sn(neighb()[i])); }; typedef decltype(nbh) NBH; loop_unroll<std::tuple_size<NBH>::value - 1>(it); sn(0,0) = min_dist; }; }; run(forward, forward_ws, _top_to_bottom, _left_to_right); run(backward, backward_ws, _bottom_to_top, _right_to_left); } const auto d4_distance_transform = [] (auto& a, auto& b) { generic_incremental_distance_transform(a, b, [] () { return make_array(vint2{-1, 0}, vint2{0, -1}); }, [] () { return make_array(1, 1); }, [] () { return make_array(vint2{1, 0}, vint2{0, 1}); }, [] () { return make_array(1, 1); }); }; const auto d8_distance_transform = [] (auto& a, auto& b) { generic_incremental_distance_transform(a, b, [] () { return make_array(vint2{-1, -1}, vint2{-1, 0}, vint2{-1, 1}, vint2{0, -1}); }, [] () { return make_array(1,1,1,1); }, [] () { return make_array(vint2{1, 1}, vint2{1, 0}, vint2{1, -1}, vint2{0, 1}); }, [] () { return make_array(1, 1, 1, 1); }); }; const auto d3_4_distance_transform = [] (auto& a, auto& b) { generic_incremental_distance_transform(a, b, [] () { return make_array(vint2{-1, -1}, vint2{-1, 0}, vint2{-1, 1}, vint2{0, -1}); }, [] () { return make_array(4,3,4,3); }, [] () { return make_array(vint2{1, 1}, vint2{1, 0}, vint2{1, -1}, vint2{0, 1}); }, [] () { return make_array(4, 3, 4, 3); }, std::integral_constant<int, 5>()); }; const auto d5_7_11_distance_transform = [] (auto& a, auto& b) { generic_incremental_distance_transform(a, b, [] () { return make_array(vint2{-2, -1}, vint2{-2, 1}, vint2{-1, -2}, vint2{-1, -1}, vint2{-1, 0}, vint2{-1, 1}, vint2{-1, 2}, vint2{0, -1}); }, [] () { return make_array(11,11,11,7,5,7,11,5); }, [] () { return make_array(vint2{0, 1}, vint2{1, -2}, vint2{1, -1}, vint2{1, 0}, vint2{1, 1}, vint2{1, 2}, vint2{2, -1}, vint2{2, 1}); }, [] () { return make_array(5,11,7,5,7,11,11,11); }, std::integral_constant<int, 5>()); }; } <commit_msg>Remove box_nbh2d from distance_transforms.<commit_after>#pragma once #include <vector> #include <tuple> #include <array> #include <Eigen/Dense> #include <iod/symbols.hh> #include <vpp/core/image2d.hh> #include <vpp/core/vector.hh> #include <vpp/core/liie.hh> #include <vpp/core/make_array.hh> namespace vpp { template <typename T, typename U> void euclide_distance_transform(image2d<T>& input, image2d<U>& sedt) { image2d<vshort2> R(input.domain(), _border = 1); fill_with_border(R, vshort2{0,0}); auto forward4 = [] () { return make_array(vint2{-1, -1}, vint2{-1, 0}, vint2{-1, 1}, vint2{0, -1}); }; auto backward4 = [] () { return make_array(vint2{1, 1}, vint2{1, 0}, vint2{1, -1}, vint2{0, 1}); }; fill_with_border(sedt, input.nrows() + input.ncols()); pixel_wise(input, sedt) | [] (auto& i, auto& s) { if (i == 0) s = 0; }; auto run = [&] (auto neighborhood, auto col_direction, auto row_direction1, auto row_direction2, auto spn) { row_wise(sedt, R)(col_direction) | [&] (auto sedt_row, auto R_row) { // Forward pass pixel_wise(relative_access(sedt_row), relative_access(R_row))(row_direction1) | [&] (auto& sedt_nbh, auto& R_nbh) { vint2 min_rel_coord = neighborhood()[0]; int min_dist = INT_MAX; for (vint2 nc : neighborhood()) { int d = sedt_nbh(nc) + 2 * (std::abs(R_nbh(nc)[0] * nc[0]) + std::abs(R_nbh(nc)[1] * nc[1])) + nc.cwiseAbs().sum(); if (d < min_dist) { min_dist = d; min_rel_coord = nc; } } if (min_dist < sedt_nbh(0, 0)) { R_nbh(0, 0) = (R_nbh(min_rel_coord) + min_rel_coord.cast<short>()).template cast<short>(); sedt_nbh(0, 0) = min_dist; } }; // Backward pass pixel_wise(relative_access(sedt_row), relative_access(R_row)) (row_direction2, _no_threads) | [&] (auto sedt_nbh, auto R_nbh) { int d = sedt_nbh(spn()) + 2 * std::abs(R_nbh(spn())[1]) + 1; if (d < sedt_nbh(0, 0)) { sedt_nbh(0, 0) = d; R_nbh(0, 0) = (R_nbh(spn()) + spn().template cast<short>()).template cast<short>(); } }; }; }; run(forward4, _top_to_bottom, _left_to_right, _right_to_left, [] () { return vint2{0, 1}; }); run(backward4, _bottom_to_top, _right_to_left, _left_to_right, [] () { return vint2{0, -1}; }); // pixel_wise(sedt) | [] (auto& p) { p/=100; }; } template <unsigned N, typename F> void loop_unroll(F f, std::enable_if_t<N == 0>* = 0) { f(N); } template <unsigned N, typename F> void loop_unroll(F f, std::enable_if_t<N != 0>* = 0) { f(N); loop_unroll<N-1>(f); } template <typename T, typename U, typename F, typename FW, typename B, typename BW, int WS = 3> void generic_incremental_distance_transform(image2d<T>& input, image2d<U>& sedt, F forward, FW forward_ws, B backward, BW backward_ws, std::integral_constant<int, WS> = std::integral_constant<int, WS>()) { fill_with_border(sedt, input.nrows() + input.ncols()); pixel_wise(input, sedt) | [] (auto& i, auto& s) { if (i == 0) s = 0; }; auto run = [&] (auto neighb, auto ws, auto col_direction, auto row_direction) { pixel_wise(relative_access(sedt))(col_direction, row_direction) | [neighb, ws] (auto sn) { int min_dist = sn(0,0); auto nbh = neighb(); // if (neighb().size() < 6) auto it = [&] (int i) { min_dist = std::min(min_dist, ws()[i] + sn(neighb()[i])); }; typedef decltype(nbh) NBH; loop_unroll<std::tuple_size<NBH>::value - 1>(it); sn(0,0) = min_dist; }; }; run(forward, forward_ws, _top_to_bottom, _left_to_right); run(backward, backward_ws, _bottom_to_top, _right_to_left); } const auto d4_distance_transform = [] (auto& a, auto& b) { generic_incremental_distance_transform(a, b, [] () { return make_array(vint2{-1, 0}, vint2{0, -1}); }, [] () { return make_array(1, 1); }, [] () { return make_array(vint2{1, 0}, vint2{0, 1}); }, [] () { return make_array(1, 1); }); }; const auto d8_distance_transform = [] (auto& a, auto& b) { generic_incremental_distance_transform(a, b, [] () { return make_array(vint2{-1, -1}, vint2{-1, 0}, vint2{-1, 1}, vint2{0, -1}); }, [] () { return make_array(1,1,1,1); }, [] () { return make_array(vint2{1, 1}, vint2{1, 0}, vint2{1, -1}, vint2{0, 1}); }, [] () { return make_array(1, 1, 1, 1); }); }; const auto d3_4_distance_transform = [] (auto& a, auto& b) { generic_incremental_distance_transform(a, b, [] () { return make_array(vint2{-1, -1}, vint2{-1, 0}, vint2{-1, 1}, vint2{0, -1}); }, [] () { return make_array(4,3,4,3); }, [] () { return make_array(vint2{1, 1}, vint2{1, 0}, vint2{1, -1}, vint2{0, 1}); }, [] () { return make_array(4, 3, 4, 3); }, std::integral_constant<int, 5>()); }; const auto d5_7_11_distance_transform = [] (auto& a, auto& b) { generic_incremental_distance_transform(a, b, [] () { return make_array(vint2{-2, -1}, vint2{-2, 1}, vint2{-1, -2}, vint2{-1, -1}, vint2{-1, 0}, vint2{-1, 1}, vint2{-1, 2}, vint2{0, -1}); }, [] () { return make_array(11,11,11,7,5,7,11,5); }, [] () { return make_array(vint2{0, 1}, vint2{1, -2}, vint2{1, -1}, vint2{1, 0}, vint2{1, 1}, vint2{1, 2}, vint2{2, -1}, vint2{2, 1}); }, [] () { return make_array(5,11,7,5,7,11,11,11); }, std::integral_constant<int, 5>()); }; } <|endoftext|>
<commit_before>// Copyright (C) 2014 sails Authors. // All rights reserved. // // Official git repository and contact information can be found at // https://github.com/sails/sails and http://www.sailsxu.com/. // // Filename: monitor.cc // // Author: sailsxu <[email protected]> // Created: 2014-10-20 17:14:50 #include "src/monitor.h" #include <string> #include <vector> #ifdef __linux__ #include "sails/system/cpu_usage.h" #endif #include "sails/system/mem_usage.h" #include "src/service_register.h" #include "cpptempl/src/cpptempl.h" namespace sails { void ServerStatProcessor::serverstat(sails::net::HttpRequest*, sails::net::HttpResponse* response) { cpptempl::auto_data dict; pid_t pid = getpid(); dict["PID"] = pid; dict["PORT"] = server->ListenPort(); // cpu info #ifdef __linux__ double cpu = 0; if (sails::system::GetProcessCpuUsage(pid, 100, &cpu)) { dict["CPU"] = cpu; } #endif // memory info uint64_t vm_size, mem_size; if (sails::system::GetMemoryUsedKiloBytes(pid, &vm_size, &mem_size)) { dict["VMSIZE"] = (int64_t)vm_size; dict["MEMSIZE"] = (int64_t)mem_size; } char run_mode[2]; snprintf(run_mode, sizeof(run_mode), "%d", server->RunMode()); dict["run_mode"] = run_mode; dict["recv_queue_size"] = (int64_t)server->GetRecvDataNum(); // 网络线程信息 dict["NetThreadNum"] = (int64_t)server->NetThreadNum(); for (size_t i = 0; i < server->NetThreadNum(); i++) { cpptempl::auto_data netthread_dict; net::NetThread<sails::ReqMessage>::NetThreadStatus netstatus = server->GetNetThreadStatus(i); netthread_dict["NetThread_NO"] = i; netthread_dict["NetThread_status"] = netstatus.status; netthread_dict["NetThread_connector_num"] = netstatus.connector_num; netthread_dict["NetThread_accept_times"] = (int64_t)netstatus.accept_times; netthread_dict["NetThread_reject_times"] = (int64_t)netstatus.reject_times; netthread_dict["NetThread_send_queue_capacity"] = (int64_t)netstatus.send_queue_capacity; netthread_dict["NetThread_send_queue_size"] = (int64_t)netstatus.send_queue_size; dict["net_threads"].push_back(netthread_dict); } // 处理线程信息 dict["HandleThreadNum"] = (int64_t)server->HandleThreadNum(); for (size_t i = 0; i < server->HandleThreadNum(); i++) { cpptempl::auto_data handlethread_dict; net::HandleThread<sails::ReqMessage>::HandleThreadStatus handlestatus = server->GetHandleThreadStatus(i); handlethread_dict["HandleThread_NO"] = i; handlethread_dict["HandleThread_status"] = handlestatus.status; handlethread_dict["HandleThread_handle_times"] = (int64_t)handlestatus.handle_times; if (server->RunMode() == 2) { handlethread_dict["HandleThread_handle_queue_capacity"] = (int64_t)handlestatus.handle_queue_capacity; handlethread_dict["HandleThread_handle_queue_size"] = (int64_t)handlestatus.handle_queue_size; } dict["handle_threads"].push_back(handlethread_dict); } // service std::vector<ServiceRegister::ServiceStat> services = ServiceRegister::instance()->GetAllServiceStat(); dict["serivcesNum"] = services.size(); for (size_t i = 0; i < services.size(); ++i) { cpptempl::auto_data service_dict; service_dict["serviceName"] = services[i].name; service_dict["callTimes"] = (int64_t)services[i].call_times; service_dict["failedTimes"] = (int64_t)services[i].failed_times; service_dict["successTimes"] = (int64_t)services[i].success_times; for (int index = 0; index < 11; index++) { char time_name[5] = {"\0"}; snprintf(time_name, sizeof(time_name), "L%d", index); service_dict[std::string(time_name)] = services[i].spendTime[index]; } dict["services"].push_back(service_dict); } FILE* file = fopen("../static/stat.html", "r"); if (file == NULL) { printf("can't open file\n"); } char buf[5000] = {'\0'}; int readNum = fread(buf, 1, 5000, file); std::string str(buf, readNum); std::string body = cpptempl::parse(str, dict); response->SetBody(body.c_str(), body.size()); } void ServerStatProcessor::index(sails::net::HttpRequest*, sails::net::HttpResponse* response) { response->SetBody("saf index"); } Monitor::Monitor(sails::Server* server, int port) { thread = NULL; status = Monitor::STOPING; isTerminate = false; this->server = server; this->port = port; } Monitor::~Monitor() { if (processor != NULL) { delete processor; processor = NULL; } if (thread != NULL) { Terminate(); Join(); } if (http_server != NULL) { delete http_server; http_server = NULL; } } void Monitor::Run() { isTerminate = false; thread = new std::thread(Start, this); status = Monitor::RUNING; } void Monitor::Terminate() { http_server->Stop(); isTerminate = true; } void Monitor::Join() { if (thread != NULL) { thread->join(); status = Monitor::STOPING; delete thread; thread = NULL; } } void Monitor::Start(Monitor* monitor) { monitor->http_server = new sails::net::HttpServer(); monitor->http_server->Init(monitor->port, 1, 10, 1); monitor->http_server->SetStaticResourcePath(std::string("../static/")); // 请求处理器与url映射 monitor->processor = new ServerStatProcessor(monitor->server); HTTPBIND(monitor->http_server, "/stat", monitor->processor, ServerStatProcessor::serverstat); HTTPBIND(monitor->http_server, "/", monitor->processor, ServerStatProcessor::index); while (!monitor->isTerminate) { sleep(1); } } } // namespace sails <commit_msg>update<commit_after>// Copyright (C) 2014 sails Authors. // All rights reserved. // // Official git repository and contact information can be found at // https://github.com/sails/sails and http://www.sailsxu.com/. // // Filename: monitor.cc // // Author: sailsxu <[email protected]> // Created: 2014-10-20 17:14:50 #include "src/monitor.h" #include <string> #include <vector> #ifdef __linux__ #include "sails/system/cpu_usage.h" #endif #include "sails/system/mem_usage.h" #include "src/service_register.h" #include "cpptempl/src/cpptempl.h" namespace sails { void ServerStatProcessor::serverstat(sails::net::HttpRequest*, sails::net::HttpResponse* response) { cpptempl::auto_data dict; pid_t pid = getpid(); dict["PID"] = pid; dict["PORT"] = server->ListenPort(); // cpu info #ifdef __linux__ double cpu = 0; if (sails::system::GetProcessCpuUsage(pid, 100, &cpu)) { dict["CPU"] = cpu; } #endif // memory info uint64_t vm_size, mem_size; if (sails::system::GetMemoryUsedKiloBytes(pid, &vm_size, &mem_size)) { dict["VMSIZE"] = (int64_t)vm_size; dict["MEMSIZE"] = (int64_t)mem_size; } char run_mode[2]; snprintf(run_mode, sizeof(run_mode), "%d", server->RunMode()); dict["run_mode"] = run_mode; dict["recv_queue_size"] = (int64_t)server->GetRecvDataNum(); // 网络线程信息 dict["NetThreadNum"] = (int64_t)server->NetThreadNum(); for (size_t i = 0; i < server->NetThreadNum(); i++) { cpptempl::auto_data netthread_dict; net::NetThread<sails::ReqMessage>::NetThreadStatus netstatus = server->GetNetThreadStatus(i); netthread_dict["NetThread_NO"] = i; netthread_dict["NetThread_status"] = netstatus.status; netthread_dict["NetThread_connector_num"] = netstatus.connector_num; netthread_dict["NetThread_accept_times"] = (int64_t)netstatus.accept_times; netthread_dict["NetThread_reject_times"] = (int64_t)netstatus.reject_times; netthread_dict["NetThread_send_queue_capacity"] = (int64_t)netstatus.send_queue_capacity; netthread_dict["NetThread_send_queue_size"] = (int64_t)netstatus.send_queue_size; dict["net_threads"].push_back(netthread_dict); } // 处理线程信息 dict["HandleThreadNum"] = (int64_t)server->HandleThreadNum(); for (size_t i = 0; i < server->HandleThreadNum(); i++) { cpptempl::auto_data handlethread_dict; net::HandleThread<sails::ReqMessage>::HandleThreadStatus handlestatus = server->GetHandleThreadStatus(i); handlethread_dict["HandleThread_NO"] = i; handlethread_dict["HandleThread_status"] = handlestatus.status; handlethread_dict["HandleThread_handle_times"] = (int64_t)handlestatus.handle_times; if (server->RunMode() == 2) { handlethread_dict["HandleThread_handle_queue_capacity"] = (int64_t)handlestatus.handle_queue_capacity; handlethread_dict["HandleThread_handle_queue_size"] = (int64_t)handlestatus.handle_queue_size; } dict["handle_threads"].push_back(handlethread_dict); } // service std::vector<ServiceRegister::ServiceStat> services = ServiceRegister::instance()->GetAllServiceStat(); dict["serivcesNum"] = services.size(); for (size_t i = 0; i < services.size(); ++i) { cpptempl::auto_data service_dict; service_dict["serviceName"] = services[i].name; service_dict["callTimes"] = (int64_t)services[i].call_times; service_dict["failedTimes"] = (int64_t)services[i].failed_times; service_dict["successTimes"] = (int64_t)services[i].success_times; for (int index = 0; index < 11; index++) { char time_name[5] = {"\0"}; snprintf(time_name, sizeof(time_name), "L%d", index); service_dict[std::string(time_name)] = services[i].spendTime[index]; } dict["services"].push_back(service_dict); } FILE* file = fopen("../static/stat.html", "r"); if (file == NULL) { printf("can't open file\n"); } static std::string fileconent = ""; static time_t lastReloadTime = time(NULL); bool reloadFile = true; if (fileconent.length() > 0) { // 已经有内容了 time_t now = time(NULL); if (now - lastReloadTime < 60) { // 一分钟重新加载一次 reloadFile = false; } } if (reloadFile) { lastReloadTime = time(NULL); char buf[5000] = {'\0'}; int readNum = fread(buf, 1, 5000, file); fileconent = std::string(buf, readNum); } std::string body = cpptempl::parse(fileconent, dict); response->SetBody(body.c_str(), body.size()); } void ServerStatProcessor::index(sails::net::HttpRequest*, sails::net::HttpResponse* response) { response->SetBody("saf index"); } Monitor::Monitor(sails::Server* server, int port) { thread = NULL; status = Monitor::STOPING; isTerminate = false; this->server = server; this->port = port; } Monitor::~Monitor() { if (processor != NULL) { delete processor; processor = NULL; } if (thread != NULL) { Terminate(); Join(); } if (http_server != NULL) { delete http_server; http_server = NULL; } } void Monitor::Run() { isTerminate = false; thread = new std::thread(Start, this); status = Monitor::RUNING; } void Monitor::Terminate() { http_server->Stop(); isTerminate = true; } void Monitor::Join() { if (thread != NULL) { thread->join(); status = Monitor::STOPING; delete thread; thread = NULL; } } void Monitor::Start(Monitor* monitor) { monitor->http_server = new sails::net::HttpServer(); monitor->http_server->Init(monitor->port, 1, 10, 1); monitor->http_server->SetStaticResourcePath(std::string("../static/")); // 请求处理器与url映射 monitor->processor = new ServerStatProcessor(monitor->server); HTTPBIND(monitor->http_server, "/stat", monitor->processor, ServerStatProcessor::serverstat); HTTPBIND(monitor->http_server, "/", monitor->processor, ServerStatProcessor::index); while (!monitor->isTerminate) { sleep(1); } } } // namespace sails <|endoftext|>
<commit_before>// Copyright 2015 Toggl Desktop developers. #include "../src/netconf.h" #include <string> #include <sstream> #include "./https_client.h" #include "Poco/Environment.h" #include "Poco/Logger.h" #include "Poco/Net/HTTPCredentials.h" #include "Poco/Net/HTTPSClientSession.h" #include "Poco/URI.h" #include "Poco/UnicodeConverter.h" #ifdef __MACH__ #include <CoreFoundation/CoreFoundation.h> // NOLINT #include <CoreServices/CoreServices.h> // NOLINT #endif #ifdef _WIN32 #include <winhttp.h> #pragma comment(lib, "winhttp") #endif #ifdef __linux__ #include <sys/types.h> #include <sys/wait.h> #include <spawn.h> #endif namespace toggl { error Netconf::autodetectProxy( const std::string encoded_url, std::vector<std::string> *proxy_strings) { poco_assert(proxy_strings); proxy_strings->clear(); if (encoded_url.empty()) { return noError; } #ifdef _WIN32 WINHTTP_CURRENT_USER_IE_PROXY_CONFIG ie_config = { 0 }; if (!WinHttpGetIEProxyConfigForCurrentUser(&ie_config)) { std::stringstream ss; ss << "WinHttpGetIEProxyConfigForCurrentUser error: " << GetLastError(); return ss.str(); } if (ie_config.lpszProxy) { std::wstring proxy_url_wide(ie_config.lpszProxy); std::string s(""); Poco::UnicodeConverter::toUTF8(proxy_url_wide, s); proxy_strings->push_back(s); } #endif // Inspired by VLC source code // https://github.com/videolan/vlc/blob/master/src/darwin/netconf.c #ifdef __MACH__ CFDictionaryRef dicRef = CFNetworkCopySystemProxySettings(); if (NULL != dicRef) { const CFStringRef proxyCFstr = (const CFStringRef)CFDictionaryGetValue( dicRef, (const void*)kCFNetworkProxiesHTTPProxy); const CFNumberRef portCFnum = (const CFNumberRef)CFDictionaryGetValue( dicRef, (const void*)kCFNetworkProxiesHTTPPort); if (NULL != proxyCFstr && NULL != portCFnum) { int port = 0; if (!CFNumberGetValue(portCFnum, kCFNumberIntType, &port)) { CFRelease(dicRef); return noError; } const std::size_t kBufsize(4096); char host_buffer[kBufsize]; memset(host_buffer, 0, sizeof(host_buffer)); if (CFStringGetCString(proxyCFstr, host_buffer, sizeof(host_buffer) - 1, kCFStringEncodingUTF8)) { char buffer[kBufsize]; snprintf(buffer, kBufsize, "%s:%d", host_buffer, port); proxy_strings->push_back(std::string(buffer)); } } CFRelease(dicRef); } #endif // Inspired by VLC source code // https://github.com/videolan/vlc/blob/master/src/posix/netconf.c #ifdef __linux__ posix_spawn_file_actions_t actions; posix_spawn_file_actions_init(&actions); posix_spawn_file_actions_addopen(&actions, STDIN_FILENO, "/dev/null", O_RDONLY, 0644); int fd[2]; posix_spawn_file_actions_adddup2(&actions, fd[1], STDOUT_FILENO); posix_spawnattr_t attr; posix_spawnattr_init(&attr); { sigset_t set; sigemptyset(&set); posix_spawnattr_setsigmask(&attr, &set); sigaddset(&set, SIGPIPE); posix_spawnattr_setsigdefault(&attr, &set); posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK); } pid_t pid; char *argv[3] = { const_cast<char *>("proxy"), const_cast<char *>(encoded_url.c_str()), NULL }; if (posix_spawnp(&pid, "proxy", &actions, &attr, argv, environ)) { pid = -1; } posix_spawnattr_destroy(&attr); posix_spawn_file_actions_destroy(&actions); close(fd[1]); if (-1 == pid) { close(fd[0]); return error("Failed to run proxy command"); } char buf[1024]; size_t len = 0; do { ssize_t val = read(fd[0], buf + len, sizeof (buf) - len); if (val <= 0) { break; } len += val; } while (len < sizeof (buf)); close(fd[0]); while (true) { int status = {0}; if (-1 != waitpid(pid, &status, 0)) { break; } } if (len >= 9 && !strncasecmp(buf, "direct://", 9)) { return noError; } char *end = <char *>(memchr(buf, '\n', len)); if (end != NULL) { *end = '\0'; proxy_strings->push_back(std::string(buf)); } #endif return noError; } error Netconf::ConfigureProxy( const std::string encoded_url, Poco::Net::HTTPSClientSession *session) { Poco::Logger &logger = Poco::Logger::get("ConfigureProxy"); std::string proxy_url(""); if (HTTPSClient::Config.AutodetectProxy) { if (Poco::Environment::has("HTTPS_PROXY")) { proxy_url = Poco::Environment::get("HTTPS_PROXY"); } if (Poco::Environment::has("https_proxy")) { proxy_url = Poco::Environment::get("https_proxy"); } if (Poco::Environment::has("HTTP_PROXY")) { proxy_url = Poco::Environment::get("HTTP_PROXY"); } if (Poco::Environment::has("http_proxy")) { proxy_url = Poco::Environment::get("http_proxy"); } if (proxy_url.empty()) { std::vector<std::string> proxy_strings; error err = autodetectProxy(encoded_url, &proxy_strings); if (err != noError) { return err; } if (!proxy_strings.empty()) { proxy_url = proxy_strings[0]; } } if (!proxy_url.empty()) { if (proxy_url.find("://") == std::string::npos) { proxy_url = "http://" + proxy_url; } Poco::URI proxy_uri(proxy_url); std::stringstream ss; ss << "Using proxy URI=" + proxy_uri.toString() << " host=" << proxy_uri.getHost() << " port=" << proxy_uri.getPort(); logger.debug(ss.str()); session->setProxy( proxy_uri.getHost(), proxy_uri.getPort()); if (!proxy_uri.getUserInfo().empty()) { Poco::Net::HTTPCredentials credentials; credentials.fromUserInfo(proxy_uri.getUserInfo()); session->setProxyCredentials( credentials.getUsername(), credentials.getPassword()); logger.debug("Proxy credentials detected username=" + credentials.getUsername()); } } } // Try to use user-configured proxy if (proxy_url.empty() && HTTPSClient::Config.UseProxy && HTTPSClient::Config.ProxySettings.IsConfigured()) { session->setProxy( HTTPSClient::Config.ProxySettings.Host(), static_cast<Poco::UInt16>( HTTPSClient::Config.ProxySettings.Port())); std::stringstream ss; ss << "Proxy configured " << " host=" << HTTPSClient::Config.ProxySettings.Host() << " port=" << HTTPSClient::Config.ProxySettings.Port(); logger.debug(ss.str()); if (HTTPSClient::Config.ProxySettings.HasCredentials()) { session->setProxyCredentials( HTTPSClient::Config.ProxySettings.Username(), HTTPSClient::Config.ProxySettings.Password()); logger.debug("Proxy credentials configured username=" + HTTPSClient::Config.ProxySettings.Username()); } } return noError; } } // namespace toggl <commit_msg>fix build (linux)<commit_after>// Copyright 2015 Toggl Desktop developers. #include "../src/netconf.h" #include <string> #include <sstream> #include "./https_client.h" #include "Poco/Environment.h" #include "Poco/Logger.h" #include "Poco/Net/HTTPCredentials.h" #include "Poco/Net/HTTPSClientSession.h" #include "Poco/URI.h" #include "Poco/UnicodeConverter.h" #ifdef __MACH__ #include <CoreFoundation/CoreFoundation.h> // NOLINT #include <CoreServices/CoreServices.h> // NOLINT #endif #ifdef _WIN32 #include <winhttp.h> #pragma comment(lib, "winhttp") #endif #ifdef __linux__ #include <sys/types.h> #include <sys/wait.h> #include <spawn.h> #endif namespace toggl { error Netconf::autodetectProxy( const std::string encoded_url, std::vector<std::string> *proxy_strings) { poco_assert(proxy_strings); proxy_strings->clear(); if (encoded_url.empty()) { return noError; } #ifdef _WIN32 WINHTTP_CURRENT_USER_IE_PROXY_CONFIG ie_config = { 0 }; if (!WinHttpGetIEProxyConfigForCurrentUser(&ie_config)) { std::stringstream ss; ss << "WinHttpGetIEProxyConfigForCurrentUser error: " << GetLastError(); return ss.str(); } if (ie_config.lpszProxy) { std::wstring proxy_url_wide(ie_config.lpszProxy); std::string s(""); Poco::UnicodeConverter::toUTF8(proxy_url_wide, s); proxy_strings->push_back(s); } #endif // Inspired by VLC source code // https://github.com/videolan/vlc/blob/master/src/darwin/netconf.c #ifdef __MACH__ CFDictionaryRef dicRef = CFNetworkCopySystemProxySettings(); if (NULL != dicRef) { const CFStringRef proxyCFstr = (const CFStringRef)CFDictionaryGetValue( dicRef, (const void*)kCFNetworkProxiesHTTPProxy); const CFNumberRef portCFnum = (const CFNumberRef)CFDictionaryGetValue( dicRef, (const void*)kCFNetworkProxiesHTTPPort); if (NULL != proxyCFstr && NULL != portCFnum) { int port = 0; if (!CFNumberGetValue(portCFnum, kCFNumberIntType, &port)) { CFRelease(dicRef); return noError; } const std::size_t kBufsize(4096); char host_buffer[kBufsize]; memset(host_buffer, 0, sizeof(host_buffer)); if (CFStringGetCString(proxyCFstr, host_buffer, sizeof(host_buffer) - 1, kCFStringEncodingUTF8)) { char buffer[kBufsize]; snprintf(buffer, kBufsize, "%s:%d", host_buffer, port); proxy_strings->push_back(std::string(buffer)); } } CFRelease(dicRef); } #endif // Inspired by VLC source code // https://github.com/videolan/vlc/blob/master/src/posix/netconf.c #ifdef __linux__ posix_spawn_file_actions_t actions; posix_spawn_file_actions_init(&actions); posix_spawn_file_actions_addopen(&actions, STDIN_FILENO, "/dev/null", O_RDONLY, 0644); int fd[2]; posix_spawn_file_actions_adddup2(&actions, fd[1], STDOUT_FILENO); posix_spawnattr_t attr; posix_spawnattr_init(&attr); { sigset_t set; sigemptyset(&set); posix_spawnattr_setsigmask(&attr, &set); sigaddset(&set, SIGPIPE); posix_spawnattr_setsigdefault(&attr, &set); posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK); } pid_t pid; char *argv[3] = { const_cast<char *>("proxy"), const_cast<char *>(encoded_url.c_str()), NULL }; if (posix_spawnp(&pid, "proxy", &actions, &attr, argv, environ)) { pid = -1; } posix_spawnattr_destroy(&attr); posix_spawn_file_actions_destroy(&actions); close(fd[1]); if (-1 == pid) { close(fd[0]); return error("Failed to run proxy command"); } char buf[1024]; size_t len = 0; do { ssize_t val = read(fd[0], buf + len, sizeof (buf) - len); if (val <= 0) { break; } len += val; } while (len < sizeof (buf)); close(fd[0]); while (true) { int status = {0}; if (-1 != waitpid(pid, &status, 0)) { break; } } if (len >= 9 && !strncasecmp(buf, "direct://", 9)) { return noError; } char *end = static_cast<char *>(memchr(buf, '\n', len)); if (end != NULL) { *end = '\0'; proxy_strings->push_back(std::string(buf)); } #endif return noError; } error Netconf::ConfigureProxy( const std::string encoded_url, Poco::Net::HTTPSClientSession *session) { Poco::Logger &logger = Poco::Logger::get("ConfigureProxy"); std::string proxy_url(""); if (HTTPSClient::Config.AutodetectProxy) { if (Poco::Environment::has("HTTPS_PROXY")) { proxy_url = Poco::Environment::get("HTTPS_PROXY"); } if (Poco::Environment::has("https_proxy")) { proxy_url = Poco::Environment::get("https_proxy"); } if (Poco::Environment::has("HTTP_PROXY")) { proxy_url = Poco::Environment::get("HTTP_PROXY"); } if (Poco::Environment::has("http_proxy")) { proxy_url = Poco::Environment::get("http_proxy"); } if (proxy_url.empty()) { std::vector<std::string> proxy_strings; error err = autodetectProxy(encoded_url, &proxy_strings); if (err != noError) { return err; } if (!proxy_strings.empty()) { proxy_url = proxy_strings[0]; } } if (!proxy_url.empty()) { if (proxy_url.find("://") == std::string::npos) { proxy_url = "http://" + proxy_url; } Poco::URI proxy_uri(proxy_url); std::stringstream ss; ss << "Using proxy URI=" + proxy_uri.toString() << " host=" << proxy_uri.getHost() << " port=" << proxy_uri.getPort(); logger.debug(ss.str()); session->setProxy( proxy_uri.getHost(), proxy_uri.getPort()); if (!proxy_uri.getUserInfo().empty()) { Poco::Net::HTTPCredentials credentials; credentials.fromUserInfo(proxy_uri.getUserInfo()); session->setProxyCredentials( credentials.getUsername(), credentials.getPassword()); logger.debug("Proxy credentials detected username=" + credentials.getUsername()); } } } // Try to use user-configured proxy if (proxy_url.empty() && HTTPSClient::Config.UseProxy && HTTPSClient::Config.ProxySettings.IsConfigured()) { session->setProxy( HTTPSClient::Config.ProxySettings.Host(), static_cast<Poco::UInt16>( HTTPSClient::Config.ProxySettings.Port())); std::stringstream ss; ss << "Proxy configured " << " host=" << HTTPSClient::Config.ProxySettings.Host() << " port=" << HTTPSClient::Config.ProxySettings.Port(); logger.debug(ss.str()); if (HTTPSClient::Config.ProxySettings.HasCredentials()) { session->setProxyCredentials( HTTPSClient::Config.ProxySettings.Username(), HTTPSClient::Config.ProxySettings.Password()); logger.debug("Proxy credentials configured username=" + HTTPSClient::Config.ProxySettings.Username()); } } return noError; } } // namespace toggl <|endoftext|>
<commit_before>#include <cstdio> #include <cmath> #include <cstring> #include <iostream> #include <algorithm> #include <set> #include <vector> #include <sstream> #include <typeinfo> using namespace std; class ${ClassName} { public: ${Method.ReturnType} ${Method.Name}(${Method.Params}) { return ${Method.ReturnType;ZeroValue}; } }; ${CutBegin} ${<TestCode} ${CutEnd} <commit_msg>added ctime header for clock() and CLOCKS_PER_SEC<commit_after>#include <cstdio> #include <cmath> #include <cstring> #include <ctime> #include <iostream> #include <algorithm> #include <set> #include <vector> #include <sstream> #include <typeinfo> using namespace std; class ${ClassName} { public: ${Method.ReturnType} ${Method.Name}(${Method.Params}) { return ${Method.ReturnType;ZeroValue}; } }; ${CutBegin} ${<TestCode} ${CutEnd} <|endoftext|>
<commit_before>/* * Copyright © 2012 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "brw_fs.h" #include "brw_cfg.h" /** @file brw_fs_cse.cpp * * Support for local common subexpression elimination. * * See Muchnick's Advanced Compiler Design and Implementation, section * 13.1 (p378). */ using namespace brw; namespace { struct aeb_entry : public exec_node { /** The instruction that generates the expression value. */ fs_inst *generator; /** The temporary where the value is stored. */ fs_reg tmp; }; } static bool is_expression(const fs_visitor *v, const fs_inst *const inst) { switch (inst->opcode) { case BRW_OPCODE_MOV: case BRW_OPCODE_SEL: case BRW_OPCODE_NOT: case BRW_OPCODE_AND: case BRW_OPCODE_OR: case BRW_OPCODE_XOR: case BRW_OPCODE_SHR: case BRW_OPCODE_SHL: case BRW_OPCODE_ASR: case BRW_OPCODE_CMP: case BRW_OPCODE_CMPN: case BRW_OPCODE_ADD: case BRW_OPCODE_MUL: case SHADER_OPCODE_MULH: case BRW_OPCODE_FRC: case BRW_OPCODE_RNDU: case BRW_OPCODE_RNDD: case BRW_OPCODE_RNDE: case BRW_OPCODE_RNDZ: case BRW_OPCODE_LINE: case BRW_OPCODE_PLN: case BRW_OPCODE_MAD: case BRW_OPCODE_LRP: case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD: case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_GEN7: case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD: case FS_OPCODE_CINTERP: case FS_OPCODE_LINTERP: case SHADER_OPCODE_FIND_LIVE_CHANNEL: case SHADER_OPCODE_BROADCAST: case SHADER_OPCODE_MOV_INDIRECT: return true; case SHADER_OPCODE_RCP: case SHADER_OPCODE_RSQ: case SHADER_OPCODE_SQRT: case SHADER_OPCODE_EXP2: case SHADER_OPCODE_LOG2: case SHADER_OPCODE_POW: case SHADER_OPCODE_INT_QUOTIENT: case SHADER_OPCODE_INT_REMAINDER: case SHADER_OPCODE_SIN: case SHADER_OPCODE_COS: return inst->mlen < 2; case SHADER_OPCODE_LOAD_PAYLOAD: return !inst->is_copy_payload(v->alloc); default: return inst->is_send_from_grf() && !inst->has_side_effects() && !inst->is_volatile(); } } static bool operands_match(const fs_inst *a, const fs_inst *b, bool *negate) { fs_reg *xs = a->src; fs_reg *ys = b->src; if (a->opcode == BRW_OPCODE_MAD) { return xs[0].equals(ys[0]) && ((xs[1].equals(ys[1]) && xs[2].equals(ys[2])) || (xs[2].equals(ys[1]) && xs[1].equals(ys[2]))); } else if (a->opcode == BRW_OPCODE_MUL && a->dst.type == BRW_REGISTER_TYPE_F) { bool xs0_negate = xs[0].negate; bool xs1_negate = xs[1].file == IMM ? xs[1].f < 0.0f : xs[1].negate; bool ys0_negate = ys[0].negate; bool ys1_negate = ys[1].file == IMM ? ys[1].f < 0.0f : ys[1].negate; float xs1_imm = xs[1].f; float ys1_imm = ys[1].f; xs[0].negate = false; xs[1].negate = false; ys[0].negate = false; ys[1].negate = false; xs[1].f = fabsf(xs[1].f); ys[1].f = fabsf(ys[1].f); bool ret = (xs[0].equals(ys[0]) && xs[1].equals(ys[1])) || (xs[1].equals(ys[0]) && xs[0].equals(ys[1])); xs[0].negate = xs0_negate; xs[1].negate = xs[1].file == IMM ? false : xs1_negate; ys[0].negate = ys0_negate; ys[1].negate = ys[1].file == IMM ? false : ys1_negate; xs[1].f = xs1_imm; ys[1].f = ys1_imm; *negate = (xs0_negate != xs1_negate) != (ys0_negate != ys1_negate); return ret; } else if (!a->is_commutative()) { bool match = true; for (int i = 0; i < a->sources; i++) { if (!xs[i].equals(ys[i])) { match = false; break; } } return match; } else { return (xs[0].equals(ys[0]) && xs[1].equals(ys[1])) || (xs[1].equals(ys[0]) && xs[0].equals(ys[1])); } } static bool instructions_match(fs_inst *a, fs_inst *b, bool *negate) { return a->opcode == b->opcode && a->force_writemask_all == b->force_writemask_all && a->exec_size == b->exec_size && a->force_sechalf == b->force_sechalf && a->saturate == b->saturate && a->predicate == b->predicate && a->predicate_inverse == b->predicate_inverse && a->conditional_mod == b->conditional_mod && a->flag_subreg == b->flag_subreg && a->dst.type == b->dst.type && a->offset == b->offset && a->mlen == b->mlen && a->regs_written == b->regs_written && a->base_mrf == b->base_mrf && a->eot == b->eot && a->header_size == b->header_size && a->shadow_compare == b->shadow_compare && a->pi_noperspective == b->pi_noperspective && a->sources == b->sources && operands_match(a, b, negate); } static void create_copy_instr(const fs_builder &bld, fs_inst *inst, fs_reg src, bool negate) { int written = inst->regs_written; int dst_width = inst->exec_size / 8; fs_inst *copy; if (written > dst_width) { fs_reg *payload; int sources, header_size; if (inst->opcode == SHADER_OPCODE_LOAD_PAYLOAD) { sources = inst->sources; header_size = inst->header_size; } else { assert(written % dst_width == 0); sources = written / dst_width; header_size = 0; } assert(src.file == VGRF); payload = ralloc_array(bld.shader->mem_ctx, fs_reg, sources); for (int i = 0; i < header_size; i++) { payload[i] = src; src.reg_offset++; } for (int i = header_size; i < sources; i++) { payload[i] = src; src = offset(src, bld, 1); } copy = bld.LOAD_PAYLOAD(inst->dst, payload, sources, header_size); } else { copy = bld.MOV(inst->dst, src); copy->src[0].negate = negate; } assert(copy->regs_written == written); } bool fs_visitor::opt_cse_local(bblock_t *block) { bool progress = false; exec_list aeb; void *cse_ctx = ralloc_context(NULL); int ip = block->start_ip; foreach_inst_in_block(fs_inst, inst, block) { /* Skip some cases. */ if (is_expression(this, inst) && !inst->is_partial_write() && ((inst->dst.file != ARF && inst->dst.file != FIXED_GRF) || inst->dst.is_null())) { bool found = false; bool negate = false; foreach_in_list_use_after(aeb_entry, entry, &aeb) { /* Match current instruction's expression against those in AEB. */ if (!(entry->generator->dst.is_null() && !inst->dst.is_null()) && instructions_match(inst, entry->generator, &negate)) { found = true; progress = true; break; } } if (!found) { if (inst->opcode != BRW_OPCODE_MOV || (inst->opcode == BRW_OPCODE_MOV && inst->src[0].file == IMM && inst->src[0].type == BRW_REGISTER_TYPE_VF)) { /* Our first sighting of this expression. Create an entry. */ aeb_entry *entry = ralloc(cse_ctx, aeb_entry); entry->tmp = reg_undef; entry->generator = inst; aeb.push_tail(entry); } } else { /* This is at least our second sighting of this expression. * If we don't have a temporary already, make one. */ bool no_existing_temp = entry->tmp.file == BAD_FILE; if (no_existing_temp && !entry->generator->dst.is_null()) { const fs_builder ibld = fs_builder(this, block, entry->generator) .at(block, entry->generator->next); int written = entry->generator->regs_written; entry->tmp = fs_reg(VGRF, alloc.allocate(written), entry->generator->dst.type); create_copy_instr(ibld, entry->generator, entry->tmp, false); entry->generator->dst = entry->tmp; } /* dest <- temp */ if (!inst->dst.is_null()) { assert(inst->regs_written == entry->generator->regs_written); assert(inst->dst.type == entry->tmp.type); const fs_builder ibld(this, block, inst); create_copy_instr(ibld, inst, entry->tmp, negate); } /* Set our iterator so that next time through the loop inst->next * will get the instruction in the basic block after the one we've * removed. */ fs_inst *prev = (fs_inst *)inst->prev; inst->remove(block); inst = prev; } } foreach_in_list_safe(aeb_entry, entry, &aeb) { /* Kill all AEB entries that write a different value to or read from * the flag register if we just wrote it. */ if (inst->writes_flag()) { bool negate; /* dummy */ if (entry->generator->reads_flag() || (entry->generator->writes_flag() && !instructions_match(inst, entry->generator, &negate))) { entry->remove(); ralloc_free(entry); continue; } } for (int i = 0; i < entry->generator->sources; i++) { fs_reg *src_reg = &entry->generator->src[i]; /* Kill all AEB entries that use the destination we just * overwrote. */ if (inst->overwrites_reg(entry->generator->src[i])) { entry->remove(); ralloc_free(entry); break; } /* Kill any AEB entries using registers that don't get reused any * more -- a sure sign they'll fail operands_match(). */ if (src_reg->file == VGRF && virtual_grf_end[src_reg->nr] < ip) { entry->remove(); ralloc_free(entry); break; } } } ip++; } ralloc_free(cse_ctx); return progress; } bool fs_visitor::opt_cse() { bool progress = false; calculate_live_intervals(); foreach_block (block, cfg) { progress = opt_cse_local(block) || progress; } if (progress) invalidate_live_intervals(); return progress; } <commit_msg>i965/fs: respect force_sechalf/force_writemask_all in CSE<commit_after>/* * Copyright © 2012 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "brw_fs.h" #include "brw_cfg.h" /** @file brw_fs_cse.cpp * * Support for local common subexpression elimination. * * See Muchnick's Advanced Compiler Design and Implementation, section * 13.1 (p378). */ using namespace brw; namespace { struct aeb_entry : public exec_node { /** The instruction that generates the expression value. */ fs_inst *generator; /** The temporary where the value is stored. */ fs_reg tmp; }; } static bool is_expression(const fs_visitor *v, const fs_inst *const inst) { switch (inst->opcode) { case BRW_OPCODE_MOV: case BRW_OPCODE_SEL: case BRW_OPCODE_NOT: case BRW_OPCODE_AND: case BRW_OPCODE_OR: case BRW_OPCODE_XOR: case BRW_OPCODE_SHR: case BRW_OPCODE_SHL: case BRW_OPCODE_ASR: case BRW_OPCODE_CMP: case BRW_OPCODE_CMPN: case BRW_OPCODE_ADD: case BRW_OPCODE_MUL: case SHADER_OPCODE_MULH: case BRW_OPCODE_FRC: case BRW_OPCODE_RNDU: case BRW_OPCODE_RNDD: case BRW_OPCODE_RNDE: case BRW_OPCODE_RNDZ: case BRW_OPCODE_LINE: case BRW_OPCODE_PLN: case BRW_OPCODE_MAD: case BRW_OPCODE_LRP: case FS_OPCODE_UNIFORM_PULL_CONSTANT_LOAD: case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD_GEN7: case FS_OPCODE_VARYING_PULL_CONSTANT_LOAD: case FS_OPCODE_CINTERP: case FS_OPCODE_LINTERP: case SHADER_OPCODE_FIND_LIVE_CHANNEL: case SHADER_OPCODE_BROADCAST: case SHADER_OPCODE_MOV_INDIRECT: return true; case SHADER_OPCODE_RCP: case SHADER_OPCODE_RSQ: case SHADER_OPCODE_SQRT: case SHADER_OPCODE_EXP2: case SHADER_OPCODE_LOG2: case SHADER_OPCODE_POW: case SHADER_OPCODE_INT_QUOTIENT: case SHADER_OPCODE_INT_REMAINDER: case SHADER_OPCODE_SIN: case SHADER_OPCODE_COS: return inst->mlen < 2; case SHADER_OPCODE_LOAD_PAYLOAD: return !inst->is_copy_payload(v->alloc); default: return inst->is_send_from_grf() && !inst->has_side_effects() && !inst->is_volatile(); } } static bool operands_match(const fs_inst *a, const fs_inst *b, bool *negate) { fs_reg *xs = a->src; fs_reg *ys = b->src; if (a->opcode == BRW_OPCODE_MAD) { return xs[0].equals(ys[0]) && ((xs[1].equals(ys[1]) && xs[2].equals(ys[2])) || (xs[2].equals(ys[1]) && xs[1].equals(ys[2]))); } else if (a->opcode == BRW_OPCODE_MUL && a->dst.type == BRW_REGISTER_TYPE_F) { bool xs0_negate = xs[0].negate; bool xs1_negate = xs[1].file == IMM ? xs[1].f < 0.0f : xs[1].negate; bool ys0_negate = ys[0].negate; bool ys1_negate = ys[1].file == IMM ? ys[1].f < 0.0f : ys[1].negate; float xs1_imm = xs[1].f; float ys1_imm = ys[1].f; xs[0].negate = false; xs[1].negate = false; ys[0].negate = false; ys[1].negate = false; xs[1].f = fabsf(xs[1].f); ys[1].f = fabsf(ys[1].f); bool ret = (xs[0].equals(ys[0]) && xs[1].equals(ys[1])) || (xs[1].equals(ys[0]) && xs[0].equals(ys[1])); xs[0].negate = xs0_negate; xs[1].negate = xs[1].file == IMM ? false : xs1_negate; ys[0].negate = ys0_negate; ys[1].negate = ys[1].file == IMM ? false : ys1_negate; xs[1].f = xs1_imm; ys[1].f = ys1_imm; *negate = (xs0_negate != xs1_negate) != (ys0_negate != ys1_negate); return ret; } else if (!a->is_commutative()) { bool match = true; for (int i = 0; i < a->sources; i++) { if (!xs[i].equals(ys[i])) { match = false; break; } } return match; } else { return (xs[0].equals(ys[0]) && xs[1].equals(ys[1])) || (xs[1].equals(ys[0]) && xs[0].equals(ys[1])); } } static bool instructions_match(fs_inst *a, fs_inst *b, bool *negate) { return a->opcode == b->opcode && a->force_writemask_all == b->force_writemask_all && a->exec_size == b->exec_size && a->force_sechalf == b->force_sechalf && a->saturate == b->saturate && a->predicate == b->predicate && a->predicate_inverse == b->predicate_inverse && a->conditional_mod == b->conditional_mod && a->flag_subreg == b->flag_subreg && a->dst.type == b->dst.type && a->offset == b->offset && a->mlen == b->mlen && a->regs_written == b->regs_written && a->base_mrf == b->base_mrf && a->eot == b->eot && a->header_size == b->header_size && a->shadow_compare == b->shadow_compare && a->pi_noperspective == b->pi_noperspective && a->sources == b->sources && operands_match(a, b, negate); } static void create_copy_instr(const fs_builder &bld, fs_inst *inst, fs_reg src, bool negate) { int written = inst->regs_written; int dst_width = inst->exec_size / 8; fs_inst *copy; if (written > dst_width) { fs_reg *payload; int sources, header_size; if (inst->opcode == SHADER_OPCODE_LOAD_PAYLOAD) { sources = inst->sources; header_size = inst->header_size; } else { assert(written % dst_width == 0); sources = written / dst_width; header_size = 0; } assert(src.file == VGRF); payload = ralloc_array(bld.shader->mem_ctx, fs_reg, sources); for (int i = 0; i < header_size; i++) { payload[i] = src; src.reg_offset++; } for (int i = header_size; i < sources; i++) { payload[i] = src; src = offset(src, bld, 1); } copy = bld.LOAD_PAYLOAD(inst->dst, payload, sources, header_size); } else { copy = bld.MOV(inst->dst, src); copy->force_sechalf = inst->force_sechalf; copy->force_writemask_all = inst->force_writemask_all; copy->src[0].negate = negate; } assert(copy->regs_written == written); } bool fs_visitor::opt_cse_local(bblock_t *block) { bool progress = false; exec_list aeb; void *cse_ctx = ralloc_context(NULL); int ip = block->start_ip; foreach_inst_in_block(fs_inst, inst, block) { /* Skip some cases. */ if (is_expression(this, inst) && !inst->is_partial_write() && ((inst->dst.file != ARF && inst->dst.file != FIXED_GRF) || inst->dst.is_null())) { bool found = false; bool negate = false; foreach_in_list_use_after(aeb_entry, entry, &aeb) { /* Match current instruction's expression against those in AEB. */ if (!(entry->generator->dst.is_null() && !inst->dst.is_null()) && instructions_match(inst, entry->generator, &negate)) { found = true; progress = true; break; } } if (!found) { if (inst->opcode != BRW_OPCODE_MOV || (inst->opcode == BRW_OPCODE_MOV && inst->src[0].file == IMM && inst->src[0].type == BRW_REGISTER_TYPE_VF)) { /* Our first sighting of this expression. Create an entry. */ aeb_entry *entry = ralloc(cse_ctx, aeb_entry); entry->tmp = reg_undef; entry->generator = inst; aeb.push_tail(entry); } } else { /* This is at least our second sighting of this expression. * If we don't have a temporary already, make one. */ bool no_existing_temp = entry->tmp.file == BAD_FILE; if (no_existing_temp && !entry->generator->dst.is_null()) { const fs_builder ibld = fs_builder(this, block, entry->generator) .at(block, entry->generator->next); int written = entry->generator->regs_written; entry->tmp = fs_reg(VGRF, alloc.allocate(written), entry->generator->dst.type); create_copy_instr(ibld, entry->generator, entry->tmp, false); entry->generator->dst = entry->tmp; } /* dest <- temp */ if (!inst->dst.is_null()) { assert(inst->regs_written == entry->generator->regs_written); assert(inst->dst.type == entry->tmp.type); const fs_builder ibld(this, block, inst); create_copy_instr(ibld, inst, entry->tmp, negate); } /* Set our iterator so that next time through the loop inst->next * will get the instruction in the basic block after the one we've * removed. */ fs_inst *prev = (fs_inst *)inst->prev; inst->remove(block); inst = prev; } } foreach_in_list_safe(aeb_entry, entry, &aeb) { /* Kill all AEB entries that write a different value to or read from * the flag register if we just wrote it. */ if (inst->writes_flag()) { bool negate; /* dummy */ if (entry->generator->reads_flag() || (entry->generator->writes_flag() && !instructions_match(inst, entry->generator, &negate))) { entry->remove(); ralloc_free(entry); continue; } } for (int i = 0; i < entry->generator->sources; i++) { fs_reg *src_reg = &entry->generator->src[i]; /* Kill all AEB entries that use the destination we just * overwrote. */ if (inst->overwrites_reg(entry->generator->src[i])) { entry->remove(); ralloc_free(entry); break; } /* Kill any AEB entries using registers that don't get reused any * more -- a sure sign they'll fail operands_match(). */ if (src_reg->file == VGRF && virtual_grf_end[src_reg->nr] < ip) { entry->remove(); ralloc_free(entry); break; } } } ip++; } ralloc_free(cse_ctx); return progress; } bool fs_visitor::opt_cse() { bool progress = false; calculate_live_intervals(); foreach_block (block, cfg) { progress = opt_cse_local(block) || progress; } if (progress) invalidate_live_intervals(); return progress; } <|endoftext|>
<commit_before>#ifndef TOML_PARSER #define TOML_PARSER #include "definitions.hpp" #include "exceptions.hpp" #include "line_operation.hpp" #include "toml_values.hpp" #include "parse_to_value.hpp" namespace toml { enum class LineKind { TABLE_TITLE, // (ex) [tablename] ARRAY_OF_TABLE_TITLE, // (ex) [[tablename]] KEY_VALUE, // (ex) key = value UNKNOWN, }; template<typename charT, typename traits, typename alloc> inline std::basic_string<charT, traits, alloc> remove_comment(const std::basic_string<charT, traits, alloc>& line) { return std::basic_string<charT, traits, alloc>(line.cbegin(), std::find(line.cbegin(), line.cend(), '#')); } template<typename charT, typename traits> std::basic_string<charT, traits> read_line(std::basic_istream<charT, traits>& is) { std::basic_string<charT, traits> line; std::getline(is, line); return remove_indent(remove_extraneous_whitespace(remove_comment(line))); } template<typename charT, typename traits, typename alloc> std::basic_istream<charT, traits>& putback_line(std::basic_istream<charT, traits>& is, const std::basic_string<charT, traits, alloc>& line) { for(auto iter = line.crbegin(); iter != line.crend(); ++iter) is.putback(*iter); return is; } template<typename charT, typename traits, typename alloc> LineKind determine_line_kind(const std::basic_string<charT, traits, alloc>& line) { if(line.front() == '[' && line.back() == ']') { if(line.size() >= 4) if(line.at(1) == '[' && line.at(line.size() - 2) == ']') return LineKind::ARRAY_OF_TABLE_TITLE; return LineKind::TABLE_TITLE; } else if(std::count(line.begin(), line.end(), '=') >= 1) { if(line.front() == '=') throw syntax_error("line starts with ="); return LineKind::KEY_VALUE; } else return LineKind::UNKNOWN;// a part of multi-line value? } template<typename charT, typename traits, typename alloc> std::basic_string<charT, traits, alloc> extract_table_title(const std::basic_string<charT, traits, alloc>& line) { if(line.front() == '[' && line.back() == ']') { if(line.size() >= 4) if(line.at(1) == '[' && line.at(line.size() - 2) == ']') return line.substr(2, line.size()-4); return line.substr(1, line.size()-2); } else throw internal_error("not table title line"); } template<typename charT, typename traits, typename alloc> bool is_multi_line_value(const std::basic_string<charT, traits, alloc>& line) { // multi-line string/string-literal, multi-line array. // multi-line inline table(!) is ignored if(count(line, std::basic_string<charT, traits, alloc>("\"\"\"")) == 1) return true; else if(count(line, std::basic_string<charT, traits, alloc>("\'\'\'")) == 1) return true; else if(line.front() == '[') return !is_closed(line, '[', ']'); else return false; } template<typename charT, typename traits, typename alloc> std::pair<std::string, std::shared_ptr<value_base>> parse_key_value(const std::basic_string<charT, traits, alloc>& line, std::basic_istream<charT, traits>& is) { auto equal = std::find(line.begin(), line.end(), '='); std::basic_string<charT, traits, alloc> key(line.cbegin(), equal); key = remove_extraneous_whitespace(key); std::basic_string<charT, traits, alloc> value(equal+1, line.cend()); value = remove_indent(value); while(is_multi_line_value(value)) { if(is.eof()) throw end_of_file("eof"); const auto additional = read_line(is); if(additional.empty()) continue; value += additional; } return std::make_pair(key, parse_value(value)); } template<typename charT, typename traits> std::shared_ptr<value_base> parse_table(std::basic_istream<charT, traits>& is) { std::shared_ptr<value_base> retval(new table_type); std::shared_ptr<table_type> table = std::dynamic_pointer_cast<table_type>(retval); while(!is.eof()) { const std::basic_string<charT, traits> line = read_line(is); if(line.empty()) continue; LineKind kind = determine_line_kind(line); switch(kind) { case LineKind::TABLE_TITLE: { putback_line(is, line); return retval; } case LineKind::ARRAY_OF_TABLE_TITLE: { putback_line(is, line); return retval; } case LineKind::KEY_VALUE: { try { const auto kv = parse_key_value(line, is); table->value[kv.first] = kv.second; } catch(end_of_file& eof){throw syntax_error("sudden eof");} break; } case LineKind::UNKNOWN: throw syntax_error("unknown line: " + line); // XXX! default: throw internal_error("invalid line kind"); } } return retval; } template<typename charT, typename traits> Data parse(std::basic_istream<charT, traits>& is) { Data data; while(!is.eof()) { const std::basic_string<charT, traits> line = read_line(is); if(line.empty()) continue; LineKind kind = determine_line_kind(line); switch(kind) { case LineKind::TABLE_TITLE: { data[extract_table_title(line)] = parse_table(is); break; } case LineKind::ARRAY_OF_TABLE_TITLE: { break; } case LineKind::KEY_VALUE: { try { const auto kv = parse_key_value(line, is); data[kv.first] = kv.second; } catch(end_of_file& eof) { throw syntax_error("sudden eof"); } break; } case LineKind::UNKNOWN: throw syntax_error("unknown line: " + line); default: throw internal_error("invalid line kind"); } } return data; } }//toml #endif /* TOML_PARSER */ <commit_msg>fix putback_line using seekg<commit_after>#ifndef TOML_PARSER #define TOML_PARSER #include "definitions.hpp" #include "exceptions.hpp" #include "line_operation.hpp" #include "toml_values.hpp" #include "parse_value.hpp" namespace toml { enum class LineKind { TABLE_TITLE, // (ex) [tablename] ARRAY_OF_TABLE_TITLE, // (ex) [[tablename]] KEY_VALUE, // (ex) key = value UNKNOWN, }; template<typename charT, typename traits, typename alloc> inline std::basic_string<charT, traits, alloc> remove_comment(const std::basic_string<charT, traits, alloc>& line) { return std::basic_string<charT, traits, alloc>(line.cbegin(), std::find(line.cbegin(), line.cend(), '#')); } template<typename charT, typename traits> std::basic_string<charT, traits> read_line(std::basic_istream<charT, traits>& is) { std::basic_string<charT, traits> line; std::getline(is, line); return remove_indent(remove_extraneous_whitespace(remove_comment(line))); } template<typename charT, typename traits, typename alloc> LineKind determine_line_kind(const std::basic_string<charT, traits, alloc>& line) { if(line.front() == '[' && line.back() == ']') { if(line.size() >= 4) if(line.at(1) == '[' && line.at(line.size() - 2) == ']') return LineKind::ARRAY_OF_TABLE_TITLE; return LineKind::TABLE_TITLE; } else if(std::count(line.begin(), line.end(), '=') >= 1) { if(line.front() == '=') throw syntax_error("line starts with ="); return LineKind::KEY_VALUE; } else return LineKind::UNKNOWN;// a part of multi-line value? } template<typename charT, typename traits, typename alloc> std::basic_string<charT, traits, alloc> extract_table_title(const std::basic_string<charT, traits, alloc>& line) { if(line.front() == '[' && line.back() == ']') { if(line.size() >= 4) if(line.at(1) == '[' && line.at(line.size() - 2) == ']') return line.substr(2, line.size()-4); return line.substr(1, line.size()-2); } else throw internal_error("not table title line"); } template<typename charT, typename traits, typename alloc> bool is_multi_line_value(const std::basic_string<charT, traits, alloc>& line) { // multi-line string/string-literal, multi-line array. // multi-line inline table(!) is ignored if(count(line, std::basic_string<charT, traits, alloc>("\"\"\"")) == 1) return true; else if(count(line, std::basic_string<charT, traits, alloc>("\'\'\'")) == 1) return true; else if(line.front() == '[') return !is_closed(line, '[', ']'); else return false; } template<typename charT, typename traits, typename alloc> std::pair<std::string, std::shared_ptr<value_base>> parse_key_value(const std::basic_string<charT, traits, alloc>& line, std::basic_istream<charT, traits>& is) { auto equal = std::find(line.begin(), line.end(), '='); std::basic_string<charT, traits, alloc> key(line.cbegin(), equal); key = remove_extraneous_whitespace(key); std::basic_string<charT, traits, alloc> value(equal+1, line.cend()); value = remove_indent(value); while(is_multi_line_value(value)) { if(is.eof()) throw end_of_file("eof"); const auto additional = read_line(is); if(additional.empty()) continue; value += additional; } return std::make_pair(key, parse_value(value)); } template<typename charT, typename traits> std::shared_ptr<value_base> parse_table(std::basic_istream<charT, traits>& is) { std::shared_ptr<value_base> retval(new table_type); std::shared_ptr<table_type> table = std::dynamic_pointer_cast<table_type>(retval); while(!is.eof()) { const auto current_pos = is.tellg(); const std::basic_string<charT, traits> line = read_line(is); if(line.empty()) continue; LineKind kind = determine_line_kind(line); switch(kind) { case LineKind::TABLE_TITLE: { is.seekg(current_pos); return retval; } case LineKind::ARRAY_OF_TABLE_TITLE: { is.seekg(current_pos); return retval; } case LineKind::KEY_VALUE: { try { const auto kv = parse_key_value(line, is); table->value[kv.first] = kv.second; } catch(end_of_file& eof){throw syntax_error("sudden eof");} break; } case LineKind::UNKNOWN: throw syntax_error("unknown line: " + line); // XXX! default: throw internal_error("invalid line kind"); } } return retval; } template<typename charT, typename traits> Data parse(std::basic_istream<charT, traits>& is) { Data data; while(!is.eof()) { const std::basic_string<charT, traits> line = read_line(is); if(line.empty()) continue; LineKind kind = determine_line_kind(line); switch(kind) { case LineKind::TABLE_TITLE: { data[extract_table_title(line)] = parse_table(is); break; } case LineKind::ARRAY_OF_TABLE_TITLE: { break; } case LineKind::KEY_VALUE: { try { const auto kv = parse_key_value(line, is); data[kv.first] = kv.second; } catch(end_of_file& eof) { throw syntax_error("sudden eof"); } break; } case LineKind::UNKNOWN: throw syntax_error("unknown line: " + line); default: throw internal_error("invalid line kind"); } } return data; } }//toml #endif /* TOML_PARSER */ <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2012-2015 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 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. * ****************************************************************************/ /** * @file PreflightCheck.cpp * * Preflight check for main system components * * @author Lorenz Meier <[email protected]> * @author Johan Jansen <[email protected]> */ #include <nuttx/config.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <fcntl.h> #include <errno.h> #include <math.h> #include <systemlib/err.h> #include <systemlib/param/param.h> #include <systemlib/rc_check.h> #include <drivers/drv_hrt.h> #include <drivers/drv_mag.h> #include <drivers/drv_gyro.h> #include <drivers/drv_accel.h> #include <drivers/drv_baro.h> #include <drivers/drv_airspeed.h> #include <uORB/topics/airspeed.h> #include <mavlink/mavlink_log.h> #include "PreflightCheck.h" namespace Commander { static bool magnometerCheck(int mavlink_fd, unsigned instance, bool optional) { bool success = true; char s[30]; sprintf(s, "%s%u", MAG_BASE_DEVICE_PATH, instance); int fd = open(s, 0); if (fd < 0) { if (!optional) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: NO MAG SENSOR #%u", instance); } return false; } int calibration_devid; int ret; int devid = ioctl(fd, DEVIOCGDEVICEID, 0); sprintf(s, "CAL_MAG%u_ID", instance); param_get(param_find(s), &(calibration_devid)); if (devid != calibration_devid) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: MAG #%u UNCALIBRATED (NO ID)", instance); success = false; goto out; } ret = ioctl(fd, MAGIOCSELFTEST, 0); if (ret != OK) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: MAG #%u SELFTEST FAILED", instance); success = false; goto out; } out: close(fd); return success; } static bool accelerometerCheck(int mavlink_fd, unsigned instance, bool optional, bool dynamic) { bool success = true; char s[30]; sprintf(s, "%s%u", ACCEL_BASE_DEVICE_PATH, instance); int fd = open(s, O_RDONLY); if (fd < 0) { if (!optional) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: NO ACCEL SENSOR #%u", instance); } return false; } int calibration_devid; int ret; int devid = ioctl(fd, DEVIOCGDEVICEID, 0); sprintf(s, "CAL_ACC%u_ID", instance); param_get(param_find(s), &(calibration_devid)); if (devid != calibration_devid) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: ACCEL #%u UNCALIBRATED (NO ID)", instance); success = false; goto out; } ret = ioctl(fd, ACCELIOCSELFTEST, 0); if (ret != OK) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: ACCEL #%u SELFTEST FAILED", instance); success = false; goto out; } if (dynamic) { /* check measurement result range */ struct accel_report acc; ret = read(fd, &acc, sizeof(acc)); if (ret == sizeof(acc)) { /* evaluate values */ float accel_magnitude = sqrtf(acc.x * acc.x + acc.y * acc.y + acc.z * acc.z); if (accel_magnitude < 4.0f || accel_magnitude > 15.0f /* m/s^2 */) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: ACCEL RANGE, hold still"); /* this is frickin' fatal */ success = false; goto out; } } else { mavlink_log_critical(mavlink_fd, "PREFLIGHT FAIL: ACCEL READ"); /* this is frickin' fatal */ success = false; goto out; } } out: close(fd); return success; } static bool gyroCheck(int mavlink_fd, unsigned instance, bool optional) { bool success = true; char s[30]; sprintf(s, "%s%u", GYRO_BASE_DEVICE_PATH, instance); int fd = open(s, 0); if (fd < 0) { if (!optional) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: NO GYRO SENSOR #%u", instance); } return false; } int calibration_devid; int ret; int devid = ioctl(fd, DEVIOCGDEVICEID, 0); sprintf(s, "CAL_GYRO%u_ID", instance); param_get(param_find(s), &(calibration_devid)); if (devid != calibration_devid) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: GYRO #%u UNCALIBRATED (NO ID)", instance); success = false; goto out; } ret = ioctl(fd, GYROIOCSELFTEST, 0); if (ret != OK) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: GYRO #%u SELFTEST FAILED", instance); success = false; goto out; } out: close(fd); return success; } static bool baroCheck(int mavlink_fd, unsigned instance, bool optional) { bool success = true; char s[30]; sprintf(s, "%s%u", BARO_BASE_DEVICE_PATH, instance); int fd = open(s, 0); if (fd < 0) { if (!optional) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: NO BARO SENSOR #%u", instance); } return false; } close(fd); return success; } static bool airspeedCheck(int mavlink_fd, bool optional) { bool success = true; int ret; int fd = orb_subscribe(ORB_ID(airspeed)); struct airspeed_s airspeed; if ((ret = orb_copy(ORB_ID(airspeed), fd, &airspeed)) || (hrt_elapsed_time(&airspeed.timestamp) > (500 * 1000))) { mavlink_log_critical(mavlink_fd, "PREFLIGHT FAIL: AIRSPEED SENSOR MISSING"); success = false; goto out; } if (fabsf(airspeed.indicated_airspeed_m_s > 6.0f)) { mavlink_log_critical(mavlink_fd, "AIRSPEED WARNING: WIND OR CALIBRATION ISSUE"); // XXX do not make this fatal yet } out: close(fd); return success; } bool preflightCheck(int mavlink_fd, bool checkMag, bool checkAcc, bool checkGyro, bool checkBaro, bool checkAirspeed, bool checkRC, bool checkDynamic) { bool failed = false; /* ---- MAG ---- */ if (checkMag) { /* check all sensors, but fail only for mandatory ones */ for (unsigned i = 0; i < max_optional_mag_count; i++) { bool required = (i < max_mandatory_mag_count); if (!magnometerCheck(mavlink_fd, i, !required) && required) { failed = true; } } } /* ---- ACCEL ---- */ if (checkAcc) { /* check all sensors, but fail only for mandatory ones */ for (unsigned i = 0; i < max_optional_accel_count; i++) { bool required = (i < max_mandatory_accel_count); if (!accelerometerCheck(mavlink_fd, i, !required, checkDynamic) && required) { failed = true; } } } /* ---- GYRO ---- */ if (checkGyro) { /* check all sensors, but fail only for mandatory ones */ for (unsigned i = 0; i < max_optional_gyro_count; i++) { bool required = (i < max_mandatory_gyro_count); if (!gyroCheck(mavlink_fd, i, !required) && required) { failed = true; } } } /* ---- BARO ---- */ if (checkBaro) { /* check all sensors, but fail only for mandatory ones */ for (unsigned i = 0; i < max_optional_baro_count; i++) { bool required = (i < max_mandatory_baro_count); if (!baroCheck(mavlink_fd, i, !required) && required) { failed = true; } } } /* ---- AIRSPEED ---- */ if (checkAirspeed) { if (!airspeedCheck(mavlink_fd, true)) { failed = true; } } /* ---- RC CALIBRATION ---- */ if (checkRC) { if (rc_calibration_check(mavlink_fd) != OK) { failed = true; } } /* Report status */ return !failed; } } <commit_msg>Fixed parenthesis bug<commit_after>/**************************************************************************** * * Copyright (c) 2012-2015 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 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. * ****************************************************************************/ /** * @file PreflightCheck.cpp * * Preflight check for main system components * * @author Lorenz Meier <[email protected]> * @author Johan Jansen <[email protected]> */ #include <px4_config.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <fcntl.h> #include <errno.h> #include <math.h> #include <systemlib/err.h> #include <systemlib/param/param.h> #include <systemlib/rc_check.h> #include <drivers/drv_hrt.h> #include <drivers/drv_mag.h> #include <drivers/drv_gyro.h> #include <drivers/drv_accel.h> #include <drivers/drv_baro.h> #include <drivers/drv_airspeed.h> #include <uORB/topics/airspeed.h> #include <mavlink/mavlink_log.h> #include "PreflightCheck.h" namespace Commander { static bool magnometerCheck(int mavlink_fd, unsigned instance, bool optional) { bool success = true; char s[30]; sprintf(s, "%s%u", MAG_BASE_DEVICE_PATH, instance); int fd = open(s, 0); if (fd < 0) { if (!optional) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: NO MAG SENSOR #%u", instance); } return false; } int calibration_devid; int ret; int devid = ioctl(fd, DEVIOCGDEVICEID, 0); sprintf(s, "CAL_MAG%u_ID", instance); param_get(param_find(s), &(calibration_devid)); if (devid != calibration_devid) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: MAG #%u UNCALIBRATED (NO ID)", instance); success = false; goto out; } ret = ioctl(fd, MAGIOCSELFTEST, 0); if (ret != OK) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: MAG #%u SELFTEST FAILED", instance); success = false; goto out; } out: close(fd); return success; } static bool accelerometerCheck(int mavlink_fd, unsigned instance, bool optional, bool dynamic) { bool success = true; char s[30]; sprintf(s, "%s%u", ACCEL_BASE_DEVICE_PATH, instance); int fd = open(s, O_RDONLY); if (fd < 0) { if (!optional) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: NO ACCEL SENSOR #%u", instance); } return false; } int calibration_devid; int ret; int devid = ioctl(fd, DEVIOCGDEVICEID, 0); sprintf(s, "CAL_ACC%u_ID", instance); param_get(param_find(s), &(calibration_devid)); if (devid != calibration_devid) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: ACCEL #%u UNCALIBRATED (NO ID)", instance); success = false; goto out; } ret = ioctl(fd, ACCELIOCSELFTEST, 0); if (ret != OK) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: ACCEL #%u SELFTEST FAILED", instance); success = false; goto out; } if (dynamic) { /* check measurement result range */ struct accel_report acc; ret = read(fd, &acc, sizeof(acc)); if (ret == sizeof(acc)) { /* evaluate values */ float accel_magnitude = sqrtf(acc.x * acc.x + acc.y * acc.y + acc.z * acc.z); if (accel_magnitude < 4.0f || accel_magnitude > 15.0f /* m/s^2 */) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: ACCEL RANGE, hold still"); /* this is frickin' fatal */ success = false; goto out; } } else { mavlink_log_critical(mavlink_fd, "PREFLIGHT FAIL: ACCEL READ"); /* this is frickin' fatal */ success = false; goto out; } } out: close(fd); return success; } static bool gyroCheck(int mavlink_fd, unsigned instance, bool optional) { bool success = true; char s[30]; sprintf(s, "%s%u", GYRO_BASE_DEVICE_PATH, instance); int fd = open(s, 0); if (fd < 0) { if (!optional) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: NO GYRO SENSOR #%u", instance); } return false; } int calibration_devid; int ret; int devid = ioctl(fd, DEVIOCGDEVICEID, 0); sprintf(s, "CAL_GYRO%u_ID", instance); param_get(param_find(s), &(calibration_devid)); if (devid != calibration_devid) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: GYRO #%u UNCALIBRATED (NO ID)", instance); success = false; goto out; } ret = ioctl(fd, GYROIOCSELFTEST, 0); if (ret != OK) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: GYRO #%u SELFTEST FAILED", instance); success = false; goto out; } out: close(fd); return success; } static bool baroCheck(int mavlink_fd, unsigned instance, bool optional) { bool success = true; char s[30]; sprintf(s, "%s%u", BARO_BASE_DEVICE_PATH, instance); int fd = open(s, 0); if (fd < 0) { if (!optional) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: NO BARO SENSOR #%u", instance); } return false; } close(fd); return success; } static bool airspeedCheck(int mavlink_fd, bool optional) { bool success = true; int ret; int fd = orb_subscribe(ORB_ID(airspeed)); struct airspeed_s airspeed; if ((ret = orb_copy(ORB_ID(airspeed), fd, &airspeed)) || (hrt_elapsed_time(&airspeed.timestamp) > (500 * 1000))) { mavlink_log_critical(mavlink_fd, "PREFLIGHT FAIL: AIRSPEED SENSOR MISSING"); success = false; goto out; } if (fabsf(airspeed.indicated_airspeed_m_s) > 6.0f) { mavlink_log_critical(mavlink_fd, "AIRSPEED WARNING: WIND OR CALIBRATION ISSUE"); // XXX do not make this fatal yet } out: close(fd); return success; } bool preflightCheck(int mavlink_fd, bool checkMag, bool checkAcc, bool checkGyro, bool checkBaro, bool checkAirspeed, bool checkRC, bool checkDynamic) { bool failed = false; /* ---- MAG ---- */ if (checkMag) { /* check all sensors, but fail only for mandatory ones */ for (unsigned i = 0; i < max_optional_mag_count; i++) { bool required = (i < max_mandatory_mag_count); if (!magnometerCheck(mavlink_fd, i, !required) && required) { failed = true; } } } /* ---- ACCEL ---- */ if (checkAcc) { /* check all sensors, but fail only for mandatory ones */ for (unsigned i = 0; i < max_optional_accel_count; i++) { bool required = (i < max_mandatory_accel_count); if (!accelerometerCheck(mavlink_fd, i, !required, checkDynamic) && required) { failed = true; } } } /* ---- GYRO ---- */ if (checkGyro) { /* check all sensors, but fail only for mandatory ones */ for (unsigned i = 0; i < max_optional_gyro_count; i++) { bool required = (i < max_mandatory_gyro_count); if (!gyroCheck(mavlink_fd, i, !required) && required) { failed = true; } } } /* ---- BARO ---- */ if (checkBaro) { /* check all sensors, but fail only for mandatory ones */ for (unsigned i = 0; i < max_optional_baro_count; i++) { bool required = (i < max_mandatory_baro_count); if (!baroCheck(mavlink_fd, i, !required) && required) { failed = true; } } } /* ---- AIRSPEED ---- */ if (checkAirspeed) { if (!airspeedCheck(mavlink_fd, true)) { failed = true; } } /* ---- RC CALIBRATION ---- */ if (checkRC) { if (rc_calibration_check(mavlink_fd) != OK) { failed = true; } } /* Report status */ return !failed; } } <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2012-2015 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 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. * ****************************************************************************/ /** * @file PreflightCheck.cpp * * Preflight check for main system components * * @author Lorenz Meier <[email protected]> * @author Johan Jansen <[email protected]> */ #include <nuttx/config.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <fcntl.h> #include <errno.h> #include <math.h> #include <systemlib/err.h> #include <systemlib/param/param.h> #include <systemlib/rc_check.h> #include <drivers/drv_hrt.h> #include <drivers/drv_mag.h> #include <drivers/drv_gyro.h> #include <drivers/drv_accel.h> #include <drivers/drv_baro.h> #include <drivers/drv_airspeed.h> #include <uORB/topics/airspeed.h> #include <uORB/topics/vehicle_gps_position.h> #include <mavlink/mavlink_log.h> #include "PreflightCheck.h" namespace Commander { static bool magnometerCheck(int mavlink_fd, unsigned instance, bool optional) { bool success = true; char s[30]; sprintf(s, "%s%u", MAG_BASE_DEVICE_PATH, instance); int fd = open(s, 0); if (fd < 0) { if (!optional) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: NO MAG SENSOR #%u", instance); } return false; } int calibration_devid; int ret; int devid = ioctl(fd, DEVIOCGDEVICEID, 0); sprintf(s, "CAL_MAG%u_ID", instance); param_get(param_find(s), &(calibration_devid)); if (devid != calibration_devid) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: MAG #%u UNCALIBRATED", instance); success = false; goto out; } ret = ioctl(fd, MAGIOCSELFTEST, 0); if (ret != OK) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: MAG #%u SELFTEST FAILED", instance); success = false; goto out; } out: close(fd); return success; } static bool accelerometerCheck(int mavlink_fd, unsigned instance, bool optional, bool dynamic) { bool success = true; char s[30]; sprintf(s, "%s%u", ACCEL_BASE_DEVICE_PATH, instance); int fd = open(s, O_RDONLY); if (fd < 0) { if (!optional) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: NO ACCEL SENSOR #%u", instance); } return false; } int calibration_devid; int ret; int devid = ioctl(fd, DEVIOCGDEVICEID, 0); sprintf(s, "CAL_ACC%u_ID", instance); param_get(param_find(s), &(calibration_devid)); if (devid != calibration_devid) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: ACCEL #%u UNCALIBRATED", instance); success = false; goto out; } ret = ioctl(fd, ACCELIOCSELFTEST, 0); if (ret != OK) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: ACCEL #%u SELFTEST FAILED", instance); success = false; goto out; } if (dynamic) { /* check measurement result range */ struct accel_report acc; ret = read(fd, &acc, sizeof(acc)); if (ret == sizeof(acc)) { /* evaluate values */ float accel_magnitude = sqrtf(acc.x * acc.x + acc.y * acc.y + acc.z * acc.z); if (accel_magnitude < 4.0f || accel_magnitude > 15.0f /* m/s^2 */) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: ACCEL RANGE, hold still on arming"); /* this is frickin' fatal */ success = false; goto out; } } else { mavlink_log_critical(mavlink_fd, "PREFLIGHT FAIL: ACCEL READ"); /* this is frickin' fatal */ success = false; goto out; } } out: close(fd); return success; } static bool gyroCheck(int mavlink_fd, unsigned instance, bool optional) { bool success = true; char s[30]; sprintf(s, "%s%u", GYRO_BASE_DEVICE_PATH, instance); int fd = open(s, 0); if (fd < 0) { if (!optional) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: NO GYRO SENSOR #%u", instance); } return false; } int calibration_devid; int ret; int devid = ioctl(fd, DEVIOCGDEVICEID, 0); sprintf(s, "CAL_GYRO%u_ID", instance); param_get(param_find(s), &(calibration_devid)); if (devid != calibration_devid) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: GYRO #%u UNCALIBRATED", instance); success = false; goto out; } ret = ioctl(fd, GYROIOCSELFTEST, 0); if (ret != OK) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: GYRO #%u SELFTEST FAILED", instance); success = false; goto out; } out: close(fd); return success; } static bool baroCheck(int mavlink_fd, unsigned instance, bool optional) { bool success = true; char s[30]; sprintf(s, "%s%u", BARO_BASE_DEVICE_PATH, instance); int fd = open(s, 0); if (fd < 0) { if (!optional) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: NO BARO SENSOR #%u", instance); } return false; } close(fd); return success; } static bool airspeedCheck(int mavlink_fd, bool optional) { bool success = true; int ret; int fd = orb_subscribe(ORB_ID(airspeed)); struct airspeed_s airspeed; if ((ret = orb_copy(ORB_ID(airspeed), fd, &airspeed)) || (hrt_elapsed_time(&airspeed.timestamp) > (500 * 1000))) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: AIRSPEED SENSOR MISSING"); success = false; goto out; } if (fabsf(airspeed.indicated_airspeed_m_s > 6.0f)) { mavlink_and_console_log_critical(mavlink_fd, "AIRSPEED WARNING: WIND OR CALIBRATION ISSUE"); // XXX do not make this fatal yet } out: close(fd); return success; } static bool gnssCheck(int mavlink_fd) { bool success = true; int gpsSub = orb_subscribe(ORB_ID(vehicle_gps_position)); struct vehicle_gps_position_s gps; if (!orb_copy(ORB_ID(vehicle_gps_position), gpsSub, &gps) || (hrt_elapsed_time(&gps.timestamp_position) > 500000)) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: GPS RECEIVER MISSING"); success = false; } close(gpsSub); return success; } bool preflightCheck(int mavlink_fd, bool checkMag, bool checkAcc, bool checkGyro, bool checkBaro, bool checkAirspeed, bool checkRC, bool checkGNSS, bool checkDynamic) { bool failed = false; /* ---- MAG ---- */ if (checkMag) { /* check all sensors, but fail only for mandatory ones */ for (unsigned i = 0; i < max_optional_mag_count; i++) { bool required = (i < max_mandatory_mag_count); if (!magnometerCheck(mavlink_fd, i, !required) && required) { failed = true; } } } /* ---- ACCEL ---- */ if (checkAcc) { /* check all sensors, but fail only for mandatory ones */ for (unsigned i = 0; i < max_optional_accel_count; i++) { bool required = (i < max_mandatory_accel_count); if (!accelerometerCheck(mavlink_fd, i, !required, checkDynamic) && required) { failed = true; } } } /* ---- GYRO ---- */ if (checkGyro) { /* check all sensors, but fail only for mandatory ones */ for (unsigned i = 0; i < max_optional_gyro_count; i++) { bool required = (i < max_mandatory_gyro_count); if (!gyroCheck(mavlink_fd, i, !required) && required) { failed = true; } } } /* ---- BARO ---- */ if (checkBaro) { /* check all sensors, but fail only for mandatory ones */ for (unsigned i = 0; i < max_optional_baro_count; i++) { bool required = (i < max_mandatory_baro_count); if (!baroCheck(mavlink_fd, i, !required) && required) { failed = true; } } } /* ---- AIRSPEED ---- */ if (checkAirspeed) { if (!airspeedCheck(mavlink_fd, true)) { failed = true; } } /* ---- RC CALIBRATION ---- */ if (checkRC) { if (rc_calibration_check(mavlink_fd) != OK) { failed = true; } } /* ---- Global Navigation Satellite System receiver ---- */ if(checkGNSS) { if(!gnssCheck(mavlink_fd)) { failed = true; } } /* Report status */ return !failed; } } <commit_msg>Commander: Wait up to 1 second to allow GPS module to be detected<commit_after>/**************************************************************************** * * Copyright (c) 2012-2015 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 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. * ****************************************************************************/ /** * @file PreflightCheck.cpp * * Preflight check for main system components * * @author Lorenz Meier <[email protected]> * @author Johan Jansen <[email protected]> */ #include <nuttx/config.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <fcntl.h> #include <errno.h> #include <math.h> #include <poll.h> #include <systemlib/err.h> #include <systemlib/param/param.h> #include <systemlib/rc_check.h> #include <drivers/drv_hrt.h> #include <drivers/drv_mag.h> #include <drivers/drv_gyro.h> #include <drivers/drv_accel.h> #include <drivers/drv_baro.h> #include <drivers/drv_airspeed.h> #include <uORB/topics/airspeed.h> #include <uORB/topics/vehicle_gps_position.h> #include <mavlink/mavlink_log.h> #include "PreflightCheck.h" namespace Commander { static bool magnometerCheck(int mavlink_fd, unsigned instance, bool optional) { bool success = true; char s[30]; sprintf(s, "%s%u", MAG_BASE_DEVICE_PATH, instance); int fd = open(s, 0); if (fd < 0) { if (!optional) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: NO MAG SENSOR #%u", instance); } return false; } int calibration_devid; int ret; int devid = ioctl(fd, DEVIOCGDEVICEID, 0); sprintf(s, "CAL_MAG%u_ID", instance); param_get(param_find(s), &(calibration_devid)); if (devid != calibration_devid) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: MAG #%u UNCALIBRATED", instance); success = false; goto out; } ret = ioctl(fd, MAGIOCSELFTEST, 0); if (ret != OK) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: MAG #%u SELFTEST FAILED", instance); success = false; goto out; } out: close(fd); return success; } static bool accelerometerCheck(int mavlink_fd, unsigned instance, bool optional, bool dynamic) { bool success = true; char s[30]; sprintf(s, "%s%u", ACCEL_BASE_DEVICE_PATH, instance); int fd = open(s, O_RDONLY); if (fd < 0) { if (!optional) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: NO ACCEL SENSOR #%u", instance); } return false; } int calibration_devid; int ret; int devid = ioctl(fd, DEVIOCGDEVICEID, 0); sprintf(s, "CAL_ACC%u_ID", instance); param_get(param_find(s), &(calibration_devid)); if (devid != calibration_devid) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: ACCEL #%u UNCALIBRATED", instance); success = false; goto out; } ret = ioctl(fd, ACCELIOCSELFTEST, 0); if (ret != OK) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: ACCEL #%u SELFTEST FAILED", instance); success = false; goto out; } if (dynamic) { /* check measurement result range */ struct accel_report acc; ret = read(fd, &acc, sizeof(acc)); if (ret == sizeof(acc)) { /* evaluate values */ float accel_magnitude = sqrtf(acc.x * acc.x + acc.y * acc.y + acc.z * acc.z); if (accel_magnitude < 4.0f || accel_magnitude > 15.0f /* m/s^2 */) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: ACCEL RANGE, hold still on arming"); /* this is frickin' fatal */ success = false; goto out; } } else { mavlink_log_critical(mavlink_fd, "PREFLIGHT FAIL: ACCEL READ"); /* this is frickin' fatal */ success = false; goto out; } } out: close(fd); return success; } static bool gyroCheck(int mavlink_fd, unsigned instance, bool optional) { bool success = true; char s[30]; sprintf(s, "%s%u", GYRO_BASE_DEVICE_PATH, instance); int fd = open(s, 0); if (fd < 0) { if (!optional) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: NO GYRO SENSOR #%u", instance); } return false; } int calibration_devid; int ret; int devid = ioctl(fd, DEVIOCGDEVICEID, 0); sprintf(s, "CAL_GYRO%u_ID", instance); param_get(param_find(s), &(calibration_devid)); if (devid != calibration_devid) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: GYRO #%u UNCALIBRATED", instance); success = false; goto out; } ret = ioctl(fd, GYROIOCSELFTEST, 0); if (ret != OK) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: GYRO #%u SELFTEST FAILED", instance); success = false; goto out; } out: close(fd); return success; } static bool baroCheck(int mavlink_fd, unsigned instance, bool optional) { bool success = true; char s[30]; sprintf(s, "%s%u", BARO_BASE_DEVICE_PATH, instance); int fd = open(s, 0); if (fd < 0) { if (!optional) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: NO BARO SENSOR #%u", instance); } return false; } close(fd); return success; } static bool airspeedCheck(int mavlink_fd, bool optional) { bool success = true; int ret; int fd = orb_subscribe(ORB_ID(airspeed)); struct airspeed_s airspeed; if ((ret = orb_copy(ORB_ID(airspeed), fd, &airspeed)) || (hrt_elapsed_time(&airspeed.timestamp) > (500 * 1000))) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: AIRSPEED SENSOR MISSING"); success = false; goto out; } if (fabsf(airspeed.indicated_airspeed_m_s > 6.0f)) { mavlink_and_console_log_critical(mavlink_fd, "AIRSPEED WARNING: WIND OR CALIBRATION ISSUE"); // XXX do not make this fatal yet } out: close(fd); return success; } static bool gnssCheck(int mavlink_fd) { bool success = true; int gpsSub = orb_subscribe(ORB_ID(vehicle_gps_position)); //Wait up to 1000ms to allow the driver to detect a GNSS receiver module struct pollfd fds[1]; fds[0].fd = gpsSub; fds[0].events = POLLIN; if(poll(fds, 1, 1000) <= 0) { success = false; } else { struct vehicle_gps_position_s gps; if ( (OK != orb_copy(ORB_ID(vehicle_gps_position), gpsSub, &gps)) || (hrt_elapsed_time(&gps.timestamp_position) > 1000000)) { success = false; } } //Report failure to detect module if(!success) { mavlink_and_console_log_critical(mavlink_fd, "PREFLIGHT FAIL: GPS RECEIVER MISSING"); } close(gpsSub); return success; } bool preflightCheck(int mavlink_fd, bool checkMag, bool checkAcc, bool checkGyro, bool checkBaro, bool checkAirspeed, bool checkRC, bool checkGNSS, bool checkDynamic) { bool failed = false; /* ---- MAG ---- */ if (checkMag) { /* check all sensors, but fail only for mandatory ones */ for (unsigned i = 0; i < max_optional_mag_count; i++) { bool required = (i < max_mandatory_mag_count); if (!magnometerCheck(mavlink_fd, i, !required) && required) { failed = true; } } } /* ---- ACCEL ---- */ if (checkAcc) { /* check all sensors, but fail only for mandatory ones */ for (unsigned i = 0; i < max_optional_accel_count; i++) { bool required = (i < max_mandatory_accel_count); if (!accelerometerCheck(mavlink_fd, i, !required, checkDynamic) && required) { failed = true; } } } /* ---- GYRO ---- */ if (checkGyro) { /* check all sensors, but fail only for mandatory ones */ for (unsigned i = 0; i < max_optional_gyro_count; i++) { bool required = (i < max_mandatory_gyro_count); if (!gyroCheck(mavlink_fd, i, !required) && required) { failed = true; } } } /* ---- BARO ---- */ if (checkBaro) { /* check all sensors, but fail only for mandatory ones */ for (unsigned i = 0; i < max_optional_baro_count; i++) { bool required = (i < max_mandatory_baro_count); if (!baroCheck(mavlink_fd, i, !required) && required) { failed = true; } } } /* ---- AIRSPEED ---- */ if (checkAirspeed) { if (!airspeedCheck(mavlink_fd, true)) { failed = true; } } /* ---- RC CALIBRATION ---- */ if (checkRC) { if (rc_calibration_check(mavlink_fd) != OK) { failed = true; } } /* ---- Global Navigation Satellite System receiver ---- */ if(checkGNSS) { if(!gnssCheck(mavlink_fd)) { failed = true; } } /* Report status */ return !failed; } } <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (C) 2013 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 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. * ****************************************************************************/ /** * @file rc_calibration.cpp * Remote Control calibration routine */ #include <px4_posix.h> #include <px4_time.h> #include "rc_calibration.h" #include "commander_helper.h" #include <poll.h> #include <unistd.h> #include <uORB/topics/sensor_combined.h> #include <uORB/topics/manual_control_setpoint.h> #include <systemlib/mavlink_log.h> #include <systemlib/param/param.h> #include <systemlib/err.h> /* oddly, ERROR is not defined for c++ */ #ifdef ERROR # undef ERROR #endif static const int ERROR = -1; int do_trim_calibration(orb_advert_t *mavlink_log_pub) { int sub_man = orb_subscribe(ORB_ID(manual_control_setpoint)); usleep(400000); struct manual_control_setpoint_s sp; bool changed; orb_check(sub_man, &changed); if (!changed) { mavlink_log_critical(mavlink_log_pub, "no inputs, aborting"); return ERROR; } orb_copy(ORB_ID(manual_control_setpoint), sub_man, &sp); /* load trim values which are active */ float roll_trim_active; param_get(param_find("TRIM_ROLL"), &roll_trim_active); float pitch_trim_active; param_get(param_find("TRIM_PITCH"), &pitch_trim_active); float yaw_trim_active; param_get(param_find("TRIM_YAW"), &yaw_trim_active); /* set parameters: the new trim values are the combination of active trim values and the values coming from the remote control of the user */ float p = sp.y + roll_trim_active; int p1r = param_set(param_find("TRIM_ROLL"), &p); /* we explicitly swap sign here because the trim is added to the actuator controls which are moving in an inverse sense to manual pitch inputs */ p = -sp.x + pitch_trim_active; int p2r = param_set(param_find("TRIM_PITCH"), &p); p = sp.r + yaw_trim_active; int p3r = param_set(param_find("TRIM_YAW"), &p); /* store to permanent storage */ /* auto-save */ int save_ret = param_save_default(); if (save_ret != 0 || p1r != 0 || p2r != 0 || p3r != 0) { mavlink_log_critical(mavlink_log_pub, "TRIM: PARAM SET FAIL"); px4_close(sub_man); return ERROR; } mavlink_log_info(mavlink_log_pub, "trim cal done"); px4_close(sub_man); return OK; } <commit_msg>consider scale parameters in rc calibration code<commit_after>/**************************************************************************** * * Copyright (C) 2013 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 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. * ****************************************************************************/ /** * @file rc_calibration.cpp * Remote Control calibration routine */ #include <px4_posix.h> #include <px4_time.h> #include "rc_calibration.h" #include "commander_helper.h" #include <poll.h> #include <unistd.h> #include <uORB/topics/sensor_combined.h> #include <uORB/topics/manual_control_setpoint.h> #include <systemlib/mavlink_log.h> #include <systemlib/param/param.h> #include <systemlib/err.h> /* oddly, ERROR is not defined for c++ */ #ifdef ERROR # undef ERROR #endif static const int ERROR = -1; int do_trim_calibration(orb_advert_t *mavlink_log_pub) { int sub_man = orb_subscribe(ORB_ID(manual_control_setpoint)); usleep(400000); struct manual_control_setpoint_s sp; bool changed; orb_check(sub_man, &changed); if (!changed) { mavlink_log_critical(mavlink_log_pub, "no inputs, aborting"); return ERROR; } orb_copy(ORB_ID(manual_control_setpoint), sub_man, &sp); /* load trim values which are active */ float roll_trim_active; param_get(param_find("TRIM_ROLL"), &roll_trim_active); float pitch_trim_active; param_get(param_find("TRIM_PITCH"), &pitch_trim_active); float yaw_trim_active; param_get(param_find("TRIM_YAW"), &yaw_trim_active); /* get manual control scale values */ float roll_scale; param_get(param_find("FW_MAN_R_SC"), &roll_scale); float pitch_scale; param_get(param_find("FW_MAN_P_SC"), &pitch_scale); float yaw_scale; param_get(param_find("FW_MAN_Y_SC"), &yaw_scale); /* set parameters: the new trim values are the combination of active trim values and the values coming from the remote control of the user */ float p = sp.y * roll_scale + roll_trim_active; int p1r = param_set(param_find("TRIM_ROLL"), &p); /* we explicitly swap sign here because the trim is added to the actuator controls which are moving in an inverse sense to manual pitch inputs */ p = -sp.x * pitch_scale + pitch_trim_active; int p2r = param_set(param_find("TRIM_PITCH"), &p); p = sp.r * yaw_scale + yaw_trim_active; int p3r = param_set(param_find("TRIM_YAW"), &p); /* store to permanent storage */ /* auto-save */ int save_ret = param_save_default(); if (save_ret != 0 || p1r != 0 || p2r != 0 || p3r != 0) { mavlink_log_critical(mavlink_log_pub, "TRIM: PARAM SET FAIL"); px4_close(sub_man); return ERROR; } mavlink_log_info(mavlink_log_pub, "trim cal done"); px4_close(sub_man); return OK; } <|endoftext|>
<commit_before>/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2022 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * * without restriction, including without limitation the rights to use, copy, modify, * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * * permit persons to whom the Software is furnished to do so, subject to the following * * conditions: * * * * The above copyright notice and this permission notice shall be included in all copies * * or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ namespace { /** * Load a navigation state from file. The file should be a lua file returning the * navigation state as a table formatted as a Navigation State, such as the output files * of saveNavigationState. */ [[codegen::luawrap]] void loadNavigationState(std::string cameraStateFilePath) { if (cameraStateFilePath.empty()) { throw ghoul::lua::LuaError("Filepath string is empty"); } openspace::global::navigationHandler->loadNavigationState(cameraStateFilePath); } /** * Return the current navigation state as a lua table. The optional argument is the scene * graph node to use as reference frame. By default, the reference frame will picked based * on whether the orbital navigator is currently following the anchor node rotation. If it * is, the anchor will be chosen as reference frame. If not, the reference frame will be * set to the scene graph root. */ [[codegen::luawrap]] ghoul::Dictionary getNavigationState( std::optional<std::string> frame) { using namespace openspace; interaction::NavigationState state; if (frame.has_value()) { const SceneGraphNode* referenceFrame = sceneGraphNode(*frame); if (!referenceFrame) { throw ghoul::lua::LuaError( fmt::format("Could not find node '{}' as reference frame", *frame) ); } state = global::navigationHandler->navigationState(*referenceFrame); } else { state = global::navigationHandler->navigationState(); } ghoul::Dictionary res; res.setValue("Anchor", state.anchor); if (!state.aim.empty()) { res.setValue("Aim", state.aim); } if (!state.referenceFrame.empty()) { res.setValue("ReferenceFrame", state.referenceFrame); } res.setValue("ReferenceFrame", state.position); if (state.up.has_value()) { res.setValue("Up", *state.up); } if (state.yaw != 0) { res.setValue("Up", state.yaw); } if (state.pitch != 0) { res.setValue("Pitch", state.pitch); } return res; } // Set the navigation state. The argument must be a valid Navigation State. [[codegen::luawrap]] void setNavigationState(ghoul::Dictionary navigationState) { using namespace openspace; documentation::TestResult r = documentation::testSpecification( interaction::NavigationState::Documentation(), navigationState ); if (!r.success) { throw ghoul::lua::LuaError( fmt::format("Could not set camera state: {}", ghoul::to_string(r)) ); } global::navigationHandler->setNavigationStateNextFrame( interaction::NavigationState(navigationState) ); } /** * Save the current navigation state to a file with the path given by the first argument. * The optional second argument is the scene graph node to use as reference frame. By * default, the reference frame will picked based on whether the orbital navigator is * currently following the anchor node rotation. If it is, the anchor will be chosen as * reference frame. If not, the reference frame will be set to the scene graph root. */ [[codegen::luawrap]] void saveNavigationState(std::string path, std::string frame = "") { if (path.empty()) { throw ghoul::lua::LuaError("Filepath string is empty"); } openspace::global::navigationHandler->saveNavigationState(path, frame); } // Reset the camera direction to point at the anchor node. [[codegen::luawrap]] void retargetAnchor() { openspace::global::navigationHandler->orbitalNavigator().startRetargetAnchor(); } // Reset the camera direction to point at the aim node. [[codegen::luawrap]] void retargetAim() { openspace::global::navigationHandler->orbitalNavigator().startRetargetAim(); } // Picks the next node from the interesting nodes out of the profile and selects that. If // the current anchor is not an interesting node, the first will be selected [[codegen::luawrap]] void targetNextInterestingAnchor() { using namespace openspace; if (global::profile->markNodes.empty()) { LWARNINGC( "targetNextInterestingAnchor", "Profile does not define any interesting nodes" ); return; } const std::vector<std::string>& markNodes = global::profile->markNodes; std::string currAnchor = global::navigationHandler->orbitalNavigator().anchorNode()->identifier(); auto it = std::find(markNodes.begin(), markNodes.end(), currAnchor); if (it == markNodes.end() || ((it + 1) == markNodes.end())) { // We want to use the first node either if // 1. The current node is not an interesting node // 2. The current node is the last interesting node global::navigationHandler->orbitalNavigator().setFocusNode(markNodes.front()); } else { // Otherwise we can just select the next one global::navigationHandler->orbitalNavigator().setFocusNode(*(it + 1)); } global::navigationHandler->orbitalNavigator().startRetargetAnchor(); } /** * Finds the input joystick with the given 'name' and binds the axis identified by the * second argument to be used as the type identified by the third argument. If * 'isInverted' is 'true', the axis value is inverted. 'joystickType' is if the joystick * behaves more like a joystick or a trigger, where the first is the default. If * 'isSticky' is 'true', the value is calculated relative to the previous value. If * 'sensitivity' is given then that value will affect the sensitivity of the axis together * with the global sensitivity. */ [[codegen::luawrap]] void bindJoystickAxis(std::string joystickName, int axis, std::string axisType, bool shouldInvert = false, std::string joystickType = "JoystickLike", bool isSticky = false, double sensitivity = 0.0) { using namespace openspace; using JoystickCameraStates = interaction::JoystickCameraStates; global::navigationHandler->setJoystickAxisMapping( std::move(joystickName), axis, ghoul::from_string<JoystickCameraStates::AxisType>(axisType), JoystickCameraStates::AxisInvert(shouldInvert), ghoul::from_string<JoystickCameraStates::JoystickType>(joystickType), isSticky, sensitivity ); } /** * Finds the input joystick with the given 'name' and binds the axis identified by the * second argument to be bound to the property identified by the third argument. 'min' and * 'max' is the minimum and the maximum allowed value for the given property and the axis * value is rescaled from [-1, 1] to [min, max], default is [0, 1]. If 'isInverted' is * 'true', the axis value is inverted. The last argument determines whether the property * change is going to be executed locally or remotely, where the latter is the default. */ [[codegen::luawrap]] void bindJoystickAxisProperty(std::string joystickName, int axis, std::string propertyUri, float min = 0.f, float max = 1.f, bool shouldInvert = false, bool isRemote = true) { using namespace openspace; global::navigationHandler->setJoystickAxisMappingProperty( std::move(joystickName), axis, std::move(propertyUri), min, max, interaction::JoystickCameraStates::AxisInvert(shouldInvert), isRemote ); } /** * Finds the input joystick with the given 'name' and returns the joystick axis * information for the passed axis. The information that is returned is the current axis * binding as a string, whether the values are inverted as bool, the joystick type as a * string, whether the axis is sticky as bool, the sensitivity as number, the property uri * bound to the axis as string (empty is type is not Property), the min and max values for * the property as numbers and whether the property change will be executed remotly as * bool. */ [[codegen::luawrap]] std::tuple<std::string, bool, std::string, bool, double, std::string, float, float, bool> joystickAxis(std::string joystickName, int axis) { using namespace openspace; interaction::JoystickCameraStates::AxisInformation info = global::navigationHandler->joystickAxisMapping(joystickName, axis); return { ghoul::to_string(info.type), info.invert, ghoul::to_string(info.joystickType), info.isSticky, info.sensitivity, info.propertyUri, info.minValue, info.maxValue, info.isRemote }; } /** * Finds the input joystick with the given 'name' and sets the deadzone for a particular * joystick axis, which means that any input less than this value is completely ignored. */ [[codegen::luawrap("setAxisDeadZone")]] void setJoystickAxisDeadZone( std::string joystickName, int axis, float deadzone) { using namespace openspace; global::navigationHandler->setJoystickAxisDeadzone(joystickName, axis, deadzone); } /** * Returns the deadzone for the desired axis of the provided joystick. */ [[codegen::luawrap("axisDeadzone")]] float joystickAxisDeadzone(std::string joystickName, int axis) { float deadzone = openspace::global::navigationHandler->joystickAxisDeadzone( joystickName, axis ); return deadzone; } /** * Finds the input joystick with the given 'name' and binds a Lua script given by the * third argument to be executed when the joystick button identified by the second * argument is triggered. The fifth argument determines when the script should be * executed, this defaults to 'Press', which means that the script is run when the user * presses the button. The fourth arguemnt is the documentation of the script in the third * argument. The sixth argument determines whether the command is going to be executable * locally or remotely, where the latter is the default. */ [[codegen::luawrap]] void bindJoystickButton(std::string joystickName, int button, std::string command, std::string documentation, std::string action = "Press", bool isRemote = true) { using namespace openspace; interaction::JoystickAction act = ghoul::from_string<interaction::JoystickAction>(action); global::navigationHandler->bindJoystickButtonCommand( joystickName, button, command, act, interaction::JoystickCameraStates::ButtonCommandRemote(isRemote), documentation ); } /** * Finds the input joystick with the given 'name' and removes all commands that are * currently bound to the button identified by the second argument. */ [[codegen::luawrap]] void clearJoystickButton(std::string joystickName, int button) { openspace::global::navigationHandler->clearJoystickButtonCommand( joystickName, button ); } /** * Finds the input joystick with the given 'name' and returns the script that is currently * bound to be executed when the provided button is pressed. */ [[codegen::luawrap]] std::string joystickButton(std::string joystickName, int button) { using namespace openspace; const std::vector<std::string>& cmds = global::navigationHandler->joystickButtonCommand(joystickName, button); std::string cmd = std::accumulate( cmds.cbegin(), cmds.cend(), std::string(), [](const std::string& lhs, const std::string& rhs) { return lhs + ";" + rhs; } ); return cmd; } // Directly adds to the global rotation of the camera. [[codegen::luawrap]] void addGlobalRotation(double v1, double v2) { using namespace openspace; global::navigationHandler->orbitalNavigator().scriptStates().addGlobalRotation( glm::dvec2(v1, v2) ); } // Directly adds to the local rotation of the camera. [[codegen::luawrap]] void addLocalRotation(double v1, double v2) { using namespace openspace; global::navigationHandler->orbitalNavigator().scriptStates().addLocalRotation( glm::dvec2(v1, v2) ); } // Directly adds to the truck movement of the camera. [[codegen::luawrap]] void addTruckMovement(double v1, double v2) { using namespace openspace; global::navigationHandler->orbitalNavigator().scriptStates().addTruckMovement( glm::dvec2(v1, v2) ); } // Directly adds to the local roll of the camera. [[codegen::luawrap]] void addLocalRoll(double v1, double v2) { using namespace openspace; global::navigationHandler->orbitalNavigator().scriptStates().addLocalRoll( glm::dvec2(v1, v2) ); } // Directly adds to the global roll of the camera. [[codegen::luawrap]] void addGlobalRoll(double v1, double v2) { using namespace openspace; global::navigationHandler->orbitalNavigator().scriptStates().addGlobalRoll( glm::dvec2(v1, v2) ); } /** * Immediately start applying the chosen IdleBehavior. If none is specified, use the one * set to default in the OrbitalNavigator. */ [[codegen::luawrap]] void triggerIdleBehavior(std::string choice = "") { using namespace openspace; try { global::navigationHandler->orbitalNavigator().triggerIdleBehavior(choice); } catch (ghoul::RuntimeError& e) { throw ghoul::lua::LuaError(e.message); } } /** * Return the complete list of connected joysticks */ [[codegen::luawrap]] std::vector<std::string> listAllJoysticks() { using namespace openspace; return global::navigationHandler->listAllJoysticks(); } #include "navigationhandler_lua_codegen.cpp" } // namespace <commit_msg>Fix broken getNavigationState function<commit_after>/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2022 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * * without restriction, including without limitation the rights to use, copy, modify, * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * * permit persons to whom the Software is furnished to do so, subject to the following * * conditions: * * * * The above copyright notice and this permission notice shall be included in all copies * * or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ namespace { /** * Load a navigation state from file. The file should be a lua file returning the * navigation state as a table formatted as a Navigation State, such as the output files * of saveNavigationState. */ [[codegen::luawrap]] void loadNavigationState(std::string cameraStateFilePath) { if (cameraStateFilePath.empty()) { throw ghoul::lua::LuaError("Filepath string is empty"); } openspace::global::navigationHandler->loadNavigationState(cameraStateFilePath); } /** * Return the current navigation state as a lua table. The optional argument is the scene * graph node to use as reference frame. By default, the reference frame will picked based * on whether the orbital navigator is currently following the anchor node rotation. If it * is, the anchor will be chosen as reference frame. If not, the reference frame will be * set to the scene graph root. */ [[codegen::luawrap]] ghoul::Dictionary getNavigationState( std::optional<std::string> frame) { using namespace openspace; interaction::NavigationState state; if (frame.has_value()) { const SceneGraphNode* referenceFrame = sceneGraphNode(*frame); if (!referenceFrame) { throw ghoul::lua::LuaError( fmt::format("Could not find node '{}' as reference frame", *frame) ); } state = global::navigationHandler->navigationState(*referenceFrame); } else { state = global::navigationHandler->navigationState(); } return state.dictionary(); } // Set the navigation state. The argument must be a valid Navigation State. [[codegen::luawrap]] void setNavigationState(ghoul::Dictionary navigationState) { using namespace openspace; documentation::TestResult r = documentation::testSpecification( interaction::NavigationState::Documentation(), navigationState ); if (!r.success) { throw ghoul::lua::LuaError( fmt::format("Could not set camera state: {}", ghoul::to_string(r)) ); } global::navigationHandler->setNavigationStateNextFrame( interaction::NavigationState(navigationState) ); } /** * Save the current navigation state to a file with the path given by the first argument. * The optional second argument is the scene graph node to use as reference frame. By * default, the reference frame will picked based on whether the orbital navigator is * currently following the anchor node rotation. If it is, the anchor will be chosen as * reference frame. If not, the reference frame will be set to the scene graph root. */ [[codegen::luawrap]] void saveNavigationState(std::string path, std::string frame = "") { if (path.empty()) { throw ghoul::lua::LuaError("Filepath string is empty"); } openspace::global::navigationHandler->saveNavigationState(path, frame); } // Reset the camera direction to point at the anchor node. [[codegen::luawrap]] void retargetAnchor() { openspace::global::navigationHandler->orbitalNavigator().startRetargetAnchor(); } // Reset the camera direction to point at the aim node. [[codegen::luawrap]] void retargetAim() { openspace::global::navigationHandler->orbitalNavigator().startRetargetAim(); } // Picks the next node from the interesting nodes out of the profile and selects that. If // the current anchor is not an interesting node, the first will be selected [[codegen::luawrap]] void targetNextInterestingAnchor() { using namespace openspace; if (global::profile->markNodes.empty()) { LWARNINGC( "targetNextInterestingAnchor", "Profile does not define any interesting nodes" ); return; } const std::vector<std::string>& markNodes = global::profile->markNodes; std::string currAnchor = global::navigationHandler->orbitalNavigator().anchorNode()->identifier(); auto it = std::find(markNodes.begin(), markNodes.end(), currAnchor); if (it == markNodes.end() || ((it + 1) == markNodes.end())) { // We want to use the first node either if // 1. The current node is not an interesting node // 2. The current node is the last interesting node global::navigationHandler->orbitalNavigator().setFocusNode(markNodes.front()); } else { // Otherwise we can just select the next one global::navigationHandler->orbitalNavigator().setFocusNode(*(it + 1)); } global::navigationHandler->orbitalNavigator().startRetargetAnchor(); } /** * Finds the input joystick with the given 'name' and binds the axis identified by the * second argument to be used as the type identified by the third argument. If * 'isInverted' is 'true', the axis value is inverted. 'joystickType' is if the joystick * behaves more like a joystick or a trigger, where the first is the default. If * 'isSticky' is 'true', the value is calculated relative to the previous value. If * 'sensitivity' is given then that value will affect the sensitivity of the axis together * with the global sensitivity. */ [[codegen::luawrap]] void bindJoystickAxis(std::string joystickName, int axis, std::string axisType, bool shouldInvert = false, std::string joystickType = "JoystickLike", bool isSticky = false, double sensitivity = 0.0) { using namespace openspace; using JoystickCameraStates = interaction::JoystickCameraStates; global::navigationHandler->setJoystickAxisMapping( std::move(joystickName), axis, ghoul::from_string<JoystickCameraStates::AxisType>(axisType), JoystickCameraStates::AxisInvert(shouldInvert), ghoul::from_string<JoystickCameraStates::JoystickType>(joystickType), isSticky, sensitivity ); } /** * Finds the input joystick with the given 'name' and binds the axis identified by the * second argument to be bound to the property identified by the third argument. 'min' and * 'max' is the minimum and the maximum allowed value for the given property and the axis * value is rescaled from [-1, 1] to [min, max], default is [0, 1]. If 'isInverted' is * 'true', the axis value is inverted. The last argument determines whether the property * change is going to be executed locally or remotely, where the latter is the default. */ [[codegen::luawrap]] void bindJoystickAxisProperty(std::string joystickName, int axis, std::string propertyUri, float min = 0.f, float max = 1.f, bool shouldInvert = false, bool isRemote = true) { using namespace openspace; global::navigationHandler->setJoystickAxisMappingProperty( std::move(joystickName), axis, std::move(propertyUri), min, max, interaction::JoystickCameraStates::AxisInvert(shouldInvert), isRemote ); } /** * Finds the input joystick with the given 'name' and returns the joystick axis * information for the passed axis. The information that is returned is the current axis * binding as a string, whether the values are inverted as bool, the joystick type as a * string, whether the axis is sticky as bool, the sensitivity as number, the property uri * bound to the axis as string (empty is type is not Property), the min and max values for * the property as numbers and whether the property change will be executed remotly as * bool. */ [[codegen::luawrap]] std::tuple<std::string, bool, std::string, bool, double, std::string, float, float, bool> joystickAxis(std::string joystickName, int axis) { using namespace openspace; interaction::JoystickCameraStates::AxisInformation info = global::navigationHandler->joystickAxisMapping(joystickName, axis); return { ghoul::to_string(info.type), info.invert, ghoul::to_string(info.joystickType), info.isSticky, info.sensitivity, info.propertyUri, info.minValue, info.maxValue, info.isRemote }; } /** * Finds the input joystick with the given 'name' and sets the deadzone for a particular * joystick axis, which means that any input less than this value is completely ignored. */ [[codegen::luawrap("setAxisDeadZone")]] void setJoystickAxisDeadZone( std::string joystickName, int axis, float deadzone) { using namespace openspace; global::navigationHandler->setJoystickAxisDeadzone(joystickName, axis, deadzone); } /** * Returns the deadzone for the desired axis of the provided joystick. */ [[codegen::luawrap("axisDeadzone")]] float joystickAxisDeadzone(std::string joystickName, int axis) { float deadzone = openspace::global::navigationHandler->joystickAxisDeadzone( joystickName, axis ); return deadzone; } /** * Finds the input joystick with the given 'name' and binds a Lua script given by the * third argument to be executed when the joystick button identified by the second * argument is triggered. The fifth argument determines when the script should be * executed, this defaults to 'Press', which means that the script is run when the user * presses the button. The fourth arguemnt is the documentation of the script in the third * argument. The sixth argument determines whether the command is going to be executable * locally or remotely, where the latter is the default. */ [[codegen::luawrap]] void bindJoystickButton(std::string joystickName, int button, std::string command, std::string documentation, std::string action = "Press", bool isRemote = true) { using namespace openspace; interaction::JoystickAction act = ghoul::from_string<interaction::JoystickAction>(action); global::navigationHandler->bindJoystickButtonCommand( joystickName, button, command, act, interaction::JoystickCameraStates::ButtonCommandRemote(isRemote), documentation ); } /** * Finds the input joystick with the given 'name' and removes all commands that are * currently bound to the button identified by the second argument. */ [[codegen::luawrap]] void clearJoystickButton(std::string joystickName, int button) { openspace::global::navigationHandler->clearJoystickButtonCommand( joystickName, button ); } /** * Finds the input joystick with the given 'name' and returns the script that is currently * bound to be executed when the provided button is pressed. */ [[codegen::luawrap]] std::string joystickButton(std::string joystickName, int button) { using namespace openspace; const std::vector<std::string>& cmds = global::navigationHandler->joystickButtonCommand(joystickName, button); std::string cmd = std::accumulate( cmds.cbegin(), cmds.cend(), std::string(), [](const std::string& lhs, const std::string& rhs) { return lhs + ";" + rhs; } ); return cmd; } // Directly adds to the global rotation of the camera. [[codegen::luawrap]] void addGlobalRotation(double v1, double v2) { using namespace openspace; global::navigationHandler->orbitalNavigator().scriptStates().addGlobalRotation( glm::dvec2(v1, v2) ); } // Directly adds to the local rotation of the camera. [[codegen::luawrap]] void addLocalRotation(double v1, double v2) { using namespace openspace; global::navigationHandler->orbitalNavigator().scriptStates().addLocalRotation( glm::dvec2(v1, v2) ); } // Directly adds to the truck movement of the camera. [[codegen::luawrap]] void addTruckMovement(double v1, double v2) { using namespace openspace; global::navigationHandler->orbitalNavigator().scriptStates().addTruckMovement( glm::dvec2(v1, v2) ); } // Directly adds to the local roll of the camera. [[codegen::luawrap]] void addLocalRoll(double v1, double v2) { using namespace openspace; global::navigationHandler->orbitalNavigator().scriptStates().addLocalRoll( glm::dvec2(v1, v2) ); } // Directly adds to the global roll of the camera. [[codegen::luawrap]] void addGlobalRoll(double v1, double v2) { using namespace openspace; global::navigationHandler->orbitalNavigator().scriptStates().addGlobalRoll( glm::dvec2(v1, v2) ); } /** * Immediately start applying the chosen IdleBehavior. If none is specified, use the one * set to default in the OrbitalNavigator. */ [[codegen::luawrap]] void triggerIdleBehavior(std::string choice = "") { using namespace openspace; try { global::navigationHandler->orbitalNavigator().triggerIdleBehavior(choice); } catch (ghoul::RuntimeError& e) { throw ghoul::lua::LuaError(e.message); } } /** * Return the complete list of connected joysticks */ [[codegen::luawrap]] std::vector<std::string> listAllJoysticks() { using namespace openspace; return global::navigationHandler->listAllJoysticks(); } #include "navigationhandler_lua_codegen.cpp" } // namespace <|endoftext|>
<commit_before>// Copyright (c) 2011-2012 Zeex // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <amx/amx.h> #include "amx.h" #include "amxerror.h" #include "compiler.h" #include "crashdetect.h" #include "fileutils.h" #include "hook.h" #include "logprintf.h" #include "os.h" #include "plugincommon.h" #include "version.h" extern "C" int AMXAPI amx_Error(AMX *amx, cell index, int error) { if (error != AMX_ERR_NONE) { CrashDetect::Get(amx)->HandleExecError(index, error); } return AMX_ERR_NONE; } static int AMXAPI AmxCallback(AMX *amx, cell index, cell *result, cell *params) { return CrashDetect::Get(amx)->DoAmxCallback(index, result, params); } static int AMXAPI AmxExec(AMX *amx, cell *retval, int index) { if (amx->flags & AMX_FLAG_BROWSE) { return amx_Exec(amx, retval, index); } return CrashDetect::Get(amx)->DoAmxExec(retval, index); } PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() { return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES; } PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) { void **exports = reinterpret_cast<void**>(ppData[PLUGIN_DATA_AMX_EXPORTS]); ::logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF]; void *amx_Exec_ptr = exports[PLUGIN_AMX_EXPORT_Exec]; void *amx_Exec_sub = Hook::GetTargetAddress(reinterpret_cast<unsigned char*>(amx_Exec_ptr)); if (amx_Exec_sub == 0) { new Hook(amx_Exec_ptr, (void*)AmxExec); } else { std::string module = fileutils::GetFileName(os::GetModulePathFromAddr(amx_Exec_sub)); if (!module.empty()) { logprintf(" Warning: Runtime error detection will not work during this run because "); logprintf(" %s has been loaded before CrashDetect.", module.c_str()); } } os::SetExceptionHandler(CrashDetect::OnException); os::SetInterruptHandler(CrashDetect::OnInterrupt); logprintf(" crashdetect v"PROJECT_VERSION_STRING" is OK."); return true; } PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) { int error = CrashDetect::Create(amx)->Load(); if (error == AMX_ERR_NONE) { amx_SetCallback(amx, AmxCallback); } return error; } PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) { int error = CrashDetect::Get(amx)->Unload(); CrashDetect::Destroy(amx); return error; } <commit_msg>Change message<commit_after>// Copyright (c) 2011-2012 Zeex // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <amx/amx.h> #include "amx.h" #include "amxerror.h" #include "compiler.h" #include "crashdetect.h" #include "fileutils.h" #include "hook.h" #include "logprintf.h" #include "os.h" #include "plugincommon.h" #include "version.h" extern "C" int AMXAPI amx_Error(AMX *amx, cell index, int error) { if (error != AMX_ERR_NONE) { CrashDetect::Get(amx)->HandleExecError(index, error); } return AMX_ERR_NONE; } static int AMXAPI AmxCallback(AMX *amx, cell index, cell *result, cell *params) { return CrashDetect::Get(amx)->DoAmxCallback(index, result, params); } static int AMXAPI AmxExec(AMX *amx, cell *retval, int index) { if (amx->flags & AMX_FLAG_BROWSE) { return amx_Exec(amx, retval, index); } return CrashDetect::Get(amx)->DoAmxExec(retval, index); } PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() { return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES; } PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) { void **exports = reinterpret_cast<void**>(ppData[PLUGIN_DATA_AMX_EXPORTS]); ::logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF]; void *amx_Exec_ptr = exports[PLUGIN_AMX_EXPORT_Exec]; void *amx_Exec_sub = Hook::GetTargetAddress(reinterpret_cast<unsigned char*>(amx_Exec_ptr)); if (amx_Exec_sub == 0) { new Hook(amx_Exec_ptr, (void*)AmxExec); } else { std::string module = fileutils::GetFileName(os::GetModulePathFromAddr(amx_Exec_sub)); if (!module.empty()) { logprintf(" In order for runtime error detection to work crashdetect must be loaded before %s.",module.c_str()); } } os::SetExceptionHandler(CrashDetect::OnException); os::SetInterruptHandler(CrashDetect::OnInterrupt); logprintf(" crashdetect v"PROJECT_VERSION_STRING" is OK."); return true; } PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) { int error = CrashDetect::Create(amx)->Load(); if (error == AMX_ERR_NONE) { amx_SetCallback(amx, AmxCallback); } return error; } PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) { int error = CrashDetect::Get(amx)->Unload(); CrashDetect::Destroy(amx); return error; } <|endoftext|>
<commit_before>/* * Copyright (c) 2015 OpenALPR Technology, Inc. * Open source Automated License Plate Recognition [http://www.openalpr.com] * * This file is part of OpenALPR. * * OpenALPR is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License * version 3 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/>. */ #include "postprocess.h" using namespace std; namespace alpr { PostProcess::PostProcess(Config* config) { this->config = config; stringstream filename; filename << config->getPostProcessRuntimeDir() << "/" << config->country << ".patterns"; std::ifstream infile(filename.str().c_str()); string region, pattern; while (infile >> region >> pattern) { RegexRule* rule = new RegexRule(region, pattern, config->postProcessRegexLetters, config->postProcessRegexNumbers); //cout << "REGION: " << region << " PATTERN: " << pattern << endl; if (rules.find(region) == rules.end()) { vector<RegexRule*> newRule; newRule.push_back(rule); rules[region] = newRule; } else { vector<RegexRule*> oldRule = rules[region]; oldRule.push_back(rule); rules[region] = oldRule; } } //vector<RegexRule> test = rules["base"]; //for (int i = 0; i < test.size(); i++) // cout << "Rule: " << test[i].regex << endl; } PostProcess::~PostProcess() { // TODO: Delete all entries in rules vector map<string, vector<RegexRule*> >::iterator iter; for (iter = rules.begin(); iter != rules.end(); ++iter) { for (int i = 0; i < iter->second.size(); i++) { delete iter->second[i]; } } } void PostProcess::addLetter(string letter, int line_index, int charposition, float score) { if (score < config->postProcessMinConfidence) return; insertLetter(letter, line_index, charposition, score); if (score < config->postProcessConfidenceSkipLevel) { float adjustedScore = abs(config->postProcessConfidenceSkipLevel - score) + config->postProcessMinConfidence; insertLetter(SKIP_CHAR, line_index, charposition, adjustedScore ); } //if (letter == '0') //{ // insertLetter('O', charposition, score - 0.5); //} } void PostProcess::insertLetter(string letter, int line_index, int charposition, float score) { score = score - config->postProcessMinConfidence; int existingIndex = -1; if (letters.size() < charposition + 1) { for (int i = letters.size(); i < charposition + 1; i++) { vector<Letter> tmp; letters.push_back(tmp); } } for (int i = 0; i < letters[charposition].size(); i++) { if (letters[charposition][i].letter == letter && letters[charposition][i].line_index == line_index && letters[charposition][i].charposition == charposition) { existingIndex = i; break; } } if (existingIndex == -1) { Letter newLetter; newLetter.line_index = line_index; newLetter.charposition = charposition; newLetter.letter = letter; newLetter.occurences = 1; newLetter.totalscore = score; letters[charposition].push_back(newLetter); } else { letters[charposition][existingIndex].occurences = letters[charposition][existingIndex].occurences + 1; letters[charposition][existingIndex].totalscore = letters[charposition][existingIndex].totalscore + score; } } void PostProcess::clear() { for (int i = 0; i < letters.size(); i++) { letters[i].clear(); } letters.resize(0); unknownCharPositions.clear(); unknownCharPositions.resize(0); allPossibilities.clear(); allPossibilitiesLetters.clear(); //allPossibilities.resize(0); bestChars = ""; matchesTemplate = false; } void PostProcess::analyze(string templateregion, int topn) { timespec startTime; getTimeMonotonic(&startTime); // Get a list of missing positions for (int i = letters.size() -1; i >= 0; i--) { if (letters[i].size() == 0) { unknownCharPositions.push_back(i); } } if (letters.size() == 0) return; // Sort the letters as they are for (int i = 0; i < letters.size(); i++) { if (letters[i].size() > 0) std::stable_sort(letters[i].begin(), letters[i].end(), letterCompare); } if (this->config->debugPostProcess) { // Print all letters for (int i = 0; i < letters.size(); i++) { for (int j = 0; j < letters[i].size(); j++) cout << "PostProcess Line " << letters[i][j].line_index << " Letter: " << letters[i][j].charposition << " " << letters[i][j].letter << " -- score: " << letters[i][j].totalscore << " -- occurences: " << letters[i][j].occurences << endl; } } timespec permutationStartTime; getTimeMonotonic(&permutationStartTime); findAllPermutations(templateregion, topn); if (config->debugTiming) { timespec permutationEndTime; getTimeMonotonic(&permutationEndTime); cout << " -- PostProcess Permutation Time: " << diffclock(permutationStartTime, permutationEndTime) << "ms." << endl; } if (allPossibilities.size() > 0) { bestChars = allPossibilities[0].letters; for (int z = 0; z < allPossibilities.size(); z++) { if (allPossibilities[z].matchesTemplate) { bestChars = allPossibilities[z].letters; break; } } // Now adjust the confidence scores to a percentage value float maxPercentScore = calculateMaxConfidenceScore(); float highestRelativeScore = (float) allPossibilities[0].totalscore; for (int i = 0; i < allPossibilities.size(); i++) { allPossibilities[i].totalscore = maxPercentScore * (allPossibilities[i].totalscore / highestRelativeScore); } } if (this->config->debugPostProcess) { // Print top words for (int i = 0; i < allPossibilities.size(); i++) { cout << "Top " << topn << " Possibilities: " << allPossibilities[i].letters << " :\t" << allPossibilities[i].totalscore; if (allPossibilities[i].letters == bestChars) cout << " <--- "; cout << endl; } cout << allPossibilities.size() << " total permutations" << endl; } if (config->debugTiming) { timespec endTime; getTimeMonotonic(&endTime); cout << "PostProcess Time: " << diffclock(startTime, endTime) << "ms." << endl; } if (this->config->debugPostProcess) cout << "PostProcess Analysis Complete: " << bestChars << " -- MATCH: " << matchesTemplate << endl; } bool PostProcess::regionIsValid(std::string templateregion) { return rules.find(templateregion) != rules.end(); } float PostProcess::calculateMaxConfidenceScore() { // Take the best score for each char position and average it. float totalScore = 0; int numScores = 0; // Get a list of missing positions for (int i = 0; i < letters.size(); i++) { if (letters[i].size() > 0) { totalScore += (letters[i][0].totalscore / letters[i][0].occurences) + config->postProcessMinConfidence; numScores++; } } if (numScores == 0) return 0; return totalScore / ((float) numScores); } const vector<PPResult> PostProcess::getResults() { return this->allPossibilities; } struct PermutationCompare { bool operator() (pair<float,vector<int> > &a, pair<float,vector<int> > &b) { return (a.first < b.first); } }; void PostProcess::findAllPermutations(string templateregion, int topn) { // use a priority queue to process permutations in highest scoring order priority_queue<pair<float,vector<int> >, vector<pair<float,vector<int> > >, PermutationCompare> permutations; set<float> permutationHashes; // push the first word onto the queue float totalscore = 0; for (int i=0; i<letters.size(); i++) { if (letters[i].size() > 0) totalscore += letters[i][0].totalscore; } vector<int> v(letters.size()); permutations.push(make_pair(totalscore, v)); int consecutiveNonMatches = 0; while (permutations.size() > 0) { // get the top permutation and analyze pair<float, vector<int> > topPermutation = permutations.top(); if (analyzePermutation(topPermutation.second, templateregion, topn) == true) consecutiveNonMatches = 0; else consecutiveNonMatches += 1; permutations.pop(); if (allPossibilities.size() >= topn || consecutiveNonMatches >= 10) break; // add child permutations to queue for (int i=0; i<letters.size(); i++) { // no more permutations with this letter if (topPermutation.second[i]+1 >= letters[i].size()) continue; pair<float, vector<int> > childPermutation = topPermutation; childPermutation.first -= letters[i][topPermutation.second[i]].totalscore - letters[i][topPermutation.second[i] + 1].totalscore; childPermutation.second[i] += 1; // ignore permutations that have already been visited (assume that score is a good hash for permutation) if (permutationHashes.end() != permutationHashes.find(childPermutation.first)) continue; permutations.push(childPermutation); permutationHashes.insert(childPermutation.first); } } } bool PostProcess::analyzePermutation(vector<int> letterIndices, string templateregion, int topn) { PPResult possibility; possibility.letters = ""; possibility.totalscore = 0; possibility.matchesTemplate = false; int plate_char_length = 0; int last_line = 0; for (int i = 0; i < letters.size(); i++) { if (letters[i].size() == 0) continue; Letter letter = letters[i][letterIndices[i]]; // Add a "\n" on new lines if (letter.line_index != last_line) { possibility.letters = possibility.letters + "\n"; } last_line = letter.line_index; if (letter.letter != SKIP_CHAR) { possibility.letters = possibility.letters + letter.letter; possibility.letter_details.push_back(letter); plate_char_length += 1; } possibility.totalscore = possibility.totalscore + letter.totalscore; } // ignore plates that don't fit the length requirements if (plate_char_length < config->postProcessMinCharacters || plate_char_length > config->postProcessMaxCharacters) return false; // Apply templates if (templateregion != "") { vector<RegexRule*> regionRules = rules[templateregion]; for (int i = 0; i < regionRules.size(); i++) { possibility.matchesTemplate = regionRules[i]->match(possibility.letters); if (possibility.matchesTemplate) { possibility.letters = regionRules[i]->filterSkips(possibility.letters); break; } } } // ignore duplicate words if (allPossibilitiesLetters.end() != allPossibilitiesLetters.find(possibility.letters)) return false; // If mustMatchPattern is toggled in the config and a template is provided, // only include this result if there is a pattern match if (!config->mustMatchPattern || templateregion.size() == 0 || (config->mustMatchPattern && possibility.matchesTemplate)) { allPossibilities.push_back(possibility); allPossibilitiesLetters.insert(possibility.letters); return true; } return false; } std::vector<string> PostProcess::getPatterns() { vector<string> v; for(map<string,std::vector<RegexRule*> >::iterator it = rules.begin(); it != rules.end(); ++it) { v.push_back(it->first); } return v; } bool letterCompare( const Letter &left, const Letter &right ) { if (left.totalscore < right.totalscore) return false; return true; } }<commit_msg>Fixed issue with must_match_pattern not returning enough values<commit_after>/* * Copyright (c) 2015 OpenALPR Technology, Inc. * Open source Automated License Plate Recognition [http://www.openalpr.com] * * This file is part of OpenALPR. * * OpenALPR is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License * version 3 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/>. */ #include "postprocess.h" using namespace std; namespace alpr { PostProcess::PostProcess(Config* config) { this->config = config; stringstream filename; filename << config->getPostProcessRuntimeDir() << "/" << config->country << ".patterns"; std::ifstream infile(filename.str().c_str()); string region, pattern; while (infile >> region >> pattern) { RegexRule* rule = new RegexRule(region, pattern, config->postProcessRegexLetters, config->postProcessRegexNumbers); //cout << "REGION: " << region << " PATTERN: " << pattern << endl; if (rules.find(region) == rules.end()) { vector<RegexRule*> newRule; newRule.push_back(rule); rules[region] = newRule; } else { vector<RegexRule*> oldRule = rules[region]; oldRule.push_back(rule); rules[region] = oldRule; } } //vector<RegexRule> test = rules["base"]; //for (int i = 0; i < test.size(); i++) // cout << "Rule: " << test[i].regex << endl; } PostProcess::~PostProcess() { // TODO: Delete all entries in rules vector map<string, vector<RegexRule*> >::iterator iter; for (iter = rules.begin(); iter != rules.end(); ++iter) { for (int i = 0; i < iter->second.size(); i++) { delete iter->second[i]; } } } void PostProcess::addLetter(string letter, int line_index, int charposition, float score) { if (score < config->postProcessMinConfidence) return; insertLetter(letter, line_index, charposition, score); if (score < config->postProcessConfidenceSkipLevel) { float adjustedScore = abs(config->postProcessConfidenceSkipLevel - score) + config->postProcessMinConfidence; insertLetter(SKIP_CHAR, line_index, charposition, adjustedScore ); } //if (letter == '0') //{ // insertLetter('O', charposition, score - 0.5); //} } void PostProcess::insertLetter(string letter, int line_index, int charposition, float score) { score = score - config->postProcessMinConfidence; int existingIndex = -1; if (letters.size() < charposition + 1) { for (int i = letters.size(); i < charposition + 1; i++) { vector<Letter> tmp; letters.push_back(tmp); } } for (int i = 0; i < letters[charposition].size(); i++) { if (letters[charposition][i].letter == letter && letters[charposition][i].line_index == line_index && letters[charposition][i].charposition == charposition) { existingIndex = i; break; } } if (existingIndex == -1) { Letter newLetter; newLetter.line_index = line_index; newLetter.charposition = charposition; newLetter.letter = letter; newLetter.occurences = 1; newLetter.totalscore = score; letters[charposition].push_back(newLetter); } else { letters[charposition][existingIndex].occurences = letters[charposition][existingIndex].occurences + 1; letters[charposition][existingIndex].totalscore = letters[charposition][existingIndex].totalscore + score; } } void PostProcess::clear() { for (int i = 0; i < letters.size(); i++) { letters[i].clear(); } letters.resize(0); unknownCharPositions.clear(); unknownCharPositions.resize(0); allPossibilities.clear(); allPossibilitiesLetters.clear(); //allPossibilities.resize(0); bestChars = ""; matchesTemplate = false; } void PostProcess::analyze(string templateregion, int topn) { timespec startTime; getTimeMonotonic(&startTime); // Get a list of missing positions for (int i = letters.size() -1; i >= 0; i--) { if (letters[i].size() == 0) { unknownCharPositions.push_back(i); } } if (letters.size() == 0) return; // Sort the letters as they are for (int i = 0; i < letters.size(); i++) { if (letters[i].size() > 0) std::stable_sort(letters[i].begin(), letters[i].end(), letterCompare); } if (this->config->debugPostProcess) { // Print all letters for (int i = 0; i < letters.size(); i++) { for (int j = 0; j < letters[i].size(); j++) cout << "PostProcess Line " << letters[i][j].line_index << " Letter: " << letters[i][j].charposition << " " << letters[i][j].letter << " -- score: " << letters[i][j].totalscore << " -- occurences: " << letters[i][j].occurences << endl; } } timespec permutationStartTime; getTimeMonotonic(&permutationStartTime); findAllPermutations(templateregion, topn); if (config->debugTiming) { timespec permutationEndTime; getTimeMonotonic(&permutationEndTime); cout << " -- PostProcess Permutation Time: " << diffclock(permutationStartTime, permutationEndTime) << "ms." << endl; } if (allPossibilities.size() > 0) { bestChars = allPossibilities[0].letters; for (int z = 0; z < allPossibilities.size(); z++) { if (allPossibilities[z].matchesTemplate) { bestChars = allPossibilities[z].letters; break; } } // Now adjust the confidence scores to a percentage value float maxPercentScore = calculateMaxConfidenceScore(); float highestRelativeScore = (float) allPossibilities[0].totalscore; for (int i = 0; i < allPossibilities.size(); i++) { allPossibilities[i].totalscore = maxPercentScore * (allPossibilities[i].totalscore / highestRelativeScore); } } if (this->config->debugPostProcess) { // Print top words for (int i = 0; i < allPossibilities.size(); i++) { cout << "Top " << topn << " Possibilities: " << allPossibilities[i].letters << " :\t" << allPossibilities[i].totalscore; if (allPossibilities[i].letters == bestChars) cout << " <--- "; cout << endl; } cout << allPossibilities.size() << " total permutations" << endl; } if (config->debugTiming) { timespec endTime; getTimeMonotonic(&endTime); cout << "PostProcess Time: " << diffclock(startTime, endTime) << "ms." << endl; } if (this->config->debugPostProcess) cout << "PostProcess Analysis Complete: " << bestChars << " -- MATCH: " << matchesTemplate << endl; } bool PostProcess::regionIsValid(std::string templateregion) { return rules.find(templateregion) != rules.end(); } float PostProcess::calculateMaxConfidenceScore() { // Take the best score for each char position and average it. float totalScore = 0; int numScores = 0; // Get a list of missing positions for (int i = 0; i < letters.size(); i++) { if (letters[i].size() > 0) { totalScore += (letters[i][0].totalscore / letters[i][0].occurences) + config->postProcessMinConfidence; numScores++; } } if (numScores == 0) return 0; return totalScore / ((float) numScores); } const vector<PPResult> PostProcess::getResults() { return this->allPossibilities; } struct PermutationCompare { bool operator() (pair<float,vector<int> > &a, pair<float,vector<int> > &b) { return (a.first < b.first); } }; void PostProcess::findAllPermutations(string templateregion, int topn) { // use a priority queue to process permutations in highest scoring order priority_queue<pair<float,vector<int> >, vector<pair<float,vector<int> > >, PermutationCompare> permutations; set<float> permutationHashes; // push the first word onto the queue float totalscore = 0; for (int i=0; i<letters.size(); i++) { if (letters[i].size() > 0) totalscore += letters[i][0].totalscore; } vector<int> v(letters.size()); permutations.push(make_pair(totalscore, v)); int consecutiveNonMatches = 0; while (permutations.size() > 0) { // get the top permutation and analyze pair<float, vector<int> > topPermutation = permutations.top(); if (analyzePermutation(topPermutation.second, templateregion, topn) == true) consecutiveNonMatches = 0; else consecutiveNonMatches += 1; permutations.pop(); if (allPossibilities.size() >= topn || consecutiveNonMatches >= (topn*2)) break; // add child permutations to queue for (int i=0; i<letters.size(); i++) { // no more permutations with this letter if (topPermutation.second[i]+1 >= letters[i].size()) continue; pair<float, vector<int> > childPermutation = topPermutation; childPermutation.first -= letters[i][topPermutation.second[i]].totalscore - letters[i][topPermutation.second[i] + 1].totalscore; childPermutation.second[i] += 1; // ignore permutations that have already been visited (assume that score is a good hash for permutation) if (permutationHashes.end() != permutationHashes.find(childPermutation.first)) continue; permutations.push(childPermutation); permutationHashes.insert(childPermutation.first); } } } bool PostProcess::analyzePermutation(vector<int> letterIndices, string templateregion, int topn) { PPResult possibility; possibility.letters = ""; possibility.totalscore = 0; possibility.matchesTemplate = false; int plate_char_length = 0; int last_line = 0; for (int i = 0; i < letters.size(); i++) { if (letters[i].size() == 0) continue; Letter letter = letters[i][letterIndices[i]]; // Add a "\n" on new lines if (letter.line_index != last_line) { possibility.letters = possibility.letters + "\n"; } last_line = letter.line_index; if (letter.letter != SKIP_CHAR) { possibility.letters = possibility.letters + letter.letter; possibility.letter_details.push_back(letter); plate_char_length += 1; } possibility.totalscore = possibility.totalscore + letter.totalscore; } // ignore plates that don't fit the length requirements if (plate_char_length < config->postProcessMinCharacters || plate_char_length > config->postProcessMaxCharacters) return false; // Apply templates if (templateregion != "") { vector<RegexRule*> regionRules = rules[templateregion]; for (int i = 0; i < regionRules.size(); i++) { possibility.matchesTemplate = regionRules[i]->match(possibility.letters); if (possibility.matchesTemplate) { possibility.letters = regionRules[i]->filterSkips(possibility.letters); break; } } } // ignore duplicate words if (allPossibilitiesLetters.end() != allPossibilitiesLetters.find(possibility.letters)) return false; // If mustMatchPattern is toggled in the config and a template is provided, // only include this result if there is a pattern match if (!config->mustMatchPattern || templateregion.size() == 0 || (config->mustMatchPattern && possibility.matchesTemplate)) { allPossibilities.push_back(possibility); allPossibilitiesLetters.insert(possibility.letters); return true; } return false; } std::vector<string> PostProcess::getPatterns() { vector<string> v; for(map<string,std::vector<RegexRule*> >::iterator it = rules.begin(); it != rules.end(); ++it) { v.push_back(it->first); } return v; } bool letterCompare( const Letter &left, const Letter &right ) { if (left.totalscore < right.totalscore) return false; return true; } }<|endoftext|>
<commit_before>/** * \file prastar.cc * * * * \author Seth Lemons * \date 2008-11-19 */ #include <assert.h> #include <math.h> #include <errno.h> #include <vector> #include <limits> extern "C" { #include "lockfree/include/atomic.h" } #include "util/timer.h" #include "util/mutex.h" #include "util/msg_buffer.h" #include "prastar.h" #include "projection.h" #include "search.h" #include "state.h" using namespace std; PRAStar::PRAStarThread::PRAStarThread(PRAStar *p, vector<PRAStarThread *> *threads, CompletionCounter* cc) : p(p), threads(threads), cc(cc), q_empty(true) { time_spinning = 0; out_qs.resize(threads->size(), NULL); completed = false; } PRAStar::PRAStarThread::~PRAStarThread(void) { vector<MsgBuffer<State*> *>::iterator i; for (i = out_qs.begin(); i != out_qs.end(); i++) if (*i) delete *i; } vector<State*> *PRAStar::PRAStarThread::get_queue(void) { return &q; } Mutex *PRAStar::PRAStarThread::get_mutex(void) { return &mutex; } void PRAStar::PRAStarThread::post_send(void *t) { PRAStarThread *thr = (PRAStarThread*) t; if (thr->completed) { thr->cc->uncomplete(); thr->completed = false; } thr->q_empty = false; } bool PRAStar::PRAStarThread::flush_sends(void) { unsigned int i; bool has_sends = false; for (i = 0; i < threads->size(); i += 1) { if (!out_qs[i]) continue; if (out_qs[i]) { out_qs[i]->try_flush(); if (!out_qs[i]->is_empty()) has_sends = true; } } return has_sends; } /** * Flush the queue */ void PRAStar::PRAStarThread::flush_receives(bool has_sends) { // wait for either completion or more nodes to expand if (open.empty()) mutex.lock(); else if (!mutex.try_lock()) return; if (q_empty && !has_sends) { if (!open.empty()) { mutex.unlock(); return; } completed = true; cc->complete(); // busy wait mutex.unlock(); while (q_empty && !cc->is_complete() && !p->is_done()) ; mutex.lock(); // we are done, just return if (cc->is_complete()) { assert(q_empty); mutex.unlock(); return; } } // got some stuff on the queue, lets do duplicate detection // and add stuff to the open list for (unsigned int i = 0; i < q.size(); i += 1) { State *c = q[i]; if (c->get_f() >= p->bound.read()) { delete c; continue; } State *dup = closed.lookup(c); if (dup){ if (dup->get_g() > c->get_g()) { dup->update(c->get_parent(), c->get_c(), c->get_g()); if (dup->is_open()) open.see_update(dup); else open.add(dup); } delete c; } else{ open.add(c); closed.add(c); } } q.clear(); q_empty = true; mutex.unlock(); } void PRAStar::PRAStarThread::send_state(State *c) { /* unsigned long hash = p->project->project(c); */ unsigned long hash = p->use_abstraction ? p->project->project(c) : c->hash(); unsigned int dest_tid = threads->at(hash % p->n_threads)->get_id(); bool self_add = dest_tid == this->get_id(); assert (p->n_threads != 1 || self_add); if (self_add) { State *dup = closed.lookup(c); if (dup){ if (dup->get_g() > c->get_g()) { dup->update(c->get_parent(), c->get_c(), c->get_g()); if (dup->is_open()) open.see_update(dup); else open.add(dup); } delete c; } else{ open.add(c); closed.add(c); } return; } // not a self add // // Do a buffered send, in which case we can just sit on a lock // because there is no work to do anyway. if (!out_qs[dest_tid]) { Mutex *lk = threads->at(dest_tid)->get_mutex(); vector<State*> *qu = threads->at(dest_tid)->get_queue(); out_qs[dest_tid] = new MsgBuffer<State*>(lk, qu, post_send, threads->at(dest_tid)); } out_qs[dest_tid]->try_send(c); } State *PRAStar::PRAStarThread::take(void) { Timer t; bool entered_loop = false; t.start(); while (open.empty() || !q_empty) { entered_loop = true; bool has_sends = flush_sends(); flush_receives(has_sends); if (cc->is_complete()){ p->set_done(); return NULL; } } t.stop(); if (entered_loop) time_spinning += t.get_wall_time(); State *ret = NULL; if (!p->is_done()) ret = open.take(); return ret; } /** * Run the search thread. */ void PRAStar::PRAStarThread::run(void){ vector<State *> *children = NULL; while(!p->is_done()){ State *s = take(); if (s == NULL) continue; if (s->get_f() >= p->bound.read()) { open.prune(); continue; } if (s->is_goal()) { p->set_path(s->get_path()); } children = p->expand(s); for (unsigned int i = 0; i < children->size(); i += 1) { State *c = children->at(i); if (c->get_f() < p->bound.read()) send_state(c); else delete c; } delete children; } } /************************************************************/ PRAStar::PRAStar(unsigned int n_threads, bool use_abst) : n_threads(n_threads), bound(fp_infinity), project(NULL), path(NULL), use_abstraction(use_abst){ done = false; } PRAStar::~PRAStar(void) { for (iter = threads.begin(); iter != threads.end(); iter++) delete (*iter); } void PRAStar::set_done() { mutex.lock(); done = true; mutex.unlock(); } bool PRAStar::is_done() { return done; } void PRAStar::set_path(vector<State *> *p) { mutex.lock(); if (this->path == NULL || this->path->at(0)->get_g() > p->at(0)->get_g()){ this->path = p; bound.set(p->at(0)->get_g()); } mutex.unlock(); } bool PRAStar::has_path() { bool ret; ret = (path != NULL); return ret; } vector<State *> *PRAStar::search(Timer *timer, State *init) { project = init->get_domain()->get_projection(); CompletionCounter cc = CompletionCounter(n_threads); threads.resize(n_threads, NULL); for (unsigned int i = 0; i < n_threads; i += 1) threads.at(i) = new PRAStarThread(this, &threads, &cc); if (use_abstraction) threads.at(project->project(init)%n_threads)->open.add(init); else threads.at(init->hash() % n_threads)->open.add(init); for (iter = threads.begin(); iter != threads.end(); iter++) { (*iter)->start(); } for (iter = threads.begin(); iter != threads.end(); iter++) (*iter)->join(); return path; } void PRAStar::output_stats(void) { time_spinning = 0.0; max_open_size = 0; avg_open_size = 0; for (iter = threads.begin(); iter != threads.end(); iter++) { time_spinning += (*iter)->time_spinning; avg_open_size += (*iter)->open.get_avg_size(); if ((*iter)->open.get_max_size() > max_open_size) max_open_size = (*iter)->open.get_max_size(); } avg_open_size /= n_threads; cout << "total-time-acquiring-locks: " << Mutex::get_total_lock_acquisition_time() << endl; cout << "average-time-acquiring-locks: " << Mutex::get_avg_lock_acquisition_time() << endl; cout << "total-time-waiting: " << time_spinning << endl; cout << "avgerage-time-waiting: " << time_spinning / n_threads << endl; cout << "average-open-size: " << avg_open_size << endl; cout << "max-open-size: " << max_open_size << endl; } <commit_msg>Fix a typeo in PRA* output.<commit_after>/** * \file prastar.cc * * * * \author Seth Lemons * \date 2008-11-19 */ #include <assert.h> #include <math.h> #include <errno.h> #include <vector> #include <limits> extern "C" { #include "lockfree/include/atomic.h" } #include "util/timer.h" #include "util/mutex.h" #include "util/msg_buffer.h" #include "prastar.h" #include "projection.h" #include "search.h" #include "state.h" using namespace std; PRAStar::PRAStarThread::PRAStarThread(PRAStar *p, vector<PRAStarThread *> *threads, CompletionCounter* cc) : p(p), threads(threads), cc(cc), q_empty(true) { time_spinning = 0; out_qs.resize(threads->size(), NULL); completed = false; } PRAStar::PRAStarThread::~PRAStarThread(void) { vector<MsgBuffer<State*> *>::iterator i; for (i = out_qs.begin(); i != out_qs.end(); i++) if (*i) delete *i; } vector<State*> *PRAStar::PRAStarThread::get_queue(void) { return &q; } Mutex *PRAStar::PRAStarThread::get_mutex(void) { return &mutex; } void PRAStar::PRAStarThread::post_send(void *t) { PRAStarThread *thr = (PRAStarThread*) t; if (thr->completed) { thr->cc->uncomplete(); thr->completed = false; } thr->q_empty = false; } bool PRAStar::PRAStarThread::flush_sends(void) { unsigned int i; bool has_sends = false; for (i = 0; i < threads->size(); i += 1) { if (!out_qs[i]) continue; if (out_qs[i]) { out_qs[i]->try_flush(); if (!out_qs[i]->is_empty()) has_sends = true; } } return has_sends; } /** * Flush the queue */ void PRAStar::PRAStarThread::flush_receives(bool has_sends) { // wait for either completion or more nodes to expand if (open.empty()) mutex.lock(); else if (!mutex.try_lock()) return; if (q_empty && !has_sends) { if (!open.empty()) { mutex.unlock(); return; } completed = true; cc->complete(); // busy wait mutex.unlock(); while (q_empty && !cc->is_complete() && !p->is_done()) ; mutex.lock(); // we are done, just return if (cc->is_complete()) { assert(q_empty); mutex.unlock(); return; } } // got some stuff on the queue, lets do duplicate detection // and add stuff to the open list for (unsigned int i = 0; i < q.size(); i += 1) { State *c = q[i]; if (c->get_f() >= p->bound.read()) { delete c; continue; } State *dup = closed.lookup(c); if (dup){ if (dup->get_g() > c->get_g()) { dup->update(c->get_parent(), c->get_c(), c->get_g()); if (dup->is_open()) open.see_update(dup); else open.add(dup); } delete c; } else{ open.add(c); closed.add(c); } } q.clear(); q_empty = true; mutex.unlock(); } void PRAStar::PRAStarThread::send_state(State *c) { /* unsigned long hash = p->project->project(c); */ unsigned long hash = p->use_abstraction ? p->project->project(c) : c->hash(); unsigned int dest_tid = threads->at(hash % p->n_threads)->get_id(); bool self_add = dest_tid == this->get_id(); assert (p->n_threads != 1 || self_add); if (self_add) { State *dup = closed.lookup(c); if (dup){ if (dup->get_g() > c->get_g()) { dup->update(c->get_parent(), c->get_c(), c->get_g()); if (dup->is_open()) open.see_update(dup); else open.add(dup); } delete c; } else{ open.add(c); closed.add(c); } return; } // not a self add // // Do a buffered send, in which case we can just sit on a lock // because there is no work to do anyway. if (!out_qs[dest_tid]) { Mutex *lk = threads->at(dest_tid)->get_mutex(); vector<State*> *qu = threads->at(dest_tid)->get_queue(); out_qs[dest_tid] = new MsgBuffer<State*>(lk, qu, post_send, threads->at(dest_tid)); } out_qs[dest_tid]->try_send(c); } State *PRAStar::PRAStarThread::take(void) { Timer t; bool entered_loop = false; t.start(); while (open.empty() || !q_empty) { entered_loop = true; bool has_sends = flush_sends(); flush_receives(has_sends); if (cc->is_complete()){ p->set_done(); return NULL; } } t.stop(); if (entered_loop) time_spinning += t.get_wall_time(); State *ret = NULL; if (!p->is_done()) ret = open.take(); return ret; } /** * Run the search thread. */ void PRAStar::PRAStarThread::run(void){ vector<State *> *children = NULL; while(!p->is_done()){ State *s = take(); if (s == NULL) continue; if (s->get_f() >= p->bound.read()) { open.prune(); continue; } if (s->is_goal()) { p->set_path(s->get_path()); } children = p->expand(s); for (unsigned int i = 0; i < children->size(); i += 1) { State *c = children->at(i); if (c->get_f() < p->bound.read()) send_state(c); else delete c; } delete children; } } /************************************************************/ PRAStar::PRAStar(unsigned int n_threads, bool use_abst) : n_threads(n_threads), bound(fp_infinity), project(NULL), path(NULL), use_abstraction(use_abst){ done = false; } PRAStar::~PRAStar(void) { for (iter = threads.begin(); iter != threads.end(); iter++) delete (*iter); } void PRAStar::set_done() { mutex.lock(); done = true; mutex.unlock(); } bool PRAStar::is_done() { return done; } void PRAStar::set_path(vector<State *> *p) { mutex.lock(); if (this->path == NULL || this->path->at(0)->get_g() > p->at(0)->get_g()){ this->path = p; bound.set(p->at(0)->get_g()); } mutex.unlock(); } bool PRAStar::has_path() { bool ret; ret = (path != NULL); return ret; } vector<State *> *PRAStar::search(Timer *timer, State *init) { project = init->get_domain()->get_projection(); CompletionCounter cc = CompletionCounter(n_threads); threads.resize(n_threads, NULL); for (unsigned int i = 0; i < n_threads; i += 1) threads.at(i) = new PRAStarThread(this, &threads, &cc); if (use_abstraction) threads.at(project->project(init)%n_threads)->open.add(init); else threads.at(init->hash() % n_threads)->open.add(init); for (iter = threads.begin(); iter != threads.end(); iter++) { (*iter)->start(); } for (iter = threads.begin(); iter != threads.end(); iter++) (*iter)->join(); return path; } void PRAStar::output_stats(void) { time_spinning = 0.0; max_open_size = 0; avg_open_size = 0; for (iter = threads.begin(); iter != threads.end(); iter++) { time_spinning += (*iter)->time_spinning; avg_open_size += (*iter)->open.get_avg_size(); if ((*iter)->open.get_max_size() > max_open_size) max_open_size = (*iter)->open.get_max_size(); } avg_open_size /= n_threads; cout << "total-time-acquiring-locks: " << Mutex::get_total_lock_acquisition_time() << endl; cout << "average-time-acquiring-locks: " << Mutex::get_avg_lock_acquisition_time() << endl; cout << "total-time-waiting: " << time_spinning << endl; cout << "average-time-waiting: " << time_spinning / n_threads << endl; cout << "average-open-size: " << avg_open_size << endl; cout << "max-open-size: " << max_open_size << endl; } <|endoftext|>
<commit_before>#include <Python.h> #include "structmember.h" #include <cassert> #include <string> #include <iostream> #include <indri/CompressedCollection.hpp> #include <indri/DiskIndex.hpp> #include <indri/QueryEnvironment.hpp> #include <indri/Path.hpp> using std::string; #define CHECK_EQ(first, second) assert(first == second) // Index typedef struct { PyObject_HEAD indri::api::Parameters* parameters_; indri::collection::CompressedCollection* collection_; indri::index::DiskIndex* index_; indri::api::QueryEnvironment* query_env_; } Index; static void Index_dealloc(Index* self) { self->ob_type->tp_free((PyObject*) self); self->collection_->close(); self->index_->close(); self->query_env_->close(); delete self->parameters_; delete self->collection_; delete self->index_; delete self->query_env_; } static PyObject* Index_new(PyTypeObject* type, PyObject* args, PyObject* kwds) { Index* self; self = (Index*) type->tp_alloc(type, 0); if (self != NULL) { self->parameters_ = new indri::api::Parameters(); self->collection_ = new indri::collection::CompressedCollection(); self->index_ = new indri::index::DiskIndex(); self->query_env_ = new indri::api::QueryEnvironment(); } return (PyObject*) self; } static int Index_init(Index* self, PyObject* args, PyObject* kwds) { PyObject* repository_path_object = NULL; static char* kwlist[] = {"repository_path", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "S", kwlist, &repository_path_object)) { return -1; } const char* repository_path = PyString_AsString(repository_path_object); // Load parameters. self->parameters_->loadFile(indri::file::Path::combine(repository_path, "manifest")); const std::string collection_path = indri::file::Path::combine(repository_path, "collection"); try { self->collection_->open(collection_path); } catch (const lemur::api::Exception& e) { PyErr_SetString(PyExc_IOError, e.what().c_str()); return -1; } // Load index. std::string index_path = "index"; indri::api::Parameters container = (*self->parameters_)["indexes"]; if(container.exists("index")) { indri::api::Parameters indexes = container["index"]; if (indexes.size() != 1) { PyErr_SetString(PyExc_IOError, "Indri repository contain more than one index."); return -1; } index_path = indri::file::Path::combine( index_path, (std::string) indexes[static_cast<size_t>(0)]); } else { PyErr_SetString(PyExc_IOError, "Indri repository does not contain an index."); return -1; } try { self->index_->open(repository_path, index_path); } catch (const lemur::api::Exception& e) { PyErr_SetString(PyExc_IOError, e.what().c_str()); return -1; } try { self->query_env_->addIndex(repository_path); } catch (const lemur::api::Exception& e) { PyErr_SetString(PyExc_IOError, e.what().c_str()); return -1; } return 0; } static PyMemberDef Index_members[] = { {NULL} /* Sentinel */ }; static PyObject* Index_document(Index* self, PyObject* args) { int int_document_id; if (!PyArg_ParseTuple(args, "i", &int_document_id)) { return NULL; } if (int_document_id < self->index_->documentBase() || int_document_id >= self->index_->documentMaximum()) { PyErr_SetString( PyExc_IndexError, "Specified internal document identifier is out of bounds."); return NULL; } const string ext_document_id = self->collection_->retrieveMetadatum( int_document_id, "docno"); const indri::index::TermList* const term_list = self->index_->termList( int_document_id); PyObject* terms = PyTuple_New(term_list->terms().size()); indri::utility::greedy_vector<lemur::api::TERMID_T>::const_iterator term_it = term_list->terms().begin(); Py_ssize_t pos = 0; for (; term_it != term_list->terms().end(); ++term_it, ++pos) { PyTuple_SetItem(terms, pos, PyInt_FromLong(*term_it)); } delete term_list; return PyTuple_Pack(2, PyString_FromString(ext_document_id.c_str()), terms); } static PyObject* Index_document_base(Index* self) { return PyInt_FromLong(self->index_->documentBase()); } static PyObject* Index_maximum_document(Index* self) { return PyInt_FromLong(self->index_->documentMaximum()); } static PyObject* Index_run_query(Index* self, PyObject* args) { char* query_str; long results_requested = 100; if (!PyArg_ParseTuple(args, "s|i", &query_str, &results_requested)) { return NULL; } const std::vector<indri::api::ScoredExtentResult> query_results = self->query_env_->runQuery(query_str, results_requested); PyObject* results = PyTuple_New(query_results.size()); std::vector<indri::api::ScoredExtentResult>::const_iterator it = query_results.begin(); Py_ssize_t pos = 0; for (; it != query_results.end(); ++it, ++pos) { PyTuple_SetItem( results, pos, PyTuple_Pack(2, PyInt_FromLong(it->document), PyFloat_FromDouble(it->score))); } return results; } static PyObject* Index_get_dictionary(Index* self, PyObject* args) { indri::index::VocabularyIterator* const vocabulary_it = self->index_->vocabularyIterator(); PyObject* const token2id = PyDict_New(); PyObject* const id2token = PyDict_New(); PyObject* const id2df = PyDict_New(); vocabulary_it->startIteration(); while (!vocabulary_it->finished()) { indri::index::DiskTermData* const term_data = vocabulary_it->currentEntry(); const lemur::api::TERMID_T term_id = term_data->termID; const string term = term_data->termData->term; const unsigned int document_frequency = term_data->termData->corpus.documentCount; PyDict_SetItemString(token2id, term.c_str(), PyInt_FromLong(term_id)); PyDict_SetItem(id2token, PyInt_FromLong(term_id), PyString_FromString(term.c_str())); PyDict_SetItem(id2df, PyInt_FromLong(term_id), PyInt_FromLong(document_frequency)); vocabulary_it->nextEntry(); } delete vocabulary_it; CHECK_EQ(PyDict_Size(token2id), self->index_->uniqueTermCount()); CHECK_EQ(PyDict_Size(id2token), self->index_->uniqueTermCount()); CHECK_EQ(PyDict_Size(id2df), self->index_->uniqueTermCount()); return PyTuple_Pack(3, token2id, id2token, id2df); } static PyMethodDef Index_methods[] = { {"document", (PyCFunction) Index_document, METH_VARARGS, "Return a document (ext_document_id, terms) pair."}, {"document_base", (PyCFunction) Index_document_base, METH_NOARGS, "Returns the lower bound document identifier (inclusive)."}, {"maximum_document", (PyCFunction) Index_maximum_document, METH_NOARGS, "Returns the upper bound document identifier (exclusive)."}, {"query", (PyCFunction) Index_run_query, METH_VARARGS, "Queries an Indri index."}, {"get_dictionary", (PyCFunction) Index_get_dictionary, METH_NOARGS, "Extracts the dictionary from the Index."}, {NULL} /* Sentinel */ }; static PyTypeObject IndexType = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ "pyndri.Index", /*tp_name*/ sizeof(Index), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor) Index_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 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 | Py_TPFLAGS_BASETYPE, /*tp_flags*/ "Index objects", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ Index_methods, /* tp_methods */ Index_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc) Index_init, /* tp_init */ 0, /* tp_alloc */ Index_new, /* tp_new */ }; // Module methods. static PyMethodDef PyndriMethods[] = { {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC initpyndri(void) { if (PyType_Ready(&IndexType) < 0) { return; } PyObject* const module = Py_InitModule("pyndri", PyndriMethods); Py_INCREF(&IndexType); PyModule_AddObject(module, "Index", (PyObject*) &IndexType); } <commit_msg>Adds additional check for document frequencies.<commit_after>#include <Python.h> #include "structmember.h" #include <cassert> #include <string> #include <iostream> #include <indri/CompressedCollection.hpp> #include <indri/DiskIndex.hpp> #include <indri/QueryEnvironment.hpp> #include <indri/Path.hpp> using std::string; #define CHECK_EQ(first, second) assert(first == second) #define CHECK_GT(first, second) assert(first > second) // Index typedef struct { PyObject_HEAD indri::api::Parameters* parameters_; indri::collection::CompressedCollection* collection_; indri::index::DiskIndex* index_; indri::api::QueryEnvironment* query_env_; } Index; static void Index_dealloc(Index* self) { self->ob_type->tp_free((PyObject*) self); self->collection_->close(); self->index_->close(); self->query_env_->close(); delete self->parameters_; delete self->collection_; delete self->index_; delete self->query_env_; } static PyObject* Index_new(PyTypeObject* type, PyObject* args, PyObject* kwds) { Index* self; self = (Index*) type->tp_alloc(type, 0); if (self != NULL) { self->parameters_ = new indri::api::Parameters(); self->collection_ = new indri::collection::CompressedCollection(); self->index_ = new indri::index::DiskIndex(); self->query_env_ = new indri::api::QueryEnvironment(); } return (PyObject*) self; } static int Index_init(Index* self, PyObject* args, PyObject* kwds) { PyObject* repository_path_object = NULL; static char* kwlist[] = {"repository_path", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "S", kwlist, &repository_path_object)) { return -1; } const char* repository_path = PyString_AsString(repository_path_object); // Load parameters. self->parameters_->loadFile(indri::file::Path::combine(repository_path, "manifest")); const std::string collection_path = indri::file::Path::combine(repository_path, "collection"); try { self->collection_->open(collection_path); } catch (const lemur::api::Exception& e) { PyErr_SetString(PyExc_IOError, e.what().c_str()); return -1; } // Load index. std::string index_path = "index"; indri::api::Parameters container = (*self->parameters_)["indexes"]; if(container.exists("index")) { indri::api::Parameters indexes = container["index"]; if (indexes.size() != 1) { PyErr_SetString(PyExc_IOError, "Indri repository contain more than one index."); return -1; } index_path = indri::file::Path::combine( index_path, (std::string) indexes[static_cast<size_t>(0)]); } else { PyErr_SetString(PyExc_IOError, "Indri repository does not contain an index."); return -1; } try { self->index_->open(repository_path, index_path); } catch (const lemur::api::Exception& e) { PyErr_SetString(PyExc_IOError, e.what().c_str()); return -1; } try { self->query_env_->addIndex(repository_path); } catch (const lemur::api::Exception& e) { PyErr_SetString(PyExc_IOError, e.what().c_str()); return -1; } return 0; } static PyMemberDef Index_members[] = { {NULL} /* Sentinel */ }; static PyObject* Index_document(Index* self, PyObject* args) { int int_document_id; if (!PyArg_ParseTuple(args, "i", &int_document_id)) { return NULL; } if (int_document_id < self->index_->documentBase() || int_document_id >= self->index_->documentMaximum()) { PyErr_SetString( PyExc_IndexError, "Specified internal document identifier is out of bounds."); return NULL; } const string ext_document_id = self->collection_->retrieveMetadatum( int_document_id, "docno"); const indri::index::TermList* const term_list = self->index_->termList( int_document_id); PyObject* terms = PyTuple_New(term_list->terms().size()); indri::utility::greedy_vector<lemur::api::TERMID_T>::const_iterator term_it = term_list->terms().begin(); Py_ssize_t pos = 0; for (; term_it != term_list->terms().end(); ++term_it, ++pos) { PyTuple_SetItem(terms, pos, PyInt_FromLong(*term_it)); } delete term_list; return PyTuple_Pack(2, PyString_FromString(ext_document_id.c_str()), terms); } static PyObject* Index_document_base(Index* self) { return PyInt_FromLong(self->index_->documentBase()); } static PyObject* Index_maximum_document(Index* self) { return PyInt_FromLong(self->index_->documentMaximum()); } static PyObject* Index_run_query(Index* self, PyObject* args) { char* query_str; long results_requested = 100; if (!PyArg_ParseTuple(args, "s|i", &query_str, &results_requested)) { return NULL; } const std::vector<indri::api::ScoredExtentResult> query_results = self->query_env_->runQuery(query_str, results_requested); PyObject* results = PyTuple_New(query_results.size()); std::vector<indri::api::ScoredExtentResult>::const_iterator it = query_results.begin(); Py_ssize_t pos = 0; for (; it != query_results.end(); ++it, ++pos) { PyTuple_SetItem( results, pos, PyTuple_Pack(2, PyInt_FromLong(it->document), PyFloat_FromDouble(it->score))); } return results; } static PyObject* Index_get_dictionary(Index* self, PyObject* args) { indri::index::VocabularyIterator* const vocabulary_it = self->index_->vocabularyIterator(); PyObject* const token2id = PyDict_New(); PyObject* const id2token = PyDict_New(); PyObject* const id2df = PyDict_New(); vocabulary_it->startIteration(); while (!vocabulary_it->finished()) { indri::index::DiskTermData* const term_data = vocabulary_it->currentEntry(); const lemur::api::TERMID_T term_id = term_data->termID; const string term = term_data->termData->term; const unsigned int document_frequency = term_data->termData->corpus.documentCount; CHECK_GT(document_frequency, 0); PyDict_SetItemString(token2id, term.c_str(), PyInt_FromLong(term_id)); PyDict_SetItem(id2token, PyInt_FromLong(term_id), PyString_FromString(term.c_str())); PyDict_SetItem(id2df, PyInt_FromLong(term_id), PyInt_FromLong(document_frequency)); vocabulary_it->nextEntry(); } delete vocabulary_it; CHECK_EQ(PyDict_Size(token2id), self->index_->uniqueTermCount()); CHECK_EQ(PyDict_Size(id2token), self->index_->uniqueTermCount()); CHECK_EQ(PyDict_Size(id2df), self->index_->uniqueTermCount()); return PyTuple_Pack(3, token2id, id2token, id2df); } static PyMethodDef Index_methods[] = { {"document", (PyCFunction) Index_document, METH_VARARGS, "Return a document (ext_document_id, terms) pair."}, {"document_base", (PyCFunction) Index_document_base, METH_NOARGS, "Returns the lower bound document identifier (inclusive)."}, {"maximum_document", (PyCFunction) Index_maximum_document, METH_NOARGS, "Returns the upper bound document identifier (exclusive)."}, {"query", (PyCFunction) Index_run_query, METH_VARARGS, "Queries an Indri index."}, {"get_dictionary", (PyCFunction) Index_get_dictionary, METH_NOARGS, "Extracts the dictionary from the Index."}, {NULL} /* Sentinel */ }; static PyTypeObject IndexType = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ "pyndri.Index", /*tp_name*/ sizeof(Index), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor) Index_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 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 | Py_TPFLAGS_BASETYPE, /*tp_flags*/ "Index objects", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ Index_methods, /* tp_methods */ Index_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc) Index_init, /* tp_init */ 0, /* tp_alloc */ Index_new, /* tp_new */ }; // Module methods. static PyMethodDef PyndriMethods[] = { {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC initpyndri(void) { if (PyType_Ready(&IndexType) < 0) { return; } PyObject* const module = Py_InitModule("pyndri", PyndriMethods); Py_INCREF(&IndexType); PyModule_AddObject(module, "Index", (PyObject*) &IndexType); } <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "editortoolbar.h" #include <coreplugin/coreconstants.h> #include <coreplugin/editormanager/ieditor.h> #include <coreplugin/icore.h> #include <coreplugin/minisplitter.h> #include <coreplugin/sidebar.h> #include <coreplugin/editormanager/editorview.h> #include <coreplugin/editormanager/editormanager.h> #include <coreplugin/editormanager/openeditorsmodel.h> #include <coreplugin/editormanager/ieditor.h> #include <coreplugin/actionmanager/actionmanager.h> #include <coreplugin/actionmanager/command.h> #include <utils/parameteraction.h> #include <utils/qtcassert.h> #include <utils/styledbar.h> #include <QtCore/QSettings> #include <QtCore/QEvent> #include <QtCore/QDir> #include <QtGui/QApplication> #include <QtGui/QPlainTextEdit> #include <QtGui/QVBoxLayout> #include <QtGui/QScrollArea> #include <QtGui/QTabWidget> #include <QtGui/QToolButton> #include <QtGui/QMenu> #include <QtGui/QClipboard> #include <QtGui/QLabel> #include <QtGui/QToolBar> Q_DECLARE_METATYPE(Core::IEditor*) enum { debug = false }; namespace Core { /*! Mimic the look of the text editor toolbar as defined in e.g. EditorView::EditorView */ EditorToolBar::EditorToolBar(QWidget *parent) : Utils::StyledBar(parent), m_editorList(new QComboBox(this)), m_closeButton(new QToolButton), m_lockButton(new QToolButton), m_goBackAction(new QAction(QIcon(QLatin1String(":/help/images/previous.png")), EditorManager::tr("Go Back"), parent)), m_goForwardAction(new QAction(QIcon(QLatin1String(":/help/images/next.png")), EditorManager::tr("Go Forward"), parent)), m_activeToolBar(0), m_toolBarPlaceholder(new QWidget), m_defaultToolBar(new QWidget(this)), m_isStandalone(false) { QHBoxLayout *toolBarLayout = new QHBoxLayout(this); toolBarLayout->setMargin(0); toolBarLayout->setSpacing(0); toolBarLayout->addWidget(m_defaultToolBar); m_toolBarPlaceholder->setLayout(toolBarLayout); m_toolBarPlaceholder->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); m_defaultToolBar->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); m_activeToolBar = m_defaultToolBar; m_editorsListModel = EditorManager::instance()->openedEditorsModel(); connect(m_goBackAction, SIGNAL(triggered()), this, SIGNAL(goBackClicked())); connect(m_goForwardAction, SIGNAL(triggered()), this, SIGNAL(goForwardClicked())); m_editorList->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); m_editorList->setMinimumContentsLength(20); m_editorList->setModel(m_editorsListModel); m_editorList->setMaxVisibleItems(40); m_editorList->setContextMenuPolicy(Qt::CustomContextMenu); m_lockButton->setAutoRaise(true); m_lockButton->setProperty("type", QLatin1String("dockbutton")); m_lockButton->setVisible(false); m_closeButton->setAutoRaise(true); m_closeButton->setIcon(QIcon(":/core/images/closebutton.png")); m_closeButton->setProperty("type", QLatin1String("dockbutton")); m_closeButton->setEnabled(false); m_toolBarPlaceholder->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); m_backButton = new QToolButton(this); m_backButton->setDefaultAction(m_goBackAction); m_forwardButton= new QToolButton(this); m_forwardButton->setDefaultAction(m_goForwardAction); QHBoxLayout *toplayout = new QHBoxLayout(this); toplayout->setSpacing(0); toplayout->setMargin(0); toplayout->addWidget(m_backButton); toplayout->addWidget(m_forwardButton); toplayout->addWidget(m_editorList); toplayout->addWidget(m_toolBarPlaceholder, 1); // Custom toolbar stretches toplayout->addWidget(m_lockButton); toplayout->addWidget(m_closeButton); setLayout(toplayout); // this signal is disconnected for standalone toolbars and replaced with // a private slot connection connect(m_editorList, SIGNAL(activated(int)), this, SIGNAL(listSelectionActivated(int))); connect(m_editorList, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(listContextMenu(QPoint))); connect(m_lockButton, SIGNAL(clicked()), this, SLOT(makeEditorWritable())); connect(m_closeButton, SIGNAL(clicked()), this, SLOT(closeView()), Qt::QueuedConnection); ActionManager *am = ICore::instance()->actionManager(); connect(am->command(Constants::CLOSE), SIGNAL(keySequenceChanged()), this, SLOT(updateActionShortcuts())); connect(am->command(Constants::GO_BACK), SIGNAL(keySequenceChanged()), this, SLOT(updateActionShortcuts())); connect(am->command(Constants::GO_FORWARD), SIGNAL(keySequenceChanged()), this, SLOT(updateActionShortcuts())); } void EditorToolBar::removeToolbarForEditor(IEditor *editor) { QTC_ASSERT(editor, return) disconnect(editor, SIGNAL(changed()), this, SLOT(checkEditorStatus())); QWidget *toolBar = editor->toolBar(); if (toolBar != 0) { if (m_activeToolBar == toolBar) { m_activeToolBar = m_defaultToolBar; m_activeToolBar->setVisible(true); } m_toolBarPlaceholder->layout()->removeWidget(toolBar); toolBar->setVisible(false); toolBar->setParent(0); } } void EditorToolBar::closeView() { if (!currentEditor()) return; if (m_isStandalone) { EditorManager *em = ICore::instance()->editorManager(); if (IEditor *editor = currentEditor()) { em->closeEditor(editor); } } emit closeClicked(); } void EditorToolBar::addEditor(IEditor *editor) { QTC_ASSERT(editor, return) connect(editor, SIGNAL(changed()), this, SLOT(checkEditorStatus())); QWidget *toolBar = editor->toolBar(); if (toolBar && !m_isStandalone) addCenterToolBar(toolBar); updateEditorStatus(editor); } void EditorToolBar::addCenterToolBar(QWidget *toolBar) { QTC_ASSERT(toolBar, return) toolBar->setVisible(false); // will be made visible in setCurrentEditor m_toolBarPlaceholder->layout()->addWidget(toolBar); updateToolBar(toolBar); } void EditorToolBar::updateToolBar(QWidget *toolBar) { if (!toolBar) toolBar = m_defaultToolBar; if (m_activeToolBar == toolBar) return; toolBar->setVisible(true); m_activeToolBar->setVisible(false); m_activeToolBar = toolBar; } void EditorToolBar::setToolbarCreationFlags(ToolbarCreationFlags flags) { m_isStandalone = flags & FlagsStandalone; if (m_isStandalone) { EditorManager *em = EditorManager::instance(); connect(em, SIGNAL(currentEditorChanged(Core::IEditor*)), SLOT(updateEditorListSelection(Core::IEditor*))); disconnect(m_editorList, SIGNAL(activated(int)), this, SIGNAL(listSelectionActivated(int))); connect(m_editorList, SIGNAL(activated(int)), this, SLOT(changeActiveEditor(int))); } } void EditorToolBar::setCurrentEditor(IEditor *editor) { QTC_ASSERT(editor, return) m_editorList->setCurrentIndex(m_editorsListModel->indexOf(editor).row()); // If we never added the toolbar from the editor, we will never change // the editor, so there's no need to update the toolbar either. if (!m_isStandalone) updateToolBar(editor->toolBar()); updateEditorStatus(editor); } void EditorToolBar::updateEditorListSelection(IEditor *newSelection) { if (newSelection) m_editorList->setCurrentIndex(m_editorsListModel->indexOf(newSelection).row()); } void EditorToolBar::changeActiveEditor(int row) { EditorManager *em = ICore::instance()->editorManager(); QAbstractItemModel *model = m_editorList->model(); const QModelIndex modelIndex = model->index(row, 0); IEditor *editor = model->data(modelIndex, Qt::UserRole).value<IEditor*>(); if (editor) { if (editor != em->currentEditor()) em->activateEditor(editor, EditorManager::NoModeSwitch); } else { //em->activateEditor(model->index(index, 0), this); QString fileName = model->data(modelIndex, Qt::UserRole + 1).toString(); QByteArray kind = model->data(modelIndex, Qt::UserRole + 2).toByteArray(); editor = em->openEditor(fileName, kind, EditorManager::NoModeSwitch); } if (editor) { m_editorList->setCurrentIndex(m_editorsListModel->indexOf(editor).row()); } } void EditorToolBar::listContextMenu(QPoint pos) { QModelIndex index = m_editorsListModel->index(m_editorList->currentIndex(), 0); QString fileName = m_editorsListModel->data(index, Qt::UserRole + 1).toString(); if (fileName.isEmpty()) return; QMenu menu; menu.addAction(tr("Copy full path to clipboard")); if (menu.exec(m_editorList->mapToGlobal(pos))) { QApplication::clipboard()->setText(fileName); } } void EditorToolBar::makeEditorWritable() { if (currentEditor()) ICore::instance()->editorManager()->makeEditorWritable(currentEditor()); } void EditorToolBar::setCanGoBack(bool canGoBack) { m_goBackAction->setEnabled(canGoBack); } void EditorToolBar::setCanGoForward(bool canGoForward) { m_goForwardAction->setEnabled(canGoForward); } void EditorToolBar::updateActionShortcuts() { ActionManager *am = ICore::instance()->actionManager(); m_closeButton->setToolTip(am->command(Constants::CLOSE)->stringWithAppendedShortcut(EditorManager::tr("Close"))); m_goBackAction->setToolTip(am->command(Constants::GO_BACK)->action()->toolTip()); m_goForwardAction->setToolTip(am->command(Constants::GO_FORWARD)->action()->toolTip()); } IEditor *EditorToolBar::currentEditor() const { return ICore::instance()->editorManager()->currentEditor(); } void EditorToolBar::checkEditorStatus() { IEditor *editor = qobject_cast<IEditor *>(sender()); IEditor *current = currentEditor(); if (current == editor) updateEditorStatus(editor); } void EditorToolBar::updateEditorStatus(IEditor *editor) { m_lockButton->setVisible(editor != 0); m_closeButton->setEnabled(editor != 0); if (!editor || !editor->file()) { m_editorList->setToolTip(QString()); return; } m_editorList->setCurrentIndex(m_editorsListModel->indexOf(editor).row()); if (editor->file()->isReadOnly()) { m_lockButton->setIcon(QIcon(m_editorsListModel->lockedIcon())); m_lockButton->setEnabled(!editor->file()->fileName().isEmpty()); m_lockButton->setToolTip(tr("Make writable")); } else { m_lockButton->setIcon(QIcon(m_editorsListModel->unlockedIcon())); m_lockButton->setEnabled(false); m_lockButton->setToolTip(tr("File is writable")); } if (editor == currentEditor()) m_editorList->setToolTip( currentEditor()->file()->fileName().isEmpty() ? currentEditor()->displayName() : QDir::toNativeSeparators(editor->file()->fileName()) ); } void EditorToolBar::setNavigationVisible(bool isVisible) { m_goBackAction->setVisible(isVisible); m_goForwardAction->setVisible(isVisible); m_backButton->setVisible(isVisible); m_forwardButton->setVisible(isVisible); } } // Core <commit_msg>Copying path with native separators to clipboard.<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "editortoolbar.h" #include <coreplugin/coreconstants.h> #include <coreplugin/editormanager/ieditor.h> #include <coreplugin/icore.h> #include <coreplugin/minisplitter.h> #include <coreplugin/sidebar.h> #include <coreplugin/editormanager/editorview.h> #include <coreplugin/editormanager/editormanager.h> #include <coreplugin/editormanager/openeditorsmodel.h> #include <coreplugin/editormanager/ieditor.h> #include <coreplugin/actionmanager/actionmanager.h> #include <coreplugin/actionmanager/command.h> #include <utils/parameteraction.h> #include <utils/qtcassert.h> #include <utils/styledbar.h> #include <QtCore/QSettings> #include <QtCore/QEvent> #include <QtCore/QDir> #include <QtGui/QApplication> #include <QtGui/QPlainTextEdit> #include <QtGui/QVBoxLayout> #include <QtGui/QScrollArea> #include <QtGui/QTabWidget> #include <QtGui/QToolButton> #include <QtGui/QMenu> #include <QtGui/QClipboard> #include <QtGui/QLabel> #include <QtGui/QToolBar> Q_DECLARE_METATYPE(Core::IEditor*) enum { debug = false }; namespace Core { /*! Mimic the look of the text editor toolbar as defined in e.g. EditorView::EditorView */ EditorToolBar::EditorToolBar(QWidget *parent) : Utils::StyledBar(parent), m_editorList(new QComboBox(this)), m_closeButton(new QToolButton), m_lockButton(new QToolButton), m_goBackAction(new QAction(QIcon(QLatin1String(":/help/images/previous.png")), EditorManager::tr("Go Back"), parent)), m_goForwardAction(new QAction(QIcon(QLatin1String(":/help/images/next.png")), EditorManager::tr("Go Forward"), parent)), m_activeToolBar(0), m_toolBarPlaceholder(new QWidget), m_defaultToolBar(new QWidget(this)), m_isStandalone(false) { QHBoxLayout *toolBarLayout = new QHBoxLayout(this); toolBarLayout->setMargin(0); toolBarLayout->setSpacing(0); toolBarLayout->addWidget(m_defaultToolBar); m_toolBarPlaceholder->setLayout(toolBarLayout); m_toolBarPlaceholder->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); m_defaultToolBar->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); m_activeToolBar = m_defaultToolBar; m_editorsListModel = EditorManager::instance()->openedEditorsModel(); connect(m_goBackAction, SIGNAL(triggered()), this, SIGNAL(goBackClicked())); connect(m_goForwardAction, SIGNAL(triggered()), this, SIGNAL(goForwardClicked())); m_editorList->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); m_editorList->setMinimumContentsLength(20); m_editorList->setModel(m_editorsListModel); m_editorList->setMaxVisibleItems(40); m_editorList->setContextMenuPolicy(Qt::CustomContextMenu); m_lockButton->setAutoRaise(true); m_lockButton->setProperty("type", QLatin1String("dockbutton")); m_lockButton->setVisible(false); m_closeButton->setAutoRaise(true); m_closeButton->setIcon(QIcon(":/core/images/closebutton.png")); m_closeButton->setProperty("type", QLatin1String("dockbutton")); m_closeButton->setEnabled(false); m_toolBarPlaceholder->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); m_backButton = new QToolButton(this); m_backButton->setDefaultAction(m_goBackAction); m_forwardButton= new QToolButton(this); m_forwardButton->setDefaultAction(m_goForwardAction); QHBoxLayout *toplayout = new QHBoxLayout(this); toplayout->setSpacing(0); toplayout->setMargin(0); toplayout->addWidget(m_backButton); toplayout->addWidget(m_forwardButton); toplayout->addWidget(m_editorList); toplayout->addWidget(m_toolBarPlaceholder, 1); // Custom toolbar stretches toplayout->addWidget(m_lockButton); toplayout->addWidget(m_closeButton); setLayout(toplayout); // this signal is disconnected for standalone toolbars and replaced with // a private slot connection connect(m_editorList, SIGNAL(activated(int)), this, SIGNAL(listSelectionActivated(int))); connect(m_editorList, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(listContextMenu(QPoint))); connect(m_lockButton, SIGNAL(clicked()), this, SLOT(makeEditorWritable())); connect(m_closeButton, SIGNAL(clicked()), this, SLOT(closeView()), Qt::QueuedConnection); ActionManager *am = ICore::instance()->actionManager(); connect(am->command(Constants::CLOSE), SIGNAL(keySequenceChanged()), this, SLOT(updateActionShortcuts())); connect(am->command(Constants::GO_BACK), SIGNAL(keySequenceChanged()), this, SLOT(updateActionShortcuts())); connect(am->command(Constants::GO_FORWARD), SIGNAL(keySequenceChanged()), this, SLOT(updateActionShortcuts())); } void EditorToolBar::removeToolbarForEditor(IEditor *editor) { QTC_ASSERT(editor, return) disconnect(editor, SIGNAL(changed()), this, SLOT(checkEditorStatus())); QWidget *toolBar = editor->toolBar(); if (toolBar != 0) { if (m_activeToolBar == toolBar) { m_activeToolBar = m_defaultToolBar; m_activeToolBar->setVisible(true); } m_toolBarPlaceholder->layout()->removeWidget(toolBar); toolBar->setVisible(false); toolBar->setParent(0); } } void EditorToolBar::closeView() { if (!currentEditor()) return; if (m_isStandalone) { EditorManager *em = ICore::instance()->editorManager(); if (IEditor *editor = currentEditor()) { em->closeEditor(editor); } } emit closeClicked(); } void EditorToolBar::addEditor(IEditor *editor) { QTC_ASSERT(editor, return) connect(editor, SIGNAL(changed()), this, SLOT(checkEditorStatus())); QWidget *toolBar = editor->toolBar(); if (toolBar && !m_isStandalone) addCenterToolBar(toolBar); updateEditorStatus(editor); } void EditorToolBar::addCenterToolBar(QWidget *toolBar) { QTC_ASSERT(toolBar, return) toolBar->setVisible(false); // will be made visible in setCurrentEditor m_toolBarPlaceholder->layout()->addWidget(toolBar); updateToolBar(toolBar); } void EditorToolBar::updateToolBar(QWidget *toolBar) { if (!toolBar) toolBar = m_defaultToolBar; if (m_activeToolBar == toolBar) return; toolBar->setVisible(true); m_activeToolBar->setVisible(false); m_activeToolBar = toolBar; } void EditorToolBar::setToolbarCreationFlags(ToolbarCreationFlags flags) { m_isStandalone = flags & FlagsStandalone; if (m_isStandalone) { EditorManager *em = EditorManager::instance(); connect(em, SIGNAL(currentEditorChanged(Core::IEditor*)), SLOT(updateEditorListSelection(Core::IEditor*))); disconnect(m_editorList, SIGNAL(activated(int)), this, SIGNAL(listSelectionActivated(int))); connect(m_editorList, SIGNAL(activated(int)), this, SLOT(changeActiveEditor(int))); } } void EditorToolBar::setCurrentEditor(IEditor *editor) { QTC_ASSERT(editor, return) m_editorList->setCurrentIndex(m_editorsListModel->indexOf(editor).row()); // If we never added the toolbar from the editor, we will never change // the editor, so there's no need to update the toolbar either. if (!m_isStandalone) updateToolBar(editor->toolBar()); updateEditorStatus(editor); } void EditorToolBar::updateEditorListSelection(IEditor *newSelection) { if (newSelection) m_editorList->setCurrentIndex(m_editorsListModel->indexOf(newSelection).row()); } void EditorToolBar::changeActiveEditor(int row) { EditorManager *em = ICore::instance()->editorManager(); QAbstractItemModel *model = m_editorList->model(); const QModelIndex modelIndex = model->index(row, 0); IEditor *editor = model->data(modelIndex, Qt::UserRole).value<IEditor*>(); if (editor) { if (editor != em->currentEditor()) em->activateEditor(editor, EditorManager::NoModeSwitch); } else { //em->activateEditor(model->index(index, 0), this); QString fileName = model->data(modelIndex, Qt::UserRole + 1).toString(); QByteArray kind = model->data(modelIndex, Qt::UserRole + 2).toByteArray(); editor = em->openEditor(fileName, kind, EditorManager::NoModeSwitch); } if (editor) { m_editorList->setCurrentIndex(m_editorsListModel->indexOf(editor).row()); } } void EditorToolBar::listContextMenu(QPoint pos) { QModelIndex index = m_editorsListModel->index(m_editorList->currentIndex(), 0); QString fileName = m_editorsListModel->data(index, Qt::UserRole + 1).toString(); if (fileName.isEmpty()) return; QMenu menu; menu.addAction(tr("Copy full path to clipboard")); if (menu.exec(m_editorList->mapToGlobal(pos))) { QApplication::clipboard()->setText(QDir::toNativeSeparators(fileName)); } } void EditorToolBar::makeEditorWritable() { if (currentEditor()) ICore::instance()->editorManager()->makeEditorWritable(currentEditor()); } void EditorToolBar::setCanGoBack(bool canGoBack) { m_goBackAction->setEnabled(canGoBack); } void EditorToolBar::setCanGoForward(bool canGoForward) { m_goForwardAction->setEnabled(canGoForward); } void EditorToolBar::updateActionShortcuts() { ActionManager *am = ICore::instance()->actionManager(); m_closeButton->setToolTip(am->command(Constants::CLOSE)->stringWithAppendedShortcut(EditorManager::tr("Close"))); m_goBackAction->setToolTip(am->command(Constants::GO_BACK)->action()->toolTip()); m_goForwardAction->setToolTip(am->command(Constants::GO_FORWARD)->action()->toolTip()); } IEditor *EditorToolBar::currentEditor() const { return ICore::instance()->editorManager()->currentEditor(); } void EditorToolBar::checkEditorStatus() { IEditor *editor = qobject_cast<IEditor *>(sender()); IEditor *current = currentEditor(); if (current == editor) updateEditorStatus(editor); } void EditorToolBar::updateEditorStatus(IEditor *editor) { m_lockButton->setVisible(editor != 0); m_closeButton->setEnabled(editor != 0); if (!editor || !editor->file()) { m_editorList->setToolTip(QString()); return; } m_editorList->setCurrentIndex(m_editorsListModel->indexOf(editor).row()); if (editor->file()->isReadOnly()) { m_lockButton->setIcon(QIcon(m_editorsListModel->lockedIcon())); m_lockButton->setEnabled(!editor->file()->fileName().isEmpty()); m_lockButton->setToolTip(tr("Make writable")); } else { m_lockButton->setIcon(QIcon(m_editorsListModel->unlockedIcon())); m_lockButton->setEnabled(false); m_lockButton->setToolTip(tr("File is writable")); } if (editor == currentEditor()) m_editorList->setToolTip( currentEditor()->file()->fileName().isEmpty() ? currentEditor()->displayName() : QDir::toNativeSeparators(editor->file()->fileName()) ); } void EditorToolBar::setNavigationVisible(bool isVisible) { m_goBackAction->setVisible(isVisible); m_goForwardAction->setVisible(isVisible); m_backButton->setVisible(isVisible); m_forwardButton->setVisible(isVisible); } } // Core <|endoftext|>
<commit_before>#ifndef BULL_GRAPHICS_LIGHT_DIRECTIONALLIGHT_HPP #define BULL_GRAPHICS_LIGHT_DIRECTIONALLIGHT_HPP #include <Bull/Graphics/Light/AbstractLight.hpp> #include <Bull/Math/Vector/Vector3.hpp> namespace Bull { class BULL_GRAPHICS_API DirectionalLight : public AbstractLight { public: /*! \brief Default constructor * */ DirectionalLight(); /*! \brief Constructor * * \param direction The direction of the DirectionalLight * \param color The Color of the DirectionalLight * */ explicit DirectionalLight(const Vector3F& direction, const Color& color = Color::White); /*! \brief Set the direction of the DirectionalLight * * \param direction The direction * */ void setDirection(const Vector3F& direction); /*! \brief Get the direction of the DirectionalLight * * \return The direction * */ const Vector3F& getDirection() const; private: Vector3F m_direction; }; } #endif // BULL_GRAPHICS_LIGHT_DIRECTIONALLIGHT_HPP <commit_msg>[Graphics/Light] Fix some typo<commit_after>#ifndef BULL_GRAPHICS_LIGHT_DIRECTIONALLIGHT_HPP #define BULL_GRAPHICS_LIGHT_DIRECTIONALLIGHT_HPP #include <Bull/Graphics/Light/AbstractLight.hpp> #include <Bull/Math/Vector/Vector3.hpp> namespace Bull { class BULL_GRAPHICS_API DirectionalLight : public AbstractLight { public: /*! \brief Default constructor * */ DirectionalLight(); /*! \brief Constructor * * \param direction The direction of the DirectionalLight * \param color The Color of the DirectionalLight * */ explicit DirectionalLight(const Vector3F& direction, const Color& color = Color::White); /*! \brief Set the direction of the DirectionalLight * * \param direction The direction * */ void setDirection(const Vector3F& direction); /*! \brief Get the direction of the DirectionalLight * * \return The direction * */ const Vector3F& getDirection() const; private: Vector3F m_direction; }; } #endif // BULL_GRAPHICS_LIGHT_DIRECTIONALLIGHT_HPP <|endoftext|>
<commit_before>/* Copyright (c) 2009-2014, Jack Poulson All rights reserved. This file is part of Elemental and is under the BSD 2-Clause License, which can be found in the LICENSE file in the root directory, or at http://opensource.org/licenses/BSD-2-Clause */ #pragma once #ifndef EL_HERMITIANUNIFORMSPECTRUM_HPP #define EL_HERMITIANUNIFORMSPECTRUM_HPP #include "./Diagonal.hpp" #include "./Haar.hpp" #include "./Uniform.hpp" namespace El { // Draw the spectrum from the specified half-open interval on the real line, // then rotate with a Haar matrix template<typename F> inline void MakeHermitianUniformSpectrum( Matrix<F>& A, Base<F> lower=0, Base<F> upper=1 ) { DEBUG_ONLY(CallStackEntry cse("MakeHermitianUniformSpectrum")) if( A.Height() != A.Width() ) LogicError("Cannot make a non-square matrix Hermitian"); typedef Base<F> Real; const bool isComplex = IsComplex<F>::val; // Form d and D const Int n = A.Height(); std::vector<F> d( n ); for( Int j=0; j<n; ++j ) d[j] = SampleUniform<Real>( lower, upper ); Diagonal( A, d ); // Apply a Haar matrix from both sides Matrix<F> Q, t; Matrix<Real> s; ImplicitHaar( Q, t, s, n ); qr::ApplyQ( LEFT, NORMAL, Q, t, s, A ); qr::ApplyQ( RIGHT, ADJOINT, Q, t, s, A ); if( isComplex ) { const Int height = A.Height(); for( Int j=0; j<height; ++j ) A.SetImagPart( j, j, Real(0) ); } } template<typename F,Dist U,Dist V> inline void MakeHermitianUniformSpectrum ( DistMatrix<F,U,V>& A, Base<F> lower=0, Base<F> upper=1 ) { DEBUG_ONLY(CallStackEntry cse("MakeHermitianUniformSpectrum")) if( A.Height() != A.Width() ) LogicError("Cannot make a non-square matrix Hermitian"); const Grid& grid = A.Grid(); typedef Base<F> Real; const bool isComplex = IsComplex<F>::val; const bool standardDist = ( U == MC && V == MR ); // Form d and D const Int n = A.Height(); std::vector<F> d( n ); if( grid.Rank() == 0 ) for( Int j=0; j<n; ++j ) d[j] = SampleUniform<Real>( lower, upper ); mpi::Broadcast( d.data(), n, 0, grid.Comm() ); DistMatrix<F> ABackup( grid ); if( standardDist ) Diagonal( A, d ); else { ABackup.AlignWith( A ); Diagonal( ABackup, d ); } // Apply a Haar matrix from both sides DistMatrix<F> Q(grid); DistMatrix<F,MD,STAR> t(grid); DistMatrix<Real,MD,STAR> s(grid); ImplicitHaar( Q, t, s, n ); // Copy the result into the correct distribution if( standardDist ) { qr::ApplyQ( LEFT, NORMAL, Q, t, s, A ); qr::ApplyQ( RIGHT, ADJOINT, Q, t, s, A ); } else { qr::ApplyQ( LEFT, NORMAL, Q, t, s, ABackup ); qr::ApplyQ( RIGHT, ADJOINT, Q, t, s, ABackup ); A = ABackup; } // Force the diagonal to be real-valued if( isComplex ) { const Int localHeight = A.LocalHeight(); const Int localWidth = A.LocalWidth(); for( Int jLoc=0; jLoc<localWidth; ++jLoc ) { const Int j = A.GlobalCol(jLoc); for( Int iLoc=0; iLoc<localHeight; ++iLoc ) { const Int i = A.GlobalRow(iLoc); if( i == j ) A.SetLocalImagPart( iLoc, jLoc, Real(0) ); } } } } template<typename F> inline void HermitianUniformSpectrum ( Matrix<F>& A, Int n, Base<F> lower=0, Base<F> upper=1 ) { DEBUG_ONLY(CallStackEntry cse("HermitianUniformSpectrum")) A.Resize( n, n ); MakeHermitianUniformSpectrum( A, lower, upper ); } template<typename F,Dist U,Dist V> inline void HermitianUniformSpectrum ( DistMatrix<F,U,V>& A, Int n, Base<F> lower=0, Base<F> upper=1 ) { DEBUG_ONLY(CallStackEntry cse("HermitianUniformSpectrum")) A.Resize( n, n ); MakeHermitianUniformSpectrum( A, lower, upper ); } } // namespace El #endif // ifndef EL_HERMITIANUNIFORMSPECTRUM_HPP <commit_msg>Resolving one more include issue<commit_after>/* Copyright (c) 2009-2014, Jack Poulson All rights reserved. This file is part of Elemental and is under the BSD 2-Clause License, which can be found in the LICENSE file in the root directory, or at http://opensource.org/licenses/BSD-2-Clause */ #pragma once #ifndef EL_HERMITIANUNIFORMSPECTRUM_HPP #define EL_HERMITIANUNIFORMSPECTRUM_HPP #include "./Diagonal.hpp" #include "./Haar.hpp" namespace El { // Draw the spectrum from the specified half-open interval on the real line, // then rotate with a Haar matrix template<typename F> inline void MakeHermitianUniformSpectrum( Matrix<F>& A, Base<F> lower=0, Base<F> upper=1 ) { DEBUG_ONLY(CallStackEntry cse("MakeHermitianUniformSpectrum")) if( A.Height() != A.Width() ) LogicError("Cannot make a non-square matrix Hermitian"); typedef Base<F> Real; const bool isComplex = IsComplex<F>::val; // Form d and D const Int n = A.Height(); std::vector<F> d( n ); for( Int j=0; j<n; ++j ) d[j] = SampleUniform<Real>( lower, upper ); Diagonal( A, d ); // Apply a Haar matrix from both sides Matrix<F> Q, t; Matrix<Real> s; ImplicitHaar( Q, t, s, n ); qr::ApplyQ( LEFT, NORMAL, Q, t, s, A ); qr::ApplyQ( RIGHT, ADJOINT, Q, t, s, A ); if( isComplex ) { const Int height = A.Height(); for( Int j=0; j<height; ++j ) A.SetImagPart( j, j, Real(0) ); } } template<typename F,Dist U,Dist V> inline void MakeHermitianUniformSpectrum ( DistMatrix<F,U,V>& A, Base<F> lower=0, Base<F> upper=1 ) { DEBUG_ONLY(CallStackEntry cse("MakeHermitianUniformSpectrum")) if( A.Height() != A.Width() ) LogicError("Cannot make a non-square matrix Hermitian"); const Grid& grid = A.Grid(); typedef Base<F> Real; const bool isComplex = IsComplex<F>::val; const bool standardDist = ( U == MC && V == MR ); // Form d and D const Int n = A.Height(); std::vector<F> d( n ); if( grid.Rank() == 0 ) for( Int j=0; j<n; ++j ) d[j] = SampleUniform<Real>( lower, upper ); mpi::Broadcast( d.data(), n, 0, grid.Comm() ); DistMatrix<F> ABackup( grid ); if( standardDist ) Diagonal( A, d ); else { ABackup.AlignWith( A ); Diagonal( ABackup, d ); } // Apply a Haar matrix from both sides DistMatrix<F> Q(grid); DistMatrix<F,MD,STAR> t(grid); DistMatrix<Real,MD,STAR> s(grid); ImplicitHaar( Q, t, s, n ); // Copy the result into the correct distribution if( standardDist ) { qr::ApplyQ( LEFT, NORMAL, Q, t, s, A ); qr::ApplyQ( RIGHT, ADJOINT, Q, t, s, A ); } else { qr::ApplyQ( LEFT, NORMAL, Q, t, s, ABackup ); qr::ApplyQ( RIGHT, ADJOINT, Q, t, s, ABackup ); A = ABackup; } // Force the diagonal to be real-valued if( isComplex ) { const Int localHeight = A.LocalHeight(); const Int localWidth = A.LocalWidth(); for( Int jLoc=0; jLoc<localWidth; ++jLoc ) { const Int j = A.GlobalCol(jLoc); for( Int iLoc=0; iLoc<localHeight; ++iLoc ) { const Int i = A.GlobalRow(iLoc); if( i == j ) A.SetLocalImagPart( iLoc, jLoc, Real(0) ); } } } } template<typename F> inline void HermitianUniformSpectrum ( Matrix<F>& A, Int n, Base<F> lower=0, Base<F> upper=1 ) { DEBUG_ONLY(CallStackEntry cse("HermitianUniformSpectrum")) A.Resize( n, n ); MakeHermitianUniformSpectrum( A, lower, upper ); } template<typename F,Dist U,Dist V> inline void HermitianUniformSpectrum ( DistMatrix<F,U,V>& A, Int n, Base<F> lower=0, Base<F> upper=1 ) { DEBUG_ONLY(CallStackEntry cse("HermitianUniformSpectrum")) A.Resize( n, n ); MakeHermitianUniformSpectrum( A, lower, upper ); } } // namespace El #endif // ifndef EL_HERMITIANUNIFORMSPECTRUM_HPP <|endoftext|>
<commit_before>// Copyright (C) 2015 Jérôme Leclercq // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_DEPTHRENDERTECHNIQUE_HPP #define NAZARA_DEPTHRENDERTECHNIQUE_HPP #include <Nazara/Prerequesites.hpp> #include <Nazara/Graphics/AbstractRenderTechnique.hpp> #include <Nazara/Graphics/Config.hpp> #include <Nazara/Graphics/DepthRenderQueue.hpp> #include <Nazara/Graphics/Light.hpp> #include <Nazara/Renderer/Shader.hpp> #include <Nazara/Utility/IndexBuffer.hpp> #include <Nazara/Utility/VertexBuffer.hpp> namespace Nz { class NAZARA_GRAPHICS_API DepthRenderTechnique : public AbstractRenderTechnique { public: DepthRenderTechnique(); ~DepthRenderTechnique() = default; void Clear(const SceneData& sceneData) const override; bool Draw(const SceneData& sceneData) const override; AbstractRenderQueue* GetRenderQueue() override; RenderTechniqueType GetType() const override; static bool Initialize(); static void Uninitialize(); private: struct ShaderUniforms; void DrawBasicSprites(const SceneData& sceneData, ForwardRenderQueue::Layer& layer) const; void DrawBillboards(const SceneData& sceneData, ForwardRenderQueue::Layer& layer) const; void DrawOpaqueModels(const SceneData& sceneData, ForwardRenderQueue::Layer& layer) const; const ShaderUniforms* GetShaderUniforms(const Shader* shader) const; void OnShaderInvalidated(const Shader* shader) const; struct LightIndex { LightType type; float score; unsigned int index; }; struct ShaderUniforms { NazaraSlot(Shader, OnShaderUniformInvalidated, shaderUniformInvalidatedSlot); NazaraSlot(Shader, OnShaderRelease, shaderReleaseSlot); // Autre uniformes int eyePosition; int sceneAmbient; int textureOverlay; }; mutable std::unordered_map<const Shader*, ShaderUniforms> m_shaderUniforms; Buffer m_vertexBuffer; mutable DepthRenderQueue m_renderQueue; VertexBuffer m_billboardPointBuffer; VertexBuffer m_spriteBuffer; static IndexBuffer s_quadIndexBuffer; static VertexBuffer s_quadVertexBuffer; static VertexDeclaration s_billboardInstanceDeclaration; static VertexDeclaration s_billboardVertexDeclaration; }; } #include <Nazara/Graphics/dEPTHRenderTechnique.inl> #endif // NAZARA_DEPTHRENDERTECHNIQUE_HPP <commit_msg>Graphics/DepthRenderTechnique: Fix typo in include name<commit_after>// Copyright (C) 2015 Jérôme Leclercq // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_DEPTHRENDERTECHNIQUE_HPP #define NAZARA_DEPTHRENDERTECHNIQUE_HPP #include <Nazara/Prerequesites.hpp> #include <Nazara/Graphics/AbstractRenderTechnique.hpp> #include <Nazara/Graphics/Config.hpp> #include <Nazara/Graphics/DepthRenderQueue.hpp> #include <Nazara/Graphics/Light.hpp> #include <Nazara/Renderer/Shader.hpp> #include <Nazara/Utility/IndexBuffer.hpp> #include <Nazara/Utility/VertexBuffer.hpp> namespace Nz { class NAZARA_GRAPHICS_API DepthRenderTechnique : public AbstractRenderTechnique { public: DepthRenderTechnique(); ~DepthRenderTechnique() = default; void Clear(const SceneData& sceneData) const override; bool Draw(const SceneData& sceneData) const override; AbstractRenderQueue* GetRenderQueue() override; RenderTechniqueType GetType() const override; static bool Initialize(); static void Uninitialize(); private: struct ShaderUniforms; void DrawBasicSprites(const SceneData& sceneData, ForwardRenderQueue::Layer& layer) const; void DrawBillboards(const SceneData& sceneData, ForwardRenderQueue::Layer& layer) const; void DrawOpaqueModels(const SceneData& sceneData, ForwardRenderQueue::Layer& layer) const; const ShaderUniforms* GetShaderUniforms(const Shader* shader) const; void OnShaderInvalidated(const Shader* shader) const; struct LightIndex { LightType type; float score; unsigned int index; }; struct ShaderUniforms { NazaraSlot(Shader, OnShaderUniformInvalidated, shaderUniformInvalidatedSlot); NazaraSlot(Shader, OnShaderRelease, shaderReleaseSlot); // Autre uniformes int eyePosition; int sceneAmbient; int textureOverlay; }; mutable std::unordered_map<const Shader*, ShaderUniforms> m_shaderUniforms; Buffer m_vertexBuffer; mutable DepthRenderQueue m_renderQueue; VertexBuffer m_billboardPointBuffer; VertexBuffer m_spriteBuffer; static IndexBuffer s_quadIndexBuffer; static VertexBuffer s_quadVertexBuffer; static VertexDeclaration s_billboardInstanceDeclaration; static VertexDeclaration s_billboardVertexDeclaration; }; } #include <Nazara/Graphics/DepthRenderTechnique.inl> #endif // NAZARA_DEPTHRENDERTECHNIQUE_HPP <|endoftext|>
<commit_before>#pragma once #include <type_traits> #include "string_literal.hpp" namespace named_types { template <class Char> unsigned long long constexpr const_hash(Char const *input) { return *input ? static_cast<unsigned long long>(*input) + 33 * const_hash(input + 1) : 5381; } template <class Char, size_t Size> unsigned long long constexpr array_const_hash(Char const (&input)[Size]) { return const_hash<Char>(input); } template <class T, T ... chars> struct string_literal { static const char data[sizeof ... (chars) + 1u]; static const size_t data_size = sizeof ... (chars); static const unsigned long long hash_value = array_const_hash<T, sizeof ... (chars) + 1>({chars..., '\0'}); constexpr string_literal() = default; constexpr char const* str() const { return data; } constexpr size_t size() const { return sizeof ... (chars); } constexpr char operator[] (size_t index) const { return data[index]; } }; template <class T, T ... chars> const char string_literal<T,chars...>::data[sizeof ... (chars) + 1u] = {chars..., '\0'}; } // namespace string_literal <commit_msg>Preparing string_literal hash for MSVC.<commit_after>#pragma once #include <type_traits> #include "string_literal.hpp" namespace named_types { template <class Char> unsigned long long constexpr const_hash(Char const *input) { return *input ? static_cast<unsigned long long>(*input) + 33 * const_hash(input + 1) : 5381; } #ifdef __GNUG__ template <class Char, size_t Size> unsigned long long constexpr array_const_hash(Char const (&input)[Size]) { return const_hash<Char>(input); } #else // MSVC does not support arrays in constexpr unsigned long long constexpr array_const_hash() { return 5381llu; } template <class Head, class ... Tail> unsigned long long constexpr array_const_hash(Head current, Tail ... tail) { return 0u == current ? static_cast<unsigned long long>(current) + 33llu * array_const_hash(tail...) : 5381llu; } #endif template <class T, T ... chars> struct string_literal { static const char data[sizeof ... (chars) + 1u]; static const size_t data_size = sizeof ... (chars); # ifdef __GNUG__ static const unsigned long long hash_value = array_const_hash<T, sizeof ... (chars) + 1>({chars..., '\0'}); # else static const unsigned long long hash_value = array_const_hash(chars...); # endif constexpr string_literal() = default; constexpr char const* str() const { return data; } constexpr size_t size() const { return sizeof ... (chars); } constexpr char operator[] (size_t index) const { return data[index]; } }; template <class T, T ... chars> const char string_literal<T,chars...>::data[sizeof ... (chars) + 1u] = {chars..., '\0'}; } // namespace string_literal <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2016 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 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. * ****************************************************************************/ /** * @file motor_ramp.cpp * Application to test motor ramp up. * * @author Andreas Antener <[email protected]> * @author Roman Bapst <[email protected]> */ #include <px4_config.h> #include <px4_defines.h> #include <px4_tasks.h> #include <px4_posix.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <math.h> #include <poll.h> #include <arch/board/board.h> #include <drivers/drv_hrt.h> #include <drivers/drv_pwm_output.h> #include <platforms/px4_defines.h> #include "systemlib/systemlib.h" #include "systemlib/err.h" static bool _thread_should_exit = false; /**< motor_ramp exit flag */ static bool _thread_running = false; /**< motor_ramp status flag */ static int _motor_ramp_task; /**< Handle of motor_ramp task / thread */ static float _ramp_time; static int _min_pwm; static bool _sine_output = false; enum RampState { RAMP_INIT, RAMP_MIN, RAMP_RAMP, RAMP_WAIT }; /** * motor_ramp management function. */ extern "C" __EXPORT int motor_ramp_main(int argc, char *argv[]); /** * Mainloop of motor_ramp. */ int motor_ramp_thread_main(int argc, char *argv[]); bool min_pwm_valid(unsigned pwm_value); int set_min_pwm(int fd, unsigned long max_channels, unsigned pwm_value); int set_out(int fd, unsigned long max_channels, float output); int prepare(int fd, unsigned long *max_channels); /** * Print the correct usage. */ static void usage(const char *reason); static void usage(const char *reason) { if (reason) { PX4_ERR("%s", reason); } PX4_WARN("\n\nWARNING: motors will ramp up to full speed!\n\n" "Usage: motor_ramp <min_pwm> <ramp_time> <-s>\n" "Setting option <-s> will enable sinus output with period <ramp_time>\n\n" "Example:\n" "nsh> sdlog2 on\n" "nsh> mc_att_control stop\n" "nsh> motor_ramp 1100 0.5\n"); } /** * The motor_ramp app only briefly exists to start * the background job. The stack size assigned in the * Makefile does only apply to this management task. * * The actual stack size should be set in the call * to task_create(). */ int motor_ramp_main(int argc, char *argv[]) { if (argc < 3) { usage("missing parameters"); return 1; } if (_thread_running) { PX4_WARN("motor_ramp already running\n"); /* this is not an error */ return 0; } _min_pwm = atoi(argv[1]); if (!min_pwm_valid(_min_pwm)) { usage("min pwm not in range"); return 1; } _ramp_time = atof(argv[2]); // check if we should apply sine ouput instead of ramp if (argc > 3) { if (strcmp(argv[3], "-s") == 0) { _sine_output = true; } } else { _sine_output = false; } if (!(_ramp_time > 0)) { usage("ramp time must be greater than 0"); return 1; } _thread_should_exit = false; _motor_ramp_task = px4_task_spawn_cmd("motor_ramp", SCHED_DEFAULT, SCHED_PRIORITY_DEFAULT + 40, 2000, motor_ramp_thread_main, (argv) ? (char *const *)&argv[2] : (char *const *)NULL); return 0; usage("unrecognized command"); return 1; } bool min_pwm_valid(unsigned pwm_value) { return pwm_value > 900 && pwm_value < 1300; } int set_min_pwm(int fd, unsigned long max_channels, unsigned pwm_value) { int ret; struct pwm_output_values pwm_values; memset(&pwm_values, 0, sizeof(pwm_values)); pwm_values.channel_count = max_channels; for (int i = 0; i < max_channels; i++) { pwm_values.values[i] = pwm_value; } ret = px4_ioctl(fd, PWM_SERVO_SET_MIN_PWM, (long unsigned int)&pwm_values); if (ret != OK) { PX4_ERR("failed setting min values"); return 1; } return 0; } int set_out(int fd, unsigned long max_channels, float output) { int ret; int pwm = (2000 - _min_pwm) * output + _min_pwm; for (unsigned i = 0; i < max_channels; i++) { ret = ioctl(fd, PWM_SERVO_SET(i), pwm); if (ret != OK) { PX4_ERR("PWM_SERVO_SET(%d), value: %d", i, pwm); return 1; } } return 0; } int prepare(int fd, unsigned long *max_channels) { /* make sure no other source is publishing control values now */ struct actuator_controls_s actuators; int act_sub = orb_subscribe(ORB_ID_VEHICLE_ATTITUDE_CONTROLS); /* clear changed flag */ orb_copy(ORB_ID_VEHICLE_ATTITUDE_CONTROLS, act_sub, &actuators); /* wait 50 ms */ usleep(50000); /* now expect nothing changed on that topic */ bool orb_updated; orb_check(act_sub, &orb_updated); if (orb_updated) { PX4_ERR("ABORTING! Attitude control still active. Please ensure to shut down all controllers:\n" "\tmc_att_control stop\n" "\tfw_att_control stop\n"); return 1; } /* get number of channels available on the device */ if (px4_ioctl(fd, PWM_SERVO_GET_COUNT, (unsigned long)max_channels) != OK) { PX4_ERR("PWM_SERVO_GET_COUNT"); return 1; } /* tell IO/FMU that its ok to disable its safety with the switch */ if (px4_ioctl(fd, PWM_SERVO_SET_ARM_OK, 0) != OK) { PX4_ERR("PWM_SERVO_SET_ARM_OK"); return 1; } /* tell IO/FMU that the system is armed (it will output values if safety is off) */ if (px4_ioctl(fd, PWM_SERVO_ARM, 0) != OK) { PX4_ERR("PWM_SERVO_ARM"); return 1; } /* tell IO to switch off safety without using the safety switch */ if (px4_ioctl(fd, PWM_SERVO_SET_FORCE_SAFETY_OFF, 0) != OK) { PX4_ERR("PWM_SERVO_SET_FORCE_SAFETY_OFF"); return 1; } return 0; } int motor_ramp_thread_main(int argc, char *argv[]) { _thread_running = true; char *dev = PWM_OUTPUT0_DEVICE_PATH; unsigned long max_channels = 0; int fd = px4_open(dev, 0); if (fd < 0) { PX4_ERR("can't open %s", dev); } if (prepare(fd, &max_channels) != OK) { _thread_should_exit = true; } set_out(fd, max_channels, 0.0f); float dt = 0.01f; // prevent division with 0 float timer = 0.0f; hrt_abstime start = 0; hrt_abstime last_run = 0; enum RampState ramp_state = RAMP_INIT; float output = 0.0f; while (!_thread_should_exit) { if (last_run > 0) { dt = hrt_elapsed_time(&last_run) * 1e-6; } else { start = hrt_absolute_time(); } last_run = hrt_absolute_time(); timer = hrt_elapsed_time(&start) * 1e-6; switch (ramp_state) { case RAMP_INIT: { PX4_WARN("setting pwm min: %d", _min_pwm); set_min_pwm(fd, max_channels, _min_pwm); ramp_state = RAMP_MIN; break; } case RAMP_MIN: { if (timer > 3.0f) { PX4_WARN("starting %s: %.2f sec", _sine_output ? "sine" : "ramp", (double)_ramp_time); start = hrt_absolute_time(); ramp_state = RAMP_RAMP; } set_out(fd, max_channels, output); break; } case RAMP_RAMP: { if (!_sine_output) { output += dt / _ramp_time; } else { // sine outpout with period T = _ramp_time and magnitude between [0,1] // phase shift makes sure that it starts at zero when timer is zero output = 0.5f * (1.0f + sinf(M_TWOPI_F * timer / _ramp_time - M_PI_2_F)); } if ((output > 1.0f && !_sine_output) || (timer > 3.0f * _ramp_time && _sine_output)) { // for ramp mode we set output to 1, for sine mode we just leave it as is output = _sine_output ? output : 1.0f; start = hrt_absolute_time(); ramp_state = RAMP_WAIT; PX4_WARN("%s finished, waiting", _sine_output ? "sine" : "ramp"); } set_out(fd, max_channels, output); break; } case RAMP_WAIT: { if (timer > 1.0f) { _thread_should_exit = true; break; } set_out(fd, max_channels, output); break; } } // rate limit usleep(2000); } if (fd >= 0) { /* disarm */ ioctl(fd, PWM_SERVO_DISARM, 0); px4_close(fd); } _thread_running = false; return 0; } <commit_msg>added square wave mode and PWM max parameter<commit_after>/**************************************************************************** * * Copyright (c) 2016 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 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. * ****************************************************************************/ /** * @file motor_ramp.cpp * Application to test motor ramp up. * * @author Andreas Antener <[email protected]> * @author Roman Bapst <[email protected]> */ #include <px4_config.h> #include <px4_defines.h> #include <px4_tasks.h> #include <px4_posix.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <math.h> #include <poll.h> #include <arch/board/board.h> #include <drivers/drv_hrt.h> #include <drivers/drv_pwm_output.h> #include <platforms/px4_defines.h> #include "systemlib/systemlib.h" #include "systemlib/err.h" enum RampState { RAMP_INIT, RAMP_MIN, RAMP_RAMP, RAMP_WAIT }; enum Mode { RAMP, SINE, SQUARE }; static bool _thread_should_exit = false; /**< motor_ramp exit flag */ static bool _thread_running = false; /**< motor_ramp status flag */ static int _motor_ramp_task; /**< Handle of motor_ramp task / thread */ static float _ramp_time; static int _min_pwm; static int _max_pwm; static Mode _mode; static char *_mode_c; /** * motor_ramp management function. */ extern "C" __EXPORT int motor_ramp_main(int argc, char *argv[]); /** * Mainloop of motor_ramp. */ int motor_ramp_thread_main(int argc, char *argv[]); bool min_pwm_valid(unsigned pwm_value); bool max_pwm_valid(unsigned pwm_value); int set_min_pwm(int fd, unsigned long max_channels, unsigned pwm_value); int set_out(int fd, unsigned long max_channels, float output); int prepare(int fd, unsigned long *max_channels); /** * Print the correct usage. */ static void usage(const char *reason); static void usage(const char *reason) { if (reason) { PX4_ERR("%s", reason); } PX4_WARN("\n\nWARNING: motors will ramp up to full speed!\n\n" "Usage: motor_ramp <mode> <min_pwm> <time> [<max_pwm>]\n" "<mode> can be one of (ramp|sine|square)\n\n" "Example:\n" "sdlog2 on\n" "mc_att_control stop\n" "motor_ramp sine 1100 0.5\n"); } /** * The motor_ramp app only briefly exists to start * the background job. The stack size assigned in the * Makefile does only apply to this management task. * * The actual stack size should be set in the call * to task_create(). */ int motor_ramp_main(int argc, char *argv[]) { if (argc < 4) { usage("missing parameters"); return 1; } if (_thread_running) { PX4_WARN("motor_ramp already running\n"); /* this is not an error */ return 0; } if (!strcmp(argv[1], "ramp")) { _mode = RAMP; } else if (!strcmp(argv[1], "sine")) { _mode = SINE; } else if (!strcmp(argv[1], "square")) { _mode = SQUARE; } else { usage("selected mode not valid"); return 1; } _mode_c = argv[1]; _min_pwm = atoi(argv[2]); if (!min_pwm_valid(_min_pwm)) { usage("min PWM not in range"); return 1; } _ramp_time = atof(argv[3]); if (argc > 4) { _max_pwm = atoi(argv[4]); if (!max_pwm_valid(_max_pwm)) { usage("max PWM not in range"); return 1; } } else { _max_pwm = 2000; } if (!(_ramp_time > 0)) { usage("ramp time must be greater than 0"); return 1; } _thread_should_exit = false; _motor_ramp_task = px4_task_spawn_cmd("motor_ramp", SCHED_DEFAULT, SCHED_PRIORITY_DEFAULT + 40, 2000, motor_ramp_thread_main, (argv) ? (char *const *)&argv[2] : (char *const *)NULL); return 0; usage("unrecognized command"); return 1; } bool min_pwm_valid(unsigned pwm_value) { return pwm_value >= 900 && pwm_value <= 1500; } bool max_pwm_valid(unsigned pwm_value) { return pwm_value <= 2100 && pwm_value > _min_pwm; } int set_min_pwm(int fd, unsigned long max_channels, unsigned pwm_value) { int ret; struct pwm_output_values pwm_values; memset(&pwm_values, 0, sizeof(pwm_values)); pwm_values.channel_count = max_channels; for (int i = 0; i < max_channels; i++) { pwm_values.values[i] = pwm_value; } ret = px4_ioctl(fd, PWM_SERVO_SET_MIN_PWM, (long unsigned int)&pwm_values); if (ret != OK) { PX4_ERR("failed setting min values"); return 1; } return 0; } int set_out(int fd, unsigned long max_channels, float output) { int ret; int pwm = (_max_pwm - _min_pwm) * output + _min_pwm; for (unsigned i = 0; i < max_channels; i++) { ret = ioctl(fd, PWM_SERVO_SET(i), pwm); if (ret != OK) { PX4_ERR("PWM_SERVO_SET(%d), value: %d", i, pwm); return 1; } } return 0; } int prepare(int fd, unsigned long *max_channels) { /* make sure no other source is publishing control values now */ struct actuator_controls_s actuators; int act_sub = orb_subscribe(ORB_ID_VEHICLE_ATTITUDE_CONTROLS); /* clear changed flag */ orb_copy(ORB_ID_VEHICLE_ATTITUDE_CONTROLS, act_sub, &actuators); /* wait 50 ms */ usleep(50000); /* now expect nothing changed on that topic */ bool orb_updated; orb_check(act_sub, &orb_updated); if (orb_updated) { PX4_ERR("ABORTING! Attitude control still active. Please ensure to shut down all controllers:\n" "\tmc_att_control stop\n" "\tfw_att_control stop\n"); return 1; } /* get number of channels available on the device */ if (px4_ioctl(fd, PWM_SERVO_GET_COUNT, (unsigned long)max_channels) != OK) { PX4_ERR("PWM_SERVO_GET_COUNT"); return 1; } /* tell IO/FMU that its ok to disable its safety with the switch */ if (px4_ioctl(fd, PWM_SERVO_SET_ARM_OK, 0) != OK) { PX4_ERR("PWM_SERVO_SET_ARM_OK"); return 1; } /* tell IO/FMU that the system is armed (it will output values if safety is off) */ if (px4_ioctl(fd, PWM_SERVO_ARM, 0) != OK) { PX4_ERR("PWM_SERVO_ARM"); return 1; } /* tell IO to switch off safety without using the safety switch */ if (px4_ioctl(fd, PWM_SERVO_SET_FORCE_SAFETY_OFF, 0) != OK) { PX4_ERR("PWM_SERVO_SET_FORCE_SAFETY_OFF"); return 1; } return 0; } int motor_ramp_thread_main(int argc, char *argv[]) { _thread_running = true; char *dev = PWM_OUTPUT0_DEVICE_PATH; unsigned long max_channels = 0; int fd = px4_open(dev, 0); if (fd < 0) { PX4_ERR("can't open %s", dev); } if (prepare(fd, &max_channels) != OK) { _thread_should_exit = true; } set_out(fd, max_channels, 0.0f); float dt = 0.001f; // prevent division with 0 float timer = 0.0f; hrt_abstime start = 0; hrt_abstime last_run = 0; enum RampState ramp_state = RAMP_INIT; float output = 0.0f; while (!_thread_should_exit) { if (last_run > 0) { dt = hrt_elapsed_time(&last_run) * 1e-6; } else { start = hrt_absolute_time(); } last_run = hrt_absolute_time(); timer = hrt_elapsed_time(&start) * 1e-6; switch (ramp_state) { case RAMP_INIT: { PX4_WARN("setting pwm min: %d", _min_pwm); set_min_pwm(fd, max_channels, _min_pwm); ramp_state = RAMP_MIN; break; } case RAMP_MIN: { if (timer > 3.0f) { PX4_WARN("starting %s: %.2f sec", _mode_c, (double)_ramp_time); start = hrt_absolute_time(); ramp_state = RAMP_RAMP; } set_out(fd, max_channels, output); break; } case RAMP_RAMP: { if (_mode == RAMP) { output += dt / _ramp_time; } else if (_mode == SINE) { // sine outpout with period T = _ramp_time and magnitude between [0,1] // phase shift makes sure that it starts at zero when timer is zero output = 0.5f * (1.0f + sinf(M_TWOPI_F * timer / _ramp_time - M_PI_2_F)); } else if (_mode == SQUARE) { output = fmodf(timer, _ramp_time) > (_ramp_time * 0.5f) ? 1.0f : 0.0f; } if ((output > 1.0f && _mode == RAMP) || (timer > 3.0f * _ramp_time)) { // for ramp mode we set output to 1, for others we just leave it as is output = _mode != RAMP ? output : 1.0f; start = hrt_absolute_time(); ramp_state = RAMP_WAIT; PX4_WARN("%s finished, waiting", _mode_c); } set_out(fd, max_channels, output); break; } case RAMP_WAIT: { if (timer > 1.0f) { _thread_should_exit = true; break; } set_out(fd, max_channels, output); break; } } // rate limit usleep(2000); } if (fd >= 0) { /* disarm */ ioctl(fd, PWM_SERVO_DISARM, 0); px4_close(fd); } _thread_running = false; return 0; } <|endoftext|>
<commit_before>#include <algorithm> #include <iostream> #include <tiramisu/debug.h> #include <Halide.h> using namespace Halide; using namespace Halide::Internal; using std::string; using std::map; using std::vector; namespace tiramisu { namespace { string stmt_to_string(const string &str, const Stmt &s) { std::ostringstream stream; stream << str << s << "\n"; return stream.str(); } } // anonymous namespace Module lower_halide_pipeline(const string &pipeline_name, const Target &t, const vector<Argument> &args, const Internal::LoweredFunc::LinkageType linkage_type, Stmt s) { Module result_module(pipeline_name, t); // TODO(tiramisu): Compute the env (function DAG). This is needed for // the sliding window and storage folding passes. map<string, Function> env; if (ENABLE_DEBUG) { std::cout << "Lower halide pipeline...\n" << s << "\n"; std::flush(std::cout); } DEBUG(3, tiramisu::str_dump("Performing sliding window optimization...\n")); s = sliding_window(s, env); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after sliding window:\n", s))); DEBUG(3, tiramisu::str_dump("Removing code that depends on undef values...\n")); s = remove_undef(s); DEBUG(4, tiramisu::str_dump( stmt_to_string("Lowering after removing code that depends on undef values:\n", s))); // This uniquifies the variable names, so we're good to simplify // after this point. This lets later passes assume syntactic // equivalence means semantic equivalence. DEBUG(3, tiramisu::str_dump("Uniquifying variable names...\n")); s = uniquify_variable_names(s); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after uniquifying variable names:\n", s))); DEBUG(3, tiramisu::str_dump("Simplifying...\n")); // without removing dead lets, because storage flattening needs the strides s = simplify(s, false); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after simplification:\n", s))); DEBUG(3, tiramisu::str_dump("Performing storage folding optimization...\n")); s = storage_folding(s, env); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after storage folding:\n", s))); DEBUG(3, tiramisu::str_dump("Simplifying...\n")); // without removing dead lets, because storage flattening needs the strides s = simplify(s, false); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after simplification:\n", s))); /* DEBUG(3, tiramisu::str_dump("Injecting prefetches...\n")); s = inject_prefetch(s, env); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after injecting prefetches:\n", s))); */ DEBUG(3, tiramisu::str_dump("Destructuring tuple-valued realizations...\n")); s = split_tuples(s, env); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after destructuring tuple-valued realizations:\n", s))); DEBUG(3, tiramisu::str_dump("\n\n")); // TODO(tiramisu): This pass is important to figure out all the buffer symbols. // Maybe we should put it somewhere else instead of here. DEBUG(3, tiramisu::str_dump("Unpacking buffer arguments...\n")); s = unpack_buffers(s); DEBUG(0, tiramisu::str_dump(stmt_to_string("Lowering after unpacking buffer arguments:\n", s))); if (t.has_gpu_feature() || t.has_feature(Target::OpenGLCompute) || t.has_feature(Target::OpenGL) || (t.arch != Target::Hexagon && (t.features_any_of({Target::HVX_64, Target::HVX_128})))) { DEBUG(3, tiramisu::str_dump("Selecting a GPU API for GPU loops...\n")); s = select_gpu_api(s, t); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after selecting a GPU API:\n", s))); DEBUG(3, tiramisu::str_dump("Injecting host <-> dev buffer copies...\n")); s = inject_host_dev_buffer_copies(s, t); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after injecting host <-> dev buffer copies:\n", s))); } if (t.has_feature(Target::OpenGL)) { DEBUG(3, tiramisu::str_dump("Injecting OpenGL texture intrinsics...\n")); s = inject_opengl_intrinsics(s); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after OpenGL intrinsics:\n", s))); } if (t.has_gpu_feature() || t.has_feature(Target::OpenGLCompute)) { DEBUG(3, tiramisu::str_dump("Injecting per-block gpu synchronization...\n")); s = fuse_gpu_thread_loops(s); DEBUG(4, tiramisu::str_dump( stmt_to_string("Lowering after injecting per-block gpu synchronization:\n", s))); } DEBUG(3, tiramisu::str_dump("Simplifying...\n")); s = simplify(s); s = unify_duplicate_lets(s); s = remove_trivial_for_loops(s); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after second simplifcation:\n", s))); DEBUG(3, tiramisu::str_dump("Reduce prefetch dimension...\n")); s = reduce_prefetch_dimension(s, t); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after reduce prefetch dimension:\n", s))); DEBUG(3, tiramisu::str_dump("Unrolling...\n")); s = unroll_loops(s); s = simplify(s); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after unrolling:\n", s))); DEBUG(3, tiramisu::str_dump("Vectorizing...\n")); s = vectorize_loops(s, t); s = simplify(s); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after vectorizing:\n", s))); DEBUG(3, tiramisu::str_dump("Detecting vector interleavings...\n")); s = rewrite_interleavings(s); s = simplify(s); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after rewriting vector interleavings:\n", s))); DEBUG(3, tiramisu::str_dump("Partitioning loops to simplify boundary conditions...\n")); s = partition_loops(s); s = simplify(s); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after partitioning loops:\n", s))); DEBUG(3, tiramisu::str_dump("Trimming loops to the region over which they do something...\n")); s = trim_no_ops(s); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after loop trimming:\n", s))); DEBUG(3, tiramisu::str_dump("Injecting early frees...\n")); s = inject_early_frees(s); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after injecting early frees:\n", s))); if (t.has_feature(Target::FuzzFloatStores)) { DEBUG(3, tiramisu::str_dump("Fuzzing floating point stores...\n")); s = fuzz_float_stores(s); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after fuzzing floating point stores:\n", s))); } //DEBUG(3, tiramisu::str_dump("Simplifying...\n")); //s = common_subexpression_elimination(s); if (t.has_feature(Target::OpenGL)) { DEBUG(3, tiramisu::str_dump("Detecting varying attributes...\n")); s = find_linear_expressions(s); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after detecting varying attributes:\n", s))); DEBUG(3, tiramisu::str_dump("Moving varying attribute expressions out of the shader...\n")); s = setup_gpu_vertex_buffer(s); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after removing varying attributes:\n", s))); } s = remove_dead_allocations(s); s = remove_trivial_for_loops(s); s = simplify(s); // s = loop_invariant_code_motion(s); if (ENABLE_DEBUG) { std::cout << "Lowering after final simplification:\n" << s << "\n"; std::flush(std::cout); } DEBUG(3, tiramisu::str_dump("Splitting off Hexagon offload...\n")); // s = inject_hexagon_rpc(s, t, result_module); // DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after splitting off Hexagon offload:\n", s))); vector<Argument> public_args = args; // We're about to drop the environment and outputs vector, which // contain the only strong refs to Functions that may still be // pointed to by the IR. So make those refs strong. class StrengthenRefs : public IRMutator { using IRMutator::visit; void visit(const Call *c) { IRMutator::visit(c); c = expr.as<Call>(); //internal_assert(c); if (c->func.defined()) { FunctionPtr ptr = c->func; ptr.strengthen(); expr = Call::make(c->type, c->name, c->args, c->call_type, ptr, c->value_index, c->image, c->param); } } }; s = StrengthenRefs().mutate(s); LoweredFunc main_func(pipeline_name, public_args, s, linkage_type); result_module.append(main_func); // Append a wrapper for this pipeline that accepts old buffer_ts // and upgrades them. It will use the same name, so it will // require C++ linkage. We don't need it when jitting. if (!t.has_feature(Target::JIT)) { add_legacy_wrapper(result_module, main_func); } // Also append any wrappers for extern stages that expect the old buffer_t wrap_legacy_extern_stages(result_module); return result_module; } } <commit_msg>Disable trim_no_ops to avoid a bug in dibaryon<commit_after>#include <algorithm> #include <iostream> #include <tiramisu/debug.h> #include <Halide.h> using namespace Halide; using namespace Halide::Internal; using std::string; using std::map; using std::vector; namespace tiramisu { namespace { string stmt_to_string(const string &str, const Stmt &s) { std::ostringstream stream; stream << str << s << "\n"; return stream.str(); } } // anonymous namespace Module lower_halide_pipeline(const string &pipeline_name, const Target &t, const vector<Argument> &args, const Internal::LoweredFunc::LinkageType linkage_type, Stmt s) { Module result_module(pipeline_name, t); // TODO(tiramisu): Compute the env (function DAG). This is needed for // the sliding window and storage folding passes. map<string, Function> env; if (ENABLE_DEBUG) { std::cout << "Lower halide pipeline...\n" << s << "\n"; std::flush(std::cout); } DEBUG(3, tiramisu::str_dump("Performing sliding window optimization...\n")); s = sliding_window(s, env); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after sliding window:\n", s))); DEBUG(3, tiramisu::str_dump("Removing code that depends on undef values...\n")); s = remove_undef(s); DEBUG(4, tiramisu::str_dump( stmt_to_string("Lowering after removing code that depends on undef values:\n", s))); // This uniquifies the variable names, so we're good to simplify // after this point. This lets later passes assume syntactic // equivalence means semantic equivalence. DEBUG(3, tiramisu::str_dump("Uniquifying variable names...\n")); s = uniquify_variable_names(s); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after uniquifying variable names:\n", s))); DEBUG(3, tiramisu::str_dump("Simplifying...\n")); // without removing dead lets, because storage flattening needs the strides s = simplify(s, false); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after simplification:\n", s))); DEBUG(3, tiramisu::str_dump("Performing storage folding optimization...\n")); s = storage_folding(s, env); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after storage folding:\n", s))); DEBUG(3, tiramisu::str_dump("Simplifying...\n")); // without removing dead lets, because storage flattening needs the strides s = simplify(s, false); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after simplification:\n", s))); /* DEBUG(3, tiramisu::str_dump("Injecting prefetches...\n")); s = inject_prefetch(s, env); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after injecting prefetches:\n", s))); */ DEBUG(3, tiramisu::str_dump("Destructuring tuple-valued realizations...\n")); s = split_tuples(s, env); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after destructuring tuple-valued realizations:\n", s))); DEBUG(3, tiramisu::str_dump("\n\n")); // TODO(tiramisu): This pass is important to figure out all the buffer symbols. // Maybe we should put it somewhere else instead of here. DEBUG(3, tiramisu::str_dump("Unpacking buffer arguments...\n")); s = unpack_buffers(s); DEBUG(0, tiramisu::str_dump(stmt_to_string("Lowering after unpacking buffer arguments:\n", s))); if (t.has_gpu_feature() || t.has_feature(Target::OpenGLCompute) || t.has_feature(Target::OpenGL) || (t.arch != Target::Hexagon && (t.features_any_of({Target::HVX_64, Target::HVX_128})))) { DEBUG(3, tiramisu::str_dump("Selecting a GPU API for GPU loops...\n")); s = select_gpu_api(s, t); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after selecting a GPU API:\n", s))); DEBUG(3, tiramisu::str_dump("Injecting host <-> dev buffer copies...\n")); s = inject_host_dev_buffer_copies(s, t); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after injecting host <-> dev buffer copies:\n", s))); } if (t.has_feature(Target::OpenGL)) { DEBUG(3, tiramisu::str_dump("Injecting OpenGL texture intrinsics...\n")); s = inject_opengl_intrinsics(s); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after OpenGL intrinsics:\n", s))); } if (t.has_gpu_feature() || t.has_feature(Target::OpenGLCompute)) { DEBUG(3, tiramisu::str_dump("Injecting per-block gpu synchronization...\n")); s = fuse_gpu_thread_loops(s); DEBUG(4, tiramisu::str_dump( stmt_to_string("Lowering after injecting per-block gpu synchronization:\n", s))); } DEBUG(3, tiramisu::str_dump("Simplifying...\n")); s = simplify(s); s = unify_duplicate_lets(s); s = remove_trivial_for_loops(s); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after second simplifcation:\n", s))); DEBUG(3, tiramisu::str_dump("Reduce prefetch dimension...\n")); s = reduce_prefetch_dimension(s, t); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after reduce prefetch dimension:\n", s))); DEBUG(3, tiramisu::str_dump("Unrolling...\n")); s = unroll_loops(s); s = simplify(s); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after unrolling:\n", s))); DEBUG(3, tiramisu::str_dump("Vectorizing...\n")); s = vectorize_loops(s, t); s = simplify(s); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after vectorizing:\n", s))); DEBUG(3, tiramisu::str_dump("Detecting vector interleavings...\n")); s = rewrite_interleavings(s); s = simplify(s); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after rewriting vector interleavings:\n", s))); DEBUG(3, tiramisu::str_dump("Partitioning loops to simplify boundary conditions...\n")); s = partition_loops(s); s = simplify(s); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after partitioning loops:\n", s))); // DEBUG(3, tiramisu::str_dump("Trimming loops to the region over which they do something...\n")); // s = trim_no_ops(s); // DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after loop trimming:\n", s))); DEBUG(3, tiramisu::str_dump("Injecting early frees...\n")); s = inject_early_frees(s); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after injecting early frees:\n", s))); if (t.has_feature(Target::FuzzFloatStores)) { DEBUG(3, tiramisu::str_dump("Fuzzing floating point stores...\n")); s = fuzz_float_stores(s); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after fuzzing floating point stores:\n", s))); } //DEBUG(3, tiramisu::str_dump("Simplifying...\n")); //s = common_subexpression_elimination(s); if (t.has_feature(Target::OpenGL)) { DEBUG(3, tiramisu::str_dump("Detecting varying attributes...\n")); s = find_linear_expressions(s); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after detecting varying attributes:\n", s))); DEBUG(3, tiramisu::str_dump("Moving varying attribute expressions out of the shader...\n")); s = setup_gpu_vertex_buffer(s); DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after removing varying attributes:\n", s))); } s = remove_dead_allocations(s); s = remove_trivial_for_loops(s); s = simplify(s); // s = loop_invariant_code_motion(s); if (ENABLE_DEBUG) { std::cout << "Lowering after final simplification:\n" << s << "\n"; std::flush(std::cout); } DEBUG(3, tiramisu::str_dump("Splitting off Hexagon offload...\n")); // s = inject_hexagon_rpc(s, t, result_module); // DEBUG(4, tiramisu::str_dump(stmt_to_string("Lowering after splitting off Hexagon offload:\n", s))); vector<Argument> public_args = args; // We're about to drop the environment and outputs vector, which // contain the only strong refs to Functions that may still be // pointed to by the IR. So make those refs strong. class StrengthenRefs : public IRMutator { using IRMutator::visit; void visit(const Call *c) { IRMutator::visit(c); c = expr.as<Call>(); //internal_assert(c); if (c->func.defined()) { FunctionPtr ptr = c->func; ptr.strengthen(); expr = Call::make(c->type, c->name, c->args, c->call_type, ptr, c->value_index, c->image, c->param); } } }; s = StrengthenRefs().mutate(s); LoweredFunc main_func(pipeline_name, public_args, s, linkage_type); result_module.append(main_func); // Append a wrapper for this pipeline that accepts old buffer_ts // and upgrades them. It will use the same name, so it will // require C++ linkage. We don't need it when jitting. if (!t.has_feature(Target::JIT)) { add_legacy_wrapper(result_module, main_func); } // Also append any wrappers for extern stages that expect the old buffer_t wrap_legacy_extern_stages(result_module); return result_module; } } <|endoftext|>
<commit_before>#ifndef STAN_MATH_REV_CORE_OPERATOR_ADDITION_HPP #define STAN_MATH_REV_CORE_OPERATOR_ADDITION_HPP #include <stan/math/rev/meta.hpp> #include <stan/math/rev/core/var.hpp> #include <stan/math/prim/err/check_matching_dims.hpp> #include <stan/math/rev/core/callback_vari.hpp> #include <stan/math/prim/fun/constants.hpp> namespace stan { namespace math { /** * Addition operator for variables (C++). * * The partial derivatives are defined by * * \f$\frac{\partial}{\partial x} (x+y) = 1\f$, and * * \f$\frac{\partial}{\partial y} (x+y) = 1\f$. * * \f[ \mbox{operator+}(x, y) = \begin{cases} x+y & \mbox{if } -\infty\leq x, y \leq \infty \\[6pt] \textrm{NaN} & \mbox{if } x = \textrm{NaN or } y = \textrm{NaN} \end{cases} \f] \f[ \frac{\partial\, \mbox{operator+}(x, y)}{\partial x} = \begin{cases} 1 & \mbox{if } -\infty\leq x, y \leq \infty \\[6pt] \textrm{NaN} & \mbox{if } x = \textrm{NaN or } y = \textrm{NaN} \end{cases} \f] \f[ \frac{\partial\, \mbox{operator+}(x, y)}{\partial y} = \begin{cases} 1 & \mbox{if } -\infty\leq x, y \leq \infty \\[6pt] \textrm{NaN} & \mbox{if } x = \textrm{NaN or } y = \textrm{NaN} \end{cases} \f] * * @param a First variable operand. * @param b Second variable operand. * @return Variable result of adding two variables. */ inline var operator+(const var& a, const var& b) { return make_callback_vari(a.vi_->val_ + b.vi_->val_, [avi = a.vi_, bvi = b.vi_](const auto& vi) mutable { if (unlikely(std::isnan(vi.val_))) { avi->adj_ = NOT_A_NUMBER; bvi->adj_ = NOT_A_NUMBER; } else { avi->adj_ += vi.adj_; bvi->adj_ += vi.adj_; } }); } /** * Addition operator for variable and scalar (C++). * * The derivative with respect to the variable is * * \f$\frac{d}{dx} (x + c) = 1\f$. * * @tparam Arith An arithmetic type * @param a First variable operand. * @param b Second scalar operand. * @return Result of adding variable and scalar. */ template <typename Arith, require_arithmetic_t<Arith>* = nullptr> inline var operator+(const var& a, Arith b) { if (unlikely(b == 0.0)) { return a; } return make_callback_vari(a.vi_->val_ + b, [avi = a.vi_, b](const auto& vi) mutable { if (unlikely(std::isnan(vi.val_))) { avi->adj_ = NOT_A_NUMBER; } else { avi->adj_ += vi.adj_; } }); } /** * Addition operator for scalar and variable (C++). * * The derivative with respect to the variable is * * \f$\frac{d}{dy} (c + y) = 1\f$. * * @tparam Arith An arithmetic type * @param a First scalar operand. * @param b Second variable operand. * @return Result of adding variable and scalar. */ template <typename Arith, require_arithmetic_t<Arith>* = nullptr> inline var operator+(Arith a, const var& b) { return b + a; // by symmetry } /** * Addition operator for matrix variables (C++). * * @tparam VarMat1 A matrix of vars or a var with an underlying matrix type. * @tparam VarMat2 A matrix of vars or a var with an underlying matrix type. * @param a First variable operand. * @param b Second variable operand. * @return Variable result of adding two variables. */ template <typename VarMat1, typename VarMat2, require_all_rev_matrix_t<VarMat1, VarMat2>* = nullptr> inline auto add(const VarMat1& a, const VarMat2& b) { check_matching_dims("add", "a", a, "b", b); using op_ret_type = decltype(a.val() + b.val()); using ret_type = promote_var_matrix_t<op_ret_type, VarMat1, VarMat2>; arena_t<VarMat1> arena_a(a); arena_t<VarMat2> arena_b(b); arena_t<ret_type> ret(arena_a.val() + arena_b.val()); reverse_pass_callback([ret, arena_a, arena_b]() mutable { for (Eigen::Index i = 0; i < ret.size(); ++i) { const auto ref_adj = ret.adj().coeffRef(i); arena_a.adj().coeffRef(i) += ref_adj; arena_b.adj().coeffRef(i) += ref_adj; } }); return ret_type(ret); } /** * Addition operator for a matrix variable and arithmetic (C++). * * @tparam VarMat A matrix of vars or a var with an underlying matrix type. * @tparam Arith A type with an arithmetic Scalar type. * @param a First variable operand. * @param b Second variable operand. * @return Variable result of adding two variables. */ template <typename Arith, typename VarMat, require_st_arithmetic<Arith>* = nullptr, require_rev_matrix_t<VarMat>* = nullptr> inline auto add(const VarMat& a, const Arith& b) { if (is_eigen<Arith>::value) { check_matching_dims("add", "a", a, "b", b); } using op_ret_type = decltype((a.val().array() + as_array_or_scalar(b)).matrix()); using ret_type = promote_var_matrix_t<op_ret_type, VarMat>; arena_t<VarMat> arena_a(a); arena_t<ret_type> ret(arena_a.val().array() + as_array_or_scalar(b)); reverse_pass_callback( [ret, arena_a]() mutable { arena_a.adj() += ret.adj_op(); }); return ret_type(ret); } /** * Addition operator for an arithmetic type and matrix variable (C++). * * @tparam VarMat A matrix of vars or a var with an underlying matrix type. * @tparam Arith A type with an arithmetic Scalar type. * @param a First variable operand. * @param b Second variable operand. * @return Variable result of adding two variables. */ template <typename Arith, typename VarMat, require_st_arithmetic<Arith>* = nullptr, require_rev_matrix_t<VarMat>* = nullptr> inline auto add(const Arith& a, const VarMat& b) { return add(b, a); } /** * Addition operator for an arithmetic matrix and variable (C++). * * @tparam Var A `var_value` with an underlying arithmetic type. * @tparam EigMat An Eigen Matrix type with an arithmetic Scalar type. * @param a First variable operand. * @param b Second variable operand. * @return Variable result of adding two variables. */ template <typename Var, typename EigMat, require_var_vt<std::is_arithmetic, Var>* = nullptr, require_eigen_vt<std::is_arithmetic, EigMat>* = nullptr> inline auto add(const Var& a, const EigMat& b) { using ret_type = promote_scalar_t<var, EigMat>; arena_t<ret_type> ret(a.val() + b.array()); reverse_pass_callback([ret, a]() mutable { a.adj() += ret.adj().sum(); }); return ret_type(ret); } /** * Addition operator for a variable and arithmetic matrix (C++). * * @tparam EigMat An Eigen Matrix type with an arithmetic Scalar type. * @tparam Var A `var_value` with an underlying arithmetic type. * @param a First variable operand. * @param b Second variable operand. * @return Variable result of adding two variables. */ template <typename EigMat, typename Var, require_eigen_vt<std::is_arithmetic, EigMat>* = nullptr, require_var_vt<std::is_arithmetic, Var>* = nullptr> inline auto add(const EigMat& a, const Var& b) { return add(b, a); } /** * Addition operator for a variable and variable matrix (C++). * * @tparam Var A `var_value` with an underlying arithmetic type. * @tparam VarMat An Eigen Matrix type with a variable Scalar type or a * `var_value` with an underlying matrix type. * @param a First variable operand. * @param b Second variable operand. * @return Variable result of adding two variables. */ template <typename Var, typename VarMat, require_var_vt<std::is_arithmetic, Var>* = nullptr, require_rev_matrix_t<VarMat>* = nullptr> inline auto add(const Var& a, const VarMat& b) { arena_t<VarMat> arena_b(b); arena_t<VarMat> ret(a.val() + arena_b.val().array()); reverse_pass_callback([ret, a, arena_b]() mutable { for (Eigen::Index i = 0; i < arena_b.size(); ++i) { const auto ret_adj = ret.adj().coeffRef(i); a.adj() += ret_adj; arena_b.adj().coeffRef(i) += ret_adj; } }); return plain_type_t<VarMat>(ret); } /** * Addition operator for a variable matrix and variable (C++). * * @tparam VarMat An Eigen Matrix type with a variable Scalar type or a * `var_value` with an underlying matrix type. * @tparam Var A `var_value` with an underlying arithmetic type. * @param a First variable operand. * @param b Second variable operand. * @return Variable result of adding two variables. */ template <typename Var, typename VarMat, require_var_vt<std::is_arithmetic, Var>* = nullptr, require_rev_matrix_t<VarMat>* = nullptr> inline auto add(const VarMat& a, const Var& b) { return add(b, a); } template <typename T1, typename T2, require_any_var_vt<std::is_arithmetic, T1, T2>* = nullptr, require_any_arithmetic_t<T1, T2>* = nullptr> inline auto add(const T1& a, const T2& b) { return a + b; } template <typename T1, typename T2, require_all_var_vt<std::is_arithmetic, T1, T2>* = nullptr> inline auto add(const T1& a, const T2& b) { return a + b; } /** * Addition operator for matrix variables (C++). * * @tparam VarMat1 A matrix of vars or a var with an underlying matrix type. * @tparam VarMat2 A matrix of vars or a var with an underlying matrix type. * @param a First variable operand. * @param b Second variable operand. * @return Variable result of adding two variables. */ template <typename VarMat1, typename VarMat2, require_any_var_matrix_t<VarMat1, VarMat2>* = nullptr> inline auto operator+(const VarMat1& a, const VarMat2& b) { return add(a, b); } } // namespace math } // namespace stan #endif <commit_msg>kickoff jenkins<commit_after>#ifndef STAN_MATH_REV_CORE_OPERATOR_ADDITION_HPP #define STAN_MATH_REV_CORE_OPERATOR_ADDITION_HPP #include <stan/math/rev/meta.hpp> #include <stan/math/rev/core/var.hpp> #include <stan/math/prim/err/check_matching_dims.hpp> #include <stan/math/rev/core/callback_vari.hpp> #include <stan/math/prim/fun/constants.hpp> namespace stan { namespace math { /** * Addition operator for variables (C++). * * The partial derivatives are defined by * * \f$\frac{\partial}{\partial x} (x+y) = 1\f$, and * * \f$\frac{\partial}{\partial y} (x+y) = 1\f$. * * \f[ \mbox{operator+}(x, y) = \begin{cases} x+y & \mbox{if } -\infty\leq x, y \leq \infty \\[6pt] \textrm{NaN} & \mbox{if } x = \textrm{NaN or } y = \textrm{NaN} \end{cases} \f] \f[ \frac{\partial\, \mbox{operator+}(x, y)}{\partial x} = \begin{cases} 1 & \mbox{if } -\infty\leq x, y \leq \infty \\[6pt] \textrm{NaN} & \mbox{if } x = \textrm{NaN or } y = \textrm{NaN} \end{cases} \f] \f[ \frac{\partial\, \mbox{operator+}(x, y)}{\partial y} = \begin{cases} 1 & \mbox{if } -\infty\leq x, y \leq \infty \\[6pt] \textrm{NaN} & \mbox{if } x = \textrm{NaN or } y = \textrm{NaN} \end{cases} \f] * * @param a First variable operand. * @param b Second variable operand. * @return Variable result of adding two variables. */ inline var operator+(const var& a, const var& b) { return make_callback_vari(a.vi_->val_ + b.vi_->val_, [avi = a.vi_, bvi = b.vi_](const auto& vi) mutable { if (unlikely(std::isnan(vi.val_))) { avi->adj_ = NOT_A_NUMBER; bvi->adj_ = NOT_A_NUMBER; } else { avi->adj_ += vi.adj_; bvi->adj_ += vi.adj_; } }); } /** * Addition operator for variable and scalar (C++). * * The derivative with respect to the variable is * * \f$\frac{d}{dx} (x + c) = 1\f$. * * @tparam Arith An arithmetic type * @param a First variable operand. * @param b Second scalar operand. * @return Result of adding variable and scalar. */ template <typename Arith, require_arithmetic_t<Arith>* = nullptr> inline var operator+(const var& a, Arith b) { if (unlikely(b == 0.0)) { return a; } return make_callback_vari(a.vi_->val_ + b, [avi = a.vi_, b](const auto& vi) mutable { if (unlikely(std::isnan(vi.val_))) { avi->adj_ = NOT_A_NUMBER; } else { avi->adj_ += vi.adj_; } }); } /** * Addition operator for scalar and variable (C++). * * The derivative with respect to the variable is * * \f$\frac{d}{dy} (c + y) = 1\f$. * * @tparam Arith An arithmetic type * @param a First scalar operand. * @param b Second variable operand. * @return Result of adding variable and scalar. */ template <typename Arith, require_arithmetic_t<Arith>* = nullptr> inline var operator+(Arith a, const var& b) { return b + a; // by symmetry } /** * Addition operator for matrix variables (C++). * * @tparam VarMat1 A matrix of vars or a var with an underlying matrix type. * @tparam VarMat2 A matrix of vars or a var with an underlying matrix type. * @param a First variable operand. * @param b Second variable operand. * @return Variable result of adding two variables. */ template <typename VarMat1, typename VarMat2, require_all_rev_matrix_t<VarMat1, VarMat2>* = nullptr> inline auto add(const VarMat1& a, const VarMat2& b) { check_matching_dims("add", "a", a, "b", b); using op_ret_type = decltype(a.val() + b.val()); using ret_type = promote_var_matrix_t<op_ret_type, VarMat1, VarMat2>; arena_t<VarMat1> arena_a(a); arena_t<VarMat2> arena_b(b); arena_t<ret_type> ret(arena_a.val() + arena_b.val()); reverse_pass_callback([ret, arena_a, arena_b]() mutable { for (Eigen::Index i = 0; i < ret.size(); ++i) { const auto ref_adj = ret.adj().coeffRef(i); arena_a.adj().coeffRef(i) += ref_adj; arena_b.adj().coeffRef(i) += ref_adj; } }); return ret_type(ret); } /** * Addition operator for a matrix variable and arithmetic (C++). * * @tparam VarMat A matrix of vars or a var with an underlying matrix type. * @tparam Arith A type with an arithmetic Scalar type. * @param a First variable operand. * @param b Second variable operand. * @return Variable result of adding two variables. */ template <typename Arith, typename VarMat, require_st_arithmetic<Arith>* = nullptr, require_rev_matrix_t<VarMat>* = nullptr> inline auto add(const VarMat& a, const Arith& b) { if (is_eigen<Arith>::value) { check_matching_dims("add", "a", a, "b", b); } using op_ret_type = decltype((a.val().array() + as_array_or_scalar(b)).matrix()); using ret_type = promote_var_matrix_t<op_ret_type, VarMat>; arena_t<VarMat> arena_a(a); arena_t<ret_type> ret(arena_a.val().array() + as_array_or_scalar(b)); reverse_pass_callback( [ret, arena_a]() mutable { arena_a.adj() += ret.adj_op(); }); return ret_type(ret); } /** * Addition operator for an arithmetic type and matrix variable (C++). * * @tparam VarMat A matrix of vars or a var with an underlying matrix type. * @tparam Arith A type with an arithmetic Scalar type. * @param a First variable operand. * @param b Second variable operand. * @return Variable result of adding two variables. */ template <typename Arith, typename VarMat, require_st_arithmetic<Arith>* = nullptr, require_rev_matrix_t<VarMat>* = nullptr> inline auto add(const Arith& a, const VarMat& b) { return add(b, a); } /** * Addition operator for an arithmetic matrix and variable (C++). * * @tparam Var A `var_value` with an underlying arithmetic type. * @tparam EigMat An Eigen Matrix type with an arithmetic Scalar type. * @param a First variable operand. * @param b Second variable operand. * @return Variable result of adding two variables. */ template <typename Var, typename EigMat, require_var_vt<std::is_arithmetic, Var>* = nullptr, require_eigen_vt<std::is_arithmetic, EigMat>* = nullptr> inline auto add(const Var& a, const EigMat& b) { using ret_type = promote_scalar_t<var, EigMat>; arena_t<ret_type> ret(a.val() + b.array()); reverse_pass_callback([ret, a]() mutable { a.adj() += ret.adj().sum(); }); return ret_type(ret); } /** * Addition operator for a variable and arithmetic matrix (C++). * * @tparam EigMat An Eigen Matrix type with an arithmetic Scalar type. * @tparam Var A `var_value` with an underlying arithmetic type. * @param a First variable operand. * @param b Second variable operand. * @return Variable result of adding two variables. */ template <typename EigMat, typename Var, require_eigen_vt<std::is_arithmetic, EigMat>* = nullptr, require_var_vt<std::is_arithmetic, Var>* = nullptr> inline auto add(const EigMat& a, const Var& b) { return add(b, a); } /** * Addition operator for a variable and variable matrix (C++). * * @tparam Var A `var_value` with an underlying arithmetic type. * @tparam VarMat An Eigen Matrix type with a variable Scalar type or a * `var_value` with an underlying matrix type. * @param a First variable operand. * @param b Second variable operand. * @return Variable result of adding two variables. */ template <typename Var, typename VarMat, require_var_vt<std::is_arithmetic, Var>* = nullptr, require_rev_matrix_t<VarMat>* = nullptr> inline auto add(const Var& a, const VarMat& b) { arena_t<VarMat> arena_b(b); arena_t<VarMat> ret(a.val() + arena_b.val().array()); reverse_pass_callback([ret, a, arena_b]() mutable { for (Eigen::Index i = 0; i < arena_b.size(); ++i) { const auto ret_adj = ret.adj().coeffRef(i); a.adj() += ret_adj; arena_b.adj().coeffRef(i) += ret_adj; } }); return plain_type_t<VarMat>(ret); } /** * Addition operator for a variable matrix and variable (C++). * * @tparam VarMat An Eigen Matrix type with a variable Scalar type or a * `var_value` with an underlying matrix type. * @tparam Var A `var_value` with an underlying arithmetic type. * @param a First variable operand. * @param b Second variable operand. * @return Variable result of adding two variables. */ template <typename Var, typename VarMat, require_var_vt<std::is_arithmetic, Var>* = nullptr, require_rev_matrix_t<VarMat>* = nullptr> inline auto add(const VarMat& a, const Var& b) { return add(b, a); } template <typename T1, typename T2, require_any_var_vt<std::is_arithmetic, T1, T2>* = nullptr, require_any_arithmetic_t<T1, T2>* = nullptr> inline auto add(const T1& a, const T2& b) { return a + b; } template <typename T1, typename T2, require_all_var_vt<std::is_arithmetic, T1, T2>* = nullptr> inline auto add(const T1& a, const T2& b) { return a + b; } /** * Addition operator for matrix variables. * * @tparam VarMat1 A matrix of vars or a var with an underlying matrix type. * @tparam VarMat2 A matrix of vars or a var with an underlying matrix type. * @param a First variable operand. * @param b Second variable operand. * @return Variable result of adding two variables. */ template <typename VarMat1, typename VarMat2, require_any_var_matrix_t<VarMat1, VarMat2>* = nullptr> inline auto operator+(const VarMat1& a, const VarMat2& b) { return add(a, b); } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>/* Licensed Materials - Property of IBM DB2 Storage Engine Enablement Copyright IBM Corporation 2007,2008 All rights reserved Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: (a) Redistributions of source code must retain this list of conditions, the copyright notice in section {d} below, and the disclaimer following this list of conditions. (b) Redistributions in binary form must reproduce this list of conditions, the copyright notice in section (d) below, and the disclaimer following this list of conditions, in the documentation and/or other materials provided with the distribution. (c) The name of IBM may not be used to endorse or promote products derived from this software without specific prior written permission. (d) The text of the required copyright notice is: Licensed Materials - Property of IBM DB2 Storage Engine Enablement Copyright IBM Corporation 2007,2008 All rights reserved THIS SOFTWARE IS PROVIDED BY IBM CORPORATION "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 IBM CORPORATION BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "db2i_collationSupport.h" #include "db2i_errors.h" /* The following arrays define a mapping between MySQL collation names and corresponding IBM i sort sequences. The mapping is a 1-to-1 correlation between corresponding array slots but is incomplete without case-sensitivity markers dynamically added to the mySqlSortSequence names. */ #define MAX_COLLATION 89 static const char* mySQLCollation[MAX_COLLATION] = { {"ascii_general"}, {"ascii"}, {"big5_chinese"}, {"big5"}, {"cp1250_croatian"}, {"cp1250_czech"}, {"cp1250_general"}, {"cp1250_polish"}, {"cp1250"}, {"cp1251_bulgarian"}, {"cp1251_general"}, {"cp1251"}, {"cp1256_general"}, {"cp1256"}, {"cp850_general"}, {"cp850"}, {"cp852_general"}, {"cp852"}, {"cp932_japanese"}, {"cp932"}, {"euckr_korean"}, {"euckr"}, {"gb2312_chinese"}, {"gb2312"}, {"gbk_chinese"}, {"gbk"}, {"greek_general"}, {"greek"}, {"hebrew_general"}, {"hebrew"}, {"latin1_danish"}, {"latin1_general"}, {"latin1_german1"}, {"latin1_spanish"}, {"latin1_swedish"}, {"latin1"}, {"latin2_croatian"}, {"latin2_czech"}, {"latin2_general"}, {"latin2_hungarian"}, {"latin2"}, {"latin5_turkish"}, {"latin5"}, {"macce_general"}, {"macce"}, {"sjis_japanese"}, {"sjis"}, {"tis620_thai"}, {"tis620"}, {"ucs2_czech"}, {"ucs2_danish"}, {"ucs2_esperanto"}, {"ucs2_estonian"}, {"ucs2_general"}, {"ucs2_hungarian"}, {"ucs2_icelandic"}, {"ucs2_latvian"}, {"ucs2_lithuanian"}, {"ucs2_persian"}, {"ucs2_polish"}, {"ucs2_romanian"}, {"ucs2_slovak"}, {"ucs2_slovenian"}, {"ucs2_spanish"}, {"ucs2_spanish2"}, {"ucs2_turkish"}, {"ucs2_unicode"}, {"ucs2"}, {"ujis_japanese"}, {"ujis"}, {"utf8_czech"}, {"utf8_danish"}, {"utf8_esperanto"}, {"utf8_estonian"}, {"utf8_general"}, {"utf8_hungarian"}, {"utf8_icelandic"}, {"utf8_latvian"}, {"utf8_lithuanian"}, {"utf8_persian"}, {"utf8_polish"}, {"utf8_romanian"}, {"utf8_slovak"}, {"utf8_slovenian"}, {"utf8_spanish"}, {"utf8_spanish2"}, {"utf8_turkish"}, {"utf8_unicode"}, {"utf8"} }; static const char* mySqlSortSequence[MAX_COLLATION] = { {"QALA101F4"}, {"QBLA101F4"}, {"QACHT04B0"}, {"QBCHT04B0"}, {"QALA20481"}, {"QBLA20481"}, {"QCLA20481"}, {"QDLA20481"}, {"QELA20481"}, {"QACYR0401"}, {"QBCYR0401"}, {"QCCYR0401"}, {"QAARA01A4"}, {"QBARA01A4"}, {"QCLA101F4"}, {"QDLA101F4"}, {"QALA20366"}, {"QBLA20366"}, {"QAJPN04B0"}, {"QBJPN04B0"}, {"QAKOR04B0"}, {"QBKOR04B0"}, {"QACHS04B0"}, {"QBCHS04B0"}, {"QCCHS04B0"}, {"QDCHS04B0"}, {"QAELL036B"}, {"QBELL036B"}, {"QAHEB01A8"}, {"QBHEB01A8"}, {"QALA1047C"}, {"QBLA1047C"}, {"QCLA1047C"}, {"QDLA1047C"}, {"QELA1047C"}, {"QFLA1047C"}, {"QCLA20366"}, {"QDLA20366"}, {"QELA20366"}, {"QFLA20366"}, {"QGLA20366"}, {"QATRK0402"}, {"QBTRK0402"}, {"QHLA20366"}, {"QILA20366"}, {"QCJPN04B0"}, {"QDJPN04B0"}, {"QATHA0346"}, {"QBTHA0346"}, {"ACS"}, {"ADA"}, {"AEO"}, {"AET"}, {"QAUCS04B0"}, {"AHU"}, {"AIS"}, {"ALV"}, {"ALT"}, {"AFA"}, {"APL"}, {"ARO"}, {"ASK"}, {"ASL"}, {"AES"}, {"AES__TRADIT"}, {"ATR"}, {"AEN"}, {"*HEX"}, {"QEJPN04B0"}, {"QFJPN04B0"}, {"ACS"}, {"ADA"}, {"AEO"}, {"AET"}, {"QAUCS04B0"}, {"AHU"}, {"AIS"}, {"ALV"}, {"ALT"}, {"AFA"}, {"APL"}, {"ARO"}, {"ASK"}, {"ASL"}, {"AES"}, {"AES__TRADIT"}, {"ATR"}, {"AEN"}, {"*HEX"} }; /** Get the IBM i sort sequence that corresponds to the given MySQL collation. @param fieldCharSet The collated character set @param[out] rtnSortSequence The corresponding sort sequence @return 0 if successful. Failure otherwise */ static int32 getAssociatedSortSequence(const CHARSET_INFO *fieldCharSet, const char** rtnSortSequence) { DBUG_ENTER("ha_ibmdb2i::getAssociatedSortSequence"); if (strcmp(fieldCharSet->csname,"binary") != 0) { int collationSearchLen = strlen(fieldCharSet->name); if (fieldCharSet->state & MY_CS_BINSORT) collationSearchLen -= 4; else collationSearchLen -= 3; uint16 loopCnt = 0; for (loopCnt; loopCnt < MAX_COLLATION; ++loopCnt) { if ((strlen(mySQLCollation[loopCnt]) == collationSearchLen) && (strncmp((char*)mySQLCollation[loopCnt], fieldCharSet->name, collationSearchLen) == 0)) break; } if (loopCnt == MAX_COLLATION) // Did not find associated sort sequence { getErrTxt(DB2I_ERR_SRTSEQ); DBUG_RETURN(DB2I_ERR_SRTSEQ); } *rtnSortSequence = mySqlSortSequence[loopCnt]; } DBUG_RETURN(0); } /** Update sort sequence information for a key. This function accumulates information about a key as it is called for each field composing the key. The caller should invoke the function for each field and (with the exception of the charset parm) preserve the values for the parms across invocations, until a particular key has been evaluated. Once the last field in the key has been evaluated, the fileSortSequence and fileSortSequenceLibrary parms will contain the correct information for creating the corresponding DB2 key. @param charset The character set under consideration @param[in, out] fileSortSequenceType The type of the current key's sort seq @param[in, out] fileSortSequence The IBM i identifier for the DB2 sort sequence that corresponds @return 0 if successful. Failure otherwise */ int32 updateAssociatedSortSequence(const CHARSET_INFO* charset, char* fileSortSequenceType, char* fileSortSequence, char* fileSortSequenceLibrary) { DBUG_ENTER("ha_ibmdb2i::updateAssociatedSortSequence"); DBUG_ASSERT(charset); if (strcmp(charset->csname,"binary") != 0) { char newSortSequence[11] = ""; char newSortSequenceType = ' '; const char* foundSortSequence; int rc = getAssociatedSortSequence(charset, &foundSortSequence); if (rc) DBUG_RETURN (rc); switch(foundSortSequence[0]) { case '*': // Binary strcat(newSortSequence,foundSortSequence); newSortSequenceType = 'B'; break; case 'Q': // Non-ICU sort sequence strcat(newSortSequence,foundSortSequence); if ((charset->state & MY_CS_BINSORT) != 0) { strcat(newSortSequence,"U"); } else if ((charset->state & MY_CS_CSSORT) != 0) { strcat(newSortSequence,"U"); } else { strcat(newSortSequence,"S"); } newSortSequenceType = 'N'; break; default: // ICU sort sequence { if ((charset->state & MY_CS_CSSORT) == 0) { if (osVersion.v >= 6) strcat(newSortSequence,"I34"); // ICU 3.4 else strcat(newSortSequence,"I26"); // ICU 2.6.1 } strcat(newSortSequence,foundSortSequence); newSortSequenceType = 'I'; } break; } if (*fileSortSequenceType == ' ') // If no sort sequence has been set yet { // Set associated sort sequence strcpy(fileSortSequence,newSortSequence); strcpy(fileSortSequenceLibrary,"QSYS"); *fileSortSequenceType = newSortSequenceType; } else if (strcmp(fileSortSequence,newSortSequence) != 0) { // Only one sort sequence/collation is supported for each DB2 index. getErrTxt(DB2I_ERR_MIXED_COLLATIONS); DBUG_RETURN(DB2I_ERR_MIXED_COLLATIONS); } } DBUG_RETURN(0); } <commit_msg>merging with mysql-5.1-bugteam tree<commit_after>/* Licensed Materials - Property of IBM DB2 Storage Engine Enablement Copyright IBM Corporation 2007,2008 All rights reserved Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: (a) Redistributions of source code must retain this list of conditions, the copyright notice in section {d} below, and the disclaimer following this list of conditions. (b) Redistributions in binary form must reproduce this list of conditions, the copyright notice in section (d) below, and the disclaimer following this list of conditions, in the documentation and/or other materials provided with the distribution. (c) The name of IBM may not be used to endorse or promote products derived from this software without specific prior written permission. (d) The text of the required copyright notice is: Licensed Materials - Property of IBM DB2 Storage Engine Enablement Copyright IBM Corporation 2007,2008 All rights reserved THIS SOFTWARE IS PROVIDED BY IBM CORPORATION "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 IBM CORPORATION BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "db2i_collationSupport.h" #include "db2i_errors.h" /* The following arrays define a mapping between MySQL collation names and corresponding IBM i sort sequences. The mapping is a 1-to-1 correlation between corresponding array slots but is incomplete without case-sensitivity markers dynamically added to the mySqlSortSequence names. */ #define MAX_COLLATION 89 static const char* mySQLCollation[MAX_COLLATION] = { {"ascii_general"}, {"ascii"}, {"big5_chinese"}, {"big5"}, {"cp1250_croatian"}, {"cp1250_czech"}, {"cp1250_general"}, {"cp1250_polish"}, {"cp1250"}, {"cp1251_bulgarian"}, {"cp1251_general"}, {"cp1251"}, {"cp1256_general"}, {"cp1256"}, {"cp850_general"}, {"cp850"}, {"cp852_general"}, {"cp852"}, {"cp932_japanese"}, {"cp932"}, {"euckr_korean"}, {"euckr"}, {"gb2312_chinese"}, {"gb2312"}, {"gbk_chinese"}, {"gbk"}, {"greek_general"}, {"greek"}, {"hebrew_general"}, {"hebrew"}, {"latin1_danish"}, {"latin1_general"}, {"latin1_german1"}, {"latin1_spanish"}, {"latin1_swedish"}, {"latin1"}, {"latin2_croatian"}, {"latin2_czech"}, {"latin2_general"}, {"latin2_hungarian"}, {"latin2"}, {"latin5_turkish"}, {"latin5"}, {"macce_general"}, {"macce"}, {"sjis_japanese"}, {"sjis"}, {"tis620_thai"}, {"tis620"}, {"ucs2_czech"}, {"ucs2_danish"}, {"ucs2_esperanto"}, {"ucs2_estonian"}, {"ucs2_general"}, {"ucs2_hungarian"}, {"ucs2_icelandic"}, {"ucs2_latvian"}, {"ucs2_lithuanian"}, {"ucs2_persian"}, {"ucs2_polish"}, {"ucs2_romanian"}, {"ucs2_slovak"}, {"ucs2_slovenian"}, {"ucs2_spanish"}, {"ucs2_swedish"}, {"ucs2_turkish"}, {"ucs2_unicode"}, {"ucs2"}, {"ujis_japanese"}, {"ujis"}, {"utf8_czech"}, {"utf8_danish"}, {"utf8_esperanto"}, {"utf8_estonian"}, {"utf8_general"}, {"utf8_hungarian"}, {"utf8_icelandic"}, {"utf8_latvian"}, {"utf8_lithuanian"}, {"utf8_persian"}, {"utf8_polish"}, {"utf8_romanian"}, {"utf8_slovak"}, {"utf8_slovenian"}, {"utf8_spanish"}, {"utf8_swedish"}, {"utf8_turkish"}, {"utf8_unicode"}, {"utf8"} }; static const char* mySqlSortSequence[MAX_COLLATION] = { {"QALA101F4"}, {"QBLA101F4"}, {"QACHT04B0"}, {"QBCHT04B0"}, {"QALA20481"}, {"QBLA20481"}, {"QCLA20481"}, {"QDLA20481"}, {"QELA20481"}, {"QACYR0401"}, {"QBCYR0401"}, {"QCCYR0401"}, {"QAARA01A4"}, {"QBARA01A4"}, {"QCLA101F4"}, {"QDLA101F4"}, {"QALA20366"}, {"QBLA20366"}, {"QAJPN04B0"}, {"QBJPN04B0"}, {"QAKOR04B0"}, {"QBKOR04B0"}, {"QACHS04B0"}, {"QBCHS04B0"}, {"QCCHS04B0"}, {"QDCHS04B0"}, {"QAELL036B"}, {"QBELL036B"}, {"QAHEB01A8"}, {"QBHEB01A8"}, {"QALA1047C"}, {"QBLA1047C"}, {"QCLA1047C"}, {"QDLA1047C"}, {"QELA1047C"}, {"QFLA1047C"}, {"QCLA20366"}, {"QDLA20366"}, {"QELA20366"}, {"QFLA20366"}, {"QGLA20366"}, {"QATRK0402"}, {"QBTRK0402"}, {"QHLA20366"}, {"QILA20366"}, {"QCJPN04B0"}, {"QDJPN04B0"}, {"QATHA0346"}, {"QBTHA0346"}, {"ACS"}, {"ADA"}, {"AEO"}, {"AET"}, {"QAUCS04B0"}, {"AHU"}, {"AIS"}, {"ALV"}, {"ALT"}, {"AFA"}, {"APL"}, {"ARO"}, {"ASK"}, {"ASL"}, {"AES"}, {"ASW"}, {"ATR"}, {"AEN"}, {"*HEX"}, {"QEJPN04B0"}, {"QFJPN04B0"}, {"ACS"}, {"ADA"}, {"AEO"}, {"AET"}, {"QAUCS04B0"}, {"AHU"}, {"AIS"}, {"ALV"}, {"ALT"}, {"AFA"}, {"APL"}, {"ARO"}, {"ASK"}, {"ASL"}, {"AES"}, {"ASW"}, {"ATR"}, {"AEN"}, {"*HEX"} }; /** Get the IBM i sort sequence that corresponds to the given MySQL collation. @param fieldCharSet The collated character set @param[out] rtnSortSequence The corresponding sort sequence @return 0 if successful. Failure otherwise */ static int32 getAssociatedSortSequence(const CHARSET_INFO *fieldCharSet, const char** rtnSortSequence) { DBUG_ENTER("ha_ibmdb2i::getAssociatedSortSequence"); if (strcmp(fieldCharSet->csname,"binary") != 0) { int collationSearchLen = strlen(fieldCharSet->name); if (fieldCharSet->state & MY_CS_BINSORT) collationSearchLen -= 4; else collationSearchLen -= 3; uint16 loopCnt = 0; for (loopCnt; loopCnt < MAX_COLLATION; ++loopCnt) { if ((strlen(mySQLCollation[loopCnt]) == collationSearchLen) && (strncmp((char*)mySQLCollation[loopCnt], fieldCharSet->name, collationSearchLen) == 0)) break; } if (loopCnt == MAX_COLLATION) // Did not find associated sort sequence { getErrTxt(DB2I_ERR_SRTSEQ); DBUG_RETURN(DB2I_ERR_SRTSEQ); } *rtnSortSequence = mySqlSortSequence[loopCnt]; } DBUG_RETURN(0); } /** Update sort sequence information for a key. This function accumulates information about a key as it is called for each field composing the key. The caller should invoke the function for each field and (with the exception of the charset parm) preserve the values for the parms across invocations, until a particular key has been evaluated. Once the last field in the key has been evaluated, the fileSortSequence and fileSortSequenceLibrary parms will contain the correct information for creating the corresponding DB2 key. @param charset The character set under consideration @param[in, out] fileSortSequenceType The type of the current key's sort seq @param[in, out] fileSortSequence The IBM i identifier for the DB2 sort sequence that corresponds @return 0 if successful. Failure otherwise */ int32 updateAssociatedSortSequence(const CHARSET_INFO* charset, char* fileSortSequenceType, char* fileSortSequence, char* fileSortSequenceLibrary) { DBUG_ENTER("ha_ibmdb2i::updateAssociatedSortSequence"); DBUG_ASSERT(charset); if (strcmp(charset->csname,"binary") != 0) { char newSortSequence[11] = ""; char newSortSequenceType = ' '; const char* foundSortSequence; int rc = getAssociatedSortSequence(charset, &foundSortSequence); if (rc) DBUG_RETURN (rc); switch(foundSortSequence[0]) { case '*': // Binary strcat(newSortSequence,foundSortSequence); newSortSequenceType = 'B'; break; case 'Q': // Non-ICU sort sequence strcat(newSortSequence,foundSortSequence); if ((charset->state & MY_CS_BINSORT) != 0) { strcat(newSortSequence,"U"); } else if ((charset->state & MY_CS_CSSORT) != 0) { strcat(newSortSequence,"U"); } else { strcat(newSortSequence,"S"); } newSortSequenceType = 'N'; break; default: // ICU sort sequence { if ((charset->state & MY_CS_CSSORT) == 0) { if (osVersion.v >= 6) strcat(newSortSequence,"I34"); // ICU 3.4 else strcat(newSortSequence,"I26"); // ICU 2.6.1 } strcat(newSortSequence,foundSortSequence); newSortSequenceType = 'I'; } break; } if (*fileSortSequenceType == ' ') // If no sort sequence has been set yet { // Set associated sort sequence strcpy(fileSortSequence,newSortSequence); strcpy(fileSortSequenceLibrary,"QSYS"); *fileSortSequenceType = newSortSequenceType; } else if (strcmp(fileSortSequence,newSortSequence) != 0) { // Only one sort sequence/collation is supported for each DB2 index. getErrTxt(DB2I_ERR_MIXED_COLLATIONS); DBUG_RETURN(DB2I_ERR_MIXED_COLLATIONS); } } DBUG_RETURN(0); } <|endoftext|>
<commit_before>/* An erlang driver for taglib that outputs JSON. This process is passed filenames on stdin (from erlang) It uses taglib on the file, and outputs JSON containing the metadata, according to taglib. One line of JSON output per file. */ #include <taglib/fileref.h> #include <taglib/tag.h> #include <iostream> #include <cstdio> #include <sstream> #include <algorithm> #include <string> #include <netinet/in.h> // for htonl etc using namespace std; #ifdef WIN32 wstring fromUtf8(const string& i); string toUtf8(const wstring& i); #else #define fromUtf8(s) (s) #define toUtf8(s) (s) #endif void trim(string& str) { size_t startpos = str.find_first_not_of(" \t"); size_t endpos = str.find_last_not_of(" \t"); if(( string::npos == startpos ) || ( string::npos == endpos)) str = ""; else str = str.substr( startpos, endpos-startpos+1 ); } string urlify(const string& p) { // turn it into a url by prepending file:// // because we pass all urls to curl: string urlpath("file://"); if (p.at(0)=='/') // posix path starting with / { urlpath += p; } else if (p.at(1)==':') // windows style filepath { urlpath += "/" + p; } else urlpath = p; return urlpath; } string ext2mime(const string& ext) { if(ext==".mp3") return "audio/mpeg"; if(ext==".aac") return "audio/mp4"; if(ext==".mp4") return "audio/mp4"; if(ext==".m4a") return "audio/mp4"; if(ext==".ogg") return "application/ogg"; cerr << "Warning, unhandled file extension. Don't know mimetype for " << ext << endl; //generic: return "application/octet-stream"; } // replace whitespace and other control codes with ' ' and replace multiple whitespace with single string tidy(const string& s) { string r; bool prevWasSpace = false; r.reserve(s.length()); for (string::const_iterator i = s.begin(); i != s.end(); i++) { if (*i > 0 && *i <= ' ') { if (!prevWasSpace) { r += ' '; prevWasSpace = true; } } else if (*i == '"') { r += '\\'; r += '"'; prevWasSpace = false; } else { r += *i; prevWasSpace = false; } } return r; } string esc(const string& s) { string r; bool prevWasSpace = false; r.reserve(s.length()+4); for (string::const_iterator i = s.begin(); i != s.end(); i++) { if (*i == '"') { r += '\\'; r += '"'; prevWasSpace = false; } else { r += *i; prevWasSpace = false; } } return r; } string scan_file(const char* path) { TagLib::FileRef f(path); if (!f.isNull() && f.tag()) { TagLib::Tag *tag = f.tag(); int bitrate = 0; int duration = 0; if (f.audioProperties()) { TagLib::AudioProperties *properties = f.audioProperties(); duration = properties->length(); bitrate = properties->bitrate(); } string artist = tag->artist().toCString(true); string album = tag->album().toCString(true); string track = tag->title().toCString(true); trim(artist); trim(album); trim(track); if (artist.length()==0 || track.length()==0) { return "{\"error\" : \"no tags\"}\n"; } string pathstr(path); string ext = pathstr.substr(pathstr.length()-4); std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); string mimetype = ext2mime(ext); // turn it into a url by prepending file:// // because we pass all urls to curl: string urlpath = urlify( toUtf8(path) ); ostringstream os; os << "{ \"url\" : \"" << esc(urlpath) << "\"," " \"mimetype\" : \"" << mimetype << "\"," " \"artist\" : \"" << tidy(artist) << "\"," " \"album\" : \"" << tidy(album) << "\"," " \"track\" : \"" << tidy(track) << "\"," " \"duration\" : " << duration << "," " \"bitrate\" : " << bitrate << "," " \"trackno\" : " << tag->track() << "}\n"; return os.str(); } return "{\"error\" : \"no tags\"}\n"; } int readn(unsigned char *buf, int len) { int i, got = 0; do { if((i=read(0,buf+got, len-got))<=0) return i; got += i; } while(got<len); return len; } int writen(unsigned char *buf, int len) { int i, wrote = 0; do { if ((i = write(1, buf+wrote, len-wrote)) <= 0) return i; wrote += i; } while (wrote<len); return len; } #ifdef WIN32 int wmain(int argc, wchar_t* argv[]) #else int main(int argc, char* argv[]) #endif { //scan_file( argv[1] ); unsigned char buffer[256]; unsigned int len0,len; while(1) { if(readn((unsigned char*)&len0,4)!=4) break; len = ntohl(len0); readn((unsigned char*)&buffer, len); buffer[len]='\0'; string j = scan_file((const char*)&buffer); unsigned int l = htonl(j.length()); writen((unsigned char*)&l,4); printf("%s", j.c_str()); cout.flush(); } } <commit_msg>Port taglib_json_reader to windows<commit_after>/* An erlang driver for taglib that outputs JSON. This process is passed filenames on stdin (from erlang) It uses taglib on the file, and outputs JSON containing the metadata, according to taglib. One line of JSON output per file. */ #include <taglib/fileref.h> #include <taglib/tag.h> #include <cstdio> #include <sstream> #include <algorithm> #include <string> #ifdef WIN32 #include <Winsock2.h> #else #include <netinet/in.h> // for htonl etc #endif using namespace std; #ifdef WIN32 wstring fromUtf8(const string& i); string toUtf8(const wstring& i); #else #define fromUtf8(s) (s) #define toUtf8(s) (s) #endif void trim(string& str) { size_t startpos = str.find_first_not_of(" \t"); size_t endpos = str.find_last_not_of(" \t"); if(( string::npos == startpos ) || ( string::npos == endpos)) str = ""; else str = str.substr( startpos, endpos-startpos+1 ); } string urlify(const string& p) { // turn it into a url by prepending file:// // because we pass all urls to curl: string urlpath("file://"); if (p.at(0)=='/') // posix path starting with / { urlpath += p; } else if (p.at(1)==':') // windows style filepath { urlpath += "/" + p; } else urlpath = p; return urlpath; } string ext2mime(const string& ext) { if(ext==".mp3") return "audio/mpeg"; if(ext==".aac") return "audio/mp4"; if(ext==".mp4") return "audio/mp4"; if(ext==".m4a") return "audio/mp4"; if(ext==".ogg") return "application/ogg"; cerr << "Warning, unhandled file extension. Don't know mimetype for " << ext << endl; //generic: return "application/octet-stream"; } // replace whitespace and other control codes with ' ' and replace multiple whitespace with single string tidy(const string& s) { string r; bool prevWasSpace = false; r.reserve(s.length()); for (string::const_iterator i = s.begin(); i != s.end(); i++) { if (*i > 0 && *i <= ' ') { if (!prevWasSpace) { r += ' '; prevWasSpace = true; } } else if (*i == '"') { r += '\\'; r += '"'; prevWasSpace = false; } else { r += *i; prevWasSpace = false; } } return r; } string esc(const string& s) { string r; bool prevWasSpace = false; r.reserve(s.length()+4); for (string::const_iterator i = s.begin(); i != s.end(); i++) { if (*i == '"') { r += '\\'; r += '"'; prevWasSpace = false; } else { r += *i; prevWasSpace = false; } } return r; } string scan_file(const char* path) { TagLib::FileRef f(path); if (!f.isNull() && f.tag()) { TagLib::Tag *tag = f.tag(); int bitrate = 0; int duration = 0; if (f.audioProperties()) { TagLib::AudioProperties *properties = f.audioProperties(); duration = properties->length(); bitrate = properties->bitrate(); } string artist = tag->artist().toCString(true); string album = tag->album().toCString(true); string track = tag->title().toCString(true); trim(artist); trim(album); trim(track); if (artist.length()==0 || track.length()==0) { return "{\"error\" : \"no tags\"}\n"; } string pathstr(path); string ext = pathstr.substr(pathstr.length()-4); std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); string mimetype = ext2mime(ext); // turn it into a url by prepending file:// // because we pass all urls to curl: string urlpath = urlify( path ); ostringstream os; os << "{ \"url\" : \"" << esc(urlpath) << "\"," " \"mimetype\" : \"" << mimetype << "\"," " \"artist\" : \"" << tidy(artist) << "\"," " \"album\" : \"" << tidy(album) << "\"," " \"track\" : \"" << tidy(track) << "\"," " \"duration\" : " << duration << "," " \"bitrate\" : " << bitrate << "," " \"trackno\" : " << tag->track() << "}\n"; return os.str(); } return "{\"error\" : \"no tags\"}\n"; } #ifdef WIN32 int wmain(int argc, wchar_t* argv[]) #else int main(int argc, char* argv[]) #endif { //scan_file( argv[1] ); char buffer[256]; unsigned int len0,len; while(1) { if(fread(&len0, 4, 1, stdin)!=1) break; len = ntohl(len0); fread(&buffer, 1, len, stdin); buffer[len]='\0'; string j = scan_file((const char*)&buffer); // newlines #ifdef WIN32 unsigned int l = htonl(j.length()+1); #else unsigned int l = htonl(j.length()); #endif fwrite(&l,4,1,stdout); printf("%s", j.c_str()); fflush(stdout); } return 0; } <|endoftext|>
<commit_before>/** @file @brief Implementation @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Sensics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Internal Includes #include "HDKLedIdentifierFactory.h" #include "HDKLedIdentifier.h" // Library/third-party includes #include <boost/assert.hpp> // Standard includes // - none namespace osvr { namespace vbtracker { /// @brief Helper for factory function. static inline LedIdentifierPtr createHDKLedIdentifier(const PatternStringList &patterns) { LedIdentifierPtr ret{new OsvrHdkLedIdentifier(patterns)}; return ret; } // clang-format off /// @brief Determines the LED IDs for the OSVR HDK sensor 0 (face plate) /// These estimates are from the original documentation, not from the /// as-built measurements. /// First number in comments is overall LED ID, second is LED ID in the /// sensor it was in static const std::vector<std::string> OsvrHdkLedIdentifier_SENSOR0_PATTERNS_ORIGINAL = { "..*.....*...*..." // 7 1 , "...*......*...*." // 8 2 , ".......*...*...*" // 9 3 , "......*...*..*.." // 10 4 , ".......*....*..*" // 11 5 , "..*.....*..*...." // 12 6 , "....*......*..*." // 13 7 , "....*..*....*..." // 14 8 , "..*...*........*" // 15 9 , "........*..*..*." // 16 10 , "..*..*.*........" // 17 11 , "....*...*.*....." // 18 12 , "...*.*........*." // 19 13 , "...*.....*.*...." // 20 14 , "....*.*......*.." // 21 15 , "*.......*.*....." // 22 16 , ".*........*.*..." // 23 17 , ".*.........*.*.." // 24 18 , "....*.*..*......" // 25 19 , ".*.*.*.........." // 26 20 , ".........*.**..." // 27 21 , "**...........*.." // 28 22 , ".*...**........." // 29 23 , ".........*....**" // 30 24 , "..*.....**......" // 31 25 , "*......**......." // 32 26 , "...*.......**..." // 33 27 , "...**.....*....." // 34 28 , ".**....*........" // 35 29 , "....**...*......" // 36 30 , "*...........**.." // 37 31 , "......**.*......" // 38 32 , ".............***" // 39 33 , "..........*....." // 40 34 }; /// @brief Determines the LED IDs for the OSVR HDK sensor 1 (back plate) /// These estimates are from the original documentation, not from the /// as-built measurements. static const std::vector<std::string> OsvrHdkLedIdentifier_SENSOR1_PATTERNS_ORIGINAL = { "***...*........*" // 1 1 , "...****..*......" // 2 2 , "*.*..........***" // 3 3 , "**...........***" // 4 4 , "*....*....*....." // 5 5 , "...*....*...*..." // 6 6 }; /// @brief Determines the LED IDs for the OSVR HDK sensor 0 (face plate) /// These are from the as-built measurements. /// First number in comments is overall LED ID, second is LED ID in the /// sensor it was in static const std::vector<std::string> OsvrHdkLedIdentifier_SENSOR0_PATTERNS = { "..*.....**......" // 1 , "*......**......." // 2 , ".*...**........." // 3 , ".........*....**" // 4 , ".**....*........" // 5 , "....**...*......" // 6 , "**...........*.." // 7 , ".*.*.*.........." // 8 , ".........*.**..." // 9 , "....*.*..*......" // 10 , "....*.*......*.." // 11 , "*.......*.*....." // 28 , ".*........*.*..." // 27 , ".*.........*.*.." // 25 , "..*..*.*........" // 15 , "....*...*.*....." // 16 , "...*.*........*." // 17 , "...*.....*.*...." // 18 , "....*......*..*." // 19 , "....*..*....*..." // 20 , "..*...*........*" // 21 , "........*..*..*." // 22 , ".......*...*...*" // 23 , "......*...*..*.." // 24 , ".......*....*..*" // 14 , "..*.....*..*...." // 26 , "*....*....*....." // 13 , "...*....*...*..." // 12 , "..*.....*...*..." // 29 , "...*......*...*." // 30 , "***...*........*" // 31 , "...****..*......" // 32 , "*.*..........***" // 33 , "**...........***" // 34 }; /// @brief Determines the LED IDs for the OSVR HDK sensor 1 (back plate) /// These are from the as-built measurements. static const std::vector<std::string> OsvrHdkLedIdentifier_SENSOR1_PATTERNS = { "*...........**.." // 37 31 , "......**.*......" // 38 32 , ".............***" // 39 33 , "..........*....." // 40 34 , "...*.......**..." // 33 27 , "...**.....*....." // 34 28 }; // clang-format on LedIdentifierPtr createHDKLedIdentifier(uint8_t sensor) { LedIdentifierPtr ret; switch (sensor) { case 0: ret = createHDKLedIdentifier(OsvrHdkLedIdentifier_SENSOR0_PATTERNS); break; case 1: ret = createHDKLedIdentifier(OsvrHdkLedIdentifier_SENSOR1_PATTERNS); default: BOOST_ASSERT_MSG(sensor < 2, "Valid sensors are only 0 or 1!"); break; } return ret; } // clang-format off /// @brief Patterns found in the "HDK_random_images" folder, which has only /// 8 images for each and they are a random subset of the actual images. static const std::vector<std::string> OsvrHdkLedIdentifier_RANDOM_IMAGES_PATTERNS = { "..*....." // 7 , "...*...." // 8 , ".......*" // 9 , "......*." // 10 , ".......*" // 11 , "..*....." // 12 , "....*..." // 13 , "....*..*" // 14 , "********" // 15 , "........" // 16 , "********" // 17 , "....*..." // 18 , "...*.*.." // 19 , "...*...." // 20 , "....*.*." // 21 , "...*.***" // 22 , ".*......" // 23 , "..*...*." // 24 , "....*.*." // 25 , ".*.*.*.." // 26 , "........" // 27 , "**......" // 28 , ".*...**." // 29 , "........" // 30 , "..*....." // 31 , "*......*" // 32 , "...*...." // 33 , "...**..." // 34 , ".......*" // 35 , "*..*..*." // 36 , "*......." // 37 , "......**" // 38 , "........" // 39 , "........" // 40 }; // clang-format on LedIdentifierPtr createRandomHDKLedIdentifier() { return createHDKLedIdentifier( OsvrHdkLedIdentifier_RANDOM_IMAGES_PATTERNS); } } // End namespace vbtracker } // End namespace osvr <commit_msg>Now has the LEDs ordered correctly w.r.t. the first HDK shipped in the OSVR packing box, compared to the list of locations in the BeaconBasedPoseEstimator. Note that a couple of the beacons on the top are not actaully where they were listed on the diagram, so that will need to be changed.<commit_after>/** @file @brief Implementation @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Sensics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Internal Includes #include "HDKLedIdentifierFactory.h" #include "HDKLedIdentifier.h" // Library/third-party includes #include <boost/assert.hpp> // Standard includes // - none namespace osvr { namespace vbtracker { /// @brief Helper for factory function. static inline LedIdentifierPtr createHDKLedIdentifier(const PatternStringList &patterns) { LedIdentifierPtr ret{new OsvrHdkLedIdentifier(patterns)}; return ret; } // clang-format off /// @brief Determines the LED IDs for the OSVR HDK sensor 0 (face plate) /// These estimates are from the original documentation, not from the /// as-built measurements. /// First number in comments is overall LED ID, second is LED ID in the /// sensor it was in static const std::vector<std::string> OsvrHdkLedIdentifier_SENSOR0_PATTERNS_ORIGINAL = { "..*.....*...*..." // 7 1 , "...*......*...*." // 8 2 , ".......*...*...*" // 9 3 , "......*...*..*.." // 10 4 , ".......*....*..*" // 11 5 , "..*.....*..*...." // 12 6 , "....*......*..*." // 13 7 , "....*..*....*..." // 14 8 , "..*...*........*" // 15 9 , "........*..*..*." // 16 10 , "..*..*.*........" // 17 11 , "....*...*.*....." // 18 12 , "...*.*........*." // 19 13 , "...*.....*.*...." // 20 14 , "....*.*......*.." // 21 15 , "*.......*.*....." // 22 16 , ".*........*.*..." // 23 17 , ".*.........*.*.." // 24 18 , "....*.*..*......" // 25 19 , ".*.*.*.........." // 26 20 , ".........*.**..." // 27 21 , "**...........*.." // 28 22 , ".*...**........." // 29 23 , ".........*....**" // 30 24 , "..*.....**......" // 31 25 , "*......**......." // 32 26 , "...*.......**..." // 33 27 , "...**.....*....." // 34 28 , ".**....*........" // 35 29 , "....**...*......" // 36 30 , "*...........**.." // 37 31 , "......**.*......" // 38 32 , ".............***" // 39 33 , "..........*....." // 40 34 }; /// @brief Determines the LED IDs for the OSVR HDK sensor 1 (back plate) /// These estimates are from the original documentation, not from the /// as-built measurements. static const std::vector<std::string> OsvrHdkLedIdentifier_SENSOR1_PATTERNS_ORIGINAL = { "***...*........*" // 1 1 , "...****..*......" // 2 2 , "*.*..........***" // 3 3 , "**...........***" // 4 4 , "*....*....*....." // 5 5 , "...*....*...*..." // 6 6 }; /// @brief Determines the LED IDs for the OSVR HDK sensor 0 (face plate) /// These are from the as-built measurements. /// First number in comments is overall LED ID, second is LED ID in the /// sensor it was in static const std::vector<std::string> OsvrHdkLedIdentifier_SENSOR0_PATTERNS = { ".**....*........" // 5 , "....**...*......" // 6 , ".*...**........." // 3 , ".........*....**" // 4 , "..*.....**......" // 1 , "*......**......." // 2 , "....*.*..*......" // 10 , ".*.*.*.........." // 8 , ".........*.**..." // 9 , "**...........*.." // 7 , "....*.*......*.." // 11 , "*.......*.*....." // 28 , ".*........*.*..." // 27 , ".*.........*.*.." // 25 , "..*..*.*........" // 15 , "....*...*.*....." // 16 , "...*.*........*." // 17 , "...*.....*.*...." // 18 , "....*......*..*." // 19 , "....*..*....*..." // 20 , "..*...*........*" // 21 , "........*..*..*." // 22 , ".......*...*...*" // 23 , "......*...*..*.." // 24 , ".......*....*..*" // 14 , "..*.....*..*...." // 26 , "*....*....*....." // 13 , "...*....*...*..." // 12 , "..*.....*...*..." // 29 , "...*......*...*." // 30 , "***...*........*" // 31 , "...****..*......" // 32 , "*.*..........***" // 33 , "**...........***" // 34 }; /// @brief Determines the LED IDs for the OSVR HDK sensor 1 (back plate) /// These are from the as-built measurements. static const std::vector<std::string> OsvrHdkLedIdentifier_SENSOR1_PATTERNS = { "*...........**.." // 37 31 , "......**.*......" // 38 32 , ".............***" // 39 33 , "..........*....." // 40 34 , "...*.......**..." // 33 27 , "...**.....*....." // 34 28 }; // clang-format on LedIdentifierPtr createHDKLedIdentifier(uint8_t sensor) { LedIdentifierPtr ret; switch (sensor) { case 0: ret = createHDKLedIdentifier(OsvrHdkLedIdentifier_SENSOR0_PATTERNS); break; case 1: ret = createHDKLedIdentifier(OsvrHdkLedIdentifier_SENSOR1_PATTERNS); default: BOOST_ASSERT_MSG(sensor < 2, "Valid sensors are only 0 or 1!"); break; } return ret; } // clang-format off /// @brief Patterns found in the "HDK_random_images" folder, which has only /// 8 images for each and they are a random subset of the actual images. static const std::vector<std::string> OsvrHdkLedIdentifier_RANDOM_IMAGES_PATTERNS = { "..*....." // 7 , "...*...." // 8 , ".......*" // 9 , "......*." // 10 , ".......*" // 11 , "..*....." // 12 , "....*..." // 13 , "....*..*" // 14 , "********" // 15 , "........" // 16 , "********" // 17 , "....*..." // 18 , "...*.*.." // 19 , "...*...." // 20 , "....*.*." // 21 , "...*.***" // 22 , ".*......" // 23 , "..*...*." // 24 , "....*.*." // 25 , ".*.*.*.." // 26 , "........" // 27 , "**......" // 28 , ".*...**." // 29 , "........" // 30 , "..*....." // 31 , "*......*" // 32 , "...*...." // 33 , "...**..." // 34 , ".......*" // 35 , "*..*..*." // 36 , "*......." // 37 , "......**" // 38 , "........" // 39 , "........" // 40 }; // clang-format on LedIdentifierPtr createRandomHDKLedIdentifier() { return createHDKLedIdentifier( OsvrHdkLedIdentifier_RANDOM_IMAGES_PATTERNS); } } // End namespace vbtracker } // End namespace osvr <|endoftext|>
<commit_before>/* This file is part of the KDE project Copyright (C) 2007 Matthias Kretz <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "kiomediastream.h" #include "kiomediastream_p.h" #include <kdebug.h> #include <kprotocolmanager.h> #include <kio/filejob.h> #include <kio/job.h> #include <klocale.h> namespace Phonon { KioMediaStream::KioMediaStream(const QUrl &url, QObject *parent) : AbstractMediaStream(*new KioMediaStreamPrivate(url), parent) { reset(); } void KioMediaStream::reset() { Q_D(KioMediaStream); if (d->kiojob) { d->kiojob->disconnect(this); d->kiojob->kill(); d->endOfDataSent = false; d->seeking = false; d->reading = false; d->open = false; d->seekPosition = 0; } if (KProtocolManager::supportsOpening(d->url)) { d->kiojob = KIO::open(d->url, QIODevice::ReadOnly); Q_ASSERT(d->kiojob); d->open = false; setStreamSeekable(true); connect(d->kiojob, SIGNAL(open(KIO::Job *)), this, SLOT(_k_bytestreamFileJobOpen(KIO::Job *))); connect(d->kiojob, SIGNAL(position(KIO::Job *, KIO::filesize_t)), this, SLOT(_k_bytestreamSeekDone(KIO::Job *, KIO::filesize_t))); } else { d->kiojob = KIO::get(d->url, false, false); Q_ASSERT(d->kiojob); setStreamSeekable(false); connect(d->kiojob, SIGNAL(totalSize(KJob *, qulonglong)), this, SLOT(_k_bytestreamTotalSize(KJob *,qulonglong))); d->kiojob->suspend(); } d->kiojob->addMetaData("UserAgent", QLatin1String("KDE Phonon")); connect(d->kiojob, SIGNAL(data(KIO::Job *,const QByteArray &)), this, SLOT(_k_bytestreamData(KIO::Job *,const QByteArray &))); connect(d->kiojob, SIGNAL(result(KJob *)), this, SLOT(_k_bytestreamResult(KJob *))); } KioMediaStream::~KioMediaStream() { } void KioMediaStream::needData() { Q_D(KioMediaStream); if (!d->kiojob) { // no job => job is finished and endOfData was already sent return; } KIO::FileJob *filejob = qobject_cast<KIO::FileJob *>(d->kiojob); if (filejob) { // while d->seeking the backend won't get any data if (d->seeking || !d->open) { d->reading = true; } else if (!d->reading) { d->reading = true; filejob->read(32768); } } else { // KIO::TransferJob d->kiojob->resume(); } } void KioMediaStream::enoughData() { Q_D(KioMediaStream); kDebug(600) ; // Don't suspend when using a FileJob. The FileJob is controlled by calls to // FileJob::read() if (d->kiojob && !qobject_cast<KIO::FileJob *>(d->kiojob) && !d->kiojob->isSuspended()) { d->kiojob->suspend(); } else { d->reading = false; } } void KioMediaStream::seekStream(qint64 position) { Q_D(KioMediaStream); if (!d->kiojob) { // no job => job is finished and endOfData was already sent reset(); } Q_ASSERT(d->kiojob); kDebug(600) << position << " = " << qulonglong(position); d->seeking = true; if (d->open) { KIO::FileJob *filejob = qobject_cast<KIO::FileJob *>(d->kiojob); filejob->seek(position); } else { d->seekPosition = position; } } void KioMediaStreamPrivate::_k_bytestreamData(KIO::Job *, const QByteArray &data) { Q_Q(KioMediaStream); Q_ASSERT(kiojob); if (seeking) { // seek doesn't block, so don't send data to the backend until it signals us // that the seek is done kDebug(600) << "seeking: do nothing"; return; } if (data.isEmpty()) { reading = false; if (!endOfDataSent) { kDebug(600) << "empty data: stopping the stream"; endOfDataSent = true; q->endOfData(); } return; } //kDebug(600) << "calling writeData on the Backend ByteStream " << data.size(); q->writeData(data); if (reading) { KIO::FileJob *filejob = qobject_cast<KIO::FileJob *>(kiojob); Q_ASSERT(filejob); filejob->read(32768); } } void KioMediaStreamPrivate::_k_bytestreamResult(KJob *job) { Q_Q(KioMediaStream); Q_ASSERT(kiojob == job); if (job->error()) { QString kioErrorString = job->errorString(); kDebug(600) << "KIO Job error: " << kioErrorString; QObject::disconnect(kiojob, SIGNAL(data(KIO::Job *,const QByteArray &)), q, SLOT(_k_bytestreamData(KIO::Job *,const QByteArray &))); QObject::disconnect(kiojob, SIGNAL(result(KJob *)), q, SLOT(_k_bytestreamResult(KJob *))); KIO::FileJob *filejob = qobject_cast<KIO::FileJob *>(kiojob); if (filejob) { QObject::disconnect(kiojob, SIGNAL(open(KIO::Job *)), q, SLOT(_k_bytestreamFileJobOpen(KIO::Job *))); QObject::disconnect(kiojob, SIGNAL(position(KIO::Job *, KIO::filesize_t)), q, SLOT(_k_bytestreamSeekDone(KIO::Job *, KIO::filesize_t))); } else { QObject::disconnect(kiojob, SIGNAL(totalSize(KJob *, qulonglong)), q, SLOT(_k_bytestreamTotalSize(KJob *,qulonglong))); } // go to ErrorState - NormalError q->error(NormalError, kioErrorString); } kiojob = 0; kDebug(600) << "KIO Job is done (will delete itself) and d->kiojob reset to 0"; endOfDataSent = true; q->endOfData(); reading = false; } void KioMediaStreamPrivate::_k_bytestreamTotalSize(KJob *, qulonglong size) { Q_Q(KioMediaStream); kDebug(600) << size; q->setStreamSize(size); } void KioMediaStreamPrivate::_k_bytestreamFileJobOpen(KIO::Job *) { Q_Q(KioMediaStream); Q_ASSERT(kiojob); open = true; endOfDataSent = false; KIO::FileJob *filejob = static_cast<KIO::FileJob *>(kiojob); kDebug(600) << filejob->size(); q->setStreamSize(filejob->size()); if (seeking) { filejob->seek(seekPosition); } else if (reading) { filejob->read(32768); } } void KioMediaStreamPrivate::_k_bytestreamSeekDone(KIO::Job *, KIO::filesize_t offset) { Q_ASSERT(kiojob); kDebug(600) << offset; seeking = false; endOfDataSent = false; if (reading) { KIO::FileJob *filejob = qobject_cast<KIO::FileJob *>(kiojob); Q_ASSERT(filejob); filejob->read(32768); } } } // namespace Phonon #include "kiomediastream.moc" // vim: sw=4 sts=4 et tw=100 <commit_msg>fix race: FileJob would send an empty data QByteArray, meaning it reached EOF and will emit result later and then delete itself, but before result is received the backend requests a seek - the job is still seems to be valid, but really is just about to delete itself<commit_after>/* This file is part of the KDE project Copyright (C) 2007 Matthias Kretz <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "kiomediastream.h" #include "kiomediastream_p.h" #include <kdebug.h> #include <kprotocolmanager.h> #include <kio/filejob.h> #include <kio/job.h> #include <klocale.h> namespace Phonon { KioMediaStream::KioMediaStream(const QUrl &url, QObject *parent) : AbstractMediaStream(*new KioMediaStreamPrivate(url), parent) { reset(); } void KioMediaStream::reset() { Q_D(KioMediaStream); if (d->kiojob) { d->kiojob->disconnect(this); d->kiojob->kill(); d->endOfDataSent = false; d->seeking = false; d->reading = false; d->open = false; d->seekPosition = 0; } if (KProtocolManager::supportsOpening(d->url)) { d->kiojob = KIO::open(d->url, QIODevice::ReadOnly); Q_ASSERT(d->kiojob); d->open = false; setStreamSeekable(true); connect(d->kiojob, SIGNAL(open(KIO::Job *)), this, SLOT(_k_bytestreamFileJobOpen(KIO::Job *))); connect(d->kiojob, SIGNAL(position(KIO::Job *, KIO::filesize_t)), this, SLOT(_k_bytestreamSeekDone(KIO::Job *, KIO::filesize_t))); } else { d->kiojob = KIO::get(d->url, false, false); Q_ASSERT(d->kiojob); setStreamSeekable(false); connect(d->kiojob, SIGNAL(totalSize(KJob *, qulonglong)), this, SLOT(_k_bytestreamTotalSize(KJob *,qulonglong))); d->kiojob->suspend(); } d->kiojob->addMetaData("UserAgent", QLatin1String("KDE Phonon")); connect(d->kiojob, SIGNAL(data(KIO::Job *,const QByteArray &)), this, SLOT(_k_bytestreamData(KIO::Job *,const QByteArray &))); connect(d->kiojob, SIGNAL(result(KJob *)), this, SLOT(_k_bytestreamResult(KJob *))); } KioMediaStream::~KioMediaStream() { } void KioMediaStream::needData() { Q_D(KioMediaStream); if (!d->kiojob) { // no job => job is finished and endOfData was already sent return; } KIO::FileJob *filejob = qobject_cast<KIO::FileJob *>(d->kiojob); if (filejob) { // while d->seeking the backend won't get any data if (d->seeking || !d->open) { d->reading = true; } else if (!d->reading) { d->reading = true; filejob->read(32768); } } else { // KIO::TransferJob d->kiojob->resume(); } } void KioMediaStream::enoughData() { Q_D(KioMediaStream); kDebug(600) ; // Don't suspend when using a FileJob. The FileJob is controlled by calls to // FileJob::read() if (d->kiojob && !qobject_cast<KIO::FileJob *>(d->kiojob) && !d->kiojob->isSuspended()) { d->kiojob->suspend(); } else { d->reading = false; } } void KioMediaStream::seekStream(qint64 position) { Q_D(KioMediaStream); if (!d->kiojob || d->endOfDataSent) { // no job => job is finished and endOfData was already sent reset(); } Q_ASSERT(d->kiojob); kDebug(600) << position << " = " << qulonglong(position); d->seeking = true; if (d->open) { KIO::FileJob *filejob = qobject_cast<KIO::FileJob *>(d->kiojob); filejob->seek(position); } else { d->seekPosition = position; } } void KioMediaStreamPrivate::_k_bytestreamData(KIO::Job *, const QByteArray &data) { Q_Q(KioMediaStream); Q_ASSERT(kiojob); if (seeking) { // seek doesn't block, so don't send data to the backend until it signals us // that the seek is done kDebug(600) << "seeking: do nothing"; return; } if (data.isEmpty()) { reading = false; if (!endOfDataSent) { kDebug(600) << "empty data: stopping the stream"; endOfDataSent = true; q->endOfData(); } return; } //kDebug(600) << "calling writeData on the Backend ByteStream " << data.size(); q->writeData(data); if (reading) { KIO::FileJob *filejob = qobject_cast<KIO::FileJob *>(kiojob); Q_ASSERT(filejob); filejob->read(32768); } } void KioMediaStreamPrivate::_k_bytestreamResult(KJob *job) { Q_Q(KioMediaStream); Q_ASSERT(kiojob == job); if (job->error()) { QString kioErrorString = job->errorString(); kDebug(600) << "KIO Job error: " << kioErrorString; QObject::disconnect(kiojob, SIGNAL(data(KIO::Job *,const QByteArray &)), q, SLOT(_k_bytestreamData(KIO::Job *,const QByteArray &))); QObject::disconnect(kiojob, SIGNAL(result(KJob *)), q, SLOT(_k_bytestreamResult(KJob *))); KIO::FileJob *filejob = qobject_cast<KIO::FileJob *>(kiojob); if (filejob) { QObject::disconnect(kiojob, SIGNAL(open(KIO::Job *)), q, SLOT(_k_bytestreamFileJobOpen(KIO::Job *))); QObject::disconnect(kiojob, SIGNAL(position(KIO::Job *, KIO::filesize_t)), q, SLOT(_k_bytestreamSeekDone(KIO::Job *, KIO::filesize_t))); } else { QObject::disconnect(kiojob, SIGNAL(totalSize(KJob *, qulonglong)), q, SLOT(_k_bytestreamTotalSize(KJob *,qulonglong))); } // go to ErrorState - NormalError q->error(NormalError, kioErrorString); } kiojob = 0; kDebug(600) << "KIO Job is done (will delete itself) and d->kiojob reset to 0"; endOfDataSent = true; q->endOfData(); reading = false; } void KioMediaStreamPrivate::_k_bytestreamTotalSize(KJob *, qulonglong size) { Q_Q(KioMediaStream); kDebug(600) << size; q->setStreamSize(size); } void KioMediaStreamPrivate::_k_bytestreamFileJobOpen(KIO::Job *) { Q_Q(KioMediaStream); Q_ASSERT(kiojob); open = true; endOfDataSent = false; KIO::FileJob *filejob = static_cast<KIO::FileJob *>(kiojob); kDebug(600) << filejob->size(); q->setStreamSize(filejob->size()); if (seeking) { filejob->seek(seekPosition); } else if (reading) { filejob->read(32768); } } void KioMediaStreamPrivate::_k_bytestreamSeekDone(KIO::Job *, KIO::filesize_t offset) { Q_ASSERT(kiojob); kDebug(600) << offset; seeking = false; endOfDataSent = false; if (reading) { KIO::FileJob *filejob = qobject_cast<KIO::FileJob *>(kiojob); Q_ASSERT(filejob); filejob->read(32768); } } } // namespace Phonon #include "kiomediastream.moc" // vim: sw=4 sts=4 et tw=100 <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/perception/onboard/component/radar_detection_component.h" #include "modules/perception/common/sensor_manager/sensor_manager.h" #include "modules/perception/lib/utils/perf.h" namespace apollo { namespace perception { namespace onboard { bool RadarDetectionComponent::Init() { RadarComponentConfig comp_config; if (!GetProtoConfig(&comp_config)) { return false; } AINFO << "Radar Component Configs: " << comp_config.DebugString(); // To load component configs tf_child_frame_id_ = comp_config.tf_child_frame_id(); radar_forward_distance_ = comp_config.radar_forward_distance(); preprocessor_method_ = comp_config.radar_preprocessor_method(); perception_method_ = comp_config.radar_perception_method(); pipeline_name_ = comp_config.radar_pipeline_name(); odometry_channel_name_ = comp_config.odometry_channel_name(); if (!common::SensorManager::Instance()->GetSensorInfo( comp_config.radar_name(), &radar_info_)) { AERROR << "Failed to get sensor info, sensor name: " << comp_config.radar_name(); return false; } writer_ = node_->CreateWriter<SensorFrameMessage>( comp_config.output_channel_name()); // Init algorithm plugin CHECK(InitAlgorithmPlugin() == true) << "Failed to init algorithm plugin."; radar2world_trans_.Init(tf_child_frame_id_); radar2novatel_trans_.Init(tf_child_frame_id_); localization_subscriber_.Init( odometry_channel_name_, odometry_channel_name_ + '_' + comp_config.radar_name()); return true; } bool RadarDetectionComponent::Proc(const std::shared_ptr<ContiRadar>& message) { AINFO << "Enter radar preprocess, message timestamp: " << std::to_string(message->header().timestamp_sec()) << " current timestamp " << lib::TimeUtil::GetCurrentTime(); std::shared_ptr<SensorFrameMessage> out_message(new (std::nothrow) SensorFrameMessage); int status = InternalProc(message, out_message); if (status) { writer_->Write(out_message); AINFO << "Send radar processing output message."; } return status; } bool RadarDetectionComponent::InitAlgorithmPlugin() { AINFO << "onboard radar_preprocessor: " << preprocessor_method_; if (FLAGS_obs_enable_hdmap_input) { hdmap_input_ = map::HDMapInput::Instance(); CHECK(hdmap_input_->Init()) << "Failed to init hdmap input."; } radar::BasePreprocessor* preprocessor = radar::BasePreprocessorRegisterer::GetInstanceByName( preprocessor_method_); CHECK_NOTNULL(preprocessor); radar_preprocessor_.reset(preprocessor); CHECK(radar_preprocessor_->Init()) << "Failed to init radar preprocessor."; radar::BaseRadarObstaclePerception* radar_perception = radar::BaseRadarObstaclePerceptionRegisterer::GetInstanceByName( perception_method_); CHECK(radar_perception != nullptr) << "No radar obstacle perception named: " << perception_method_; radar_perception_.reset(radar_perception); CHECK(radar_perception_->Init(pipeline_name_)) << "Failed to init radar perception."; AINFO << "Init algorithm plugin successfully."; return true; } bool RadarDetectionComponent::InternalProc( const std::shared_ptr<ContiRadar>& in_message, std::shared_ptr<SensorFrameMessage> out_message) { PERCEPTION_PERF_FUNCTION_WITH_INDICATOR(radar_info_.name); ContiRadar raw_obstacles = *in_message; { std::unique_lock<std::mutex> lock(_mutex); ++seq_num_; } double timestamp = in_message->header().timestamp_sec(); const double cur_time = lib::TimeUtil::GetCurrentTime(); const double start_latency = (cur_time - timestamp) * 1e3; AINFO << "FRAME_STATISTICS:Radar:Start:msg_time[" << std::to_string(timestamp) << "]:cur_time[" << std::to_string(cur_time) << "]:cur_latency[" << start_latency << "]"; PERCEPTION_PERF_BLOCK_START(); // Init preprocessor_options radar::PreprocessorOptions preprocessor_options; ContiRadar corrected_obstacles; radar_preprocessor_->Preprocess(raw_obstacles, preprocessor_options, &corrected_obstacles); PERCEPTION_PERF_BLOCK_END_WITH_INDICATOR(radar_info_.name, "radar_preprocessor"); timestamp = corrected_obstacles.header().timestamp_sec(); out_message->timestamp_ = timestamp; out_message->seq_num_ = seq_num_; out_message->process_stage_ = ProcessStage::LONG_RANGE_RADAR_DETECTION; out_message->sensor_id_ = radar_info_.name; // Init radar perception options radar::RadarPerceptionOptions options; options.sensor_name = radar_info_.name; // Init detector_options Eigen::Affine3d radar_trans; if (!radar2world_trans_.GetSensor2worldTrans(timestamp, &radar_trans)) { out_message->error_code_ = apollo::common::ErrorCode::PERCEPTION_ERROR_TF; AERROR << "Failed to get pose at time: " << timestamp; return true; } Eigen::Affine3d radar2novatel_trans; if (!radar2novatel_trans_.GetTrans(timestamp, &radar2novatel_trans, "novatel", tf_child_frame_id_)) { out_message->error_code_ = apollo::common::ErrorCode::PERCEPTION_ERROR_TF; AERROR << "Failed to get radar2novatel trans at time: " << timestamp; return true; } PERCEPTION_PERF_BLOCK_END_WITH_INDICATOR(radar_info_.name, "GetSensor2worldTrans"); Eigen::Matrix4d radar2world_pose = radar_trans.matrix(); options.detector_options.radar2world_pose = &radar2world_pose; Eigen::Matrix4d radar2novatel_trans_m = radar2novatel_trans.matrix(); options.detector_options.radar2novatel_trans = &radar2novatel_trans_m; if (!GetCarLocalizationSpeed( timestamp, &(options.detector_options.car_linear_speed), &(options.detector_options.car_angular_speed))) { AERROR << "Failed to call get_car_speed. [timestamp: " << std::to_string(timestamp); // return false; } PERCEPTION_PERF_BLOCK_END_WITH_INDICATOR(radar_info_.name, "GetCarSpeed"); // Init roi_filter_options base::PointD position; position.x = radar_trans(0, 3); position.y = radar_trans(1, 3); position.z = radar_trans(2, 3); options.roi_filter_options.roi.reset(new base::HdmapStruct()); if (FLAGS_obs_enable_hdmap_input) { hdmap_input_->GetRoiHDMapStruct(position, radar_forward_distance_, options.roi_filter_options.roi); } PERCEPTION_PERF_BLOCK_END_WITH_INDICATOR(radar_info_.name, "GetRoiHDMapStruct"); // Init object_filter_options // Init track_options // Init object_builder_options std::vector<base::ObjectPtr> radar_objects; if (!radar_perception_->Perceive(corrected_obstacles, options, &radar_objects)) { out_message->error_code_ = apollo::common::ErrorCode::PERCEPTION_ERROR_PROCESS; AERROR << "RadarDetector Proc failed."; return true; } out_message->frame_.reset(new base::Frame()); out_message->frame_->sensor_info = radar_info_; out_message->frame_->timestamp = timestamp; out_message->frame_->sensor2world_pose = radar_trans; out_message->frame_->objects = radar_objects; const double end_timestamp = lib::TimeUtil::GetCurrentTime(); const double end_latency = (end_timestamp - in_message->header().timestamp_sec()) * 1e3; PERCEPTION_PERF_BLOCK_END_WITH_INDICATOR(radar_info_.name, "radar_perception"); AINFO << "FRAME_STATISTICS:Radar:End:msg_time[" << std::to_string(in_message->header().timestamp_sec()) << "]:cur_time[" << std::to_string(end_timestamp) << "]:cur_latency[" << end_latency << "]"; return true; } bool RadarDetectionComponent::GetCarLocalizationSpeed( double timestamp, Eigen::Vector3f* car_linear_speed, Eigen::Vector3f* car_angular_speed) { CHECK_NOTNULL(car_linear_speed); (*car_linear_speed) = Eigen::Vector3f::Zero(); CHECK_NOTNULL(car_angular_speed); (*car_angular_speed) = Eigen::Vector3f::Zero(); std::shared_ptr<LocalizationEstimate const> loct_ptr; if (!localization_subscriber_.LookupNearest(timestamp, &loct_ptr)) { AERROR << "Cannot get car speed."; return false; } (*car_linear_speed)[0] = static_cast<float>(loct_ptr->pose().linear_velocity().x()); (*car_linear_speed)[1] = static_cast<float>(loct_ptr->pose().linear_velocity().y()); (*car_linear_speed)[2] = static_cast<float>(loct_ptr->pose().linear_velocity().z()); (*car_angular_speed)[0] = static_cast<float>(loct_ptr->pose().angular_velocity().x()); (*car_angular_speed)[1] = static_cast<float>(loct_ptr->pose().angular_velocity().y()); (*car_angular_speed)[2] = static_cast<float>(loct_ptr->pose().angular_velocity().z()); return true; } } // namespace onboard } // namespace perception } // namespace apollo <commit_msg>Update radar_detection_component.cc<commit_after>/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/perception/onboard/component/radar_detection_component.h" #include "modules/perception/common/sensor_manager/sensor_manager.h" #include "modules/perception/lib/utils/perf.h" namespace apollo { namespace perception { namespace onboard { bool RadarDetectionComponent::Init() { RadarComponentConfig comp_config; if (!GetProtoConfig(&comp_config)) { return false; } AINFO << "Radar Component Configs: " << comp_config.DebugString(); // To load component configs tf_child_frame_id_ = comp_config.tf_child_frame_id(); radar_forward_distance_ = comp_config.radar_forward_distance(); preprocessor_method_ = comp_config.radar_preprocessor_method(); perception_method_ = comp_config.radar_perception_method(); pipeline_name_ = comp_config.radar_pipeline_name(); odometry_channel_name_ = comp_config.odometry_channel_name(); if (!common::SensorManager::Instance()->GetSensorInfo( comp_config.radar_name(), &radar_info_)) { AERROR << "Failed to get sensor info, sensor name: " << comp_config.radar_name(); return false; } writer_ = node_->CreateWriter<SensorFrameMessage>( comp_config.output_channel_name()); // Init algorithm plugin CHECK(InitAlgorithmPlugin() == true) << "Failed to init algorithm plugin."; radar2world_trans_.Init(tf_child_frame_id_); radar2novatel_trans_.Init(tf_child_frame_id_); localization_subscriber_.Init( odometry_channel_name_, odometry_channel_name_ + '_' + comp_config.radar_name()); return true; } bool RadarDetectionComponent::Proc(const std::shared_ptr<ContiRadar>& message) { AINFO << "Enter radar preprocess, message timestamp: " << std::to_string(message->header().timestamp_sec()) << " current timestamp " << lib::TimeUtil::GetCurrentTime(); std::shared_ptr<SensorFrameMessage> out_message(new (std::nothrow) SensorFrameMessage); int status = InternalProc(message, out_message); if (status) { writer_->Write(out_message); AINFO << "Send radar processing output message."; } return status; } bool RadarDetectionComponent::InitAlgorithmPlugin() { AINFO << "onboard radar_preprocessor: " << preprocessor_method_; if (FLAGS_obs_enable_hdmap_input) { hdmap_input_ = map::HDMapInput::Instance(); CHECK(hdmap_input_->Init()) << "Failed to init hdmap input."; } radar::BasePreprocessor* preprocessor = radar::BasePreprocessorRegisterer::GetInstanceByName( preprocessor_method_); CHECK_NOTNULL(preprocessor); radar_preprocessor_.reset(preprocessor); CHECK(radar_preprocessor_->Init()) << "Failed to init radar preprocessor."; radar::BaseRadarObstaclePerception* radar_perception = radar::BaseRadarObstaclePerceptionRegisterer::GetInstanceByName( perception_method_); CHECK(radar_perception != nullptr) << "No radar obstacle perception named: " << perception_method_; radar_perception_.reset(radar_perception); CHECK(radar_perception_->Init(pipeline_name_)) << "Failed to init radar perception."; AINFO << "Init algorithm plugin successfully."; return true; } bool RadarDetectionComponent::InternalProc( const std::shared_ptr<ContiRadar>& in_message, std::shared_ptr<SensorFrameMessage> out_message) { PERCEPTION_PERF_FUNCTION_WITH_INDICATOR(radar_info_.name); ContiRadar raw_obstacles = *in_message; { std::unique_lock<std::mutex> lock(_mutex); ++seq_num_; } double timestamp = in_message->header().timestamp_sec(); const double cur_time = lib::TimeUtil::GetCurrentTime(); const double start_latency = (cur_time - timestamp) * 1e3; AINFO << "FRAME_STATISTICS:Radar:Start:msg_time[" << std::to_string(timestamp) << "]:cur_time[" << std::to_string(cur_time) << "]:cur_latency[" << start_latency << "]"; PERCEPTION_PERF_BLOCK_START(); // Init preprocessor_options radar::PreprocessorOptions preprocessor_options; ContiRadar corrected_obstacles; radar_preprocessor_->Preprocess(raw_obstacles, preprocessor_options, &corrected_obstacles); PERCEPTION_PERF_BLOCK_END_WITH_INDICATOR(radar_info_.name, "radar_preprocessor"); timestamp = corrected_obstacles.header().timestamp_sec(); out_message->timestamp_ = timestamp; out_message->seq_num_ = seq_num_; out_message->process_stage_ = ProcessStage::LONG_RANGE_RADAR_DETECTION; out_message->sensor_id_ = radar_info_.name; // Init radar perception options radar::RadarPerceptionOptions options; options.sensor_name = radar_info_.name; // Init detector_options Eigen::Affine3d radar_trans; if (!radar2world_trans_.GetSensor2worldTrans(timestamp, &radar_trans)) { out_message->error_code_ = apollo::common::ErrorCode::PERCEPTION_ERROR_TF; AERROR << "Failed to get pose at time: " << timestamp; return true; } Eigen::Affine3d radar2novatel_trans; if (!radar2novatel_trans_.GetTrans(timestamp, &radar2novatel_trans, "novatel", tf_child_frame_id_)) { out_message->error_code_ = apollo::common::ErrorCode::PERCEPTION_ERROR_TF; AERROR << "Failed to get radar2novatel trans at time: " << timestamp; return true; } PERCEPTION_PERF_BLOCK_END_WITH_INDICATOR(radar_info_.name, "GetSensor2worldTrans"); Eigen::Matrix4d radar2world_pose = radar_trans.matrix(); options.detector_options.radar2world_pose = &radar2world_pose; Eigen::Matrix4d radar2novatel_trans_m = radar2novatel_trans.matrix(); options.detector_options.radar2novatel_trans = &radar2novatel_trans_m; if (!GetCarLocalizationSpeed( timestamp, &(options.detector_options.car_linear_speed), &(options.detector_options.car_angular_speed))) { AERROR << "Failed to call get_car_speed. [timestamp: " << std::to_string(timestamp); // return false; } PERCEPTION_PERF_BLOCK_END_WITH_INDICATOR(radar_info_.name, "GetCarSpeed"); // Init roi_filter_options base::PointD position; position.x = radar_trans(0, 3); position.y = radar_trans(1, 3); position.z = radar_trans(2, 3); options.roi_filter_options.roi.reset(new base::HdmapStruct()); if (FLAGS_obs_enable_hdmap_input) { hdmap_input_->GetRoiHDMapStruct(position, radar_forward_distance_, options.roi_filter_options.roi); } PERCEPTION_PERF_BLOCK_END_WITH_INDICATOR(radar_info_.name, "GetRoiHDMapStruct"); // Init object_filter_options // Init track_options // Init object_builder_options std::vector<base::ObjectPtr> radar_objects; if (!radar_perception_->Perceive(corrected_obstacles, options, &radar_objects)) { out_message->error_code_ = apollo::common::ErrorCode::PERCEPTION_ERROR_PROCESS; AERROR << "RadarDetector Proc failed."; return true; } out_message->frame_.reset(new base::Frame()); out_message->frame_->sensor_info = radar_info_; out_message->frame_->timestamp = timestamp; out_message->frame_->sensor2world_pose = radar_trans; out_message->frame_->objects = radar_objects; const double end_timestamp = lib::TimeUtil::GetCurrentTime(); const double end_latency = (end_timestamp - in_message->header().timestamp_sec()) * 1e3; PERCEPTION_PERF_BLOCK_END_WITH_INDICATOR(radar_info_.name, "radar_perception"); AINFO << "FRAME_STATISTICS:Radar:End:msg_time[" << std::to_string(in_message->header().timestamp_sec()) << "]:cur_time[" << std::to_string(end_timestamp) << "]:cur_latency[" << end_latency << "]"; return true; } bool RadarDetectionComponent::GetCarLocalizationSpeed( double timestamp, Eigen::Vector3f* car_linear_speed, Eigen::Vector3f* car_angular_speed) { CHECK_NOTNULL(car_linear_speed); (*car_linear_speed) = Eigen::Vector3f::Zero(); CHECK_NOTNULL(car_angular_speed); (*car_angular_speed) = Eigen::Vector3f::Zero(); std::shared_ptr<LocalizationEstimate const> loct_ptr; if (!localization_subscriber_.LookupNearest(timestamp, &loct_ptr)) { AERROR << "Cannot get car speed."; return false; } (*car_linear_speed)[0] = static_cast<float>(loct_ptr->pose().linear_velocity().x()); (*car_linear_speed)[1] = static_cast<float>(loct_ptr->pose().linear_velocity().y()); (*car_linear_speed)[2] = static_cast<float>(loct_ptr->pose().linear_velocity().z()); (*car_angular_speed)[0] = static_cast<float>(loct_ptr->pose().angular_velocity().x()); (*car_angular_speed)[1] = static_cast<float>(loct_ptr->pose().angular_velocity().y()); (*car_angular_speed)[2] = static_cast<float>(loct_ptr->pose().angular_velocity().z()); return true; } } // namespace onboard } // namespace perception } // namespace apollo <|endoftext|>
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "attributefactory.h" #include "integerbase.h" #include "floatbase.h" #include "defines.h" #include "singlestringattribute.h" #include "singleboolattribute.h" #include "singlestringpostattribute.hpp" #include "singlenumericpostattribute.hpp" #define INTPOSTING(T) SingleValueNumericPostingAttribute< ENUM_ATTRIBUTE(IntegerAttributeTemplate<T>) > #define FLOATPOSTING(T) SingleValueNumericPostingAttribute< ENUM_ATTRIBUTE(FloatingPointAttributeTemplate<T>) > namespace search { using attribute::BasicType; AttributeVector::SP AttributeFactory::createSingleFastSearch(stringref name, const Config & info) { assert(info.collectionType().type() == attribute::CollectionType::SINGLE); assert(info.fastSearch()); switch(info.basicType().type()) { case BasicType::BOOL: return std::make_shared<SingleBoolAttribute>(name, info.getGrowStrategy()); case BasicType::UINT2: case BasicType::UINT4: break; case BasicType::INT8: return std::make_shared<INTPOSTING(int8_t)>(name, info); case BasicType::INT16: return std::make_shared<INTPOSTING(int16_t)>(name, info); case BasicType::INT32: return std::make_shared<INTPOSTING(int32_t)>(name, info); case BasicType::INT64: return std::make_shared<INTPOSTING(int64_t)>(name, info); case BasicType::FLOAT: return std::make_shared<FLOATPOSTING(float)>(name, info); case BasicType::DOUBLE: return std::make_shared<FLOATPOSTING(double)>(name, info); case BasicType::STRING: return std::make_shared<SingleValueStringPostingAttribute>(name, info); default: break; } return AttributeVector::SP(); } } <commit_msg>create DirectTensorAttribute for sparse tensors with fast-search<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "attributefactory.h" #include "integerbase.h" #include "floatbase.h" #include "defines.h" #include "singlestringattribute.h" #include "singleboolattribute.h" #include "singlestringpostattribute.hpp" #include "singlenumericpostattribute.hpp" #include <vespa/searchlib/tensor/direct_tensor_attribute.h> #define INTPOSTING(T) SingleValueNumericPostingAttribute< ENUM_ATTRIBUTE(IntegerAttributeTemplate<T>) > #define FLOATPOSTING(T) SingleValueNumericPostingAttribute< ENUM_ATTRIBUTE(FloatingPointAttributeTemplate<T>) > namespace search { using attribute::BasicType; AttributeVector::SP AttributeFactory::createSingleFastSearch(stringref name, const Config & info) { assert(info.collectionType().type() == attribute::CollectionType::SINGLE); assert(info.fastSearch()); switch(info.basicType().type()) { case BasicType::BOOL: return std::make_shared<SingleBoolAttribute>(name, info.getGrowStrategy()); case BasicType::UINT2: case BasicType::UINT4: break; case BasicType::INT8: return std::make_shared<INTPOSTING(int8_t)>(name, info); case BasicType::INT16: return std::make_shared<INTPOSTING(int16_t)>(name, info); case BasicType::INT32: return std::make_shared<INTPOSTING(int32_t)>(name, info); case BasicType::INT64: return std::make_shared<INTPOSTING(int64_t)>(name, info); case BasicType::FLOAT: return std::make_shared<FLOATPOSTING(float)>(name, info); case BasicType::DOUBLE: return std::make_shared<FLOATPOSTING(double)>(name, info); case BasicType::STRING: return std::make_shared<SingleValueStringPostingAttribute>(name, info); case BasicType::TENSOR: if (info.tensorType().is_sparse()) { return std::make_shared<tensor::DirectTensorAttribute>(name, info); } break; default: break; } return AttributeVector::SP(); } } <|endoftext|>
<commit_before>#define GLOG_NO_ABBREVIATED_SEVERITIES #undef TRACE_SYMPLECTIC_PARTITIONED_RUNGE_KUTTA_INTEGRATOR #include <algorithm> #include "benchmark/benchmark.h" #include "integrators/symplectic_partitioned_runge_kutta_integrator.hpp" using principia::integrators::SPRKIntegrator; namespace principia { namespace benchmarks { namespace { inline void compute_harmonic_oscillator_force(double const t, std::vector<double> const& q, std::vector<double>* result) { (*result)[0] = -q[0]; } inline void compute_harmonice_oscillator_velocity(std::vector<double> const& p, std::vector<double>* result) { (*result)[0] = p[0]; } } // namespace void SolveHarmonicOscillator(benchmark::State* state, double* q_error, double* p_error) { SPRKIntegrator integrator; SPRKIntegrator::Parameters parameters; SPRKIntegrator::Solution solution; parameters.q0 = {1.0}; parameters.p0 = {0.0}; parameters.t0 = 0.0; #ifdef _DEBUG parameters.tmax = 100.0; #else parameters.tmax = 1000.0; #endif parameters.Δt = 1.0E-4; parameters.coefficients = integrator.Order5Optimal(); parameters.sampling_period = 1; integrator.Solve(&compute_harmonic_oscillator_force, &compute_harmonice_oscillator_velocity, parameters, &solution); state->PauseTiming(); *q_error = 0; *p_error = 0; for (size_t i = 0; i < solution.time.quantities.size(); ++i) { *q_error = std::max(*q_error, std::abs(solution.position[0].quantities[i] - std::cos(solution.time.quantities[i]))); *p_error = std::max(*p_error, std::abs(solution.momentum[0].quantities[i] + std::sin(solution.time.quantities[i]))); } state->ResumeTiming(); } static void BM_SolveHarmonicOscillator(benchmark::State& state) { double q_error; double p_error; while (state.KeepRunning()) { SolveHarmonicOscillator(&state, &q_error, &p_error); } std::stringstream ss; ss << q_error << ", " << p_error; state.SetLabel(ss.str()); } BENCHMARK(BM_SolveHarmonicOscillator); } // namespace benchmarks } // namespace principia int main(int argc, const char* argv[]) { benchmark::Initialize(&argc, argv); benchmark::RunSpecifiedBenchmarks(); } <commit_msg>Lint and warnings.<commit_after>#define GLOG_NO_ABBREVIATED_SEVERITIES #undef TRACE_SYMPLECTIC_PARTITIONED_RUNGE_KUTTA_INTEGRATOR #include <algorithm> #include <vector> #include "integrators/symplectic_partitioned_runge_kutta_integrator.hpp" // Must come last to avoid conflicts when defining the CHECK macros. #include "benchmark/benchmark.h" using principia::integrators::SPRKIntegrator; namespace principia { namespace benchmarks { namespace { inline void compute_harmonic_oscillator_force(double const t, std::vector<double> const& q, std::vector<double>* result) { (*result)[0] = -q[0]; } inline void compute_harmonic_oscillator_velocity(std::vector<double> const& p, std::vector<double>* result) { (*result)[0] = p[0]; } } // namespace void SolveHarmonicOscillator(benchmark::State* state, double* q_error, double* p_error) { SPRKIntegrator integrator; SPRKIntegrator::Parameters parameters; SPRKIntegrator::Solution solution; parameters.q0 = {1.0}; parameters.p0 = {0.0}; parameters.t0 = 0.0; #ifdef _DEBUG parameters.tmax = 100.0; #else parameters.tmax = 1000.0; #endif parameters.Δt = 1.0E-4; parameters.coefficients = integrator.Order5Optimal(); parameters.sampling_period = 1; integrator.Solve(&compute_harmonic_oscillator_force, &compute_harmonic_oscillator_velocity, parameters, &solution); state->PauseTiming(); *q_error = 0; *p_error = 0; for (size_t i = 0; i < solution.time.quantities.size(); ++i) { *q_error = std::max(*q_error, std::abs(solution.position[0].quantities[i] - std::cos(solution.time.quantities[i]))); *p_error = std::max(*p_error, std::abs(solution.momentum[0].quantities[i] + std::sin(solution.time.quantities[i]))); } state->ResumeTiming(); } static void BM_SolveHarmonicOscillator( benchmark::State& state) { // NOLINT(runtime/references) double q_error; double p_error; while (state.KeepRunning()) { SolveHarmonicOscillator(&state, &q_error, &p_error); } std::stringstream ss; ss << q_error << ", " << p_error; state.SetLabel(ss.str()); } BENCHMARK(BM_SolveHarmonicOscillator); } // namespace benchmarks } // namespace principia int main(int argc, const char* argv[]) { benchmark::Initialize(&argc, argv); benchmark::RunSpecifiedBenchmarks(); } <|endoftext|>
<commit_before>#include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> // get<n>(xxx) #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> // S.insert(M); // if (S.find(key) != S.end()) { } // for (auto it=S.begin(); it != S.end(); it++) { } // auto it = S.lower_bound(M); #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // atoi(xxx) using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. // insert #if<tab> by my emacs. #if DEBUG == 1 ... #end typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; const ll infty = 10000000000000007; struct edge { int to; ll cap; int rev; }; vector<edge> G[100010]; bool used[100010]; void add_edge(int from, int to, ll cap) { G[from].push_back((edge){to, cap, (int)G[to].size()}); G[to].push_back((edge){from, 0, (int)G[from].size()-1}); } ll dfs(int v, int t, ll f) { if (v == t) return f; used[v] = true; for (auto& e : G[v]) { if (!used[e.to] && e.cap > 0) { ll d = dfs(e.to, t, min(f, e.cap)); if (d > 0) { e.cap -= d; G[e.to][e.rev].cap += d; return d; } } } return 0; } ll max_flow(int s, int t) { ll flow = 0; while (true) { fill(used, used+100010, false); ll f = dfs(s, t, infty); if (f == 0) return flow; flow += f; } } typedef tuple<ll, int> state; // kachi, bit int N; ll x[20]; ll c[20]; ll v[20]; vector<state> V[20]; int main () { cin >> N; for (auto i = 0; i < N; ++i) { cin >> x[i]; } for (auto i = 0; i < N-1; ++i) { x[i+1] += x[i]; } for (auto i = 0; i < N; ++i) { cin >> c[i]; } for (auto i = 0; i < N; ++i) { cin >> v[i]; } for (auto i = 0; i < (1 << N); ++i) { ll kakaku = 0; ll kachi = 0; for (auto j = 0; j < N; ++j) { if ((i >> j) & 1) { kakaku += c[j]; kachi += v[j]; } } for (auto j = 0; j < N; ++j) { if (kakaku <= x[j]) { V[j].push_back(make_tuple(kachi, i)); break; } } } ll ans = 0; for (auto i = 0; i < N; ++i) { sort(V[i].begin(), V[i].end()); reverse(V[i].begin(), V[i].end()); int comb = (1 << (i+1)) - 1; while (comb < (1 << N)) { // ここで作業する for (auto x : V[i]) { int bit = get<1>(x); if ((comb & bit) > 0) { // ban } else { ans = max(ans, get<0>(x)); break; } } // 以下処理。 int tmpx = comb & (-comb); int tmpy = comb + tmpx; int tmpz = comb & (~(tmpy)); comb = (((tmpz/tmpx) >> 1) | tmpy); } } cout << ans << endl; } <commit_msg>tried C.cpp to 'C'<commit_after>#include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> // get<n>(xxx) #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> // S.insert(M); // if (S.find(key) != S.end()) { } // for (auto it=S.begin(); it != S.end(); it++) { } // auto it = S.lower_bound(M); #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // atoi(xxx) using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. // insert #if<tab> by my emacs. #if DEBUG == 1 ... #end typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; const ll infty = 10000000000000007; struct edge { int to; ll cap; int rev; }; vector<edge> G[100010]; bool used[100010]; void add_edge(int from, int to, ll cap) { G[from].push_back((edge){to, cap, (int)G[to].size()}); G[to].push_back((edge){from, 0, (int)G[from].size()-1}); } ll dfs(int v, int t, ll f) { if (v == t) return f; used[v] = true; for (auto& e : G[v]) { if (!used[e.to] && e.cap > 0) { ll d = dfs(e.to, t, min(f, e.cap)); if (d > 0) { e.cap -= d; G[e.to][e.rev].cap += d; return d; } } } return 0; } ll max_flow(int s, int t) { ll flow = 0; while (true) { fill(used, used+100010, false); ll f = dfs(s, t, infty); if (f == 0) return flow; flow += f; } } typedef tuple<ll, int> state; // kachi, bit int N; ll x[20]; ll c[20]; ll v[20]; vector<state> V[20]; int main () { cin >> N; for (auto i = 0; i < N; ++i) { cin >> x[i]; } for (auto i = 0; i < N-1; ++i) { x[i+1] += x[i]; } for (auto i = 0; i < N; ++i) { cin >> c[i]; } for (auto i = 0; i < N; ++i) { cin >> v[i]; } for (auto i = 0; i < (1 << N); ++i) { ll kakaku = 0; ll kachi = 0; for (auto j = 0; j < N; ++j) { if ((i >> j) & 1) { kakaku += c[j]; kachi += v[j]; } } for (auto j = 0; j < N; ++j) { if (kakaku <= x[j]) { V[j].push_back(make_tuple(kachi, i)); break; } } } ll ans = 0; for (auto i = 0; i < N; ++i) { sort(V[i].begin(), V[i].end()); reverse(V[i].begin(), V[i].end()); int comb = (1 << (i+1)) - 1; while (comb < (1 << N)) { // ここで作業する cerr << "comb = " << comb << endl; for (auto x : V[i]) { int bit = get<1>(x); if ((comb & bit) > 0) { // ban cerr << "bit = " << bit << " is banned." << endl; } else { cerr << "bit = " << bit << " is allowed. Get " << get<0>(x) << "." << endl; ans = max(ans, get<0>(x)); break; } } // 以下処理。 int tmpx = comb & (-comb); int tmpy = comb + tmpx; int tmpz = comb & (~(tmpy)); comb = (((tmpz/tmpx) >> 1) | tmpy); } } cout << ans << endl; } <|endoftext|>
<commit_before>//============================================================================ // Name : jaco_arm.cpp // Author : WPI, Clearpath Robotics // Version : 0.5 // Copyright : BSD // Description : A ROS driver for controlling the Kinova Jaco robotic manipulator arm //============================================================================ #include "jaco_driver/jaco_arm.h" namespace jaco { JacoArm::JacoArm(JacoComm &arm_comm, ros::NodeHandle &nh) : arm(arm_comm) { std::string joint_velocity_topic, joint_angles_topic, cartesian_velocity_topic, tool_position_topic, set_finger_position_topic, finger_position_topic, joint_state_topic, set_joint_angle_topic; nh.param<std::string>("joint_velocity_topic", joint_velocity_topic, "joint_velocity"); nh.param<std::string>("joint_angles_topic", joint_angles_topic, "joint_angles"); nh.param<std::string>("cartesian_velocity_topic", cartesian_velocity_topic, "cartesian_velocity"); nh.param<std::string>("tool_position_topic", tool_position_topic, "tool_position"); nh.param<std::string>("set_finger_position_topic", set_finger_position_topic, "set_finger_position"); nh.param<std::string>("finger_position_topic", finger_position_topic, "finger_position"); nh.param<std::string>("joint_state_topic", joint_state_topic, "joint_state"); nh.param<std::string>("set_joint_angle_topic", set_joint_angle_topic, "set_joint_angle"); //Print out received topics ROS_DEBUG("Got Joint Velocity Topic Name: <%s>", joint_velocity_topic.c_str()); ROS_DEBUG("Got Joint Angles Topic Name: <%s>", joint_angles_topic.c_str()); ROS_DEBUG("Got Cartesian Velocity Topic Name: <%s>", cartesian_velocity_topic.c_str()); ROS_DEBUG("Got Tool Position Topic Name: <%s>", tool_position_topic.c_str()); ROS_DEBUG("Got Set Finger Position Topic Name: <%s>", set_finger_position_topic.c_str()); ROS_DEBUG("Got Finger Position Topic Name: <%s>", finger_position_topic.c_str()); ROS_DEBUG("Got Joint State Topic Name: <%s>", joint_state_topic.c_str()); ROS_DEBUG("Got Set Joint Angle Topic Name: <%s>", set_joint_angle_topic.c_str()); ROS_INFO("Starting Up Jaco Arm Controller..."); previous_state = 0; /* Set up Services */ stop_service = nh.advertiseService("stop", &JacoArm::StopSRV, this); start_service = nh.advertiseService("start", &JacoArm::StartSRV, this); homing_service = nh.advertiseService("home_arm", &JacoArm::HomeArmSRV, this); /* Set Default Configuration */ // API->RestoreFactoryDefault(); // uncomment comment ONLY if you want to lose your settings on each launch. ClientConfigurations configuration; arm.GetConfig(configuration); arm.PrintConfig(configuration); last_update_time = ros::Time::now(); update_time = ros::Duration(5.0); /* Storing arm in home position */ /* Set up Publishers */ JointAngles_pub = nh.advertise<jaco_driver::JointAngles>(joint_angles_topic, 2); JointState_pub = nh.advertise<sensor_msgs::JointState>(joint_state_topic, 2); ToolPosition_pub = nh.advertise<geometry_msgs::PoseStamped>(tool_position_topic, 2); FingerPosition_pub = nh.advertise<jaco_driver::FingerPosition>(finger_position_topic, 2); /* Set up Subscribers*/ JointVelocity_sub = nh.subscribe(joint_velocity_topic, 1, &JacoArm::VelocityMSG, this); CartesianVelocity_sub = nh.subscribe(cartesian_velocity_topic, 1, &JacoArm::CartesianVelocityMSG, this); SetFingerPosition_sub = nh.subscribe(set_finger_position_topic, 1, &JacoArm::SetFingerPositionMSG, this); SetJoint_sub = nh.subscribe(set_joint_angle_topic, 1, &JacoArm::SetJointAnglesMSG, this); status_timer = nh.createTimer(ros::Duration(0.05), &JacoArm::StatusTimer, this); joint_vel_timer = nh.createTimer(ros::Duration(0.01), &JacoArm::JointVelTimer, this); joint_vel_timer.stop(); joint_vel_timer_flag = false; cartesian_vel_timer = nh.createTimer(ros::Duration(0.01), &JacoArm::CartesianVelTimer, this); cartesian_vel_timer.stop(); cartesian_vel_timer_flag = false; ROS_INFO("The Arm is ready to use."); TrajectoryPoint Jaco_Velocity; memset(&Jaco_Velocity, 0, sizeof(Jaco_Velocity)); //zero structure arm.SetCartesianVelocities(Jaco_Velocity.Position.CartesianPosition); } JacoArm::~JacoArm() { } bool JacoArm::HomeArmSRV(jaco_driver::HomeArm::Request &req, jaco_driver::HomeArm::Response &res) { arm.HomeArm(); res.homearm_result = "JACO ARM HAS BEEN RETURNED HOME"; return true; } /*! * \brief Receives ROS command messages and relays them to SetFingers. */ void JacoArm::SetFingerPositionMSG(const jaco_driver::FingerPositionConstPtr& finger_pos) { if (!arm.Stopped()) { FingersPosition Finger_Position; memset(&Finger_Position, 0, sizeof(Finger_Position)); //zero structure Finger_Position.Finger1 = finger_pos->Finger_1; Finger_Position.Finger2 = finger_pos->Finger_2; Finger_Position.Finger3 = finger_pos->Finger_3; arm.SetFingers(Finger_Position); } } /*! * \brief Receives ROS command messages and relays them to SetAngles. */ void JacoArm::SetJointAnglesMSG(const jaco_driver::JointAnglesConstPtr& angles) { if (!arm.Stopped()) { AngularInfo Joint_Position; memset(&Joint_Position, 0, sizeof(Joint_Position)); //zero structure Joint_Position.Actuator1 = angles->Angle_J1; Joint_Position.Actuator2 = angles->Angle_J2; Joint_Position.Actuator3 = angles->Angle_J3; Joint_Position.Actuator4 = angles->Angle_J4; Joint_Position.Actuator5 = angles->Angle_J5; Joint_Position.Actuator6 = angles->Angle_J6; arm.SetAngles(Joint_Position); } } void JacoArm::VelocityMSG(const jaco_driver::JointVelocityConstPtr& joint_vel) { if (!arm.Stopped()) { joint_velocities.Actuator1 = joint_vel->Velocity_J1; joint_velocities.Actuator2 = joint_vel->Velocity_J2; joint_velocities.Actuator3 = joint_vel->Velocity_J3; joint_velocities.Actuator4 = joint_vel->Velocity_J4; joint_velocities.Actuator5 = joint_vel->Velocity_J5; joint_velocities.Actuator6 = joint_vel->Velocity_J6; last_joint_update = ros::Time().now(); if (joint_vel_timer_flag == false) { joint_vel_timer.start(); joint_vel_timer_flag = true; } } } /*! * \brief Handler for "stop" service. * * Instantly stops the arm and prevents further movement until start service is * invoked. */ bool JacoArm::StopSRV(jaco_driver::Stop::Request &req, jaco_driver::Stop::Response &res) { arm.Stop(); res.stop_result = "JACO ARM HAS BEEN STOPPED"; ROS_DEBUG("JACO ARM STOP REQUEST"); return true; } /*! * \brief Handler for "start" service. * * Re-enables control of the arm after a stop. */ bool JacoArm::StartSRV(jaco_driver::Start::Request &req, jaco_driver::Start::Response &res) { arm.Start(); res.start_result = "JACO ARM CONTROL HAS BEEN ENABLED"; ROS_DEBUG("JACO ARM START REQUEST"); return true; } void JacoArm::CartesianVelocityMSG(const geometry_msgs::TwistStampedConstPtr& cartesian_vel) { if (!arm.Stopped()) { cartesian_velocities.X = cartesian_vel->twist.linear.x; cartesian_velocities.Y = cartesian_vel->twist.linear.y; cartesian_velocities.Z = cartesian_vel->twist.linear.z; cartesian_velocities.ThetaX = cartesian_vel->twist.angular.x; cartesian_velocities.ThetaY = cartesian_vel->twist.angular.y; cartesian_velocities.ThetaZ = cartesian_vel->twist.angular.z; last_cartesian_update = ros::Time().now(); if (cartesian_vel_timer_flag == false) { cartesian_vel_timer.start(); cartesian_vel_timer_flag = true; } } } void JacoArm::CartesianVelTimer(const ros::TimerEvent&) { arm.SetCartesianVelocities(cartesian_velocities); if ((ros::Time().now().toSec() - last_cartesian_update.toSec()) > 1) { cartesian_vel_timer.stop(); cartesian_vel_timer_flag = false; } } void JacoArm::JointVelTimer(const ros::TimerEvent&) { arm.SetVelocities(joint_velocities); if ((ros::Time().now().toSec() - last_joint_update.toSec()) > 1) { joint_vel_timer.stop(); joint_vel_timer_flag = false; } } /*! * \brief Contains coordinates for an alternate "Home" position * * GoHome() function must be enabled in the initialization routine for this to * work. */ void JacoArm::GoHome(void) { /* AngularInfo joint_home; joint_home.Actuator1 = 176.0; joint_home.Actuator2 = 111.0; joint_home.Actuator3 = 107.0; joint_home.Actuator4 = 459.0; joint_home.Actuator5 = 102.0; joint_home.Actuator6 = 106.0; SetAngles(joint_home, 10); //send joints to home position API->SetCartesianControl(); */ } /*! * \brief Publishes the current joint angles. * * Joint angles are published in both their raw state as obtained from the arm * (JointAngles), and transformed & converted to radians (joint_state) as per * the Jaco Kinematics PDF. * * JointState will eventually also publish the velocity and effort for each * joint, when this data is made available by the C++ API. Currenty velocity * and effort are reported as being zero (0.0) for all joints. */ void JacoArm::BroadCastAngles(void) { // Populate an array of joint names. arm_0_joint is the base, arm_5_joint is the wrist. const char* nameArgs[] = {"arm_0_joint", "arm_1_joint", "arm_2_joint", "arm_3_joint", "arm_4_joint", "arm_5_joint"}; std::vector<std::string> JointName(nameArgs, nameArgs+6); AngularPosition arm_angles; jaco_driver::JointAngles current_angles; sensor_msgs::JointState joint_state; joint_state.name = JointName; // Define array sizes for the joint_state topic joint_state.position.resize(6); joint_state.velocity.resize(6); joint_state.effort.resize(6); memset(&arm_angles, 0, sizeof(arm_angles)); //zero structure //Query arm for current joint angles arm.GetAngles(arm_angles.Actuators); // Raw joint angles current_angles.Angle_J1 = arm_angles.Actuators.Actuator1; current_angles.Angle_J2 = arm_angles.Actuators.Actuator2; current_angles.Angle_J3 = arm_angles.Actuators.Actuator3; current_angles.Angle_J4 = arm_angles.Actuators.Actuator4; current_angles.Angle_J5 = arm_angles.Actuators.Actuator5; current_angles.Angle_J6 = arm_angles.Actuators.Actuator6; // Transform from Kinova DH algorithm to physical angles in radians, then place into vector array joint_state.position[0] = (180.0 - arm_angles.Actuators.Actuator1) / (180.0 / PI); joint_state.position[1] = (arm_angles.Actuators.Actuator2 - 270.0) / (180.0 / PI); joint_state.position[2] = (90.0 - arm_angles.Actuators.Actuator3) / (180.0 / PI); joint_state.position[3] = (180.0 - arm_angles.Actuators.Actuator4) / (180.0 / PI); joint_state.position[4] = (180.0 - arm_angles.Actuators.Actuator5) / (180.0 / PI); joint_state.position[5] = (260.0 - arm_angles.Actuators.Actuator6) / (180.0 / PI); //Publish the joint state messages JointAngles_pub.publish(current_angles); // Publishes the raw joint angles in a custom message. JointState_pub.publish(joint_state); // Publishes the transformed angles in a standard sensor_msgs format. } /*! * \brief Publishes the current cartesian coordinates */ void JacoArm::BroadCastPosition(void) { JacoPose pose; geometry_msgs::PoseStamped current_position; arm.GetPosition(pose); current_position.pose = pose.Pose(); ToolPosition_pub.publish(current_position); } void JacoArm::BroadCastFingerPosition(void) { /* Publishes the current finger positions. */ CartesianPosition Jaco_Position; jaco_driver::FingerPosition finger_position; memset(&Jaco_Position, 0, sizeof(Jaco_Position)); //zero structure arm.GetFingers(Jaco_Position.Fingers); finger_position.Finger_1 = Jaco_Position.Fingers.Finger1; finger_position.Finger_2 = Jaco_Position.Fingers.Finger2; finger_position.Finger_3 = Jaco_Position.Fingers.Finger3; FingerPosition_pub.publish(finger_position); } void JacoArm::StatusTimer(const ros::TimerEvent&) { BroadCastAngles(); BroadCastPosition(); BroadCastFingerPosition(); } } <commit_msg>Small bugfix.<commit_after>//============================================================================ // Name : jaco_arm.cpp // Author : WPI, Clearpath Robotics // Version : 0.5 // Copyright : BSD // Description : A ROS driver for controlling the Kinova Jaco robotic manipulator arm //============================================================================ #include "jaco_driver/jaco_arm.h" namespace jaco { JacoArm::JacoArm(JacoComm &arm_comm, ros::NodeHandle &nh) : arm(arm_comm) { std::string joint_velocity_topic, joint_angles_topic, cartesian_velocity_topic, tool_position_topic, set_finger_position_topic, finger_position_topic, joint_state_topic, set_joint_angle_topic; nh.param<std::string>("joint_velocity_topic", joint_velocity_topic, "joint_velocity"); nh.param<std::string>("joint_angles_topic", joint_angles_topic, "joint_angles"); nh.param<std::string>("cartesian_velocity_topic", cartesian_velocity_topic, "cartesian_velocity"); nh.param<std::string>("tool_position_topic", tool_position_topic, "tool_position"); nh.param<std::string>("set_finger_position_topic", set_finger_position_topic, "set_finger_position"); nh.param<std::string>("finger_position_topic", finger_position_topic, "finger_position"); nh.param<std::string>("joint_state_topic", joint_state_topic, "joint_state"); nh.param<std::string>("set_joint_angle_topic", set_joint_angle_topic, "set_joint_angle"); //Print out received topics ROS_DEBUG("Got Joint Velocity Topic Name: <%s>", joint_velocity_topic.c_str()); ROS_DEBUG("Got Joint Angles Topic Name: <%s>", joint_angles_topic.c_str()); ROS_DEBUG("Got Cartesian Velocity Topic Name: <%s>", cartesian_velocity_topic.c_str()); ROS_DEBUG("Got Tool Position Topic Name: <%s>", tool_position_topic.c_str()); ROS_DEBUG("Got Set Finger Position Topic Name: <%s>", set_finger_position_topic.c_str()); ROS_DEBUG("Got Finger Position Topic Name: <%s>", finger_position_topic.c_str()); ROS_DEBUG("Got Joint State Topic Name: <%s>", joint_state_topic.c_str()); ROS_DEBUG("Got Set Joint Angle Topic Name: <%s>", set_joint_angle_topic.c_str()); ROS_INFO("Starting Up Jaco Arm Controller..."); previous_state = 0; /* Set up Services */ stop_service = nh.advertiseService("stop", &JacoArm::StopSRV, this); start_service = nh.advertiseService("start", &JacoArm::StartSRV, this); homing_service = nh.advertiseService("home_arm", &JacoArm::HomeArmSRV, this); /* Set Default Configuration */ // API->RestoreFactoryDefault(); // uncomment comment ONLY if you want to lose your settings on each launch. ClientConfigurations configuration; arm.GetConfig(configuration); arm.PrintConfig(configuration); last_update_time = ros::Time::now(); update_time = ros::Duration(5.0); /* Storing arm in home position */ /* Set up Publishers */ JointAngles_pub = nh.advertise<jaco_driver::JointAngles>(joint_angles_topic, 2); JointState_pub = nh.advertise<sensor_msgs::JointState>(joint_state_topic, 2); ToolPosition_pub = nh.advertise<geometry_msgs::PoseStamped>(tool_position_topic, 2); FingerPosition_pub = nh.advertise<jaco_driver::FingerPosition>(finger_position_topic, 2); /* Set up Subscribers*/ JointVelocity_sub = nh.subscribe(joint_velocity_topic, 1, &JacoArm::VelocityMSG, this); CartesianVelocity_sub = nh.subscribe(cartesian_velocity_topic, 1, &JacoArm::CartesianVelocityMSG, this); SetFingerPosition_sub = nh.subscribe(set_finger_position_topic, 1, &JacoArm::SetFingerPositionMSG, this); SetJoint_sub = nh.subscribe(set_joint_angle_topic, 1, &JacoArm::SetJointAnglesMSG, this); status_timer = nh.createTimer(ros::Duration(0.05), &JacoArm::StatusTimer, this); joint_vel_timer = nh.createTimer(ros::Duration(0.01), &JacoArm::JointVelTimer, this); joint_vel_timer.stop(); joint_vel_timer_flag = false; cartesian_vel_timer = nh.createTimer(ros::Duration(0.01), &JacoArm::CartesianVelTimer, this); cartesian_vel_timer.stop(); cartesian_vel_timer_flag = false; ROS_INFO("The Arm is ready to use."); TrajectoryPoint Jaco_Velocity; memset(&Jaco_Velocity, 0, sizeof(Jaco_Velocity)); //zero structure arm.SetCartesianVelocities(Jaco_Velocity.Position.CartesianPosition); } JacoArm::~JacoArm() { } bool JacoArm::HomeArmSRV(jaco_driver::HomeArm::Request &req, jaco_driver::HomeArm::Response &res) { arm.HomeArm(); res.homearm_result = "JACO ARM HAS BEEN RETURNED HOME"; return true; } /*! * \brief Receives ROS command messages and relays them to SetFingers. */ void JacoArm::SetFingerPositionMSG(const jaco_driver::FingerPositionConstPtr& finger_pos) { if (!arm.Stopped()) { FingersPosition Finger_Position; memset(&Finger_Position, 0, sizeof(Finger_Position)); //zero structure Finger_Position.Finger1 = finger_pos->Finger_1; Finger_Position.Finger2 = finger_pos->Finger_2; Finger_Position.Finger3 = finger_pos->Finger_3; arm.SetFingers(Finger_Position); } } /*! * \brief Receives ROS command messages and relays them to SetAngles. */ void JacoArm::SetJointAnglesMSG(const jaco_driver::JointAnglesConstPtr& angles) { if (!arm.Stopped()) { AngularInfo Joint_Position; memset(&Joint_Position, 0, sizeof(Joint_Position)); //zero structure Joint_Position.Actuator1 = angles->Angle_J1; Joint_Position.Actuator2 = angles->Angle_J2; Joint_Position.Actuator3 = angles->Angle_J3; Joint_Position.Actuator4 = angles->Angle_J4; Joint_Position.Actuator5 = angles->Angle_J5; Joint_Position.Actuator6 = angles->Angle_J6; arm.SetAngles(Joint_Position); } } void JacoArm::VelocityMSG(const jaco_driver::JointVelocityConstPtr& joint_vel) { if (!arm.Stopped()) { joint_velocities.Actuator1 = joint_vel->Velocity_J1; joint_velocities.Actuator2 = joint_vel->Velocity_J2; joint_velocities.Actuator3 = joint_vel->Velocity_J3; joint_velocities.Actuator4 = joint_vel->Velocity_J4; joint_velocities.Actuator5 = joint_vel->Velocity_J5; joint_velocities.Actuator6 = joint_vel->Velocity_J6; last_joint_update = ros::Time().now(); if (joint_vel_timer_flag == false) { joint_vel_timer.start(); joint_vel_timer_flag = true; } } } /*! * \brief Handler for "stop" service. * * Instantly stops the arm and prevents further movement until start service is * invoked. */ bool JacoArm::StopSRV(jaco_driver::Stop::Request &req, jaco_driver::Stop::Response &res) { arm.Stop(); res.stop_result = "JACO ARM HAS BEEN STOPPED"; ROS_DEBUG("JACO ARM STOP REQUEST"); return true; } /*! * \brief Handler for "start" service. * * Re-enables control of the arm after a stop. */ bool JacoArm::StartSRV(jaco_driver::Start::Request &req, jaco_driver::Start::Response &res) { arm.Start(); res.start_result = "JACO ARM CONTROL HAS BEEN ENABLED"; ROS_DEBUG("JACO ARM START REQUEST"); return true; } void JacoArm::CartesianVelocityMSG(const geometry_msgs::TwistStampedConstPtr& cartesian_vel) { if (!arm.Stopped()) { cartesian_velocities.X = cartesian_vel->twist.linear.x; cartesian_velocities.Y = cartesian_vel->twist.linear.y; cartesian_velocities.Z = cartesian_vel->twist.linear.z; cartesian_velocities.ThetaX = cartesian_vel->twist.angular.x; cartesian_velocities.ThetaY = cartesian_vel->twist.angular.y; cartesian_velocities.ThetaZ = cartesian_vel->twist.angular.z; last_cartesian_update = ros::Time().now(); if (cartesian_vel_timer_flag == false) { cartesian_vel_timer.start(); cartesian_vel_timer_flag = true; } } } void JacoArm::CartesianVelTimer(const ros::TimerEvent&) { arm.SetCartesianVelocities(cartesian_velocities); if ((ros::Time().now().toSec() - last_cartesian_update.toSec()) > 1) { cartesian_vel_timer.stop(); cartesian_vel_timer_flag = false; } } void JacoArm::JointVelTimer(const ros::TimerEvent&) { arm.SetVelocities(joint_velocities); if ((ros::Time().now().toSec() - last_joint_update.toSec()) > 1) { joint_vel_timer.stop(); joint_vel_timer_flag = false; } } /*! * \brief Contains coordinates for an alternate "Home" position * * GoHome() function must be enabled in the initialization routine for this to * work. */ void JacoArm::GoHome(void) { /* AngularInfo joint_home; joint_home.Actuator1 = 176.0; joint_home.Actuator2 = 111.0; joint_home.Actuator3 = 107.0; joint_home.Actuator4 = 459.0; joint_home.Actuator5 = 102.0; joint_home.Actuator6 = 106.0; SetAngles(joint_home, 10); //send joints to home position API->SetCartesianControl(); */ } /*! * \brief Publishes the current joint angles. * * Joint angles are published in both their raw state as obtained from the arm * (JointAngles), and transformed & converted to radians (joint_state) as per * the Jaco Kinematics PDF. * * JointState will eventually also publish the velocity and effort for each * joint, when this data is made available by the C++ API. Currenty velocity * and effort are reported as being zero (0.0) for all joints. */ void JacoArm::BroadCastAngles(void) { // Populate an array of joint names. arm_0_joint is the base, arm_5_joint is the wrist. const char* nameArgs[] = {"arm_0_joint", "arm_1_joint", "arm_2_joint", "arm_3_joint", "arm_4_joint", "arm_5_joint"}; std::vector<std::string> JointName(nameArgs, nameArgs+6); AngularPosition arm_angles; jaco_driver::JointAngles current_angles; sensor_msgs::JointState joint_state; joint_state.name = JointName; // Define array sizes for the joint_state topic joint_state.position.resize(6); joint_state.velocity.resize(6); joint_state.effort.resize(6); memset(&arm_angles, 0, sizeof(arm_angles)); //zero structure //Query arm for current joint angles arm.GetAngles(arm_angles.Actuators); // Raw joint angles current_angles.Angle_J1 = arm_angles.Actuators.Actuator1; current_angles.Angle_J2 = arm_angles.Actuators.Actuator2; current_angles.Angle_J3 = arm_angles.Actuators.Actuator3; current_angles.Angle_J4 = arm_angles.Actuators.Actuator4; current_angles.Angle_J5 = arm_angles.Actuators.Actuator5; current_angles.Angle_J6 = arm_angles.Actuators.Actuator6; // Transform from Kinova DH algorithm to physical angles in radians, then place into vector array joint_state.position[0] = (180.0 - arm_angles.Actuators.Actuator1) / (180.0 / M_PI); joint_state.position[1] = (arm_angles.Actuators.Actuator2 - 270.0) / (180.0 / M_PI); joint_state.position[2] = (90.0 - arm_angles.Actuators.Actuator3) / (180.0 / M_PI); joint_state.position[3] = (180.0 - arm_angles.Actuators.Actuator4) / (180.0 / M_PI); joint_state.position[4] = (180.0 - arm_angles.Actuators.Actuator5) / (180.0 / M_PI); joint_state.position[5] = (260.0 - arm_angles.Actuators.Actuator6) / (180.0 / M_PI); //Publish the joint state messages JointAngles_pub.publish(current_angles); // Publishes the raw joint angles in a custom message. JointState_pub.publish(joint_state); // Publishes the transformed angles in a standard sensor_msgs format. } /*! * \brief Publishes the current cartesian coordinates */ void JacoArm::BroadCastPosition(void) { JacoPose pose; geometry_msgs::PoseStamped current_position; arm.GetPosition(pose); current_position.pose = pose.Pose(); ToolPosition_pub.publish(current_position); } void JacoArm::BroadCastFingerPosition(void) { /* Publishes the current finger positions. */ CartesianPosition Jaco_Position; jaco_driver::FingerPosition finger_position; memset(&Jaco_Position, 0, sizeof(Jaco_Position)); //zero structure arm.GetFingers(Jaco_Position.Fingers); finger_position.Finger_1 = Jaco_Position.Fingers.Finger1; finger_position.Finger_2 = Jaco_Position.Fingers.Finger2; finger_position.Finger_3 = Jaco_Position.Fingers.Finger3; FingerPosition_pub.publish(finger_position); } void JacoArm::StatusTimer(const ros::TimerEvent&) { BroadCastAngles(); BroadCastPosition(); BroadCastFingerPosition(); } } <|endoftext|>
<commit_before>/** * @file /sophus_ros_conversions/include/sophus_ros_conversions/geometry.hpp */ /***************************************************************************** ** Ifdefs *****************************************************************************/ #ifndef sophus_ros_conversions_GEOMETRY_HPP_ #define sophus_ros_conversions_GEOMETRY_HPP_ /***************************************************************************** ** Includes *****************************************************************************/ #include <geometry_msgs/Pose.h> #include <geometry_msgs/Transform.h> #include <geometry_msgs/Vector3.h> #include <sophus/se3.hpp> /***************************************************************************** ** Namespaces *****************************************************************************/ namespace sophus_ros_conversions { /***************************************************************************** ** Interfaces *****************************************************************************/ /** * Converts a ros pose message to a sophus pose. * * @param p * @param s */ void poseMsgToSophus(const geometry_msgs::Pose &p, Sophus::SE3f &s); /** * Converts a sophus pose to a ros pose message. * @param s * @return */ geometry_msgs::Pose sophusToPoseMsg(const Sophus::SE3f& s); /** * Converts vector3f, usually used as part of ros transform messages into * the translation part that gets used in Sophus::SE3f types. Note that * sophus uses SE3f::Point as the translation type in the constructors of SE3f types. */ void vector3MsgToSophus(const geometry_msgs::Vector3 &v, Sophus::SE3f::Point &translation); /** * Converts ros transform message to a homogenous transform in sophus. * @param transform * @param se3 */ void transformMsgToSophus(const geometry_msgs::Transform &transform, Sophus::SE3f &se3); /** * Alternate form of ros transform -> sophus conversion. * * @param transform * @return Sophus::SE3f */ Sophus::SE3f transformMsgToSophus(const geometry_msgs::Transform &transform); /** * Convert sophus transform to ros transform. * @param se3 * @return geometry_msgs::Transform */ geometry_msgs::Transform sophusToTransformMsg(const Sophus::SE3f& se3); /***************************************************************************** ** Trailers *****************************************************************************/ } // namespace sophus_ros_conversions #endif /* sophus_ros_conversions_GEOMETRY_HPP_ */ <commit_msg>add function to convert tf::stampedTransform to sophus<commit_after>/** * @file /sophus_ros_conversions/include/sophus_ros_conversions/geometry.hpp */ /***************************************************************************** ** Ifdefs *****************************************************************************/ #ifndef sophus_ros_conversions_GEOMETRY_HPP_ #define sophus_ros_conversions_GEOMETRY_HPP_ /***************************************************************************** ** Includes *****************************************************************************/ #include <geometry_msgs/Pose.h> #include <geometry_msgs/Transform.h> #include <geometry_msgs/Vector3.h> #include <sophus/se3.hpp> #include <tf/transform_listener.h> /***************************************************************************** ** Namespaces *****************************************************************************/ namespace sophus_ros_conversions { /***************************************************************************** ** Interfaces *****************************************************************************/ /** * Converts a ros pose message to a sophus pose. * * @param p * @param s */ void poseMsgToSophus(const geometry_msgs::Pose &p, Sophus::SE3f &s); /** * Converts a sophus pose to a ros pose message. * @param s * @return */ geometry_msgs::Pose sophusToPoseMsg(const Sophus::SE3f& s); /** * Converts vector3f, usually used as part of ros transform messages into * the translation part that gets used in Sophus::SE3f types. Note that * sophus uses SE3f::Point as the translation type in the constructors of SE3f types. */ void vector3MsgToSophus(const geometry_msgs::Vector3 &v, Sophus::SE3f::Point &translation); /** * Converts ros transform message to a homogenous transform in sophus. * @param transform * @param se3 */ void transformMsgToSophus(const geometry_msgs::Transform &transform, Sophus::SE3f &se3); template<typename T> void stampedTransformToSophus( const tf::StampedTransform & transform, Sophus::SE3Group<T> & se3 ) { Eigen::Quaternion<T> q; Eigen::Matrix<T,3,1> t; q.x() = transform.getRotation().getX(); q.y() = transform.getRotation().getY(); q.z() = transform.getRotation().getZ(); q.w() = transform.getRotation().getW(); t.x() = transform.getOrigin().getX(); t.y() = transform.getOrigin().getY(); t.z() = transform.getOrigin().getZ(); se3 = Sophus::SE3Group<T>(q,t); } /** * Alternate form of ros transform -> sophus conversion. * * @param transform * @return Sophus::SE3f */ Sophus::SE3f transformMsgToSophus(const geometry_msgs::Transform &transform); /** * Convert sophus transform to ros transform. * @param se3 * @return geometry_msgs::Transform */ geometry_msgs::Transform sophusToTransformMsg(const Sophus::SE3f& se3); /***************************************************************************** ** Trailers *****************************************************************************/ } // namespace sophus_ros_conversions #endif /* sophus_ros_conversions_GEOMETRY_HPP_ */ <|endoftext|>
<commit_before>/* GNE - Game Networking Engine, a portable multithreaded networking library. * Copyright (C) 2001 Jason Winnebeck ([email protected]) * Project website: http://www.rit.edu/~jpw9607/ * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "gneintern.h" #include "ListServerConnection.h" //##ModelId=3AE4AA420046 ListServerConnection::ListServerConnection(std::string address) : ClientConnection(0, 0, address) { } //##ModelId=3AE4AA420078 ListServerConnection::~ListServerConnection() { } //##ModelId=3AE4AAE000C8 void ListServerConnection::setGame(std::string gameName) { } //##ModelId=3AE4AB3A0000 void ListServerConnection::getGameList() { } <commit_msg>ctor change.<commit_after>/* GNE - Game Networking Engine, a portable multithreaded networking library. * Copyright (C) 2001 Jason Winnebeck ([email protected]) * Project website: http://www.rit.edu/~jpw9607/ * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "gneintern.h" #include "ListServerConnection.h" //##ModelId=3AE4AA420046 ListServerConnection::ListServerConnection(std::string address) : ClientConnection(0, 0) { } //##ModelId=3AE4AA420078 ListServerConnection::~ListServerConnection() { } //##ModelId=3AE4AAE000C8 void ListServerConnection::setGame(std::string gameName) { } //##ModelId=3AE4AB3A0000 void ListServerConnection::getGameList() { } <|endoftext|>
<commit_before>#include "ArraySort.h" namespace NP_ARRAYSORT { void quickSort(Comparable ** array, int fromIndex, int toIndex) { if (fromIndex < toIndex) { int position = partition(array, fromIndex, toIndex); quickSort(array, fromIndex, position - 1); quickSort(array, position + 1, toIndex); } } int partition(Comparable ** array, int fromIndex, int toIndex) { Comparable * pivot = array[toIndex]; int small = fromIndex - 1; for (int k = fromIndex; k < toIndex; k++) { if (*array[k] <= *pivot) { small++; swap(array, k, small); } } swap(array, toIndex, small + 1); return small + 1; } //----------------------------------------------------------------------------- // function: SortFirstMiddleLast // description: Sort the three items // // Called By: all sorting algs // // Parameters: Comparable ** array, int loIndex, int midIndex, int hiIndex // // Returns: void // // History Log: // 4/27/17 NP completed version 1.0 // ---------------------------------------------------------------------------- void SortFirstMiddleLast(Comparable ** array, int loIndex, int midIndex, int hiIndex) { Comparable * low = array[loIndex]; Comparable * mid = array[midIndex]; Comparable * hi = array[hiIndex]; while (!((low < mid) && (mid < hi))) { if (low > mid) swap(array, loIndex, midIndex); if (mid > hi) swap(array, midIndex, hiIndex); if (low > hi) swap(array, loIndex, hiIndex); low = array[loIndex]; mid = array[midIndex]; hi = array[hiIndex]; } } //----------------------------------------------------------------------------- // function: swap // description: swaps two items in an array // // Input: Comparable ** array, int index1, int index2 // // Called By: all sorting algs // // Parameters: Comparable ** array, int index1, int index2 // // Returns: void // // History Log: // 4/27/17 NP completed version 1.0 // ---------------------------------------------------------------------------- void swap(Comparable ** array, int index1, int index2) { Comparable * tmp = array[index1]; array[index1] = array[index2]; array[index2] = tmp; } void insertionSort(Comparable ** array, int fromIndex, int toIndex) { if (fromIndex < 1) fromIndex = 1; for (int outerIndex = fromIndex; outerIndex < toIndex; outerIndex++) { int innerIndex = outerIndex - 1; Comparable * temp = array[outerIndex]; while (innerIndex >= 0 && *temp < *array[innerIndex]) { array[innerIndex + 1] = array[innerIndex]; innerIndex--; } array[innerIndex + 1] = temp; } } //----------------------------------------------------------------------------- // function: safeRead(istream& sin, Comparable* d, const char* re) // description: safely reads in a DateTime (d) from sin. // Re-prompts and re-enters if input is invalid // // Input: Comparable* d from sin // // Called By: main // // Parameters: istream& sin -- the input stream // Comparable* d -- pointer to the object input // const char* prompt -- prompt, if necessary // // Returns: void // // History Log: // 2/9/08 PB completed version 1.0 // ---------------------------------------------------------------------------- void safeRead(istream& sin, Comparable* d, const char* prompt) { const int BUFFERSIZE = 256; d->input(sin); while (!sin) { // read in number--enter loop if fail sin.clear(); // clear fail sin.ignore(BUFFERSIZE, '\n'); // read past newline cout << prompt; // re-prompt d->input(sin); } // read past newline once input succeeds sin.ignore(BUFFERSIZE, '\n'); } //----------------------------------------------------------------------------- /// function: void printArray(ostream & sout, Comparable **a, int size) /// description: can print out an array of DateTime * // // Output: Comparable* d sout // // Called By: main // // Parameters: ostream& sout -- the output stream // Comparable** a -- array of pointers to the objects // int size -- number of elements in the array // // Returns: void // // History Log: // 2/9/08 PB completed version 1.0 // ---------------------------------------------------------------------------- void printArray(ostream & sout, Comparable **array, int len) { for (int i = 0; i < len; i++) { array[i]->print(sout); if (i + 1 < len) sout << ", "; } sout << endl; } } <commit_msg>use "optimized" sort<commit_after>#include "ArraySort.h" namespace NP_ARRAYSORT { void quickSort(Comparable ** array, int fromIndex, int toIndex) { if (fromIndex + 4 < toIndex) { int position = partition(array, fromIndex, toIndex); quickSort(array, fromIndex, position - 1); quickSort(array, position + 1, toIndex); } else if (fromIndex < toIndex) { insertionSort(array, fromIndex, toIndex); } } int partition(Comparable ** array, int fromIndex, int toIndex) { Comparable * pivot = array[toIndex]; int small = fromIndex - 1; for (int index = fromIndex; index < toIndex; index++) { if (*array[index] <= *pivot) { small++; swap(array, index, small); } } swap(array, toIndex, small + 1); return small + 1; } //----------------------------------------------------------------------------- // function: SortFirstMiddleLast // description: Sort the three items // // Called By: all sorting algs // // Parameters: Comparable ** array, int loIndex, int midIndex, int hiIndex // // Returns: void // // History Log: // 4/27/17 NP completed version 1.0 // ---------------------------------------------------------------------------- void SortFirstMiddleLast(Comparable ** array, int loIndex, int midIndex, int hiIndex) { Comparable * low = array[loIndex]; Comparable * mid = array[midIndex]; Comparable * hi = array[hiIndex]; while ((low > mid) || (mid > hi)) { if (low > mid) swap(array, loIndex, midIndex); if (mid > hi) swap(array, midIndex, hiIndex); if (low > hi) swap(array, loIndex, hiIndex); low = array[loIndex]; mid = array[midIndex]; hi = array[hiIndex]; } } //----------------------------------------------------------------------------- // function: swap // description: swaps two items in an array // // Input: Comparable ** array, int index1, int index2 // // Called By: all sorting algs // // Parameters: Comparable ** array, int index1, int index2 // // Returns: void // // History Log: // 4/27/17 NP completed version 1.0 // ---------------------------------------------------------------------------- void swap(Comparable ** array, int index1, int index2) { Comparable * tmp = array[index1]; array[index1] = array[index2]; array[index2] = tmp; } void insertionSort(Comparable ** array, int fromIndex, int toIndex) { if (fromIndex < 1) fromIndex = 1; for (int outerIndex = fromIndex; outerIndex < toIndex; outerIndex++) { int innerIndex = outerIndex - 1; Comparable * temp = array[outerIndex]; while (innerIndex >= 0 && *temp < *array[innerIndex]) { array[innerIndex + 1] = array[innerIndex]; innerIndex--; } array[innerIndex + 1] = temp; } } //----------------------------------------------------------------------------- // function: safeRead(istream& sin, Comparable* d, const char* re) // description: safely reads in a DateTime (d) from sin. // Re-prompts and re-enters if input is invalid // // Input: Comparable* d from sin // // Called By: main // // Parameters: istream& sin -- the input stream // Comparable* d -- pointer to the object input // const char* prompt -- prompt, if necessary // // Returns: void // // History Log: // 2/9/08 PB completed version 1.0 // ---------------------------------------------------------------------------- void safeRead(istream& sin, Comparable* d, const char* prompt) { const int BUFFERSIZE = 256; d->input(sin); while (!sin) { // read in number--enter loop if fail sin.clear(); // clear fail sin.ignore(BUFFERSIZE, '\n'); // read past newline cout << prompt; // re-prompt d->input(sin); } // read past newline once input succeeds sin.ignore(BUFFERSIZE, '\n'); } //----------------------------------------------------------------------------- /// function: void printArray(ostream & sout, Comparable **a, int size) /// description: can print out an array of DateTime * // // Output: Comparable* d sout // // Called By: main // // Parameters: ostream& sout -- the output stream // Comparable** a -- array of pointers to the objects // int size -- number of elements in the array // // Returns: void // // History Log: // 2/9/08 PB completed version 1.0 // ---------------------------------------------------------------------------- void printArray(ostream & sout, Comparable **array, int len) { for (int i = 0; i < len; i++) { array[i]->print(sout); if (i + 1 < len) sout << ", "; } sout << endl; } } <|endoftext|>
<commit_before>/// \file ROOT/TCanvas.hxx /// \ingroup Gpad ROOT7 /// \author Axel Naumann <[email protected]> /// \date 2015-07-08 /// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback /// is welcome! /************************************************************************* * Copyright (C) 1995-2015, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT7_TCanvas #define ROOT7_TCanvas #include "ROOT/TColor.hxx" #include "ROOT/TPad.hxx" #include "ROOT/TVirtualCanvasPainter.hxx" #include <memory> #include <string> #include <vector> namespace ROOT { namespace Experimental { class TDrawingOptsBaseNoDefault; template <class PRIMITIVE> class TDrawingAttrRef; /** \class ROOT::Experimental::TCanvas A window's topmost `TPad`. Access is through TCanvasPtr. */ class TCanvas: public TPadBase { private: /// Title of the canvas. std::string fTitle; /// Size of the canvas in pixels, std::array<TPadCoord::Pixel, 2> fSize; /// Colors used by drawing options in the pad and any sub-pad. Internal::TDrawingAttrTable<TColor> fColorTable; /// Integers used by drawing options in the pad and any sub-pad. Internal::TDrawingAttrTable<long long> fIntAttrTable; /// Floating points used by drawing options in the pad and any sub-pad. Internal::TDrawingAttrTable<double> fFPAttrTable; /// Modify counter, incremented every time canvas is changed uint64_t fModified; ///<! /// The painter of this canvas, bootstrapping the graphics connection. /// Unmapped canvases (those that never had `Draw()` invoked) might not have /// a painter. std::unique_ptr<Internal::TVirtualCanvasPainter> fPainter; ///<! /// Disable copy construction for now. TCanvas(const TCanvas &) = delete; /// Disable assignment for now. TCanvas &operator=(const TCanvas &) = delete; ///\{ ///\name Drawing options attribute handling /// Attribute table (non-const access). Internal::TDrawingAttrTable<TColor> &GetAttrTable(TColor *) { return fColorTable; } Internal::TDrawingAttrTable<long long> &GetAttrTable(long long *) { return fIntAttrTable; } Internal::TDrawingAttrTable<double> &GetAttrTable(double *) { return fFPAttrTable; } /// Attribute table (const access). const Internal::TDrawingAttrTable<TColor> &GetAttrTable(TColor *) const { return fColorTable; } const Internal::TDrawingAttrTable<long long> &GetAttrTable(long long *) const { return fIntAttrTable; } const Internal::TDrawingAttrTable<double> &GetAttrTable(double *) const { return fFPAttrTable; } friend class ROOT::Experimental::TDrawingOptsBaseNoDefault; template <class PRIMITIVE> friend class ROOT::Experimental::TDrawingAttrRef; ///\} public: static std::shared_ptr<TCanvas> Create(const std::string &title); /// Create a temporary TCanvas; for long-lived ones please use Create(). TCanvas() = default; ~TCanvas() { Wipe(); /* FIXME: this should become Attrs owned and referenced by the TPads */} const TCanvas &GetCanvas() const override { return *this; } /// Access to the top-most canvas, if any (non-const version). TCanvas &GetCanvas() override { return *this; } /// Return canvas pixel size as array with two elements - width and height const std::array<TPadCoord::Pixel, 2> &GetSize() const { return fSize; } /// Set canvas pixel size as array with two elements - width and height void SetSize(const std::array<TPadCoord::Pixel, 2> &sz) { fSize = sz; } /// Set canvas pixel size - width and height void SetSize(const TPadCoord::Pixel &width, const TPadCoord::Pixel &height) { fSize[0] = width; fSize[1] = height; } /// Display the canvas. void Show(const std::string &where = ""); /// Close all canvas displays void Hide(); /// Insert panel into the canvas, canvas should be shown at this moment template <class PANEL> bool AddPanel(std::shared_ptr<PANEL> &panel) { if (!fPainter) return false; return fPainter->AddPanel(panel->GetWindow()); } // Indicates that primitives list was changed or any primitive was modified void Modified() { fModified++; } // Return if canvas was modified and not yet updated bool IsModified() const; /// update drawing void Update(bool async = false, CanvasCallback_t callback = nullptr); /// Save canvas in image file void SaveAs(const std::string &filename, bool async = false, CanvasCallback_t callback = nullptr); /// Get the canvas's title. const std::string &GetTitle() const { return fTitle; } /// Set the canvas's title. void SetTitle(const std::string &title) { fTitle = title; } /// Convert a `Pixel` position to Canvas-normalized positions. std::array<TPadCoord::Normal, 2> PixelsToNormal(const std::array<TPadCoord::Pixel, 2> &pos) const final { return {{pos[0] / fSize[0], pos[1] / fSize[1]}}; } static const std::vector<std::shared_ptr<TCanvas>> &GetCanvases(); }; } // namespace Experimental } // namespace ROOT #endif <commit_msg>Remove attr table from canvas.<commit_after>/// \file ROOT/TCanvas.hxx /// \ingroup Gpad ROOT7 /// \author Axel Naumann <[email protected]> /// \date 2015-07-08 /// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback /// is welcome! /************************************************************************* * Copyright (C) 1995-2015, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT7_TCanvas #define ROOT7_TCanvas #include "ROOT/TPad.hxx" #include "ROOT/TVirtualCanvasPainter.hxx" #include <memory> #include <string> #include <vector> namespace ROOT { namespace Experimental { class TDrawingOptsBaseNoDefault; template <class PRIMITIVE> class TDrawingAttrRef; /** \class ROOT::Experimental::TCanvas A window's topmost `TPad`. */ class TCanvas: public TPadBase { private: /// Title of the canvas. std::string fTitle; /// Size of the canvas in pixels, std::array<TPadCoord::Pixel, 2> fSize; /// Modify counter, incremented every time canvas is changed uint64_t fModified; ///<! /// The painter of this canvas, bootstrapping the graphics connection. /// Unmapped canvases (those that never had `Draw()` invoked) might not have /// a painter. std::unique_ptr<Internal::TVirtualCanvasPainter> fPainter; ///<! /// Disable copy construction for now. TCanvas(const TCanvas &) = delete; /// Disable assignment for now. TCanvas &operator=(const TCanvas &) = delete; public: static std::shared_ptr<TCanvas> Create(const std::string &title); /// Create a temporary TCanvas; for long-lived ones please use Create(). TCanvas() = default; ~TCanvas() = default; const TCanvas &GetCanvas() const override { return *this; } /// Access to the top-most canvas, if any (non-const version). TCanvas &GetCanvas() override { return *this; } /// Return canvas pixel size as array with two elements - width and height const std::array<TPadCoord::Pixel, 2> &GetSize() const { return fSize; } /// Set canvas pixel size as array with two elements - width and height void SetSize(const std::array<TPadCoord::Pixel, 2> &sz) { fSize = sz; } /// Set canvas pixel size - width and height void SetSize(const TPadCoord::Pixel &width, const TPadCoord::Pixel &height) { fSize[0] = width; fSize[1] = height; } /// Display the canvas. void Show(const std::string &where = ""); /// Close all canvas displays void Hide(); /// Insert panel into the canvas, canvas should be shown at this moment template <class PANEL> bool AddPanel(std::shared_ptr<PANEL> &panel) { if (!fPainter) return false; return fPainter->AddPanel(panel->GetWindow()); } // Indicates that primitives list was changed or any primitive was modified void Modified() { fModified++; } // Return if canvas was modified and not yet updated bool IsModified() const; /// update drawing void Update(bool async = false, CanvasCallback_t callback = nullptr); /// Save canvas in image file void SaveAs(const std::string &filename, bool async = false, CanvasCallback_t callback = nullptr); /// Get the canvas's title. const std::string &GetTitle() const { return fTitle; } /// Set the canvas's title. void SetTitle(const std::string &title) { fTitle = title; } /// Convert a `Pixel` position to Canvas-normalized positions. std::array<TPadCoord::Normal, 2> PixelsToNormal(const std::array<TPadCoord::Pixel, 2> &pos) const final { return {{pos[0] / fSize[0], pos[1] / fSize[1]}}; } static const std::vector<std::shared_ptr<TCanvas>> &GetCanvases(); }; } // namespace Experimental } // namespace ROOT #endif <|endoftext|>
<commit_before>/* The OpenTRV project licenses this file to you under the Apache Licence, Version 2.0 (the "Licence"); you may not use this file except in compliance with the Licence. You may obtain a copy of the Licence at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Licence for the specific language governing permissions and limitations under the Licence. Author(s) / Copyright (s): Damon Hart-Davis 2016 */ /* * OTRadValve CurrentSenseValveMotorDirect tests. */ #include <gtest/gtest.h> #include <cstdint> #include <cstdio> #include <OTRadValve.h> // Test calibration calculations in CurrentSenseValveMotorDirect for REV7/DORM1/TRV1 board. // Also check some of the use of those calculations. // In particular test the logic in ModelledRadValveState for starting from extreme positions. // // Adapted 2016/10/18 from test_VALVEMODEL.ino testCSVMDC(). TEST(CurrentSenseValveMotorDirect,REV7CSVMDC) { // Compute minimum dead-reckoning ticks as for V0p2/REV7 20161018. const uint8_t subcycleTicksRoundedDown_ms = 7; const uint8_t minTicks = OTRadValve::CurrentSenseValveMotorDirect::computeMinMotorDRTicks(subcycleTicksRoundedDown_ms); ASSERT_EQ(35, minTicks); // Compute maximum sub-cycle time to start valve movement as for V0p2/REV7 20161018. const uint8_t gst_max = 255; const uint8_t minimumMotorRunupTicks = 4; // OTRadValve::ValveMotorDirectV1HardwareDriverBase::minMotorRunupTicks as at 20161018. const uint8_t sctAbsLimit = OTRadValve::CurrentSenseValveMotorDirect::computeSctAbsLimit(subcycleTicksRoundedDown_ms, gst_max, minimumMotorRunupTicks); ASSERT_EQ(230, sctAbsLimit); // Create calibration parameters with values that happen to work for V0p2/REV7. OTRadValve::CurrentSenseValveMotorDirect::CalibrationParameters cp(minTicks); // Test the calculations with one plausible calibration data set. ASSERT_TRUE(cp.updateAndCompute(1601U, 1105U)); // Must not fail... ASSERT_EQ(4, cp.getApproxPrecisionPC()); ASSERT_EQ(25, cp.getTfotcSmall()); ASSERT_EQ(17, cp.getTfctoSmall()); // Check that a calibration instance can be reused correctly. const uint16_t tfo2 = 1803U; const uint16_t tfc2 = 1373U; ASSERT_TRUE(cp.updateAndCompute(tfo2, tfc2)); // Must not fail... ASSERT_EQ(3, cp.getApproxPrecisionPC()); ASSERT_EQ(28, cp.getTfotcSmall()); ASSERT_EQ(21, cp.getTfctoSmall()); // Check that computing position works... // Simple case: fully closed, no accumulated reverse ticks. volatile uint16_t ticksFromOpen, ticksReverse; ticksFromOpen = tfo2; ticksReverse = 0; ASSERT_EQ(0, cp.computePosition(ticksFromOpen, ticksReverse)); ASSERT_EQ(tfo2, ticksFromOpen); ASSERT_EQ(0, ticksReverse); // Simple case: fully open, no accumulated reverse ticks. ticksFromOpen = 0; ticksReverse = 0; ASSERT_EQ(100, cp.computePosition(ticksFromOpen, ticksReverse)); ASSERT_EQ(0, ticksFromOpen); ASSERT_EQ(0, ticksReverse); // Try at half-way mark, no reverse ticks. ticksFromOpen = tfo2 / 2; ticksReverse = 0; ASSERT_EQ(50, cp.computePosition(ticksFromOpen, ticksReverse)); ASSERT_EQ(tfo2/2, ticksFromOpen); ASSERT_EQ(0, ticksReverse); // Try at half-way mark with just one reverse tick (nothing should change). ticksFromOpen = tfo2 / 2; ticksReverse = 1; ASSERT_EQ(50, cp.computePosition(ticksFromOpen, ticksReverse)); ASSERT_EQ(tfo2/2, ticksFromOpen); ASSERT_EQ(1, ticksReverse); // Try at half-way mark with a big-enough block of reverse ticks to be significant. ticksFromOpen = tfo2 / 2; ticksReverse = cp.getTfctoSmall(); ASSERT_EQ(51, cp.computePosition(ticksFromOpen, ticksReverse)); ASSERT_EQ(tfo2/2 - cp.getTfotcSmall(), ticksFromOpen); ASSERT_EQ(0, ticksReverse); // DHD20151025: one set of actual measurements during calibration. // ticksFromOpenToClosed: 1529 // ticksFromClosedToOpen: 1295 } class DummyHardwareDriver : public OTRadValve::HardwareMotorDriverInterface { public: // Detect if end-stop is reached or motor current otherwise very high. virtual bool isCurrentHigh(OTRadValve::HardwareMotorDriverInterface::motor_drive mdir = motorDriveOpening) const override { return(currentHigh); } // isCurrentHigh() returns this value. bool currentHigh; DummyHardwareDriver() : currentHigh(false) { } virtual void motorRun(uint8_t maxRunTicks, motor_drive dir, OTRadValve::HardwareMotorDriverInterfaceCallbackHandler &callback) override { } }; // Always claims to be at the start of a major cycle. static uint8_t dummyGetSubCycleTime() { return(0); } // Test that direct abstract motor drive logic is constructable and minimally sane.. // // Adapted 2016/10/18 from test_VALVEMODEL.ino testCurrentSenseValveMotorDirect(). TEST(CurrentSenseValveMotorDirect,bascis) { const uint8_t subcycleTicksRoundedDown_ms = 7; // For REV7: OTV0P2BASE::SUBCYCLE_TICK_MS_RD. const uint8_t gsct_max = 255; // For REV7: OTV0P2BASE::GSCT_MAX. const uint8_t minimumMotorRunupTicks = 4; // For REV7: OTRadValve::ValveMotorDirectV1HardwareDriverBase::minMotorRunupTicks. DummyHardwareDriver dhw; OTRadValve::CurrentSenseValveMotorDirect csvmd1(&dhw, dummyGetSubCycleTime, OTRadValve::CurrentSenseValveMotorDirect::computeMinMotorDRTicks(subcycleTicksRoundedDown_ms), OTRadValve::CurrentSenseValveMotorDirect::computeSctAbsLimit(subcycleTicksRoundedDown_ms, gsct_max, minimumMotorRunupTicks)); // POWER UP // Whitebox test of internal state: should be init. ASSERT_EQ(OTRadValve::CurrentSenseValveMotorDirect::init, csvmd1.getState()); // Verify NOT marked as in normal run state immediately upon initialisation. ASSERT_TRUE(!csvmd1.isInNormalRunState()); // Verify NOT marked as in error state immediately upon initialisation. ASSERT_TRUE(!csvmd1.isInErrorState()); // Target % open must start off in a sensible state; fully-closed is good. ASSERT_EQ(0, csvmd1.getTargetPC()); // Until calibration has been successfully run, this should be in non-proportional mode. ASSERT_TRUE(csvmd1.inNonProprtionalMode()); // Nothing passed in requires deferral of (re)calibration. ASSERT_FALSE(csvmd1.shouldDeferCalibration()); } <commit_msg>TODO-1037: tests of shouldDeferCalibration()<commit_after>/* The OpenTRV project licenses this file to you under the Apache Licence, Version 2.0 (the "Licence"); you may not use this file except in compliance with the Licence. You may obtain a copy of the Licence at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Licence for the specific language governing permissions and limitations under the Licence. Author(s) / Copyright (s): Damon Hart-Davis 2016 */ /* * OTRadValve CurrentSenseValveMotorDirect tests. */ #include <gtest/gtest.h> #include <cstdint> #include <cstdio> #include <OTRadValve.h> // Test calibration calculations in CurrentSenseValveMotorDirect for REV7/DORM1/TRV1 board. // Also check some of the use of those calculations. // In particular test the logic in ModelledRadValveState for starting from extreme positions. // // Adapted 2016/10/18 from test_VALVEMODEL.ino testCSVMDC(). TEST(CurrentSenseValveMotorDirect,REV7CSVMDC) { // Compute minimum dead-reckoning ticks as for V0p2/REV7 20161018. const uint8_t subcycleTicksRoundedDown_ms = 7; const uint8_t minTicks = OTRadValve::CurrentSenseValveMotorDirect::computeMinMotorDRTicks(subcycleTicksRoundedDown_ms); ASSERT_EQ(35, minTicks); // Compute maximum sub-cycle time to start valve movement as for V0p2/REV7 20161018. const uint8_t gst_max = 255; const uint8_t minimumMotorRunupTicks = 4; // OTRadValve::ValveMotorDirectV1HardwareDriverBase::minMotorRunupTicks as at 20161018. const uint8_t sctAbsLimit = OTRadValve::CurrentSenseValveMotorDirect::computeSctAbsLimit(subcycleTicksRoundedDown_ms, gst_max, minimumMotorRunupTicks); ASSERT_EQ(230, sctAbsLimit); // Create calibration parameters with values that happen to work for V0p2/REV7. OTRadValve::CurrentSenseValveMotorDirect::CalibrationParameters cp(minTicks); // Test the calculations with one plausible calibration data set. ASSERT_TRUE(cp.updateAndCompute(1601U, 1105U)); // Must not fail... ASSERT_EQ(4, cp.getApproxPrecisionPC()); ASSERT_EQ(25, cp.getTfotcSmall()); ASSERT_EQ(17, cp.getTfctoSmall()); // Check that a calibration instance can be reused correctly. const uint16_t tfo2 = 1803U; const uint16_t tfc2 = 1373U; ASSERT_TRUE(cp.updateAndCompute(tfo2, tfc2)); // Must not fail... ASSERT_EQ(3, cp.getApproxPrecisionPC()); ASSERT_EQ(28, cp.getTfotcSmall()); ASSERT_EQ(21, cp.getTfctoSmall()); // Check that computing position works... // Simple case: fully closed, no accumulated reverse ticks. volatile uint16_t ticksFromOpen, ticksReverse; ticksFromOpen = tfo2; ticksReverse = 0; ASSERT_EQ(0, cp.computePosition(ticksFromOpen, ticksReverse)); ASSERT_EQ(tfo2, ticksFromOpen); ASSERT_EQ(0, ticksReverse); // Simple case: fully open, no accumulated reverse ticks. ticksFromOpen = 0; ticksReverse = 0; ASSERT_EQ(100, cp.computePosition(ticksFromOpen, ticksReverse)); ASSERT_EQ(0, ticksFromOpen); ASSERT_EQ(0, ticksReverse); // Try at half-way mark, no reverse ticks. ticksFromOpen = tfo2 / 2; ticksReverse = 0; ASSERT_EQ(50, cp.computePosition(ticksFromOpen, ticksReverse)); ASSERT_EQ(tfo2/2, ticksFromOpen); ASSERT_EQ(0, ticksReverse); // Try at half-way mark with just one reverse tick (nothing should change). ticksFromOpen = tfo2 / 2; ticksReverse = 1; ASSERT_EQ(50, cp.computePosition(ticksFromOpen, ticksReverse)); ASSERT_EQ(tfo2/2, ticksFromOpen); ASSERT_EQ(1, ticksReverse); // Try at half-way mark with a big-enough block of reverse ticks to be significant. ticksFromOpen = tfo2 / 2; ticksReverse = cp.getTfctoSmall(); ASSERT_EQ(51, cp.computePosition(ticksFromOpen, ticksReverse)); ASSERT_EQ(tfo2/2 - cp.getTfotcSmall(), ticksFromOpen); ASSERT_EQ(0, ticksReverse); // DHD20151025: one set of actual measurements during calibration. // ticksFromOpenToClosed: 1529 // ticksFromClosedToOpen: 1295 } class DummyHardwareDriver : public OTRadValve::HardwareMotorDriverInterface { public: // Detect if end-stop is reached or motor current otherwise very high. virtual bool isCurrentHigh(OTRadValve::HardwareMotorDriverInterface::motor_drive mdir = motorDriveOpening) const override { return(currentHigh); } // isCurrentHigh() returns this value. bool currentHigh; DummyHardwareDriver() : currentHigh(false) { } virtual void motorRun(uint8_t maxRunTicks, motor_drive dir, OTRadValve::HardwareMotorDriverInterfaceCallbackHandler &callback) override { } }; // Always claims to be at the start of a major cycle. static uint8_t dummyGetSubCycleTime() { return(0); } // Test that direct abstract motor drive logic is constructable and minimally sane.. // // Adapted 2016/10/18 from test_VALVEMODEL.ino testCurrentSenseValveMotorDirect(). TEST(CurrentSenseValveMotorDirect,bascis) { const uint8_t subcycleTicksRoundedDown_ms = 7; // For REV7: OTV0P2BASE::SUBCYCLE_TICK_MS_RD. const uint8_t gsct_max = 255; // For REV7: OTV0P2BASE::GSCT_MAX. const uint8_t minimumMotorRunupTicks = 4; // For REV7: OTRadValve::ValveMotorDirectV1HardwareDriverBase::minMotorRunupTicks. DummyHardwareDriver dhw; OTRadValve::CurrentSenseValveMotorDirect csvmd1(&dhw, dummyGetSubCycleTime, OTRadValve::CurrentSenseValveMotorDirect::computeMinMotorDRTicks(subcycleTicksRoundedDown_ms), OTRadValve::CurrentSenseValveMotorDirect::computeSctAbsLimit(subcycleTicksRoundedDown_ms, gsct_max, minimumMotorRunupTicks)); // POWER UP // Whitebox test of internal state: should be init. ASSERT_EQ(OTRadValve::CurrentSenseValveMotorDirect::init, csvmd1.getState()); // Verify NOT marked as in normal run state immediately upon initialisation. ASSERT_TRUE(!csvmd1.isInNormalRunState()); // Verify NOT marked as in error state immediately upon initialisation. ASSERT_TRUE(!csvmd1.isInErrorState()); // Target % open must start off in a sensible state; fully-closed is good. ASSERT_EQ(0, csvmd1.getTargetPC()); // Until calibration has been successfully run, this should be in non-proportional mode. ASSERT_TRUE(csvmd1.inNonProprtionalMode()); // Nothing passed in requires deferral of (re)calibration. ASSERT_FALSE(csvmd1.shouldDeferCalibration()); } class SVL final : public OTV0P2BASE::SupplyVoltageLow { public: SVL() { setAllLowFlags(false); } void setAllLowFlags(const bool f) { isLow = f; isVeryLow = f; } virtual uint16_t get() const override { return(0); } virtual uint16_t read() override { return(0); } }; // State of ambient lighting. static bool _isDark; static bool isDark() { return(_isDark); } // Test that logic for potentially deferring (re)calibration is correct. TEST(CurrentSenseValveMotorDirect,calibrationDeferral) { const uint8_t subcycleTicksRoundedDown_ms = 7; // For REV7: OTV0P2BASE::SUBCYCLE_TICK_MS_RD. const uint8_t gsct_max = 255; // For REV7: OTV0P2BASE::GSCT_MAX. const uint8_t minimumMotorRunupTicks = 4; // For REV7: OTRadValve::ValveMotorDirectV1HardwareDriverBase::minMotorRunupTicks. DummyHardwareDriver dhw; SVL svl; _isDark = false; OTRadValve::CurrentSenseValveMotorDirect csvmd1(&dhw, dummyGetSubCycleTime, OTRadValve::CurrentSenseValveMotorDirect::computeMinMotorDRTicks(subcycleTicksRoundedDown_ms), OTRadValve::CurrentSenseValveMotorDirect::computeSctAbsLimit(subcycleTicksRoundedDown_ms, gsct_max, minimumMotorRunupTicks), &svl, isDark); // Nothing yet requires deferral of (re)calibration. ASSERT_FALSE(csvmd1.shouldDeferCalibration()); svl.setAllLowFlags(true); // Low supply voltage requires deferral of (re)calibration. ASSERT_TRUE(csvmd1.shouldDeferCalibration()); svl.setAllLowFlags(false); ASSERT_FALSE(csvmd1.shouldDeferCalibration()); _isDark = true; // Low light level requires deferral of (re)calibration. ASSERT_TRUE(csvmd1.shouldDeferCalibration()); svl.setAllLowFlags(true); ASSERT_TRUE(csvmd1.shouldDeferCalibration()); _isDark = false; svl.setAllLowFlags(false); // Nothing requires deferral of (re)calibration. ASSERT_FALSE(csvmd1.shouldDeferCalibration()); } <|endoftext|>
<commit_before>// $Id: sample.cpp 793 2008-08-17 14:33:30Z glandrum $ // // Copyright (C) 2009 Greg Landrum // This file is part of the RDKit. // The contents are covered by the terms of the BSD license // which is included in the file license.txt, found at the root // of the RDKit source tree. // #include <GraphMol/RDKitBase.h> #include <GraphMol/SmilesParse/SmilesParse.h> #include <GraphMol/Depictor/RDDepictor.h> #include <Demos/RDKit/Draw/MolDrawing.h> #include <RDGeneral/RDLog.h> #include <vector> using namespace RDKit; void DrawDemo(){ RWMol *mol=SmilesToMol("Clc1c(C#N)cc(C(=O)NCc2sccc2)cc1"); //RWMol *mol=SmilesToMol("c1ncncn1"); RDKit::MolOps::Kekulize(*mol); // generate the 2D coordinates: RDDepict::compute2DCoords(*mol); std::vector<int> drawing=RDKit::Drawing::DrawMol(*mol); std::cout<<"var codes=["; std::copy(drawing.begin(),drawing.end(),std::ostream_iterator<int>(std::cout,",")); std::cout<<"];"<<std::endl; delete mol; } int main(int argc, char *argv[]) { RDLog::InitLogs(); DrawDemo(); } <commit_msg>initial pass at very crude svg translation<commit_after>// $Id: sample.cpp 793 2008-08-17 14:33:30Z glandrum $ // // Copyright (C) 2009 Greg Landrum // This file is part of the RDKit. // The contents are covered by the terms of the BSD license // which is included in the file license.txt, found at the root // of the RDKit source tree. // #include <GraphMol/RDKitBase.h> #include <GraphMol/SmilesParse/SmilesParse.h> #include <GraphMol/Depictor/RDDepictor.h> #include <Demos/RDKit/Draw/MolDrawing.h> #include <RDGeneral/RDLog.h> #include <vector> #include <sstream> using namespace RDKit; std::string getColor(int atNum){ static std::map<int,std::string> colors; if(colors.empty()){ colors[7]="#0000FF"; colors[8]="#FF0000"; colors[9]="#33CCCC"; colors[15]="#FF7F00"; colors[16]="#CCCC00"; colors[16]="#00CC00"; colors[35]="#7F4C19"; colors[0]="#7F7F7F"; } std::string res="#000000"; if(colors.find(atNum)!=colors.end()) res= colors[atNum]; return res; } void drawLine(std::vector<int>::const_iterator &pos,std::ostringstream &sstr){ pos+=4; sstr<<"<svg:path "; sstr<<"d='M "<<*pos<<","<<*(pos+1)<<" "<<*(pos+2)<<","<<*(pos+3)<<"' "; pos+=4; sstr<<"style='fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:3px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1'"; sstr<<" />\n"; } void drawAtom(std::vector<int>::const_iterator &pos,std::ostringstream &sstr){ int atNum=*pos++; int xp=*pos++; int yp=*pos++; int slen=*pos++; std::string label=""; for(unsigned int i=0;i<slen;++i){ label+=(char)*pos++; } sstr<<"<svg:text x='"<<xp<<"' y='"<<yp<<"'"; sstr<<" style='font-size:40px;font-style:normal;font-weight:normal;line-height:125%;letter-spacing:0px;word-spacing:0px;fill-opacity:1;stroke:none;font-family:Sans;text-anchor:middle;baseline-shift:sub"<<";fill:"<<getColor(atNum)<<"'"; sstr<<">"; sstr<<"<svg:tspan x='"<<xp<<"' y='"<<yp<<"'>"; sstr<<label<<"</svg:tspan>"; sstr<<"</svg:text>\n"; } std::string ToSVG(const std::vector<int> &drawing){ std::ostringstream sstr; sstr<<"<?xml version='1.0' encoding='iso-8859-1'?>\n"; int width=300,height=300; std::vector<int>::const_iterator pos=drawing.begin()+2; TEST_ASSERT(*pos==Drawing::BOUNDS); pos+=3; width = *pos++; height = *pos++; sstr << "<svg:svg version='1.1' baseProfile='full'\n \ xmlns:svg='http://www.w3.org/2000/svg'\n \ xmlns:xlink='http://www.w3.org/1999/xlink'\n \ xml:space='preserve'\n"; sstr<<"width='"<<width<<"px' height='"<<height<<"px' >\n"; sstr<<"<svg:g transform='translate("<<width*.05<<","<<height*.05<<") scale(.9,.9)'>"; while(pos!=drawing.end()){ int token=*pos++; switch(token){ case Drawing::LINE: drawLine(pos,sstr); break; case Drawing::ATOM: drawAtom(pos,sstr); break; default: std::cerr<<"unrecognized token: "<<token<<std::endl; } } sstr<<"</svg:g></svg:svg>"; return sstr.str(); } void DrawDemo(){ RWMol *mol=SmilesToMol("Clc1c(C#N)cc(C(=O)NCc2sccc2)cc1"); //RWMol *mol=SmilesToMol("c1ncncn1"); RDKit::MolOps::Kekulize(*mol); // generate the 2D coordinates: RDDepict::compute2DCoords(*mol); std::vector<int> drawing=RDKit::Drawing::DrawMol(*mol); std::cerr<<"var codes=["; std::copy(drawing.begin(),drawing.end(),std::ostream_iterator<int>(std::cerr,",")); std::cerr<<"];"<<std::endl; std::string svg=ToSVG(drawing); std::cout<<svg<<std::endl; delete mol; } int main(int argc, char *argv[]) { RDLog::InitLogs(); DrawDemo(); } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef __otbOGRVectorDataIO_txx #define __otbOGRVectorDataIO_txx #include "otbOGRVectorDataIO.h" #include "ogrsf_frmts.h" #include "itksys/SystemTools.hxx" #include "itkByteSwapper.h" #include "otbMacro.h" #include "otbSystem.h" #include "otbDataNode.h" #include "otbMetaDataKey.h" #include "itkTimeProbe.h" #include "otbVectorDataKeywordlist.h" #include "otbOGRIOHelper.h" namespace otb { OGRVectorDataIO ::OGRVectorDataIO() : m_DataSource(NULL) { // OGR factory registration OGRRegisterAll(); } OGRVectorDataIO::~OGRVectorDataIO() { if (m_DataSource != NULL) { OGRDataSource::DestroyDataSource(m_DataSource); } } bool OGRVectorDataIO::CanReadFile(const char* filename) const { OGRDataSource * poDS = OGRSFDriverRegistrar::Open(filename, FALSE); if (poDS == NULL) { return false; } // std::cout << poDS->GetDriver()->GetName() << std::endl; OGRDataSource::DestroyDataSource(poDS); return true; } // Used to print information about this object void OGRVectorDataIO::PrintSelf(std::ostream& os, itk::Indent indent) const { Superclass::PrintSelf(os, indent); } // Read vector data void OGRVectorDataIO ::Read(itk::DataObject* datag) { VectorDataPointerType data = dynamic_cast<VectorDataType*>(datag); // Destroy previous opened data source if (m_DataSource != NULL) { OGRDataSource::DestroyDataSource(m_DataSource); } m_DataSource = OGRSFDriverRegistrar::Open(this->m_FileName.c_str(), FALSE); if (m_DataSource == NULL) { itkExceptionMacro(<< "Failed to open data file " << this->m_FileName); } otbMsgDebugMacro(<< "Driver to read: OGR"); otbMsgDebugMacro(<< "Reading file: " << this->m_FileName); // Reading layers otbMsgDevMacro(<< "Number of layers: " << m_DataSource->GetLayerCount()); // Retrieving root node DataTreePointerType tree = data->GetDataTree(); DataNodePointerType root = tree->GetRoot()->Get(); OGRSpatialReference * oSRS = NULL; //We take the assumption that the spatial reference is common to all layers oSRS = m_DataSource->GetLayer(0)->GetSpatialRef(); if (oSRS != NULL) { char * projectionRefChar; oSRS->exportToWkt(&projectionRefChar); std::string projectionRef = projectionRefChar; CPLFree(projectionRefChar); itk::MetaDataDictionary& dict = data->GetMetaDataDictionary(); itk::EncapsulateMetaData<std::string>(dict, MetaDataKey::ProjectionRefKey, projectionRef); } else { otbMsgDevMacro(<< "Can't retrieve the OGRSpatialReference from the shapefile"); } std::string projectionRefWkt = data->GetProjectionRef(); bool projectionInformationAvailable = !projectionRefWkt.empty(); if (projectionInformationAvailable) { otbMsgDevMacro(<< "Projection information : " << projectionRefWkt); } else { otbMsgDevMacro(<< "Projection information unavailable: assuming WGS84"); } // For each layer for (int layerIndex = 0; layerIndex < m_DataSource->GetLayerCount(); ++layerIndex) { /** retrieving layer and property */ OGRLayer * layer = m_DataSource->GetLayer(layerIndex); otbMsgDevMacro(<< "Number of features: " << layer->GetFeatureCount()); OGRFeatureDefn * dfn = layer->GetLayerDefn(); /** Create the document node */ DataNodePointerType document = DataNodeType::New(); document->SetNodeType(DOCUMENT); document->SetNodeId(dfn->GetName()); /** Retrieving the fields types */ // OGRFieldDefn * field; // for (int fieldIndex = 0; fieldIndex<dfn->GetFieldCount(); ++fieldIndex) // { // field = dfn->GetFieldDefn(fieldIndex); // document->SetField(field->GetNameRef(), OGRFieldDefn::GetFieldTypeName(field->GetType())); // // std::cout<<"Document "<<document->GetNodeId()<<": Adding field "<<field->GetNameRef()<<" "<<OGRFieldDefn::GetFieldTypeName(field->GetType())<<std::endl; // } /** Adding the layer to the data tree */ tree->Add(document, root); /// This is not good but we do not have the choice if we want to /// get a hook on the internal structure InternalTreeNodeType * documentPtr = const_cast<InternalTreeNodeType *>(tree->GetNode(document)); /** IO class helper to convert ogr layer*/ OGRIOHelper::Pointer OGRConversion = OGRIOHelper::New(); OGRConversion->ConvertOGRLayerToDataTreeNode(layer, documentPtr); } // end For each layer OGRDataSource::DestroyDataSource(m_DataSource); m_DataSource = NULL; } bool OGRVectorDataIO::CanWriteFile(const char* filename) const { std::string lFileName(filename); if (System::IsADirName(lFileName) == true) { return false; } return (this->GetOGRDriverName(filename) != "NOT-FOUND"); } void OGRVectorDataIO::Write(const itk::DataObject* datag, char ** papszOptions) { itk::TimeProbe chrono; chrono.Start(); VectorDataConstPointerType data = dynamic_cast<const VectorDataType*>(datag); //Find first the OGR driver OGRSFDriver * ogrDriver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(this->GetOGRDriverName(this->m_FileName).data()); if (ogrDriver == NULL) { itkExceptionMacro(<< "No OGR driver found to write file " << this->m_FileName); } // free an existing previous data source, if any if (m_DataSource != NULL) { OGRDataSource::DestroyDataSource(m_DataSource); } // Erase the dataSource if already exist //TODO investigate the possibility of giving the option OVERWRITE=YES to the CreateDataSource method OGRDataSource * poDS = OGRSFDriverRegistrar::Open(this->m_FileName.c_str(), TRUE); if (poDS != NULL) { //Erase the data if possible if (poDS->GetDriver()->TestCapability(ODrCDeleteDataSource)) { //Delete datasource poDS->GetDriver()->DeleteDataSource(this->m_FileName.c_str()); } } OGRDataSource::DestroyDataSource(poDS); // m_DataSource = OGRSFDriverRegistrar::Open(this->m_FileName.c_str(), TRUE); m_DataSource = ogrDriver->CreateDataSource(this->m_FileName.c_str(), papszOptions); // check the created data source if (m_DataSource == NULL) { itkExceptionMacro( << "Failed to create OGR data source for file " << this->m_FileName << ". Since OGR can not overwrite existing file, be sure that this file does not already exist"); } // Retrieve data required for georeferencing std::string projectionRefWkt = data->GetProjectionRef(); bool projectionInformationAvailable = !projectionRefWkt.empty(); if (projectionInformationAvailable) { otbMsgDevMacro(<< "Projection information : " << projectionRefWkt); } else { otbMsgDevMacro(<< "Projection information unavailable"); } //TODO georeference here from OGRSpatialReference http://www.gdal.org/ogr/classOGRDataSource.html OGRSpatialReference * oSRS = NULL; if (projectionInformationAvailable) { oSRS = static_cast<OGRSpatialReference *>(OSRNewSpatialReference(projectionRefWkt.c_str())); } // Retrieving root node DataTreeConstPointerType tree = data->GetDataTree(); if (tree->GetRoot() == NULL) { itkExceptionMacro(<< "Data tree is empty: Root == NULL"); } DataNodePointerType root = tree->GetRoot()->Get(); unsigned int layerKept; OGRLayer * ogrCurrentLayer = NULL; // OGRFeatureVectorType ogrFeatures; OGRGeometryCollection * ogrCollection = NULL; // OGRGeometry * ogrCurrentGeometry = NULL; // Get the input tree root InternalTreeNodeType * inputRoot = const_cast<InternalTreeNodeType *>(tree->GetRoot()); //Refactoring SHPIO Manuel OGRIOHelper::Pointer IOConversion = OGRIOHelper::New(); layerKept = IOConversion->ProcessNodeWrite(inputRoot, m_DataSource, ogrCollection, ogrCurrentLayer, oSRS); otbMsgDevMacro( << "layerKept " << layerKept ); OGRDataSource::DestroyDataSource(m_DataSource); m_DataSource = NULL; if (oSRS != NULL) { OSRRelease(oSRS); } chrono.Stop(); otbMsgDevMacro( << "OGRVectorDataIO: file saved in " << chrono.GetMeanTime() << " seconds. (" << layerKept << " elements)" ); otbMsgDevMacro(<< " OGRVectorDataIO::Write() "); } std::string OGRVectorDataIO::GetOGRDriverName(std::string name) const { std::string extension; std::string driverOGR; std::string upperName; upperName = name; std::transform(name.begin(), name.end(), upperName.begin(), (int (*)(int))toupper); //Test of PostGIS connection string if (upperName.substr(0, 3) == "PG:") { driverOGR = "PostgreSQL"; } else { extension = System::GetExtension(upperName); if (extension == "SHP") driverOGR = "ESRI Shapefile"; else if ((extension == "TAB")) driverOGR = "MapInfo File"; else if (extension == "GML") driverOGR = "GML"; else if (extension == "GPX") driverOGR = "GPX"; else if (extension == "SQLITE") driverOGR = "SQLite"; // else if (extension=="KML") // driverOGR="KML"; else driverOGR = "NOT-FOUND"; } //std::cout << name << " " << driverOGR <<" "<<upperName<< " "<< upperName.substr(0, 3) << std::endl; return driverOGR; } } // end namespace otb #endif <commit_msg>ENH: enable kml writing using OGR<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef __otbOGRVectorDataIO_txx #define __otbOGRVectorDataIO_txx #include "otbOGRVectorDataIO.h" #include "ogrsf_frmts.h" #include "itksys/SystemTools.hxx" #include "itkByteSwapper.h" #include "otbMacro.h" #include "otbSystem.h" #include "otbDataNode.h" #include "otbMetaDataKey.h" #include "itkTimeProbe.h" #include "otbVectorDataKeywordlist.h" #include "otbOGRIOHelper.h" namespace otb { OGRVectorDataIO ::OGRVectorDataIO() : m_DataSource(NULL) { // OGR factory registration OGRRegisterAll(); } OGRVectorDataIO::~OGRVectorDataIO() { if (m_DataSource != NULL) { OGRDataSource::DestroyDataSource(m_DataSource); } } bool OGRVectorDataIO::CanReadFile(const char* filename) const { OGRDataSource * poDS = OGRSFDriverRegistrar::Open(filename, FALSE); if (poDS == NULL) { return false; } // std::cout << poDS->GetDriver()->GetName() << std::endl; OGRDataSource::DestroyDataSource(poDS); return true; } // Used to print information about this object void OGRVectorDataIO::PrintSelf(std::ostream& os, itk::Indent indent) const { Superclass::PrintSelf(os, indent); } // Read vector data void OGRVectorDataIO ::Read(itk::DataObject* datag) { VectorDataPointerType data = dynamic_cast<VectorDataType*>(datag); // Destroy previous opened data source if (m_DataSource != NULL) { OGRDataSource::DestroyDataSource(m_DataSource); } m_DataSource = OGRSFDriverRegistrar::Open(this->m_FileName.c_str(), FALSE); if (m_DataSource == NULL) { itkExceptionMacro(<< "Failed to open data file " << this->m_FileName); } otbMsgDebugMacro(<< "Driver to read: OGR"); otbMsgDebugMacro(<< "Reading file: " << this->m_FileName); // Reading layers otbMsgDevMacro(<< "Number of layers: " << m_DataSource->GetLayerCount()); // Retrieving root node DataTreePointerType tree = data->GetDataTree(); DataNodePointerType root = tree->GetRoot()->Get(); OGRSpatialReference * oSRS = NULL; //We take the assumption that the spatial reference is common to all layers oSRS = m_DataSource->GetLayer(0)->GetSpatialRef(); if (oSRS != NULL) { char * projectionRefChar; oSRS->exportToWkt(&projectionRefChar); std::string projectionRef = projectionRefChar; CPLFree(projectionRefChar); itk::MetaDataDictionary& dict = data->GetMetaDataDictionary(); itk::EncapsulateMetaData<std::string>(dict, MetaDataKey::ProjectionRefKey, projectionRef); } else { otbMsgDevMacro(<< "Can't retrieve the OGRSpatialReference from the shapefile"); } std::string projectionRefWkt = data->GetProjectionRef(); bool projectionInformationAvailable = !projectionRefWkt.empty(); if (projectionInformationAvailable) { otbMsgDevMacro(<< "Projection information : " << projectionRefWkt); } else { otbMsgDevMacro(<< "Projection information unavailable: assuming WGS84"); } // For each layer for (int layerIndex = 0; layerIndex < m_DataSource->GetLayerCount(); ++layerIndex) { /** retrieving layer and property */ OGRLayer * layer = m_DataSource->GetLayer(layerIndex); otbMsgDevMacro(<< "Number of features: " << layer->GetFeatureCount()); OGRFeatureDefn * dfn = layer->GetLayerDefn(); /** Create the document node */ DataNodePointerType document = DataNodeType::New(); document->SetNodeType(DOCUMENT); document->SetNodeId(dfn->GetName()); /** Retrieving the fields types */ // OGRFieldDefn * field; // for (int fieldIndex = 0; fieldIndex<dfn->GetFieldCount(); ++fieldIndex) // { // field = dfn->GetFieldDefn(fieldIndex); // document->SetField(field->GetNameRef(), OGRFieldDefn::GetFieldTypeName(field->GetType())); // // std::cout<<"Document "<<document->GetNodeId()<<": Adding field "<<field->GetNameRef()<<" "<<OGRFieldDefn::GetFieldTypeName(field->GetType())<<std::endl; // } /** Adding the layer to the data tree */ tree->Add(document, root); /// This is not good but we do not have the choice if we want to /// get a hook on the internal structure InternalTreeNodeType * documentPtr = const_cast<InternalTreeNodeType *>(tree->GetNode(document)); /** IO class helper to convert ogr layer*/ OGRIOHelper::Pointer OGRConversion = OGRIOHelper::New(); OGRConversion->ConvertOGRLayerToDataTreeNode(layer, documentPtr); } // end For each layer OGRDataSource::DestroyDataSource(m_DataSource); m_DataSource = NULL; } bool OGRVectorDataIO::CanWriteFile(const char* filename) const { std::string lFileName(filename); if (System::IsADirName(lFileName) == true) { return false; } return (this->GetOGRDriverName(filename) != "NOT-FOUND"); } void OGRVectorDataIO::Write(const itk::DataObject* datag, char ** papszOptions) { itk::TimeProbe chrono; chrono.Start(); VectorDataConstPointerType data = dynamic_cast<const VectorDataType*>(datag); //Find first the OGR driver OGRSFDriver * ogrDriver = OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(this->GetOGRDriverName(this->m_FileName).data()); if (ogrDriver == NULL) { itkExceptionMacro(<< "No OGR driver found to write file " << this->m_FileName); } // free an existing previous data source, if any if (m_DataSource != NULL) { OGRDataSource::DestroyDataSource(m_DataSource); } // Erase the dataSource if already exist //TODO investigate the possibility of giving the option OVERWRITE=YES to the CreateDataSource method OGRDataSource * poDS = OGRSFDriverRegistrar::Open(this->m_FileName.c_str(), TRUE); if (poDS != NULL) { //Erase the data if possible if (poDS->GetDriver()->TestCapability(ODrCDeleteDataSource)) { //Delete datasource poDS->GetDriver()->DeleteDataSource(this->m_FileName.c_str()); } } OGRDataSource::DestroyDataSource(poDS); // m_DataSource = OGRSFDriverRegistrar::Open(this->m_FileName.c_str(), TRUE); m_DataSource = ogrDriver->CreateDataSource(this->m_FileName.c_str(), papszOptions); // check the created data source if (m_DataSource == NULL) { itkExceptionMacro( << "Failed to create OGR data source for file " << this->m_FileName << ". Since OGR can not overwrite existing file, be sure that this file does not already exist"); } // Retrieve data required for georeferencing std::string projectionRefWkt = data->GetProjectionRef(); bool projectionInformationAvailable = !projectionRefWkt.empty(); if (projectionInformationAvailable) { otbMsgDevMacro(<< "Projection information : " << projectionRefWkt); } else { otbMsgDevMacro(<< "Projection information unavailable"); } //TODO georeference here from OGRSpatialReference http://www.gdal.org/ogr/classOGRDataSource.html OGRSpatialReference * oSRS = NULL; if (projectionInformationAvailable) { oSRS = static_cast<OGRSpatialReference *>(OSRNewSpatialReference(projectionRefWkt.c_str())); } // Retrieving root node DataTreeConstPointerType tree = data->GetDataTree(); if (tree->GetRoot() == NULL) { itkExceptionMacro(<< "Data tree is empty: Root == NULL"); } DataNodePointerType root = tree->GetRoot()->Get(); unsigned int layerKept; OGRLayer * ogrCurrentLayer = NULL; // OGRFeatureVectorType ogrFeatures; OGRGeometryCollection * ogrCollection = NULL; // OGRGeometry * ogrCurrentGeometry = NULL; // Get the input tree root InternalTreeNodeType * inputRoot = const_cast<InternalTreeNodeType *>(tree->GetRoot()); //Refactoring SHPIO Manuel OGRIOHelper::Pointer IOConversion = OGRIOHelper::New(); layerKept = IOConversion->ProcessNodeWrite(inputRoot, m_DataSource, ogrCollection, ogrCurrentLayer, oSRS); otbMsgDevMacro( << "layerKept " << layerKept ); OGRDataSource::DestroyDataSource(m_DataSource); m_DataSource = NULL; if (oSRS != NULL) { OSRRelease(oSRS); } chrono.Stop(); otbMsgDevMacro( << "OGRVectorDataIO: file saved in " << chrono.GetMeanTime() << " seconds. (" << layerKept << " elements)" ); otbMsgDevMacro(<< " OGRVectorDataIO::Write() "); } std::string OGRVectorDataIO::GetOGRDriverName(std::string name) const { std::string extension; std::string driverOGR; std::string upperName; upperName = name; std::transform(name.begin(), name.end(), upperName.begin(), (int (*)(int))toupper); //Test of PostGIS connection string if (upperName.substr(0, 3) == "PG:") { driverOGR = "PostgreSQL"; } else { extension = System::GetExtension(upperName); if (extension == "SHP") driverOGR = "ESRI Shapefile"; else if ((extension == "TAB")) driverOGR = "MapInfo File"; else if (extension == "GML") driverOGR = "GML"; else if (extension == "GPX") driverOGR = "GPX"; else if (extension == "SQLITE") driverOGR = "SQLite"; else if (extension=="KML") driverOGR="KML"; else driverOGR = "NOT-FOUND"; } //std::cout << name << " " << driverOGR <<" "<<upperName<< " "<< upperName.substr(0, 3) << std::endl; return driverOGR; } } // end namespace otb #endif <|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 DebuggingStateWrapper.cpp * @author Yann [email protected] * @date 2014 * Used to translate c++ type (u256, bytes, ...) into friendly value (to be used by QML). */ #include <tuple> #include <QDebug> #include <QPointer> #include <QQmlEngine> #include <QVariantList> #include <libevmcore/Instruction.h> #include <libethcore/CommonJS.h> #include <libdevcrypto/Common.h> #include <libevmcore/Instruction.h> #include <libdevcore/Common.h> #include "DebuggingStateWrapper.h" #include "QBigInt.h" using namespace dev; using namespace dev::eth; using namespace dev::mix; namespace { static QVariantList memDumpToList(bytes const& _bytes, unsigned _width) { QVariantList dumpList; for (unsigned i = 0; i < _bytes.size(); i += _width) { std::stringstream ret; for (unsigned j = i; j < i + _width; ++j) if (j < _bytes.size()) if (_bytes[j] >= 32 && _bytes[j] < 127) ret << (char)_bytes[j]; else ret << '?'; else ret << ' '; QString strPart = QString::fromStdString(ret.str()); ret.clear(); ret.str(std::string()); for (unsigned j = i; j < i + _width && j < _bytes.size(); ++j) ret << std::setfill('0') << std::setw(2) << std::hex << (unsigned)_bytes[j] << " "; QString hexPart = QString::fromStdString(ret.str()); QStringList line = { strPart, hexPart }; dumpList.push_back(line); } return dumpList; } } QCode* QMachineState::getHumanReadableCode(QObject* _owner, const Address& _address, const bytes& _code, QHash<int, int>& o_codeMap) { QVariantList codeStr; for (unsigned i = 0; i <= _code.size(); ++i) { byte b = i < _code.size() ? _code[i] : 0; try { QString s = QString::fromStdString(instructionInfo((Instruction)b).name); std::ostringstream out; out << std::hex << std::setw(4) << std::setfill('0') << i; int offset = i; if (b >= (byte)Instruction::PUSH1 && b <= (byte)Instruction::PUSH32) { unsigned bc = getPushNumber((Instruction)b); s = "PUSH 0x" + QString::fromStdString(toHex(bytesConstRef(&_code[i + 1], bc))); i += bc; } o_codeMap[offset] = codeStr.size(); codeStr.append(QVariant::fromValue(new QInstruction(_owner, QString::fromStdString(out.str()) + " " + s))); } catch (...) { qDebug() << QString("Unhandled exception!") << endl << QString::fromStdString(boost::current_exception_diagnostic_information()); break; // probably hit data segment } } return new QCode(_owner, QString::fromStdString(toString(_address)), std::move(codeStr)); } QBigInt* QMachineState::gasCost() { return new QBigInt(m_state.gasCost); } QBigInt* QMachineState::gas() { return new QBigInt(m_state.gas); } QBigInt* QMachineState::newMemSize() { return new QBigInt(m_state.newMemSize); } QStringList QMachineState::debugStack() { QStringList stack; for (std::vector<u256>::reverse_iterator i = m_state.stack.rbegin(); i != m_state.stack.rend(); ++i) stack.append(QString::fromStdString(prettyU256(*i))); return stack; } QStringList QMachineState::debugStorage() { QStringList storage; for (auto const& i: m_state.storage) { std::stringstream s; s << "@" << prettyU256(i.first) << "\t" << prettyU256(i.second); storage.append(QString::fromStdString(s.str())); } return storage; } QVariantList QMachineState::debugMemory() { return memDumpToList(m_state.memory, 16); } QCallData* QMachineState::getDebugCallData(QObject* _owner, bytes const& _data) { return new QCallData(_owner, memDumpToList(_data, 16)); } QVariantList QMachineState::levels() { QVariantList levelList; for (unsigned l: m_state.levels) levelList.push_back(l); return levelList; } QString QMachineState::instruction() { return QString::fromStdString(dev::eth::instructionInfo(m_state.inst).name); } QString QMachineState::endOfDebug() { if (m_state.gasCost > m_state.gas) return QObject::tr("OUT-OF-GAS"); else if (m_state.inst == Instruction::RETURN && m_state.stack.size() >= 2) { unsigned from = (unsigned)m_state.stack.back(); unsigned size = (unsigned)m_state.stack[m_state.stack.size() - 2]; unsigned o = 0; bytes out(size, 0); for (; o < size && from + o < m_state.memory.size(); ++o) out[o] = m_state.memory[from + o]; return QObject::tr("RETURN") + " " + QString::fromStdString(dev::memDump(out, 16, false)); } else if (m_state.inst == Instruction::STOP) return QObject::tr("STOP"); else if (m_state.inst == Instruction::SUICIDE && m_state.stack.size() >= 1) return QObject::tr("SUICIDE") + " 0x" + QString::fromStdString(toString(right160(m_state.stack.back()))); else return QObject::tr("EXCEPTION"); } <commit_msg>Add memory address in memory dump.<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 DebuggingStateWrapper.cpp * @author Yann [email protected] * @date 2014 * Used to translate c++ type (u256, bytes, ...) into friendly value (to be used by QML). */ #include <tuple> #include <QDebug> #include <QPointer> #include <QQmlEngine> #include <QVariantList> #include <libevmcore/Instruction.h> #include <libethcore/CommonJS.h> #include <libdevcrypto/Common.h> #include <libevmcore/Instruction.h> #include <libdevcore/Common.h> #include "DebuggingStateWrapper.h" #include "QBigInt.h" using namespace dev; using namespace dev::eth; using namespace dev::mix; namespace { static QVariantList memDumpToList(bytes const& _bytes, unsigned _width, bool _includeAddress = false) { QVariantList dumpList; for (unsigned i = 0; i < _bytes.size(); i += _width) { std::stringstream ret; if (_includeAddress) { ret << std::setfill('0') << std::setw(6) << std::hex << i << " "; ret << " "; } for (unsigned j = i; j < i + _width; ++j) if (j < _bytes.size()) if (_bytes[j] >= 32 && _bytes[j] < 127) ret << (char)_bytes[j]; else ret << '?'; else ret << ' '; QString strPart = QString::fromStdString(ret.str()); ret.clear(); ret.str(std::string()); for (unsigned j = i; j < i + _width && j < _bytes.size(); ++j) ret << std::setfill('0') << std::setw(2) << std::hex << (unsigned)_bytes[j] << " "; QString hexPart = QString::fromStdString(ret.str()); QStringList line = { strPart, hexPart }; dumpList.push_back(line); } return dumpList; } } QCode* QMachineState::getHumanReadableCode(QObject* _owner, const Address& _address, const bytes& _code, QHash<int, int>& o_codeMap) { QVariantList codeStr; for (unsigned i = 0; i <= _code.size(); ++i) { byte b = i < _code.size() ? _code[i] : 0; try { QString s = QString::fromStdString(instructionInfo((Instruction)b).name); std::ostringstream out; out << std::hex << std::setw(4) << std::setfill('0') << i; int offset = i; if (b >= (byte)Instruction::PUSH1 && b <= (byte)Instruction::PUSH32) { unsigned bc = getPushNumber((Instruction)b); s = "PUSH 0x" + QString::fromStdString(toHex(bytesConstRef(&_code[i + 1], bc))); i += bc; } o_codeMap[offset] = codeStr.size(); codeStr.append(QVariant::fromValue(new QInstruction(_owner, QString::fromStdString(out.str()) + " " + s))); } catch (...) { qDebug() << QString("Unhandled exception!") << endl << QString::fromStdString(boost::current_exception_diagnostic_information()); break; // probably hit data segment } } return new QCode(_owner, QString::fromStdString(toString(_address)), std::move(codeStr)); } QBigInt* QMachineState::gasCost() { return new QBigInt(m_state.gasCost); } QBigInt* QMachineState::gas() { return new QBigInt(m_state.gas); } QBigInt* QMachineState::newMemSize() { return new QBigInt(m_state.newMemSize); } QStringList QMachineState::debugStack() { QStringList stack; for (std::vector<u256>::reverse_iterator i = m_state.stack.rbegin(); i != m_state.stack.rend(); ++i) stack.append(QString::fromStdString(prettyU256(*i))); return stack; } QStringList QMachineState::debugStorage() { QStringList storage; for (auto const& i: m_state.storage) { std::stringstream s; s << "@" << prettyU256(i.first) << "\t" << prettyU256(i.second); storage.append(QString::fromStdString(s.str())); } return storage; } QVariantList QMachineState::debugMemory() { return memDumpToList(m_state.memory, 16, true); } QCallData* QMachineState::getDebugCallData(QObject* _owner, bytes const& _data) { return new QCallData(_owner, memDumpToList(_data, 16)); } QVariantList QMachineState::levels() { QVariantList levelList; for (unsigned l: m_state.levels) levelList.push_back(l); return levelList; } QString QMachineState::instruction() { return QString::fromStdString(dev::eth::instructionInfo(m_state.inst).name); } QString QMachineState::endOfDebug() { if (m_state.gasCost > m_state.gas) return QObject::tr("OUT-OF-GAS"); else if (m_state.inst == Instruction::RETURN && m_state.stack.size() >= 2) { unsigned from = (unsigned)m_state.stack.back(); unsigned size = (unsigned)m_state.stack[m_state.stack.size() - 2]; unsigned o = 0; bytes out(size, 0); for (; o < size && from + o < m_state.memory.size(); ++o) out[o] = m_state.memory[from + o]; return QObject::tr("RETURN") + " " + QString::fromStdString(dev::memDump(out, 16, false)); } else if (m_state.inst == Instruction::STOP) return QObject::tr("STOP"); else if (m_state.inst == Instruction::SUICIDE && m_state.stack.size() >= 1) return QObject::tr("SUICIDE") + " 0x" + QString::fromStdString(toString(right160(m_state.stack.back()))); else return QObject::tr("EXCEPTION"); } <|endoftext|>
<commit_before>#include "worklist3.h" #include <iostream> #include <stdlib.h> //FILE *fp; void node::set_data(int element) { data = element; } void node::get_data() { cout << data << " -> "; } linklist::linklist() { //exit = 1; count = 0; length = 0; choice = 0; search = 0; num = 0; count = 0; first = new node; first->next = NULL; } linklist::~linklist() { while (first != NULL && first->next != NULL) { //node *q; will = new node; //delete q->info.team; will = first; first = first->next; delete will; } cout << "ѵ" << endl; cout << "Աɾ" << endl; } bool linklist::creat(FILE *fp) { if (fp == NULL) { cout << "open error!" << endl; return false; } else { cout << "open success!" << endl; } int num = 1; char s[10]; int element; while ((fgets(s, 10, fp)) != NULL) { sscanf(s, "%d", &element); x = new node; x->set_data(element); now = first; count = 0; while (now != NULL && count < num - 1) { now = now->next; count++; } x->next = now->next; now->next = x; num++; } fclose(fp); return true; } void linklist::inversion() { prev = NULL; now = first->next; will = now->next; while (now != NULL) { will = now->next; now->next = prev; prev = now; now = will; } first->next = prev; } void linklist::printlist() { now = first->next; while (now != NULL) { now->get_data(); now = now->next; } }<commit_msg>debug the will = new node; 防止申请新节点后指针指向其他内存单元造成内存泄漏。<commit_after>#include "worklist3.h" #include <iostream> #include <stdlib.h> //FILE *fp; void node::set_data(int element) { data = element; } void node::get_data() { cout << data << " -> "; } linklist::linklist() { //exit = 1; count = 0; length = 0; choice = 0; search = 0; num = 0; count = 0; first = new node; first->next = NULL; } linklist::~linklist() { while (first != NULL && first->next != NULL) { //node *q; //will = new node; //delete q->info.team; will = first; first = first->next; delete will; } cout << "ѵ" << endl; cout << "Աɾ" << endl; } bool linklist::creat(FILE *fp) { if (fp == NULL) { cout << "open error!" << endl; return false; } else { cout << "open success!" << endl; } int num = 1; char s[10]; int element; while ((fgets(s, 10, fp)) != NULL) { sscanf(s, "%d", &element); x = new node; x->set_data(element); now = first; count = 0; while (now != NULL && count < num - 1) { now = now->next; count++; } x->next = now->next; now->next = x; num++; } fclose(fp); return true; } void linklist::inversion() { prev = NULL; now = first->next; will = now->next; while (now != NULL) { will = now->next; now->next = prev; prev = now; now = will; } first->next = prev; } void linklist::printlist() { now = first->next; while (now != NULL) { now->get_data(); now = now->next; } }<|endoftext|>
<commit_before>#include "xchainer/array_repr.h" #include <cassert> #include <cmath> #include <iomanip> #include <iostream> #include <memory> #include <sstream> #include <vector> #ifdef XCHAINER_ENABLE_CUDA #include <cuda_runtime.h> #endif // XCHAINER_ENABLE_CUDA #include "xchainer/array.h" #include "xchainer/array_node.h" #include "xchainer/backend.h" #ifdef XCHAINER_ENABLE_CUDA #include "xchainer/cuda/cuda_runtime.h" #endif // XCHAINER_ENABLE_CUDA #include "xchainer/dtype.h" #include "xchainer/shape.h" namespace xchainer { namespace { int GetNDigits(int64_t value) { int digits = 0; while (value != 0) { value /= 10; ++digits; } return digits; } void PrintNTimes(std::ostream& os, char c, int n) { while (n-- > 0) { os << c; } } class IntFormatter { public: void Scan(int64_t value) { int digits = 0; if (value < 0) { ++digits; value = -value; } digits += GetNDigits(value); if (max_digits_ < digits) { max_digits_ = digits; } } void Print(std::ostream& os, int64_t value) const { os << std::setw(max_digits_) << std::right << value; } private: int max_digits_ = 1; }; class FloatFormatter { public: void Scan(double value) { int b_digits = 0; if (value < 0) { has_minus_ = true; ++b_digits; value = -value; } if (std::isinf(value) || std::isnan(value)) { b_digits += 3; if (digits_before_point_ < b_digits) { digits_before_point_ = b_digits; } return; } if (value >= 100'000'000) { int e_digits = GetNDigits(static_cast<int64_t>(std::log10(value))); if (digits_after_e_ < e_digits) { digits_after_e_ = e_digits; } } if (digits_after_e_ > 0) { return; } const auto int_frac_parts = IntFracPartsToPrint(value); b_digits += GetNDigits(int_frac_parts.first); if (digits_before_point_ < b_digits) { digits_before_point_ = b_digits; } const int a_digits = GetNDigits(int_frac_parts.second) - 1; if (digits_after_point_ < a_digits) { digits_after_point_ = a_digits; } } void Print(std::ostream& os, double value) { if (digits_after_e_ > 0) { int width = 12 + (has_minus_ ? 1 : 0) + digits_after_e_; if (has_minus_ && !std::signbit(value)) { os << ' '; --width; } os << std::scientific << std::left << std::setw(width) << std::setprecision(8) << value; } else { if (std::isinf(value) || std::isnan(value)) { os << std::right << std::setw(digits_before_point_ + digits_after_point_ + 1) << value; return; } const auto int_frac_parts = IntFracPartsToPrint(value); const int a_digits = GetNDigits(int_frac_parts.second) - 1; os << std::fixed << std::right << std::setw(digits_before_point_ + a_digits + 1) << std::setprecision(a_digits) << std::showpoint << value; PrintNTimes(os, ' ', digits_after_point_ - a_digits); } } private: // Returns the integral part and fractional part as integers. // Note that the fractional part is prefixed by 1 so that the information of preceeding zeros is not missed. static std::pair<int64_t, int64_t> IntFracPartsToPrint(double value) { double int_part; const double frac_part = std::modf(value, &int_part); auto shifted_frac_part = static_cast<int64_t>((std::abs(frac_part) + 1) * 100'000'000); while ((shifted_frac_part % 10) == 0) { shifted_frac_part /= 10; } return {static_cast<int64_t>(int_part), shifted_frac_part}; } int digits_before_point_ = 1; int digits_after_point_ = 0; int digits_after_e_ = 0; bool has_minus_ = false; }; class BoolFormatter { public: void Scan(bool value) { (void)value; /* unused */ } void Print(std::ostream& os, bool value) const { os << (value ? " True" : "False"); // NOLINTER } }; template <typename T> using Formatter = std::conditional_t<std::is_same<T, bool>::value, BoolFormatter, std::conditional_t<std::is_floating_point<T>::value, FloatFormatter, IntFormatter>>; struct ArrayReprImpl { template <typename T, typename Visitor> void VisitElements(const Array& array, Visitor&& visitor) const { // TODO(niboshi): Contiguousness is assumed. // TODO(niboshi): Replace with Indxer class. auto shape = array.shape(); std::vector<int64_t> indexer; std::copy(shape.cbegin(), shape.cend(), std::back_inserter(indexer)); std::shared_ptr<const T> data = std::static_pointer_cast<const T>(array.data()); // TODO(hvy): Only synchronize devices when it is really needed #ifdef XCHAINER_ENABLE_CUDA cuda::CheckError(cudaDeviceSynchronize()); #endif // XCHAINER_ENABLE_CUDA for (int64_t i = 0; i < array.GetTotalSize(); ++i) { // Increment indexer for (int j = shape.ndim() - 1; j >= 0; --j) { indexer[j]++; if (indexer[j] >= shape[j]) { indexer[j] = 0; } else { break; } } visitor(data.get()[i], &indexer[0]); } } template <typename T> void operator()(const Array& array, std::ostream& os) const { Formatter<T> formatter; // Let formatter scan all elements to print. VisitElements<T>(array, [&formatter](T value, const int64_t* index) { (void)index; // unused formatter.Scan(value); }); // Print values using the formatter. const int8_t ndim = array.ndim(); int cur_line_size = 0; VisitElements<T>(array, [ndim, &cur_line_size, &formatter, &os](T value, const int64_t* index) { int8_t trailing_zeros = 0; if (ndim > 0) { for (auto it = index + ndim; --it >= index;) { if (*it == 0) { ++trailing_zeros; } else { break; } } } if (trailing_zeros == ndim) { // This is the first iteration, so print the header os << "array("; PrintNTimes(os, '[', ndim); } else if (trailing_zeros > 0) { PrintNTimes(os, ']', trailing_zeros); os << ','; PrintNTimes(os, '\n', trailing_zeros); PrintNTimes(os, ' ', 6 + ndim - trailing_zeros); PrintNTimes(os, '[', trailing_zeros); cur_line_size = 0; } else { if (cur_line_size == 10) { os << ",\n"; PrintNTimes(os, ' ', 6 + ndim); cur_line_size = 0; } else { os << ", "; } } formatter.Print(os, value); ++cur_line_size; }); if (array.GetTotalSize() == 0) { // In case of an empty Array, print the header here os << "array([]"; } else { PrintNTimes(os, ']', ndim); } // Print the footer os << ", shape=" << array.shape(); os << ", dtype=" << array.dtype(); os << ", device='" << array.device().name() << "'"; const std::vector<std::shared_ptr<ArrayNode>>& nodes = array.nodes(); if (!nodes.empty()) { os << ", graph_ids=["; for (size_t i = 0; i < nodes.size(); ++i) { if (i > 0) { os << ", "; } os << '\'' << nodes[i]->graph_id() << '\''; } os << ']'; } os << ')'; } }; } // namespace std::ostream& operator<<(std::ostream& os, const Array& array) { // TODO(hvy): We need to determine the output specification of this function, whether or not to align with Python repr specification, // and also whether this functionality should be defined in C++ layer or Python layer. VisitDtype(array.dtype(), [&](auto pt) { ArrayReprImpl{}.operator()<typename decltype(pt)::type>(array, os); }); return os; } std::string ArrayRepr(const Array& array) { std::ostringstream os; os << array; return os.str(); } } // namespace xchainer <commit_msg>Remove CUDA code from array_repr.cc<commit_after>#include "xchainer/array_repr.h" #include <cassert> #include <cmath> #include <iomanip> #include <iostream> #include <memory> #include <sstream> #include <vector> #include "xchainer/array.h" #include "xchainer/array_node.h" #include "xchainer/backend.h" #include "xchainer/dtype.h" #include "xchainer/shape.h" namespace xchainer { namespace { int GetNDigits(int64_t value) { int digits = 0; while (value != 0) { value /= 10; ++digits; } return digits; } void PrintNTimes(std::ostream& os, char c, int n) { while (n-- > 0) { os << c; } } class IntFormatter { public: void Scan(int64_t value) { int digits = 0; if (value < 0) { ++digits; value = -value; } digits += GetNDigits(value); if (max_digits_ < digits) { max_digits_ = digits; } } void Print(std::ostream& os, int64_t value) const { os << std::setw(max_digits_) << std::right << value; } private: int max_digits_ = 1; }; class FloatFormatter { public: void Scan(double value) { int b_digits = 0; if (value < 0) { has_minus_ = true; ++b_digits; value = -value; } if (std::isinf(value) || std::isnan(value)) { b_digits += 3; if (digits_before_point_ < b_digits) { digits_before_point_ = b_digits; } return; } if (value >= 100'000'000) { int e_digits = GetNDigits(static_cast<int64_t>(std::log10(value))); if (digits_after_e_ < e_digits) { digits_after_e_ = e_digits; } } if (digits_after_e_ > 0) { return; } const auto int_frac_parts = IntFracPartsToPrint(value); b_digits += GetNDigits(int_frac_parts.first); if (digits_before_point_ < b_digits) { digits_before_point_ = b_digits; } const int a_digits = GetNDigits(int_frac_parts.second) - 1; if (digits_after_point_ < a_digits) { digits_after_point_ = a_digits; } } void Print(std::ostream& os, double value) { if (digits_after_e_ > 0) { int width = 12 + (has_minus_ ? 1 : 0) + digits_after_e_; if (has_minus_ && !std::signbit(value)) { os << ' '; --width; } os << std::scientific << std::left << std::setw(width) << std::setprecision(8) << value; } else { if (std::isinf(value) || std::isnan(value)) { os << std::right << std::setw(digits_before_point_ + digits_after_point_ + 1) << value; return; } const auto int_frac_parts = IntFracPartsToPrint(value); const int a_digits = GetNDigits(int_frac_parts.second) - 1; os << std::fixed << std::right << std::setw(digits_before_point_ + a_digits + 1) << std::setprecision(a_digits) << std::showpoint << value; PrintNTimes(os, ' ', digits_after_point_ - a_digits); } } private: // Returns the integral part and fractional part as integers. // Note that the fractional part is prefixed by 1 so that the information of preceeding zeros is not missed. static std::pair<int64_t, int64_t> IntFracPartsToPrint(double value) { double int_part; const double frac_part = std::modf(value, &int_part); auto shifted_frac_part = static_cast<int64_t>((std::abs(frac_part) + 1) * 100'000'000); while ((shifted_frac_part % 10) == 0) { shifted_frac_part /= 10; } return {static_cast<int64_t>(int_part), shifted_frac_part}; } int digits_before_point_ = 1; int digits_after_point_ = 0; int digits_after_e_ = 0; bool has_minus_ = false; }; class BoolFormatter { public: void Scan(bool value) { (void)value; /* unused */ } void Print(std::ostream& os, bool value) const { os << (value ? " True" : "False"); // NOLINTER } }; template <typename T> using Formatter = std::conditional_t<std::is_same<T, bool>::value, BoolFormatter, std::conditional_t<std::is_floating_point<T>::value, FloatFormatter, IntFormatter>>; struct ArrayReprImpl { template <typename T, typename Visitor> void VisitElements(const Array& array, Visitor&& visitor) const { // TODO(niboshi): Contiguousness is assumed. // TODO(niboshi): Replace with Indxer class. auto shape = array.shape(); std::vector<int64_t> indexer; std::copy(shape.cbegin(), shape.cend(), std::back_inserter(indexer)); std::shared_ptr<const T> data = std::static_pointer_cast<const T>(array.data()); array.device().Synchronize(); for (int64_t i = 0; i < array.GetTotalSize(); ++i) { // Increment indexer for (int j = shape.ndim() - 1; j >= 0; --j) { indexer[j]++; if (indexer[j] >= shape[j]) { indexer[j] = 0; } else { break; } } visitor(data.get()[i], &indexer[0]); } } template <typename T> void operator()(const Array& array, std::ostream& os) const { Formatter<T> formatter; // Let formatter scan all elements to print. VisitElements<T>(array, [&formatter](T value, const int64_t* index) { (void)index; // unused formatter.Scan(value); }); // Print values using the formatter. const int8_t ndim = array.ndim(); int cur_line_size = 0; VisitElements<T>(array, [ndim, &cur_line_size, &formatter, &os](T value, const int64_t* index) { int8_t trailing_zeros = 0; if (ndim > 0) { for (auto it = index + ndim; --it >= index;) { if (*it == 0) { ++trailing_zeros; } else { break; } } } if (trailing_zeros == ndim) { // This is the first iteration, so print the header os << "array("; PrintNTimes(os, '[', ndim); } else if (trailing_zeros > 0) { PrintNTimes(os, ']', trailing_zeros); os << ','; PrintNTimes(os, '\n', trailing_zeros); PrintNTimes(os, ' ', 6 + ndim - trailing_zeros); PrintNTimes(os, '[', trailing_zeros); cur_line_size = 0; } else { if (cur_line_size == 10) { os << ",\n"; PrintNTimes(os, ' ', 6 + ndim); cur_line_size = 0; } else { os << ", "; } } formatter.Print(os, value); ++cur_line_size; }); if (array.GetTotalSize() == 0) { // In case of an empty Array, print the header here os << "array([]"; } else { PrintNTimes(os, ']', ndim); } // Print the footer os << ", shape=" << array.shape(); os << ", dtype=" << array.dtype(); os << ", device='" << array.device().name() << "'"; const std::vector<std::shared_ptr<ArrayNode>>& nodes = array.nodes(); if (!nodes.empty()) { os << ", graph_ids=["; for (size_t i = 0; i < nodes.size(); ++i) { if (i > 0) { os << ", "; } os << '\'' << nodes[i]->graph_id() << '\''; } os << ']'; } os << ')'; } }; } // namespace std::ostream& operator<<(std::ostream& os, const Array& array) { // TODO(hvy): We need to determine the output specification of this function, whether or not to align with Python repr specification, // and also whether this functionality should be defined in C++ layer or Python layer. VisitDtype(array.dtype(), [&](auto pt) { ArrayReprImpl{}.operator()<typename decltype(pt)::type>(array, os); }); return os; } std::string ArrayRepr(const Array& array) { std::ostringstream os; os << array; return os.str(); } } // namespace xchainer <|endoftext|>
<commit_before>/** --------------------------------------------------------------------------- * @file: shader.cpp * * Copyright (c) 2017 Yann Herklotz Grave <[email protected]> * MIT License, see LICENSE file for more details. * ---------------------------------------------------------------------------- */ #include "shader.h" #include <fstream> #include <sstream> #include <stdexcept> #include <string> #include <vector> using std::runtime_error; namespace yage { Shader::Shader(const std::string &vertex_path, const std::string &fragment_path) { std::string vertex_source, fragment_source; std::ifstream vertex_file, fragment_file; vertex_file.exceptions(std::ifstream::failbit | std::ifstream::badbit); fragment_file.exceptions(std::ifstream::failbit | std::ifstream::badbit); try { vertex_file.open(vertex_path); fragment_file.open(fragment_path); std::ostringstream vertex_stream, fragment_stream; vertex_stream << vertex_file.rdbuf(); fragment_stream << fragment_file.rdbuf(); vertex_file.close(); fragment_file.close(); vertex_source = vertex_stream.str(); fragment_source = fragment_stream.str(); } catch (std::ifstream::failure e) { throw runtime_error("File could not be opened: " + std::string(e.what())); } const char *vertex_source_c = vertex_source.c_str(); const char *fragment_source_c = fragment_source.c_str(); GLuint vertex_shader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex_shader, 1, &vertex_source_c, NULL); glCompileShader(vertex_shader); errorCheck(vertex_shader, "vertex"); GLuint fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment_shader, 1, &fragment_source_c, NULL); glCompileShader(fragment_shader); errorCheck(fragment_shader, "fragment"); program_id_ = glCreateProgram(); glAttachShader(program_id_, vertex_shader); glAttachShader(program_id_, fragment_shader); glLinkProgram(program_id_); errorCheck(program_id_, "program"); glDetachShader(program_id_, vertex_shader); glDetachShader(program_id_, fragment_shader); glDeleteShader(vertex_shader); glDeleteShader(fragment_shader); } Shader::~Shader() { /// cleans up all the shaders and the program if (program_id_ != 0) { glDeleteProgram(program_id_); } } void Shader::use() const { glUseProgram(program_id_); } void Shader::setUniform(const std::string &name, int value) const { glUniform1i(getUniformLocation(name), static_cast<GLint>(value)); } void Shader::setUniform(const std::string &name, float value) const { glUniform1f(getUniformLocation(name), static_cast<GLfloat>(value)); } void Shader::setUniform(const std::string &name, const glm::mat4 &matrix) const { glUniformMatrix4fv(getUniformLocation(name), 1, GL_FALSE, &(matrix[0][0])); } GLint Shader::getUniformLocation(const std::string &uniform_name) const { GLint location = glGetUniformLocation(program_id_, uniform_name.c_str()); if (location == GL_INVALID_INDEX) { throw std::runtime_error("'" + uniform_name + "' not found"); } return location; } void Shader::errorCheck(GLuint shader, const std::string &shader_type) const { int success; char info_log[1024]; if (shader_type != std::string("program")) { glGetShaderiv(shader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(shader, 1024, NULL, info_log); throw runtime_error(shader_type + " failed to compile: " + std::string(info_log)); } } else { glGetProgramiv(shader, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(shader, 1024, NULL, info_log); throw runtime_error(shader_type + " failed to link: " + std::string(info_log)); } } } } // namespace yage <commit_msg>[Bug fix] Changed int to unsigned.<commit_after>/** --------------------------------------------------------------------------- * @file: shader.cpp * * Copyright (c) 2017 Yann Herklotz Grave <[email protected]> * MIT License, see LICENSE file for more details. * ---------------------------------------------------------------------------- */ #include "shader.h" #include <fstream> #include <sstream> #include <stdexcept> #include <string> #include <vector> using std::runtime_error; namespace yage { Shader::Shader(const std::string &vertex_path, const std::string &fragment_path) { std::string vertex_source, fragment_source; std::ifstream vertex_file, fragment_file; vertex_file.exceptions(std::ifstream::failbit | std::ifstream::badbit); fragment_file.exceptions(std::ifstream::failbit | std::ifstream::badbit); try { vertex_file.open(vertex_path); fragment_file.open(fragment_path); std::ostringstream vertex_stream, fragment_stream; vertex_stream << vertex_file.rdbuf(); fragment_stream << fragment_file.rdbuf(); vertex_file.close(); fragment_file.close(); vertex_source = vertex_stream.str(); fragment_source = fragment_stream.str(); } catch (std::ifstream::failure e) { throw runtime_error("File could not be opened: " + std::string(e.what())); } const char *vertex_source_c = vertex_source.c_str(); const char *fragment_source_c = fragment_source.c_str(); GLuint vertex_shader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex_shader, 1, &vertex_source_c, NULL); glCompileShader(vertex_shader); errorCheck(vertex_shader, "vertex"); GLuint fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment_shader, 1, &fragment_source_c, NULL); glCompileShader(fragment_shader); errorCheck(fragment_shader, "fragment"); program_id_ = glCreateProgram(); glAttachShader(program_id_, vertex_shader); glAttachShader(program_id_, fragment_shader); glLinkProgram(program_id_); errorCheck(program_id_, "program"); glDetachShader(program_id_, vertex_shader); glDetachShader(program_id_, fragment_shader); glDeleteShader(vertex_shader); glDeleteShader(fragment_shader); } Shader::~Shader() { /// cleans up all the shaders and the program if (program_id_ != 0) { glDeleteProgram(program_id_); } } void Shader::use() const { glUseProgram(program_id_); } void Shader::setUniform(const std::string &name, int value) const { glUniform1i(getUniformLocation(name), static_cast<GLint>(value)); } void Shader::setUniform(const std::string &name, float value) const { glUniform1f(getUniformLocation(name), static_cast<GLfloat>(value)); } void Shader::setUniform(const std::string &name, const glm::mat4 &matrix) const { glUniformMatrix4fv(getUniformLocation(name), 1, GL_FALSE, &(matrix[0][0])); } GLint Shader::getUniformLocation(const std::string &uniform_name) const { GLuint location = glGetUniformLocation(program_id_, uniform_name.c_str()); if (location == GL_INVALID_INDEX) { throw std::runtime_error("'" + uniform_name + "' not found"); } return location; } void Shader::errorCheck(GLuint shader, const std::string &shader_type) const { int success; char info_log[1024]; if (shader_type != std::string("program")) { glGetShaderiv(shader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(shader, 1024, NULL, info_log); throw runtime_error(shader_type + " failed to compile: " + std::string(info_log)); } } else { glGetProgramiv(shader, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(shader, 1024, NULL, info_log); throw runtime_error(shader_type + " failed to link: " + std::string(info_log)); } } } } // namespace yage <|endoftext|>
<commit_before>/* -*- mode: c++; c-basic-offset:4 -*- systemtrayicon.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2007 Klarälvdalens Datakonsult AB Kleopatra 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. Kleopatra 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 In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "systemtrayicon.h" #include <KIcon> #include <KLocale> #include <KAboutApplicationDialog> #include <KAboutData> #include <KComponentData> #include <QMenu> #include <QAction> #include <QVBoxLayout> #include <QTextEdit> #include <QLabel> #include <QDialog> #include <QDialogButtonBox> #include <QPushButton> #include <QCoreApplication> #include <QProcess> #include <QPointer> #include <boost/shared_ptr.hpp> #include <boost/bind.hpp> #include <cassert> using namespace boost; class SystemTrayIcon::Private { friend class ::SystemTrayIcon; SystemTrayIcon * const q; public: explicit Private( SystemTrayIcon * qq ); ~Private(); private: void slotOpenCertificateManager() { emit q->activated( QSystemTrayIcon::Trigger ); } void slotAbout() { if ( !aboutDialog ) { aboutDialog = new KAboutApplicationDialog( KGlobal::mainComponent().aboutData() ); aboutDialog->setAttribute( Qt::WA_DeleteOnClose ); } if ( aboutDialog->isVisible() ) aboutDialog->raise(); else aboutDialog->show(); } void slotCheckConfiguration(); private: QMenu menu; QAction openCertificateManagerAction; QAction aboutAction; QAction checkConfigAction; QAction quitAction; QPointer<KAboutApplicationDialog> aboutDialog; }; SystemTrayIcon::Private::Private( SystemTrayIcon * qq ) : q( qq ), menu(), openCertificateManagerAction( i18n("&Open Certificate Manager..."), q ), aboutAction( i18n("&About %1...", KGlobal::mainComponent().aboutData()->programName() ), q ), checkConfigAction( i18n("&Check GnuPG Config..."), q ), quitAction( i18n("&Shutdown Kleopatra"), q ), aboutDialog() { KDAB_SET_OBJECT_NAME( menu ); KDAB_SET_OBJECT_NAME( openCertificateManagerAction ); KDAB_SET_OBJECT_NAME( aboutAction ); KDAB_SET_OBJECT_NAME( checkConfigAction ); KDAB_SET_OBJECT_NAME( quitAction ); connect( &openCertificateManagerAction, SIGNAL(triggered()), q, SLOT(slotOpenCertificateManager()) ); connect( &aboutAction, SIGNAL(triggered()), q, SLOT(slotAbout()) ); connect( &quitAction, SIGNAL(triggered()), QCoreApplication::instance(), SLOT(quit()) ); connect( &checkConfigAction, SIGNAL(triggered()), q, SLOT(slotCheckConfiguration()) ); menu.addAction( &openCertificateManagerAction ); menu.addAction( &aboutAction ); menu.addSeparator(); menu.addAction( &checkConfigAction ); menu.addSeparator(); menu.addAction( &quitAction ); q->setContextMenu( &menu ); } SystemTrayIcon::Private::~Private() {} SystemTrayIcon::SystemTrayIcon( QObject * p ) : QSystemTrayIcon( KIcon( "gpg" ), p ), d( new Private( this ) ) { } SystemTrayIcon::~SystemTrayIcon() {} void SystemTrayIcon::Private::slotCheckConfiguration() { assert( checkConfigAction.isEnabled() ); if ( !checkConfigAction.isEnabled() ) return; checkConfigAction.setEnabled( false ); const shared_ptr<QAction> enabler( &checkConfigAction, bind( &QAction::setEnabled, _1, true ) ); // 1. start process QProcess process; process.setProcessChannelMode( QProcess::MergedChannels ); process.start( "gpgconf", QStringList() << "--check-config", QIODevice::ReadOnly ); // 2. show dialog: QDialog dlg; QVBoxLayout vlay( &dlg ); QLabel label( i18n("This is the result of the GnuPG config check:" ), &dlg ); QTextEdit textEdit( &dlg ); QDialogButtonBox box( QDialogButtonBox::Close, Qt::Horizontal, &dlg ); textEdit.setReadOnly( true ); textEdit.setWordWrapMode( QTextOption::NoWrap ); vlay.addWidget( &label ); vlay.addWidget( &textEdit, 1 ); vlay.addWidget( &box ); dlg.show(); connect( box.button( QDialogButtonBox::Close ), SIGNAL(clicked()), &dlg, SLOT(reject()) ); connect( &dlg, SIGNAL(finished(int)), &process, SLOT(terminate()) ); // 3. wait for either dialog close or process exit QEventLoop loop; connect( &process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()) ); connect( &dlg, SIGNAL(finished(int)), &loop, SLOT(quit()) ); const QPointer<QObject> Q( q ); loop.exec(); // safety exit: if ( !Q ) return; // check whether it was the dialog that was closed, and return in // that case: if ( !dlg.isVisible() ) return; if ( process.error() != QProcess::UnknownError ) textEdit.setPlainText( QString::fromUtf8( process.readAll() ) + '\n' + process.errorString() ); else textEdit.setPlainText( QString::fromUtf8( process.readAll() ) ); // wait for dialog close: assert( dlg.isVisible() ); loop.exec(); } #include "moc_systemtrayicon.cpp" <commit_msg>use kleopatra icon for the systray<commit_after>/* -*- mode: c++; c-basic-offset:4 -*- systemtrayicon.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2007 Klarälvdalens Datakonsult AB Kleopatra 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. Kleopatra 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 In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "systemtrayicon.h" #include <KIcon> #include <KLocale> #include <KAboutApplicationDialog> #include <KAboutData> #include <KComponentData> #include <QMenu> #include <QAction> #include <QVBoxLayout> #include <QTextEdit> #include <QLabel> #include <QDialog> #include <QDialogButtonBox> #include <QPushButton> #include <QCoreApplication> #include <QProcess> #include <QPointer> #include <boost/shared_ptr.hpp> #include <boost/bind.hpp> #include <cassert> using namespace boost; class SystemTrayIcon::Private { friend class ::SystemTrayIcon; SystemTrayIcon * const q; public: explicit Private( SystemTrayIcon * qq ); ~Private(); private: void slotOpenCertificateManager() { emit q->activated( QSystemTrayIcon::Trigger ); } void slotAbout() { if ( !aboutDialog ) { aboutDialog = new KAboutApplicationDialog( KGlobal::mainComponent().aboutData() ); aboutDialog->setAttribute( Qt::WA_DeleteOnClose ); } if ( aboutDialog->isVisible() ) aboutDialog->raise(); else aboutDialog->show(); } void slotCheckConfiguration(); private: QMenu menu; QAction openCertificateManagerAction; QAction aboutAction; QAction checkConfigAction; QAction quitAction; QPointer<KAboutApplicationDialog> aboutDialog; }; SystemTrayIcon::Private::Private( SystemTrayIcon * qq ) : q( qq ), menu(), openCertificateManagerAction( i18n("&Open Certificate Manager..."), q ), aboutAction( i18n("&About %1...", KGlobal::mainComponent().aboutData()->programName() ), q ), checkConfigAction( i18n("&Check GnuPG Config..."), q ), quitAction( i18n("&Shutdown Kleopatra"), q ), aboutDialog() { KDAB_SET_OBJECT_NAME( menu ); KDAB_SET_OBJECT_NAME( openCertificateManagerAction ); KDAB_SET_OBJECT_NAME( aboutAction ); KDAB_SET_OBJECT_NAME( checkConfigAction ); KDAB_SET_OBJECT_NAME( quitAction ); connect( &openCertificateManagerAction, SIGNAL(triggered()), q, SLOT(slotOpenCertificateManager()) ); connect( &aboutAction, SIGNAL(triggered()), q, SLOT(slotAbout()) ); connect( &quitAction, SIGNAL(triggered()), QCoreApplication::instance(), SLOT(quit()) ); connect( &checkConfigAction, SIGNAL(triggered()), q, SLOT(slotCheckConfiguration()) ); menu.addAction( &openCertificateManagerAction ); menu.addAction( &aboutAction ); menu.addSeparator(); menu.addAction( &checkConfigAction ); menu.addSeparator(); menu.addAction( &quitAction ); q->setContextMenu( &menu ); } SystemTrayIcon::Private::~Private() {} SystemTrayIcon::SystemTrayIcon( QObject * p ) : QSystemTrayIcon( KIcon( "kleopatra" ), p ), d( new Private( this ) ) { } SystemTrayIcon::~SystemTrayIcon() {} void SystemTrayIcon::Private::slotCheckConfiguration() { assert( checkConfigAction.isEnabled() ); if ( !checkConfigAction.isEnabled() ) return; checkConfigAction.setEnabled( false ); const shared_ptr<QAction> enabler( &checkConfigAction, bind( &QAction::setEnabled, _1, true ) ); // 1. start process QProcess process; process.setProcessChannelMode( QProcess::MergedChannels ); process.start( "gpgconf", QStringList() << "--check-config", QIODevice::ReadOnly ); // 2. show dialog: QDialog dlg; QVBoxLayout vlay( &dlg ); QLabel label( i18n("This is the result of the GnuPG config check:" ), &dlg ); QTextEdit textEdit( &dlg ); QDialogButtonBox box( QDialogButtonBox::Close, Qt::Horizontal, &dlg ); textEdit.setReadOnly( true ); textEdit.setWordWrapMode( QTextOption::NoWrap ); vlay.addWidget( &label ); vlay.addWidget( &textEdit, 1 ); vlay.addWidget( &box ); dlg.show(); connect( box.button( QDialogButtonBox::Close ), SIGNAL(clicked()), &dlg, SLOT(reject()) ); connect( &dlg, SIGNAL(finished(int)), &process, SLOT(terminate()) ); // 3. wait for either dialog close or process exit QEventLoop loop; connect( &process, SIGNAL(finished(int,QProcess::ExitStatus)), &loop, SLOT(quit()) ); connect( &dlg, SIGNAL(finished(int)), &loop, SLOT(quit()) ); const QPointer<QObject> Q( q ); loop.exec(); // safety exit: if ( !Q ) return; // check whether it was the dialog that was closed, and return in // that case: if ( !dlg.isVisible() ) return; if ( process.error() != QProcess::UnknownError ) textEdit.setPlainText( QString::fromUtf8( process.readAll() ) + '\n' + process.errorString() ); else textEdit.setPlainText( QString::fromUtf8( process.readAll() ) ); // wait for dialog close: assert( dlg.isVisible() ); loop.exec(); } #include "moc_systemtrayicon.cpp" <|endoftext|>
<commit_before>/* Copyright (c) 2015, Dan Bethell, Johannes Saam, Vahan Sosoyan. All rights reserved. See Copyright.txt for more details. */ #include "Client.h" #include <boost/lexical_cast.hpp> #include <stdexcept> #include <iostream> using namespace aton; using boost::asio::ip::tcp; Client::Client( std::string hostname, int port ) : mHost( hostname ), mPort( port ), mImageId( -1 ), mSocket( mIoService ) { } void Client::connect( std::string hostname, int port ) { bool result = true; tcp::resolver resolver(mIoService); tcp::resolver::query query( hostname.c_str(), boost::lexical_cast<std::string>(port).c_str() ); tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); tcp::resolver::iterator end; boost::system::error_code error = boost::asio::error::host_not_found; while (error && endpoint_iterator != end) { mSocket.close(); mSocket.connect(*endpoint_iterator++, error); } if (error) throw boost::system::system_error(error); } void Client::disconnect() { mSocket.close(); } Client::~Client() { disconnect(); } void Client::openImage( Data &header ) { // connect to port! connect(mHost, mPort); // send image header message with image desc information int key = 0; boost::asio::write( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&key), sizeof(int)) ); // read our imageid boost::asio::read( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&mImageId), sizeof(int)) ); // send our width & height boost::asio::write( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&header.mWidth), sizeof(int)) ); boost::asio::write( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&header.mHeight), sizeof(int)) ); boost::asio::write( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&header.mRArea), sizeof(int)) ); boost::asio::write( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&header.mVersion), sizeof(int)) ); boost::asio::write( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&header.mCurrentFrame), sizeof(float)) ); } void Client::sendPixels( Data &data ) { if ( mImageId<0 ) { throw std::runtime_error( "Could not send data - image id is not valid!" ); } // send data for image_id int key = 1; boost::asio::write( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&key), sizeof(int)) ); boost::asio::write( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&mImageId), sizeof(int)) ); // get size of the aov name in bytes size_t aov_size = strlen(data.mAovName)+1; // send pixel data int num_samples = data.mWidth * data.mHeight * data.mSpp; boost::asio::write( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mX), sizeof(int)) ); boost::asio::write( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mY), sizeof(int)) ); boost::asio::write( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mWidth), sizeof(int)) ); boost::asio::write( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mHeight), sizeof(int)) ); boost::asio::write( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mRArea), sizeof(long long)) ); boost::asio::write( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mVersion), sizeof(int)) ); boost::asio::write( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mCurrentFrame), sizeof(float)) ); boost::asio::write( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mSpp), sizeof(int)) ); boost::asio::write( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mRam), sizeof(long long)) ); boost::asio::write( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mTime), sizeof(int)) ); boost::asio::write( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&aov_size), sizeof(size_t)) ); boost::asio::write( mSocket, boost::asio::buffer(data.mAovName, aov_size) ); boost::asio::write( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mpData[0]), sizeof(float)*num_samples) ); } void Client::closeImage( ) { // send image complete message for image_id int key = 2; boost::asio::write( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&key), sizeof(int)) ); // tell the server which image we're closing boost::asio::write( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&mImageId), sizeof(int)) ); // disconnect from port! disconnect(); } void Client::quit() { connect(mHost, mPort); int key = 9; boost::asio::write( mSocket, boost::asio::buffer(reinterpret_cast<char*>(&key), sizeof(int)) ); disconnect(); } <commit_msg>Polish<commit_after>/* Copyright (c) 2015, Dan Bethell, Johannes Saam, Vahan Sosoyan. All rights reserved. See Copyright.txt for more details. */ #include "Client.h" #include <boost/lexical_cast.hpp> #include <stdexcept> #include <iostream> using namespace aton; using boost::asio::ip::tcp; Client::Client(std::string hostname, int port) : mHost(hostname), mPort(port), mImageId(-1), mSocket(mIoService) { } void Client::connect(std::string hostname, int port) { bool result = true; tcp::resolver resolver(mIoService); tcp::resolver::query query(hostname.c_str(), boost::lexical_cast<std::string>(port).c_str()); tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); tcp::resolver::iterator end; boost::system::error_code error = boost::asio::error::host_not_found; while (error && endpoint_iterator != end) { mSocket.close(); mSocket.connect(*endpoint_iterator++, error); } if (error) throw boost::system::system_error(error); } void Client::disconnect() { mSocket.close(); } Client::~Client() { disconnect(); } void Client::openImage(Data& header) { // connect to port! connect(mHost, mPort); // send image header message with image desc information int key = 0; boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&key), sizeof(int))); // read our imageid boost::asio::read(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&mImageId), sizeof(int))); // send our width & height boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&header.mWidth), sizeof(int))); boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&header.mHeight), sizeof(int))); boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&header.mRArea), sizeof(int))); boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&header.mVersion), sizeof(int))); boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&header.mCurrentFrame), sizeof(float))); } void Client::sendPixels(Data& data) { if (mImageId < 0) { throw std::runtime_error("Could not send data - image id is not valid!"); } // send data for image_id int key = 1; boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&key), sizeof(int))); boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&mImageId), sizeof(int))); // get size of the aov name in bytes size_t aov_size = strlen(data.mAovName)+1; // send pixel data int num_samples = data.mWidth * data.mHeight * data.mSpp; boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mX), sizeof(int))); boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mY), sizeof(int))); boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mWidth), sizeof(int))); boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mHeight), sizeof(int))); boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mRArea), sizeof(long long))); boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mVersion), sizeof(int))); boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mCurrentFrame), sizeof(float))); boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mSpp), sizeof(int))); boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mRam), sizeof(long long))); boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mTime), sizeof(int))); boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&aov_size), sizeof(size_t))); boost::asio::write(mSocket, boost::asio::buffer(data.mAovName, aov_size)); boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&data.mpData[0]), sizeof(float)*num_samples)); } void Client::closeImage() { // send image complete message for image_id int key = 2; boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&key), sizeof(int))); // tell the server which image we're closing boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&mImageId), sizeof(int))); // disconnect from port! disconnect(); } void Client::quit() { connect(mHost, mPort); int key = 9; boost::asio::write(mSocket, boost::asio::buffer(reinterpret_cast<char*>(&key), sizeof(int))); disconnect(); } <|endoftext|>
<commit_before>/* Copyright (c) 2017 Wenova - Rise of Conquerors. All rights reserved. * * This work is licensed under the terms of the MIT license. * For a copy, see <https://opensource.org/licenses/MIT>. */ /** * @file Config.cpp * Implements class Config methods. */ #include "Config.h" int Config::width; int Config::height; int Config::fullscreen; /** * Will write current screen configurations to res/config_file.dat. */ void Config::init() { LOG(INFO) << "Starting CharacterSelectState init"; std::fstream config_file(CONFIGURATION_FILE_PATH); if (not config_file.is_open()) { LOG(FATAL) << "File couldn't be open"; } assert(config_file.is_open()); config_file >> width >> height >> fullscreen; LOG(INFO) << "Ending CharacterSelectState init"; } /** * Accessor to width private attribute. * * @returns Game's windows width. Unit: px, [0,] */ int Config::get_width() { LOG(INFO) << "Starting CharacterSelectState get_width"; int return_value = width; std::string log_message = "Ending CharacterSelectState get_width returning value: " + std::to_string(return_value); LOG(INFO) << log_message; return return_value; } /** * Accessor to height private attribute. * @returns Game's windows height. Unit: px, [0,] */ int Config::get_height() { LOG(INFO) << "Starting CharacterSelectState get_height"; int return_value = height; std::string log_message = "Ending CharacterSelectState get_height returning value: " + std::to_string(return_value); LOG(INFO) << log_message; return return_value; } /** * Get fullscreen current status. * * @returns 0 for no, 1 for yes [0,1] */ int Config::is_fullscreen() { LOG(INFO) << "Starting CharacterSelectState is_fullscreen"; int return_value = fullscreen; std::string log_message = "Ending CharacterSelectState is_fullscreen returning value: " + std::to_string(return_value); LOG(INFO) << log_message; return return_value; } /** * Writes to file res/config_file.dat screen information. * * @param cwidth Unit: px, [0,] * @param cheight Unit: px, [0,] * @param cfullscreen [0,1] */ void Config::update_information(int cwidth, int cheight, int cfullscreen) { std::string log_message = "Starting CharacterSelectState update_information, cwidth: "; log_message += std::to_string(cwidth) += ", cheight: "; log_message += std::to_string(cheight) + ", cfullscreen: " + std::to_string(cfullscreen); LOG(INFO) << log_message; width = cwidth; height = cheight; fullscreen = cfullscreen; std::ofstream config_file(CONFIGURATION_FILE_PATH, std::ios::trunc); if (not config_file.is_open()) { LOG(FATAL) << "File couldn't be open"; } assert(config_file.is_open()); config_file << width << " " << height << " " << fullscreen << std::endl; config_file.close(); LOG(INFO) << "Ending CharacterSelectState update_information"; } <commit_msg>Apply check return technique to Config<commit_after>/* Copyright (c) 2017 Wenova - Rise of Conquerors. All rights reserved. * * This work is licensed under the terms of the MIT license. * For a copy, see <https://opensource.org/licenses/MIT>. */ /** * @file Config.cpp * Implements class Config methods. */ #include "Config.h" int Config::width; int Config::height; int Config::fullscreen; /** * Will write current screen configurations to res/config_file.dat. */ void Config::init() { LOG(INFO) << "Starting CharacterSelectState init"; std::fstream config_file(CONFIGURATION_FILE_PATH); if (not config_file.is_open()) { LOG(FATAL) << "File couldn't be open"; } assert(config_file.is_open()); config_file >> width >> height >> fullscreen; LOG(INFO) << "Ending CharacterSelectState init"; } /** * Accessor to width private attribute. * * @returns Game's windows width. Unit: px, [0,] */ int Config::get_width() { LOG(INFO) << "Starting CharacterSelectState get_width"; int return_value = width; std::string log_message = "Ending CharacterSelectState get_width returning value: " + std::to_string(return_value); LOG(INFO) << log_message; if (width <= 0) { LOG(WARNING) << "Width is being returned with suspicious values"; } return return_value; } /** * Accessor to height private attribute. * @returns Game's windows height. Unit: px, [0,] */ int Config::get_height() { LOG(INFO) << "Starting CharacterSelectState get_height"; int return_value = height; std::string log_message = "Ending CharacterSelectState get_height returning value: " + std::to_string(return_value); LOG(INFO) << log_message; if (height <= 0) { LOG(WARNING) << "Height is being returned with suspicious values"; } return return_value; } /** * Get fullscreen current status. * * @returns 0 for no, 1 for yes [0,1] */ int Config::is_fullscreen() { LOG(INFO) << "Starting CharacterSelectState is_fullscreen"; int return_value = fullscreen; std::string log_message = "Ending CharacterSelectState is_fullscreen returning value: " + std::to_string(return_value); LOG(INFO) << log_message; return return_value; } /** * Writes to file res/config_file.dat screen information. * * @param cwidth Unit: px, [0,] * @param cheight Unit: px, [0,] * @param cfullscreen [0,1] */ void Config::update_information(int cwidth, int cheight, int cfullscreen) { std::string log_message = "Starting CharacterSelectState update_information, cwidth: "; log_message += std::to_string(cwidth) += ", cheight: "; log_message += std::to_string(cheight) + ", cfullscreen: " + std::to_string(cfullscreen); LOG(INFO) << log_message; width = cwidth; height = cheight; fullscreen = cfullscreen; std::ofstream config_file(CONFIGURATION_FILE_PATH, std::ios::trunc); if (not config_file.is_open()) { LOG(FATAL) << "File couldn't be open"; } assert(config_file.is_open()); config_file << width << " " << height << " " << fullscreen << std::endl; config_file.close(); LOG(INFO) << "Ending CharacterSelectState update_information"; } <|endoftext|>
<commit_before>#include "DG_Job.h" #include <SDL.h> #include <atomic> #include "DG_Windows.h" namespace DG { static const u32 JOB_COUNT = 4096; static const u32 JOB_MASK = JOB_COUNT - 1u; thread_local u32 LocalJobBufferIndex = 0; thread_local Job LocalJobBuffer[JOB_COUNT]; thread_local Job* LocalJobQueue[JOB_COUNT]; thread_local JobSystem::JobWorkQueue LocalQueue(LocalJobQueue, JOB_COUNT); bool g_JobQueueShutdownRequested = false; static JobSystem::JobWorkQueue* _queues[64]; static SDL_mutex* _mutex = SDL_CreateMutex(); static SDL_cond* _cond = SDL_CreateCond(); static s32 _workerCount = 0; JobSystem::JobWorkQueue::JobWorkQueue(Job** queue, u32 size) : _jobs(queue), _size(size) { } Job* JobSystem::JobWorkQueue::GetJob() { Job* job = Pop(); if (!job) { // Steal Job u32 index = rand() % _workerCount; JobWorkQueue* queueToStealFrom = _queues[index]; if (&LocalQueue != queueToStealFrom) { job = queueToStealFrom->Steal(); } } return job; } void JobSystem::JobWorkQueue::Push(Job* job) { s32 t = _top; _jobs[t & JOB_MASK] = job; SDL_CompilerBarrier(); _top = t + 1; } Job* JobSystem::JobWorkQueue::Pop() { s32 t = _top - 1; _top = t; MemoryBarrier(); // Can't find a SDL equivalent s32 b = SDL_AtomicGet(&_bottom); // Empty queue if (b > t) { _top = b; return nullptr; } // not empty Job* job = _jobs[t & JOB_MASK]; // Not Last Item if (b != t) return job; // Check if a steal operation got there before us if (!SDL_AtomicCAS(&_bottom, b, b + 1)) job = nullptr; // Someone stole the job _top = b + 1; return job; } Job* JobSystem::JobWorkQueue::Steal() { long b = SDL_AtomicGet(&_bottom); SDL_CompilerBarrier(); long t = _top; if (b < t) { // non-empty queue Job* job = _jobs[b & JOB_MASK]; if (SDL_AtomicCAS(&_bottom, b, b + 1)) { return job; } } return nullptr; } void JobSystem::Finish(Job* job) { const s32 unfinishedJobs = SDL_AtomicAdd(&job->unfinishedJobs, -1); if (unfinishedJobs == 1) { if (job->parent) { Finish(job->parent); } } } Job* JobSystem::CreateJob(JobFunction function) { u32 index = LocalJobBufferIndex & JOB_MASK; ++LocalJobBufferIndex; Job& job = LocalJobBuffer[index]; Assert(SDL_AtomicGet(&job.unfinishedJobs) == 0); job.function = function; job.parent = nullptr; SDL_AtomicSet(&job.unfinishedJobs, 1); SDL_memset(&job.data, 0, ArrayCount(job.data)); return &job; } Job* JobSystem::CreateJobAsChild(Job* parent, JobFunction function) { SDL_AtomicAdd(&parent->unfinishedJobs, 1); u32 index = LocalJobBufferIndex & JOB_MASK; ++LocalJobBufferIndex; Job& job = LocalJobBuffer[index]; Assert(SDL_AtomicGet(&job.unfinishedJobs) == 0); job.function = function; job.parent = parent; SDL_AtomicSet(&job.unfinishedJobs, 1); SDL_memset(&job.data, 0, ArrayCount(job.data)); return &job; } void JobSystem::Wait(Job* job) { // wait until the job has completed. in the meantime, work on any other job. while (SDL_AtomicGet(&job->unfinishedJobs) != 0) { Job* jobToBeDone = LocalQueue.GetJob(); if (jobToBeDone) { jobToBeDone->function(jobToBeDone, jobToBeDone->data); Finish(jobToBeDone); } } } void JobSystem::Run(Job* job) { LocalQueue.Push(job); SDL_LockMutex(_mutex); SDL_CondBroadcast(_cond); SDL_UnlockMutex(_mutex); } void JobSystem::CreateAndRegisterWorker() { SDL_CreateThread(JobQueueWorkerFunction, "Worker", nullptr); } bool JobSystem::RegisterWorker() { SDL_LockMutex(_mutex); if (_workerCount >= ArrayCount(_queues)) { Assert(false); return false; } _queues[_workerCount++] = &LocalQueue; SDL_UnlockMutex(_mutex); return true; } int JobSystem::JobQueueWorkerFunction(void* data) { if (!RegisterWorker()) return -1; while (!g_JobQueueShutdownRequested) { Job* job = LocalQueue.GetJob(); if (job) { job->function(job, job->data); Finish(job); } else { SDL_LockMutex(_mutex); SDL_CondWait(_cond, _mutex); SDL_UnlockMutex(_mutex); } } return 0; } } <commit_msg>Cond speedup by counting jobs<commit_after>#include "DG_Job.h" #include <SDL.h> #include <atomic> #include "DG_Windows.h" namespace DG { static const u32 JOB_COUNT = 4096; static const u32 JOB_MASK = JOB_COUNT - 1u; thread_local u32 LocalJobBufferIndex = 0; thread_local Job LocalJobBuffer[JOB_COUNT]; thread_local Job* LocalJobQueue[JOB_COUNT]; thread_local JobSystem::JobWorkQueue LocalQueue(LocalJobQueue, JOB_COUNT); bool g_JobQueueShutdownRequested = false; static JobSystem::JobWorkQueue* _queues[64]; static SDL_mutex* _mutex = SDL_CreateMutex(); static SDL_cond* _cond = SDL_CreateCond(); static s32 _workerCount = 0; static SDL_atomic_t _jobCount; JobSystem::JobWorkQueue::JobWorkQueue(Job** queue, u32 size) : _jobs(queue), _size(size) { } Job* JobSystem::JobWorkQueue::GetJob() { Job* job = Pop(); if (!job) { // Steal Job u32 index = rand() % _workerCount; JobWorkQueue* queueToStealFrom = _queues[index]; if (&LocalQueue != queueToStealFrom) { job = queueToStealFrom->Steal(); } } return job; } void JobSystem::JobWorkQueue::Push(Job* job) { s32 t = _top; _jobs[t & JOB_MASK] = job; SDL_CompilerBarrier(); _top = t + 1; } Job* JobSystem::JobWorkQueue::Pop() { s32 t = _top - 1; _top = t; MemoryBarrier(); // Can't find a SDL equivalent s32 b = SDL_AtomicGet(&_bottom); // Empty queue if (b > t) { _top = b; return nullptr; } // not empty Job* job = _jobs[t & JOB_MASK]; // Not Last Item if (b != t) return job; // Check if a steal operation got there before us if (!SDL_AtomicCAS(&_bottom, b, b + 1)) job = nullptr; // Someone stole the job _top = b + 1; return job; } Job* JobSystem::JobWorkQueue::Steal() { long b = SDL_AtomicGet(&_bottom); SDL_CompilerBarrier(); long t = _top; if (b < t) { // non-empty queue Job* job = _jobs[b & JOB_MASK]; if (SDL_AtomicCAS(&_bottom, b, b + 1)) { return job; } } return nullptr; } void JobSystem::Finish(Job* job) { const s32 unfinishedJobs = SDL_AtomicAdd(&job->unfinishedJobs, -1); if (unfinishedJobs == 1) { if (job->parent) { Finish(job->parent); } SDL_AtomicAdd(&_jobCount, -1); } } Job* JobSystem::CreateJob(JobFunction function) { u32 index = LocalJobBufferIndex & JOB_MASK; ++LocalJobBufferIndex; Job& job = LocalJobBuffer[index]; Assert(SDL_AtomicGet(&job.unfinishedJobs) == 0); job.function = function; job.parent = nullptr; SDL_AtomicSet(&job.unfinishedJobs, 1); SDL_memset(&job.data, 0, ArrayCount(job.data)); return &job; } Job* JobSystem::CreateJobAsChild(Job* parent, JobFunction function) { SDL_AtomicAdd(&parent->unfinishedJobs, 1); u32 index = LocalJobBufferIndex & JOB_MASK; ++LocalJobBufferIndex; Job& job = LocalJobBuffer[index]; Assert(SDL_AtomicGet(&job.unfinishedJobs) == 0); job.function = function; job.parent = parent; SDL_AtomicSet(&job.unfinishedJobs, 1); SDL_memset(&job.data, 0, ArrayCount(job.data)); return &job; } void JobSystem::Wait(Job* job) { // wait until the job has completed. in the meantime, work on any other job. while (SDL_AtomicGet(&job->unfinishedJobs) != 0) { Job* jobToBeDone = LocalQueue.GetJob(); if (jobToBeDone) { jobToBeDone->function(jobToBeDone, jobToBeDone->data); Finish(jobToBeDone); } } } void JobSystem::Run(Job* job) { LocalQueue.Push(job); s32 prev = SDL_AtomicAdd(&_jobCount, 1); if (prev == 0) { SDL_LockMutex(_mutex); SDL_CondBroadcast(_cond); SDL_UnlockMutex(_mutex); } } void JobSystem::CreateAndRegisterWorker() { SDL_CreateThread(JobQueueWorkerFunction, "Worker", nullptr); } bool JobSystem::RegisterWorker() { SDL_LockMutex(_mutex); if (_workerCount >= ArrayCount(_queues)) { Assert(false); return false; } _queues[_workerCount++] = &LocalQueue; SDL_UnlockMutex(_mutex); return true; } int JobSystem::JobQueueWorkerFunction(void* data) { if (!RegisterWorker()) return -1; while (!g_JobQueueShutdownRequested) { Job* job = LocalQueue.GetJob(); if (job) { job->function(job, job->data); Finish(job); } if (SDL_AtomicGet(&_jobCount) == 0) { SDL_LockMutex(_mutex); SDL_CondWait(_cond, _mutex); SDL_UnlockMutex(_mutex); } } return 0; } } <|endoftext|>
<commit_before>#include "Entity.hpp" Entity::Entity() { } void Entity::setVelocity(sf::Vector2f velocity) { m_velocity = velocity; } void Entity::setVelocity(float velX, float velY) { m_velocity.x = velX; m_velocity.y = velY; } sf::Vector2f Entity::getVelocity() { return m_velocity; } void Entity::updateCurrent(float dt) { // Move is the same as setPosition(getPosition() + offset) of the sf::Transformable class move(m_velocity * dt); } <commit_msg>Syntax xhanges<commit_after>#include "Entity.hpp" Entity::Entity() { } void Entity::setVelocity(sf::Vector2f velocity) { m_velocity = { velocity }; } void Entity::setVelocity(float velX, float velY) { m_velocity.x = { velX }; m_velocity.y = { velY }; } sf::Vector2f Entity::getVelocity() { return m_velocity; } void Entity::updateCurrent(float dt) { // Move is the same as setPosition(getPosition() + offset) of the sf::Transformable class move(m_velocity * dt); } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Library Module: Glyph3D.cc Language: C++ Date: $Date$ Version: $Revision$ This file is part of the Visualization Library. No part of this file or its contents may be copied, reproduced or altered in any way without the express written consent of the authors. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 =========================================================================*/ #include "Glyph3D.hh" #include "Trans.hh" #include "FVectors.hh" #include "FNormals.hh" #include "vlMath.hh" // Description // Construct object with scaling on, scaling mode is by scalar value, // scale factor = 1.0, the range is (0,1), orient geometry is on, and // orientation is by vector. vlGlyph3D::vlGlyph3D() { this->Source = NULL; this->Scaling = 1; this->ScaleMode = SCALE_BY_SCALAR; this->ScaleFactor = 1.0; this->Range[0] = 0.0; this->Range[1] = 1.0; this->Orient = 1; this->VectorMode = USE_VECTOR; } vlGlyph3D::~vlGlyph3D() { } void vlGlyph3D::PrintSelf(ostream& os, vlIndent indent) { if (this->ShouldIPrint(vlGlyph3D::GetClassName())) { vlDataSetToPolyFilter::PrintSelf(os,indent); os << indent << "Source: " << this->Source << "\n"; os << indent << "Scaling: " << (this->Scaling ? "On\n" : "Off\n"); os << indent << "Scale Mode: " << (this->ScaleMode == SCALE_BY_SCALAR ? "Scale by scalar\n" : "Scale by vector\n"); os << indent << "Scale Factor: " << this->ScaleFactor << "\n"; os << indent << "Range: (" << this->Range[0] << ", " << this->Range[1] << ")\n"; os << indent << "Orient: " << (this->Orient ? "On\n" : "Off\n"); os << indent << "Orient Mode: " << (this->VectorMode == USE_VECTOR ? "Orient by vector\n" : "Orient by normal\n"); } } void vlGlyph3D::Execute() { vlPointData *pd; vlScalars *inScalars; vlVectors *inVectors; vlNormals *inNormals, *sourceNormals; int numPts, numSourcePts, numSourceCells; int inPtId, i; vlPoints *sourcePts; vlCellArray *sourceCells; vlFloatPoints *newPts; vlFloatScalars *newScalars=NULL; vlFloatVectors *newVectors=NULL; vlFloatNormals *newNormals=NULL; float *x, *v, vNew[3]; vlTransform trans; vlCell *cell; vlIdList *cellPts; int npts, pts[MAX_CELL_SIZE]; int orient, scaleSource, ptIncr, cellId; float scale, den; vlMath math; vlDebugMacro(<<"Generating glyphs"); this->Initialize(); pd = this->Input->GetPointData(); inScalars = pd->GetScalars(); inVectors = pd->GetVectors(); inNormals = pd->GetNormals(); numPts = this->Input->GetNumberOfPoints(); // // Allocate storage for output PolyData // sourcePts = this->Source->GetPoints(); numSourcePts = sourcePts->GetNumberOfPoints(); numSourceCells = this->Source->GetNumberOfCells(); sourceNormals = this->Source->GetPointData()->GetNormals(); newPts = new vlFloatPoints(numPts*numSourcePts); if (inScalars != NULL) newScalars = new vlFloatScalars(numPts*numSourcePts); if (inVectors != NULL || inNormals != NULL ) newVectors = new vlFloatVectors(numPts*numSourcePts); if (sourceNormals != NULL) newNormals = new vlFloatNormals(numPts*numSourcePts); // Setting up for calls to PolyData::InsertNextCell() if ( (sourceCells=this->Source->GetVerts())->GetNumberOfCells() > 0 ) { this->SetVerts(new vlCellArray(numPts*sourceCells->GetSize())); } if ( (sourceCells=this->Source->GetLines())->GetNumberOfCells() > 0 ) { this->SetLines(new vlCellArray(numPts*sourceCells->GetSize())); } if ( (sourceCells=this->Source->GetPolys())->GetNumberOfCells() > 0 ) { this->SetPolys(new vlCellArray(numPts*sourceCells->GetSize())); } if ( (sourceCells=this->Source->GetStrips())->GetNumberOfCells() > 0 ) { this->SetStrips(new vlCellArray(numPts*sourceCells->GetSize())); } // // Copy (input scalars) to (output scalars) and either (input vectors or // normals) to (output vectors). All other point attributes are copied // from Source. // pd = this->Source->GetPointData(); this->PointData.CopyScalarsOff(); this->PointData.CopyVectorsOff(); this->PointData.CopyNormalsOff(); this->PointData.CopyAllocate(pd,numPts*numSourcePts); // // First copy all topology (transformation independent) // for (inPtId=0; inPtId < numPts; inPtId++) { ptIncr = inPtId * numSourcePts; for (cellId=0; cellId < numSourceCells; cellId++) { cell = this->Source->GetCell(cellId); cellPts = cell->GetPointIds(); npts = cellPts->GetNumberOfIds(); for (i=0; i < npts; i++) pts[i] = cellPts->GetId(i) + ptIncr; this->InsertNextCell(cell->GetCellType(),npts,pts); } } // // Traverse all Input points, transforming Source points and copying // point attributes. // if ( this->VectorMode == USE_VECTOR && inVectors != NULL || this->VectorMode == USE_NORMAL && inNormals != NULL ) orient = 1; else orient = 0; if ( this->Scaling && ((this->ScaleMode == SCALE_BY_SCALAR && inScalars != NULL) || (this->ScaleMode == SCALE_BY_VECTOR && (inVectors || inNormals))) ) scaleSource = 1; else scaleSource = 0; for (inPtId=0; inPtId < numPts; inPtId++) { ptIncr = inPtId * numSourcePts; trans.Identity(); // translate Source to Input point x = this->Input->GetPoint(inPtId); trans.Translate(x[0], x[1], x[2]); if ( this->VectorMode == USE_NORMAL ) v = inNormals->GetNormal(inPtId); else v = inVectors->GetVector(inPtId); scale = math.Norm(v); if ( orient ) { // Copy Input vector for (i=0; i < numSourcePts; i++) newVectors->InsertVector(ptIncr+i,v); if ( this->Orient ) { vNew[0] = (v[0]+scale) / 2.0; vNew[1] = v[1] / 2.0; vNew[2] = v[2] / 2.0; trans.RotateWXYZ(180.0,vNew[0],vNew[1],vNew[2]); } } // determine scale factor from scalars if appropriate if ( inScalars != NULL ) { // Copy Input scalar for (i=0; i < numSourcePts; i++) newScalars->InsertScalar(ptIncr+i,scale); if ( this->ScaleMode == SCALE_BY_SCALAR ) { if ( (den = this->Range[1] - this->Range[0]) == 0.0 ) den = 1.0; scale = inScalars->GetScalar(inPtId); scale = (scale < this->Range[0] ? this->Range[0] : (scale > this->Range[1] ? this->Range[1] : scale)); scale = (scale - this->Range[0]) / den; } } // scale data if appropriate if ( scaleSource ) { scale *= this->ScaleFactor; if ( scale == 0.0 ) scale = 1.0e-10; trans.Scale(scale,scale,scale); } // multiply points and normals by resulting matrix trans.MultiplyPoints(sourcePts,newPts); if ( sourceNormals != NULL ) trans.MultiplyNormals(sourceNormals,newNormals); // Copy point data from source for (i=0; i < numSourcePts; i++) this->PointData.CopyData(pd,i,ptIncr+i); } // // Update ourselves // this->SetPoints(newPts); this->PointData.SetScalars(newScalars); this->PointData.SetVectors(newVectors); this->PointData.SetNormals(newNormals); this->Squeeze(); } // Description: // Override update method because execution can branch two ways (Input // and Source) void vlGlyph3D::Update() { // make sure input is available if ( this->Input == NULL ) { vlErrorMacro(<< "No input!"); return; } if ( this->Source == NULL ) { vlErrorMacro(<< "No source data!"); return; } // prevent chasing our tail if (this->Updating) return; this->Updating = 1; this->Input->Update(); this->Source->Update(); this->Updating = 0; if (this->Input->GetMTime() > this->GetMTime() || this->Source->GetMTime() > this->GetMTime() || this->GetMTime() > this->ExecuteTime ) { if ( this->StartMethod ) (*this->StartMethod)(this->StartMethodArg); this->Execute(); this->ExecuteTime.Modified(); if ( this->EndMethod ) (*this->EndMethod)(this->EndMethodArg); } } <commit_msg>*** empty log message ***<commit_after>/*========================================================================= Program: Visualization Library Module: Glyph3D.cc Language: C++ Date: $Date$ Version: $Revision$ This file is part of the Visualization Library. No part of this file or its contents may be copied, reproduced or altered in any way without the express written consent of the authors. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 =========================================================================*/ #include "Glyph3D.hh" #include "Trans.hh" #include "FVectors.hh" #include "FNormals.hh" #include "vlMath.hh" // Description // Construct object with scaling on, scaling mode is by scalar value, // scale factor = 1.0, the range is (0,1), orient geometry is on, and // orientation is by vector. vlGlyph3D::vlGlyph3D() { this->Source = NULL; this->Scaling = 1; this->ScaleMode = SCALE_BY_SCALAR; this->ScaleFactor = 1.0; this->Range[0] = 0.0; this->Range[1] = 1.0; this->Orient = 1; this->VectorMode = USE_VECTOR; } vlGlyph3D::~vlGlyph3D() { } void vlGlyph3D::Execute() { vlPointData *pd; vlScalars *inScalars; vlVectors *inVectors; vlNormals *inNormals, *sourceNormals; int numPts, numSourcePts, numSourceCells; int inPtId, i; vlPoints *sourcePts; vlCellArray *sourceCells; vlFloatPoints *newPts; vlFloatScalars *newScalars=NULL; vlFloatVectors *newVectors=NULL; vlFloatNormals *newNormals=NULL; float *x, *v, vNew[3]; vlTransform trans; vlCell *cell; vlIdList *cellPts; int npts, pts[MAX_CELL_SIZE]; int orient, scaleSource, ptIncr, cellId; float scale, den; vlMath math; vlDebugMacro(<<"Generating glyphs"); this->Initialize(); pd = this->Input->GetPointData(); inScalars = pd->GetScalars(); inVectors = pd->GetVectors(); inNormals = pd->GetNormals(); numPts = this->Input->GetNumberOfPoints(); // // Allocate storage for output PolyData // sourcePts = this->Source->GetPoints(); numSourcePts = sourcePts->GetNumberOfPoints(); numSourceCells = this->Source->GetNumberOfCells(); sourceNormals = this->Source->GetPointData()->GetNormals(); newPts = new vlFloatPoints(numPts*numSourcePts); if (inScalars != NULL) newScalars = new vlFloatScalars(numPts*numSourcePts); if (inVectors != NULL || inNormals != NULL ) newVectors = new vlFloatVectors(numPts*numSourcePts); if (sourceNormals != NULL) newNormals = new vlFloatNormals(numPts*numSourcePts); // Setting up for calls to PolyData::InsertNextCell() if ( (sourceCells=this->Source->GetVerts())->GetNumberOfCells() > 0 ) { this->SetVerts(new vlCellArray(numPts*sourceCells->GetSize())); } if ( (sourceCells=this->Source->GetLines())->GetNumberOfCells() > 0 ) { this->SetLines(new vlCellArray(numPts*sourceCells->GetSize())); } if ( (sourceCells=this->Source->GetPolys())->GetNumberOfCells() > 0 ) { this->SetPolys(new vlCellArray(numPts*sourceCells->GetSize())); } if ( (sourceCells=this->Source->GetStrips())->GetNumberOfCells() > 0 ) { this->SetStrips(new vlCellArray(numPts*sourceCells->GetSize())); } // // Copy (input scalars) to (output scalars) and either (input vectors or // normals) to (output vectors). All other point attributes are copied // from Source. // pd = this->Source->GetPointData(); this->PointData.CopyScalarsOff(); this->PointData.CopyVectorsOff(); this->PointData.CopyNormalsOff(); this->PointData.CopyAllocate(pd,numPts*numSourcePts); // // First copy all topology (transformation independent) // for (inPtId=0; inPtId < numPts; inPtId++) { ptIncr = inPtId * numSourcePts; for (cellId=0; cellId < numSourceCells; cellId++) { cell = this->Source->GetCell(cellId); cellPts = cell->GetPointIds(); npts = cellPts->GetNumberOfIds(); for (i=0; i < npts; i++) pts[i] = cellPts->GetId(i) + ptIncr; this->InsertNextCell(cell->GetCellType(),npts,pts); } } // // Traverse all Input points, transforming Source points and copying // point attributes. // if ( this->VectorMode == USE_VECTOR && inVectors != NULL || this->VectorMode == USE_NORMAL && inNormals != NULL ) orient = 1; else orient = 0; if ( this->Scaling && ((this->ScaleMode == SCALE_BY_SCALAR && inScalars != NULL) || (this->ScaleMode == SCALE_BY_VECTOR && (inVectors || inNormals))) ) scaleSource = 1; else scaleSource = 0; for (inPtId=0; inPtId < numPts; inPtId++) { ptIncr = inPtId * numSourcePts; trans.Identity(); // translate Source to Input point x = this->Input->GetPoint(inPtId); trans.Translate(x[0], x[1], x[2]); if ( this->VectorMode == USE_NORMAL ) v = inNormals->GetNormal(inPtId); else v = inVectors->GetVector(inPtId); scale = math.Norm(v); if ( orient ) { // Copy Input vector for (i=0; i < numSourcePts; i++) newVectors->InsertVector(ptIncr+i,v); if ( this->Orient ) { vNew[0] = (v[0]+scale) / 2.0; vNew[1] = v[1] / 2.0; vNew[2] = v[2] / 2.0; trans.RotateWXYZ(180.0,vNew[0],vNew[1],vNew[2]); } } // determine scale factor from scalars if appropriate if ( inScalars != NULL ) { // Copy Input scalar for (i=0; i < numSourcePts; i++) newScalars->InsertScalar(ptIncr+i,scale); if ( this->ScaleMode == SCALE_BY_SCALAR ) { if ( (den = this->Range[1] - this->Range[0]) == 0.0 ) den = 1.0; scale = inScalars->GetScalar(inPtId); scale = (scale < this->Range[0] ? this->Range[0] : (scale > this->Range[1] ? this->Range[1] : scale)); scale = (scale - this->Range[0]) / den; } } // scale data if appropriate if ( scaleSource ) { scale *= this->ScaleFactor; if ( scale == 0.0 ) scale = 1.0e-10; trans.Scale(scale,scale,scale); } // multiply points and normals by resulting matrix trans.MultiplyPoints(sourcePts,newPts); if ( sourceNormals != NULL ) trans.MultiplyNormals(sourceNormals,newNormals); // Copy point data from source for (i=0; i < numSourcePts; i++) this->PointData.CopyData(pd,i,ptIncr+i); } // // Update ourselves // this->SetPoints(newPts); this->PointData.SetScalars(newScalars); this->PointData.SetVectors(newVectors); this->PointData.SetNormals(newNormals); this->Squeeze(); } // Description: // Override update method because execution can branch two ways (Input // and Source) void vlGlyph3D::Update() { // make sure input is available if ( this->Input == NULL ) { vlErrorMacro(<< "No input!"); return; } if ( this->Source == NULL ) { vlErrorMacro(<< "No source data!"); return; } // prevent chasing our tail if (this->Updating) return; this->Updating = 1; this->Input->Update(); this->Source->Update(); this->Updating = 0; if (this->Input->GetMTime() > this->GetMTime() || this->Source->GetMTime() > this->GetMTime() || this->GetMTime() > this->ExecuteTime ) { if ( this->StartMethod ) (*this->StartMethod)(this->StartMethodArg); this->Execute(); this->ExecuteTime.Modified(); if ( this->EndMethod ) (*this->EndMethod)(this->EndMethodArg); } } void vlGlyph3D::PrintSelf(ostream& os, vlIndent indent) { if (this->ShouldIPrint(vlGlyph3D::GetClassName())) { vlDataSetToPolyFilter::PrintSelf(os,indent); os << indent << "Source: " << this->Source << "\n"; os << indent << "Scaling: " << (this->Scaling ? "On\n" : "Off\n"); os << indent << "Scale Mode: " << (this->ScaleMode == SCALE_BY_SCALAR ? "Scale by scalar\n" : "Scale by vector\n"); os << indent << "Scale Factor: " << this->ScaleFactor << "\n"; os << indent << "Range: (" << this->Range[0] << ", " << this->Range[1] << ")\n"; os << indent << "Orient: " << (this->Orient ? "On\n" : "Off\n"); os << indent << "Orient Mode: " << (this->VectorMode == USE_VECTOR ? "Orient by vector\n" : "Orient by normal\n"); } } <|endoftext|>
<commit_before>//===--- ASTScopePrinting.cpp - Swift Object-Oriented AST Scope -----------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// /// This file implements the printing functions of the ASTScopeImpl ontology. /// //===----------------------------------------------------------------------===// #include "swift/AST/ASTScope.h" #include "swift/AST/ASTContext.h" #include "swift/AST/ASTWalker.h" #include "swift/AST/Decl.h" #include "swift/AST/Expr.h" #include "swift/AST/Initializer.h" #include "swift/AST/LazyResolver.h" #include "swift/AST/Module.h" #include "swift/AST/ParameterList.h" #include "swift/AST/Pattern.h" #include "swift/AST/Stmt.h" #include "swift/AST/TypeRepr.h" #include "swift/Basic/STLExtras.h" #include "llvm/Support/Compiler.h" #include <algorithm> using namespace swift; using namespace ast_scope; #pragma mark dumping void ASTScopeImpl::dump() const { print(llvm::errs(), 0, false); } void ASTScopeImpl::dumpOneScopeMapLocation( std::pair<unsigned, unsigned> lineColumn) const { auto bufferID = getSourceFile()->getBufferID(); if (!bufferID) { llvm::errs() << "***No buffer, dumping all scopes***"; print(llvm::errs()); return; } SourceLoc loc = getSourceManager().getLocForLineCol( *bufferID, lineColumn.first, lineColumn.second); if (loc.isInvalid()) return; llvm::errs() << "***Scope at " << lineColumn.first << ":" << lineColumn.second << "***\n"; auto *locScope = findInnermostEnclosingScope(loc); locScope->print(llvm::errs(), 0, false, false); // Dump the AST context, too. if (auto *dc = locScope->getDeclContext().getPtrOrNull()) dc->printContext(llvm::errs()); namelookup::ASTScopeDeclGatherer gatherer; // Print the local bindings introduced by this scope. locScope->lookupLocalBindings(gatherer); if (!gatherer.getDecls().empty()) { llvm::errs() << "Local bindings: "; interleave(gatherer.getDecls().begin(), gatherer.getDecls().end(), [&](ValueDecl *value) { llvm::errs() << value->getFullName(); }, [&]() { llvm::errs() << " "; }); llvm::errs() << "\n"; } } llvm::raw_ostream &ASTScopeImpl::verificationError() const { return llvm::errs() << "ASTScopeImpl verification error in source file '" << getSourceFile()->getFilename() << "': "; } #pragma mark printing void ASTScopeImpl::print(llvm::raw_ostream &out, unsigned level, bool lastChild, bool printChildren) const { // Indent for levels 2+. if (level > 1) out.indent((level - 1) * 2); // Print child marker and leading '-' for levels 1+. if (level > 0) out << (lastChild ? '`' : '|') << '-'; out << getClassName(); if (auto *a = addressForPrinting().getPtrOrNull()) out << " " << a; printSpecifics(out); printRange(out); out << "\n"; if (printChildren) { for (unsigned i : indices(getChildren())) { getChildren()[i]->print(out, level + 1, /*lastChild=*/i == getChildren().size() - 1); } } } void ASTScopeImpl::printRange(llvm::raw_ostream &out) const { if (!cachedSourceRange) out << " (uncached)"; SourceRange range = cachedSourceRange ? getSourceRange(/*forDebugging=*/true) : getUncachedSourceRange(/*forDebugging=*/true); if (range.isInvalid()) { out << " [invalid source range]"; return; } auto startLineAndCol = getSourceManager().getLineAndColumn(range.Start); auto endLineAndCol = getSourceManager().getLineAndColumn(range.End); out << " [" << startLineAndCol.first << ":" << startLineAndCol.second << " - " << endLineAndCol.first << ":" << endLineAndCol.second << "]"; } #pragma mark printSpecifics void ASTSourceFileScope::printSpecifics( llvm::raw_ostream &out) const { out << " '" << SF->getFilename() << "'"; } NullablePtr<const void> ASTScopeImpl::addressForPrinting() const { if (auto *p = getDecl().getPtrOrNull()) return p; return nullptr; } void GTXScope::printSpecifics(llvm::raw_ostream &out) const { out << " "; if (shouldHaveABody() && !doesDeclHaveABody()) out << "<no body>"; else if (auto *n = getCorrespondingNominalTypeDecl().getPtrOrNull()) out << "'" << n->getFullName() << "'"; else out << "<no extended nominal?!>"; } void GenericParamScope::printSpecifics(llvm::raw_ostream &out) const { out << " param " << index; auto *genericTypeParamDecl = paramList->getParams()[index]; out << " '"; genericTypeParamDecl->print(out); out << "'"; } void AbstractFunctionDeclScope::printSpecifics(llvm::raw_ostream &out) const { out << " '" << decl->getFullName() << "'"; } void AbstractPatternEntryScope::printSpecifics(llvm::raw_ostream &out) const { out << " entry " << patternEntryIndex; } void StatementConditionElementPatternScope::printSpecifics( llvm::raw_ostream &out) const { pattern->print(out); } void ConditionalClauseScope::printSpecifics(llvm::raw_ostream &out) const { ASTScopeImpl::printSpecifics(out); out << " index " << index; } void SubscriptDeclScope::printSpecifics(llvm::raw_ostream &out) const { out << " "; decl->dumpRef(out); } void VarDeclScope::printSpecifics(llvm::raw_ostream &out) const { out << " "; decl->dumpRef(out); } bool GTXScope::doesDeclHaveABody() const { return false; } bool IterableTypeScope::doesDeclHaveABody() const { return getBraces().Start != getBraces().End; } <commit_msg>Better pattern printing<commit_after>//===--- ASTScopePrinting.cpp - Swift Object-Oriented AST Scope -----------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// /// This file implements the printing functions of the ASTScopeImpl ontology. /// //===----------------------------------------------------------------------===// #include "swift/AST/ASTScope.h" #include "swift/AST/ASTContext.h" #include "swift/AST/ASTWalker.h" #include "swift/AST/Decl.h" #include "swift/AST/Expr.h" #include "swift/AST/Initializer.h" #include "swift/AST/LazyResolver.h" #include "swift/AST/Module.h" #include "swift/AST/ParameterList.h" #include "swift/AST/Pattern.h" #include "swift/AST/Stmt.h" #include "swift/AST/TypeRepr.h" #include "swift/Basic/STLExtras.h" #include "llvm/Support/Compiler.h" #include <algorithm> using namespace swift; using namespace ast_scope; #pragma mark dumping void ASTScopeImpl::dump() const { print(llvm::errs(), 0, false); } void ASTScopeImpl::dumpOneScopeMapLocation( std::pair<unsigned, unsigned> lineColumn) const { auto bufferID = getSourceFile()->getBufferID(); if (!bufferID) { llvm::errs() << "***No buffer, dumping all scopes***"; print(llvm::errs()); return; } SourceLoc loc = getSourceManager().getLocForLineCol( *bufferID, lineColumn.first, lineColumn.second); if (loc.isInvalid()) return; llvm::errs() << "***Scope at " << lineColumn.first << ":" << lineColumn.second << "***\n"; auto *locScope = findInnermostEnclosingScope(loc); locScope->print(llvm::errs(), 0, false, false); // Dump the AST context, too. if (auto *dc = locScope->getDeclContext().getPtrOrNull()) dc->printContext(llvm::errs()); namelookup::ASTScopeDeclGatherer gatherer; // Print the local bindings introduced by this scope. locScope->lookupLocalBindings(gatherer); if (!gatherer.getDecls().empty()) { llvm::errs() << "Local bindings: "; interleave(gatherer.getDecls().begin(), gatherer.getDecls().end(), [&](ValueDecl *value) { llvm::errs() << value->getFullName(); }, [&]() { llvm::errs() << " "; }); llvm::errs() << "\n"; } } llvm::raw_ostream &ASTScopeImpl::verificationError() const { return llvm::errs() << "ASTScopeImpl verification error in source file '" << getSourceFile()->getFilename() << "': "; } #pragma mark printing void ASTScopeImpl::print(llvm::raw_ostream &out, unsigned level, bool lastChild, bool printChildren) const { // Indent for levels 2+. if (level > 1) out.indent((level - 1) * 2); // Print child marker and leading '-' for levels 1+. if (level > 0) out << (lastChild ? '`' : '|') << '-'; out << getClassName(); if (auto *a = addressForPrinting().getPtrOrNull()) out << " " << a; printSpecifics(out); printRange(out); out << "\n"; if (printChildren) { for (unsigned i : indices(getChildren())) { getChildren()[i]->print(out, level + 1, /*lastChild=*/i == getChildren().size() - 1); } } } void ASTScopeImpl::printRange(llvm::raw_ostream &out) const { if (!cachedSourceRange) out << " (uncached)"; SourceRange range = cachedSourceRange ? getSourceRange(/*forDebugging=*/true) : getUncachedSourceRange(/*forDebugging=*/true); if (range.isInvalid()) { out << " [invalid source range]"; return; } auto startLineAndCol = getSourceManager().getLineAndColumn(range.Start); auto endLineAndCol = getSourceManager().getLineAndColumn(range.End); out << " [" << startLineAndCol.first << ":" << startLineAndCol.second << " - " << endLineAndCol.first << ":" << endLineAndCol.second << "]"; } #pragma mark printSpecifics void ASTSourceFileScope::printSpecifics( llvm::raw_ostream &out) const { out << " '" << SF->getFilename() << "'"; } NullablePtr<const void> ASTScopeImpl::addressForPrinting() const { if (auto *p = getDecl().getPtrOrNull()) return p; return nullptr; } void GTXScope::printSpecifics(llvm::raw_ostream &out) const { out << " "; if (shouldHaveABody() && !doesDeclHaveABody()) out << "<no body>"; else if (auto *n = getCorrespondingNominalTypeDecl().getPtrOrNull()) out << "'" << n->getFullName() << "'"; else out << "<no extended nominal?!>"; } void GenericParamScope::printSpecifics(llvm::raw_ostream &out) const { out << " param " << index; auto *genericTypeParamDecl = paramList->getParams()[index]; out << " '"; genericTypeParamDecl->print(out); out << "'"; } void AbstractFunctionDeclScope::printSpecifics(llvm::raw_ostream &out) const { out << " '" << decl->getFullName() << "'"; } void AbstractPatternEntryScope::printSpecifics(llvm::raw_ostream &out) const { out << " entry " << patternEntryIndex; getPattern()->forEachVariable([&](VarDecl *vd) { out << " '" << vd->getName() << "'"; }); } void StatementConditionElementPatternScope::printSpecifics( llvm::raw_ostream &out) const { pattern->print(out); } void ConditionalClauseScope::printSpecifics(llvm::raw_ostream &out) const { ASTScopeImpl::printSpecifics(out); out << " index " << index; } void SubscriptDeclScope::printSpecifics(llvm::raw_ostream &out) const { out << " "; decl->dumpRef(out); } void VarDeclScope::printSpecifics(llvm::raw_ostream &out) const { out << " "; decl->dumpRef(out); } bool GTXScope::doesDeclHaveABody() const { return false; } bool IterableTypeScope::doesDeclHaveABody() const { return getBraces().Start != getBraces().End; } <|endoftext|>
<commit_before>//== RegionStore.cpp - Field-sensitive store model --------------*- C++ -*--==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines a basic region store model. In this model, we do have field // sensitivity. But we assume nothing about the heap shape. So recursive data // structures are largely ignored. Basically we do 1-limiting analysis. // Parameter pointers are assumed with no aliasing. Pointee objects of // parameters are created lazily. // //===----------------------------------------------------------------------===// #include "clang/Analysis/PathSensitive/MemRegion.h" #include "clang/Analysis/PathSensitive/GRState.h" #include "clang/Analysis/Analyses/LiveVariables.h" #include "llvm/ADT/ImmutableMap.h" #include "llvm/Support/Compiler.h" using namespace clang; typedef llvm::ImmutableMap<const MemRegion*, SVal> RegionBindingsTy; namespace { class VISIBILITY_HIDDEN RegionStoreManager : public StoreManager { RegionBindingsTy::Factory RBFactory; GRStateManager& StateMgr; MemRegionManager MRMgr; public: RegionStoreManager(GRStateManager& mgr) : StateMgr(mgr), MRMgr(StateMgr.getAllocator()) {} virtual ~RegionStoreManager() {} SVal Retrieve(Store S, Loc L, QualType T); Store Bind(Store St, Loc LV, SVal V); Store getInitialStore(); Store AddDecl(Store store, const VarDecl* VD, Expr* Ex, SVal InitVal, unsigned Count); Loc getVarLoc(const VarDecl* VD) { return loc::MemRegionVal(MRMgr.getVarRegion(VD)); } Loc getElementLoc(const VarDecl* VD, SVal Idx); static inline RegionBindingsTy GetRegionBindings(Store store) { return RegionBindingsTy(static_cast<const RegionBindingsTy::TreeTy*>(store)); } }; } // end anonymous namespace Loc RegionStoreManager::getElementLoc(const VarDecl* VD, SVal Idx) { MemRegion* R = MRMgr.getVarRegion(VD); ElementRegion* ER = MRMgr.getElementRegion(Idx, R); return loc::MemRegionVal(ER); } SVal RegionStoreManager::Retrieve(Store S, Loc L, QualType T) { assert(!isa<UnknownVal>(L) && "location unknown"); assert(!isa<UndefinedVal>(L) && "location undefined"); switch (L.getSubKind()) { case loc::MemRegionKind: { const MemRegion* R = cast<loc::MemRegionVal>(L).getRegion(); assert(R && "bad region"); RegionBindingsTy B(static_cast<const RegionBindingsTy::TreeTy*>(S)); RegionBindingsTy::data_type* V = B.lookup(R); return V ? *V : UnknownVal(); } case loc::SymbolValKind: return UnknownVal(); case loc::ConcreteIntKind: return UndefinedVal(); // As in BasicStoreManager. case loc::FuncValKind: return L; case loc::StringLiteralValKind: return UnknownVal(); default: assert(false && "Invalid Location"); break; } } Store RegionStoreManager::Bind(Store store, Loc LV, SVal V) { assert(LV.getSubKind() == loc::MemRegionKind); const MemRegion* R = cast<loc::MemRegionVal>(LV).getRegion(); if (!R) return store; RegionBindingsTy B = GetRegionBindings(store); return V.isUnknown() ? RBFactory.Remove(B, R).getRoot() : RBFactory.Add(B, R, V).getRoot(); } Store RegionStoreManager::getInitialStore() { typedef LiveVariables::AnalysisDataTy LVDataTy; LVDataTy& D = StateMgr.getLiveVariables().getAnalysisData(); Store St = RBFactory.GetEmptyMap().getRoot(); for (LVDataTy::decl_iterator I=D.begin_decl(), E=D.end_decl(); I != E; ++I) { NamedDecl* ND = const_cast<NamedDecl*>(I->first); if (VarDecl* VD = dyn_cast<VarDecl>(ND)) { // Punt on static variables for now. if (VD->getStorageClass() == VarDecl::Static) continue; QualType T = VD->getType(); // Only handle pointers and integers for now. if (Loc::IsLocType(T) || T->isIntegerType()) { // Initialize globals and parameters to symbolic values. // Initialize local variables to undefined. SVal X = (VD->hasGlobalStorage() || isa<ParmVarDecl>(VD) || isa<ImplicitParamDecl>(VD)) ? SVal::GetSymbolValue(StateMgr.getSymbolManager(), VD) : UndefinedVal(); St = Bind(St, getVarLoc(VD), X); } } } return St; } Store RegionStoreManager::AddDecl(Store store, const VarDecl* VD, Expr* Ex, SVal InitVal, unsigned Count) { BasicValueFactory& BasicVals = StateMgr.getBasicVals(); SymbolManager& SymMgr = StateMgr.getSymbolManager(); if (VD->hasGlobalStorage()) { // Static global variables should not be visited here. assert(!(VD->getStorageClass() == VarDecl::Static && VD->isFileVarDecl())); // Process static variables. if (VD->getStorageClass() == VarDecl::Static) { if (!Ex) { // Only handle pointer and integer static variables. QualType T = VD->getType(); if (Loc::IsLocType(T)) store = Bind(store, getVarLoc(VD), loc::ConcreteInt(BasicVals.getValue(0, T))); else if (T->isIntegerType()) store = Bind(store, getVarLoc(VD), loc::ConcreteInt(BasicVals.getValue(0, T))); else assert("ignore other types of variables"); } else { store = Bind(store, getVarLoc(VD), InitVal); } } } else { // Process local variables. QualType T = VD->getType(); if (Loc::IsLocType(T) || T->isIntegerType()) { SVal V = Ex ? InitVal : UndefinedVal(); if (Ex && InitVal.isUnknown()) { // "Conjured" symbols. SymbolID Sym = SymMgr.getConjuredSymbol(Ex, Count); V = Loc::IsLocType(Ex->getType()) ? cast<SVal>(loc::SymbolVal(Sym)) : cast<SVal>(nonloc::SymbolVal(Sym)); } store = Bind(store, getVarLoc(VD), V); } else if (T->isArrayType()) { // Only handle constant size array. if (ConstantArrayType* CAT=dyn_cast<ConstantArrayType>(T.getTypePtr())) { llvm::APInt Size = CAT->getSize(); for (llvm::APInt i = llvm::APInt::getNullValue(Size.getBitWidth()); i != Size; ++i) { nonloc::ConcreteInt Idx(BasicVals.getValue(llvm::APSInt(i))); store = Bind(store, getElementLoc(VD, Idx), UndefinedVal()); } } } else if (T->isStructureType()) { // FIXME: Implement struct initialization. } } return store; } <commit_msg>Add a bunch of getLValue* methods to RegionStore.<commit_after>//== RegionStore.cpp - Field-sensitive store model --------------*- C++ -*--==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines a basic region store model. In this model, we do have field // sensitivity. But we assume nothing about the heap shape. So recursive data // structures are largely ignored. Basically we do 1-limiting analysis. // Parameter pointers are assumed with no aliasing. Pointee objects of // parameters are created lazily. // //===----------------------------------------------------------------------===// #include "clang/Analysis/PathSensitive/MemRegion.h" #include "clang/Analysis/PathSensitive/GRState.h" #include "clang/Analysis/Analyses/LiveVariables.h" #include "llvm/ADT/ImmutableMap.h" #include "llvm/Support/Compiler.h" using namespace clang; typedef llvm::ImmutableMap<const MemRegion*, SVal> RegionBindingsTy; namespace { class VISIBILITY_HIDDEN RegionStoreManager : public StoreManager { RegionBindingsTy::Factory RBFactory; GRStateManager& StateMgr; MemRegionManager MRMgr; public: RegionStoreManager(GRStateManager& mgr) : StateMgr(mgr), MRMgr(StateMgr.getAllocator()) {} virtual ~RegionStoreManager() {} SVal getLValueVar(const GRState* St, const VarDecl* VD); SVal getLValueIvar(const GRState* St, const ObjCIvarDecl* D, SVal Base); SVal getLValueField(const GRState* St, SVal Base, const FieldDecl* D); SVal Retrieve(Store S, Loc L, QualType T); Store Bind(Store St, Loc LV, SVal V); Store getInitialStore(); Store AddDecl(Store store, const VarDecl* VD, Expr* Ex, SVal InitVal, unsigned Count); Loc getVarLoc(const VarDecl* VD) { return loc::MemRegionVal(MRMgr.getVarRegion(VD)); } Loc getElementLoc(const VarDecl* VD, SVal Idx); static inline RegionBindingsTy GetRegionBindings(Store store) { return RegionBindingsTy(static_cast<const RegionBindingsTy::TreeTy*>(store)); } }; } // end anonymous namespace Loc RegionStoreManager::getElementLoc(const VarDecl* VD, SVal Idx) { MemRegion* R = MRMgr.getVarRegion(VD); ElementRegion* ER = MRMgr.getElementRegion(Idx, R); return loc::MemRegionVal(ER); } SVal RegionStoreManager::getLValueVar(const GRState* St, const VarDecl* VD) { return loc::MemRegionVal(MRMgr.getVarRegion(VD)); } SVal RegionStoreManager::getLValueIvar(const GRState* St, const ObjCIvarDecl* D, SVal Base) { return UnknownVal(); } SVal RegionStoreManager::getLValueField(const GRState* St, SVal Base, const FieldDecl* D) { if (Base.isUnknownOrUndef()) return Base; Loc BaseL = cast<Loc>(Base); const MemRegion* BaseR = 0; switch (BaseL.getSubKind()) { case loc::MemRegionKind: BaseR = cast<loc::MemRegionVal>(BaseL).getRegion(); break; case loc::SymbolValKind: BaseR = MRMgr.getSymbolicRegion(cast<loc::SymbolVal>(&BaseL)->getSymbol()); break; case loc::GotoLabelKind: case loc::FuncValKind: // These are anormal cases. Flag an undefined value. return UndefinedVal(); case loc::ConcreteIntKind: case loc::StringLiteralValKind: // While these seem funny, this can happen through casts. // FIXME: What we should return is the field offset. For example, // add the field offset to the integer value. That way funny things // like this work properly: &(((struct foo *) 0xa)->f) return Base; default: assert("Unhandled Base."); return Base; } return loc::MemRegionVal(MRMgr.getFieldRegion(D, BaseR)); } SVal RegionStoreManager::Retrieve(Store S, Loc L, QualType T) { assert(!isa<UnknownVal>(L) && "location unknown"); assert(!isa<UndefinedVal>(L) && "location undefined"); switch (L.getSubKind()) { case loc::MemRegionKind: { const MemRegion* R = cast<loc::MemRegionVal>(L).getRegion(); assert(R && "bad region"); RegionBindingsTy B(static_cast<const RegionBindingsTy::TreeTy*>(S)); RegionBindingsTy::data_type* V = B.lookup(R); return V ? *V : UnknownVal(); } case loc::SymbolValKind: return UnknownVal(); case loc::ConcreteIntKind: return UndefinedVal(); // As in BasicStoreManager. case loc::FuncValKind: return L; case loc::StringLiteralValKind: return UnknownVal(); default: assert(false && "Invalid Location"); break; } } Store RegionStoreManager::Bind(Store store, Loc LV, SVal V) { assert(LV.getSubKind() == loc::MemRegionKind); const MemRegion* R = cast<loc::MemRegionVal>(LV).getRegion(); if (!R) return store; RegionBindingsTy B = GetRegionBindings(store); return V.isUnknown() ? RBFactory.Remove(B, R).getRoot() : RBFactory.Add(B, R, V).getRoot(); } Store RegionStoreManager::getInitialStore() { typedef LiveVariables::AnalysisDataTy LVDataTy; LVDataTy& D = StateMgr.getLiveVariables().getAnalysisData(); Store St = RBFactory.GetEmptyMap().getRoot(); for (LVDataTy::decl_iterator I=D.begin_decl(), E=D.end_decl(); I != E; ++I) { NamedDecl* ND = const_cast<NamedDecl*>(I->first); if (VarDecl* VD = dyn_cast<VarDecl>(ND)) { // Punt on static variables for now. if (VD->getStorageClass() == VarDecl::Static) continue; QualType T = VD->getType(); // Only handle pointers and integers for now. if (Loc::IsLocType(T) || T->isIntegerType()) { // Initialize globals and parameters to symbolic values. // Initialize local variables to undefined. SVal X = (VD->hasGlobalStorage() || isa<ParmVarDecl>(VD) || isa<ImplicitParamDecl>(VD)) ? SVal::GetSymbolValue(StateMgr.getSymbolManager(), VD) : UndefinedVal(); St = Bind(St, getVarLoc(VD), X); } } } return St; } Store RegionStoreManager::AddDecl(Store store, const VarDecl* VD, Expr* Ex, SVal InitVal, unsigned Count) { BasicValueFactory& BasicVals = StateMgr.getBasicVals(); SymbolManager& SymMgr = StateMgr.getSymbolManager(); if (VD->hasGlobalStorage()) { // Static global variables should not be visited here. assert(!(VD->getStorageClass() == VarDecl::Static && VD->isFileVarDecl())); // Process static variables. if (VD->getStorageClass() == VarDecl::Static) { if (!Ex) { // Only handle pointer and integer static variables. QualType T = VD->getType(); if (Loc::IsLocType(T)) store = Bind(store, getVarLoc(VD), loc::ConcreteInt(BasicVals.getValue(0, T))); else if (T->isIntegerType()) store = Bind(store, getVarLoc(VD), loc::ConcreteInt(BasicVals.getValue(0, T))); else assert("ignore other types of variables"); } else { store = Bind(store, getVarLoc(VD), InitVal); } } } else { // Process local variables. QualType T = VD->getType(); if (Loc::IsLocType(T) || T->isIntegerType()) { SVal V = Ex ? InitVal : UndefinedVal(); if (Ex && InitVal.isUnknown()) { // "Conjured" symbols. SymbolID Sym = SymMgr.getConjuredSymbol(Ex, Count); V = Loc::IsLocType(Ex->getType()) ? cast<SVal>(loc::SymbolVal(Sym)) : cast<SVal>(nonloc::SymbolVal(Sym)); } store = Bind(store, getVarLoc(VD), V); } else if (T->isArrayType()) { // Only handle constant size array. if (ConstantArrayType* CAT=dyn_cast<ConstantArrayType>(T.getTypePtr())) { llvm::APInt Size = CAT->getSize(); for (llvm::APInt i = llvm::APInt::getNullValue(Size.getBitWidth()); i != Size; ++i) { nonloc::ConcreteInt Idx(BasicVals.getValue(llvm::APSInt(i))); store = Bind(store, getElementLoc(VD, Idx), UndefinedVal()); } } } else if (T->isStructureType()) { // FIXME: Implement struct initialization. } } return store; } <|endoftext|>
<commit_before>// Scintilla source code edit control /** @file KeyMap.cxx ** Defines a mapping between keystrokes and commands. **/ // Copyright 1998-2001 by Neil Hodgson <[email protected]> // The License.txt file describes the conditions under which this software may be distributed. #include "Platform.h" #include "Scintilla.h" #include "KeyMap.h" KeyMap::KeyMap() : kmap(0), len(0), alloc(0) { for (int i = 0; MapDefault[i].key; i++) { AssignCmdKey(MapDefault[i].key, MapDefault[i].modifiers, MapDefault[i].msg); } } KeyMap::~KeyMap() { Clear(); } void KeyMap::Clear() { delete []kmap; kmap = 0; len = 0; alloc = 0; } void KeyMap::AssignCmdKey(int key, int modifiers, unsigned int msg) { if ((len+1) >= alloc) { KeyToCommand *ktcNew = new KeyToCommand[alloc + 5]; if (!ktcNew) return; for (int k=0;k<len;k++) ktcNew[k] = kmap[k]; alloc += 5; delete []kmap; kmap = ktcNew; } for (int keyIndex = 0; keyIndex < len; keyIndex++) { if ((key == kmap[keyIndex].key) && (modifiers == kmap[keyIndex].modifiers)) { kmap[keyIndex].msg = msg; return; } } kmap[len].key = key; kmap[len].modifiers = modifiers; kmap[len].msg = msg; len++; } unsigned int KeyMap::Find(int key, int modifiers) { for (int i=0; i < len; i++) { if ((key == kmap[i].key) && (modifiers == kmap[i].modifiers)) { return kmap[i].msg; } } return 0; } const KeyToCommand KeyMap::MapDefault[] = { {SCK_DOWN, SCI_NORM, SCI_LINEDOWN}, {SCK_DOWN, SCI_SHIFT, SCI_LINEDOWNEXTEND}, {SCK_DOWN, SCI_CTRL, SCI_LINESCROLLDOWN}, {SCK_UP, SCI_NORM, SCI_LINEUP}, {SCK_UP, SCI_SHIFT, SCI_LINEUPEXTEND}, {SCK_UP, SCI_CTRL, SCI_LINESCROLLUP}, {SCK_LEFT, SCI_NORM, SCI_CHARLEFT}, {SCK_LEFT, SCI_SHIFT, SCI_CHARLEFTEXTEND}, {SCK_LEFT, SCI_CTRL, SCI_WORDLEFT}, {SCK_LEFT, SCI_CSHIFT, SCI_WORDLEFTEXTEND}, {SCK_LEFT, SCI_ALT, SCI_WORDPARTLEFT}, {SCK_LEFT, SCI_ASHIFT, SCI_WORDPARTLEFTEXTEND}, {SCK_RIGHT, SCI_NORM, SCI_CHARRIGHT}, {SCK_RIGHT, SCI_SHIFT, SCI_CHARRIGHTEXTEND}, {SCK_RIGHT, SCI_CTRL, SCI_WORDRIGHT}, {SCK_RIGHT, SCI_CSHIFT, SCI_WORDRIGHTEXTEND}, {SCK_RIGHT, SCI_ALT, SCI_WORDPARTRIGHT}, {SCK_RIGHT, SCI_ASHIFT, SCI_WORDPARTRIGHTEXTEND}, {SCK_HOME, SCI_NORM, SCI_VCHOME}, {SCK_HOME, SCI_SHIFT, SCI_VCHOMEEXTEND}, {SCK_HOME, SCI_CTRL, SCI_DOCUMENTSTART}, {SCK_HOME, SCI_CSHIFT, SCI_DOCUMENTSTARTEXTEND}, {SCK_END, SCI_NORM, SCI_LINEEND}, {SCK_END, SCI_SHIFT, SCI_LINEENDEXTEND}, {SCK_END, SCI_CTRL, SCI_DOCUMENTEND}, {SCK_END, SCI_CSHIFT, SCI_DOCUMENTENDEXTEND}, {SCK_PRIOR, SCI_NORM, SCI_PAGEUP}, {SCK_PRIOR, SCI_SHIFT, SCI_PAGEUPEXTEND}, {SCK_NEXT, SCI_NORM, SCI_PAGEDOWN}, {SCK_NEXT, SCI_SHIFT, SCI_PAGEDOWNEXTEND}, {SCK_DELETE, SCI_NORM, SCI_CLEAR}, {SCK_DELETE, SCI_SHIFT, SCI_CUT}, {SCK_DELETE, SCI_CTRL, SCI_DELWORDRIGHT}, {SCK_DELETE, SCI_CSHIFT, SCI_DELLINERIGHT}, {SCK_INSERT, SCI_NORM, SCI_EDITTOGGLEOVERTYPE}, {SCK_INSERT, SCI_SHIFT, SCI_PASTE}, {SCK_INSERT, SCI_CTRL, SCI_COPY}, {SCK_ESCAPE, SCI_NORM, SCI_CANCEL}, {SCK_BACK, SCI_NORM, SCI_DELETEBACK}, {SCK_BACK, SCI_SHIFT, SCI_DELETEBACK}, {SCK_BACK, SCI_CTRL, SCI_DELWORDLEFT}, {SCK_BACK, SCI_ALT, SCI_UNDO}, {SCK_BACK, SCI_CSHIFT, SCI_DELLINELEFT}, {'Z', SCI_CTRL, SCI_UNDO}, {'Y', SCI_CTRL, SCI_REDO}, {'X', SCI_CTRL, SCI_CUT}, {'C', SCI_CTRL, SCI_COPY}, {'V', SCI_CTRL, SCI_PASTE}, {'A', SCI_CTRL, SCI_SELECTALL}, {SCK_TAB, SCI_NORM, SCI_TAB}, {SCK_TAB, SCI_SHIFT, SCI_BACKTAB}, {SCK_RETURN, SCI_NORM, SCI_NEWLINE}, {SCK_ADD, SCI_CTRL, SCI_ZOOMIN}, {SCK_SUBTRACT, SCI_CTRL, SCI_ZOOMOUT}, {SCK_DIVIDE, SCI_CTRL, SCI_SETZOOM}, //'L', SCI_CTRL, SCI_FORMFEED, {'L', SCI_CTRL, SCI_LINECUT}, {'L', SCI_CSHIFT, SCI_LINEDELETE}, {'T', SCI_CTRL, SCI_LINETRANSPOSE}, {'U', SCI_CTRL, SCI_LOWERCASE}, {'U', SCI_CSHIFT, SCI_UPPERCASE}, {0,0,0}, }; <commit_msg>Made Shift+Enter be the same as Enter.<commit_after>// Scintilla source code edit control /** @file KeyMap.cxx ** Defines a mapping between keystrokes and commands. **/ // Copyright 1998-2001 by Neil Hodgson <[email protected]> // The License.txt file describes the conditions under which this software may be distributed. #include "Platform.h" #include "Scintilla.h" #include "KeyMap.h" KeyMap::KeyMap() : kmap(0), len(0), alloc(0) { for (int i = 0; MapDefault[i].key; i++) { AssignCmdKey(MapDefault[i].key, MapDefault[i].modifiers, MapDefault[i].msg); } } KeyMap::~KeyMap() { Clear(); } void KeyMap::Clear() { delete []kmap; kmap = 0; len = 0; alloc = 0; } void KeyMap::AssignCmdKey(int key, int modifiers, unsigned int msg) { if ((len+1) >= alloc) { KeyToCommand *ktcNew = new KeyToCommand[alloc + 5]; if (!ktcNew) return; for (int k=0;k<len;k++) ktcNew[k] = kmap[k]; alloc += 5; delete []kmap; kmap = ktcNew; } for (int keyIndex = 0; keyIndex < len; keyIndex++) { if ((key == kmap[keyIndex].key) && (modifiers == kmap[keyIndex].modifiers)) { kmap[keyIndex].msg = msg; return; } } kmap[len].key = key; kmap[len].modifiers = modifiers; kmap[len].msg = msg; len++; } unsigned int KeyMap::Find(int key, int modifiers) { for (int i=0; i < len; i++) { if ((key == kmap[i].key) && (modifiers == kmap[i].modifiers)) { return kmap[i].msg; } } return 0; } const KeyToCommand KeyMap::MapDefault[] = { {SCK_DOWN, SCI_NORM, SCI_LINEDOWN}, {SCK_DOWN, SCI_SHIFT, SCI_LINEDOWNEXTEND}, {SCK_DOWN, SCI_CTRL, SCI_LINESCROLLDOWN}, {SCK_UP, SCI_NORM, SCI_LINEUP}, {SCK_UP, SCI_SHIFT, SCI_LINEUPEXTEND}, {SCK_UP, SCI_CTRL, SCI_LINESCROLLUP}, {SCK_LEFT, SCI_NORM, SCI_CHARLEFT}, {SCK_LEFT, SCI_SHIFT, SCI_CHARLEFTEXTEND}, {SCK_LEFT, SCI_CTRL, SCI_WORDLEFT}, {SCK_LEFT, SCI_CSHIFT, SCI_WORDLEFTEXTEND}, {SCK_LEFT, SCI_ALT, SCI_WORDPARTLEFT}, {SCK_LEFT, SCI_ASHIFT, SCI_WORDPARTLEFTEXTEND}, {SCK_RIGHT, SCI_NORM, SCI_CHARRIGHT}, {SCK_RIGHT, SCI_SHIFT, SCI_CHARRIGHTEXTEND}, {SCK_RIGHT, SCI_CTRL, SCI_WORDRIGHT}, {SCK_RIGHT, SCI_CSHIFT, SCI_WORDRIGHTEXTEND}, {SCK_RIGHT, SCI_ALT, SCI_WORDPARTRIGHT}, {SCK_RIGHT, SCI_ASHIFT, SCI_WORDPARTRIGHTEXTEND}, {SCK_HOME, SCI_NORM, SCI_VCHOME}, {SCK_HOME, SCI_SHIFT, SCI_VCHOMEEXTEND}, {SCK_HOME, SCI_CTRL, SCI_DOCUMENTSTART}, {SCK_HOME, SCI_CSHIFT, SCI_DOCUMENTSTARTEXTEND}, {SCK_END, SCI_NORM, SCI_LINEEND}, {SCK_END, SCI_SHIFT, SCI_LINEENDEXTEND}, {SCK_END, SCI_CTRL, SCI_DOCUMENTEND}, {SCK_END, SCI_CSHIFT, SCI_DOCUMENTENDEXTEND}, {SCK_PRIOR, SCI_NORM, SCI_PAGEUP}, {SCK_PRIOR, SCI_SHIFT, SCI_PAGEUPEXTEND}, {SCK_NEXT, SCI_NORM, SCI_PAGEDOWN}, {SCK_NEXT, SCI_SHIFT, SCI_PAGEDOWNEXTEND}, {SCK_DELETE, SCI_NORM, SCI_CLEAR}, {SCK_DELETE, SCI_SHIFT, SCI_CUT}, {SCK_DELETE, SCI_CTRL, SCI_DELWORDRIGHT}, {SCK_DELETE, SCI_CSHIFT, SCI_DELLINERIGHT}, {SCK_INSERT, SCI_NORM, SCI_EDITTOGGLEOVERTYPE}, {SCK_INSERT, SCI_SHIFT, SCI_PASTE}, {SCK_INSERT, SCI_CTRL, SCI_COPY}, {SCK_ESCAPE, SCI_NORM, SCI_CANCEL}, {SCK_BACK, SCI_NORM, SCI_DELETEBACK}, {SCK_BACK, SCI_SHIFT, SCI_DELETEBACK}, {SCK_BACK, SCI_CTRL, SCI_DELWORDLEFT}, {SCK_BACK, SCI_ALT, SCI_UNDO}, {SCK_BACK, SCI_CSHIFT, SCI_DELLINELEFT}, {'Z', SCI_CTRL, SCI_UNDO}, {'Y', SCI_CTRL, SCI_REDO}, {'X', SCI_CTRL, SCI_CUT}, {'C', SCI_CTRL, SCI_COPY}, {'V', SCI_CTRL, SCI_PASTE}, {'A', SCI_CTRL, SCI_SELECTALL}, {SCK_TAB, SCI_NORM, SCI_TAB}, {SCK_TAB, SCI_SHIFT, SCI_BACKTAB}, {SCK_RETURN, SCI_NORM, SCI_NEWLINE}, {SCK_RETURN, SCI_SHIFT, SCI_NEWLINE}, {SCK_ADD, SCI_CTRL, SCI_ZOOMIN}, {SCK_SUBTRACT, SCI_CTRL, SCI_ZOOMOUT}, {SCK_DIVIDE, SCI_CTRL, SCI_SETZOOM}, //'L', SCI_CTRL, SCI_FORMFEED, {'L', SCI_CTRL, SCI_LINECUT}, {'L', SCI_CSHIFT, SCI_LINEDELETE}, {'T', SCI_CTRL, SCI_LINETRANSPOSE}, {'U', SCI_CTRL, SCI_LOWERCASE}, {'U', SCI_CSHIFT, SCI_UPPERCASE}, {0,0,0}, }; <|endoftext|>
<commit_before>//===-- MachineInstr.cpp --------------------------------------------------===// // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/MachineInstr.h" #include "llvm/Value.h" using std::cerr; // Constructor for instructions with fixed #operands (nearly all) MachineInstr::MachineInstr(MachineOpCode _opCode, OpCodeMask _opCodeMask) : opCode(_opCode), opCodeMask(_opCodeMask), operands(TargetInstrDescriptors[_opCode].numOperands) { assert(TargetInstrDescriptors[_opCode].numOperands >= 0); } // Constructor for instructions with variable #operands MachineInstr::MachineInstr(MachineOpCode _opCode, unsigned numOperands, OpCodeMask _opCodeMask) : opCode(_opCode), opCodeMask(_opCodeMask), operands(numOperands) { } void MachineInstr::SetMachineOperandVal(unsigned int i, MachineOperand::MachineOperandType opType, Value* _val, bool isdef, bool isDefAndUse) { assert(i < operands.size()); operands[i].Initialize(opType, _val); if (isdef || TargetInstrDescriptors[opCode].resultPos == (int) i) operands[i].markDef(); if (isDefAndUse) operands[i].markDefAndUse(); } void MachineInstr::SetMachineOperandConst(unsigned int i, MachineOperand::MachineOperandType operandType, int64_t intValue) { assert(i < operands.size()); assert(TargetInstrDescriptors[opCode].resultPos != (int) i && "immed. constant cannot be defined"); operands[i].InitializeConst(operandType, intValue); } void MachineInstr::SetMachineOperandReg(unsigned int i, int regNum, bool isdef, bool isDefAndUse, bool isCCReg) { assert(i < operands.size()); operands[i].InitializeReg(regNum, isCCReg); if (isdef || TargetInstrDescriptors[opCode].resultPos == (int) i) operands[i].markDef(); if (isDefAndUse) operands[i].markDefAndUse(); regsUsed.insert(regNum); } void MachineInstr::SetRegForOperand(unsigned i, int regNum) { operands[i].setRegForValue(regNum); regsUsed.insert(regNum); } // Subsitute all occurrences of Value* oldVal with newVal in all operands // and all implicit refs. If defsOnly == true, substitute defs only. unsigned MachineInstr::substituteValue(const Value* oldVal, Value* newVal, bool defsOnly) { unsigned numSubst = 0; // Subsitute operands for (MachineInstr::val_op_iterator O = begin(), E = end(); O != E; ++O) if (*O == oldVal) if (!defsOnly || O.isDef()) { O.getMachineOperand().value = newVal; ++numSubst; } // Subsitute implicit refs for (unsigned i=0, N=implicitRefs.size(); i < N; ++i) if (implicitRefs[i] == oldVal) if (!defsOnly || implicitRefIsDefined(i)) { implicitRefs[i] = newVal; ++numSubst; } return numSubst; } void MachineInstr::dump() const { cerr << " " << *this; } static inline std::ostream &OutputValue(std::ostream &os, const Value* val) { os << "(val "; if (val && val->hasName()) return os << val->getName() << ")"; else return os << (void*) val << ")"; // print address only } std::ostream &operator<<(std::ostream& os, const MachineInstr& minstr) { os << TargetInstrDescriptors[minstr.opCode].opCodeString; for (unsigned i=0, N=minstr.getNumOperands(); i < N; i++) { os << "\t" << minstr.getOperand(i); if( minstr.operandIsDefined(i) ) os << "*"; if( minstr.operandIsDefinedAndUsed(i) ) os << "*"; } // code for printing implict references unsigned NumOfImpRefs = minstr.getNumImplicitRefs(); if( NumOfImpRefs > 0 ) { os << "\tImplicit: "; for(unsigned z=0; z < NumOfImpRefs; z++) { OutputValue(os, minstr.getImplicitRef(z)); if( minstr.implicitRefIsDefined(z)) os << "*"; if( minstr.implicitRefIsDefinedAndUsed(z)) os << "*"; os << "\t"; } } return os << "\n"; } std::ostream &operator<<(std::ostream &os, const MachineOperand &mop) { if (mop.opHiBits32()) os << "%lm("; else if (mop.opLoBits32()) os << "%lo("; else if (mop.opHiBits64()) os << "%hh("; else if (mop.opLoBits64()) os << "%hm("; switch(mop.opType) { case MachineOperand::MO_VirtualRegister: os << "%reg"; OutputValue(os, mop.getVRegValue()); break; case MachineOperand::MO_CCRegister: os << "%ccreg"; OutputValue(os, mop.getVRegValue()); break; case MachineOperand::MO_MachineRegister: os << "%reg"; os << "(" << mop.getMachineRegNum() << ")"; break; case MachineOperand::MO_SignExtendedImmed: os << (long)mop.immedVal; break; case MachineOperand::MO_UnextendedImmed: os << (long)mop.immedVal; break; case MachineOperand::MO_PCRelativeDisp: { const Value* opVal = mop.getVRegValue(); bool isLabel = isa<Function>(opVal) || isa<BasicBlock>(opVal); os << "%disp(" << (isLabel? "label " : "addr-of-val "); if (opVal->hasName()) os << opVal->getName(); else os << (const void*) opVal; os << ")"; break; } default: assert(0 && "Unrecognized operand type"); break; } if (mop.flags & (MachineOperand::HIFLAG32 | MachineOperand::LOFLAG32 | MachineOperand::HIFLAG64 | MachineOperand::LOFLAG64)) os << ")"; return os; } <commit_msg>Dump routine now writes out allocated register numbers if available.<commit_after>//===-- MachineInstr.cpp --------------------------------------------------===// // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/MachineInstr.h" #include "llvm/Value.h" using std::cerr; // Constructor for instructions with fixed #operands (nearly all) MachineInstr::MachineInstr(MachineOpCode _opCode, OpCodeMask _opCodeMask) : opCode(_opCode), opCodeMask(_opCodeMask), operands(TargetInstrDescriptors[_opCode].numOperands) { assert(TargetInstrDescriptors[_opCode].numOperands >= 0); } // Constructor for instructions with variable #operands MachineInstr::MachineInstr(MachineOpCode _opCode, unsigned numOperands, OpCodeMask _opCodeMask) : opCode(_opCode), opCodeMask(_opCodeMask), operands(numOperands) { } void MachineInstr::SetMachineOperandVal(unsigned int i, MachineOperand::MachineOperandType opType, Value* _val, bool isdef, bool isDefAndUse) { assert(i < operands.size()); operands[i].Initialize(opType, _val); if (isdef || TargetInstrDescriptors[opCode].resultPos == (int) i) operands[i].markDef(); if (isDefAndUse) operands[i].markDefAndUse(); } void MachineInstr::SetMachineOperandConst(unsigned int i, MachineOperand::MachineOperandType operandType, int64_t intValue) { assert(i < operands.size()); assert(TargetInstrDescriptors[opCode].resultPos != (int) i && "immed. constant cannot be defined"); operands[i].InitializeConst(operandType, intValue); } void MachineInstr::SetMachineOperandReg(unsigned int i, int regNum, bool isdef, bool isDefAndUse, bool isCCReg) { assert(i < operands.size()); operands[i].InitializeReg(regNum, isCCReg); if (isdef || TargetInstrDescriptors[opCode].resultPos == (int) i) operands[i].markDef(); if (isDefAndUse) operands[i].markDefAndUse(); regsUsed.insert(regNum); } void MachineInstr::SetRegForOperand(unsigned i, int regNum) { operands[i].setRegForValue(regNum); regsUsed.insert(regNum); } // Subsitute all occurrences of Value* oldVal with newVal in all operands // and all implicit refs. If defsOnly == true, substitute defs only. unsigned MachineInstr::substituteValue(const Value* oldVal, Value* newVal, bool defsOnly) { unsigned numSubst = 0; // Subsitute operands for (MachineInstr::val_op_iterator O = begin(), E = end(); O != E; ++O) if (*O == oldVal) if (!defsOnly || O.isDef()) { O.getMachineOperand().value = newVal; ++numSubst; } // Subsitute implicit refs for (unsigned i=0, N=implicitRefs.size(); i < N; ++i) if (implicitRefs[i] == oldVal) if (!defsOnly || implicitRefIsDefined(i)) { implicitRefs[i] = newVal; ++numSubst; } return numSubst; } void MachineInstr::dump() const { cerr << " " << *this; } static inline std::ostream& OutputValue(std::ostream &os, const Value* val) { os << "(val "; if (val && val->hasName()) return os << val->getName() << ")"; else return os << (void*) val << ")"; // print address only } static inline std::ostream& OutputReg(std::ostream &os, unsigned int regNum) { return os << "%mreg(" << regNum << ")"; } std::ostream &operator<<(std::ostream& os, const MachineInstr& minstr) { os << TargetInstrDescriptors[minstr.opCode].opCodeString; for (unsigned i=0, N=minstr.getNumOperands(); i < N; i++) { os << "\t" << minstr.getOperand(i); if( minstr.operandIsDefined(i) ) os << "*"; if( minstr.operandIsDefinedAndUsed(i) ) os << "*"; } // code for printing implict references unsigned NumOfImpRefs = minstr.getNumImplicitRefs(); if( NumOfImpRefs > 0 ) { os << "\tImplicit: "; for(unsigned z=0; z < NumOfImpRefs; z++) { OutputValue(os, minstr.getImplicitRef(z)); if( minstr.implicitRefIsDefined(z)) os << "*"; if( minstr.implicitRefIsDefinedAndUsed(z)) os << "*"; os << "\t"; } } return os << "\n"; } std::ostream &operator<<(std::ostream &os, const MachineOperand &mop) { if (mop.opHiBits32()) os << "%lm("; else if (mop.opLoBits32()) os << "%lo("; else if (mop.opHiBits64()) os << "%hh("; else if (mop.opLoBits64()) os << "%hm("; switch(mop.opType) { case MachineOperand::MO_VirtualRegister: os << "%reg"; OutputValue(os, mop.getVRegValue()); if (mop.hasAllocatedReg()) os << "==" << OutputReg(os, mop.getAllocatedRegNum()); break; case MachineOperand::MO_CCRegister: os << "%ccreg"; OutputValue(os, mop.getVRegValue()); if (mop.hasAllocatedReg()) os << "==" << OutputReg(os, mop.getAllocatedRegNum()); break; case MachineOperand::MO_MachineRegister: OutputReg(os, mop.getMachineRegNum()); break; case MachineOperand::MO_SignExtendedImmed: os << (long)mop.immedVal; break; case MachineOperand::MO_UnextendedImmed: os << (long)mop.immedVal; break; case MachineOperand::MO_PCRelativeDisp: { const Value* opVal = mop.getVRegValue(); bool isLabel = isa<Function>(opVal) || isa<BasicBlock>(opVal); os << "%disp(" << (isLabel? "label " : "addr-of-val "); if (opVal->hasName()) os << opVal->getName(); else os << (const void*) opVal; os << ")"; break; } default: assert(0 && "Unrecognized operand type"); break; } if (mop.flags & (MachineOperand::HIFLAG32 | MachineOperand::LOFLAG32 | MachineOperand::HIFLAG64 | MachineOperand::LOFLAG64)) os << ")"; return os; } <|endoftext|>
<commit_before>// Scintilla source code edit control /** @file LexCPP.cxx ** Lexer for C++, C, Java, and Javascript. **/ // Copyright 1998-2001 by Neil Hodgson <[email protected]> // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" static bool classifyWordCpp(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler) { char s[100]; for (unsigned int i = 0; i < end - start + 1 && i < 30; i++) { s[i] = styler[start + i]; s[i + 1] = '\0'; } bool wordIsUUID = false; char chAttr = SCE_C_IDENTIFIER; if (isdigit(s[0]) || (s[0] == '.')) chAttr = SCE_C_NUMBER; else { if (keywords.InList(s)) { chAttr = SCE_C_WORD; wordIsUUID = strcmp(s, "uuid") == 0; } } styler.ColourTo(end, chAttr); return wordIsUUID; } static bool isOKBeforeRE(char ch) { return (ch == '(') || (ch == '=') || (ch == ','); } static void ColouriseCppDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { WordList &keywords = *keywordlists[0]; styler.StartAt(startPos); bool fold = styler.GetPropertyInt("fold"); bool foldComment = styler.GetPropertyInt("fold.comment"); bool stylingWithinPreprocessor = styler.GetPropertyInt("styling.within.preprocessor"); int lineCurrent = styler.GetLine(startPos); int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK; int levelCurrent = levelPrev; int state = initStyle; if (state == SCE_C_STRINGEOL) // Does not leak onto next line state = SCE_C_DEFAULT; char chPrev = ' '; char chNext = styler[startPos]; char chPrevNonWhite = ' '; unsigned int lengthDoc = startPos + length; int visibleChars = 0; styler.StartSegment(startPos); bool lastWordWasUUID = false; for (unsigned int i = startPos; i < lengthDoc; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); if ((ch == '\r' && chNext != '\n') || (ch == '\n')) { // Trigger on CR only (Mac style) or either on LF from CR+LF (Dos/Win) or on LF alone (Unix) // Avoid triggering two times on Dos/Win // End of line if (state == SCE_C_STRINGEOL) { styler.ColourTo(i, state); state = SCE_C_DEFAULT; } if (fold) { int lev = levelPrev; if (visibleChars == 0) lev |= SC_FOLDLEVELWHITEFLAG; if ((levelCurrent > levelPrev) && (visibleChars > 0)) lev |= SC_FOLDLEVELHEADERFLAG; styler.SetLevel(lineCurrent, lev); lineCurrent++; levelPrev = levelCurrent; } visibleChars = 0; } if (!isspacechar(ch)) visibleChars++; if (styler.IsLeadByte(ch)) { chNext = styler.SafeGetCharAt(i + 2); chPrev = ' '; i += 1; continue; } if (state == SCE_C_DEFAULT) { if (ch == '@' && chNext == '\"') { styler.ColourTo(i-1, state); state = SCE_C_VERBATIM; i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } else if (iswordstart(ch) || (ch == '@')) { styler.ColourTo(i-1, state); if (lastWordWasUUID) { state = SCE_C_UUID; lastWordWasUUID = false; } else { state = SCE_C_IDENTIFIER; } } else if (ch == '/' && chNext == '*') { styler.ColourTo(i-1, state); if (foldComment) levelCurrent++; if (styler.SafeGetCharAt(i + 2) == '*' || styler.SafeGetCharAt(i + 2) == '!') // Support of Qt/Doxygen doc. style state = SCE_C_COMMENTDOC; else state = SCE_C_COMMENT; } else if (ch == '/' && chNext == '/') { styler.ColourTo(i-1, state); if (styler.SafeGetCharAt(i + 2) == '/' || styler.SafeGetCharAt(i + 2) == '!') // Support of Qt/Doxygen doc. style state = SCE_C_COMMENTLINEDOC; else state = SCE_C_COMMENTLINE; } else if (ch == '/' && isOKBeforeRE(chPrevNonWhite)) { styler.ColourTo(i-1, state); state = SCE_C_REGEX; } else if (ch == '\"') { styler.ColourTo(i-1, state); state = SCE_C_STRING; } else if (ch == '\'') { styler.ColourTo(i-1, state); state = SCE_C_CHARACTER; } else if (ch == '#' && visibleChars == 1) { // Preprocessor commands are alone on their line styler.ColourTo(i-1, state); state = SCE_C_PREPROCESSOR; // Skip whitespace between # and preprocessor word do { i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } while (isspacechar(ch) && (i < lengthDoc)); } else if (isoperator(ch)) { styler.ColourTo(i-1, state); styler.ColourTo(i, SCE_C_OPERATOR); if ((ch == '{') || (ch == '}')) { levelCurrent += (ch == '{') ? 1 : -1; } } } else if (state == SCE_C_IDENTIFIER) { if (!iswordchar(ch)) { lastWordWasUUID = classifyWordCpp(styler.GetStartSegment(), i - 1, keywords, styler); state = SCE_C_DEFAULT; if (ch == '/' && chNext == '*') { if (foldComment) levelCurrent++; if (styler.SafeGetCharAt(i + 2) == '*') state = SCE_C_COMMENTDOC; else state = SCE_C_COMMENT; } else if (ch == '/' && chNext == '/') { state = SCE_C_COMMENTLINE; } else if (ch == '\"') { state = SCE_C_STRING; } else if (ch == '\'') { state = SCE_C_CHARACTER; } else if (isoperator(ch)) { styler.ColourTo(i, SCE_C_OPERATOR); if ((ch == '{') || (ch == '}')) { levelCurrent += (ch == '{') ? 1 : -1; } } } } else { if (state == SCE_C_PREPROCESSOR) { if (stylingWithinPreprocessor) { if (isspacechar(ch)) { styler.ColourTo(i-1, state); state = SCE_C_DEFAULT; } } else { if ((ch == '\r' || ch == '\n') && !(chPrev == '\\' || chPrev == '\r')) { styler.ColourTo(i-1, state); state = SCE_C_DEFAULT; } } } else if (state == SCE_C_COMMENT) { if (ch == '/' && chPrev == '*') { if (((i > styler.GetStartSegment() + 2) || ( (initStyle == SCE_C_COMMENT) && (styler.GetStartSegment() == static_cast<unsigned int>(startPos))))) { styler.ColourTo(i, state); state = SCE_C_DEFAULT; if(foldComment) levelCurrent--; } } } else if (state == SCE_C_COMMENTDOC) { if (ch == '/' && chPrev == '*') { if (((i > styler.GetStartSegment() + 2) || ( (initStyle == SCE_C_COMMENTDOC) && (styler.GetStartSegment() == static_cast<unsigned int>(startPos))))) { styler.ColourTo(i, state); state = SCE_C_DEFAULT; if(foldComment) levelCurrent--; } } } else if (state == SCE_C_COMMENTLINE || state == SCE_C_COMMENTLINEDOC) { if (ch == '\r' || ch == '\n') { styler.ColourTo(i-1, state); state = SCE_C_DEFAULT; } } else if (state == SCE_C_STRING) { if (ch == '\\') { if (chNext == '\"' || chNext == '\'' || chNext == '\\') { i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } } else if (ch == '\"') { styler.ColourTo(i, state); state = SCE_C_DEFAULT; } else if ((chNext == '\r' || chNext == '\n') && (chPrev != '\\')) { styler.ColourTo(i-1, SCE_C_STRINGEOL); state = SCE_C_STRINGEOL; } } else if (state == SCE_C_CHARACTER) { if ((ch == '\r' || ch == '\n') && (chPrev != '\\')) { styler.ColourTo(i-1, SCE_C_STRINGEOL); state = SCE_C_STRINGEOL; } else if (ch == '\\') { if (chNext == '\"' || chNext == '\'' || chNext == '\\') { i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } } else if (ch == '\'') { styler.ColourTo(i, state); state = SCE_C_DEFAULT; } } else if (state == SCE_C_REGEX) { if (ch == '\r' || ch == '\n' || ch == '/') { styler.ColourTo(i, state); state = SCE_C_DEFAULT; } else if (ch == '\\') { // Gobble up the quoted character if (chNext == '\\' || chNext == '/') { i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } } } else if (state == SCE_C_VERBATIM) { if (ch == '\"') { if (chNext == '\"') { i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } else { styler.ColourTo(i, state); state = SCE_C_DEFAULT; } } } else if (state == SCE_C_UUID) { if (ch == '\r' || ch == '\n' || ch == ')') { styler.ColourTo(i-1, state); if (ch == ')') styler.ColourTo(i, SCE_C_OPERATOR); state = SCE_C_DEFAULT; } } } chPrev = ch; if (ch != ' ' && ch != '\t') chPrevNonWhite = ch; } styler.ColourTo(lengthDoc - 1, state); // Fill in the real level of the next line, keeping the current flags as they will be filled in later if (fold) { int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; //styler.SetLevel(lineCurrent, levelCurrent | flagsNext); styler.SetLevel(lineCurrent, levelPrev | flagsNext); } } LexerModule lmCPP(SCLEX_CPP, ColouriseCppDoc); <commit_msg>Fixed CPP lexer to work correctly when the '{' starting a fold section that is folded is deleted. This leads to the fold being unfolded which leads to reentrant styling which failed.<commit_after>// Scintilla source code edit control /** @file LexCPP.cxx ** Lexer for C++, C, Java, and Javascript. **/ // Copyright 1998-2001 by Neil Hodgson <[email protected]> // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" static bool classifyWordCpp(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler) { PLATFORM_ASSERT(end >= start); char s[100]; for (unsigned int i = 0; (i < end - start + 1) && (i < 30); i++) { s[i] = styler[start + i]; s[i + 1] = '\0'; } bool wordIsUUID = false; char chAttr = SCE_C_IDENTIFIER; if (isdigit(s[0]) || (s[0] == '.')) chAttr = SCE_C_NUMBER; else { if (keywords.InList(s)) { chAttr = SCE_C_WORD; wordIsUUID = strcmp(s, "uuid") == 0; } } styler.ColourTo(end, chAttr); return wordIsUUID; } static bool isOKBeforeRE(char ch) { return (ch == '(') || (ch == '=') || (ch == ','); } static void ColouriseCppDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { WordList &keywords = *keywordlists[0]; styler.StartAt(startPos); bool fold = styler.GetPropertyInt("fold"); bool foldComment = styler.GetPropertyInt("fold.comment"); bool stylingWithinPreprocessor = styler.GetPropertyInt("styling.within.preprocessor"); int lineCurrent = styler.GetLine(startPos); int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK; int levelCurrent = levelPrev; int state = initStyle; if (state == SCE_C_STRINGEOL) // Does not leak onto next line state = SCE_C_DEFAULT; char chPrev = ' '; char chNext = styler[startPos]; char chPrevNonWhite = ' '; unsigned int lengthDoc = startPos + length; int visibleChars = 0; styler.StartSegment(startPos); bool lastWordWasUUID = false; for (unsigned int i = startPos; i < lengthDoc; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); if (atEOL) { // Trigger on CR only (Mac style) or either on LF from CR+LF (Dos/Win) or on LF alone (Unix) // Avoid triggering two times on Dos/Win // End of line if (state == SCE_C_STRINGEOL) { styler.ColourTo(i, state); state = SCE_C_DEFAULT; } } if (styler.IsLeadByte(ch)) { chNext = styler.SafeGetCharAt(i + 2); chPrev = ' '; i += 1; continue; } if (state == SCE_C_DEFAULT) { if (ch == '@' && chNext == '\"') { styler.ColourTo(i - 1, state); state = SCE_C_VERBATIM; i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } else if (iswordstart(ch) || (ch == '@')) { styler.ColourTo(i - 1, state); if (lastWordWasUUID) { state = SCE_C_UUID; lastWordWasUUID = false; } else { state = SCE_C_IDENTIFIER; } } else if (ch == '/' && chNext == '*') { styler.ColourTo(i - 1, state); if (foldComment) levelCurrent++; if (styler.SafeGetCharAt(i + 2) == '*' || styler.SafeGetCharAt(i + 2) == '!') // Support of Qt/Doxygen doc. style state = SCE_C_COMMENTDOC; else state = SCE_C_COMMENT; } else if (ch == '/' && chNext == '/') { styler.ColourTo(i - 1, state); if (styler.SafeGetCharAt(i + 2) == '/' || styler.SafeGetCharAt(i + 2) == '!') // Support of Qt/Doxygen doc. style state = SCE_C_COMMENTLINEDOC; else state = SCE_C_COMMENTLINE; } else if (ch == '/' && isOKBeforeRE(chPrevNonWhite)) { styler.ColourTo(i - 1, state); state = SCE_C_REGEX; } else if (ch == '\"') { styler.ColourTo(i - 1, state); state = SCE_C_STRING; } else if (ch == '\'') { styler.ColourTo(i - 1, state); state = SCE_C_CHARACTER; } else if (ch == '#' && visibleChars == 0) { // Preprocessor commands are alone on their line styler.ColourTo(i - 1, state); state = SCE_C_PREPROCESSOR; // Skip whitespace between # and preprocessor word do { i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } while (isspacechar(ch) && (i < lengthDoc)); } else if (isoperator(ch)) { styler.ColourTo(i-1, state); styler.ColourTo(i, SCE_C_OPERATOR); if ((ch == '{') || (ch == '}')) { levelCurrent += (ch == '{') ? 1 : -1; } } } else if (state == SCE_C_IDENTIFIER) { if (!iswordchar(ch)) { lastWordWasUUID = classifyWordCpp(styler.GetStartSegment(), i - 1, keywords, styler); state = SCE_C_DEFAULT; if (ch == '/' && chNext == '*') { if (foldComment) levelCurrent++; if (styler.SafeGetCharAt(i + 2) == '*') state = SCE_C_COMMENTDOC; else state = SCE_C_COMMENT; } else if (ch == '/' && chNext == '/') { state = SCE_C_COMMENTLINE; } else if (ch == '\"') { state = SCE_C_STRING; } else if (ch == '\'') { state = SCE_C_CHARACTER; } else if (isoperator(ch)) { styler.ColourTo(i, SCE_C_OPERATOR); if ((ch == '{') || (ch == '}')) { levelCurrent += (ch == '{') ? 1 : -1; } } } } else { if (state == SCE_C_PREPROCESSOR) { if (stylingWithinPreprocessor) { if (isspacechar(ch)) { styler.ColourTo(i - 1, state); state = SCE_C_DEFAULT; } } else { if (atEOL && (chPrev != '\\')) { styler.ColourTo(i - 1, state); state = SCE_C_DEFAULT; } } } else if (state == SCE_C_COMMENT) { if (ch == '/' && chPrev == '*') { if (((i > styler.GetStartSegment() + 2) || ( (initStyle == SCE_C_COMMENT) && (styler.GetStartSegment() == static_cast<unsigned int>(startPos))))) { styler.ColourTo(i, state); state = SCE_C_DEFAULT; if (foldComment) levelCurrent--; } } } else if (state == SCE_C_COMMENTDOC) { if (ch == '/' && chPrev == '*') { if (((i > styler.GetStartSegment() + 2) || ( (initStyle == SCE_C_COMMENTDOC) && (styler.GetStartSegment() == static_cast<unsigned int>(startPos))))) { styler.ColourTo(i, state); state = SCE_C_DEFAULT; if (foldComment) levelCurrent--; } } } else if (state == SCE_C_COMMENTLINE || state == SCE_C_COMMENTLINEDOC) { if (ch == '\r' || ch == '\n') { styler.ColourTo(i - 1, state); state = SCE_C_DEFAULT; } } else if (state == SCE_C_STRING) { if (ch == '\\') { if (chNext == '\"' || chNext == '\'' || chNext == '\\') { i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } } else if (ch == '\"') { styler.ColourTo(i, state); state = SCE_C_DEFAULT; } else if ((chNext == '\r' || chNext == '\n') && (chPrev != '\\')) { styler.ColourTo(i - 1, SCE_C_STRINGEOL); state = SCE_C_STRINGEOL; } } else if (state == SCE_C_CHARACTER) { if ((ch == '\r' || ch == '\n') && (chPrev != '\\')) { styler.ColourTo(i - 1, SCE_C_STRINGEOL); state = SCE_C_STRINGEOL; } else if (ch == '\\') { if (chNext == '\"' || chNext == '\'' || chNext == '\\') { i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } } else if (ch == '\'') { styler.ColourTo(i, state); state = SCE_C_DEFAULT; } } else if (state == SCE_C_REGEX) { if (ch == '\r' || ch == '\n' || ch == '/') { styler.ColourTo(i, state); state = SCE_C_DEFAULT; } else if (ch == '\\') { // Gobble up the quoted character if (chNext == '\\' || chNext == '/') { i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } } } else if (state == SCE_C_VERBATIM) { if (ch == '\"') { if (chNext == '\"') { i++; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); } else { styler.ColourTo(i, state); state = SCE_C_DEFAULT; } } } else if (state == SCE_C_UUID) { if (ch == '\r' || ch == '\n' || ch == ')') { styler.ColourTo(i - 1, state); if (ch == ')') styler.ColourTo(i, SCE_C_OPERATOR); state = SCE_C_DEFAULT; } } } if (atEOL) { if (fold) { int lev = levelPrev; if (visibleChars == 0) lev |= SC_FOLDLEVELWHITEFLAG; if ((levelCurrent > levelPrev) && (visibleChars > 0)) lev |= SC_FOLDLEVELHEADERFLAG; if (lev != styler.LevelAt(lineCurrent)) { styler.ColourTo(i, state); styler.Flush(); styler.SetLevel(lineCurrent, lev); styler.StartAt(i + 1); } lineCurrent++; levelPrev = levelCurrent; } visibleChars = 0; } if (!isspacechar(ch)) visibleChars++; chPrev = ch; if (ch != ' ' && ch != '\t') chPrevNonWhite = ch; } styler.ColourTo(lengthDoc - 1, state); // Fill in the real level of the next line, keeping the current flags as they will be filled in later if (fold) { int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK; //styler.SetLevel(lineCurrent, levelCurrent | flagsNext); styler.SetLevel(lineCurrent, levelPrev | flagsNext); } } LexerModule lmCPP(SCLEX_CPP, ColouriseCppDoc); <|endoftext|>
<commit_before>#include "Matrix.h" /* =========================================================================================== // Basic constructor ============================================================================================*/ Matrix::Matrix() : m_iColumns(1) , m_iRows(1) , m_pdData(NULL) { bool bSuccess = Init(m_iRows, m_iColumns); assert(bSuccess); } /* =========================================================================================== // Matrix constructor ============================================================================================*/ Matrix::Matrix(int row, int col) : m_iColumns(col) , m_iRows(row) , m_pdData(NULL) { bool bSuccess = Init(m_iRows, m_iColumns); assert(bSuccess); } /* =========================================================================================== // Matrix copy constructor ============================================================================================*/ Matrix::Matrix(const Matrix& other) : m_iColumns(other.GetColumns()) , m_iRows(other.GetRows()) , m_pdData(NULL) { bool bSuccess = Init(m_iRows, m_iColumns); assert(bSuccess); memcpy(m_pdData, other.m_pdData, sizeof(double)*m_iColumns*m_iRows); } Matrix::~Matrix() { if(m_pdData != NULL) { delete [] m_pdData; m_pdData = NULL; } } /* =========================================================================================== // Initialize the matrix ============================================================================================*/ bool Matrix::Init(int row, int col) { if(m_pdData!=NULL) { delete [] m_pdData; m_pdData = NULL; } m_iRows = row; m_iColumns = col; int size = row*col; if(size<0) { return false; } m_pdData = new double[size]; if(m_pdData == NULL) { return false; } memset(m_pdData, 0, sizeof(double)*size); return true; } bool Matrix::JacobiEigenv(double* dblEigenValue, Matrix& mtxEigenVector, int nMaxIt, double eps) { int i = 0, j = 0, p = 0, q = 0, u = 0, w = 0, t = 0, s = 0, l = 0; double fm = 0.0, cn = 0.0, sn = 0.0, omega = 0.0, x = 0.0, y = 0.0, d = 0.0; if(!mtxEigenVector.Init(m_iColumns, m_iRows)) { return false; } l = 1; for(i=0;i<=m_iColumns-1;i++) { mtxEigenVector.m_pdData[i*m_iColumns]=1.0; for(j=0;j<=m_iColumns-1;j++) { if(i!=j) { mtxEigenVector.m_pdData[i*m_iColumns] = 0.0; } } } while(true) { fm = 0.0; for(i=0;i<=m_iColumns-1;i++) { for(j=0;j<=i-1;j++) { d=fabs(m_pdData[i*m_iColumns+j]); if((i!=j) && (d>fm)) { fm=d; p=i; q=j; } } } // Error smaller than the eps, use values on the diagnoal as Eigen value and return true if(fm<eps) { for(i=0;i<m_iColumns;++i) { dblEigenValue[i] = GetElement(i, i); } return true; } if(l>nMaxIt) { return false; } l++; u = p*m_iColumns+q; w = p*m_iColumns+p; t = q*m_iColumns+p; s = q*m_iColumns+q; x = -m_pdData[u]; y = (m_pdData[s]-m_pdData[w])/2.0; omega = x/sqrt(x*x + y*y); if(y<0.0) { omega = -omega; } sn = 1.0 + sqrt(1.0-omega*omega); sn = omega/sqrt(2.0*sn); cn = sqrt(1.0 - sn*sn); fm = m_pdData[w]; m_pdData[w] = fm*cn*cn + m_pdData[s]*sn*sn + m_pdData[u]*omega; m_pdData[s] = fm*sn*sn + m_pdData[s]*cn*cn - m_pdData[u]*omega; m_pdData[u] = 0.0; m_pdData[t] = 0.0; for(j=0;j<=m_iColumns-1;j++) { if((j!=p) && (j!=q)) { u = p*m_iColumns+j; w = q*m_iColumns+j; fm = m_pdData[u]; m_pdData[u] = fm*cn + m_pdData[w]*sn; m_pdData[w] = fm*sn + m_pdData[w]*cn; } } for(i=0;i<=m_iColumns-1;i++) { if((i!=p) && (i!=q)) { u = i*m_iColumns+p; w = i*m_iColumns+q; fm = m_pdData[u]; m_pdData[u] = fm*cn + m_pdData[w]*sn; m_pdData[w] = -fm*sn + m_pdData[w]*cn; } } for(i=0;i<m_iColumns-1;i++) { u = i*m_iColumns+p; w = i*m_iColumns+q; fm = mtxEigenVector.m_pdData[u]; mtxEigenVector.m_pdData[u] = fm*cn + mtxEigenVector.m_pdData[w]*sn; mtxEigenVector.m_pdData[w] = -fm*sn + mtxEigenVector.m_pdData[w]*cn; } } for(i=0;i<m_iColumns;++i) { dblEigenValue[i] = GetElement(i,i); } return true; } Matrix& Matrix::operator=(const Matrix& other) { if(&other!=this) { bool bSuccess = Init(other.GetRows(), other.GetColumns()); assert(bSuccess); memcpy(m_pdData, other.m_pdData, sizeof(double)*m_iColumns*m_iRows); } return *this; } bool Matrix::operator==(const Matrix& other) const { int i = 0, j = 0; if(m_iColumns!=other.GetColumns() || m_iRows!=other.GetRows()) { return false; } for(i=0;i<m_iRows;++i) { for(j=0;j<m_iColumns;++j) { if(GetElement(i, j) != other.GetElement(i, j)) { return false; } } } return true; } bool Matrix::operator!=(const Matrix& other) const { return !(*this == other); } Matrix Matrix::operator+(const Matrix& other) const { int i = 0, j = 0; assert(m_iColumns == other.GetColumns() && m_iRows == other.GetRows()); Matrix result(*this); for(i=0;i<m_iRows;++i) { for(j=0;j<m_iColumns;++j) { result.SetElement(i, j, result.GetElement(i,j) + other.GetElement(i,j)); } } return result; } Matrix Matrix::operator-(const Matrix& other) const { int i = 0, j = 0; assert(m_iColumns == other.GetColumns() && m_iRows == other.GetRows()); Matrix result(*this); for(i=0;i<m_iRows;++i) { for(j=0;j<m_iColumns;++j) { result.SetElement(i, j, result.GetElement(i, j) - other.GetElement(i, j)); } } return result; } Matrix Matrix::operator*(double value) const { int i = 0, j = 0; Matrix result(*this); for(i=0;i<m_iRows;++i) { for(j=0;j<m_iColumns;++j) { result.SetElement(i, j, result.GetElement(i, j)*value); } } return result; } Matrix Matrix::operator*(const Matrix& other) const { assert(m_iColumns == other.GetRows()); int i = 0, j = 0, k = 0; Matrix result(m_iRows, other.GetColumns()); double value; for(i=0;i<result.GetRows();++i) { for(j=0;j<other.GetColumns();++j) { value = 0.0; for(k=0;k<m_iColumns;++k) { value += GetElement(i, k)*other.GetElement(k, j); } result.SetElement(i, j, value); } } return result; } /* =========================================================================================== // Get data pointer of the matrix ============================================================================================*/ void Matrix::SetData(double* value) { memset(m_pdData, 0, sizeof(double)*m_iColumns*m_iRows); memcpy(m_pdData, value, sizeof(double)*m_iColumns*m_iRows); } /* =========================================================================================== // Get data pointer of the matrix ============================================================================================*/ double* Matrix::GetData() const { return m_pdData; } bool Matrix::SetElement(int row, int col, double value) { if(col<0 || col>=m_iColumns || row<0 || row>=m_iRows) { return false; } if(m_pdData == NULL) { return false; } m_pdData[col+row*m_iColumns] = value; } double Matrix::GetElement(int row, int col) const { if(col<0 || col>=m_iColumns || row<0 || row>=m_iRows) { return false; } if(m_pdData == NULL) { return false; } return m_pdData[col+row*m_iColumns]; } int Matrix::GetColumns() const { return m_iColumns; } int Matrix::GetRows() const { return m_iRows; } <commit_msg>Oops... Small fix for Matrix<commit_after>#include "Matrix.h" /* =========================================================================================== // Basic constructor ============================================================================================*/ Matrix::Matrix() : m_iColumns(1) , m_iRows(1) , m_pdData(NULL) { bool bSuccess = Init(m_iRows, m_iColumns); assert(bSuccess); } /* =========================================================================================== // Matrix constructor ============================================================================================*/ Matrix::Matrix(int row, int col) : m_iColumns(col) , m_iRows(row) , m_pdData(NULL) { bool bSuccess = Init(m_iRows, m_iColumns); assert(bSuccess); } /* =========================================================================================== // Matrix copy constructor ============================================================================================*/ Matrix::Matrix(const Matrix& other) : m_iColumns(other.GetColumns()) , m_iRows(other.GetRows()) , m_pdData(NULL) { bool bSuccess = Init(m_iRows, m_iColumns); assert(bSuccess); memcpy(m_pdData, other.m_pdData, sizeof(double)*m_iColumns*m_iRows); } Matrix::~Matrix() { if(m_pdData != NULL) { delete [] m_pdData; m_pdData = NULL; } } /* =========================================================================================== // Initialize the matrix ============================================================================================*/ bool Matrix::Init(int row, int col) { if(m_pdData!=NULL) { delete [] m_pdData; m_pdData = NULL; } m_iRows = row; m_iColumns = col; int size = row*col; if(size<0) { return false; } m_pdData = new double[size]; if(m_pdData == NULL) { return false; } memset(m_pdData, 0, sizeof(double)*size); return true; } bool Matrix::JacobiEigenv(double* dblEigenValue, Matrix& mtxEigenVector, int nMaxIt, double eps) { int i = 0, j = 0, p = 0, q = 0, u = 0, w = 0, t = 0, s = 0, l = 0; double fm = 0.0, cn = 0.0, sn = 0.0, omega = 0.0, x = 0.0, y = 0.0, d = 0.0; if(!mtxEigenVector.Init(m_iColumns, m_iRows)) { return false; } l = 1; for(i=0;i<=m_iColumns-1;i++) { mtxEigenVector.m_pdData[i*m_iColumns]=1.0; for(j=0;j<=m_iColumns-1;j++) { if(i!=j) { mtxEigenVector.m_pdData[i*m_iColumns] = 0.0; } } } while(true) { fm = 0.0; for(i=0;i<=m_iColumns-1;i++) { for(j=0;j<=i-1;j++) { d=fabs(m_pdData[i*m_iColumns+j]); if((i!=j) && (d>fm)) { fm=d; p=i; q=j; } } } // Error smaller than the eps, use values on the diagnoal as Eigen value and return true if(fm<eps) { for(i=0;i<m_iColumns;++i) { dblEigenValue[i] = GetElement(i, i); } return true; } if(l>nMaxIt) { return false; } l++; u = p*m_iColumns+q; w = p*m_iColumns+p; t = q*m_iColumns+p; s = q*m_iColumns+q; x = -m_pdData[u]; y = (m_pdData[s]-m_pdData[w])/2.0; omega = x/sqrt(x*x + y*y); if(y<0.0) { omega = -omega; } sn = 1.0 + sqrt(1.0-omega*omega); sn = omega/sqrt(2.0*sn); cn = sqrt(1.0 - sn*sn); fm = m_pdData[w]; m_pdData[w] = fm*cn*cn + m_pdData[s]*sn*sn + m_pdData[u]*omega; m_pdData[s] = fm*sn*sn + m_pdData[s]*cn*cn - m_pdData[u]*omega; m_pdData[u] = 0.0; m_pdData[t] = 0.0; for(j=0;j<=m_iColumns-1;j++) { if((j!=p) && (j!=q)) { u = p*m_iColumns+j; w = q*m_iColumns+j; fm = m_pdData[u]; m_pdData[u] = fm*cn + m_pdData[w]*sn; m_pdData[w] = fm*sn + m_pdData[w]*cn; } } for(i=0;i<=m_iColumns-1;i++) { if((i!=p) && (i!=q)) { u = i*m_iColumns+p; w = i*m_iColumns+q; fm = m_pdData[u]; m_pdData[u] = fm*cn + m_pdData[w]*sn; m_pdData[w] = -fm*sn + m_pdData[w]*cn; } } for(i=0;i<m_iColumns-1;i++) { u = i*m_iColumns+p; w = i*m_iColumns+q; fm = mtxEigenVector.m_pdData[u]; mtxEigenVector.m_pdData[u] = fm*cn + mtxEigenVector.m_pdData[w]*sn; mtxEigenVector.m_pdData[w] = -fm*sn + mtxEigenVector.m_pdData[w]*cn; } } for(i=0;i<m_iColumns;++i) { dblEigenValue[i] = GetElement(i,i); } return true; } Matrix& Matrix::operator=(const Matrix& other) { if(&other!=this) { bool bSuccess = Init(other.GetRows(), other.GetColumns()); assert(bSuccess); memcpy(m_pdData, other.m_pdData, sizeof(double)*m_iColumns*m_iRows); } return *this; } bool Matrix::operator==(const Matrix& other) const { int i = 0, j = 0; if(m_iColumns!=other.GetColumns() || m_iRows!=other.GetRows()) { return false; } for(i=0;i<m_iRows;++i) { for(j=0;j<m_iColumns;++j) { if(GetElement(i, j) != other.GetElement(i, j)) { return false; } } } return true; } bool Matrix::operator!=(const Matrix& other) const { return !(*this == other); } Matrix Matrix::operator+(const Matrix& other) const { int i = 0, j = 0; assert(m_iColumns == other.GetColumns() && m_iRows == other.GetRows()); Matrix result(*this); for(i=0;i<m_iRows;++i) { for(j=0;j<m_iColumns;++j) { result.SetElement(i, j, result.GetElement(i,j) + other.GetElement(i,j)); } } return result; } Matrix Matrix::operator-(const Matrix& other) const { int i = 0, j = 0; assert(m_iColumns == other.GetColumns() && m_iRows == other.GetRows()); Matrix result(*this); for(i=0;i<m_iRows;++i) { for(j=0;j<m_iColumns;++j) { result.SetElement(i, j, result.GetElement(i, j) - other.GetElement(i, j)); } } return result; } Matrix Matrix::operator*(double value) const { int i = 0, j = 0; Matrix result(*this); for(i=0;i<m_iRows;++i) { for(j=0;j<m_iColumns;++j) { result.SetElement(i, j, result.GetElement(i, j)*value); } } return result; } Matrix Matrix::operator*(const Matrix& other) const { assert(m_iColumns == other.GetRows()); int i = 0, j = 0, k = 0; Matrix result(m_iRows, other.GetColumns()); double value; for(i=0;i<result.GetRows();++i) { for(j=0;j<other.GetColumns();++j) { value = 0.0; for(k=0;k<m_iColumns;++k) { value += GetElement(i, k)*other.GetElement(k, j); } result.SetElement(i, j, value); } } return result; } /* =========================================================================================== // Get data pointer of the matrix ============================================================================================*/ void Matrix::SetData(double* value) { memset(m_pdData, 0, sizeof(double)*m_iColumns*m_iRows); memcpy(m_pdData, value, sizeof(double)*m_iColumns*m_iRows); } /* =========================================================================================== // Get data pointer of the matrix ============================================================================================*/ double* Matrix::GetData() const { return m_pdData; } bool Matrix::SetElement(int row, int col, double value) { if(col<0 || col>=m_iColumns || row<0 || row>=m_iRows) { return false; } if(m_pdData == NULL) { return false; } m_pdData[col+row*m_iColumns] = value; return true; } double Matrix::GetElement(int row, int col) const { if(col<0 || col>=m_iColumns || row<0 || row>=m_iRows) { return false; } if(m_pdData == NULL) { return false; } return m_pdData[col+row*m_iColumns]; } int Matrix::GetColumns() const { return m_iColumns; } int Matrix::GetRows() const { return m_iRows; } <|endoftext|>
<commit_before>#include <Refal2.h> namespace Refal2 { //----------------------------------------------------------------------------- // CProgram CProgram::CProgram( int numberOfModules ) : modulesSize( numberOfModules ), modules( new CRuntimeModule[modulesSize] ) { assert( modulesSize > 0 ); assert( modules != nullptr ); } CProgram::~CProgram() { delete[] modules; } CRuntimeModule& CProgram::Module( TRuntimeModuleId moduleId ) { assert( moduleId >= 0 && moduleId < modulesSize ); return modules[moduleId]; } //----------------------------------------------------------------------------- // Standart embedded functions static void notImplemented( const char* name ) { std::cout << "external function `" << name << "` not implemented yet."; } static bool embeddedPrint() { notImplemented( __FUNCTION__ ); return false; } static bool embeddedPrintm() { notImplemented( __FUNCTION__ ); return false; } static bool embeddedProut() { notImplemented( __FUNCTION__ ); return false; } static bool embeddedProutm() { notImplemented( __FUNCTION__ ); return false; } //----------------------------------------------------------------------------- // CStandartEmbeddedFunctionData struct CStandartEmbeddedFunctionData { const char* const externalName; const TEmbeddedFunctionPtr EmbeddedFunction; }; const CStandartEmbeddedFunctionData standartEmbeddedFunctions[] = { { "print", embeddedPrint }, { "printm", embeddedPrintm }, { "prout", embeddedProut }, { "proutm", embeddedProutm }, { nullptr, nullptr } }; //----------------------------------------------------------------------------- // CGlobalFunctionData class CGlobalFunctionData { public: CGlobalFunctionData() : preparatoryFunction( nullptr ), embeddedFunction( nullptr ), runtimeModuleId( 0 ) { } bool IsEmbeddedFunction() const { return ( embeddedFunction != nullptr ); } bool IsPreparatoryFunction() const { return ( preparatoryFunction != nullptr ); } bool IsDefined() const { return ( IsEmbeddedFunction() || IsPreparatoryFunction() ); } void SetPreparatoryFunction( const CPreparatoryFunction* const _preparatoryFunction, const TRuntimeModuleId _runtimeModuleId ) { assert( !IsDefined() ); assert( _preparatoryFunction != nullptr ); preparatoryFunction = _preparatoryFunction; runtimeModuleId = _runtimeModuleId; } const CPreparatoryFunction* PreparatoryFunction() const { assert( IsPreparatoryFunction() ); return preparatoryFunction; } const TRuntimeModuleId RuntimeModuleId() const { assert( IsPreparatoryFunction() ); return runtimeModuleId; } void SetEmbeddedFunction( const TEmbeddedFunctionPtr _embeddedFunction ) { assert( !IsDefined() ); assert( _embeddedFunction != nullptr ); embeddedFunction = _embeddedFunction; } TEmbeddedFunctionPtr EmbeddedFunction() const { assert( IsEmbeddedFunction() ); return embeddedFunction; } private: const CPreparatoryFunction* preparatoryFunction; TEmbeddedFunctionPtr embeddedFunction; TRuntimeModuleId runtimeModuleId; }; //----------------------------------------------------------------------------- // CExternalFunctionData class CExternalFunctionData { public: CExternalFunctionData( int _globalIndex, CPreparatoryFunction* _preparatoryFunction ) : globalIndex( _globalIndex ), preparatoryFunction( _preparatoryFunction ) { assert( globalIndex >= 0 ); assert( preparatoryFunction != nullptr ); } int GlobalIndex() const { return globalIndex; } CPreparatoryFunction* PreparatoryFunction() const { return preparatoryFunction; } private: int globalIndex; CPreparatoryFunction* preparatoryFunction; }; //----------------------------------------------------------------------------- // CPreparatoryRuntimeFunction class CPreparatoryRuntimeFunction : public CRuntimeFunction { public: CPreparatoryRuntimeFunction( CPreparatoryFunctionPtr& function, const TRuntimeModuleId moduleId ); CPreparatoryFunction* PreparatoryFunction() const { return function.get(); } TRuntimeModuleId RuntimeModuleId() const { return moduleId; } private: const CPreparatoryFunctionPtr function; const TRuntimeModuleId moduleId; static TRuntimeFunctionType convertType( const CPreparatoryFunction* const function ); }; CPreparatoryRuntimeFunction::CPreparatoryRuntimeFunction( CPreparatoryFunctionPtr& _function, const TRuntimeModuleId _moduleId ) : CRuntimeFunction( convertType( _function.get() ) ), function( _function.release() ), moduleId( _moduleId ) { } TRuntimeFunctionType CPreparatoryRuntimeFunction::convertType( const CPreparatoryFunction* const function ) { assert( function != nullptr ); switch( function->GetType() ) { case PFT_Ordinary: return RFT_Ordinary; case PFT_Empty: return RFT_Empty; case PFT_External: return RFT_External; case PFT_Declared: case PFT_Defined: case PFT_Compiled: case PFT_Embedded: default: break; } assert( false ); return RFT_Empty; } //----------------------------------------------------------------------------- // CInternalProgramBuilder class CInternalProgramBuilder { public: static CProgramPtr Build( CModuleDataVector& modules, CErrorsHelper& errors ); private: CErrorsHelper& errors; typedef std::vector<CExternalFunctionData> CExternals; CExternals externals; CDictionary<CGlobalFunctionData, std::string> globals; CProgramPtr program; CInternalProgramBuilder( CErrorsHelper& _errors, int numberOfModules ); void addFunction( CPreparatoryFunction* function, const TRuntimeModuleId runtimeModuleId ); void addFunctions( const CModuleData& module, CRuntimeModule& runtimeModule, const TRuntimeModuleId runtimeModuleId ); void collect( CModuleDataVector& modules ); void check(); void compile(); void link(); }; //----------------------------------------------------------------------------- CInternalProgramBuilder::CInternalProgramBuilder( CErrorsHelper& _errors, int numberOfModules ) : errors( _errors ), program( new CProgram( numberOfModules ) ) { assert( static_cast<bool>( program ) ); for( int i = 0; standartEmbeddedFunctions[i].EmbeddedFunction != nullptr; i++ ) { assert( standartEmbeddedFunctions[i].externalName != nullptr ); std::string externalName = standartEmbeddedFunctions[i].externalName; assert( !externalName.empty() ); const int globalIndex = globals.AddKey( externalName ); CGlobalFunctionData& global = globals.GetData( globalIndex ); global.SetEmbeddedFunction( standartEmbeddedFunctions[i].EmbeddedFunction ); } } CProgramPtr CInternalProgramBuilder::Build( CModuleDataVector& modules, CErrorsHelper& errors ) { assert( !errors.HasErrors() ); assert( !modules.empty() ); CInternalProgramBuilder builder( errors, modules.size() ); builder.collect( modules ); if( errors.HasErrors() ) { return nullptr; } builder.check(); if( errors.HasErrors() ) { return nullptr; } builder.compile(); assert( !errors.HasErrors() ); builder.link(); assert( !errors.HasErrors() ); return CProgramPtr( builder.program.release() ); } void CInternalProgramBuilder::addFunction( CPreparatoryFunction* function, const TRuntimeModuleId runtimeModuleId ) { const bool isExternal = function->IsExternal(); const bool isGlobal = function->IsEntry(); if( !( isExternal || isGlobal ) ) { return; } const int globalIndex = globals.AddKey( function->ExternalName() ); if( isGlobal ) { assert( !isExternal ); CGlobalFunctionData& global = globals.GetData( globalIndex ); if( global.IsDefined() ) { std::ostringstream stringStream; stringStream << "function with external name `" << function->ExternalNameToken().word << "` already defined in program"; errors.Error( stringStream.str() ); } else { global.SetPreparatoryFunction( function, runtimeModuleId ); } } else { assert( isExternal ); externals.push_back( CExternalFunctionData( globalIndex, function ) ); } } void CInternalProgramBuilder::addFunctions( const CModuleData& module, CRuntimeModule& runtimeModule, const TRuntimeModuleId runtimeModuleId ) { const CPreparatoryFunctions& functions = module.Functions; for( int i = 0; i < functions.Size(); i++ ) { CPreparatoryFunctionPtr function( functions.GetData( i ).release() ); addFunction( function.get(), runtimeModuleId ); CRuntimeFunctionPtr& runtimeFunction = runtimeModule.Functions.GetData( runtimeModule.Functions.AddKey( function->Name() ) ); assert( !static_cast<bool>( runtimeFunction ) ); runtimeFunction.reset( new CPreparatoryRuntimeFunction( function, runtimeModuleId ) ); } } void CInternalProgramBuilder::collect( CModuleDataVector& modules ) { TRuntimeModuleId currentModuleId = 0; for( CModuleDataVector::const_iterator module = modules.begin(); module != modules.end(); ++module ) { addFunctions( *( *module ), program->Module( currentModuleId ), currentModuleId ); currentModuleId++; } modules.clear(); } void CInternalProgramBuilder::check() { for( CExternals::const_iterator function = externals.begin(); function != externals.end(); ++function ) { const int globalIndex = function->GlobalIndex(); if( !globals.GetData( globalIndex ).IsDefined() ) { std::ostringstream stringStream; stringStream << "function with external name `" << globals.GetKey( globalIndex ) << "` was not defined in program"; errors.Error( stringStream.str() ); } } } void CInternalProgramBuilder::compile() { CFunctionCompiler compiler; for( int moduleId = 0; moduleId < program->NumberOfModules(); moduleId++ ) { const CRuntimeFunctions& functions = program->Module( moduleId ).Functions; for( int i = 0; i < functions.Size(); i++ ) { const CRuntimeFunction& runtimeFunction = *functions.GetData( i ); const CPreparatoryRuntimeFunction& function = static_cast< const CPreparatoryRuntimeFunction&>( runtimeFunction ); if( function.PreparatoryFunction()->IsOrdinary() ) { function.PreparatoryFunction()->Compile( compiler ); } } } } void CInternalProgramBuilder::link() { for( CExternals::iterator function = externals.begin(); function != externals.end(); ++function ) { function->PreparatoryFunction(); const int globalIndex = function->GlobalIndex(); const CGlobalFunctionData& global = globals.GetData( globalIndex ); assert( global.IsDefined() ); if( global.IsEmbeddedFunction() ) { function->PreparatoryFunction()->SetEmbedded( global.EmbeddedFunction() ); } else { assert( !global.IsPreparatoryFunction() ); function->PreparatoryFunction()->Link( *global.PreparatoryFunction() ); } } for( int moduleId = 0; moduleId < program->NumberOfModules(); moduleId++ ) { const CRuntimeFunctions& functions = program->Module( moduleId ).Functions; for( int i = 0; i < functions.Size(); i++ ) { const CPreparatoryRuntimeFunction& function = static_cast< CPreparatoryRuntimeFunction&>( *functions.GetData( i ) ); const CPreparatoryFunction* preparatoryFunction = function.PreparatoryFunction(); CRuntimeFunctionPtr newRuntimeFunction; switch( function.Type() ) { case RFT_Empty: assert( preparatoryFunction->IsEmpty() ); newRuntimeFunction.reset( new CEmptyFunction ); break; case RFT_Embedded: assert( preparatoryFunction->IsEmbedded() ); newRuntimeFunction.reset( new CEmbeddedFunction( preparatoryFunction->EmbeddedFunction() ) ); break; case RFT_External: assert( preparatoryFunction->IsEmpty() || preparatoryFunction->IsEmbedded() || preparatoryFunction->IsOrdinary() ); // todo: --- newRuntimeFunction.reset( new CExternalFunction( 0, function.RuntimeModuleId() ) ); break; case RFT_Ordinary: assert( preparatoryFunction->IsOrdinary() ); // todo: --- newRuntimeFunction.reset( new COrdinaryFunction( 0 ) ); break; default: assert( false ); break; } } } } //----------------------------------------------------------------------------- // CProgramBuilder CProgramBuilder::CProgramBuilder( IErrorHandler* errorHandler ) : CFunctionBuilder( errorHandler ) { Reset(); } void CProgramBuilder::Reset() { CFunctionBuilder::Reset(); } void CProgramBuilder::AddModule( CModuleDataPtr& module ) { modules.push_back( CModuleDataPtr( module.release() ) ); } void CProgramBuilder::BuildProgram() { CInternalProgramBuilder::Build( modules, *this ); } //----------------------------------------------------------------------------- } // end of namespace Refal2 <commit_msg>error fixes<commit_after>#include <Refal2.h> namespace Refal2 { //----------------------------------------------------------------------------- // CProgram CProgram::CProgram( int numberOfModules ) : modulesSize( numberOfModules ), modules( new CRuntimeModule[modulesSize] ) { assert( modulesSize > 0 ); assert( modules != nullptr ); } CProgram::~CProgram() { delete[] modules; } CRuntimeModule& CProgram::Module( TRuntimeModuleId moduleId ) { assert( moduleId >= 0 && moduleId < modulesSize ); return modules[moduleId]; } //----------------------------------------------------------------------------- // Standart embedded functions static void notImplemented( const char* name ) { std::cout << "external function `" << name << "` not implemented yet."; } static bool embeddedPrint() { notImplemented( __FUNCTION__ ); return false; } static bool embeddedPrintm() { notImplemented( __FUNCTION__ ); return false; } static bool embeddedProut() { notImplemented( __FUNCTION__ ); return false; } static bool embeddedProutm() { notImplemented( __FUNCTION__ ); return false; } //----------------------------------------------------------------------------- // CStandartEmbeddedFunctionData struct CStandartEmbeddedFunctionData { const char* const externalName; const TEmbeddedFunctionPtr EmbeddedFunction; }; const CStandartEmbeddedFunctionData standartEmbeddedFunctions[] = { { "print", embeddedPrint }, { "printm", embeddedPrintm }, { "prout", embeddedProut }, { "proutm", embeddedProutm }, { nullptr, nullptr } }; //----------------------------------------------------------------------------- // CGlobalFunctionData class CGlobalFunctionData { public: CGlobalFunctionData() : preparatoryFunction( nullptr ), embeddedFunction( nullptr ), runtimeModuleId( 0 ) { } bool IsEmbeddedFunction() const { return ( embeddedFunction != nullptr ); } bool IsPreparatoryFunction() const { return ( preparatoryFunction != nullptr ); } bool IsDefined() const { return ( IsEmbeddedFunction() || IsPreparatoryFunction() ); } void SetPreparatoryFunction( const CPreparatoryFunction* const _preparatoryFunction, const TRuntimeModuleId _runtimeModuleId ) { assert( !IsDefined() ); assert( _preparatoryFunction != nullptr ); preparatoryFunction = _preparatoryFunction; runtimeModuleId = _runtimeModuleId; } const CPreparatoryFunction* PreparatoryFunction() const { assert( IsPreparatoryFunction() ); return preparatoryFunction; } const TRuntimeModuleId RuntimeModuleId() const { assert( IsPreparatoryFunction() ); return runtimeModuleId; } void SetEmbeddedFunction( const TEmbeddedFunctionPtr _embeddedFunction ) { assert( !IsDefined() ); assert( _embeddedFunction != nullptr ); embeddedFunction = _embeddedFunction; } TEmbeddedFunctionPtr EmbeddedFunction() const { assert( IsEmbeddedFunction() ); return embeddedFunction; } private: const CPreparatoryFunction* preparatoryFunction; TEmbeddedFunctionPtr embeddedFunction; TRuntimeModuleId runtimeModuleId; }; //----------------------------------------------------------------------------- // CExternalFunctionData class CExternalFunctionData { public: CExternalFunctionData( int _globalIndex, CPreparatoryFunction* _preparatoryFunction ) : globalIndex( _globalIndex ), preparatoryFunction( _preparatoryFunction ) { assert( globalIndex >= 0 ); assert( preparatoryFunction != nullptr ); } int GlobalIndex() const { return globalIndex; } CPreparatoryFunction* PreparatoryFunction() const { return preparatoryFunction; } private: int globalIndex; CPreparatoryFunction* preparatoryFunction; }; //----------------------------------------------------------------------------- // CPreparatoryRuntimeFunction class CPreparatoryRuntimeFunction : public CRuntimeFunction { public: CPreparatoryRuntimeFunction( CPreparatoryFunctionPtr& function, const TRuntimeModuleId moduleId ); CPreparatoryFunction* PreparatoryFunction() const { return function.get(); } TRuntimeModuleId RuntimeModuleId() const { return moduleId; } private: const CPreparatoryFunctionPtr function; const TRuntimeModuleId moduleId; static TRuntimeFunctionType convertType( const CPreparatoryFunction* const function ); }; CPreparatoryRuntimeFunction::CPreparatoryRuntimeFunction( CPreparatoryFunctionPtr& _function, const TRuntimeModuleId _moduleId ) : CRuntimeFunction( convertType( _function.get() ) ), function( _function.release() ), moduleId( _moduleId ) { } TRuntimeFunctionType CPreparatoryRuntimeFunction::convertType( const CPreparatoryFunction* const function ) { assert( function != nullptr ); switch( function->GetType() ) { case PFT_Ordinary: return RFT_Ordinary; case PFT_Empty: return RFT_Empty; case PFT_External: return RFT_External; case PFT_Declared: case PFT_Defined: case PFT_Compiled: case PFT_Embedded: default: break; } assert( false ); return RFT_Empty; } //----------------------------------------------------------------------------- // CInternalProgramBuilder class CInternalProgramBuilder { public: static CProgramPtr Build( CModuleDataVector& modules, CErrorsHelper& errors ); private: CErrorsHelper& errors; typedef std::vector<CExternalFunctionData> CExternals; CExternals externals; CDictionary<CGlobalFunctionData, std::string> globals; CProgramPtr program; CInternalProgramBuilder( CErrorsHelper& _errors, int numberOfModules ); void addFunction( CPreparatoryFunction* function, const TRuntimeModuleId runtimeModuleId ); void addFunctions( const CModuleData& module, CRuntimeModule& runtimeModule, const TRuntimeModuleId runtimeModuleId ); void collect( CModuleDataVector& modules ); void check(); void compile(); void link(); }; //----------------------------------------------------------------------------- CInternalProgramBuilder::CInternalProgramBuilder( CErrorsHelper& _errors, int numberOfModules ) : errors( _errors ), program( new CProgram( numberOfModules ) ) { assert( static_cast<bool>( program ) ); for( int i = 0; standartEmbeddedFunctions[i].EmbeddedFunction != nullptr; i++ ) { assert( standartEmbeddedFunctions[i].externalName != nullptr ); std::string externalName = standartEmbeddedFunctions[i].externalName; assert( !externalName.empty() ); const int globalIndex = globals.AddKey( externalName ); CGlobalFunctionData& global = globals.GetData( globalIndex ); global.SetEmbeddedFunction( standartEmbeddedFunctions[i].EmbeddedFunction ); } } CProgramPtr CInternalProgramBuilder::Build( CModuleDataVector& modules, CErrorsHelper& errors ) { assert( !errors.HasErrors() ); assert( !modules.empty() ); CInternalProgramBuilder builder( errors, modules.size() ); builder.collect( modules ); if( errors.HasErrors() ) { return nullptr; } builder.check(); if( errors.HasErrors() ) { return nullptr; } builder.compile(); assert( !errors.HasErrors() ); builder.link(); assert( !errors.HasErrors() ); return CProgramPtr( builder.program.release() ); } void CInternalProgramBuilder::addFunction( CPreparatoryFunction* function, const TRuntimeModuleId runtimeModuleId ) { const bool isExternal = function->IsExternal(); const bool isGlobal = function->IsEntry(); if( !( isExternal || isGlobal ) ) { return; } const int globalIndex = globals.AddKey( function->ExternalName() ); if( isGlobal ) { assert( !isExternal ); CGlobalFunctionData& global = globals.GetData( globalIndex ); if( global.IsDefined() ) { std::ostringstream stringStream; stringStream << "function with external name `" << function->ExternalNameToken().word << "` already defined in program"; errors.Error( stringStream.str() ); } else { global.SetPreparatoryFunction( function, runtimeModuleId ); } } else { assert( isExternal ); externals.push_back( CExternalFunctionData( globalIndex, function ) ); } } void CInternalProgramBuilder::addFunctions( const CModuleData& module, CRuntimeModule& runtimeModule, const TRuntimeModuleId runtimeModuleId ) { const CPreparatoryFunctions& functions = module.Functions; for( int i = 0; i < functions.Size(); i++ ) { CPreparatoryFunctionPtr function( functions.GetData( i ).release() ); addFunction( function.get(), runtimeModuleId ); CRuntimeFunctionPtr& runtimeFunction = runtimeModule.Functions.GetData( runtimeModule.Functions.AddKey( function->Name() ) ); assert( !static_cast<bool>( runtimeFunction ) ); runtimeFunction.reset( new CPreparatoryRuntimeFunction( function, runtimeModuleId ) ); } } void CInternalProgramBuilder::collect( CModuleDataVector& modules ) { TRuntimeModuleId currentModuleId = 0; for( CModuleDataVector::const_iterator module = modules.begin(); module != modules.end(); ++module ) { addFunctions( *( *module ), program->Module( currentModuleId ), currentModuleId ); currentModuleId++; } modules.clear(); } void CInternalProgramBuilder::check() { for( CExternals::const_iterator function = externals.begin(); function != externals.end(); ++function ) { const int globalIndex = function->GlobalIndex(); if( !globals.GetData( globalIndex ).IsDefined() ) { std::ostringstream stringStream; stringStream << "function with external name `" << globals.GetKey( globalIndex ) << "` was not defined in program"; errors.Error( stringStream.str() ); } } } void CInternalProgramBuilder::compile() { CFunctionCompiler compiler; for( int moduleId = 0; moduleId < program->NumberOfModules(); moduleId++ ) { const CRuntimeFunctions& functions = program->Module( moduleId ).Functions; for( int i = 0; i < functions.Size(); i++ ) { const CRuntimeFunction& runtimeFunction = *functions.GetData( i ); const CPreparatoryRuntimeFunction& function = static_cast< const CPreparatoryRuntimeFunction&>( runtimeFunction ); if( function.PreparatoryFunction()->IsOrdinary() ) { function.PreparatoryFunction()->Compile( compiler ); } } } } void CInternalProgramBuilder::link() { for( CExternals::iterator function = externals.begin(); function != externals.end(); ++function ) { function->PreparatoryFunction(); const int globalIndex = function->GlobalIndex(); const CGlobalFunctionData& global = globals.GetData( globalIndex ); assert( global.IsDefined() ); if( global.IsEmbeddedFunction() ) { function->PreparatoryFunction()->SetEmbedded( global.EmbeddedFunction() ); } else { assert( !global.IsPreparatoryFunction() ); function->PreparatoryFunction()->Link( *global.PreparatoryFunction() ); } } for( int moduleId = 0; moduleId < program->NumberOfModules(); moduleId++ ) { const CRuntimeFunctions& functions = program->Module( moduleId ).Functions; for( int i = 0; i < functions.Size(); i++ ) { const CPreparatoryRuntimeFunction& function = static_cast< CPreparatoryRuntimeFunction&>( *functions.GetData( i ) ); const CPreparatoryFunction* preparatoryFunction = function.PreparatoryFunction(); CRuntimeFunctionPtr newRuntimeFunction; switch( function.Type() ) { case RFT_Empty: assert( preparatoryFunction->IsEmpty() ); newRuntimeFunction.reset( new CEmptyFunction ); break; case RFT_Embedded: assert( preparatoryFunction->IsEmbedded() ); newRuntimeFunction.reset( new CEmbeddedFunction( preparatoryFunction->EmbeddedFunction() ) ); break; case RFT_External: assert( preparatoryFunction->IsEmpty() || preparatoryFunction->IsEmbedded() || preparatoryFunction->IsCompiled() ); // todo: --- //newRuntimeFunction.reset( new CExternalFunction( 0, // function.RuntimeModuleId() ) ); break; case RFT_Ordinary: assert( preparatoryFunction->IsCompiled() ); // todo: --- //newRuntimeFunction.reset( new COrdinaryFunction( 0 ) ); break; default: assert( false ); break; } functions.GetData( i ).reset( newRuntimeFunction.release() ); } } } //----------------------------------------------------------------------------- // CProgramBuilder CProgramBuilder::CProgramBuilder( IErrorHandler* errorHandler ) : CFunctionBuilder( errorHandler ) { Reset(); } void CProgramBuilder::Reset() { CFunctionBuilder::Reset(); } void CProgramBuilder::AddModule( CModuleDataPtr& module ) { modules.push_back( CModuleDataPtr( module.release() ) ); } void CProgramBuilder::BuildProgram() { CInternalProgramBuilder::Build( modules, *this ); } //----------------------------------------------------------------------------- } // end of namespace Refal2 <|endoftext|>
<commit_before>#include <nan.h> #include "Packers.h" #include "Memory.h" namespace streampunk { void dumpPGroupRaw (uint8_t *pgbuf, uint32_t width, uint32_t numLines) { uint8_t *buf = pgbuf; for (uint32_t i = 0; i < numLines; ++i) { printf("PGroup Line%02d: %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x\n", i, buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6], buf[7], buf[8], buf[9]); buf += width * 5 / 2; } } void dump420P (uint8_t *buf, uint32_t width, uint32_t height, uint32_t numLines) { uint8_t *ybuf = buf; uint8_t *ubuf = ybuf + width * height; uint8_t *vbuf = ubuf + width * height / 4; for (uint32_t i = 0; i < numLines; ++i) { printf("420P Line %02d: Y: %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x\n", i, ybuf[0], ybuf[1], ybuf[2], ybuf[3], ybuf[4], ybuf[5], ybuf[6], ybuf[7]); ybuf += width; if ((i & 1) == 0) { printf("420P Line %02d: U: %02x, %02x, %02x, %02x\n", i, ubuf[0], ubuf[1], ubuf[2], ubuf[3]); printf("420P Line %02d: V: %02x, %02x, %02x, %02x\n", i, vbuf[0], vbuf[1], vbuf[2], vbuf[3]); ubuf += width / 2; vbuf += width / 2; } } } Packers::Packers(uint32_t srcWidth, uint32_t srcHeight, const std::string& srcFmtCode, uint32_t srcBytes, const std::string& dstFmtCode) : mSrcWidth(srcWidth), mSrcHeight(srcHeight), mSrcFmtCode(srcFmtCode), mSrcBytes(srcBytes), mDstFmtCode(dstFmtCode) { if (0 == mSrcFmtCode.compare("4175")) { uint32_t srcPitchBytes = mSrcWidth * 5 / 2; if (srcPitchBytes * mSrcHeight > mSrcBytes) { Nan::ThrowError("insufficient source buffer for conversion\n"); } } else if (0 == mSrcFmtCode.compare("v210")) { uint32_t srcPitchBytes = ((mSrcWidth + 47) / 48) * 48 * 8 / 3; if ((mSrcWidth * 5 / 2) * mSrcHeight > mSrcBytes) { Nan::ThrowError("insufficient source buffer for conversion\n"); } } else Nan::ThrowError("unsupported source packing type\n"); if (0 != mDstFmtCode.compare("420P")) Nan::ThrowError("unsupported destination packing type\n"); } std::shared_ptr<Memory> Packers::concatBuffers(const tBufVec& bufVec) { std::shared_ptr<Memory> concatBuf = Memory::makeNew(mSrcBytes); uint32_t concatBufOffset = 0; for (tBufVec::const_iterator it = bufVec.begin(); it != bufVec.end(); ++it) { const uint8_t* buf = it->first; uint32_t len = it->second; memcpy (concatBuf->buf() + concatBufOffset, buf, len); concatBufOffset += len; } return concatBuf; } std::shared_ptr<Memory> Packers::convert(std::shared_ptr<Memory> srcBuf) { // only 420P supported currently uint32_t lumaBytes = mSrcWidth * mSrcHeight; std::shared_ptr<Memory> convertBuf = Memory::makeNew(lumaBytes * 3 / 2); if (0 == mSrcFmtCode.compare("4175")) { convertPGroupto420P (srcBuf->buf(), convertBuf->buf()); } else if (0 == mSrcFmtCode.compare("v210")) { convertV210to420P (srcBuf->buf(), convertBuf->buf()); } return convertBuf; } // private void Packers::convertPGroupto420P (const uint8_t *const srcBuf, uint8_t *const dstBuf) { uint32_t srcPitchBytes = mSrcWidth * 5 / 2; uint32_t dstLumaPitchBytes = mSrcWidth; uint32_t dstChromaPitchBytes = mSrcWidth / 2; uint32_t dstLumaPlaneBytes = mSrcWidth * mSrcHeight; const uint8_t *srcLine = srcBuf; uint8_t *dstYLine = dstBuf; uint8_t *dstULine = dstBuf + dstLumaPlaneBytes; uint8_t *dstVLine = dstBuf + dstLumaPlaneBytes + dstLumaPlaneBytes / 4; for (uint32_t y=0; y<mSrcHeight; ++y) { const uint8_t *srcBytes = srcLine; uint8_t *dstYBytes = dstYLine; uint8_t *dstUBytes = dstULine; uint8_t *dstVBytes = dstVLine; bool evenLine = (y & 1) == 0; // read 5 source bytes / 2 source pixels at a time for (uint32_t x=0; x<mSrcWidth; x+=2) { uint8_t s0 = srcBytes[0]; uint8_t s1 = srcBytes[1]; uint8_t s2 = srcBytes[2]; uint8_t s3 = srcBytes[3]; uint8_t s4 = srcBytes[4]; srcBytes += 5; dstYBytes[0] = ((s1 & 0x3f) << 2) | ((s2 & 0xc0) >> 6); dstYBytes[1] = ((s3 & 0x03) << 6) | ((s4 & 0xfc) >> 2); dstYBytes += 2; // chroma interp between lines dstUBytes[0] = evenLine ? s0 : (s0 + dstUBytes[0]) >> 1; dstUBytes += 1; uint32_t v0 = ((s2 & 0x0f) << 4) | ((s3 & 0xf0) >> 4); dstVBytes[0] = evenLine ? v0 : (v0 + dstVBytes[0]) >> 1; dstVBytes += 1; } srcLine += srcPitchBytes; dstYLine += dstLumaPitchBytes; if (evenLine) { dstULine += dstChromaPitchBytes; dstVLine += dstChromaPitchBytes; } } } void Packers::convertV210to420P (const uint8_t *const srcBuf, uint8_t *const dstBuf) { // V210: https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG8-V210__4_2_2_COMPRESSION_TYPE // 420P: https://en.wikipedia.org/wiki/YUV uint32_t srcPitchBytes = ((mSrcWidth + 47) / 48) * 48 * 8 / 3; uint32_t dstLumaPitchBytes = mSrcWidth; uint32_t dstChromaPitchBytes = mSrcWidth / 2; uint32_t dstLumaPlaneBytes = mSrcWidth * mSrcHeight; const uint8_t *srcLine = srcBuf; uint8_t *dstYLine = dstBuf; uint8_t *dstULine = dstBuf + dstLumaPlaneBytes; uint8_t *dstVLine = dstBuf + dstLumaPlaneBytes + dstLumaPlaneBytes / 4; for (uint32_t y=0; y<mSrcHeight; ++y) { uint32_t *srcInts = (uint32_t *)srcLine; uint8_t *dstYBytes = dstYLine; uint8_t *dstUBytes = dstULine; uint8_t *dstVBytes = dstVLine; bool evenLine = (y & 1) == 0; // read 4 source ints / 6 source pixels at a time for (uint32_t x=0; x<mSrcWidth; x+=6) { uint32_t s0 = srcInts[0]; uint32_t s1 = srcInts[1]; uint32_t s2 = srcInts[2]; uint32_t s3 = srcInts[3]; srcInts += 4; dstYBytes[0] = (s0 >> 12) & 0xff; dstYBytes[1] = (s1 >> 2) & 0xff; dstYBytes[2] = (s1 >> 22) & 0xff; dstYBytes[3] = (s2 >> 12) & 0xff; dstYBytes[4] = (s3 >> 2) & 0xff; dstYBytes[5] = (s3 >> 22) & 0xff; dstYBytes += 6; dstUBytes[0] = evenLine ? ((s0 >> 2) & 0xff) : (((s0 >> 2) & 0xff) + dstUBytes[0]) >> 1; dstUBytes[1] = evenLine ? ((s1 >> 12) & 0xff) : (((s1 >> 12) & 0xff) + dstUBytes[1]) >> 1; dstUBytes[2] = evenLine ? ((s2 >> 22) & 0xff) : (((s2 >> 22) & 0xff) + dstUBytes[2]) >> 1; dstUBytes += 3; dstVBytes[0] = evenLine ? ((s0 >> 22) & 0xff) : (((s0 >> 22) & 0xff) + dstVBytes[0]) >> 1; dstVBytes[1] = evenLine ? ((s2 >> 2) & 0xff) : (((s2 >> 2) & 0xff) + dstVBytes[1]) >> 1; dstVBytes[2] = evenLine ? ((s3 >> 12) & 0xff) : (((s3 >> 12) & 0xff) + dstVBytes[2]) >> 1; dstVBytes += 3; } srcLine += srcPitchBytes; dstYLine += dstLumaPitchBytes; if (evenLine) { dstULine += dstChromaPitchBytes; dstVLine += dstChromaPitchBytes; } } } } // namespace streampunk <commit_msg>Fix buffer size check<commit_after>#include <nan.h> #include "Packers.h" #include "Memory.h" namespace streampunk { void dumpPGroupRaw (uint8_t *pgbuf, uint32_t width, uint32_t numLines) { uint8_t *buf = pgbuf; for (uint32_t i = 0; i < numLines; ++i) { printf("PGroup Line%02d: %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x\n", i, buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6], buf[7], buf[8], buf[9]); buf += width * 5 / 2; } } void dump420P (uint8_t *buf, uint32_t width, uint32_t height, uint32_t numLines) { uint8_t *ybuf = buf; uint8_t *ubuf = ybuf + width * height; uint8_t *vbuf = ubuf + width * height / 4; for (uint32_t i = 0; i < numLines; ++i) { printf("420P Line %02d: Y: %02x, %02x, %02x, %02x, %02x, %02x, %02x, %02x\n", i, ybuf[0], ybuf[1], ybuf[2], ybuf[3], ybuf[4], ybuf[5], ybuf[6], ybuf[7]); ybuf += width; if ((i & 1) == 0) { printf("420P Line %02d: U: %02x, %02x, %02x, %02x\n", i, ubuf[0], ubuf[1], ubuf[2], ubuf[3]); printf("420P Line %02d: V: %02x, %02x, %02x, %02x\n", i, vbuf[0], vbuf[1], vbuf[2], vbuf[3]); ubuf += width / 2; vbuf += width / 2; } } } Packers::Packers(uint32_t srcWidth, uint32_t srcHeight, const std::string& srcFmtCode, uint32_t srcBytes, const std::string& dstFmtCode) : mSrcWidth(srcWidth), mSrcHeight(srcHeight), mSrcFmtCode(srcFmtCode), mSrcBytes(srcBytes), mDstFmtCode(dstFmtCode) { if (0 == mSrcFmtCode.compare("4175")) { uint32_t srcPitchBytes = mSrcWidth * 5 / 2; if (srcPitchBytes * mSrcHeight > mSrcBytes) { Nan::ThrowError("insufficient source buffer for conversion\n"); } } else if (0 == mSrcFmtCode.compare("v210")) { uint32_t srcPitchBytes = ((mSrcWidth + 47) / 48) * 48 * 8 / 3; if (srcPitchBytes * mSrcHeight > mSrcBytes) { Nan::ThrowError("insufficient source buffer for conversion\n"); } } else Nan::ThrowError("unsupported source packing type\n"); if (0 != mDstFmtCode.compare("420P")) Nan::ThrowError("unsupported destination packing type\n"); } std::shared_ptr<Memory> Packers::concatBuffers(const tBufVec& bufVec) { std::shared_ptr<Memory> concatBuf = Memory::makeNew(mSrcBytes); uint32_t concatBufOffset = 0; for (tBufVec::const_iterator it = bufVec.begin(); it != bufVec.end(); ++it) { const uint8_t* buf = it->first; uint32_t len = it->second; memcpy (concatBuf->buf() + concatBufOffset, buf, len); concatBufOffset += len; } return concatBuf; } std::shared_ptr<Memory> Packers::convert(std::shared_ptr<Memory> srcBuf) { // only 420P supported currently uint32_t lumaBytes = mSrcWidth * mSrcHeight; std::shared_ptr<Memory> convertBuf = Memory::makeNew(lumaBytes * 3 / 2); if (0 == mSrcFmtCode.compare("4175")) { convertPGroupto420P (srcBuf->buf(), convertBuf->buf()); } else if (0 == mSrcFmtCode.compare("v210")) { convertV210to420P (srcBuf->buf(), convertBuf->buf()); } return convertBuf; } // private void Packers::convertPGroupto420P (const uint8_t *const srcBuf, uint8_t *const dstBuf) { uint32_t srcPitchBytes = mSrcWidth * 5 / 2; uint32_t dstLumaPitchBytes = mSrcWidth; uint32_t dstChromaPitchBytes = mSrcWidth / 2; uint32_t dstLumaPlaneBytes = mSrcWidth * mSrcHeight; const uint8_t *srcLine = srcBuf; uint8_t *dstYLine = dstBuf; uint8_t *dstULine = dstBuf + dstLumaPlaneBytes; uint8_t *dstVLine = dstBuf + dstLumaPlaneBytes + dstLumaPlaneBytes / 4; for (uint32_t y=0; y<mSrcHeight; ++y) { const uint8_t *srcBytes = srcLine; uint8_t *dstYBytes = dstYLine; uint8_t *dstUBytes = dstULine; uint8_t *dstVBytes = dstVLine; bool evenLine = (y & 1) == 0; // read 5 source bytes / 2 source pixels at a time for (uint32_t x=0; x<mSrcWidth; x+=2) { uint8_t s0 = srcBytes[0]; uint8_t s1 = srcBytes[1]; uint8_t s2 = srcBytes[2]; uint8_t s3 = srcBytes[3]; uint8_t s4 = srcBytes[4]; srcBytes += 5; dstYBytes[0] = ((s1 & 0x3f) << 2) | ((s2 & 0xc0) >> 6); dstYBytes[1] = ((s3 & 0x03) << 6) | ((s4 & 0xfc) >> 2); dstYBytes += 2; // chroma interp between lines dstUBytes[0] = evenLine ? s0 : (s0 + dstUBytes[0]) >> 1; dstUBytes += 1; uint32_t v0 = ((s2 & 0x0f) << 4) | ((s3 & 0xf0) >> 4); dstVBytes[0] = evenLine ? v0 : (v0 + dstVBytes[0]) >> 1; dstVBytes += 1; } srcLine += srcPitchBytes; dstYLine += dstLumaPitchBytes; if (evenLine) { dstULine += dstChromaPitchBytes; dstVLine += dstChromaPitchBytes; } } } void Packers::convertV210to420P (const uint8_t *const srcBuf, uint8_t *const dstBuf) { // V210: https://developer.apple.com/library/mac/technotes/tn2162/_index.html#//apple_ref/doc/uid/DTS40013070-CH1-TNTAG8-V210__4_2_2_COMPRESSION_TYPE // 420P: https://en.wikipedia.org/wiki/YUV uint32_t srcPitchBytes = ((mSrcWidth + 47) / 48) * 48 * 8 / 3; uint32_t dstLumaPitchBytes = mSrcWidth; uint32_t dstChromaPitchBytes = mSrcWidth / 2; uint32_t dstLumaPlaneBytes = mSrcWidth * mSrcHeight; const uint8_t *srcLine = srcBuf; uint8_t *dstYLine = dstBuf; uint8_t *dstULine = dstBuf + dstLumaPlaneBytes; uint8_t *dstVLine = dstBuf + dstLumaPlaneBytes + dstLumaPlaneBytes / 4; for (uint32_t y=0; y<mSrcHeight; ++y) { uint32_t *srcInts = (uint32_t *)srcLine; uint8_t *dstYBytes = dstYLine; uint8_t *dstUBytes = dstULine; uint8_t *dstVBytes = dstVLine; bool evenLine = (y & 1) == 0; // read 4 source ints / 6 source pixels at a time for (uint32_t x=0; x<mSrcWidth; x+=6) { uint32_t s0 = srcInts[0]; uint32_t s1 = srcInts[1]; uint32_t s2 = srcInts[2]; uint32_t s3 = srcInts[3]; srcInts += 4; dstYBytes[0] = (s0 >> 12) & 0xff; dstYBytes[1] = (s1 >> 2) & 0xff; dstYBytes[2] = (s1 >> 22) & 0xff; dstYBytes[3] = (s2 >> 12) & 0xff; dstYBytes[4] = (s3 >> 2) & 0xff; dstYBytes[5] = (s3 >> 22) & 0xff; dstYBytes += 6; dstUBytes[0] = evenLine ? ((s0 >> 2) & 0xff) : (((s0 >> 2) & 0xff) + dstUBytes[0]) >> 1; dstUBytes[1] = evenLine ? ((s1 >> 12) & 0xff) : (((s1 >> 12) & 0xff) + dstUBytes[1]) >> 1; dstUBytes[2] = evenLine ? ((s2 >> 22) & 0xff) : (((s2 >> 22) & 0xff) + dstUBytes[2]) >> 1; dstUBytes += 3; dstVBytes[0] = evenLine ? ((s0 >> 22) & 0xff) : (((s0 >> 22) & 0xff) + dstVBytes[0]) >> 1; dstVBytes[1] = evenLine ? ((s2 >> 2) & 0xff) : (((s2 >> 2) & 0xff) + dstVBytes[1]) >> 1; dstVBytes[2] = evenLine ? ((s3 >> 12) & 0xff) : (((s3 >> 12) & 0xff) + dstVBytes[2]) >> 1; dstVBytes += 3; } srcLine += srcPitchBytes; dstYLine += dstLumaPitchBytes; if (evenLine) { dstULine += dstChromaPitchBytes; dstVLine += dstChromaPitchBytes; } } } } // namespace streampunk <|endoftext|>
<commit_before>//===-- TargetAsmInfo.cpp - Asm Info ---------------------------------------==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines target asm properties related what form asm statements // should take. // //===----------------------------------------------------------------------===// #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/GlobalVariable.h" #include "llvm/Function.h" #include "llvm/Module.h" #include "llvm/Type.h" #include "llvm/Target/TargetAsmInfo.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Support/Dwarf.h" #include "llvm/Support/ErrorHandling.h" #include <cctype> #include <cstring> using namespace llvm; TargetAsmInfo::TargetAsmInfo(const TargetMachine &tm) : TM(tm) { BSSSection = "\t.bss"; BSSSection_ = 0; ReadOnlySection = 0; TLSDataSection = 0; TLSBSSSection = 0; ZeroFillDirective = 0; NonexecutableStackDirective = 0; NeedsSet = false; MaxInstLength = 4; PCSymbol = "$"; SeparatorChar = ';'; CommentColumn = 60; CommentString = "#"; FirstOperandColumn = 0; MaxOperandLength = 0; GlobalPrefix = ""; PrivateGlobalPrefix = "."; LinkerPrivateGlobalPrefix = ""; JumpTableSpecialLabelPrefix = 0; GlobalVarAddrPrefix = ""; GlobalVarAddrSuffix = ""; FunctionAddrPrefix = ""; FunctionAddrSuffix = ""; PersonalityPrefix = ""; PersonalitySuffix = ""; NeedsIndirectEncoding = false; InlineAsmStart = "#APP"; InlineAsmEnd = "#NO_APP"; AssemblerDialect = 0; AllowQuotesInName = false; ZeroDirective = "\t.zero\t"; ZeroDirectiveSuffix = 0; AsciiDirective = "\t.ascii\t"; AscizDirective = "\t.asciz\t"; Data8bitsDirective = "\t.byte\t"; Data16bitsDirective = "\t.short\t"; Data32bitsDirective = "\t.long\t"; Data64bitsDirective = "\t.quad\t"; AlignDirective = "\t.align\t"; AlignmentIsInBytes = true; TextAlignFillValue = 0; SwitchToSectionDirective = "\t.section\t"; TextSectionStartSuffix = ""; DataSectionStartSuffix = ""; SectionEndDirectiveSuffix = 0; ConstantPoolSection = "\t.section .rodata"; JumpTableDataSection = "\t.section .rodata"; JumpTableDirective = 0; CStringSection = 0; CStringSection_ = 0; // FIXME: Flags are ELFish - replace with normal section stuff. StaticCtorsSection = "\t.section .ctors,\"aw\",@progbits"; StaticDtorsSection = "\t.section .dtors,\"aw\",@progbits"; GlobalDirective = "\t.globl\t"; SetDirective = 0; LCOMMDirective = 0; COMMDirective = "\t.comm\t"; COMMDirectiveTakesAlignment = true; HasDotTypeDotSizeDirective = true; HasSingleParameterDotFile = true; UsedDirective = 0; WeakRefDirective = 0; WeakDefDirective = 0; // FIXME: These are ELFish - move to ELFTAI. HiddenDirective = "\t.hidden\t"; ProtectedDirective = "\t.protected\t"; AbsoluteDebugSectionOffsets = false; AbsoluteEHSectionOffsets = false; HasLEB128 = false; HasDotLocAndDotFile = false; SupportsDebugInformation = false; SupportsExceptionHandling = false; DwarfRequiresFrameSection = true; DwarfUsesInlineInfoSection = false; Is_EHSymbolPrivate = true; GlobalEHDirective = 0; SupportsWeakOmittedEHFrame = true; DwarfSectionOffsetDirective = 0; DwarfAbbrevSection = ".debug_abbrev"; DwarfInfoSection = ".debug_info"; DwarfLineSection = ".debug_line"; DwarfFrameSection = ".debug_frame"; DwarfPubNamesSection = ".debug_pubnames"; DwarfPubTypesSection = ".debug_pubtypes"; DwarfDebugInlineSection = ".debug_inlined"; DwarfStrSection = ".debug_str"; DwarfLocSection = ".debug_loc"; DwarfARangesSection = ".debug_aranges"; DwarfRangesSection = ".debug_ranges"; DwarfMacroInfoSection = ".debug_macinfo"; DwarfEHFrameSection = ".eh_frame"; DwarfExceptionSection = ".gcc_except_table"; AsmTransCBE = 0; TextSection = getUnnamedSection("\t.text", SectionFlags::Code); DataSection = getUnnamedSection("\t.data", SectionFlags::Writeable); } TargetAsmInfo::~TargetAsmInfo() { } /// Measure the specified inline asm to determine an approximation of its /// length. /// Comments (which run till the next SeparatorChar or newline) do not /// count as an instruction. /// Any other non-whitespace text is considered an instruction, with /// multiple instructions separated by SeparatorChar or newlines. /// Variable-length instructions are not handled here; this function /// may be overloaded in the target code to do that. unsigned TargetAsmInfo::getInlineAsmLength(const char *Str) const { // Count the number of instructions in the asm. bool atInsnStart = true; unsigned Length = 0; for (; *Str; ++Str) { if (*Str == '\n' || *Str == SeparatorChar) atInsnStart = true; if (atInsnStart && !isspace(*Str)) { Length += MaxInstLength; atInsnStart = false; } if (atInsnStart && strncmp(Str, CommentString, strlen(CommentString))==0) atInsnStart = false; } return Length; } unsigned TargetAsmInfo::PreferredEHDataFormat(DwarfEncoding::Target Reason, bool Global) const { return dwarf::DW_EH_PE_absptr; } static bool isSuitableForBSS(const GlobalVariable *GV) { if (!GV->hasInitializer()) return true; // Leave constant zeros in readonly constant sections, so they can be shared Constant *C = GV->getInitializer(); return (C->isNullValue() && !GV->isConstant() && !NoZerosInBSS); } static bool isConstantString(const Constant *C) { // First check: is we have constant array of i8 terminated with zero const ConstantArray *CVA = dyn_cast<ConstantArray>(C); // Check, if initializer is a null-terminated string if (CVA && CVA->isCString()) return true; // Another possibility: [1 x i8] zeroinitializer if (isa<ConstantAggregateZero>(C)) { if (const ArrayType *Ty = dyn_cast<ArrayType>(C->getType())) { return (Ty->getElementType() == Type::Int8Ty && Ty->getNumElements() == 1); } } return false; } static unsigned SectionFlagsForGlobal(const GlobalValue *GV, SectionKind::Kind Kind, const char *Name = 0) { unsigned Flags = SectionFlags::None; // Decode flags from global itself. switch (Kind) { case SectionKind::Text: Flags |= SectionFlags::Code; break; case SectionKind::ThreadData: case SectionKind::ThreadBSS: Flags |= SectionFlags::TLS; // FALLS THROUGH case SectionKind::Data: case SectionKind::DataRel: case SectionKind::DataRelLocal: case SectionKind::DataRelRO: case SectionKind::DataRelROLocal: case SectionKind::BSS: Flags |= SectionFlags::Writeable; break; case SectionKind::ROData: case SectionKind::RODataMergeStr: case SectionKind::RODataMergeConst: // No additional flags here break; default: llvm_unreachable("Unexpected section kind!"); } if (GV->isWeakForLinker()) Flags |= SectionFlags::Linkonce; // Add flags from sections, if any. if (Name && *Name != '\0') { Flags |= SectionFlags::Named; // Some lame default implementation based on some magic section names. if (strncmp(Name, ".gnu.linkonce.b.", 16) == 0 || strncmp(Name, ".llvm.linkonce.b.", 17) == 0 || strncmp(Name, ".gnu.linkonce.sb.", 17) == 0 || strncmp(Name, ".llvm.linkonce.sb.", 18) == 0) Flags |= SectionFlags::BSS; else if (strcmp(Name, ".tdata") == 0 || strncmp(Name, ".tdata.", 7) == 0 || strncmp(Name, ".gnu.linkonce.td.", 17) == 0 || strncmp(Name, ".llvm.linkonce.td.", 18) == 0) Flags |= SectionFlags::TLS; else if (strcmp(Name, ".tbss") == 0 || strncmp(Name, ".tbss.", 6) == 0 || strncmp(Name, ".gnu.linkonce.tb.", 17) == 0 || strncmp(Name, ".llvm.linkonce.tb.", 18) == 0) Flags |= SectionFlags::BSS | SectionFlags::TLS; } return Flags; } SectionKind::Kind TargetAsmInfo::SectionKindForGlobal(const GlobalValue *GV) const { // Early exit - functions should be always in text sections. if (isa<Function>(GV)) return SectionKind::Text; const GlobalVariable* GVar = dyn_cast<GlobalVariable>(GV); bool isThreadLocal = GVar->isThreadLocal(); assert(GVar && "Invalid global value for section selection"); if (isSuitableForBSS(GVar)) { // Variable can be easily put to BSS section. return isThreadLocal ? SectionKind::ThreadBSS : SectionKind::BSS; } else if (GVar->isConstant() && !isThreadLocal) { // Now we know, that variable has initializer and it is constant. We need to // check its initializer to decide, which section to output it into. Also // note, there is no thread-local r/o section. Constant *C = GVar->getInitializer(); if (C->getRelocationInfo() != 0) { // Decide whether it is still possible to put symbol into r/o section. if (TM.getRelocationModel() != Reloc::Static) return SectionKind::Data; else return SectionKind::ROData; } else { // Check, if initializer is a null-terminated string if (isConstantString(C)) return SectionKind::RODataMergeStr; else return SectionKind::RODataMergeConst; } } // Variable either is not constant or thread-local - output to data section. return isThreadLocal ? SectionKind::ThreadData : SectionKind::Data; } const Section *TargetAsmInfo::SectionForGlobal(const GlobalValue *GV) const { // Select section name if (GV->hasSection()) { // Honour section already set, if any. unsigned Flags = SectionFlagsForGlobal(GV, SectionKindForGlobal(GV), GV->getSection().c_str()); return getNamedSection(GV->getSection().c_str(), Flags); } // If this global is linkonce/weak and the target handles this by emitting it // into a 'uniqued' section name, create and return the section now. if (GV->isWeakForLinker()) { if (const char *Prefix = getSectionPrefixForUniqueGlobal(SectionKindForGlobal(GV))) { // FIXME: Use mangler interface (PR4584). std::string Name = Prefix+GV->getNameStr(); unsigned Flags = SectionFlagsForGlobal(GV, SectionKindForGlobal(GV)); return getNamedSection(Name.c_str(), Flags); } } // Use default section depending on the 'type' of global return SelectSectionForGlobal(GV); } // Lame default implementation. Calculate the section name for global. const Section* TargetAsmInfo::SelectSectionForGlobal(const GlobalValue *GV) const { SectionKind::Kind Kind = SectionKindForGlobal(GV); if (Kind == SectionKind::Text) return getTextSection(); if (isBSS(Kind)) if (const Section *S = getBSSSection_()) return S; if (SectionKind::isReadOnly(Kind)) if (const Section *S = getReadOnlySection()) return S; return getDataSection(); } /// getSectionForMergableConstant - Given a mergable constant with the /// specified size and relocation information, return a section that it /// should be placed in. const Section * TargetAsmInfo::getSectionForMergableConstant(uint64_t Size, unsigned ReloInfo) const { // FIXME: Support data.rel stuff someday // Lame default implementation. Calculate the section name for machine const. return getDataSection(); } const char * TargetAsmInfo::getSectionPrefixForUniqueGlobal(SectionKind::Kind Kind) const { switch (Kind) { default: llvm_unreachable("Unknown section kind"); case SectionKind::Text: return ".gnu.linkonce.t."; case SectionKind::Data: return ".gnu.linkonce.d."; case SectionKind::DataRel: return ".gnu.linkonce.d.rel."; case SectionKind::DataRelLocal: return ".gnu.linkonce.d.rel.local."; case SectionKind::DataRelRO: return ".gnu.linkonce.d.rel.ro."; case SectionKind::DataRelROLocal: return ".gnu.linkonce.d.rel.ro.local."; case SectionKind::BSS: return ".gnu.linkonce.b."; case SectionKind::ROData: case SectionKind::RODataMergeConst: case SectionKind::RODataMergeStr: return ".gnu.linkonce.r."; case SectionKind::ThreadData: return ".gnu.linkonce.td."; case SectionKind::ThreadBSS: return ".gnu.linkonce.tb."; } } const Section *TargetAsmInfo::getNamedSection(const char *Name, unsigned Flags, bool Override) const { Section &S = Sections[Name]; // This is newly-created section, set it up properly. if (S.Flags == SectionFlags::Invalid || Override) { S.Flags = Flags | SectionFlags::Named; S.Name = Name; } return &S; } const Section* TargetAsmInfo::getUnnamedSection(const char *Directive, unsigned Flags, bool Override) const { Section& S = Sections[Directive]; // This is newly-created section, set it up properly. if (S.Flags == SectionFlags::Invalid || Override) { S.Flags = Flags & ~SectionFlags::Named; S.Name = Directive; } return &S; } const std::string& TargetAsmInfo::getSectionFlags(unsigned Flags) const { SectionFlags::FlagsStringsMapType::iterator I = FlagsStrings.find(Flags); // We didn't print these flags yet, print and save them to map. This reduces // amount of heap trashing due to std::string construction / concatenation. if (I == FlagsStrings.end()) I = FlagsStrings.insert(std::make_pair(Flags, printSectionFlags(Flags))).first; return I->second; } unsigned TargetAsmInfo::getULEB128Size(unsigned Value) { unsigned Size = 0; do { Value >>= 7; Size += sizeof(int8_t); } while (Value); return Size; } unsigned TargetAsmInfo::getSLEB128Size(int Value) { unsigned Size = 0; int Sign = Value >> (8 * sizeof(Value) - 1); bool IsMore; do { unsigned Byte = Value & 0x7f; Value >>= 7; IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0; Size += sizeof(int8_t); } while (IsMore); return Size; } <commit_msg>split the ELF-specific section flag inference-from-name code out into its own helper function.<commit_after>//===-- TargetAsmInfo.cpp - Asm Info ---------------------------------------==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines target asm properties related what form asm statements // should take. // //===----------------------------------------------------------------------===// #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/GlobalVariable.h" #include "llvm/Function.h" #include "llvm/Module.h" #include "llvm/Type.h" #include "llvm/Target/TargetAsmInfo.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Support/Dwarf.h" #include "llvm/Support/ErrorHandling.h" #include <cctype> #include <cstring> using namespace llvm; TargetAsmInfo::TargetAsmInfo(const TargetMachine &tm) : TM(tm) { BSSSection = "\t.bss"; BSSSection_ = 0; ReadOnlySection = 0; TLSDataSection = 0; TLSBSSSection = 0; ZeroFillDirective = 0; NonexecutableStackDirective = 0; NeedsSet = false; MaxInstLength = 4; PCSymbol = "$"; SeparatorChar = ';'; CommentColumn = 60; CommentString = "#"; FirstOperandColumn = 0; MaxOperandLength = 0; GlobalPrefix = ""; PrivateGlobalPrefix = "."; LinkerPrivateGlobalPrefix = ""; JumpTableSpecialLabelPrefix = 0; GlobalVarAddrPrefix = ""; GlobalVarAddrSuffix = ""; FunctionAddrPrefix = ""; FunctionAddrSuffix = ""; PersonalityPrefix = ""; PersonalitySuffix = ""; NeedsIndirectEncoding = false; InlineAsmStart = "#APP"; InlineAsmEnd = "#NO_APP"; AssemblerDialect = 0; AllowQuotesInName = false; ZeroDirective = "\t.zero\t"; ZeroDirectiveSuffix = 0; AsciiDirective = "\t.ascii\t"; AscizDirective = "\t.asciz\t"; Data8bitsDirective = "\t.byte\t"; Data16bitsDirective = "\t.short\t"; Data32bitsDirective = "\t.long\t"; Data64bitsDirective = "\t.quad\t"; AlignDirective = "\t.align\t"; AlignmentIsInBytes = true; TextAlignFillValue = 0; SwitchToSectionDirective = "\t.section\t"; TextSectionStartSuffix = ""; DataSectionStartSuffix = ""; SectionEndDirectiveSuffix = 0; ConstantPoolSection = "\t.section .rodata"; JumpTableDataSection = "\t.section .rodata"; JumpTableDirective = 0; CStringSection = 0; CStringSection_ = 0; // FIXME: Flags are ELFish - replace with normal section stuff. StaticCtorsSection = "\t.section .ctors,\"aw\",@progbits"; StaticDtorsSection = "\t.section .dtors,\"aw\",@progbits"; GlobalDirective = "\t.globl\t"; SetDirective = 0; LCOMMDirective = 0; COMMDirective = "\t.comm\t"; COMMDirectiveTakesAlignment = true; HasDotTypeDotSizeDirective = true; HasSingleParameterDotFile = true; UsedDirective = 0; WeakRefDirective = 0; WeakDefDirective = 0; // FIXME: These are ELFish - move to ELFTAI. HiddenDirective = "\t.hidden\t"; ProtectedDirective = "\t.protected\t"; AbsoluteDebugSectionOffsets = false; AbsoluteEHSectionOffsets = false; HasLEB128 = false; HasDotLocAndDotFile = false; SupportsDebugInformation = false; SupportsExceptionHandling = false; DwarfRequiresFrameSection = true; DwarfUsesInlineInfoSection = false; Is_EHSymbolPrivate = true; GlobalEHDirective = 0; SupportsWeakOmittedEHFrame = true; DwarfSectionOffsetDirective = 0; DwarfAbbrevSection = ".debug_abbrev"; DwarfInfoSection = ".debug_info"; DwarfLineSection = ".debug_line"; DwarfFrameSection = ".debug_frame"; DwarfPubNamesSection = ".debug_pubnames"; DwarfPubTypesSection = ".debug_pubtypes"; DwarfDebugInlineSection = ".debug_inlined"; DwarfStrSection = ".debug_str"; DwarfLocSection = ".debug_loc"; DwarfARangesSection = ".debug_aranges"; DwarfRangesSection = ".debug_ranges"; DwarfMacroInfoSection = ".debug_macinfo"; DwarfEHFrameSection = ".eh_frame"; DwarfExceptionSection = ".gcc_except_table"; AsmTransCBE = 0; TextSection = getUnnamedSection("\t.text", SectionFlags::Code); DataSection = getUnnamedSection("\t.data", SectionFlags::Writeable); } TargetAsmInfo::~TargetAsmInfo() { } /// Measure the specified inline asm to determine an approximation of its /// length. /// Comments (which run till the next SeparatorChar or newline) do not /// count as an instruction. /// Any other non-whitespace text is considered an instruction, with /// multiple instructions separated by SeparatorChar or newlines. /// Variable-length instructions are not handled here; this function /// may be overloaded in the target code to do that. unsigned TargetAsmInfo::getInlineAsmLength(const char *Str) const { // Count the number of instructions in the asm. bool atInsnStart = true; unsigned Length = 0; for (; *Str; ++Str) { if (*Str == '\n' || *Str == SeparatorChar) atInsnStart = true; if (atInsnStart && !isspace(*Str)) { Length += MaxInstLength; atInsnStart = false; } if (atInsnStart && strncmp(Str, CommentString, strlen(CommentString))==0) atInsnStart = false; } return Length; } unsigned TargetAsmInfo::PreferredEHDataFormat(DwarfEncoding::Target Reason, bool Global) const { return dwarf::DW_EH_PE_absptr; } static bool isSuitableForBSS(const GlobalVariable *GV) { if (!GV->hasInitializer()) return true; // Leave constant zeros in readonly constant sections, so they can be shared Constant *C = GV->getInitializer(); return (C->isNullValue() && !GV->isConstant() && !NoZerosInBSS); } static bool isConstantString(const Constant *C) { // First check: is we have constant array of i8 terminated with zero const ConstantArray *CVA = dyn_cast<ConstantArray>(C); // Check, if initializer is a null-terminated string if (CVA && CVA->isCString()) return true; // Another possibility: [1 x i8] zeroinitializer if (isa<ConstantAggregateZero>(C)) { if (const ArrayType *Ty = dyn_cast<ArrayType>(C->getType())) { return (Ty->getElementType() == Type::Int8Ty && Ty->getNumElements() == 1); } } return false; } static unsigned SectionFlagsForGlobal(const GlobalValue *GV, SectionKind::Kind Kind) { unsigned Flags = SectionFlags::None; // Decode flags from global itself. switch (Kind) { case SectionKind::Text: Flags |= SectionFlags::Code; break; case SectionKind::ThreadData: case SectionKind::ThreadBSS: Flags |= SectionFlags::TLS; // FALLS THROUGH case SectionKind::Data: case SectionKind::DataRel: case SectionKind::DataRelLocal: case SectionKind::DataRelRO: case SectionKind::DataRelROLocal: case SectionKind::BSS: Flags |= SectionFlags::Writeable; break; case SectionKind::ROData: case SectionKind::RODataMergeStr: case SectionKind::RODataMergeConst: // No additional flags here break; default: llvm_unreachable("Unexpected section kind!"); } if (GV->isWeakForLinker()) Flags |= SectionFlags::Linkonce; return Flags; } static unsigned GetSectionFlagsForNamedELFSection(const char *Name) { unsigned Flags = 0; // Some lame default implementation based on some magic section names. if (strncmp(Name, ".gnu.linkonce.b.", 16) == 0 || strncmp(Name, ".llvm.linkonce.b.", 17) == 0 || strncmp(Name, ".gnu.linkonce.sb.", 17) == 0 || strncmp(Name, ".llvm.linkonce.sb.", 18) == 0) Flags |= SectionFlags::BSS; else if (strcmp(Name, ".tdata") == 0 || strncmp(Name, ".tdata.", 7) == 0 || strncmp(Name, ".gnu.linkonce.td.", 17) == 0 || strncmp(Name, ".llvm.linkonce.td.", 18) == 0) Flags |= SectionFlags::TLS; else if (strcmp(Name, ".tbss") == 0 || strncmp(Name, ".tbss.", 6) == 0 || strncmp(Name, ".gnu.linkonce.tb.", 17) == 0 || strncmp(Name, ".llvm.linkonce.tb.", 18) == 0) Flags |= SectionFlags::BSS | SectionFlags::TLS; return Flags; } SectionKind::Kind TargetAsmInfo::SectionKindForGlobal(const GlobalValue *GV) const { // Early exit - functions should be always in text sections. if (isa<Function>(GV)) return SectionKind::Text; const GlobalVariable* GVar = dyn_cast<GlobalVariable>(GV); bool isThreadLocal = GVar->isThreadLocal(); assert(GVar && "Invalid global value for section selection"); if (isSuitableForBSS(GVar)) { // Variable can be easily put to BSS section. return isThreadLocal ? SectionKind::ThreadBSS : SectionKind::BSS; } else if (GVar->isConstant() && !isThreadLocal) { // Now we know, that variable has initializer and it is constant. We need to // check its initializer to decide, which section to output it into. Also // note, there is no thread-local r/o section. Constant *C = GVar->getInitializer(); if (C->getRelocationInfo() != 0) { // Decide whether it is still possible to put symbol into r/o section. if (TM.getRelocationModel() != Reloc::Static) return SectionKind::Data; else return SectionKind::ROData; } else { // Check, if initializer is a null-terminated string if (isConstantString(C)) return SectionKind::RODataMergeStr; else return SectionKind::RODataMergeConst; } } // Variable either is not constant or thread-local - output to data section. return isThreadLocal ? SectionKind::ThreadData : SectionKind::Data; } const Section *TargetAsmInfo::SectionForGlobal(const GlobalValue *GV) const { // Select section name if (GV->hasSection()) { // Honour section already set, if any. unsigned Flags = SectionFlagsForGlobal(GV, SectionKindForGlobal(GV)); // This is an explicitly named section. Flags |= SectionFlags::Named; // If the target has magic semantics for certain section names, make sure to // pick up the flags. This allows the user to write things with attribute // section and still get the appropriate section flags printed. Flags |= GetSectionFlagsForNamedELFSection(GV->getSection().c_str()); return getNamedSection(GV->getSection().c_str(), Flags); } // If this global is linkonce/weak and the target handles this by emitting it // into a 'uniqued' section name, create and return the section now. if (GV->isWeakForLinker()) { if (const char *Prefix = getSectionPrefixForUniqueGlobal(SectionKindForGlobal(GV))) { // FIXME: Use mangler interface (PR4584). std::string Name = Prefix+GV->getNameStr(); unsigned Flags = SectionFlagsForGlobal(GV, SectionKindForGlobal(GV)); return getNamedSection(Name.c_str(), Flags); } } // Use default section depending on the 'type' of global return SelectSectionForGlobal(GV); } // Lame default implementation. Calculate the section name for global. const Section* TargetAsmInfo::SelectSectionForGlobal(const GlobalValue *GV) const { SectionKind::Kind Kind = SectionKindForGlobal(GV); if (Kind == SectionKind::Text) return getTextSection(); if (isBSS(Kind)) if (const Section *S = getBSSSection_()) return S; if (SectionKind::isReadOnly(Kind)) if (const Section *S = getReadOnlySection()) return S; return getDataSection(); } /// getSectionForMergableConstant - Given a mergable constant with the /// specified size and relocation information, return a section that it /// should be placed in. const Section * TargetAsmInfo::getSectionForMergableConstant(uint64_t Size, unsigned ReloInfo) const { // FIXME: Support data.rel stuff someday // Lame default implementation. Calculate the section name for machine const. return getDataSection(); } const char * TargetAsmInfo::getSectionPrefixForUniqueGlobal(SectionKind::Kind Kind) const { switch (Kind) { default: llvm_unreachable("Unknown section kind"); case SectionKind::Text: return ".gnu.linkonce.t."; case SectionKind::Data: return ".gnu.linkonce.d."; case SectionKind::DataRel: return ".gnu.linkonce.d.rel."; case SectionKind::DataRelLocal: return ".gnu.linkonce.d.rel.local."; case SectionKind::DataRelRO: return ".gnu.linkonce.d.rel.ro."; case SectionKind::DataRelROLocal: return ".gnu.linkonce.d.rel.ro.local."; case SectionKind::BSS: return ".gnu.linkonce.b."; case SectionKind::ROData: case SectionKind::RODataMergeConst: case SectionKind::RODataMergeStr: return ".gnu.linkonce.r."; case SectionKind::ThreadData: return ".gnu.linkonce.td."; case SectionKind::ThreadBSS: return ".gnu.linkonce.tb."; } } const Section *TargetAsmInfo::getNamedSection(const char *Name, unsigned Flags, bool Override) const { Section &S = Sections[Name]; // This is newly-created section, set it up properly. if (S.Flags == SectionFlags::Invalid || Override) { S.Flags = Flags | SectionFlags::Named; S.Name = Name; } return &S; } const Section* TargetAsmInfo::getUnnamedSection(const char *Directive, unsigned Flags, bool Override) const { Section& S = Sections[Directive]; // This is newly-created section, set it up properly. if (S.Flags == SectionFlags::Invalid || Override) { S.Flags = Flags & ~SectionFlags::Named; S.Name = Directive; } return &S; } const std::string& TargetAsmInfo::getSectionFlags(unsigned Flags) const { SectionFlags::FlagsStringsMapType::iterator I = FlagsStrings.find(Flags); // We didn't print these flags yet, print and save them to map. This reduces // amount of heap trashing due to std::string construction / concatenation. if (I == FlagsStrings.end()) I = FlagsStrings.insert(std::make_pair(Flags, printSectionFlags(Flags))).first; return I->second; } unsigned TargetAsmInfo::getULEB128Size(unsigned Value) { unsigned Size = 0; do { Value >>= 7; Size += sizeof(int8_t); } while (Value); return Size; } unsigned TargetAsmInfo::getSLEB128Size(int Value) { unsigned Size = 0; int Sign = Value >> (8 * sizeof(Value) - 1); bool IsMore; do { unsigned Byte = Value & 0x7f; Value >>= 7; IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0; Size += sizeof(int8_t); } while (IsMore); return Size; } <|endoftext|>
<commit_before>#include <cstddef> #include "Smooth.h" #include "PollardRho.h" namespace Math { namespace Fac { bool isSmooth(const mpz_t n, const mpz_t B, mpz_t *C) { vector<mpz_t*> facs; pollardRhoFactor(n, facs); mpz_t max; mpz_init(max); mpz_set_ui(max, 0); for (size_t i = 0; i < facs.size(); i++) { mpz_t *fac = facs[i]; if (mpz_cmp(*fac, max) > 0) { mpz_set(max, *fac); } } if (mpz_cmp(max, B) <= 0) { mpz_clear(max); return true; } if (C) mpz_set(*C, max); mpz_clear(max); return false; } bool isSmoothI(int n, int B, int *C) { vector<int> facs; pollardRhoFactorI(n, facs); int max = 0; for (size_t i = 0; i < facs.size(); i++) { int fac = facs[i]; if (fac > max) max = fac; } if (max <= B) return true; if (C) *C = max; return false; } } } <commit_msg>Added cleanup of discovered factors in isSmooth.<commit_after>#include <cstddef> #include "Smooth.h" #include "PollardRho.h" namespace Math { namespace Fac { bool isSmooth(const mpz_t n, const mpz_t B, mpz_t *C) { vector<mpz_t*> facs; pollardRhoFactor(n, facs); mpz_t max; mpz_init(max); mpz_set_ui(max, 0); for (size_t i = 0; i < facs.size(); i++) { mpz_t *fac = facs[i]; if (mpz_cmp(*fac, max) > 0) { mpz_set(max, *fac); } mpz_clear(*fac); delete[] fac; } if (mpz_cmp(max, B) <= 0) { mpz_clear(max); return true; } if (C) mpz_set(*C, max); mpz_clear(max); return false; } bool isSmoothI(int n, int B, int *C) { vector<int> facs; pollardRhoFactorI(n, facs); int max = 0; for (size_t i = 0; i < facs.size(); i++) { int fac = facs[i]; if (fac > max) max = fac; } if (max <= B) return true; if (C) *C = max; return false; } } } <|endoftext|>
<commit_before>#include <node.h> #include <initializer_list> #include "../amo-library/Pump.h" #include "../amo-library/calculator/PumpEfficiency.h" #include "../amo-library/calculator/OptimalPumpEfficiency.h" #include "../amo-library/calculator/MotorRatedPower.h" #include "../amo-library/calculator/OptimalMotorRatedPower.h" #include "../amo-library/calculator/MotorShaftPower.h" #include "../amo-library/calculator/OptimalMotorShaftPower.h" #include "../amo-library/calculator/PumpShaftPower.h" #include "../amo-library/calculator/OptimalPumpShaftPower.h" #include "../amo-library/calculator/MotorEfficiency.h" #include "../amo-library/calculator/OptimalMotorEfficiency.h" #include "../amo-library/calculator/MotorPowerFactor.h" #include "../amo-library/calculator/OptimalMotorPowerFactor.h" #include "../amo-library/calculator/MotorCurrent.h" #include "../amo-library/calculator/OptimalMotorCurrent.h" #include "../amo-library/calculator/MotorPower.h" #include "../amo-library/calculator/OptimalMotorPower.h" #include "../amo-library/AnnualEnergy.h" #include "../amo-library/AnnualCost.h" #include "../amo-library/AnnualSavingsPotential.h" #include "../amo-library/OptimizationRating.h" using namespace v8; Local<Array> r; Isolate* iso; Local<Object> inp; void set(std::initializer_list <double> args) { for (auto d : args) { r->Set(r->Length(),Number::New(iso,d)); } } double get(const char * nm) { return inp->ToObject()->Get(String::NewFromUtf8(iso,nm))->NumberValue(); } void Results(const FunctionCallbackInfo<Value>& args) { iso = args.GetIsolate(); r = Array::New(iso); inp = args[0]->ToObject(); set({ (new PumpEfficiency(get("specific_gravity"),get("flow"),get("head"),get("power_rating")))->calculate(), (new OptimalPumpEfficiency(static_cast<Pump::Style>(get("style")),get("pump_rpm"),get("viscosity"),get("stages"),get("flow"),get("head"),static_cast<Pump::Speed>(!get("speed"))))->calculate(), (new MotorRatedPower(0))->calculate(), (new OptimalMotorRatedPower(0,0))->calculate(), (new MotorShaftPower(0,0))->calculate(), (new OptimalMotorShaftPower(0,Pump::Drive::DIRECT_DRIVE))->calculate(), (new PumpShaftPower(0,Pump::Drive::DIRECT_DRIVE))->calculate(), (new OptimalPumpShaftPower(0,0,0,0))->calculate(), (new MotorEfficiency(0,0,Motor::EfficiencyClass::STANDARD,0,FieldData::LoadEstimationMethod::POWER,0,0,0))->calculate(), (new OptimalMotorEfficiency(0,0))->calculate(), (new MotorPowerFactor(0,0,Motor::EfficiencyClass::STANDARD,0,FieldData::LoadEstimationMethod::POWER,0,0,0))->calculate(), (new OptimalMotorPowerFactor(0,0))->calculate(), (new MotorCurrent(0,0,0))->calculate(), (new OptimalMotorCurrent(0,0))->calculate(), (new MotorPower(0,0,0,0))->calculate(), (new OptimalMotorPower(0,0))->calculate(), (new AnnualEnergy(0,0))->calculate(), (new AnnualEnergy(0,0))->calculate(), (new AnnualCost(0,0))->calculate(), (new AnnualCost(0,0))->calculate(), -1, (new AnnualSavingsPotential(0,0))->calculate(), -1, (new OptimizationRating(0,0))->calculate() }); args.GetReturnValue().Set(r); } void init(Local<Object> exports) { NODE_SET_METHOD(exports, "results", Results); } NODE_MODULE(bridge, init) <commit_msg>no message<commit_after>#include <node.h> #include <initializer_list> #include "../amo-library/Pump.h" #include "../amo-library/calculator/PumpEfficiency.h" #include "../amo-library/calculator/OptimalPumpEfficiency.h" #include "../amo-library/calculator/MotorRatedPower.h" #include "../amo-library/calculator/OptimalMotorRatedPower.h" #include "../amo-library/calculator/MotorShaftPower.h" #include "../amo-library/calculator/OptimalMotorShaftPower.h" #include "../amo-library/calculator/PumpShaftPower.h" #include "../amo-library/calculator/OptimalPumpShaftPower.h" #include "../amo-library/calculator/MotorEfficiency.h" #include "../amo-library/calculator/OptimalMotorEfficiency.h" #include "../amo-library/calculator/MotorPowerFactor.h" #include "../amo-library/calculator/OptimalMotorPowerFactor.h" #include "../amo-library/calculator/MotorCurrent.h" #include "../amo-library/calculator/OptimalMotorCurrent.h" #include "../amo-library/calculator/MotorPower.h" #include "../amo-library/calculator/OptimalMotorPower.h" #include "../amo-library/AnnualEnergy.h" #include "../amo-library/AnnualCost.h" #include "../amo-library/AnnualSavingsPotential.h" #include "../amo-library/OptimizationRating.h" using namespace v8; Local<Array> r; Isolate* iso; Local<Object> inp; void set(std::initializer_list <double> args) { for (auto d : args) { r->Set(r->Length(),Number::New(iso,d)); } } double get(const char * nm) { return inp->ToObject()->Get(String::NewFromUtf8(iso,nm))->NumberValue(); } void Results(const FunctionCallbackInfo<Value>& args) { iso = args.GetIsolate(); r = Array::New(iso); inp = args[0]->ToObject(); set({ (new PumpEfficiency(get("specific_gravity"),get("flow"),get("head"),0))->calculate(), (new OptimalPumpEfficiency(static_cast<Pump::Style>(get("style")),get("pump_rpm"),get("viscosity"),get("stages"),get("flow"),get("head"),static_cast<Pump::Speed>(!get("speed"))))->calculate(), (new MotorRatedPower(get("power_rating")))->calculate(), (new OptimalMotorRatedPower(0,get("margin")))->calculate(), (new MotorShaftPower(0,0))->calculate(), (new OptimalMotorShaftPower(0,Pump::Drive::DIRECT_DRIVE))->calculate(), (new PumpShaftPower(0,static_cast<Pump::Drive>(get("drive"))))))->calculate(), (new OptimalPumpShaftPower(0,0,0,0))->calculate(), (new MotorEfficiency(0,0,Motor::EfficiencyClass::STANDARD,0,FieldData::LoadEstimationMethod::POWER,0,0,0))->calculate(), (new OptimalMotorEfficiency(0,0))->calculate(), (new MotorPowerFactor(0,0,Motor::EfficiencyClass::STANDARD,0,FieldData::LoadEstimationMethod::POWER,0,0,0))->calculate(), (new OptimalMotorPowerFactor(0,0))->calculate(), (new MotorCurrent(0,0,0))->calculate(), (new OptimalMotorCurrent(0,0))->calculate(), (new MotorPower(0,0,0,0))->calculate(), (new OptimalMotorPower(0,0))->calculate(), (new AnnualEnergy(0,0))->calculate(), (new AnnualEnergy(0,0))->calculate(), (new AnnualCost(0,0))->calculate(), (new AnnualCost(0,0))->calculate(), -1, (new AnnualSavingsPotential(0,0))->calculate(), -1, (new OptimizationRating(0,0))->calculate() }); args.GetReturnValue().Set(r); } void init(Local<Object> exports) { NODE_SET_METHOD(exports, "results", Results); } NODE_MODULE(bridge, init) <|endoftext|>
<commit_before>// // vertex.cpp // regex // // Created by leviathan on 16/7/19. // Copyright © 2016年 leviathan. All rights reserved. // #include <iostream> #include "vertex.hpp" <commit_msg>Delete Vertex.cpp<commit_after><|endoftext|>
<commit_before>/* Copyright (c) 2007, 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. */ #if defined TORRENT_DEBUG || defined TORRENT_ASIO_DEBUGGING || TORRENT_RELEASE_ASSERTS #include "libtorrent/config.hpp" #ifdef __APPLE__ #include <AvailabilityMacros.h> #endif #include <string> #include <cstring> #include <stdlib.h> // uClibc++ doesn't have cxxabi.h #if defined __GNUC__ && __GNUC__ >= 3 \ && !defined __UCLIBCXX_MAJOR__ #include <cxxabi.h> std::string demangle(char const* name) { // in case this string comes // this is needed on linux char const* start = strchr(name, '('); if (start != 0) { ++start; } else { // this is needed on macos x start = strstr(name, "0x"); if (start != 0) { start = strchr(start, ' '); if (start != 0) ++start; else start = name; } else start = name; } char const* end = strchr(start, '+'); if (end) while (*(end-1) == ' ') --end; std::string in; if (end == 0) in.assign(start); else in.assign(start, end); size_t len; int status; char* unmangled = ::abi::__cxa_demangle(in.c_str(), 0, &len, &status); if (unmangled == 0) return in; std::string ret(unmangled); free(unmangled); return ret; } #elif defined WIN32 #undef _WIN32_WINNT #define _WIN32_WINNT 0x0501 // XP #include "windows.h" #include "dbghelp.h" std::string demangle(char const* name) { char demangled_name[256]; if (UnDecorateSymbolName(name, demangled_name, sizeof(demangled_name), UNDNAME_NO_THROW_SIGNATURES) == 0) demangled_name[0] = 0; return demangled_name; } #else std::string demangle(char const* name) { return name; } #endif #include <stdlib.h> #include <stdio.h> #include <signal.h> #include "libtorrent/version.hpp" // execinfo.h is available in the MacOS X 10.5 SDK. #if (defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050)) #include <execinfo.h> void print_backtrace(char* out, int len) { void* stack[50]; int size = backtrace(stack, 50); char** symbols = backtrace_symbols(stack, size); for (int i = 1; i < size && len > 0; ++i) { int ret = snprintf(out, len, "%d: %s\n", i, demangle(symbols[i]).c_str()); out += ret; len -= ret; } free(symbols); } #elif defined WIN32 #undef _WIN32_WINNT #define _WIN32_WINNT 0x0501 // XP #include "windows.h" #include "libtorrent/utf8.hpp" #include "winbase.h" #include "dbghelp.h" void print_backtrace(char* out, int len) { typedef USHORT (*RtlCaptureStackBackTrace_t)( __in ULONG FramesToSkip, __in ULONG FramesToCapture, __out PVOID *BackTrace, __out_opt PULONG BackTraceHash); static RtlCaptureStackBackTrace_t RtlCaptureStackBackTrace = 0; if (RtlCaptureStackBackTrace == 0) { // we don't actually have to free this library, everyone has it loaded HMODULE lib = LoadLibrary(TEXT("kernel32.dll")); RtlCaptureStackBackTrace = (RtlCaptureStackBackTrace_t)GetProcAddress(lib, "RtlCaptureStackBackTrace"); if (RtlCaptureStackBackTrace == 0) { out[0] = 0; return; } } int i; void* stack[50]; int size = CaptureStackBackTrace(0, 50, stack, 0); SYMBOL_INFO* symbol = (SYMBOL_INFO*)calloc(sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR), 1); symbol->MaxNameLen = MAX_SYM_NAME; symbol->SizeOfStruct = sizeof(SYMBOL_INFO); HANDLE p = GetCurrentProcess(); static bool sym_initialized = false; if (!sym_initialized) { sym_initialized = true; SymInitialize(p, NULL, true); } for (i = 0; i < size && len > 0; ++i) { int ret; if (SymFromAddr(p, uintptr_t(stack[i]), 0, symbol)) ret = snprintf(out, len, "%d: %s\n", i, symbol->Name); else ret = snprintf(out, len, "%d: <unknown>\n", i); out += ret; len -= ret; } free(symbol); } #else void print_backtrace(char* out, int len) {} #endif #if TORRENT_PRODUCTION_ASSERTS char const* libtorrent_assert_log = "asserts.log"; #endif TORRENT_EXPORT void assert_fail(char const* expr, int line, char const* file , char const* function, char const* value) { #if TORRENT_PRODUCTION_ASSERTS FILE* out = fopen(libtorrent_assert_log, "a+"); if (out == 0) out = stderr; #else FILE* out = stderr; #endif char stack[8192]; print_backtrace(stack, sizeof(stack)); fprintf(out, "assertion failed. Please file a bugreport at " "http://code.rasterbar.com/libtorrent/newticket\n" "Please include the following information:\n\n" "version: " LIBTORRENT_VERSION "\n" "%s\n" "file: '%s'\n" "line: %d\n" "function: %s\n" "expression: %s\n" "%s%s\n" "stack:\n" "%s\n" , LIBTORRENT_REVISION, file, line, function, expr , value ? value : "", value ? "\n" : "" , stack); // if production asserts are defined, don't abort, just print the error #if TORRENT_PRODUCTION_ASSERTS if (out != stderr) fclose(out); #else // send SIGINT to the current process // to break into the debugger raise(SIGINT); abort(); #endif } #else void assert_fail(char const* expr, int line, char const* file, char const* function) {} #endif <commit_msg>export assert_fail<commit_after>/* Copyright (c) 2007, 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. */ #if defined TORRENT_DEBUG || defined TORRENT_ASIO_DEBUGGING || TORRENT_RELEASE_ASSERTS #include "libtorrent/config.hpp" #ifdef __APPLE__ #include <AvailabilityMacros.h> #endif #include <string> #include <cstring> #include <stdlib.h> // uClibc++ doesn't have cxxabi.h #if defined __GNUC__ && __GNUC__ >= 3 \ && !defined __UCLIBCXX_MAJOR__ #include <cxxabi.h> std::string demangle(char const* name) { // in case this string comes // this is needed on linux char const* start = strchr(name, '('); if (start != 0) { ++start; } else { // this is needed on macos x start = strstr(name, "0x"); if (start != 0) { start = strchr(start, ' '); if (start != 0) ++start; else start = name; } else start = name; } char const* end = strchr(start, '+'); if (end) while (*(end-1) == ' ') --end; std::string in; if (end == 0) in.assign(start); else in.assign(start, end); size_t len; int status; char* unmangled = ::abi::__cxa_demangle(in.c_str(), 0, &len, &status); if (unmangled == 0) return in; std::string ret(unmangled); free(unmangled); return ret; } #elif defined WIN32 #undef _WIN32_WINNT #define _WIN32_WINNT 0x0501 // XP #include "windows.h" #include "dbghelp.h" std::string demangle(char const* name) { char demangled_name[256]; if (UnDecorateSymbolName(name, demangled_name, sizeof(demangled_name), UNDNAME_NO_THROW_SIGNATURES) == 0) demangled_name[0] = 0; return demangled_name; } #else std::string demangle(char const* name) { return name; } #endif #include <stdlib.h> #include <stdio.h> #include <signal.h> #include "libtorrent/version.hpp" // execinfo.h is available in the MacOS X 10.5 SDK. #if (defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050)) #include <execinfo.h> void print_backtrace(char* out, int len) { void* stack[50]; int size = backtrace(stack, 50); char** symbols = backtrace_symbols(stack, size); for (int i = 1; i < size && len > 0; ++i) { int ret = snprintf(out, len, "%d: %s\n", i, demangle(symbols[i]).c_str()); out += ret; len -= ret; } free(symbols); } #elif defined WIN32 #undef _WIN32_WINNT #define _WIN32_WINNT 0x0501 // XP #include "windows.h" #include "libtorrent/utf8.hpp" #include "winbase.h" #include "dbghelp.h" void print_backtrace(char* out, int len) { typedef USHORT (*RtlCaptureStackBackTrace_t)( __in ULONG FramesToSkip, __in ULONG FramesToCapture, __out PVOID *BackTrace, __out_opt PULONG BackTraceHash); static RtlCaptureStackBackTrace_t RtlCaptureStackBackTrace = 0; if (RtlCaptureStackBackTrace == 0) { // we don't actually have to free this library, everyone has it loaded HMODULE lib = LoadLibrary(TEXT("kernel32.dll")); RtlCaptureStackBackTrace = (RtlCaptureStackBackTrace_t)GetProcAddress(lib, "RtlCaptureStackBackTrace"); if (RtlCaptureStackBackTrace == 0) { out[0] = 0; return; } } int i; void* stack[50]; int size = CaptureStackBackTrace(0, 50, stack, 0); SYMBOL_INFO* symbol = (SYMBOL_INFO*)calloc(sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR), 1); symbol->MaxNameLen = MAX_SYM_NAME; symbol->SizeOfStruct = sizeof(SYMBOL_INFO); HANDLE p = GetCurrentProcess(); static bool sym_initialized = false; if (!sym_initialized) { sym_initialized = true; SymInitialize(p, NULL, true); } for (i = 0; i < size && len > 0; ++i) { int ret; if (SymFromAddr(p, uintptr_t(stack[i]), 0, symbol)) ret = snprintf(out, len, "%d: %s\n", i, symbol->Name); else ret = snprintf(out, len, "%d: <unknown>\n", i); out += ret; len -= ret; } free(symbol); } #else void print_backtrace(char* out, int len) {} #endif #if TORRENT_PRODUCTION_ASSERTS char const* libtorrent_assert_log = "asserts.log"; #endif TORRENT_EXPORT void assert_fail(char const* expr, int line, char const* file , char const* function, char const* value) { #if TORRENT_PRODUCTION_ASSERTS FILE* out = fopen(libtorrent_assert_log, "a+"); if (out == 0) out = stderr; #else FILE* out = stderr; #endif char stack[8192]; print_backtrace(stack, sizeof(stack)); fprintf(out, "assertion failed. Please file a bugreport at " "http://code.rasterbar.com/libtorrent/newticket\n" "Please include the following information:\n\n" "version: " LIBTORRENT_VERSION "\n" "%s\n" "file: '%s'\n" "line: %d\n" "function: %s\n" "expression: %s\n" "%s%s\n" "stack:\n" "%s\n" , LIBTORRENT_REVISION, file, line, function, expr , value ? value : "", value ? "\n" : "" , stack); // if production asserts are defined, don't abort, just print the error #if TORRENT_PRODUCTION_ASSERTS if (out != stderr) fclose(out); #else // send SIGINT to the current process // to break into the debugger raise(SIGINT); abort(); #endif } #else TORRENT_EXPORT void assert_fail(char const* expr, int line, char const* file, char const* function) {} #endif <|endoftext|>
<commit_before>#include "broker.hpp" #include "message.hpp" #include <algorithm> #include <boost/algorithm/string.hpp> #include <unordered_map> namespace { bool revStrEquals(const std::string& str1, const std::string& str2) { //compare strings in reverse if(str1.length() != str2.length()) return false; for(int i = str1.length() - 1; i >= 0; --i) if(str1[i] != str2[i]) return false; return true; } bool equalOrPlus(const std::string& pat, const std::string& top) { return pat == "+" || revStrEquals(pat, top); } } //anonymous namespace class Subscription { public: Subscription(MqttSubscriber& subscriber, MqttSubscribe::Topic topic, std::deque<std::string> topicParts): _subscriber(subscriber), _part(std::move(topicParts.back())), _topic(std::move(topic.topic)), _qos(topic.qos) { } void newMessage(std::string topic, std::vector<ubyte> payload) { _subscriber.newMessage(topic, payload); } bool isSubscriber(const MqttSubscriber& subscriber) const { return &_subscriber == &subscriber; } bool isSubscription(const MqttSubscriber& subscriber, std::vector<std::string> topics) const { return isSubscriber(subscriber) && isTopic(topics); } bool isTopic(std::vector<std::string> topics) const { return std::find(topics.cbegin(), topics.cend(), _topic) == topics.cend(); } private: MqttSubscriber& _subscriber; std::string _part; std::string _topic; ubyte _qos; }; struct SubscriptionTree { public: void addSubscription(Subscription* s, std::deque<std::string> parts) { assert(parts.size()); if(_useCache) _cache.clear(); //invalidate cache addSubscriptionImpl(s, parts, nullptr, _nodes); } // void removeSubscription(MqttSubscriber subscriber, ref Node*[string] nodes) { // if(_useCache) _cache = _cache.init; //invalidate cache // auto newnodes = nodes.dup; // foreach(n; newnodes) { // if(n.leaves) { // n.leaves = std.algorithm.remove!(l => l.isSubscriber(subscriber))(n.leaves); // if(n.leaves.empty && !n.branches.length) { // removeNode(n.parent, n); // } // } else { // removeSubscription(subscriber, n.branches); // } // } // } // void removeSubscription(MqttSubscriber subscriber, in string[] topic, ref Node*[string] nodes) { // if(_useCache) _cache = _cache.init; //invalidate cache // auto newnodes = nodes.dup; // foreach(n; newnodes) { // if(n.leaves) { // n.leaves = std.algorithm.remove!(l => l.isSubscription(subscriber, topic))(n.leaves); // if(n.leaves.empty && !n.branches.length) { // removeNode(n.parent, n); // } // } else { // removeSubscription(subscriber, topic, n.branches); // } // } // } // void removeNode(Node* parent, Node* child) { // if(parent) { // parent.branches.remove(child.part); // } else { // _nodes.remove(child.part); // } // if(parent && !parent.branches.length && parent.leaves.empty) // removeNode(parent.parent, parent); // } // void publish(in string topic, string[] topParts, in const(ubyte)[] payload) { // publish(topic, topParts, payload, _nodes); // } // void publish(in string topic, string[] topParts, in const(ubyte)[] payload, // Node*[string] nodes) { // //check the cache first // if(_useCache && topic in _cache) { // foreach(s; _cache[topic]) s.newMessage(topic, payload); // return; // } // //not in the cache or not using the cache, do it the hard way // foreach(part; [topParts[0], "#", "+"]) { // if(part in nodes) { // if(topParts.length == 1 && "#" in nodes[part].branches) { // //So that "finance/#" matches finance // publishLeaves(topic, payload, topParts, nodes[part].branches["#"].leaves); // } // publishLeaves(topic, payload, topParts, nodes[part].leaves); // if(topParts.length > 1) { // publish(topic, topParts[1..$], payload, nodes[part].branches); // } // } // } // } // void publishLeaves(in string topic, in const(ubyte)[] payload, // in string[] topParts, // Subscription[] subscriptions) { // foreach(sub; subscriptions) { // if(topParts.length == 1 && // equalOrPlus(sub._part, topParts[0])) { // publishLeaf(sub, topic, payload); // } // else if(sub._part == "#") { // publishLeaf(sub, topic, payload); // } // } // } // void publishLeaf(Subscription sub, in string topic, in const(ubyte)[] payload) { // sub.newMessage(topic, payload); // if(_useCache) _cache[topic] ~= sub; // } void useCache(bool u) { _useCache = u; } private: struct Node { Node(std::string pt, Node* pr):part(pt), parent(pr) {} std::string part; Node* parent; std::unordered_map<std::string, Node*> branches; std::vector<Subscription*> leaves; }; bool _useCache; std::unordered_map<std::string, Subscription*> _cache; std::unordered_map<std::string, Node*> _nodes; void addSubscriptionImpl(Subscription* s, std::deque<std::string> parts, Node* parent, std::unordered_map<std::string, Node*> nodes) { auto part = parts.front(); parts.pop_front(); auto node = addOrFindNode(part, parent, nodes); if(!parts.size()) { node->leaves.emplace_back(s); } else { addSubscriptionImpl(s, parts, node, node->branches); } } Node* addOrFindNode(std::string part, Node* parent, std::unordered_map<std::string, Node*> nodes) { if(nodes.count(part) && part == nodes[part]->part) { return nodes[part]; } auto node = new Node(part, parent); nodes[part] = node; return node; } }; class MqttBroker { public: void subscribe(MqttSubscriber& subscriber, std::vector<std::string> topics) { std::vector<MqttSubscribe::Topic> newTopics; std::transform(topics.cbegin(), topics.cend(), std::back_inserter(newTopics), [](std::string t) { return MqttSubscribe::Topic(t, 0); }); subscribe(subscriber, newTopics); } void subscribe(MqttSubscriber& subscriber, std::vector<MqttSubscribe::Topic> topics) { for(const auto& t: topics) { std::deque<std::string> parts; boost::split(parts, t.topic, boost::is_any_of("/")); _subscriptions.addSubscription(new Subscription(subscriber, t, parts), parts); } } // void unsubscribe(MqttSubscriber& subscriber) { // _subscriptions.removeSubscription(subscriber, _subscriptions._nodes); // } // void unsubscribe(MqttSubscriber& subscriber, std::vector<std::string> topics) { // _subscriptions.removeSubscription(subscriber, topics, _subscriptions._nodes); // } // void publish(std::string topic, std::vector<ubyte> payload) { // auto topParts = array(splitter(topic, "/")); // publish(topic, topParts, payload); // } void useCache(bool u) { _subscriptions.useCache(u); } private: SubscriptionTree _subscriptions; // void publish(std::string topic, std::vector<std::string> topParts, // std::vector<ubyte> payload) { // _subscriptions.publish(topic, topParts, payload); // } }; <commit_msg>Uncommented removeNode<commit_after>#include "broker.hpp" #include "message.hpp" #include <algorithm> #include <boost/algorithm/string.hpp> #include <unordered_map> namespace { bool revStrEquals(const std::string& str1, const std::string& str2) { //compare strings in reverse if(str1.length() != str2.length()) return false; for(int i = str1.length() - 1; i >= 0; --i) if(str1[i] != str2[i]) return false; return true; } bool equalOrPlus(const std::string& pat, const std::string& top) { return pat == "+" || revStrEquals(pat, top); } } //anonymous namespace class Subscription { public: Subscription(MqttSubscriber& subscriber, MqttSubscribe::Topic topic, std::deque<std::string> topicParts): _subscriber(subscriber), _part(std::move(topicParts.back())), _topic(std::move(topic.topic)), _qos(topic.qos) { } void newMessage(std::string topic, std::vector<ubyte> payload) { _subscriber.newMessage(topic, payload); } bool isSubscriber(const MqttSubscriber& subscriber) const { return &_subscriber == &subscriber; } bool isSubscription(const MqttSubscriber& subscriber, std::vector<std::string> topics) const { return isSubscriber(subscriber) && isTopic(topics); } bool isTopic(std::vector<std::string> topics) const { return std::find(topics.cbegin(), topics.cend(), _topic) == topics.cend(); } private: MqttSubscriber& _subscriber; std::string _part; std::string _topic; ubyte _qos; }; struct SubscriptionTree { public: void addSubscription(Subscription* s, std::deque<std::string> parts) { assert(parts.size()); clearCache(); addSubscriptionImpl(s, parts, nullptr, _nodes); } // void removeSubscription(MqttSubscriber& subscriber, // std::unordered_map<std::string, Node*>& nodes) { // clearCache(); // decltype(nodes) newNodes; // std::copy(nodes.cbegin(), nodes.cend(), std::back_inserter(newNodes)); // for(auto n: newnodes) { // if(n->leaves) { // std::remove_if(n->leaves.begin(), n->leaves.end(), // [](Subscription* l) { return l.isSubscriber(subscriber); }); // if(!n->leaves.size() && !n->branches.size()) { // removeNode(n->parent, n); // } // } else { // removeSubscription(subscriber, n.branches); // } // } // } // void removeSubscription(MqttSubscriber subscriber, in string[] topic, ref Node*[string] nodes) { // clearCache(); // auto newnodes = nodes.dup; // foreach(n; newnodes) { // if(n.leaves) { // n.leaves = std.algorithm.remove!(l => l.isSubscription(subscriber, topic))(n.leaves); // if(n.leaves.empty && !n.branches.length) { // removeNode(n.parent, n); // } // } else { // removeSubscription(subscriber, topic, n.branches); // } // } // } // void publish(in string topic, string[] topParts, in const(ubyte)[] payload) { // publish(topic, topParts, payload, _nodes); // } // void publish(in string topic, string[] topParts, in const(ubyte)[] payload, // Node*[string] nodes) { // //check the cache first // if(_useCache && topic in _cache) { // foreach(s; _cache[topic]) s.newMessage(topic, payload); // return; // } // //not in the cache or not using the cache, do it the hard way // foreach(part; [topParts[0], "#", "+"]) { // if(part in nodes) { // if(topParts.length == 1 && "#" in nodes[part].branches) { // //So that "finance/#" matches finance // publishLeaves(topic, payload, topParts, nodes[part].branches["#"].leaves); // } // publishLeaves(topic, payload, topParts, nodes[part].leaves); // if(topParts.length > 1) { // publish(topic, topParts[1..$], payload, nodes[part].branches); // } // } // } // } // void publishLeaves(in string topic, in const(ubyte)[] payload, // in string[] topParts, // Subscription[] subscriptions) { // foreach(sub; subscriptions) { // if(topParts.length == 1 && // equalOrPlus(sub._part, topParts[0])) { // publishLeaf(sub, topic, payload); // } // else if(sub._part == "#") { // publishLeaf(sub, topic, payload); // } // } // } // void publishLeaf(Subscription sub, in string topic, in const(ubyte)[] payload) { // sub.newMessage(topic, payload); // if(_useCache) _cache[topic] ~= sub; // } void useCache(bool u) { _useCache = u; } private: struct Node { Node(std::string pt, Node* pr):part(pt), parent(pr) {} std::string part; Node* parent; std::unordered_map<std::string, Node*> branches; std::vector<Subscription*> leaves; }; bool _useCache; std::unordered_map<std::string, Subscription*> _cache; std::unordered_map<std::string, Node*> _nodes; void addSubscriptionImpl(Subscription* s, std::deque<std::string> parts, Node* parent, std::unordered_map<std::string, Node*> nodes) { auto part = parts.front(); parts.pop_front(); auto node = addOrFindNode(part, parent, nodes); if(!parts.size()) { node->leaves.emplace_back(s); } else { addSubscriptionImpl(s, parts, node, node->branches); } } Node* addOrFindNode(std::string part, Node* parent, std::unordered_map<std::string, Node*> nodes) { if(nodes.count(part) && part == nodes[part]->part) { return nodes[part]; } auto node = new Node(part, parent); nodes[part] = node; return node; } void clearCache() { if(_useCache) _cache.clear(); } void removeNode(Node* parent, Node* child) { if(parent) { parent->branches.erase(child->part); } else { _nodes.erase(child->part); } if(parent && !parent->branches.size() && !parent->leaves.size()) removeNode(parent->parent, parent); } }; class MqttBroker { public: void subscribe(MqttSubscriber& subscriber, std::vector<std::string> topics) { std::vector<MqttSubscribe::Topic> newTopics; std::transform(topics.cbegin(), topics.cend(), std::back_inserter(newTopics), [](std::string t) { return MqttSubscribe::Topic(t, 0); }); subscribe(subscriber, newTopics); } void subscribe(MqttSubscriber& subscriber, std::vector<MqttSubscribe::Topic> topics) { for(const auto& t: topics) { std::deque<std::string> parts; boost::split(parts, t.topic, boost::is_any_of("/")); _subscriptions.addSubscription(new Subscription(subscriber, t, parts), parts); } } // void unsubscribe(MqttSubscriber& subscriber) { // _subscriptions.removeSubscription(subscriber, _subscriptions._nodes); // } // void unsubscribe(MqttSubscriber& subscriber, std::vector<std::string> topics) { // _subscriptions.removeSubscription(subscriber, topics, _subscriptions._nodes); // } // void publish(std::string topic, std::vector<ubyte> payload) { // auto topParts = array(splitter(topic, "/")); // publish(topic, topParts, payload); // } void useCache(bool u) { _subscriptions.useCache(u); } private: SubscriptionTree _subscriptions; // void publish(std::string topic, std::vector<std::string> topParts, // std::vector<ubyte> payload) { // _subscriptions.publish(topic, topParts, payload); // } }; <|endoftext|>
<commit_before>#ifdef HAVE_CONFIG_H #include <config.h> #endif #include <iostream> #include <fstream> #include <string> #include <cstring> #include <cerrno> /* Use the POSIX glob(3) function if available. On a native Windows port, * you'll need to make your own glob(3) implementation and define HAVE_GLOB, or * entirely reimplement ls. */ #ifdef HAVE_GLOB_H #include <glob.h> #endif #include "../interp.hxx" #include "../command.hxx" #include "../function.hxx" #include "list.hxx" #include "../common.hxx" using namespace std; namespace tglng { #ifdef HAVE_GLOB //Define glob parms which might not exist #ifndef GLOB_BRACE # define GLOB_BRACE 0 #endif #ifndef GLOB_TILDE # define GLOB_TILDE 0 #endif bool fs_ls(wstring* out, const wstring* in, Interpreter& interp, unsigned) { glob_t results; out->clear(); //Transcode in[0] to a narrow string vector<char> pattern; if (!wstrtontbs(pattern, in[0])) { wcerr << L"Could not convert glob pattern to narrow string: " << *in << endl; return false; } //Perform the glob //If it fails, just return an empty list (*out is already empty); //otherwise, convert to a list. if (!glob(&pattern[0], GLOB_BRACE|GLOB_TILDE, NULL, &results)) { for (unsigned i = 0; i < results.gl_pathc; ++i) { wstring name; //Convert the filename back to a wide string if (!ntbstowstr(name, results.gl_pathv[i])) { //Print a warning about this one cerr << "WARN: Could not convert narrow filename to wide string: " << results.gl_pathv[i] << endl; continue; } //OK, add to the list list::lappend(*out, name); } globfree(&results); } return true; } static GlobalBinding<TFunctionParser<1,1,fs_ls> > _ls(L"ls"); #endif /* HAVE_GLOB */ /** * Converts the given wstring to a char*, stored within dst. The actual size * of dst is not defined; rather, the only guarantee is that &dst[0] is a * valid NTBS. * * If successful, returns true; otherwise, prints a diagnostic and returns * false. */ static bool wstrtofn(vector<char>& dst, const wstring& src) { bool success = wstrtontbs(dst, src); if (!success) wcerr << L"Could not convert filename to narrow string: " << src << endl; return success; } static void blitstr(wstring& dst, const wstring& src) { dst = src; } static void blitstr(wstring& dst, const string& src) { dst.resize(src.size()); for (unsigned i = 0; i < src.size(); ++i) dst[i] = (wchar_t)(unsigned char)src[i]; } static void blitstr(string& dst, const wstring& src) { dst.resize(src.size()); for (unsigned i = 0; i < src.size(); ++i) dst[i] = (char)src[i]; } template<typename Ifstream, typename String, bool Text> bool fs_read(wstring* out, const wstring* in, Interpreter& interp, unsigned) { vector<char> fname; if (!wstrtofn(fname, in[0])) return false; Ifstream input(&fname[0], Text? ios::in : ios::in | ios::binary); if (!input) { out[0].clear(); out[1] = L"0"; return true; } String str; static String eof((size_t)1, 4); getline(input, str, eof[0]); blitstr(out[0], str); if (!input.fail() && !input.eof()) out[1] = L"1"; else out[1] = L"0"; return true; } static GlobalBinding<TFunctionParser<2,1,fs_read<wifstream, wstring, true> > > _read(L"read"); static GlobalBinding<TFunctionParser< 2,1,fs_read<ifstream, string, false> > > _readBinary(L"read-binary"); template<typename Ofstream, typename String, bool Text, bool Append> bool fs_write(wstring* out, const wstring* in, Interpreter& interp, unsigned) { vector<char> fname; String content; if (!wstrtofn(fname, in[0])) return false; blitstr(content, in[1]); ios_base::openmode mode = ios::out; if (!Text) mode |= ios::binary; if (Append) mode |= ios::app; else mode |= ios::trunc; Ofstream output(&fname[0], mode); if (!output) { out[0] = L"0"; return true; } output << content; out[0] = output? L"1" : L"0"; return true; } static GlobalBinding<TFunctionParser<1,2,fs_write<wofstream, wstring, true, false> > > _write(L"write"); static GlobalBinding<TFunctionParser<1,2,fs_write<wofstream, wstring, true, true> > > _append(L"append"); static GlobalBinding<TFunctionParser<1,2,fs_write<ofstream, string, false, false> > > _writeBinary(L"write-binary"); static GlobalBinding<TFunctionParser<1,2,fs_write<ofstream, string, false, true> > > _appendBinary(L"append-binary"); } <commit_msg>Fix read() always returning failure to status.<commit_after>#ifdef HAVE_CONFIG_H #include <config.h> #endif #include <iostream> #include <fstream> #include <string> #include <cstring> #include <cerrno> /* Use the POSIX glob(3) function if available. On a native Windows port, * you'll need to make your own glob(3) implementation and define HAVE_GLOB, or * entirely reimplement ls. */ #ifdef HAVE_GLOB_H #include <glob.h> #endif #include "../interp.hxx" #include "../command.hxx" #include "../function.hxx" #include "list.hxx" #include "../common.hxx" using namespace std; namespace tglng { #ifdef HAVE_GLOB //Define glob parms which might not exist #ifndef GLOB_BRACE # define GLOB_BRACE 0 #endif #ifndef GLOB_TILDE # define GLOB_TILDE 0 #endif bool fs_ls(wstring* out, const wstring* in, Interpreter& interp, unsigned) { glob_t results; out->clear(); //Transcode in[0] to a narrow string vector<char> pattern; if (!wstrtontbs(pattern, in[0])) { wcerr << L"Could not convert glob pattern to narrow string: " << *in << endl; return false; } //Perform the glob //If it fails, just return an empty list (*out is already empty); //otherwise, convert to a list. if (!glob(&pattern[0], GLOB_BRACE|GLOB_TILDE, NULL, &results)) { for (unsigned i = 0; i < results.gl_pathc; ++i) { wstring name; //Convert the filename back to a wide string if (!ntbstowstr(name, results.gl_pathv[i])) { //Print a warning about this one cerr << "WARN: Could not convert narrow filename to wide string: " << results.gl_pathv[i] << endl; continue; } //OK, add to the list list::lappend(*out, name); } globfree(&results); } return true; } static GlobalBinding<TFunctionParser<1,1,fs_ls> > _ls(L"ls"); #endif /* HAVE_GLOB */ /** * Converts the given wstring to a char*, stored within dst. The actual size * of dst is not defined; rather, the only guarantee is that &dst[0] is a * valid NTBS. * * If successful, returns true; otherwise, prints a diagnostic and returns * false. */ static bool wstrtofn(vector<char>& dst, const wstring& src) { bool success = wstrtontbs(dst, src); if (!success) wcerr << L"Could not convert filename to narrow string: " << src << endl; return success; } static void blitstr(wstring& dst, const wstring& src) { dst = src; } static void blitstr(wstring& dst, const string& src) { dst.resize(src.size()); for (unsigned i = 0; i < src.size(); ++i) dst[i] = (wchar_t)(unsigned char)src[i]; } static void blitstr(string& dst, const wstring& src) { dst.resize(src.size()); for (unsigned i = 0; i < src.size(); ++i) dst[i] = (char)src[i]; } template<typename Ifstream, typename String, bool Text> bool fs_read(wstring* out, const wstring* in, Interpreter& interp, unsigned) { vector<char> fname; if (!wstrtofn(fname, in[0])) return false; Ifstream input(&fname[0], Text? ios::in : ios::in | ios::binary); if (!input) { out[0].clear(); out[1] = L"0"; return true; } String str; static String eof((size_t)1, 4); getline(input, str, eof[0]); blitstr(out[0], str); if (!input.fail()) out[1] = L"1"; else out[1] = L"0"; return true; } static GlobalBinding<TFunctionParser<2,1,fs_read<wifstream, wstring, true> > > _read(L"read"); static GlobalBinding<TFunctionParser< 2,1,fs_read<ifstream, string, false> > > _readBinary(L"read-binary"); template<typename Ofstream, typename String, bool Text, bool Append> bool fs_write(wstring* out, const wstring* in, Interpreter& interp, unsigned) { vector<char> fname; String content; if (!wstrtofn(fname, in[0])) return false; blitstr(content, in[1]); ios_base::openmode mode = ios::out; if (!Text) mode |= ios::binary; if (Append) mode |= ios::app; else mode |= ios::trunc; Ofstream output(&fname[0], mode); if (!output) { out[0] = L"0"; return true; } output << content; out[0] = output? L"1" : L"0"; return true; } static GlobalBinding<TFunctionParser<1,2,fs_write<wofstream, wstring, true, false> > > _write(L"write"); static GlobalBinding<TFunctionParser<1,2,fs_write<wofstream, wstring, true, true> > > _append(L"append"); static GlobalBinding<TFunctionParser<1,2,fs_write<ofstream, string, false, false> > > _writeBinary(L"write-binary"); static GlobalBinding<TFunctionParser<1,2,fs_write<ofstream, string, false, true> > > _appendBinary(L"append-binary"); } <|endoftext|>
<commit_before>/* * Copyright (c) 2012, Dennis Hedback * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "common.hpp" #include <iostream> #include <vector> struct Counter { Set::const_iterator begin; Set::const_iterator end; Set::const_iterator current; }; typedef std::vector<Counter> Counters; void init_counters(Counters &ctrs, Generator &gen) { for (Generator::const_iterator set = gen.begin(); set != gen.end(); set++) { Counter ctr = { set->begin(), set->end(), set->begin() }; ctrs.push_back(ctr); } } void populate_tuple(Tuple &tup, Counters &ctrs) { for(Counters::const_iterator ctr = ctrs.begin(); ctr != ctrs.end(); ctr++) { tup.push_back(*(ctr->current)); } } int increment_counters(Counters &ctrs) { for (Counters::iterator ctr = ctrs.begin(); ; ) { (ctr->current)++; if (ctr->current == ctr->end) { if (ctr+1 == ctrs.end()) { return 1; } else { ctr->current = ctr->begin; ctr++; } } else { break; } } return 0; } void print_tuple(Tuple &tup) { for (Tuple::const_iterator ti = tup.begin(); ti != tup.end(); ti++) { std::cout << *ti; if (++ti != tup.end()) std::cout << ','; ti--; } std::cout << '\n'; } void cartesian_product(Generator &gen, Product &prod, bool print) { Counters ctrs; init_counters(ctrs, gen); while (true) { Tuple tup; populate_tuple(tup, ctrs); if (print) print_tuple(tup); else prod.insert(tup); if (increment_counters(ctrs) != 0) return; } } <commit_msg>Abolished the use of push_back to speed up the quotient executable.<commit_after>/* * Copyright (c) 2012, Dennis Hedback * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "common.hpp" #include <iostream> #include <vector> struct Counter { Set::const_iterator begin; Set::const_iterator end; Set::const_iterator current; }; typedef std::vector<Counter> Counters; void init_counters(Counters &ctrs, Generator &gen) { Counter tpl; ctrs = Counters(gen.size(), tpl); unsigned int i = 0; for (Generator::const_iterator set = gen.begin(); set != gen.end(); set++, i++) { ctrs[i].begin = set->begin(); ctrs[i].end = set->end(); ctrs[i].current = ctrs[i].begin; } } void populate_tuple(Tuple &tup, Counters &ctrs) { for(Counters::const_iterator ctr = ctrs.begin(); ctr != ctrs.end(); ctr++) { tup.push_back(*(ctr->current)); } } int increment_counters(Counters &ctrs) { for (Counters::iterator ctr = ctrs.begin(); ; ) { (ctr->current)++; if (ctr->current == ctr->end) { if (ctr+1 == ctrs.end()) { return 1; } else { ctr->current = ctr->begin; ctr++; } } else { break; } } return 0; } void print_tuple(Tuple &tup) { for (Tuple::const_iterator ti = tup.begin(); ti != tup.end(); ti++) { std::cout << *ti; if (++ti != tup.end()) std::cout << ','; ti--; } std::cout << '\n'; } void cartesian_product(Generator &gen, Product &prod, bool print) { Counters ctrs; init_counters(ctrs, gen); while (true) { Tuple tup; populate_tuple(tup, ctrs); if (print) print_tuple(tup); else prod.insert(tup); if (increment_counters(ctrs) != 0) return; } } <|endoftext|>
<commit_before>/* * Copyright (c) 2011, Peter Thorson. 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 WebSocket++ Project 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 PETER THORSON 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 WEBSOCKET_CONSTANTS_HPP #define WEBSOCKET_CONSTANTS_HPP #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS #endif #include <stdint.h> #include <exception> #include <string> #include <vector> #include <boost/shared_ptr.hpp> // Defaults namespace websocketpp { typedef std::vector<unsigned char> binary_string; typedef boost::shared_ptr<binary_string> binary_string_ptr; typedef std::string utf8_string; typedef boost::shared_ptr<utf8_string> utf8_string_ptr; const uint64_t DEFAULT_MAX_MESSAGE_SIZE = 0xFFFFFF; // ~16MB const uint16_t DEFAULT_PORT = 80; const uint16_t DEFAULT_SECURE_PORT = 443; inline uint16_t default_port(bool secure) { return (secure ? DEFAULT_SECURE_PORT : DEFAULT_PORT); } namespace session { namespace state { enum value { CONNECTING = 0, OPEN = 1, CLOSING = 2, CLOSED = 3 }; } } namespace close { namespace status { enum value { INVALID_END = 999, NORMAL = 1000, GOING_AWAY = 1001, PROTOCOL_ERROR = 1002, UNSUPPORTED_DATA = 1003, RSV_ADHOC_1 = 1004, NO_STATUS = 1005, ABNORMAL_CLOSE = 1006, INVALID_PAYLOAD = 1007, POLICY_VIOLATION = 1008, MESSAGE_TOO_BIG = 1009, EXTENSION_REQUIRE = 1010, INTERNAL_ENDPOINT_ERROR = 1011, RSV_START = 1012, RSV_END = 2999, INVALID_START = 5000 }; inline bool reserved(value s) { return ((s >= RSV_START && s <= RSV_END) || s == RSV_ADHOC_1); } inline bool invalid(value s) { return ((s <= INVALID_END || s >= INVALID_START) || s == NO_STATUS || s == ABNORMAL_CLOSE); } // TODO functions for application ranges? } // namespace status } // namespace close namespace frame { // Opcodes are 4 bits // See spec section 5.2 namespace opcode { enum value { CONTINUATION = 0x0, TEXT = 0x1, BINARY = 0x2, RSV3 = 0x3, RSV4 = 0x4, RSV5 = 0x5, RSV6 = 0x6, RSV7 = 0x7, CLOSE = 0x8, PING = 0x9, PONG = 0xA, CONTROL_RSVB = 0xB, CONTROL_RSVC = 0xC, CONTROL_RSVD = 0xD, CONTROL_RSVE = 0xE, CONTROL_RSVF = 0xF, }; inline bool reserved(value v) { return (v >= RSV3 && v <= RSV7) || (v >= CONTROL_RSVB && v <= CONTROL_RSVF); } inline bool invalid(value v) { return (v > 0xF || v < 0); } inline bool is_control(value v) { return v >= 0x8; } } namespace limits { static const uint8_t PAYLOAD_SIZE_BASIC = 125; static const uint16_t PAYLOAD_SIZE_EXTENDED = 0xFFFF; // 2^16, 65535 static const uint64_t PAYLOAD_SIZE_JUMBO = 0x7FFFFFFFFFFFFFFF;//2^63 } } // namespace frame // exception class for errors that should be propogated back to the user. namespace error { enum value { GENERIC = 0, // send attempted when endpoint write queue was full SEND_QUEUE_FULL = 1, PAYLOAD_VIOLATION = 2, ENDPOINT_UNSECURE = 3, ENDPOINT_UNAVAILABLE = 4 }; } class exception : public std::exception { public: exception(const std::string& msg, error::value code = error::GENERIC) : m_msg(msg),m_code(code) {} ~exception() throw() {} virtual const char* what() const throw() { return m_msg.c_str(); } error::value code() const throw() { return m_code; } std::string m_msg; error::value m_code; }; } #endif // WEBSOCKET_CONSTANTS_HPP <commit_msg>adds SIZE_MAX definition<commit_after>/* * Copyright (c) 2011, Peter Thorson. 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 WebSocket++ Project 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 PETER THORSON 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 WEBSOCKET_CONSTANTS_HPP #define WEBSOCKET_CONSTANTS_HPP #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS #endif #include <stdint.h> // SIZE_MAX appears to be a compiler thing not an OS header thing. // make sure it is defined. #ifndef SIZE_MAX #define SIZE_MAX ((size_t)(-1)) #endif #include <exception> #include <string> #include <vector> #include <boost/shared_ptr.hpp> // Defaults namespace websocketpp { typedef std::vector<unsigned char> binary_string; typedef boost::shared_ptr<binary_string> binary_string_ptr; typedef std::string utf8_string; typedef boost::shared_ptr<utf8_string> utf8_string_ptr; const uint64_t DEFAULT_MAX_MESSAGE_SIZE = 0xFFFFFF; // ~16MB const uint16_t DEFAULT_PORT = 80; const uint16_t DEFAULT_SECURE_PORT = 443; inline uint16_t default_port(bool secure) { return (secure ? DEFAULT_SECURE_PORT : DEFAULT_PORT); } namespace session { namespace state { enum value { CONNECTING = 0, OPEN = 1, CLOSING = 2, CLOSED = 3 }; } } namespace close { namespace status { enum value { INVALID_END = 999, NORMAL = 1000, GOING_AWAY = 1001, PROTOCOL_ERROR = 1002, UNSUPPORTED_DATA = 1003, RSV_ADHOC_1 = 1004, NO_STATUS = 1005, ABNORMAL_CLOSE = 1006, INVALID_PAYLOAD = 1007, POLICY_VIOLATION = 1008, MESSAGE_TOO_BIG = 1009, EXTENSION_REQUIRE = 1010, INTERNAL_ENDPOINT_ERROR = 1011, RSV_START = 1012, RSV_END = 2999, INVALID_START = 5000 }; inline bool reserved(value s) { return ((s >= RSV_START && s <= RSV_END) || s == RSV_ADHOC_1); } inline bool invalid(value s) { return ((s <= INVALID_END || s >= INVALID_START) || s == NO_STATUS || s == ABNORMAL_CLOSE); } // TODO functions for application ranges? } // namespace status } // namespace close namespace frame { // Opcodes are 4 bits // See spec section 5.2 namespace opcode { enum value { CONTINUATION = 0x0, TEXT = 0x1, BINARY = 0x2, RSV3 = 0x3, RSV4 = 0x4, RSV5 = 0x5, RSV6 = 0x6, RSV7 = 0x7, CLOSE = 0x8, PING = 0x9, PONG = 0xA, CONTROL_RSVB = 0xB, CONTROL_RSVC = 0xC, CONTROL_RSVD = 0xD, CONTROL_RSVE = 0xE, CONTROL_RSVF = 0xF, }; inline bool reserved(value v) { return (v >= RSV3 && v <= RSV7) || (v >= CONTROL_RSVB && v <= CONTROL_RSVF); } inline bool invalid(value v) { return (v > 0xF || v < 0); } inline bool is_control(value v) { return v >= 0x8; } } namespace limits { static const uint8_t PAYLOAD_SIZE_BASIC = 125; static const uint16_t PAYLOAD_SIZE_EXTENDED = 0xFFFF; // 2^16, 65535 static const uint64_t PAYLOAD_SIZE_JUMBO = 0x7FFFFFFFFFFFFFFF;//2^63 } } // namespace frame // exception class for errors that should be propogated back to the user. namespace error { enum value { GENERIC = 0, // send attempted when endpoint write queue was full SEND_QUEUE_FULL = 1, PAYLOAD_VIOLATION = 2, ENDPOINT_UNSECURE = 3, ENDPOINT_UNAVAILABLE = 4 }; } class exception : public std::exception { public: exception(const std::string& msg, error::value code = error::GENERIC) : m_msg(msg),m_code(code) {} ~exception() throw() {} virtual const char* what() const throw() { return m_msg.c_str(); } error::value code() const throw() { return m_code; } std::string m_msg; error::value m_code; }; } #endif // WEBSOCKET_CONSTANTS_HPP <|endoftext|>
<commit_before>/* * This file is part of the QPackageKit project * Copyright (C) 2008 Adrien Bustany <[email protected]> * Copyright (C) 2010-2011 Daniel Nicoletti <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include <QtSql> #include <QDebug> #include "daemon.h" #include "daemonprivate.h" #include "daemonproxy.h" #include "common.h" using namespace PackageKit; Daemon* Daemon::m_global = 0; Daemon* Daemon::global() { if(!m_global) { m_global = new Daemon(qApp); } return m_global; } Daemon::Daemon(QObject *parent) : QObject(parent), d_ptr(new DaemonPrivate(this)) { Q_D(Daemon); d->daemon = new ::DaemonProxy(QLatin1String(PK_NAME), QLatin1String(PK_PATH), QDBusConnection::systemBus(), this); connect(d->daemon, SIGNAL(Changed()), this, SIGNAL(changed())); connect(d->daemon, SIGNAL(RepoListChanged()), this, SIGNAL(repoListChanged())); connect(d->daemon, SIGNAL(RestartSchedule()), this, SIGNAL(restartScheduled())); connect(d->daemon, SIGNAL(TransactionListChanged(QStringList)), this, SIGNAL(transactionListChanged(QStringList))); connect(d->daemon, SIGNAL(UpdatesChanged()), this, SIGNAL(updatesChanged())); // Set up database for desktop files QSqlDatabase db; db = QSqlDatabase::addDatabase("QSQLITE", PK_DESKTOP_DEFAULT_DATABASE); db.setDatabaseName(PK_DESKTOP_DEFAULT_DATABASE); if (!db.open()) { qDebug() << "Failed to initialize the desktop files database"; } } Daemon::~Daemon() { } Transaction::Roles Daemon::actions() { Q_D(const Daemon); return d->daemon->roles(); } QString Daemon::backendName() { Q_D(const Daemon); return d->daemon->backendName(); } QString Daemon::backendDescription() { Q_D(const Daemon); return d->daemon->backendDescription(); } QString Daemon::backendAuthor() { Q_D(const Daemon); return d->daemon->backendAuthor(); } Transaction::Filters Daemon::filters() { Q_D(const Daemon); return static_cast<Transaction::Filters>(d->daemon->filters()); } Transaction::Groups Daemon::groups() { Q_D(const Daemon); return static_cast<Transaction::Groups>(d->daemon->groups()); } bool Daemon::locked() { Q_D(const Daemon); return d->daemon->locked(); } QStringList Daemon::mimeTypes() { Q_D(const Daemon); return d->daemon->mimeTypes(); } Daemon::Network Daemon::networkState() { Q_D(const Daemon); return static_cast<Daemon::Network>(d->daemon->networkState()); } QString Daemon::distroID() { Q_D(const Daemon); return d->daemon->distroId(); } Daemon::Authorize Daemon::canAuthorize(const QString &actionId) { Q_D(const Daemon); uint ret; ret = d->daemon->CanAuthorize(actionId); return static_cast<Daemon::Authorize>(ret); } QDBusObjectPath Daemon::getTid() { Q_D(const Daemon); return d->daemon->CreateTransaction(); } uint Daemon::getTimeSinceAction(Transaction::Role role) { Q_D(const Daemon); return d->daemon->GetTimeSinceAction(role); } QList<QDBusObjectPath> Daemon::getTransactionList() { Q_D(const Daemon); return d->daemon->GetTransactionList(); } QList<Transaction*> Daemon::getTransactionObjects(QObject *parent) { Q_D(Daemon); return d->transactions(getTransactionList(), parent); } void Daemon::setHints(const QStringList &hints) { Q_D(Daemon); d->hints = hints; } void Daemon::setHints(const QString &hints) { Q_D(Daemon); d->hints = QStringList() << hints; } QStringList Daemon::hints() { Q_D(const Daemon); return d->hints; } Transaction::InternalError Daemon::setProxy(const QString& http_proxy, const QString& https_proxy, const QString& ftp_proxy, const QString& socks_proxy, const QString& no_proxy, const QString& pac) { Q_D(const Daemon); QDBusPendingReply<> r = d->daemon->SetProxy(http_proxy, https_proxy, ftp_proxy, socks_proxy, no_proxy, pac); r.waitForFinished(); if (r.isError ()) { return Transaction::parseError(r.error().name()); } else { return Transaction::InternalErrorNone; } } void Daemon::stateHasChanged(const QString& reason) { Q_D(const Daemon); d->daemon->StateHasChanged(reason); } void Daemon::suggestDaemonQuit() { Q_D(const Daemon); d->daemon->SuggestDaemonQuit(); } uint Daemon::versionMajor() { Q_D(const Daemon); return d->daemon->versionMajor(); } uint Daemon::versionMinor() { Q_D(const Daemon); return d->daemon->versionMinor(); } uint Daemon::versionMicro() { Q_D(const Daemon); return d->daemon->versionMicro(); } QString Daemon::packageName(const QString &packageID) { return packageID.section(QLatin1Char(';'), 0, 0); } QString Daemon::packageVersion(const QString &packageID) { return packageID.section(QLatin1Char(';'), 1, 1); } QString Daemon::packageArch(const QString &packageID) { return packageID.section(QLatin1Char(';'), 2, 2); } QString Daemon::packageData(const QString &packageID) { return packageID.section(QLatin1Char(';'), 3, 3); } QString Daemon::packageIcon(const QString &packageID) { return Transaction::packageIcon(packageID); } #include "daemon.moc" <commit_msg>Make sure we waitForFinishe() when getting the TransactionList Trying to fix kde BUG:286500<commit_after>/* * This file is part of the QPackageKit project * Copyright (C) 2008 Adrien Bustany <[email protected]> * Copyright (C) 2010-2011 Daniel Nicoletti <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include <QtSql> #include <QDebug> #include "daemon.h" #include "daemonprivate.h" #include "daemonproxy.h" #include "common.h" using namespace PackageKit; Daemon* Daemon::m_global = 0; Daemon* Daemon::global() { if(!m_global) { m_global = new Daemon(qApp); } return m_global; } Daemon::Daemon(QObject *parent) : QObject(parent), d_ptr(new DaemonPrivate(this)) { Q_D(Daemon); d->daemon = new ::DaemonProxy(QLatin1String(PK_NAME), QLatin1String(PK_PATH), QDBusConnection::systemBus(), this); connect(d->daemon, SIGNAL(Changed()), this, SIGNAL(changed())); connect(d->daemon, SIGNAL(RepoListChanged()), this, SIGNAL(repoListChanged())); connect(d->daemon, SIGNAL(RestartSchedule()), this, SIGNAL(restartScheduled())); connect(d->daemon, SIGNAL(TransactionListChanged(QStringList)), this, SIGNAL(transactionListChanged(QStringList))); connect(d->daemon, SIGNAL(UpdatesChanged()), this, SIGNAL(updatesChanged())); // Set up database for desktop files QSqlDatabase db; db = QSqlDatabase::addDatabase("QSQLITE", PK_DESKTOP_DEFAULT_DATABASE); db.setDatabaseName(PK_DESKTOP_DEFAULT_DATABASE); if (!db.open()) { qDebug() << "Failed to initialize the desktop files database"; } } Daemon::~Daemon() { } Transaction::Roles Daemon::actions() { Q_D(const Daemon); return d->daemon->roles(); } QString Daemon::backendName() { Q_D(const Daemon); return d->daemon->backendName(); } QString Daemon::backendDescription() { Q_D(const Daemon); return d->daemon->backendDescription(); } QString Daemon::backendAuthor() { Q_D(const Daemon); return d->daemon->backendAuthor(); } Transaction::Filters Daemon::filters() { Q_D(const Daemon); return static_cast<Transaction::Filters>(d->daemon->filters()); } Transaction::Groups Daemon::groups() { Q_D(const Daemon); return static_cast<Transaction::Groups>(d->daemon->groups()); } bool Daemon::locked() { Q_D(const Daemon); return d->daemon->locked(); } QStringList Daemon::mimeTypes() { Q_D(const Daemon); return d->daemon->mimeTypes(); } Daemon::Network Daemon::networkState() { Q_D(const Daemon); return static_cast<Daemon::Network>(d->daemon->networkState()); } QString Daemon::distroID() { Q_D(const Daemon); return d->daemon->distroId(); } Daemon::Authorize Daemon::canAuthorize(const QString &actionId) { Q_D(const Daemon); uint ret; ret = d->daemon->CanAuthorize(actionId); return static_cast<Daemon::Authorize>(ret); } QDBusObjectPath Daemon::getTid() { Q_D(const Daemon); return d->daemon->CreateTransaction(); } uint Daemon::getTimeSinceAction(Transaction::Role role) { Q_D(const Daemon); return d->daemon->GetTimeSinceAction(role); } QList<QDBusObjectPath> Daemon::getTransactionList() { Q_D(const Daemon); QDBusPendingReply<QList<QDBusObjectPath> > reply = d->daemon->GetTransactionList(); if (reply.isValid()) { return reply.value(); } return QList<QDBusObjectPath>(); } QList<Transaction*> Daemon::getTransactionObjects(QObject *parent) { Q_D(Daemon); return d->transactions(getTransactionList(), parent); } void Daemon::setHints(const QStringList &hints) { Q_D(Daemon); d->hints = hints; } void Daemon::setHints(const QString &hints) { Q_D(Daemon); d->hints = QStringList() << hints; } QStringList Daemon::hints() { Q_D(const Daemon); return d->hints; } Transaction::InternalError Daemon::setProxy(const QString& http_proxy, const QString& https_proxy, const QString& ftp_proxy, const QString& socks_proxy, const QString& no_proxy, const QString& pac) { Q_D(const Daemon); QDBusPendingReply<> r = d->daemon->SetProxy(http_proxy, https_proxy, ftp_proxy, socks_proxy, no_proxy, pac); r.waitForFinished(); if (r.isError ()) { return Transaction::parseError(r.error().name()); } else { return Transaction::InternalErrorNone; } } void Daemon::stateHasChanged(const QString& reason) { Q_D(const Daemon); d->daemon->StateHasChanged(reason); } void Daemon::suggestDaemonQuit() { Q_D(const Daemon); d->daemon->SuggestDaemonQuit(); } uint Daemon::versionMajor() { Q_D(const Daemon); return d->daemon->versionMajor(); } uint Daemon::versionMinor() { Q_D(const Daemon); return d->daemon->versionMinor(); } uint Daemon::versionMicro() { Q_D(const Daemon); return d->daemon->versionMicro(); } QString Daemon::packageName(const QString &packageID) { return packageID.section(QLatin1Char(';'), 0, 0); } QString Daemon::packageVersion(const QString &packageID) { return packageID.section(QLatin1Char(';'), 1, 1); } QString Daemon::packageArch(const QString &packageID) { return packageID.section(QLatin1Char(';'), 2, 2); } QString Daemon::packageData(const QString &packageID) { return packageID.section(QLatin1Char(';'), 3, 3); } QString Daemon::packageIcon(const QString &packageID) { return Transaction::packageIcon(packageID); } #include "daemon.moc" <|endoftext|>
<commit_before>/* * Copyright (c) 2013-2015 John Connor (BM-NC49AxAjcqVcF5jNPu85Rb8MJ2d9JqZt) * * This file is part of vanillacoin. * * vanillacoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU 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/>. */ #if (defined _MSC_VER) #ifndef S_IRUSR #define S_IRUSR 0400 #define S_IWUSR 0200 #endif // S_IRUSR #else #include <sys/stat.h> #endif // _MSC_VER #include <cassert> #include <sstream> #include <coin/db_env.hpp> #include <coin/globals.hpp> #include <coin/logger.hpp> #include <coin/utility.hpp> using namespace coin; db_env::db_env() : m_DbEnv(DB_CXX_NO_EXCEPTIONS) , state_(state_closed) { // ... } db_env::~db_env() { close_DbEnv(); } bool db_env::open(const std::string & data_path) { if (state_ == state_closed) { filesystem::create_path(data_path); auto log_path = data_path + "/database"; filesystem::create_path(log_path); auto errfile_path = data_path + "/db.log"; std::int32_t flags = DB_CREATE | DB_INIT_LOCK | DB_INIT_LOG | DB_INIT_MPOOL | DB_INIT_TXN | DB_THREAD | DB_RECOVER ; auto cache = 25; std::lock_guard<std::recursive_mutex> l1(m_mutex_DbEnv); m_DbEnv.set_lg_dir(log_path.c_str()); m_DbEnv.set_cachesize(cache / 1024, (cache % 1024) * 1048576, 1); m_DbEnv.set_lg_bsize(1048576); m_DbEnv.set_lg_max(10485760); m_DbEnv.set_lk_max_locks(10000); m_DbEnv.set_lk_max_objects(10000); m_DbEnv.set_errfile(fopen(errfile_path.c_str(), "a")); m_DbEnv.set_flags(DB_AUTO_COMMIT, 1); m_DbEnv.set_flags(DB_TXN_WRITE_NOSYNC, 1); auto ret = m_DbEnv.open(data_path.c_str(), flags, S_IRUSR | S_IWUSR); if (ret != 0) { log_error( "Database environment open failed, error = " << DbEnv::strerror(ret) << "." ); } else { state_ = state_opened; } return ret == 0; } else if (state_ == state_opened) { return true; } return false; } void db_env::close_DbEnv() { if (state_ == state_opened) { state_ = state_closed; std::lock_guard<std::recursive_mutex> l1(m_mutex_DbEnv); auto ret = m_DbEnv.close(0); if (ret != 0) { log_error( "Database environment closed failed, error = " << DbEnv::strerror(ret) << "." ); } std::string data_path = filesystem::data_path(); DbEnv(0).remove(data_path.c_str(), 0); } } void db_env::close_Db(const std::string & file_name) { std::lock_guard<std::recursive_mutex> l1(mutex_m_Dbs_); auto & ptr_Db = m_Dbs[file_name]; if (ptr_Db) { ptr_Db->close(0); delete ptr_Db, ptr_Db = 0; } } bool db_env::remove_Db(const std::string & file_name) { this->close_Db(file_name); std::lock_guard<std::recursive_mutex> l1(m_mutex_DbEnv); int ret = m_DbEnv.dbremove(0, file_name.c_str(), 0, DB_AUTO_COMMIT); return ret == 0; } bool db_env::verify(const std::string & file_name) { std::lock_guard<std::recursive_mutex> l1(mutex_file_use_counts_); assert(m_file_use_counts.count(file_name) == 0); std::lock_guard<std::recursive_mutex> l2(m_mutex_DbEnv); Db db(&m_DbEnv, 0); auto result = db.verify(file_name.c_str(), 0, 0, 0); return result == 0; } bool db_env::salvage( const std::string & file_name, const bool & aggressive, std::vector< std::pair< std::vector<std::uint8_t>, std::vector<std::uint8_t> > > & result ) { std::lock_guard<std::recursive_mutex> l1(mutex_file_use_counts_); assert(m_file_use_counts.count(file_name) == 0); std::lock_guard<std::recursive_mutex> l2(m_mutex_DbEnv); std::uint32_t flags = DB_SALVAGE; if (aggressive) { flags |= DB_AGGRESSIVE; } std::stringstream dump; Db db(&m_DbEnv, 0); int ret = db.verify(file_name.c_str(), 0, &dump, flags); if (ret != 0) { log_error("Database environment salvage failed."); return false; } std::string line; while (dump.eof() == false && line != "HEADER=END") { getline(dump, line); } std::string key, value; while (dump.eof() == false && key != "DATA=END") { getline(dump, key); if (key != "DATA=END") { getline(dump, value); result.push_back( std::make_pair(utility::from_hex(key), utility::from_hex(value)) ); } } return ret == 0; } void db_env::checkpoint_lsn(const std::string & file_name) { std::lock_guard<std::recursive_mutex> l2(m_mutex_DbEnv); m_DbEnv.txn_checkpoint(0, 0, 0); m_DbEnv.lsn_reset(file_name.c_str(), 0); } void db_env::flush() { if (state_ == state_opened) { globals::instance().io_service().post(globals::instance().strand().wrap( [this]() { std::lock_guard<std::recursive_mutex> l1(mutex_file_use_counts_); auto it = m_file_use_counts.begin(); while (it != m_file_use_counts.end()) { auto file_name = it->first; auto reference_count = it->second; log_debug( "Db Env " << file_name << ", reference count = " << reference_count << "." ); if (reference_count == 0) { /** * Move the log data to the dat file. */ close_Db(file_name); log_debug("Db Env checkpoint " << file_name << "."); std::lock_guard<std::recursive_mutex> l2(m_mutex_DbEnv); m_DbEnv.txn_checkpoint(0, 0, 0); static bool detach_db = true; if ( utility::is_chain_file(file_name) == false || detach_db ) { log_debug("Db Env detach " << file_name << "."); m_DbEnv.lsn_reset(file_name.c_str(), 0); } log_debug("Db Env closed " << file_name << "."); m_file_use_counts.erase(it++); } else { it++; } } if (globals::instance().state() > globals::state_started) { if (m_file_use_counts.empty()) { char ** list; std::lock_guard<std::recursive_mutex> l3(m_mutex_DbEnv); m_DbEnv.log_archive(&list, DB_ARCH_REMOVE); close_DbEnv(); } } })); } } DbEnv & db_env::get_DbEnv() { std::lock_guard<std::recursive_mutex> l1(m_mutex_DbEnv); return m_DbEnv; } std::map<std::string, std::uint32_t> & db_env::file_use_counts() { std::lock_guard<std::recursive_mutex> l1(mutex_file_use_counts_); return m_file_use_counts; } std::map<std::string, Db *> & db_env::Dbs() { std::lock_guard<std::recursive_mutex> l1(mutex_m_Dbs_); return m_Dbs; } std::recursive_mutex & db_env::mutex_DbEnv() { return m_mutex_DbEnv; } DbTxn * db_env::txn_begin(int flags) { DbTxn * ptr = 0; std::lock_guard<std::recursive_mutex> l1(m_mutex_DbEnv); int ret = m_DbEnv.txn_begin(0, &ptr, flags); if (ret == ENOMEM) { log_debug("Database environment txn_begin failed, ENOMEM."); return 0; } else if (ret != 0) { return 0; } return ptr; } <commit_msg>Fixes for Android + Berkley DB<commit_after>/* * Copyright (c) 2013-2015 John Connor (BM-NC49AxAjcqVcF5jNPu85Rb8MJ2d9JqZt) * * This file is part of vanillacoin. * * vanillacoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU 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/>. */ #if (defined _MSC_VER) #ifndef S_IRUSR #define S_IRUSR 0400 #define S_IWUSR 0200 #endif // S_IRUSR #else #include <sys/stat.h> #endif // _MSC_VER #include <cassert> #include <sstream> #include <coin/db_env.hpp> #include <coin/globals.hpp> #include <coin/logger.hpp> #include <coin/utility.hpp> using namespace coin; db_env::db_env() : m_DbEnv(DB_CXX_NO_EXCEPTIONS) , state_(state_closed) { // ... } db_env::~db_env() { close_DbEnv(); } bool db_env::open(const std::string & data_path) { if (state_ == state_closed) { filesystem::create_path(data_path); auto log_path = data_path + "database"; log_info("Database environment log path = " << log_path << "."); filesystem::create_path(log_path); auto errfile_path = data_path + "db.log"; log_info("Database environment err path = " << errfile_path << "."); std::int32_t flags = DB_CREATE | DB_INIT_LOCK | DB_INIT_LOG | DB_INIT_MPOOL | DB_INIT_TXN | DB_THREAD | DB_RECOVER ; auto cache = 25; std::lock_guard<std::recursive_mutex> l1(m_mutex_DbEnv); m_DbEnv.set_lg_dir(log_path.c_str()); m_DbEnv.set_cachesize(cache / 1024, (cache % 1024) * 1048576, 1); m_DbEnv.set_lg_bsize(1048576); m_DbEnv.set_lg_max(10485760); m_DbEnv.set_lk_max_locks(10000); m_DbEnv.set_lk_max_objects(10000); m_DbEnv.set_errfile(fopen(errfile_path.c_str(), "a")); m_DbEnv.set_flags(DB_AUTO_COMMIT, 1); m_DbEnv.set_flags(DB_TXN_WRITE_NOSYNC, 1); auto ret = m_DbEnv.open(data_path.c_str(), flags, S_IRUSR | S_IWUSR); if (ret != 0) { log_error( "Database environment open failed, error = " << DbEnv::strerror(ret) << "." ); } else { state_ = state_opened; } return ret == 0; } else if (state_ == state_opened) { return true; } return false; } void db_env::close_DbEnv() { if (state_ == state_opened) { state_ = state_closed; std::lock_guard<std::recursive_mutex> l1(m_mutex_DbEnv); auto ret = m_DbEnv.close(0); if (ret != 0) { log_error( "Database environment closed failed, error = " << DbEnv::strerror(ret) << "." ); } std::string data_path = filesystem::data_path(); DbEnv(0).remove(data_path.c_str(), 0); } } void db_env::close_Db(const std::string & file_name) { std::lock_guard<std::recursive_mutex> l1(mutex_m_Dbs_); auto & ptr_Db = m_Dbs[file_name]; if (ptr_Db) { ptr_Db->close(0); delete ptr_Db, ptr_Db = 0; } } bool db_env::remove_Db(const std::string & file_name) { this->close_Db(file_name); std::lock_guard<std::recursive_mutex> l1(m_mutex_DbEnv); int ret = m_DbEnv.dbremove(0, file_name.c_str(), 0, DB_AUTO_COMMIT); return ret == 0; } bool db_env::verify(const std::string & file_name) { std::lock_guard<std::recursive_mutex> l1(mutex_file_use_counts_); assert(m_file_use_counts.count(file_name) == 0); std::lock_guard<std::recursive_mutex> l2(m_mutex_DbEnv); Db db(&m_DbEnv, 0); auto result = db.verify(file_name.c_str(), 0, 0, 0); return result == 0; } bool db_env::salvage( const std::string & file_name, const bool & aggressive, std::vector< std::pair< std::vector<std::uint8_t>, std::vector<std::uint8_t> > > & result ) { std::lock_guard<std::recursive_mutex> l1(mutex_file_use_counts_); assert(m_file_use_counts.count(file_name) == 0); std::lock_guard<std::recursive_mutex> l2(m_mutex_DbEnv); std::uint32_t flags = DB_SALVAGE; if (aggressive) { flags |= DB_AGGRESSIVE; } std::stringstream dump; Db db(&m_DbEnv, 0); int ret = db.verify(file_name.c_str(), 0, &dump, flags); if (ret != 0) { log_error("Database environment salvage failed."); return false; } std::string line; while (dump.eof() == false && line != "HEADER=END") { getline(dump, line); } std::string key, value; while (dump.eof() == false && key != "DATA=END") { getline(dump, key); if (key != "DATA=END") { getline(dump, value); result.push_back( std::make_pair(utility::from_hex(key), utility::from_hex(value)) ); } } return ret == 0; } void db_env::checkpoint_lsn(const std::string & file_name) { std::lock_guard<std::recursive_mutex> l2(m_mutex_DbEnv); m_DbEnv.txn_checkpoint(0, 0, 0); m_DbEnv.lsn_reset(file_name.c_str(), 0); } void db_env::flush() { if (state_ == state_opened) { globals::instance().io_service().post(globals::instance().strand().wrap( [this]() { std::lock_guard<std::recursive_mutex> l1(mutex_file_use_counts_); auto it = m_file_use_counts.begin(); while (it != m_file_use_counts.end()) { auto file_name = it->first; auto reference_count = it->second; log_debug( "Db Env " << file_name << ", reference count = " << reference_count << "." ); if (reference_count == 0) { /** * Move the log data to the dat file. */ close_Db(file_name); log_debug("Db Env checkpoint " << file_name << "."); std::lock_guard<std::recursive_mutex> l2(m_mutex_DbEnv); m_DbEnv.txn_checkpoint(0, 0, 0); static bool detach_db = true; if ( utility::is_chain_file(file_name) == false || detach_db ) { log_debug("Db Env detach " << file_name << "."); m_DbEnv.lsn_reset(file_name.c_str(), 0); } log_debug("Db Env closed " << file_name << "."); m_file_use_counts.erase(it++); } else { it++; } } if (globals::instance().state() > globals::state_started) { if (m_file_use_counts.empty()) { char ** list; std::lock_guard<std::recursive_mutex> l3(m_mutex_DbEnv); m_DbEnv.log_archive(&list, DB_ARCH_REMOVE); close_DbEnv(); } } })); } } DbEnv & db_env::get_DbEnv() { std::lock_guard<std::recursive_mutex> l1(m_mutex_DbEnv); return m_DbEnv; } std::map<std::string, std::uint32_t> & db_env::file_use_counts() { std::lock_guard<std::recursive_mutex> l1(mutex_file_use_counts_); return m_file_use_counts; } std::map<std::string, Db *> & db_env::Dbs() { std::lock_guard<std::recursive_mutex> l1(mutex_m_Dbs_); return m_Dbs; } std::recursive_mutex & db_env::mutex_DbEnv() { return m_mutex_DbEnv; } DbTxn * db_env::txn_begin(int flags) { DbTxn * ptr = 0; std::lock_guard<std::recursive_mutex> l1(m_mutex_DbEnv); int ret = m_DbEnv.txn_begin(0, &ptr, flags); if (ret == ENOMEM) { log_debug("Database environment txn_begin failed, ENOMEM."); return 0; } else if (ret != 0) { return 0; } return ptr; } <|endoftext|>
<commit_before>/* Linguagens de Programação 2017.1 * Autorship: Daniel Barbosa and Erick Silva * * Implementation of the List ADT using doubly linked list */ // Quick compilation // g++ src/driver.cpp -o bin/list -I include -Wall -std=c++11 #include <iostream> #include <cassert> #include "list.h" using namespace ls; template <typename T> void print( list<T> & v ) { typename list<T>::const_iterator b_it = v.begin(); typename list<T>::const_iterator e_it = v.end(); std::cout << "[ "; for ( /*empty*/; b_it != e_it; ++b_it ) std::cout << *b_it << " "; std::cout << "]\n"; } int main() { // Teste construtor vazio. // list<int> listaVazia; std::cout << "Lista Vazia" << std::endl; print( listaVazia ); // Criando nova lista vazia list<int> listaInteiros = { 2 , 5 , 7 , 8 , 9 , 11 , 15 }; return 0; }<commit_msg>insignificant change<commit_after>/* Linguagens de Programação 2017.1 * Autorship: Daniel Barbosa and Erick Silva * * Implementation of the List ADT using doubly linked list */ // Quick compilation // g++ src/driver.cpp -o bin/list -I include -Wall -std=c++11 #include <iostream> #include <cassert> #include "list.h" using namespace ls; template <typename T> void print( list<T> & v ) { typename list<T>::const_iterator b_it = v.begin(); typename list<T>::const_iterator e_it = v.end(); std::cout << "[ "; for ( /* EMPTY */; b_it != e_it; ++b_it ) std::cout << *b_it << " "; std::cout << "]\n"; } int main() { // Teste construtor vazio. // list<int> listaVazia; std::cout << "Lista Vazia" << std::endl; print( listaVazia ); // Criando nova lista vazia list<int> listaInteiros = { 2 , 5 , 7 , 8 , 9 , 11 , 15 }; return 0; }<|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> #include "RCSwitch.h" namespace { const std::size_t UNIX_PATH_MAX = 108; const std::size_t gpio_pin = 2; //Buffers char write_buffer[4096]; char receive_buffer[4096]; bool revoke_root(){ if (getuid() == 0) { if (setgid(1000) != 0){ std::cout << "asgard:dht11: setgid: Unable to drop group privileges: " << strerror(errno) << std::endl; return false; } if (setuid(1000) != 0){ std::cout << "asgard:dht11: setgid: Unable to drop user privileges: " << strerror(errno) << std::endl; return false; } } if (setuid(0) != -1){ std::cout << "asgard:dht11: managed to regain root privileges, exiting..." << std::endl; return false; } return true; } void decode_wt450(unsigned long data, int socket_fd, int temperature_sensor, int humidity_sensor){ int house=(data>>28) & (0x0f); byte station=((data>>26) & (0x03))+1; int humidity=(data>>16)&(0xff); double temperature=((data>>8) & (0xff)); temperature = temperature - 50; byte tempfraction=(data>>4) & (0x0f); double tempdecimal=((tempfraction>>3 & 1) * 0.5) + ((tempfraction>>2 & 1) * 0.25) + ((tempfraction>>1 & 1) * 0.125) + ((tempfraction & 1) * 0.0625); temperature=temperature+tempdecimal; temperature=(int)(temperature*10); temperature=temperature/10; //Note: House and station can be used to distinguish between different weather stations (void) house; (void) station; //Send the humidity to the server auto nbytes = snprintf(write_buffer, 4096, "DATA %d %d", humidity_sensor, humidity); write(socket_fd, write_buffer, nbytes); sleep(1); //Send the temperature to the server nbytes = snprintf(write_buffer, 4096, "DATA %d %f", temperature_sensor, temperature); write(socket_fd, write_buffer, nbytes); } void read_data(RCSwitch& rc_switch, int socket_fd, int rf_button_1, int temperature_sensor, int humidity_sensor){ if (rc_switch.available()) { int value = rc_switch.getReceivedValue(); if (value) { if((rc_switch.getReceivedProtocol() == 1 || rc_switch.getReceivedProtocol() == 2) && rc_switch.getReceivedValue() == 1135920){ //Send the event to the server auto nbytes = snprintf(write_buffer, 4096, "EVENT %d 1", rf_button_1); write(socket_fd, write_buffer, nbytes); } else if(rc_switch.getReceivedProtocol() == 5){ unsigned long value = rc_switch.getReceivedValue(); decode_wt450(value, socket_fd, temperature_sensor, humidity_sensor); } else { printf("asgard:rf:received unknown value: %lu\n", rc_switch.getReceivedValue()); printf("asgard:rf:received unknown protocol: %i\n", rc_switch.getReceivedProtocol()); } } else { printf("asgard:rf:received unknown encoding\n"); } rc_switch.resetAvailable(); } } } //end of anonymous namespace int main(){ RCSwitch rc_switch; //Run the wiringPi setup (as root) wiringPiSetup(); rc_switch = RCSwitch(); rc_switch.enableReceive(gpio_pin); //Drop root privileges and run as pi:pi again if(!revoke_root()){ std::cout << "asgard:rf: unable to revoke root privileges, exiting..." << std::endl; return 1; } //Open the socket auto socket_fd = socket(PF_UNIX, SOCK_STREAM, 0); if(socket_fd < 0){ std::cout << "asgard:rf: socket() failed" << std::endl; return 1; } //Init the address struct sockaddr_un address; memset(&address, 0, sizeof(struct sockaddr_un)); address.sun_family = AF_UNIX; snprintf(address.sun_path, UNIX_PATH_MAX, "/tmp/asgard_socket"); //Connect to the server if(connect(socket_fd, (struct sockaddr *) &address, sizeof(struct sockaddr_un)) != 0){ std::cout << "asgard:rf: connect() failed" << std::endl; return 1; } //Register the actuator auto nbytes = snprintf(write_buffer, 4096, "REG_ACTUATOR rf_button_1"); write(socket_fd, write_buffer, nbytes); //Get the response from the server nbytes = read(socket_fd, receive_buffer, 4096); if(!nbytes){ std::cout << "asgard:ir: failed to register actuator" << std::endl; return 1; } receive_buffer[nbytes] = 0; //Parse the actuator id int rf_button_1 = atoi(receive_buffer); std::cout << "remote actuator: " << rf_button_1 << std::endl; nbytes = snprintf(write_buffer, 4096, "REG_SENSOR TEMPERATURE rf_weather_1"); write(socket_fd, write_buffer, nbytes); nbytes = read(socket_fd, receive_buffer, 4096); if(!nbytes){ std::cout << "asgard:dht11: failed to register temperature sensor" << std::endl; return 1; } receive_buffer[nbytes] = 0; int temperature_sensor = atoi(receive_buffer); std::cout << "Temperature sensor: " << temperature_sensor << std::endl; nbytes = snprintf(write_buffer, 4096, "REG_SENSOR HUMIDITY rf_weather_1"); write(socket_fd, write_buffer, nbytes); nbytes = read(socket_fd, receive_buffer, 4096); if(!nbytes){ std::cout << "asgard:dht11: failed to register humidity sensor" << std::endl; return 1; } receive_buffer[nbytes] = 0; int humidity_sensor = atoi(receive_buffer); std::cout << "Humidity sensor: " << humidity_sensor << std::endl; //wait for events while(true) { read_data(rc_switch, socket_fd, rf_button_1, temperature_sensor, humidity_sensor); //wait for 10 time units delay(10); } //Close the socket close(socket_fd); return 0; } <commit_msg>remove delay<commit_after>//======================================================================= // Copyright (c) 2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> #include "RCSwitch.h" namespace { const std::size_t UNIX_PATH_MAX = 108; const std::size_t gpio_pin = 2; //Buffers char write_buffer[4096]; char receive_buffer[4096]; bool revoke_root(){ if (getuid() == 0) { if (setgid(1000) != 0){ std::cout << "asgard:dht11: setgid: Unable to drop group privileges: " << strerror(errno) << std::endl; return false; } if (setuid(1000) != 0){ std::cout << "asgard:dht11: setgid: Unable to drop user privileges: " << strerror(errno) << std::endl; return false; } } if (setuid(0) != -1){ std::cout << "asgard:dht11: managed to regain root privileges, exiting..." << std::endl; return false; } return true; } void decode_wt450(unsigned long data, int socket_fd, int temperature_sensor, int humidity_sensor){ int house=(data>>28) & (0x0f); byte station=((data>>26) & (0x03))+1; int humidity=(data>>16)&(0xff); double temperature=((data>>8) & (0xff)); temperature = temperature - 50; byte tempfraction=(data>>4) & (0x0f); double tempdecimal=((tempfraction>>3 & 1) * 0.5) + ((tempfraction>>2 & 1) * 0.25) + ((tempfraction>>1 & 1) * 0.125) + ((tempfraction & 1) * 0.0625); temperature=temperature+tempdecimal; temperature=(int)(temperature*10); temperature=temperature/10; //Note: House and station can be used to distinguish between different weather stations (void) house; (void) station; //Send the humidity to the server auto nbytes = snprintf(write_buffer, 4096, "DATA %d %d", humidity_sensor, humidity); write(socket_fd, write_buffer, nbytes); //Send the temperature to the server nbytes = snprintf(write_buffer, 4096, "DATA %d %f", temperature_sensor, temperature); write(socket_fd, write_buffer, nbytes); } void read_data(RCSwitch& rc_switch, int socket_fd, int rf_button_1, int temperature_sensor, int humidity_sensor){ if (rc_switch.available()) { int value = rc_switch.getReceivedValue(); if (value) { if((rc_switch.getReceivedProtocol() == 1 || rc_switch.getReceivedProtocol() == 2) && rc_switch.getReceivedValue() == 1135920){ //Send the event to the server auto nbytes = snprintf(write_buffer, 4096, "EVENT %d 1", rf_button_1); write(socket_fd, write_buffer, nbytes); } else if(rc_switch.getReceivedProtocol() == 5){ unsigned long value = rc_switch.getReceivedValue(); decode_wt450(value, socket_fd, temperature_sensor, humidity_sensor); } else { printf("asgard:rf:received unknown value: %lu\n", rc_switch.getReceivedValue()); printf("asgard:rf:received unknown protocol: %i\n", rc_switch.getReceivedProtocol()); } } else { printf("asgard:rf:received unknown encoding\n"); } rc_switch.resetAvailable(); } } } //end of anonymous namespace int main(){ RCSwitch rc_switch; //Run the wiringPi setup (as root) wiringPiSetup(); rc_switch = RCSwitch(); rc_switch.enableReceive(gpio_pin); //Drop root privileges and run as pi:pi again if(!revoke_root()){ std::cout << "asgard:rf: unable to revoke root privileges, exiting..." << std::endl; return 1; } //Open the socket auto socket_fd = socket(PF_UNIX, SOCK_STREAM, 0); if(socket_fd < 0){ std::cout << "asgard:rf: socket() failed" << std::endl; return 1; } //Init the address struct sockaddr_un address; memset(&address, 0, sizeof(struct sockaddr_un)); address.sun_family = AF_UNIX; snprintf(address.sun_path, UNIX_PATH_MAX, "/tmp/asgard_socket"); //Connect to the server if(connect(socket_fd, (struct sockaddr *) &address, sizeof(struct sockaddr_un)) != 0){ std::cout << "asgard:rf: connect() failed" << std::endl; return 1; } //Register the actuator auto nbytes = snprintf(write_buffer, 4096, "REG_ACTUATOR rf_button_1"); write(socket_fd, write_buffer, nbytes); //Get the response from the server nbytes = read(socket_fd, receive_buffer, 4096); if(!nbytes){ std::cout << "asgard:ir: failed to register actuator" << std::endl; return 1; } receive_buffer[nbytes] = 0; //Parse the actuator id int rf_button_1 = atoi(receive_buffer); std::cout << "remote actuator: " << rf_button_1 << std::endl; nbytes = snprintf(write_buffer, 4096, "REG_SENSOR TEMPERATURE rf_weather_1"); write(socket_fd, write_buffer, nbytes); nbytes = read(socket_fd, receive_buffer, 4096); if(!nbytes){ std::cout << "asgard:dht11: failed to register temperature sensor" << std::endl; return 1; } receive_buffer[nbytes] = 0; int temperature_sensor = atoi(receive_buffer); std::cout << "Temperature sensor: " << temperature_sensor << std::endl; nbytes = snprintf(write_buffer, 4096, "REG_SENSOR HUMIDITY rf_weather_1"); write(socket_fd, write_buffer, nbytes); nbytes = read(socket_fd, receive_buffer, 4096); if(!nbytes){ std::cout << "asgard:dht11: failed to register humidity sensor" << std::endl; return 1; } receive_buffer[nbytes] = 0; int humidity_sensor = atoi(receive_buffer); std::cout << "Humidity sensor: " << humidity_sensor << std::endl; //wait for events while(true) { read_data(rc_switch, socket_fd, rf_button_1, temperature_sensor, humidity_sensor); //wait for 10 time units delay(10); } //Close the socket close(socket_fd); return 0; } <|endoftext|>
<commit_before>#include "engine.h" #include <QDateTime> #include <QTextStream> #include <QSettings> #include <QStandardPaths> #include "globals.h" #include "fileworker.h" #include "statfileinfo.h" Engine::Engine(QObject *parent) : QObject(parent), m_clipboardContainsCopy(false), m_progress(0) { m_fileWorker = new FileWorker; // update progress property when worker progresses connect(m_fileWorker, SIGNAL(progressChanged(int, QString)), this, SLOT(setProgress(int, QString))); // pass worker end signals to QML connect(m_fileWorker, SIGNAL(done()), this, SIGNAL(workerDone())); connect(m_fileWorker, SIGNAL(errorOccurred(QString, QString)), this, SIGNAL(workerErrorOccurred(QString, QString))); connect(m_fileWorker, SIGNAL(fileDeleted(QString)), this, SIGNAL(fileDeleted(QString))); } Engine::~Engine() { // is this the way to force stop the worker thread? m_fileWorker->cancel(); // stop possibly running background thread m_fileWorker->wait(); // wait until thread stops delete m_fileWorker; // delete it } void Engine::deleteFiles(QStringList filenames) { setProgress(0, ""); m_fileWorker->startDeleteFiles(filenames); } void Engine::cutFiles(QStringList filenames) { m_clipboardFiles = filenames; m_clipboardContainsCopy = false; emit clipboardCountChanged(); emit clipboardContainsCopyChanged(); } void Engine::copyFiles(QStringList filenames) { // don't copy special files (chr/blk/fifo/sock) QMutableStringListIterator i(filenames); while (i.hasNext()) { QString filename = i.next(); StatFileInfo info(filename); if (info.isSystem()) i.remove(); } m_clipboardFiles = filenames; m_clipboardContainsCopy = true; emit clipboardCountChanged(); emit clipboardContainsCopyChanged(); } void Engine::pasteFiles(QString destDirectory) { if (m_clipboardFiles.isEmpty()) { emit workerErrorOccurred("No files to paste", ""); return; } QStringList files = m_clipboardFiles; setProgress(0, ""); QDir dest(destDirectory); if (!dest.exists()) { emit workerErrorOccurred(tr("Destination does not exist"), destDirectory); return; } foreach (QString filename, files) { QFileInfo fileInfo(filename); QString newname = dest.absoluteFilePath(fileInfo.fileName()); // source and dest filenames are the same? if (filename == newname) { emit workerErrorOccurred(tr("Can't overwrite itself"), newname); return; } // dest is under source? (directory) if (newname.startsWith(filename)) { emit workerErrorOccurred(tr("Can't move/copy to itself"), filename); return; } } m_clipboardFiles.clear(); emit clipboardCountChanged(); if (m_clipboardContainsCopy) { m_fileWorker->startCopyFiles(files, destDirectory); return; } m_fileWorker->startMoveFiles(files, destDirectory); } void Engine::cancel() { m_fileWorker->cancel(); } QString Engine::homeFolder() const { return QStandardPaths::writableLocation(QStandardPaths::HomeLocation); } QString Engine::sdcardPath() const { // get sdcard dir candidates QDir dir("/media/sdcard"); if (!dir.exists()) return QString(); dir.setFilter(QDir::AllDirs | QDir::NoDotAndDotDot); QStringList sdcards = dir.entryList(); if (sdcards.isEmpty()) return QString(); // remove all directories which are not mount points QStringList mps = mountPoints(); QMutableStringListIterator i(sdcards); while (i.hasNext()) { QString dirname = i.next(); QString abspath = dir.absoluteFilePath(dirname); if (!mps.contains(abspath)) i.remove(); } // none found, return empty string if (sdcards.isEmpty()) return QString(); // if only one directory, then return it if (sdcards.count() == 1) return dir.absoluteFilePath(sdcards.first()); // if multiple directories, then return "/media/sdcard", which is the parent for them return "/media/sdcard"; } QString Engine::androidSdcardPath() const { return QStandardPaths::writableLocation(QStandardPaths::HomeLocation)+"/android_storage"; } bool Engine::exists(QString filename) { if (filename.isEmpty()) return false; return QFile::exists(filename); } QStringList Engine::diskSpace(QString path) { if (path.isEmpty()) return QStringList(); // return no disk space for sdcard parent directory if (path == "/media/sdcard") return QStringList(); // run df for the given path to get disk space QString blockSize = "--block-size=1024"; QString result = execute("/bin/df", QStringList() << blockSize << path, false); if (result.isEmpty()) return QStringList(); // split result to lines QStringList lines = result.split(QRegExp("[\n\r]")); if (lines.count() < 2) return QStringList(); // get first line and its columns QString line = lines.at(1); QStringList columns = line.split(QRegExp("\\s+"), QString::SkipEmptyParts); if (columns.count() < 5) return QStringList(); QString totalString = columns.at(1); QString usedString = columns.at(2); QString percentageString = columns.at(4); qint64 total = totalString.toLongLong() * 1024LL; qint64 used = usedString.toLongLong() * 1024LL; return QStringList() << percentageString << filesizeToString(used)+"/"+filesizeToString(total); } QStringList Engine::readFile(QString filename) { int maxLines = 1000; int maxSize = 10000; int maxBinSize = 2048; // check existence StatFileInfo fileInfo(filename); if (!fileInfo.exists()) { if (!fileInfo.isSymLink()) return makeStringList(tr("File does not exist\n%1").arg(filename)); else return makeStringList(tr("Broken symbolic link\n%1").arg(filename)); } // don't read unsafe system files if (!fileInfo.isSafeToRead()) { return makeStringList(tr("Can't read this type of file\n%1").arg(filename)); } // check permissions if (access(filename, R_OK) == -1) return makeStringList(tr("No permission to read the file\n%1").arg(filename)); QFile file(filename); if (!file.open(QIODevice::ReadOnly)) return makeStringList(tr("Error reading file\n%1").arg(filename)); // read start of file char buffer[maxSize+1]; qint64 readSize = file.read(buffer, maxSize); if (readSize < 0) return makeStringList(tr("Error reading file\n%1").arg(filename)); if (readSize == 0) return makeStringList(tr("Empty file")); bool atEnd = file.atEnd(); file.close(); // detect binary or text file, it is binary if it contains zeros bool isText = true; for (int i = 0; i < readSize; ++i) { if (buffer[i] == 0) { isText = false; break; } } // binary output if (!isText) { // two different line widths if (readSize > maxBinSize) { readSize = maxBinSize; atEnd = false; } QString out8 = createHexDump(buffer, readSize, 8); QString out16 = createHexDump(buffer, readSize, 16); QString msg = ""; if (!atEnd) { msg = tr("--- Binary file preview clipped at %1 kB ---").arg(maxBinSize/1000); msg = tr("--- Binary file preview clipped at %1 kB ---").arg(maxBinSize/1000); } return QStringList() << msg << out8 << out16; } // read lines to a string list and join QByteArray ba(buffer, readSize); QTextStream in(&ba); QStringList lines; int lineCount = 0; while (!in.atEnd() && lineCount < maxLines) { QString line = in.readLine(); lines.append(line); lineCount++; } QString msg = ""; if (lineCount == maxLines) msg = tr("--- Text file preview clipped at %1 lines ---").arg(maxLines); else if (!atEnd) msg = tr("--- Text file preview clipped at %1 kB ---").arg(maxSize/1000); return makeStringList(msg, lines.join("\n")); } QString Engine::mkdir(QString path, QString name) { QDir dir(path); if (!dir.mkdir(name)) { if (access(dir.absolutePath(), W_OK) == -1) return tr("Cannot create folder %1\nPermission denied").arg(name); return tr("Cannot create folder %1").arg(name); } return QString(); } QStringList Engine::rename(QString fullOldFilename, QString newName) { QFile file(fullOldFilename); QFileInfo fileInfo(fullOldFilename); QDir dir = fileInfo.absoluteDir(); QString fullNewFilename = dir.absoluteFilePath(newName); QString errorMessage; if (!file.rename(fullNewFilename)) { QString oldName = fileInfo.fileName(); errorMessage = tr("Cannot rename %1\n%2").arg(oldName).arg(file.errorString()); } return QStringList() << fullNewFilename << errorMessage; } QString Engine::chmod(QString path, bool ownerRead, bool ownerWrite, bool ownerExecute, bool groupRead, bool groupWrite, bool groupExecute, bool othersRead, bool othersWrite, bool othersExecute) { QFile file(path); QFileDevice::Permissions p; if (ownerRead) p |= QFileDevice::ReadOwner; if (ownerWrite) p |= QFileDevice::WriteOwner; if (ownerExecute) p |= QFileDevice::ExeOwner; if (groupRead) p |= QFileDevice::ReadGroup; if (groupWrite) p |= QFileDevice::WriteGroup; if (groupExecute) p |= QFileDevice::ExeGroup; if (othersRead) p |= QFileDevice::ReadOther; if (othersWrite) p |= QFileDevice::WriteOther; if (othersExecute) p |= QFileDevice::ExeOther; if (!file.setPermissions(p)) return tr("Cannot change permissions\n%1").arg(file.errorString()); return QString(); } QString Engine::readSetting(QString key, QString defaultValue) { QSettings settings; return settings.value(key, defaultValue).toString(); } void Engine::writeSetting(QString key, QString value) { QSettings settings; // do nothing if value didn't change if (settings.value(key) == value) return; settings.setValue(key, value); emit settingsChanged(); } void Engine::setProgress(int progress, QString filename) { m_progress = progress; m_progressFilename = filename; emit progressChanged(); emit progressFilenameChanged(); } QStringList Engine::mountPoints() const { // read /proc/mounts and return all mount points for the filesystem QFile file("/proc/mounts"); if (!file.open(QFile::ReadOnly | QFile::Text)) return QStringList(); QTextStream in(&file); QString result = in.readAll(); // split result to lines QStringList lines = result.split(QRegExp("[\n\r]")); // get columns QStringList dirs; foreach (QString line, lines) { QStringList columns = line.split(QRegExp("\\s+"), QString::SkipEmptyParts); if (columns.count() < 6) // sanity check continue; QString dir = columns.at(1); dirs.append(dir); } return dirs; } QString Engine::createHexDump(char *buffer, int size, int bytesPerLine) { QString out; QString ascDump; int i; for (i = 0; i < size; ++i) { if ((i % bytesPerLine) == 0) { // line change out += " "+ascDump+"\n"+ QString("%1").arg(QString::number(i, 16), 4, QLatin1Char('0'))+": "; ascDump.clear(); } out += QString("%1").arg(QString::number((unsigned char)buffer[i], 16), 2, QLatin1Char('0'))+" "; if (buffer[i] >= 32 && buffer[i] <= 126) ascDump += buffer[i]; else ascDump += "."; } // write out remaining asc dump if ((i % bytesPerLine) > 0) { int emptyBytes = bytesPerLine - (i % bytesPerLine); for (int j = 0; j < emptyBytes; ++j) { out += " "; } } out += " "+ascDump; return out; } QStringList Engine::makeStringList(QString msg, QString str) { QStringList list; list << msg << str << str; return list; } <commit_msg>Fix view page to display actual kilobytes (1024s)<commit_after>#include "engine.h" #include <QDateTime> #include <QTextStream> #include <QSettings> #include <QStandardPaths> #include "globals.h" #include "fileworker.h" #include "statfileinfo.h" Engine::Engine(QObject *parent) : QObject(parent), m_clipboardContainsCopy(false), m_progress(0) { m_fileWorker = new FileWorker; // update progress property when worker progresses connect(m_fileWorker, SIGNAL(progressChanged(int, QString)), this, SLOT(setProgress(int, QString))); // pass worker end signals to QML connect(m_fileWorker, SIGNAL(done()), this, SIGNAL(workerDone())); connect(m_fileWorker, SIGNAL(errorOccurred(QString, QString)), this, SIGNAL(workerErrorOccurred(QString, QString))); connect(m_fileWorker, SIGNAL(fileDeleted(QString)), this, SIGNAL(fileDeleted(QString))); } Engine::~Engine() { // is this the way to force stop the worker thread? m_fileWorker->cancel(); // stop possibly running background thread m_fileWorker->wait(); // wait until thread stops delete m_fileWorker; // delete it } void Engine::deleteFiles(QStringList filenames) { setProgress(0, ""); m_fileWorker->startDeleteFiles(filenames); } void Engine::cutFiles(QStringList filenames) { m_clipboardFiles = filenames; m_clipboardContainsCopy = false; emit clipboardCountChanged(); emit clipboardContainsCopyChanged(); } void Engine::copyFiles(QStringList filenames) { // don't copy special files (chr/blk/fifo/sock) QMutableStringListIterator i(filenames); while (i.hasNext()) { QString filename = i.next(); StatFileInfo info(filename); if (info.isSystem()) i.remove(); } m_clipboardFiles = filenames; m_clipboardContainsCopy = true; emit clipboardCountChanged(); emit clipboardContainsCopyChanged(); } void Engine::pasteFiles(QString destDirectory) { if (m_clipboardFiles.isEmpty()) { emit workerErrorOccurred("No files to paste", ""); return; } QStringList files = m_clipboardFiles; setProgress(0, ""); QDir dest(destDirectory); if (!dest.exists()) { emit workerErrorOccurred(tr("Destination does not exist"), destDirectory); return; } foreach (QString filename, files) { QFileInfo fileInfo(filename); QString newname = dest.absoluteFilePath(fileInfo.fileName()); // source and dest filenames are the same? if (filename == newname) { emit workerErrorOccurred(tr("Can't overwrite itself"), newname); return; } // dest is under source? (directory) if (newname.startsWith(filename)) { emit workerErrorOccurred(tr("Can't move/copy to itself"), filename); return; } } m_clipboardFiles.clear(); emit clipboardCountChanged(); if (m_clipboardContainsCopy) { m_fileWorker->startCopyFiles(files, destDirectory); return; } m_fileWorker->startMoveFiles(files, destDirectory); } void Engine::cancel() { m_fileWorker->cancel(); } QString Engine::homeFolder() const { return QStandardPaths::writableLocation(QStandardPaths::HomeLocation); } QString Engine::sdcardPath() const { // get sdcard dir candidates QDir dir("/media/sdcard"); if (!dir.exists()) return QString(); dir.setFilter(QDir::AllDirs | QDir::NoDotAndDotDot); QStringList sdcards = dir.entryList(); if (sdcards.isEmpty()) return QString(); // remove all directories which are not mount points QStringList mps = mountPoints(); QMutableStringListIterator i(sdcards); while (i.hasNext()) { QString dirname = i.next(); QString abspath = dir.absoluteFilePath(dirname); if (!mps.contains(abspath)) i.remove(); } // none found, return empty string if (sdcards.isEmpty()) return QString(); // if only one directory, then return it if (sdcards.count() == 1) return dir.absoluteFilePath(sdcards.first()); // if multiple directories, then return "/media/sdcard", which is the parent for them return "/media/sdcard"; } QString Engine::androidSdcardPath() const { return QStandardPaths::writableLocation(QStandardPaths::HomeLocation)+"/android_storage"; } bool Engine::exists(QString filename) { if (filename.isEmpty()) return false; return QFile::exists(filename); } QStringList Engine::diskSpace(QString path) { if (path.isEmpty()) return QStringList(); // return no disk space for sdcard parent directory if (path == "/media/sdcard") return QStringList(); // run df for the given path to get disk space QString blockSize = "--block-size=1024"; QString result = execute("/bin/df", QStringList() << blockSize << path, false); if (result.isEmpty()) return QStringList(); // split result to lines QStringList lines = result.split(QRegExp("[\n\r]")); if (lines.count() < 2) return QStringList(); // get first line and its columns QString line = lines.at(1); QStringList columns = line.split(QRegExp("\\s+"), QString::SkipEmptyParts); if (columns.count() < 5) return QStringList(); QString totalString = columns.at(1); QString usedString = columns.at(2); QString percentageString = columns.at(4); qint64 total = totalString.toLongLong() * 1024LL; qint64 used = usedString.toLongLong() * 1024LL; return QStringList() << percentageString << filesizeToString(used)+"/"+filesizeToString(total); } QStringList Engine::readFile(QString filename) { int maxLines = 1000; int maxSize = 10240; int maxBinSize = 2048; // check existence StatFileInfo fileInfo(filename); if (!fileInfo.exists()) { if (!fileInfo.isSymLink()) return makeStringList(tr("File does not exist\n%1").arg(filename)); else return makeStringList(tr("Broken symbolic link\n%1").arg(filename)); } // don't read unsafe system files if (!fileInfo.isSafeToRead()) { return makeStringList(tr("Can't read this type of file\n%1").arg(filename)); } // check permissions if (access(filename, R_OK) == -1) return makeStringList(tr("No permission to read the file\n%1").arg(filename)); QFile file(filename); if (!file.open(QIODevice::ReadOnly)) return makeStringList(tr("Error reading file\n%1").arg(filename)); // read start of file char buffer[maxSize+1]; qint64 readSize = file.read(buffer, maxSize); if (readSize < 0) return makeStringList(tr("Error reading file\n%1").arg(filename)); if (readSize == 0) return makeStringList(tr("Empty file")); bool atEnd = file.atEnd(); file.close(); // detect binary or text file, it is binary if it contains zeros bool isText = true; for (int i = 0; i < readSize; ++i) { if (buffer[i] == 0) { isText = false; break; } } // binary output if (!isText) { // two different line widths if (readSize > maxBinSize) { readSize = maxBinSize; atEnd = false; } QString out8 = createHexDump(buffer, readSize, 8); QString out16 = createHexDump(buffer, readSize, 16); QString msg = ""; if (!atEnd) { msg = tr("--- Binary file preview clipped at %1 kB ---").arg(maxBinSize/1024); msg = tr("--- Binary file preview clipped at %1 kB ---").arg(maxBinSize/1024); } return QStringList() << msg << out8 << out16; } // read lines to a string list and join QByteArray ba(buffer, readSize); QTextStream in(&ba); QStringList lines; int lineCount = 0; while (!in.atEnd() && lineCount < maxLines) { QString line = in.readLine(); lines.append(line); lineCount++; } QString msg = ""; if (lineCount == maxLines) msg = tr("--- Text file preview clipped at %1 lines ---").arg(maxLines); else if (!atEnd) msg = tr("--- Text file preview clipped at %1 kB ---").arg(maxSize/1024); return makeStringList(msg, lines.join("\n")); } QString Engine::mkdir(QString path, QString name) { QDir dir(path); if (!dir.mkdir(name)) { if (access(dir.absolutePath(), W_OK) == -1) return tr("Cannot create folder %1\nPermission denied").arg(name); return tr("Cannot create folder %1").arg(name); } return QString(); } QStringList Engine::rename(QString fullOldFilename, QString newName) { QFile file(fullOldFilename); QFileInfo fileInfo(fullOldFilename); QDir dir = fileInfo.absoluteDir(); QString fullNewFilename = dir.absoluteFilePath(newName); QString errorMessage; if (!file.rename(fullNewFilename)) { QString oldName = fileInfo.fileName(); errorMessage = tr("Cannot rename %1\n%2").arg(oldName).arg(file.errorString()); } return QStringList() << fullNewFilename << errorMessage; } QString Engine::chmod(QString path, bool ownerRead, bool ownerWrite, bool ownerExecute, bool groupRead, bool groupWrite, bool groupExecute, bool othersRead, bool othersWrite, bool othersExecute) { QFile file(path); QFileDevice::Permissions p; if (ownerRead) p |= QFileDevice::ReadOwner; if (ownerWrite) p |= QFileDevice::WriteOwner; if (ownerExecute) p |= QFileDevice::ExeOwner; if (groupRead) p |= QFileDevice::ReadGroup; if (groupWrite) p |= QFileDevice::WriteGroup; if (groupExecute) p |= QFileDevice::ExeGroup; if (othersRead) p |= QFileDevice::ReadOther; if (othersWrite) p |= QFileDevice::WriteOther; if (othersExecute) p |= QFileDevice::ExeOther; if (!file.setPermissions(p)) return tr("Cannot change permissions\n%1").arg(file.errorString()); return QString(); } QString Engine::readSetting(QString key, QString defaultValue) { QSettings settings; return settings.value(key, defaultValue).toString(); } void Engine::writeSetting(QString key, QString value) { QSettings settings; // do nothing if value didn't change if (settings.value(key) == value) return; settings.setValue(key, value); emit settingsChanged(); } void Engine::setProgress(int progress, QString filename) { m_progress = progress; m_progressFilename = filename; emit progressChanged(); emit progressFilenameChanged(); } QStringList Engine::mountPoints() const { // read /proc/mounts and return all mount points for the filesystem QFile file("/proc/mounts"); if (!file.open(QFile::ReadOnly | QFile::Text)) return QStringList(); QTextStream in(&file); QString result = in.readAll(); // split result to lines QStringList lines = result.split(QRegExp("[\n\r]")); // get columns QStringList dirs; foreach (QString line, lines) { QStringList columns = line.split(QRegExp("\\s+"), QString::SkipEmptyParts); if (columns.count() < 6) // sanity check continue; QString dir = columns.at(1); dirs.append(dir); } return dirs; } QString Engine::createHexDump(char *buffer, int size, int bytesPerLine) { QString out; QString ascDump; int i; for (i = 0; i < size; ++i) { if ((i % bytesPerLine) == 0) { // line change out += " "+ascDump+"\n"+ QString("%1").arg(QString::number(i, 16), 4, QLatin1Char('0'))+": "; ascDump.clear(); } out += QString("%1").arg(QString::number((unsigned char)buffer[i], 16), 2, QLatin1Char('0'))+" "; if (buffer[i] >= 32 && buffer[i] <= 126) ascDump += buffer[i]; else ascDump += "."; } // write out remaining asc dump if ((i % bytesPerLine) > 0) { int emptyBytes = bytesPerLine - (i % bytesPerLine); for (int j = 0; j < emptyBytes; ++j) { out += " "; } } out += " "+ascDump; return out; } QStringList Engine::makeStringList(QString msg, QString str) { QStringList list; list << msg << str << str; return list; } <|endoftext|>
<commit_before>#include "engine.h" #include "random.h" #include "gameEntity.h" #include "Updatable.h" #include "collisionable.h" #include "audio/source.h" #include <SDL.h> #ifdef DEBUG #include <typeinfo> int DEBUG_PobjCount; PObject* DEBUG_PobjListStart; #endif #ifdef WIN32 #include <windows.h> namespace { HINSTANCE exchndl = nullptr; } #endif Engine* engine; Engine::Engine() { engine = this; #ifdef WIN32 // Setup crash reporter (Dr. MinGW) if available. exchndl = LoadLibrary(TEXT("exchndl.dll")); if (exchndl) { auto pfnExcHndlInit = GetProcAddress(exchndl, "ExcHndlInit"); if (pfnExcHndlInit) { pfnExcHndlInit(); LOG(INFO) << "Crash Reporter ON"; } else { LOG(WARNING) << "Failed to initialize Crash Reporter"; FreeLibrary(exchndl); exchndl = nullptr; } } #endif // WIN32 SDL_Init(SDL_INIT_EVERYTHING); atexit(SDL_Quit); initRandom(); window = nullptr; CollisionManager::initialize(); InputHandler::initialize(); gameSpeed = 1.0; running = true; elapsedTime = 0.0; soundManager = new SoundManager(); } Engine::~Engine() { delete soundManager; soundManager = nullptr; #ifdef WIN32 if (exchndl) { FreeLibrary(exchndl); exchndl = nullptr; } #endif // WIN32 } void Engine::registerObject(string name, P<PObject> obj) { objectMap[name] = obj; } P<PObject> Engine::getObject(string name) { if (!objectMap[name]) return NULL; return objectMap[name]; } void Engine::runMainLoop() { window = dynamic_cast<Window*>(*getObject("window")); if (!window) { sp::SystemStopwatch frame_timer; while(running) { float delta = frame_timer.restart(); if (delta > 0.5f) delta = 0.5f; if (delta < 0.001f) delta = 0.001f; delta *= gameSpeed; foreach(Updatable, u, updatableList) u->update(delta); elapsedTime += delta; CollisionManager::handleCollisions(delta); ScriptObject::clearDestroyedObjects(); soundManager->updateTick(); std::this_thread::sleep_for(std::chrono::duration<float>(1.f/60.f - delta)); } }else{ sp::audio::Source::startAudioSystem(); sp::SystemStopwatch frame_timer; #ifdef DEBUG sp::SystemTimer debug_output_timer; debug_output_timer.repeat(5); #endif while(running) { InputHandler::preEventsUpdate(); // Handle events SDL_Event event; while (SDL_PollEvent(&event)) { handleEvent(event); } InputHandler::postEventsUpdate(); #ifdef DEBUG if (debug_output_timer.isExpired()) printf("Object count: %4d %4zd\n", DEBUG_PobjCount, updatableList.size()); #endif float delta = frame_timer.restart(); if (delta > 0.5f) delta = 0.5f; if (delta < 0.001f) delta = 0.001f; delta *= gameSpeed; #ifdef DEBUG #warning TODO SDL2 /* if (sf::Keyboard::isKeyPressed(sf::Keyboard::Tab)) delta /= 5.f; if (sf::Keyboard::isKeyPressed(sf::Keyboard::Tilde)) delta *= 5.f; */ #endif EngineTiming engine_timing; sp::SystemStopwatch engine_timing_stopwatch; foreach(Updatable, u, updatableList) { u->update(delta); } elapsedTime += delta; engine_timing.update = engine_timing_stopwatch.restart(); CollisionManager::handleCollisions(delta); engine_timing.collision = engine_timing_stopwatch.restart(); ScriptObject::clearDestroyedObjects(); soundManager->updateTick(); // Clear the window window->render(); engine_timing.render = engine_timing_stopwatch.restart(); engine_timing.server_update = 0.0f; if (game_server) engine_timing.server_update = game_server->getUpdateTime(); last_engine_timing = engine_timing; } soundManager->stopMusic(); } } void Engine::handleEvent(SDL_Event& event) { // Window closed: exit if (event.type == SDL_QUIT) running = false; #ifdef DEBUG if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE) running = false; if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_l) { int n = 0; printf("------------------------\n"); std::unordered_map<string,int> totals; for(PObject* obj = DEBUG_PobjListStart; obj; obj = obj->DEBUG_PobjListNext) { printf("%c%4d: %4d: %s\n", obj->isDestroyed() ? '>' : ' ', n++, obj->getRefCount(), typeid(*obj).name()); if (!obj->isDestroyed()) { totals[typeid(*obj).name()]=totals[typeid(*obj).name()]+1; } } printf("--non-destroyed totals--\n"); int grand_total=0; for (auto entry : totals) { printf("%4d %s\n", entry.second, entry.first.c_str()); grand_total+=entry.second; } printf("%4d %s\n",grand_total,"All PObjects"); printf("------------------------\n"); } #endif InputHandler::handleEvent(event); if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_RESIZED) window->setupView(); } void Engine::setGameSpeed(float speed) { gameSpeed = speed; } float Engine::getGameSpeed() { return gameSpeed; } float Engine::getElapsedTime() { return elapsedTime; } Engine::EngineTiming Engine::getEngineTiming() { return last_engine_timing; } void Engine::shutdown() { running = false; } <commit_msg>Update engine.cpp<commit_after>#include "engine.h" #include "random.h" #include "gameEntity.h" #include "Updatable.h" #include "collisionable.h" #include "audio/source.h" #include <SDL.h> #ifdef DEBUG #include <typeinfo> int DEBUG_PobjCount; PObject* DEBUG_PobjListStart; #endif #ifdef WIN32 #include <windows.h> namespace { HINSTANCE exchndl = nullptr; } #endif Engine* engine; Engine::Engine() { engine = this; #ifdef WIN32 // Setup crash reporter (Dr. MinGW) if available. exchndl = LoadLibrary(TEXT("exchndl.dll")); if (exchndl) { auto pfnExcHndlInit = GetProcAddress(exchndl, "ExcHndlInit"); if (pfnExcHndlInit) { pfnExcHndlInit(); LOG(INFO) << "Crash Reporter ON"; } else { LOG(WARNING) << "Failed to initialize Crash Reporter"; FreeLibrary(exchndl); exchndl = nullptr; } } #endif // WIN32 SDL_Init(SDL_INIT_EVERYTHING); atexit(SDL_Quit); initRandom(); window = nullptr; CollisionManager::initialize(); InputHandler::initialize(); gameSpeed = 1.0; running = true; elapsedTime = 0.0; soundManager = new SoundManager(); } Engine::~Engine() { delete soundManager; soundManager = nullptr; #ifdef WIN32 if (exchndl) { FreeLibrary(exchndl); exchndl = nullptr; } #endif // WIN32 } void Engine::registerObject(string name, P<PObject> obj) { objectMap[name] = obj; } P<PObject> Engine::getObject(string name) { if (!objectMap[name]) return NULL; return objectMap[name]; } void Engine::runMainLoop() { window = dynamic_cast<Window*>(*getObject("window")); if (!window) { sp::SystemStopwatch frame_timer; while(running) { float delta = frame_timer.restart(); if (delta > 0.5f) delta = 0.5f; if (delta < 0.001f) delta = 0.001f; delta *= gameSpeed; foreach(Updatable, u, updatableList) u->update(delta); elapsedTime += delta; CollisionManager::handleCollisions(delta); ScriptObject::clearDestroyedObjects(); soundManager->updateTick(); std::this_thread::sleep_for(std::chrono::duration<float>(1.f/60.f - delta)); } }else{ sp::audio::Source::startAudioSystem(); sp::SystemStopwatch frame_timer; #ifdef DEBUG sp::SystemTimer debug_output_timer; debug_output_timer.repeat(5); #endif while(running) { InputHandler::preEventsUpdate(); // Handle events SDL_Event event; while (SDL_PollEvent(&event)) { handleEvent(event); } InputHandler::postEventsUpdate(); #ifdef DEBUG if (debug_output_timer.isExpired()) printf("Object count: %4d %4zd\n", DEBUG_PobjCount, updatableList.size()); #endif float delta = frame_timer.restart(); if (delta > 0.5f) delta = 0.5f; if (delta < 0.001f) delta = 0.001f; delta *= gameSpeed; #ifdef DEBUG /* #warning TODO SDL2 if (sf::Keyboard::isKeyPressed(sf::Keyboard::Tab)) delta /= 5.f; if (sf::Keyboard::isKeyPressed(sf::Keyboard::Tilde)) delta *= 5.f; */ #endif EngineTiming engine_timing; sp::SystemStopwatch engine_timing_stopwatch; foreach(Updatable, u, updatableList) { u->update(delta); } elapsedTime += delta; engine_timing.update = engine_timing_stopwatch.restart(); CollisionManager::handleCollisions(delta); engine_timing.collision = engine_timing_stopwatch.restart(); ScriptObject::clearDestroyedObjects(); soundManager->updateTick(); // Clear the window window->render(); engine_timing.render = engine_timing_stopwatch.restart(); engine_timing.server_update = 0.0f; if (game_server) engine_timing.server_update = game_server->getUpdateTime(); last_engine_timing = engine_timing; } soundManager->stopMusic(); } } void Engine::handleEvent(SDL_Event& event) { // Window closed: exit if (event.type == SDL_QUIT) running = false; #ifdef DEBUG if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE) running = false; if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_l) { int n = 0; printf("------------------------\n"); std::unordered_map<string,int> totals; for(PObject* obj = DEBUG_PobjListStart; obj; obj = obj->DEBUG_PobjListNext) { printf("%c%4d: %4d: %s\n", obj->isDestroyed() ? '>' : ' ', n++, obj->getRefCount(), typeid(*obj).name()); if (!obj->isDestroyed()) { totals[typeid(*obj).name()]=totals[typeid(*obj).name()]+1; } } printf("--non-destroyed totals--\n"); int grand_total=0; for (auto entry : totals) { printf("%4d %s\n", entry.second, entry.first.c_str()); grand_total+=entry.second; } printf("%4d %s\n",grand_total,"All PObjects"); printf("------------------------\n"); } #endif InputHandler::handleEvent(event); if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_RESIZED) window->setupView(); } void Engine::setGameSpeed(float speed) { gameSpeed = speed; } float Engine::getGameSpeed() { return gameSpeed; } float Engine::getElapsedTime() { return elapsedTime; } Engine::EngineTiming Engine::getEngineTiming() { return last_engine_timing; } void Engine::shutdown() { running = false; } <|endoftext|>
<commit_before>// fluxbox.hh for Fluxbox Window Manager // Copyright (c) 2001 - 2003 Henrik Kinnunen (fluxgen at users.sourceforge.net) // // blackbox.hh for Blackbox - an X11 Window manager // Copyright (c) 1997 - 2000 Brad Hughes (bhughes at tcac.net) // // 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. // $Id: fluxbox.hh,v 1.82 2004/01/11 16:10:23 fluxgen Exp $ #ifndef FLUXBOX_HH #define FLUXBOX_HH #include "FbTk/App.hh" #include "FbTk/Resource.hh" #include "FbTk/Timer.hh" #include "FbTk/Observer.hh" #include "FbTk/SignalHandler.hh" #include <X11/Xlib.h> #include <X11/Xresource.h> #include <cstdio> #ifdef HAVE_CONFIG_H #include "config.h" #endif // HAVE_CONFIG_H #ifdef TIME_WITH_SYS_TIME #include <sys/time.h> #include <time.h> #else // !TIME_WITH_SYS_TIME #ifdef HAVE_SYS_TIME_H #include <sys/time.h> #else // !HAVE_SYS_TIME_H #include <time.h> #endif // HAVE_SYS_TIME_H #endif // TIME_WITH_SYS_TIME #include <list> #include <map> #include <memory> #include <string> #include <vector> class AtomHandler; class FluxboxWindow; class WinClient; class Keys; class BScreen; class FbAtoms; class Toolbar; /// main class for the window manager. /** singleton type */ class Fluxbox : public FbTk::App, public FbTk::SignalEventHandler, public FbTk::Observer { public: Fluxbox(int argc, char **argv, const char * dpy_name= 0, const char *rcfilename = 0); virtual ~Fluxbox(); static Fluxbox *instance() { return s_singleton; } /// main event loop void eventLoop(); bool validateWindow(Window win) const; void grab(); void ungrab(); Keys *keys() { return m_key.get(); } inline Atom getFluxboxPidAtom() const { return m_fluxbox_pid; } // Not currently implemented until we decide how it'll be used //WinClient *searchGroup(Window); WinClient *searchWindow(Window); inline WinClient *getFocusedWindow() { return m_focused_window; } BScreen *searchScreen(Window w); inline unsigned int getDoubleClickInterval() const { return *m_rc_double_click_interval; } inline unsigned int getUpdateDelayTime() const { return *m_rc_update_delay_time; } inline Time getLastTime() const { return m_last_time; } void addAtomHandler(AtomHandler *atomh); void removeAtomHandler(AtomHandler *atomh); /// obsolete enum Titlebar{SHADE=0, MINIMIZE, MAXIMIZE, CLOSE, STICK, MENU, EMPTY}; inline const Bool getIgnoreBorder() const { return *m_rc_ignoreborder; } inline const std::vector<Fluxbox::Titlebar>& getTitlebarRight() const { return *m_rc_titlebar_right; } inline const std::vector<Fluxbox::Titlebar>& getTitlebarLeft() const { return *m_rc_titlebar_left; } inline const std::string &getStyleFilename() const { return *m_rc_stylefile; } inline const std::string &getMenuFilename() const { return *m_rc_menufile; } inline const std::string &getSlitlistFilename() const { return *m_rc_slitlistfile; } inline int colorsPerChannel() const { return *m_rc_colors_per_channel; } inline int getNumberOfLayers() const { return *m_rc_numlayers; } // class to store layer numbers (special Resource type) // we have a special resource type because we need to be able to name certain layers // a Resource<int> wouldn't allow this class Layer { public: explicit Layer(int i) : m_num(i) {}; inline int getNum() const { return m_num; } Layer &operator=(int num) { m_num = num; return *this; } private: int m_num; }; // TODO these probably should be configurable inline int getMenuLayer() const { return 0; } inline int getAboveDockLayer() const { return 2; } inline int getDockLayer() const { return 4; } inline int getTopLayer() const { return 6; } inline int getNormalLayer() const { return 8; } inline int getBottomLayer() const { return 10; } inline int getDesktopLayer() const { return 12; } inline time_t getAutoRaiseDelay() const { return *m_rc_auto_raise_delay; } inline unsigned int getCacheLife() const { return *m_rc_cache_life * 60000; } inline unsigned int getCacheMax() const { return *m_rc_cache_max; } inline bool useMod1() const { return *m_rc_use_mod1; } inline void maskWindowEvents(Window w, FluxboxWindow *bw) { m_masked = w; m_masked_window = bw; } void watchKeyRelease(BScreen &screen, unsigned int mods); void setFocusedWindow(WinClient *w); void revertFocus(BScreen &screen); void shutdown(); void load_rc(BScreen &scr); void loadRootCommand(BScreen &scr); void loadTitlebar(); void saveStyleFilename(const char *val) { m_rc_stylefile = (val == 0 ? "" : val); } void saveMenuFilename(const char *); void clearMenuFilenames(); void saveTitlebarFilename(const char *); void saveSlitlistFilename(const char *val) { m_rc_slitlistfile = (val == 0 ? "" : val); } void saveWindowSearch(Window win, WinClient *winclient); // some windows relate to the group, not the client, so we record separately // searchWindow on these windows will give the active client in the group void saveWindowSearchGroup(Window win, FluxboxWindow *fbwin); void saveGroupSearch(Window win, WinClient *winclient); void save_rc(); void removeWindowSearch(Window win); void removeWindowSearchGroup(Window win); void removeGroupSearch(Window win); void restart(const char *command = 0); void reconfigure(); void rereadMenu(); /// reloads the menus if the timestamps changed void checkMenu(); void hideExtraMenus(BScreen &screen); /// handle any system signal sent to the application void handleSignal(int signum); void update(FbTk::Subject *changed); void attachSignals(FluxboxWindow &win); void attachSignals(WinClient &winclient); void timed_reconfigure(); bool isStartup() const { return m_starting; } typedef std::vector<Fluxbox::Titlebar> TitlebarList; /// @return whether the timestamps on the menu changed bool menuTimestampsChanged() const; bool haveShape() const { return m_have_shape; } int shapeEventbase() const { return m_shape_eventbase; } void getDefaultDataFilename(char *, std::string &); // screen mouse was in at last key event BScreen *mouseScreen() { return m_mousescreen; } // screen of window that last key event (i.e. focused window) went to BScreen *keyScreen() { return m_keyscreen; } // screen we are watching for modifier changes BScreen *watchingScreen() { return m_watching_screen; } const XEvent &lastEvent() const { return m_last_event; } private: typedef struct MenuTimestamp { std::string filename; time_t timestamp; } MenuTimestamp; std::string getRcFilename(); void load_rc(); void reload_rc(); void real_rereadMenu(); void real_reconfigure(); void handleEvent(XEvent *xe); void setupConfigFiles(); void handleButtonEvent(XButtonEvent &be); void handleUnmapNotify(XUnmapEvent &ue); void handleClientMessage(XClientMessageEvent &ce); void handleKeyEvent(XKeyEvent &ke); void setTitlebar(std::vector<Fluxbox::Titlebar>& dir, const char *arg); std::auto_ptr<FbAtoms> m_fbatoms; FbTk::ResourceManager m_resourcemanager, &m_screen_rm; //--- Resources FbTk::Resource<bool> m_rc_tabs, m_rc_ignoreborder; FbTk::Resource<int> m_rc_colors_per_channel, m_rc_numlayers, m_rc_double_click_interval, m_rc_update_delay_time; FbTk::Resource<std::string> m_rc_stylefile, m_rc_menufile, m_rc_keyfile, m_rc_slitlistfile, m_rc_groupfile; FbTk::Resource<TitlebarList> m_rc_titlebar_left, m_rc_titlebar_right; FbTk::Resource<unsigned int> m_rc_cache_life, m_rc_cache_max; FbTk::Resource<time_t> m_rc_auto_raise_delay; FbTk::Resource<bool> m_rc_use_mod1; /// temporary!, to disable mod1 for resize/move std::map<Window, WinClient *> m_window_search; std::map<Window, FluxboxWindow *> m_window_search_group; // A window is the group leader, which can map to several // WinClients in the group, it is *not* fluxbox's concept of groups // See ICCCM section 4.1.11 // The group leader (which may not be mapped, so may not have a WinClient) // will have it's window being the group index std::multimap<Window, WinClient *> m_group_search; std::list<MenuTimestamp *> m_menu_timestamps; typedef std::list<BScreen *> ScreenList; ScreenList m_screen_list; WinClient *m_focused_window; FluxboxWindow *m_masked_window; BScreen *m_mousescreen, *m_keyscreen; BScreen *m_watching_screen; unsigned int m_watch_keyrelease; Atom m_fluxbox_pid; bool m_reconfigure_wait, m_reread_menu_wait; Time m_last_time; Window m_masked; std::string m_rc_file; ///< resource filename char **m_argv; int m_argc; XEvent m_last_event; FbTk::Timer m_reconfig_timer; ///< when we execute reconfig command we must wait at least to next event round std::auto_ptr<Keys> m_key; //default arguments for titlebar left and right static Fluxbox::Titlebar s_titlebar_left[], s_titlebar_right[]; static Fluxbox *s_singleton; std::vector<AtomHandler *> m_atomhandler; std::vector<Toolbar *> m_toolbars; bool m_starting; bool m_shutdown; int m_server_grabs; int m_randr_event_type; ///< the type number of randr event int m_shape_eventbase; ///< event base for shape events bool m_have_shape; ///< if shape is supported by server const char *m_RC_PATH; const char *m_RC_INIT_FILE; Atom m_kwm1_dockwindow, m_kwm2_dockwindow; }; #endif // FLUXBOX_HH <commit_msg>minor fix<commit_after>// fluxbox.hh for Fluxbox Window Manager // Copyright (c) 2001 - 2003 Henrik Kinnunen (fluxgen at users.sourceforge.net) // // blackbox.hh for Blackbox - an X11 Window manager // Copyright (c) 1997 - 2000 Brad Hughes (bhughes at tcac.net) // // 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. // $Id: fluxbox.hh,v 1.83 2004/02/10 18:45:57 fluxgen Exp $ #ifndef FLUXBOX_HH #define FLUXBOX_HH #include "FbTk/App.hh" #include "FbTk/Resource.hh" #include "FbTk/Timer.hh" #include "FbTk/Observer.hh" #include "FbTk/SignalHandler.hh" #include <X11/Xlib.h> #include <X11/Xresource.h> #include <cstdio> #ifdef HAVE_CONFIG_H #include "config.h" #endif // HAVE_CONFIG_H #ifdef TIME_WITH_SYS_TIME #include <sys/time.h> #include <time.h> #else // !TIME_WITH_SYS_TIME #ifdef HAVE_SYS_TIME_H #include <sys/time.h> #else // !HAVE_SYS_TIME_H #include <time.h> #endif // HAVE_SYS_TIME_H #endif // TIME_WITH_SYS_TIME #include <list> #include <map> #include <memory> #include <string> #include <vector> class AtomHandler; class FluxboxWindow; class WinClient; class Keys; class BScreen; class FbAtoms; class Toolbar; /// main class for the window manager. /** singleton type */ class Fluxbox : public FbTk::App, public FbTk::SignalEventHandler, public FbTk::Observer { public: Fluxbox(int argc, char **argv, const char * dpy_name= 0, const char *rcfilename = 0); virtual ~Fluxbox(); static Fluxbox *instance() { return s_singleton; } /// main event loop void eventLoop(); bool validateWindow(Window win) const; void grab(); void ungrab(); Keys *keys() { return m_key.get(); } inline Atom getFluxboxPidAtom() const { return m_fluxbox_pid; } // Not currently implemented until we decide how it'll be used //WinClient *searchGroup(Window); WinClient *searchWindow(Window); inline WinClient *getFocusedWindow() { return m_focused_window; } BScreen *searchScreen(Window w); inline unsigned int getDoubleClickInterval() const { return *m_rc_double_click_interval; } inline unsigned int getUpdateDelayTime() const { return *m_rc_update_delay_time; } inline Time getLastTime() const { return m_last_time; } void addAtomHandler(AtomHandler *atomh); void removeAtomHandler(AtomHandler *atomh); /// obsolete enum Titlebar{SHADE=0, MINIMIZE, MAXIMIZE, CLOSE, STICK, MENU, EMPTY}; inline bool getIgnoreBorder() const { return *m_rc_ignoreborder; } inline const std::vector<Fluxbox::Titlebar>& getTitlebarRight() const { return *m_rc_titlebar_right; } inline const std::vector<Fluxbox::Titlebar>& getTitlebarLeft() const { return *m_rc_titlebar_left; } inline const std::string &getStyleFilename() const { return *m_rc_stylefile; } inline const std::string &getMenuFilename() const { return *m_rc_menufile; } inline const std::string &getSlitlistFilename() const { return *m_rc_slitlistfile; } inline int colorsPerChannel() const { return *m_rc_colors_per_channel; } inline int getNumberOfLayers() const { return *m_rc_numlayers; } // class to store layer numbers (special Resource type) // we have a special resource type because we need to be able to name certain layers // a Resource<int> wouldn't allow this class Layer { public: explicit Layer(int i) : m_num(i) {}; inline int getNum() const { return m_num; } Layer &operator=(int num) { m_num = num; return *this; } private: int m_num; }; // TODO these probably should be configurable inline int getMenuLayer() const { return 0; } inline int getAboveDockLayer() const { return 2; } inline int getDockLayer() const { return 4; } inline int getTopLayer() const { return 6; } inline int getNormalLayer() const { return 8; } inline int getBottomLayer() const { return 10; } inline int getDesktopLayer() const { return 12; } inline time_t getAutoRaiseDelay() const { return *m_rc_auto_raise_delay; } inline unsigned int getCacheLife() const { return *m_rc_cache_life * 60000; } inline unsigned int getCacheMax() const { return *m_rc_cache_max; } inline bool useMod1() const { return *m_rc_use_mod1; } inline void maskWindowEvents(Window w, FluxboxWindow *bw) { m_masked = w; m_masked_window = bw; } void watchKeyRelease(BScreen &screen, unsigned int mods); void setFocusedWindow(WinClient *w); void revertFocus(BScreen &screen); void shutdown(); void load_rc(BScreen &scr); void loadRootCommand(BScreen &scr); void loadTitlebar(); void saveStyleFilename(const char *val) { m_rc_stylefile = (val == 0 ? "" : val); } void saveMenuFilename(const char *); void clearMenuFilenames(); void saveTitlebarFilename(const char *); void saveSlitlistFilename(const char *val) { m_rc_slitlistfile = (val == 0 ? "" : val); } void saveWindowSearch(Window win, WinClient *winclient); // some windows relate to the group, not the client, so we record separately // searchWindow on these windows will give the active client in the group void saveWindowSearchGroup(Window win, FluxboxWindow *fbwin); void saveGroupSearch(Window win, WinClient *winclient); void save_rc(); void removeWindowSearch(Window win); void removeWindowSearchGroup(Window win); void removeGroupSearch(Window win); void restart(const char *command = 0); void reconfigure(); void rereadMenu(); /// reloads the menus if the timestamps changed void checkMenu(); void hideExtraMenus(BScreen &screen); /// handle any system signal sent to the application void handleSignal(int signum); void update(FbTk::Subject *changed); void attachSignals(FluxboxWindow &win); void attachSignals(WinClient &winclient); void timed_reconfigure(); bool isStartup() const { return m_starting; } typedef std::vector<Fluxbox::Titlebar> TitlebarList; /// @return whether the timestamps on the menu changed bool menuTimestampsChanged() const; bool haveShape() const { return m_have_shape; } int shapeEventbase() const { return m_shape_eventbase; } void getDefaultDataFilename(char *, std::string &); // screen mouse was in at last key event BScreen *mouseScreen() { return m_mousescreen; } // screen of window that last key event (i.e. focused window) went to BScreen *keyScreen() { return m_keyscreen; } // screen we are watching for modifier changes BScreen *watchingScreen() { return m_watching_screen; } const XEvent &lastEvent() const { return m_last_event; } private: typedef struct MenuTimestamp { std::string filename; time_t timestamp; } MenuTimestamp; std::string getRcFilename(); void load_rc(); void reload_rc(); void real_rereadMenu(); void real_reconfigure(); void handleEvent(XEvent *xe); void setupConfigFiles(); void handleButtonEvent(XButtonEvent &be); void handleUnmapNotify(XUnmapEvent &ue); void handleClientMessage(XClientMessageEvent &ce); void handleKeyEvent(XKeyEvent &ke); void setTitlebar(std::vector<Fluxbox::Titlebar>& dir, const char *arg); std::auto_ptr<FbAtoms> m_fbatoms; FbTk::ResourceManager m_resourcemanager, &m_screen_rm; //--- Resources FbTk::Resource<bool> m_rc_tabs, m_rc_ignoreborder; FbTk::Resource<int> m_rc_colors_per_channel, m_rc_numlayers, m_rc_double_click_interval, m_rc_update_delay_time; FbTk::Resource<std::string> m_rc_stylefile, m_rc_menufile, m_rc_keyfile, m_rc_slitlistfile, m_rc_groupfile; FbTk::Resource<TitlebarList> m_rc_titlebar_left, m_rc_titlebar_right; FbTk::Resource<unsigned int> m_rc_cache_life, m_rc_cache_max; FbTk::Resource<time_t> m_rc_auto_raise_delay; FbTk::Resource<bool> m_rc_use_mod1; /// temporary!, to disable mod1 for resize/move std::map<Window, WinClient *> m_window_search; std::map<Window, FluxboxWindow *> m_window_search_group; // A window is the group leader, which can map to several // WinClients in the group, it is *not* fluxbox's concept of groups // See ICCCM section 4.1.11 // The group leader (which may not be mapped, so may not have a WinClient) // will have it's window being the group index std::multimap<Window, WinClient *> m_group_search; std::list<MenuTimestamp *> m_menu_timestamps; typedef std::list<BScreen *> ScreenList; ScreenList m_screen_list; WinClient *m_focused_window; FluxboxWindow *m_masked_window; BScreen *m_mousescreen, *m_keyscreen; BScreen *m_watching_screen; unsigned int m_watch_keyrelease; Atom m_fluxbox_pid; bool m_reconfigure_wait, m_reread_menu_wait; Time m_last_time; Window m_masked; std::string m_rc_file; ///< resource filename char **m_argv; int m_argc; XEvent m_last_event; FbTk::Timer m_reconfig_timer; ///< when we execute reconfig command we must wait at least to next event round std::auto_ptr<Keys> m_key; //default arguments for titlebar left and right static Fluxbox::Titlebar s_titlebar_left[], s_titlebar_right[]; static Fluxbox *s_singleton; std::vector<AtomHandler *> m_atomhandler; std::vector<Toolbar *> m_toolbars; bool m_starting; bool m_shutdown; int m_server_grabs; int m_randr_event_type; ///< the type number of randr event int m_shape_eventbase; ///< event base for shape events bool m_have_shape; ///< if shape is supported by server const char *m_RC_PATH; const char *m_RC_INIT_FILE; Atom m_kwm1_dockwindow, m_kwm2_dockwindow; }; #endif // FLUXBOX_HH <|endoftext|>
<commit_before>/** * @file fsLogic.cc * @author Rafal Slota * @author Konrad Zemek * @copyright (C) 2013-2015 ACK CYFRONET AGH * @copyright This software is released under the MIT license cited in * 'LICENSE.txt' */ #include "fsLogic.h" #include "context.h" #include "events/eventManager.h" #include "logging.h" #include "messages/fuse/getFileAttr.h" #include "messages/fuse/fileAttr.h" #include "messages/fuse/createDir.h" #include "messages/fuse/deleteFile.h" #include "messages/fuse/fileChildren.h" #include "messages/fuse/getFileChildren.h" #include "messages/fuse/updateTimes.h" #include <boost/algorithm/string.hpp> using namespace std::literals; namespace one { namespace client { FsLogic::FsLogic(std::shared_ptr<Context> context) : m_uid{geteuid()} , m_gid{getegid()} , m_context{std::move(context)} , m_eventManager{std::make_unique<events::EventManager>(m_context)} { } int FsLogic::access(boost::filesystem::path path, const int mask) { DLOG(INFO) << "FUSE: access(path: '" << path << "', mask: " << mask << ")"; return 0; } int FsLogic::getattr(boost::filesystem::path path, struct stat *const statbuf) { DLOG(INFO) << "FUSE: getattr(path: '" << path << ", ...)"; auto attr = getAttr(path); statbuf->st_atime = std::chrono::system_clock::to_time_t(attr.atime()); statbuf->st_mtime = std::chrono::system_clock::to_time_t(attr.mtime()); statbuf->st_ctime = std::chrono::system_clock::to_time_t(attr.ctime()); statbuf->st_gid = attr.gid(); statbuf->st_uid = attr.uid(); statbuf->st_mode = attr.mode(); statbuf->st_size = attr.size(); return 0; } int FsLogic::readlink( boost::filesystem::path path, boost::asio::mutable_buffer buf) { DLOG(INFO) << "FUSE: readlink(path: '" << path << "', bufferSize: " << boost::asio::buffer_size(buf) << ")"; throw std::errc::operation_not_supported; } int FsLogic::mknod( boost::filesystem::path path, const mode_t mode, const dev_t dev) { DLOG(INFO) << "FUSE: mknod(path: '" << path << "', mode: " << mode << ", dev: " << dev << ")"; throw std::errc::operation_not_supported; } int FsLogic::mkdir(boost::filesystem::path path, const mode_t mode) { DLOG(INFO) << "FUSE: mkdir(path: '" << path << "', mode: " << mode << ")"; auto parentAttr = getAttr(path.parent_path()); if (parentAttr.type() != messages::fuse::FileAttr::FileType::directory) throw std::errc::not_a_directory; messages::fuse::CreateDir msg{ parentAttr.uuid(), path.filename().string(), mode}; auto future = m_context->communicator()->communicate<messages::fuse::FuseResponse>( msg); communication::wait(future); return 0; } int FsLogic::unlink(boost::filesystem::path path) { DLOG(INFO) << "FUSE: unlink(path: '" << path << "')"; removeFile(std::move(path)); return 0; } int FsLogic::rmdir(boost::filesystem::path path) { DLOG(INFO) << "FUSE: rmdir(path: '" << path << "')"; removeFile(std::move(path)); return 0; } int FsLogic::symlink( boost::filesystem::path target, boost::filesystem::path linkPath) { DLOG(INFO) << "FUSE: symlink(target: " << target << ", linkPath: " << linkPath << ")"; throw std::errc::operation_not_supported; } int FsLogic::rename( boost::filesystem::path oldPath, boost::filesystem::path newPath) { DLOG(INFO) << "FUSE: rename(oldPath: '" << oldPath << "', newPath: '" << newPath << "')"; throw std::errc::operation_not_supported; } int FsLogic::chmod(boost::filesystem::path path, const mode_t mode) { DLOG(INFO) << "FUSE: chmod(path: '" << path << "', mode: " << mode << ")"; throw std::errc::operation_not_supported; } int FsLogic::chown( boost::filesystem::path path, const uid_t uid, const gid_t gid) { DLOG(INFO) << "FUSE: chown(path: '" << path << "', uid: " << uid << ", gid: " << gid << ")"; throw std::errc::operation_not_supported; } int FsLogic::truncate(boost::filesystem::path path, const off_t newSize) { DLOG(INFO) << "FUSE: truncate(path: '" << path << "', newSize: " << newSize << ")"; // m_eventManager->emitTruncateEvent(path.string(), newSize); throw std::errc::operation_not_supported; } int FsLogic::utime(boost::filesystem::path path, struct utimbuf *const ubuf) { DLOG(INFO) << "FUSE: utime(path: '" << path << "', ...)"; auto attr = getAttr(path); messages::fuse::UpdateTimes msg{attr.uuid()}; if (!ubuf) { const auto now = std::chrono::system_clock::now(); msg.atime(now); msg.mtime(now); } else { msg.atime(std::chrono::system_clock::from_time_t(ubuf->actime)); msg.mtime(std::chrono::system_clock::from_time_t(ubuf->modtime)); } auto future = m_context->communicator()->communicate<messages::fuse::FuseResponse>( msg); communication::wait(future); return 0; } int FsLogic::open( boost::filesystem::path path, struct fuse_file_info *const fileInfo) { DLOG(INFO) << "FUSE: open(path: '" << path << "', ...)"; throw std::errc::operation_not_supported; } int FsLogic::read(boost::filesystem::path path, boost::asio::mutable_buffer buf, const off_t offset, struct fuse_file_info *const fileInfo) { DLOG(INFO) << "FUSE: read(path: '" << path << "', bufferSize: " << boost::asio::buffer_size(buf) << ", offset: " << offset << ", ...)"; // m_eventManager->emitReadEvent( // path.string(), offset, static_cast<size_t>(res)); throw std::errc::operation_not_supported; } int FsLogic::write(boost::filesystem::path path, boost::asio::const_buffer buf, const off_t offset, struct fuse_file_info *const fileInfo) { DLOG(INFO) << "FUSE: write(path: '" << path << "', bufferSize: " << boost::asio::buffer_size(buf) << ", offset: " << offset << ", ...)"; // if (m_shMock->shGetattr(path.string(), &statbuf) == 0) { // m_eventManager->emitWriteEvent(path.string(), offset, // static_cast<size_t>(res), // std::max(offset + res, statbuf.st_size)); // } // else { // m_eventManager->emitWriteEvent( // path.string(), offset, static_cast<size_t>(res), offset + // res); // } throw std::errc::operation_not_supported; } int FsLogic::statfs( boost::filesystem::path path, struct statvfs *const statInfo) { DLOG(INFO) << "FUSE: statfs(path: '" << path << "', ...)"; throw std::errc::operation_not_supported; } int FsLogic::flush( boost::filesystem::path path, struct fuse_file_info *const fileInfo) { DLOG(INFO) << "FUSE: flush(path: '" << path << "', ...)"; throw std::errc::operation_not_supported; } int FsLogic::release( boost::filesystem::path path, struct fuse_file_info *const fileInfo) { DLOG(INFO) << "FUSE: release(path: '" << path << "', ...)"; throw std::errc::operation_not_supported; } int FsLogic::fsync(boost::filesystem::path path, const int datasync, struct fuse_file_info *const fileInfo) { DLOG(INFO) << "FUSE: fsync(path: '" << path << "', datasync: " << datasync << ", ...)"; throw std::errc::operation_not_supported; } int FsLogic::opendir( boost::filesystem::path path, struct fuse_file_info *const fileInfo) { DLOG(INFO) << "FUSE: opendir(path: '" << path << "', ...)"; return 0; } int FsLogic::readdir(boost::filesystem::path path, void *const buf, const fuse_fill_dir_t filler, const off_t offset, struct fuse_file_info *const /*fileInfo*/) { DLOG(INFO) << "FUSE: readdir(path: '" << path << "', ..., offset: " << offset << ", ...)"; auto attr = getAttr(path); if (attr.type() != messages::fuse::FileAttr::FileType::directory) throw std::errc::not_a_directory; messages::fuse::GetFileChildren msg{attr.uuid(), offset, 1000}; auto future = m_context->communicator()->communicate<messages::fuse::FileChildren>( msg); auto fileChildren = communication::wait(future); auto currentOffset = offset; for (const auto &uuidAndName : fileChildren.uuidsAndNames()) { auto name = std::get<1>(uuidAndName); auto childPath = path / name; m_uuidCache.insert({std::move(childPath), std::get<0>(uuidAndName)}); if (filler(buf, name.c_str(), nullptr, ++currentOffset)) break; } return 0; } int FsLogic::releasedir( boost::filesystem::path path, struct fuse_file_info *const fileInfo) { DLOG(INFO) << "FUSE: releasedir(path: '" << path << "', ...)"; return 0; } int FsLogic::fsyncdir(boost::filesystem::path path, const int datasync, struct fuse_file_info *const fileInfo) { DLOG(INFO) << "FUSE: fsyncdir(path: '" << path << "', datasync: " << datasync << ", ...)"; return 0; } void FsLogic::removeFile(boost::filesystem::path path) { auto attr = getAttr(path); messages::fuse::DeleteFile msg{attr.uuid()}; auto future = m_context->communicator()->communicate<messages::fuse::FuseResponse>( msg); communication::wait(future); m_uuidCache.erase(path); m_attrCache.erase(attr.uuid()); } messages::fuse::FileAttr FsLogic::getAttr(const boost::filesystem::path &path) { decltype(m_uuidCache)::const_accessor acc; if (m_uuidCache.find(acc, path)) { auto uuid = acc->second; acc.release(); return getAttr(uuid); } return getAttr(messages::fuse::GetFileAttr{path}); } messages::fuse::FileAttr FsLogic::getAttr(const std::string &uuid) { decltype(m_attrCache)::const_accessor acc; if (m_attrCache.find(acc, uuid)) return acc->second; return getAttr(messages::fuse::GetFileAttr{uuid}); } messages::fuse::FileAttr FsLogic::getAttr( const messages::fuse::GetFileAttr &req) { auto future = m_context->communicator()->communicate<messages::fuse::FileAttr>(req); auto attr = communication::wait(future); m_attrCache.insert({attr.uuid(), attr}); return attr; } std::size_t FsLogic::PathHash::hash(const boost::filesystem::path &path) { return std::hash<std::string>{}(path.string()); } bool FsLogic::PathHash::equal( const boost::filesystem::path &a, const boost::filesystem::path &b) { return a == b; } } // namespace client } // namespace one <commit_msg>VFS-1153 Set file type in getattr.<commit_after>/** * @file fsLogic.cc * @author Rafal Slota * @author Konrad Zemek * @copyright (C) 2013-2015 ACK CYFRONET AGH * @copyright This software is released under the MIT license cited in * 'LICENSE.txt' */ #include "fsLogic.h" #include "context.h" #include "events/eventManager.h" #include "logging.h" #include "messages/fuse/getFileAttr.h" #include "messages/fuse/fileAttr.h" #include "messages/fuse/createDir.h" #include "messages/fuse/deleteFile.h" #include "messages/fuse/fileChildren.h" #include "messages/fuse/getFileChildren.h" #include "messages/fuse/updateTimes.h" #include <boost/algorithm/string.hpp> using namespace std::literals; namespace one { namespace client { FsLogic::FsLogic(std::shared_ptr<Context> context) : m_uid{geteuid()} , m_gid{getegid()} , m_context{std::move(context)} , m_eventManager{std::make_unique<events::EventManager>(m_context)} { } int FsLogic::access(boost::filesystem::path path, const int mask) { DLOG(INFO) << "FUSE: access(path: '" << path << "', mask: " << mask << ")"; return 0; } int FsLogic::getattr(boost::filesystem::path path, struct stat *const statbuf) { DLOG(INFO) << "FUSE: getattr(path: '" << path << ", ...)"; auto attr = getAttr(path); statbuf->st_atime = std::chrono::system_clock::to_time_t(attr.atime()); statbuf->st_mtime = std::chrono::system_clock::to_time_t(attr.mtime()); statbuf->st_ctime = std::chrono::system_clock::to_time_t(attr.ctime()); statbuf->st_gid = attr.gid(); statbuf->st_uid = attr.uid(); statbuf->st_mode = attr.mode(); statbuf->st_size = attr.size(); statbuf->st_nlink = 1; statbuf->st_blocks = 0; switch (attr.type()) { case messages::fuse::FileAttr::FileType::directory: statbuf->st_mode |= S_IFDIR; break; case messages::fuse::FileAttr::FileType::link: statbuf->st_mode |= S_IFLNK; break; case messages::fuse::FileAttr::FileType::regular: statbuf->st_mode |= S_IFREG; break; } return 0; } int FsLogic::readlink( boost::filesystem::path path, boost::asio::mutable_buffer buf) { DLOG(INFO) << "FUSE: readlink(path: '" << path << "', bufferSize: " << boost::asio::buffer_size(buf) << ")"; throw std::errc::operation_not_supported; } int FsLogic::mknod( boost::filesystem::path path, const mode_t mode, const dev_t dev) { DLOG(INFO) << "FUSE: mknod(path: '" << path << "', mode: " << mode << ", dev: " << dev << ")"; throw std::errc::operation_not_supported; } int FsLogic::mkdir(boost::filesystem::path path, const mode_t mode) { DLOG(INFO) << "FUSE: mkdir(path: '" << path << "', mode: " << mode << ")"; auto parentAttr = getAttr(path.parent_path()); if (parentAttr.type() != messages::fuse::FileAttr::FileType::directory) throw std::errc::not_a_directory; messages::fuse::CreateDir msg{ parentAttr.uuid(), path.filename().string(), mode}; auto future = m_context->communicator()->communicate<messages::fuse::FuseResponse>( msg); communication::wait(future); return 0; } int FsLogic::unlink(boost::filesystem::path path) { DLOG(INFO) << "FUSE: unlink(path: '" << path << "')"; removeFile(std::move(path)); return 0; } int FsLogic::rmdir(boost::filesystem::path path) { DLOG(INFO) << "FUSE: rmdir(path: '" << path << "')"; removeFile(std::move(path)); return 0; } int FsLogic::symlink( boost::filesystem::path target, boost::filesystem::path linkPath) { DLOG(INFO) << "FUSE: symlink(target: " << target << ", linkPath: " << linkPath << ")"; throw std::errc::operation_not_supported; } int FsLogic::rename( boost::filesystem::path oldPath, boost::filesystem::path newPath) { DLOG(INFO) << "FUSE: rename(oldPath: '" << oldPath << "', newPath: '" << newPath << "')"; throw std::errc::operation_not_supported; } int FsLogic::chmod(boost::filesystem::path path, const mode_t mode) { DLOG(INFO) << "FUSE: chmod(path: '" << path << "', mode: " << mode << ")"; throw std::errc::operation_not_supported; } int FsLogic::chown( boost::filesystem::path path, const uid_t uid, const gid_t gid) { DLOG(INFO) << "FUSE: chown(path: '" << path << "', uid: " << uid << ", gid: " << gid << ")"; throw std::errc::operation_not_supported; } int FsLogic::truncate(boost::filesystem::path path, const off_t newSize) { DLOG(INFO) << "FUSE: truncate(path: '" << path << "', newSize: " << newSize << ")"; // m_eventManager->emitTruncateEvent(path.string(), newSize); throw std::errc::operation_not_supported; } int FsLogic::utime(boost::filesystem::path path, struct utimbuf *const ubuf) { DLOG(INFO) << "FUSE: utime(path: '" << path << "', ...)"; auto attr = getAttr(path); messages::fuse::UpdateTimes msg{attr.uuid()}; if (!ubuf) { const auto now = std::chrono::system_clock::now(); msg.atime(now); msg.mtime(now); } else { msg.atime(std::chrono::system_clock::from_time_t(ubuf->actime)); msg.mtime(std::chrono::system_clock::from_time_t(ubuf->modtime)); } auto future = m_context->communicator()->communicate<messages::fuse::FuseResponse>( msg); communication::wait(future); return 0; } int FsLogic::open( boost::filesystem::path path, struct fuse_file_info *const fileInfo) { DLOG(INFO) << "FUSE: open(path: '" << path << "', ...)"; throw std::errc::operation_not_supported; } int FsLogic::read(boost::filesystem::path path, boost::asio::mutable_buffer buf, const off_t offset, struct fuse_file_info *const fileInfo) { DLOG(INFO) << "FUSE: read(path: '" << path << "', bufferSize: " << boost::asio::buffer_size(buf) << ", offset: " << offset << ", ...)"; // m_eventManager->emitReadEvent( // path.string(), offset, static_cast<size_t>(res)); throw std::errc::operation_not_supported; } int FsLogic::write(boost::filesystem::path path, boost::asio::const_buffer buf, const off_t offset, struct fuse_file_info *const fileInfo) { DLOG(INFO) << "FUSE: write(path: '" << path << "', bufferSize: " << boost::asio::buffer_size(buf) << ", offset: " << offset << ", ...)"; // if (m_shMock->shGetattr(path.string(), &statbuf) == 0) { // m_eventManager->emitWriteEvent(path.string(), offset, // static_cast<size_t>(res), // std::max(offset + res, statbuf.st_size)); // } // else { // m_eventManager->emitWriteEvent( // path.string(), offset, static_cast<size_t>(res), offset + // res); // } throw std::errc::operation_not_supported; } int FsLogic::statfs( boost::filesystem::path path, struct statvfs *const statInfo) { DLOG(INFO) << "FUSE: statfs(path: '" << path << "', ...)"; throw std::errc::operation_not_supported; } int FsLogic::flush( boost::filesystem::path path, struct fuse_file_info *const fileInfo) { DLOG(INFO) << "FUSE: flush(path: '" << path << "', ...)"; throw std::errc::operation_not_supported; } int FsLogic::release( boost::filesystem::path path, struct fuse_file_info *const fileInfo) { DLOG(INFO) << "FUSE: release(path: '" << path << "', ...)"; throw std::errc::operation_not_supported; } int FsLogic::fsync(boost::filesystem::path path, const int datasync, struct fuse_file_info *const fileInfo) { DLOG(INFO) << "FUSE: fsync(path: '" << path << "', datasync: " << datasync << ", ...)"; throw std::errc::operation_not_supported; } int FsLogic::opendir( boost::filesystem::path path, struct fuse_file_info *const fileInfo) { DLOG(INFO) << "FUSE: opendir(path: '" << path << "', ...)"; return 0; } int FsLogic::readdir(boost::filesystem::path path, void *const buf, const fuse_fill_dir_t filler, const off_t offset, struct fuse_file_info *const /*fileInfo*/) { DLOG(INFO) << "FUSE: readdir(path: '" << path << "', ..., offset: " << offset << ", ...)"; auto attr = getAttr(path); if (attr.type() != messages::fuse::FileAttr::FileType::directory) throw std::errc::not_a_directory; messages::fuse::GetFileChildren msg{attr.uuid(), offset, 1000}; auto future = m_context->communicator()->communicate<messages::fuse::FileChildren>( msg); auto fileChildren = communication::wait(future); auto currentOffset = offset; for (const auto &uuidAndName : fileChildren.uuidsAndNames()) { auto name = std::get<1>(uuidAndName); auto childPath = path / name; m_uuidCache.insert({std::move(childPath), std::get<0>(uuidAndName)}); if (filler(buf, name.c_str(), nullptr, ++currentOffset)) break; } return 0; } int FsLogic::releasedir( boost::filesystem::path path, struct fuse_file_info *const fileInfo) { DLOG(INFO) << "FUSE: releasedir(path: '" << path << "', ...)"; return 0; } int FsLogic::fsyncdir(boost::filesystem::path path, const int datasync, struct fuse_file_info *const fileInfo) { DLOG(INFO) << "FUSE: fsyncdir(path: '" << path << "', datasync: " << datasync << ", ...)"; return 0; } void FsLogic::removeFile(boost::filesystem::path path) { auto attr = getAttr(path); messages::fuse::DeleteFile msg{attr.uuid()}; auto future = m_context->communicator()->communicate<messages::fuse::FuseResponse>( msg); communication::wait(future); m_uuidCache.erase(path); m_attrCache.erase(attr.uuid()); } messages::fuse::FileAttr FsLogic::getAttr(const boost::filesystem::path &path) { decltype(m_uuidCache)::const_accessor acc; if (m_uuidCache.find(acc, path)) { auto uuid = acc->second; acc.release(); return getAttr(uuid); } return getAttr(messages::fuse::GetFileAttr{path}); } messages::fuse::FileAttr FsLogic::getAttr(const std::string &uuid) { decltype(m_attrCache)::const_accessor acc; if (m_attrCache.find(acc, uuid)) return acc->second; return getAttr(messages::fuse::GetFileAttr{uuid}); } messages::fuse::FileAttr FsLogic::getAttr( const messages::fuse::GetFileAttr &req) { auto future = m_context->communicator()->communicate<messages::fuse::FileAttr>(req); auto attr = communication::wait(future); m_attrCache.insert({attr.uuid(), attr}); return attr; } std::size_t FsLogic::PathHash::hash(const boost::filesystem::path &path) { return std::hash<std::string>{}(path.string()); } bool FsLogic::PathHash::equal( const boost::filesystem::path &a, const boost::filesystem::path &b) { return a == b; } } // namespace client } // namespace one <|endoftext|>
<commit_before>#include <cstdlib> #include <iostream> #include <sstream> #include <fstream> #include <openssl/md5.h> #include "boost/filesystem/operations.hpp" #include "boost/filesystem/path.hpp" #include <pHash.h> #include "imagedb.h" #include "common.h" using namespace std; namespace fs = boost::filesystem; void ImageDB::addImages(const string& imagepath) const { if(!fs::is_directory(imagepath)) { cerr <<"Invalid imagepath '"<<imagepath<<"' specified." <<endl; return; } fs::recursive_directory_iterator endIter; for(fs::recursive_directory_iterator itr(imagepath); itr !=endIter; ++itr) { ostringstream cmd; if(fs::is_regular_file(itr->path())) { cmd << "curl -XPOST --data-binary @" <<itr->path().string() <<" http://localhost:8080/ &"; cout << cmd.str() <<endl; system(cmd.str().c_str()); } } } void ImageDB::_updateIndicies(const Image& image) { } Result ImageDB::getImage(const unsigned char* data, unsigned int size, bool add) { Image image; MD5(data, size, image.md5); ofstream ofs; fs::path path = fs::unique_path("/tmp/%%%%%%-%%%%.jpg"); ofs.open(path.string().c_str()); /*char d[128]; memcpy(d, data, 127); d[127]='\0'; cout <<"\""<<d<<"\""<<endl;*/ ofs.write((const char*)data, size); ofs.close(); ph_dct_imagehash(path.string().c_str(), image.phash); cout <<"Image size "<< size <<endl; fs::remove(path); return PRESENT; } <commit_msg>move tmp file generation<commit_after>#include <cstdlib> #include <iostream> #include <sstream> #include <fstream> #include <openssl/md5.h> #include "boost/filesystem/operations.hpp" #include "boost/filesystem/path.hpp" #include <pHash.h> #include "imagedb.h" #include "common.h" using namespace std; namespace fs = boost::filesystem; void ImageDB::addImages(const string& imagepath) const { if(!fs::is_directory(imagepath)) { cerr <<"Invalid imagepath '"<<imagepath<<"' specified." <<endl; return; } fs::recursive_directory_iterator endIter; for(fs::recursive_directory_iterator itr(imagepath); itr !=endIter; ++itr) { ostringstream cmd; if(fs::is_regular_file(itr->path())) { cmd << "curl -XPOST --data-binary @" <<itr->path().string() <<" http://localhost:8080/ &"; system(cmd.str().c_str()); } } } void ImageDB::_updateIndicies(const Image& image) { } Result ImageDB::getImage(const unsigned char* data, unsigned int size, bool add) { Image image; MD5(data, size, image.md5); ofstream ofs; fs::path path = fs::unique_path("/tmp/%%%%%%-%%%%"); ofs.open(path.string().c_str()); ofs.write((const char*)data, size); ofs.close(); ph_dct_imagehash(path.string().c_str(), image.phash); cout <<"Image size:"<< size << " md5:"<< image.md5 << " phash:" << image.phash << endl; fs::remove(path); return PRESENT; } <|endoftext|>
<commit_before>#include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "model.h" #include "camera.h" #include "kernel.h" #include "string.h" Kernel::Kernel(int argc, char** argv) { /* open and read config file */ char option[255]; char value[255]; FILE *config_file; config_file = fopen(CONFIG_PATH, "r"); if (config_file != NULL) { while(fscanf(config_file, "%s %s", option, value) != EOF) { if (!strcmp(option, "height")) { height = atof(value); } if (!strcmp(option, "width")) { width = atof(value); } } fclose(config_file); } else { printf("Warning: no config file found\n"); } /* parse command line arguments */ static const char *optString = "m:h:w:"; int opt = 0; opt = getopt(argc, argv, optString); while(opt != -1) { switch(opt) { case 'm': map_name = optarg; break; case 'h': height = atoi(optarg); break; case 'w': width = atoi(optarg); break; } opt = getopt(argc, argv, optString); } /* write config to config file */ // FILE *config_file; config_file = fopen(CONFIG_PATH, "w"); if (config_file != NULL) { fprintf(config_file, "%s %f\n", "width", width); fprintf(config_file, "%s %f\n", "height", height); fclose(config_file); printf("Config saved\n"); } else { printf("Warning: can not save config\n"); } printf("Resolution set to %fx%f\n", width, height); printf("Loading map %s\n", map_name); }; <commit_msg>small fixes<commit_after>#include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "model.h" #include "camera.h" #include "kernel.h" #include "string.h" Kernel::Kernel(int argc, char** argv) { /* default config */ height = DEF_HEIGHT; width = DEF_WIDTH; /* open and read config file */ char option[255]; char value[255]; FILE *config_file; config_file = fopen(CONFIG_PATH, "r"); if (config_file != NULL) { while(fscanf(config_file, "%s %s", option, value) != EOF) { if (!strcmp(option, "height")) { height = atof(value); } if (!strcmp(option, "width")) { width = atof(value); } } fclose(config_file); } else { printf("Warning: no config file found\n"); } /* parse command line arguments */ static const char *optString = "m:h:w:"; int opt = 0; opt = getopt(argc, argv, optString); while(opt != -1) { switch(opt) { case 'm': map_name = optarg; break; case 'h': height = atof(optarg); break; case 'w': width = atof(optarg); break; } opt = getopt(argc, argv, optString); } /* write config to config file */ // FILE *config_file; config_file = fopen(CONFIG_PATH, "w"); if (config_file != NULL) { fprintf(config_file, "%s %f\n", "width", width); fprintf(config_file, "%s %f\n", "height", height); fclose(config_file); printf("Config saved\n"); } else { printf("Warning: can not save config\n"); } printf("Resolution set to %fx%f\n", width, height); printf("Loading map %s\n", map_name); }; <|endoftext|>
<commit_before>//----------------------------------------------------------------------------- // HIMG, by Marcus Geelnard, 2015 // // This is free and unencumbered software released into the public domain. // // See LICENSE for details. //----------------------------------------------------------------------------- #include "mapper.h" #include <algorithm> namespace himg { namespace { // This is a hand-tuned mapping table that seems to give good results. const int16_t kLowResMappingTable[128] = { 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, 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, 52, 53, 54, 55, 56, 57, 58, 59, 60, 62, 63, 64, 65, 67, 68, 70, 71, 73, 74, 76, 78, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99, 102, 104, 106, 109, 111, 114, 117, 119, 122, 125, 128, 131, 134, 137, 140, 143, 146, 150, 153, 156, 160, 164, 167, 171, 175, 178, 182, 186, 190, 195, 199, 203, 207, 212, 216, 221, 226, 230, 235, 240, 245, 250, 255, 999 // FIXME! }; } // namespace void LowResMapper::InitForQuality(int quality) { // TODO(m): Use quality to control the mapping table. for (int i = 0; i < 128; ++i) m_mapping_table[i] = kLowResMappingTable[i]; } int Mapper::MappingFunctionSize() const { // The mapping table requires one byte that tells how many items can be // represented with a single byte, plus the actual single- and double-byte // items. int single_byte_items = NumberOfSingleByteMappingItems(); return 1 + single_byte_items + 2 * (128 - single_byte_items); } void Mapper::GetMappingFunction(uint8_t *out) const { // Store the mapping table. int single_byte_items = NumberOfSingleByteMappingItems(); *out++ = static_cast<uint8_t>(single_byte_items); int i; for (i = 0; i < single_byte_items; ++i) *out++ = static_cast<uint8_t>(m_mapping_table[i]); for (; i < 128; ++i) { uint16_t x = m_mapping_table[i]; *out++ = static_cast<uint8_t>(x & 255); *out++ = static_cast<uint8_t>(x >> 8); } } bool Mapper::SetMappingFunction(const uint8_t *in, int map_fun_size) { if (map_fun_size < 1) return false; // Restore the mapping table. int single_byte_items = static_cast<int>(*in++); int actual_size = 1 + single_byte_items + 2 * (128 - single_byte_items); if (actual_size != map_fun_size) return false; int i; for (i = 0; i < single_byte_items; ++i) m_mapping_table[i] = static_cast<uint16_t>(*in++); for (; i < 128; ++i) { m_mapping_table[i] = static_cast<uint16_t>(in[0]) | (static_cast<uint16_t>(in[1]) << 8); in += 2; } return true; } uint8_t Mapper::MapTo8Bit(int16_t x) const { if (!x) return 0; uint16_t abs_x = static_cast<uint16_t>(std::abs(x)); // TODO(m): Use binary search instead of O(n) search. uint8_t mapped; for (mapped = 1; mapped < 127; ++mapped) { if (abs_x < m_mapping_table[mapped]) { if ((abs_x - m_mapping_table[mapped - 1]) < (m_mapping_table[mapped] - abs_x)) { --mapped; } break; } } return x >= 0 ? mapped : static_cast<uint8_t>(-static_cast<int8_t>(mapped)); } int16_t Mapper::UnmapFrom8Bit(uint8_t x) const { if (!x) return 0; bool negative = (x & 128) != 0; if (negative) { x = static_cast<uint8_t>(-static_cast<int8_t>(x)); } int16_t value = static_cast<int16_t>(m_mapping_table[x]); return negative ? -value : value; } int Mapper::NumberOfSingleByteMappingItems() const { int single_byte_items; for (single_byte_items = 0; single_byte_items < 128; ++single_byte_items) { if (m_mapping_table[single_byte_items] >= 256) break; } return single_byte_items; } } // namespace himg <commit_msg>First version of quality based DPCM of the low res image<commit_after>//----------------------------------------------------------------------------- // HIMG, by Marcus Geelnard, 2015 // // This is free and unencumbered software released into the public domain. // // See LICENSE for details. //----------------------------------------------------------------------------- #include "mapper.h" #include <algorithm> #include <utility> namespace himg { namespace { // This is a hand-tuned mapping table that seems to give good results. const int16_t kLowResMappingTable[128] = { 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, 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, 52, 53, 54, 55, 56, 57, 58, 59, 60, 62, 63, 64, 65, 67, 68, 70, 71, 73, 74, 76, 78, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99, 102, 104, 106, 109, 111, 114, 117, 119, 122, 125, 128, 131, 134, 137, 140, 143, 146, 150, 153, 156, 160, 164, 167, 171, 175, 178, 182, 186, 190, 195, 199, 203, 207, 212, 216, 221, 226, 230, 235, 240, 245, 250, 255, 999 // FIXME! }; const std::pair<int, int> kLowResMapScaleTable[] = { { 0, 120 }, { 5, 90 }, { 10, 70 }, { 20, 40 }, { 30, 32 }, { 40, 26 }, { 50, 20 }, { 100, 16 } }; // Given a quality value in the range [0, 100], return an interpolated scaling // factor. int QualityToScale(int quality, const std::pair<int, int> *table, int table_size) { // Look up the quality level in the quality -> scaling factor LUT. int idx; for (idx = 0; idx < table_size - 1; ++idx) { if (table[idx + 1].first > quality) break; } if (idx >= table_size - 1) return table[table_size - 1].second; // Pick out the two closest table entries. int q1 = table[idx].first; int s1 = table[idx].second; int q2 = table[idx + 1].first; int s2 = table[idx + 1].second; // Perform linear interpolation between the two table entries. int q = quality; int denom = q2 - q1; return s1 + ((s2 - s1) * (q - q1) + (denom >> 1)) / denom; } } // namespace void LowResMapper::InitForQuality(int quality) { // Determine ramp factor based on the quality setting. The ramp factor is in // 1/16ths. int16_t index_scale = QualityToScale(quality, kLowResMapScaleTable, sizeof(kLowResMapScaleTable) / sizeof(kLowResMapScaleTable[0])); // Generate the mapping table based on the index scale. for (int16_t i = 0; i < 128; ++i) { int16_t index = (i * index_scale + 8) >> 4; index = std::min(index, int16_t(127)); m_mapping_table[i] = kLowResMappingTable[index]; } } int Mapper::MappingFunctionSize() const { // The mapping table requires one byte that tells how many items can be // represented with a single byte, plus the actual single- and double-byte // items. int single_byte_items = NumberOfSingleByteMappingItems(); return 1 + single_byte_items + 2 * (128 - single_byte_items); } void Mapper::GetMappingFunction(uint8_t *out) const { // Store the mapping table. int single_byte_items = NumberOfSingleByteMappingItems(); *out++ = static_cast<uint8_t>(single_byte_items); int i; for (i = 0; i < single_byte_items; ++i) *out++ = static_cast<uint8_t>(m_mapping_table[i]); for (; i < 128; ++i) { uint16_t x = m_mapping_table[i]; *out++ = static_cast<uint8_t>(x & 255); *out++ = static_cast<uint8_t>(x >> 8); } } bool Mapper::SetMappingFunction(const uint8_t *in, int map_fun_size) { if (map_fun_size < 1) return false; // Restore the mapping table. int single_byte_items = static_cast<int>(*in++); int actual_size = 1 + single_byte_items + 2 * (128 - single_byte_items); if (actual_size != map_fun_size) return false; int i; for (i = 0; i < single_byte_items; ++i) m_mapping_table[i] = static_cast<uint16_t>(*in++); for (; i < 128; ++i) { m_mapping_table[i] = static_cast<uint16_t>(in[0]) | (static_cast<uint16_t>(in[1]) << 8); in += 2; } return true; } uint8_t Mapper::MapTo8Bit(int16_t x) const { if (!x) return 0; uint16_t abs_x = static_cast<uint16_t>(std::abs(x)); // TODO(m): Use binary search instead of O(n) search. uint8_t mapped; for (mapped = 1; mapped < 127; ++mapped) { if (abs_x < m_mapping_table[mapped]) { if ((abs_x - m_mapping_table[mapped - 1]) < (m_mapping_table[mapped] - abs_x)) { --mapped; } break; } } return x >= 0 ? mapped : static_cast<uint8_t>(-static_cast<int8_t>(mapped)); } int16_t Mapper::UnmapFrom8Bit(uint8_t x) const { if (!x) return 0; bool negative = (x & 128) != 0; if (negative) { x = static_cast<uint8_t>(-static_cast<int8_t>(x)); } int16_t value = static_cast<int16_t>(m_mapping_table[x]); return negative ? -value : value; } int Mapper::NumberOfSingleByteMappingItems() const { int single_byte_items; for (single_byte_items = 0; single_byte_items < 128; ++single_byte_items) { if (m_mapping_table[single_byte_items] >= 256) break; } return single_byte_items; } } // namespace himg <|endoftext|>
<commit_before>// cpsm - fuzzy path matcher // Copyright (C) 2015 Jamie Liu // // 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 "matcher.h" #include <algorithm> #include <cstdint> #include <utility> #include <boost/range/adaptor/reversed.hpp> #include "path_util.h" #include "str_util.h" namespace cpsm { Matcher::Matcher(std::string query, MatcherOpts opts) : query_(std::move(query)), opts_(std::move(opts)) { if (opts_.is_path) { switch (opts_.query_path_mode) { case MatcherOpts::QueryPathMode::NORMAL: require_full_part_ = false; break; case MatcherOpts::QueryPathMode::STRICT: require_full_part_ = true; break; case MatcherOpts::QueryPathMode::AUTO: require_full_part_ = (query_.find_first_of('/') != std::string::npos); break; } for (boost::string_ref const query_part : path_components_of(query_)) { std::vector<char32_t> query_part_chars; decompose_utf8_string(query_part, query_part_chars); query_parts_chars_.emplace_back(std::move(query_part_chars)); } } else { require_full_part_ = false; std::vector<char32_t> query_chars; decompose_utf8_string(query_, query_chars); query_parts_chars_.emplace_back(std::move(query_chars)); } // Queries are smartcased (case-sensitive only if any uppercase appears in the // query). is_case_sensitive_ = std::any_of(query_.begin(), query_.end(), is_uppercase); cur_file_parts_ = path_components_of(opts_.cur_file); // Keeping the filename in cur_file_parts_ causes the path distance metric to // favor the currently open file. While we don't want to exclude the // currently open file from being matched, it shouldn't be favored over its // siblings on path distance. if (!cur_file_parts_.empty()) { cur_file_parts_.pop_back(); } } bool Matcher::match_base(boost::string_ref const item, MatchBase& m, std::vector<char32_t>* item_part_chars) const { m = MatchBase(); if (query_parts_chars_.empty()) { return true; } std::vector<char32_t> item_part_chars_local; if (!item_part_chars) { item_part_chars = &item_part_chars_local; } std::vector<boost::string_ref> item_parts; if (opts_.is_path) { item_parts = path_components_of(item); m.path_distance = path_distance_between(cur_file_parts_, item_parts); } else { item_parts.push_back(item); } // Since for paths (the common case) we prefer rightmost path components, we // scan path components right-to-left. auto query_part_chars_it = query_parts_chars_.rbegin(); auto const query_part_chars_end = query_parts_chars_.rend(); // Index of the last unmatched character in query_part. std::ptrdiff_t end = std::ptrdiff_t(query_part_chars_it->size()) - 1; // Index into item_parts, counting from the right. CharCount part_index = 0; for (boost::string_ref const item_part : boost::adaptors::reverse(item_parts)) { auto const& query_part_chars = *query_part_chars_it; item_part_chars->clear(); decompose_utf8_string(item_part, *item_part_chars); if (part_index == 0) { m.unmatched_len = item_part_chars->size(); } // Since path components are matched right-to-left, query characters must be // consumed greedily right-to-left. std::ptrdiff_t start = end; // index of last unmatched query char if (start >= 0) { for (char32_t const c : boost::adaptors::reverse(*item_part_chars)) { if (match_char(c, query_part_chars[start])) { start--; if (start < 0) { break; } } } } if (require_full_part_ && start >= 0) { // Didn't consume all characters, but strict query path mode is on, so the // consumed characters don't count. part_index++; continue; } std::ptrdiff_t const next_end = start; // Since within a path component we usually prefer leftmost character // matches, we pick the leftmost match for each consumed character. start++; // now index of first matched query char if (start <= end) { const auto is_word_prefix = [&](std::size_t const i) -> bool { if (i == 0) { return true; } if (is_alphanumeric((*item_part_chars)[i]) && !is_alphanumeric((*item_part_chars)[i - 1])) { return true; } if (is_uppercase((*item_part_chars)[i]) && !is_uppercase((*item_part_chars)[i - 1])) { return true; } return false; }; bool at_word_start = false; for (std::size_t i = 0; i < item_part_chars->size(); i++) { if (match_char((*item_part_chars)[i], query_part_chars[start])) { if (part_index == 0) { if (is_word_prefix(i)) { at_word_start = true; } if (at_word_start) { m.word_prefix_len++; } if (i == 0 && start == 0) { m.prefix_match = MatchBase::PrefixMatch::PARTIAL; } } start++; if (start > end) { if (part_index == 0) { m.unmatched_len = item_part_chars->size() - (i + 1); if (i == std::size_t(end) && next_end < 0) { m.prefix_match = MatchBase::PrefixMatch::FULL; } } break; } } else { at_word_start = false; } } } // Did we match anything in this item part? if (end != next_end) { end = next_end; m.part_index_sum += part_index; } if (end < 0) { query_part_chars_it++; if (query_part_chars_it == query_part_chars_end) { return true; } end = std::ptrdiff_t(query_part_chars_it->size()) - 1; } part_index++; } return false; } bool Matcher::match_char(char32_t item, char32_t const query) const { if (!is_case_sensitive_) { // The query must not contain any uppercase letters since otherwise the // query would be case-sensitive, so just force all uppercase characters to // lowercase. if (is_uppercase(item)) { item = to_lowercase(item); } } return item == query; } } // namespace cpsm <commit_msg>Fix use of path distance for empty queries<commit_after>// cpsm - fuzzy path matcher // Copyright (C) 2015 Jamie Liu // // 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 "matcher.h" #include <algorithm> #include <cstdint> #include <utility> #include <boost/range/adaptor/reversed.hpp> #include "path_util.h" #include "str_util.h" namespace cpsm { Matcher::Matcher(std::string query, MatcherOpts opts) : query_(std::move(query)), opts_(std::move(opts)) { if (opts_.is_path) { switch (opts_.query_path_mode) { case MatcherOpts::QueryPathMode::NORMAL: require_full_part_ = false; break; case MatcherOpts::QueryPathMode::STRICT: require_full_part_ = true; break; case MatcherOpts::QueryPathMode::AUTO: require_full_part_ = (query_.find_first_of('/') != std::string::npos); break; } for (boost::string_ref const query_part : path_components_of(query_)) { std::vector<char32_t> query_part_chars; decompose_utf8_string(query_part, query_part_chars); query_parts_chars_.emplace_back(std::move(query_part_chars)); } } else { require_full_part_ = false; std::vector<char32_t> query_chars; decompose_utf8_string(query_, query_chars); query_parts_chars_.emplace_back(std::move(query_chars)); } // Queries are smartcased (case-sensitive only if any uppercase appears in the // query). is_case_sensitive_ = std::any_of(query_.begin(), query_.end(), is_uppercase); cur_file_parts_ = path_components_of(opts_.cur_file); // Keeping the filename in cur_file_parts_ causes the path distance metric to // favor the currently open file. While we don't want to exclude the // currently open file from being matched, it shouldn't be favored over its // siblings on path distance. if (!cur_file_parts_.empty()) { cur_file_parts_.pop_back(); } } bool Matcher::match_base(boost::string_ref const item, MatchBase& m, std::vector<char32_t>* item_part_chars) const { m = MatchBase(); std::vector<char32_t> item_part_chars_local; if (!item_part_chars) { item_part_chars = &item_part_chars_local; } std::vector<boost::string_ref> item_parts; if (opts_.is_path) { item_parts = path_components_of(item); m.path_distance = path_distance_between(cur_file_parts_, item_parts); } else { item_parts.push_back(item); } if (query_parts_chars_.empty()) { return true; } // Since for paths (the common case) we prefer rightmost path components, we // scan path components right-to-left. auto query_part_chars_it = query_parts_chars_.rbegin(); auto const query_part_chars_end = query_parts_chars_.rend(); // Index of the last unmatched character in query_part. std::ptrdiff_t end = std::ptrdiff_t(query_part_chars_it->size()) - 1; // Index into item_parts, counting from the right. CharCount part_index = 0; for (boost::string_ref const item_part : boost::adaptors::reverse(item_parts)) { auto const& query_part_chars = *query_part_chars_it; item_part_chars->clear(); decompose_utf8_string(item_part, *item_part_chars); if (part_index == 0) { m.unmatched_len = item_part_chars->size(); } // Since path components are matched right-to-left, query characters must be // consumed greedily right-to-left. std::ptrdiff_t start = end; // index of last unmatched query char if (start >= 0) { for (char32_t const c : boost::adaptors::reverse(*item_part_chars)) { if (match_char(c, query_part_chars[start])) { start--; if (start < 0) { break; } } } } if (require_full_part_ && start >= 0) { // Didn't consume all characters, but strict query path mode is on, so the // consumed characters don't count. part_index++; continue; } std::ptrdiff_t const next_end = start; // Since within a path component we usually prefer leftmost character // matches, we pick the leftmost match for each consumed character. start++; // now index of first matched query char if (start <= end) { const auto is_word_prefix = [&](std::size_t const i) -> bool { if (i == 0) { return true; } if (is_alphanumeric((*item_part_chars)[i]) && !is_alphanumeric((*item_part_chars)[i - 1])) { return true; } if (is_uppercase((*item_part_chars)[i]) && !is_uppercase((*item_part_chars)[i - 1])) { return true; } return false; }; bool at_word_start = false; for (std::size_t i = 0; i < item_part_chars->size(); i++) { if (match_char((*item_part_chars)[i], query_part_chars[start])) { if (part_index == 0) { if (is_word_prefix(i)) { at_word_start = true; } if (at_word_start) { m.word_prefix_len++; } if (i == 0 && start == 0) { m.prefix_match = MatchBase::PrefixMatch::PARTIAL; } } start++; if (start > end) { if (part_index == 0) { m.unmatched_len = item_part_chars->size() - (i + 1); if (i == std::size_t(end) && next_end < 0) { m.prefix_match = MatchBase::PrefixMatch::FULL; } } break; } } else { at_word_start = false; } } } // Did we match anything in this item part? if (end != next_end) { end = next_end; m.part_index_sum += part_index; } if (end < 0) { query_part_chars_it++; if (query_part_chars_it == query_part_chars_end) { return true; } end = std::ptrdiff_t(query_part_chars_it->size()) - 1; } part_index++; } return false; } bool Matcher::match_char(char32_t item, char32_t const query) const { if (!is_case_sensitive_) { // The query must not contain any uppercase letters since otherwise the // query would be case-sensitive, so just force all uppercase characters to // lowercase. if (is_uppercase(item)) { item = to_lowercase(item); } } return item == query; } } // namespace cpsm <|endoftext|>
<commit_before>// [[Rcpp::depends(RcppArmadillo)]] #include <RcppArmadillo.h> #include <Rmath.h> #include <vector> #include <cassert> #include "vmat.h" #include "gmat.h" #include "DataPairs.h" #include "quadrule.h" #include "pn.h" #include "functions.h" using namespace Rcpp; using namespace arma; using namespace std; const double twopi = 2*datum::pi; ///////////////////////////////////////////////////////////////////////////////////////////////// /* Full loglikelihood */ double loglikfull(unsigned row, DataPairs &data, const gmat &sigmaMarg, const gmat &sigmaJoint, const gmat &sigmaCond, vmat sigmaU, vec u, bool full=1){ data.pi_gen(row, u); // Estimation of pi based on u irowvec causes = data.causes_get(row); // Failure causes for pair in question double res = 0; // Initialising output (loglik contribution) if ((causes(0) > 0) & (causes(1) > 0)){ /* Both individuals experience failure */ res = logdF2(row, causes, data, sigmaJoint, u); } else if((causes(0) <= 0) & (causes(1) <= 0)){ /* Neither individual experience failure */ if ((causes(0) < 0) & (causes(1) < 0)){ // Full follow-up for both individuals for (unsigned i=1; i<=2; i++){ // Over individuals double lik = 1; for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes double prob = F1(row, j, i, data); lik -= prob; } res += log(lik); } } else if (((causes(0) < 0) & (causes(1) == 0)) | ((causes(0) == 0) & (causes(1) < 0))){ // Full follow-up for only one individual for (unsigned i=1; i<=2; i++){ // Over individuals double lik = 1; for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes if (causes(i-1) < 0){ double prob = F1(row, j, i, data); lik -= prob; } else { double prob = F1(row, j, i, data, sigmaMarg, u); lik -= prob; } } res += log(lik); } } else { // Full follow-up for neither individual double lik = 1; // Marginal probabilities for (unsigned i=1; i<=2; i++){ // Over individuals for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes double prob = F1(row, j, i, data, sigmaMarg, u); lik -= prob; // Subtracting } } // Bivariate probabilities for (unsigned k=1; k<=data.ncauses; k++){ // Over failure causes for (unsigned l=1; l<=data.ncauses; l++){ irowvec vcauses(2); vcauses(0) = k; vcauses(1) = l; double prob = F2(row, vcauses, data, sigmaJoint, u); lik += prob; // Adding } } res = log(lik); } } else { /* One individual experiences failure the other does not */ for (unsigned i=1; i<=2; i++){ // Over individuals unsigned cause = causes(i-1); if (cause > 0){ // Marginal probability of failure res += logdF1(row, cause, i, data, sigmaMarg, u); } else { // Marginal probability of no failure unsigned cond_cause; if (i==1){ cond_cause = causes(1); } else { cond_cause = causes(0); } for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes double lik = 1; if (cause < 0){ // Unconditional double prob = F1(row, j, i, data); lik -= prob; } else { // Conditional double prob = F1(row, j, i, cond_cause, data, sigmaCond, u); lik -= prob; } res += log(lik); } } } } /* Contribution from u */ if (full){ vmat sig = sigmaU; // Variance-covariance matrix of u double inner = as_scalar(u*sig.inv*u.t()); // PDF of u double logpdfu = log(pow(twopi,-(data.ncauses/2))) + sig.loginvsqdet - 0.5*inner; // Adding to the loglik res += logpdfu; } /* Return */ return(res); } ///////////////////////////////////////////////////////////////////////////////////////////////// /* Score function of full loglikelihood */ rowvec Dloglikfull(unsigned row, DataPairs &data, const gmat &sigmaMarg, const gmat &sigmaJoint, const gmat &sigmaCond, vmat sigmaU, vec u, bool full=1){ /* Estimation of pi, dpidu and dlogpidu */ data.pi_gen(row, u); data.dpidu_gen(row, u); data.dlogpidu_gen(row, u); irowvec causes = data.causes_get(row); // Failure causes for pair in question rowvec res = zeros<rowvec>(data.ncauses); // Initialising output (score contribution) if ((causes(0) > 0) & (causes(1) > 0)){ /* Both individuals experience failure */ res = dlogdF2du(row, causes, data, sigmaJoint, u); } else if((causes(0) <= 0) & (causes(1) <= 0)){ /* Neither individual experience failure */ if ((causes(0) < 0) & (causes(1) < 0)){ // Full follow-up for both individuals for (unsigned i=1; i<=2; i++){ // Over individuals double lik = 1; rowvec likdu = zeros<rowvec>(data.ncauses); for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes double prob = F1(row, j, i, data); rowvec probdu = dF1du(row, j, i, data); lik -= prob; likdu -= probdu; } res += (1/lik)*likdu; } } else if (((causes(0) < 0) & (causes(1) == 0)) | ((causes(0) == 0) & (causes(1) < 0))){ // Full follow-up for only one individual for (unsigned i=1; i<=2; i++){ // Over individuals double lik = 1; rowvec likdu = zeros<rowvec>(data.ncauses); for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes if (causes(i-1) < 0){ double prob = F1(row, j, i, data); rowvec probdu = dF1du(row, j, i, data); lik -= prob; likdu -= probdu; } else { double prob = F1(row, j, i, data, sigmaMarg, u); rowvec probdu = dF1du(row, j, i, data, sigmaMarg, u); lik -= prob; likdu -= probdu; } } res += (1/lik)*likdu; } } else { // Full follow-up for neither individual double lik = 1; rowvec likdu = zeros<rowvec>(data.ncauses); // Marginal probabilities for (unsigned i=1; i<=2; i++){ // Over individuals for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes double prob = F1(row, j, i, data, sigmaMarg, u); rowvec probdu = dF1du(row, j, i, data, sigmaMarg, u); lik -= prob; // Subtracting likdu -= probdu; } } // Bivariate probabilities for (unsigned k=1; k<=data.ncauses; k++){ // Over failure causes for (unsigned l=1; l<=data.ncauses; l++){ irowvec vcauses(2); vcauses(0) = k; vcauses(1) = l; double prob = F2(row, vcauses, data, sigmaJoint, u); rowvec probdu = dF2du(row, vcauses, data, sigmaJoint, u); lik += prob; // Adding likdu += probdu; } } res = (1/lik)*likdu; } } else { /* One individual experiences failure the other does not */ for (unsigned i=1; i<=2; i++){ // Over individuals unsigned cause = causes(i-1); if (cause > 0){ // Marginal probability of failure res += dlogdF1du(row, cause, i, data, sigmaMarg, u); } else { // Marginal probability of no failure unsigned cond_cause; if (i==1){ cond_cause = causes(1); } else { cond_cause = causes(0); } for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes double lik = 1; rowvec likdu = zeros<rowvec>(data.ncauses); if (cause < 0){ // Uncondtional double prob = F1(row, j, i, data); rowvec probdu = dF1du(row, j, i, data); lik -= prob; likdu -= probdu; } else { // Conditional double prob = F1(row, j, i, cond_cause, data, sigmaCond, u); rowvec probdu = dF1du(row, j, i, cond_cause, data, sigmaCond, u); lik -= prob; likdu -= probdu; } res += (1/lik)*likdu; } } } } /* Contribution from u */ if (full){ vmat sig = sigmaU; // Variance-covariance matrix etc. of u // Adding to the score res += -u.t()*sig.inv; }; return(res); } ///////////////////////////////////////////////////////////////////////////// // FOR TESTING // [[Rcpp::export]] double loglikout(mat sigma, vec u, int ncauses, imat causes, mat alpha, mat dalpha, mat beta, mat gamma){ // Initialising gmats of sigma (Joint, Cond) gmat sigmaJoint = gmat(ncauses, ncauses); gmat sigmaCond = gmat(ncauses, ncauses); gmat sigmaMarg = gmat(ncauses, 1); // Vectors for extracting rows and columns from sigma uvec rcJ(2); /* for joint */ uvec rc1(1); /* for conditional */ uvec rc2(ncauses+1); /* for conditional */ uvec rcu(ncauses); for (int h=0; h<ncauses; h++){ rcu(h) = ncauses + h; }; // Calculating and setting sigmaJoint for (int h=0; h<ncauses; h++){ for (int i=0; i<ncauses; i++){ rcJ(0)=h; rcJ(1)=ncauses+i; vmat x = vmat(sigma, rcJ, rcu); sigmaJoint.set(h,i,x); }; }; // Calculating and setting sigmaMarg for (int h=0; h<ncauses; h++){ rc1(0) = h; vmat x = vmat(sigma, rc1, rcu); sigmaMarg.set(h,1,x); }; // Calculating and setting sigmaCond for (int h=0; h<ncauses; h++){ for (int i=0; i<ncauses; i++){ rc1(0) = h; rc2(0) = i; for (int j=0; j<ncauses; j++){ rc2(j+1) = rcu(j); }; vmat x = vmat(sigma, rc1, rc2); sigmaCond.set(h,i,x); }; }; Rcpp::Rcout << "here " <<std::endl; // vmat of the us mat matU = sigma.submat(rcu,rcu); vmat sigmaU = vmat(matU); Rcpp::Rcout << "there " <<std::endl; // Generating DataPairs DataPairs data = DataPairs(ncauses, causes, alpha, dalpha, beta, gamma); unsigned row = 1; // Estimating likelihood contribution double loglik = loglikfull(row, data, sigmaMarg, sigmaJoint, sigmaCond, sigmaU, u); Rcpp::Rcout << "everywhere " <<std::endl; // Return return loglik; }; //rowvec Dloglikout(unsigned row, mat sigma, mat data, vec u){ // Generating gmats of sigma (Marg, Joint, MargCond, sigU) // Generating DataPairs // Estimating score contribution // rowvec score = Dloglikfull(unsigned row, DataPairs data, gmat sigmaJoint, gmat sigmaMargCond, vmat sigmaU, vec u, bool full=1); // Return // return score; //}; <commit_msg>export<commit_after>// [[Rcpp::depends(RcppArmadillo)]] #include <RcppArmadillo.h> #include <Rmath.h> #include <vector> #include <cassert> #include "vmat.h" #include "gmat.h" #include "DataPairs.h" #include "quadrule.h" #include "pn.h" #include "functions.h" using namespace Rcpp; using namespace arma; using namespace std; const double twopi = 2*datum::pi; ///////////////////////////////////////////////////////////////////////////////////////////////// /* Full loglikelihood */ double loglikfull(unsigned row, DataPairs &data, const gmat &sigmaMarg, const gmat &sigmaJoint, const gmat &sigmaCond, vmat sigmaU, vec u, bool full=1){ data.pi_gen(row, u); // Estimation of pi based on u irowvec causes = data.causes_get(row); // Failure causes for pair in question double res = 0; // Initialising output (loglik contribution) if ((causes(0) > 0) & (causes(1) > 0)){ /* Both individuals experience failure */ res = logdF2(row, causes, data, sigmaJoint, u); } else if((causes(0) <= 0) & (causes(1) <= 0)){ /* Neither individual experience failure */ if ((causes(0) < 0) & (causes(1) < 0)){ // Full follow-up for both individuals for (unsigned i=1; i<=2; i++){ // Over individuals double lik = 1; for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes double prob = F1(row, j, i, data); lik -= prob; } res += log(lik); } } else if (((causes(0) < 0) & (causes(1) == 0)) | ((causes(0) == 0) & (causes(1) < 0))){ // Full follow-up for only one individual for (unsigned i=1; i<=2; i++){ // Over individuals double lik = 1; for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes if (causes(i-1) < 0){ double prob = F1(row, j, i, data); lik -= prob; } else { double prob = F1(row, j, i, data, sigmaMarg, u); lik -= prob; } } res += log(lik); } } else { // Full follow-up for neither individual double lik = 1; // Marginal probabilities for (unsigned i=1; i<=2; i++){ // Over individuals for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes double prob = F1(row, j, i, data, sigmaMarg, u); lik -= prob; // Subtracting } } // Bivariate probabilities for (unsigned k=1; k<=data.ncauses; k++){ // Over failure causes for (unsigned l=1; l<=data.ncauses; l++){ irowvec vcauses(2); vcauses(0) = k; vcauses(1) = l; double prob = F2(row, vcauses, data, sigmaJoint, u); lik += prob; // Adding } } res = log(lik); } } else { /* One individual experiences failure the other does not */ for (unsigned i=1; i<=2; i++){ // Over individuals unsigned cause = causes(i-1); if (cause > 0){ // Marginal probability of failure res += logdF1(row, cause, i, data, sigmaMarg, u); } else { // Marginal probability of no failure unsigned cond_cause; if (i==1){ cond_cause = causes(1); } else { cond_cause = causes(0); } for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes double lik = 1; if (cause < 0){ // Unconditional double prob = F1(row, j, i, data); lik -= prob; } else { // Conditional double prob = F1(row, j, i, cond_cause, data, sigmaCond, u); lik -= prob; } res += log(lik); } } } } /* Contribution from u */ if (full){ vmat sig = sigmaU; // Variance-covariance matrix of u double inner = as_scalar(u*sig.inv*u.t()); // PDF of u double logpdfu = log(pow(twopi,-(data.ncauses/2))) + sig.loginvsqdet - 0.5*inner; // Adding to the loglik res += logpdfu; } /* Return */ return(res); } ///////////////////////////////////////////////////////////////////////////////////////////////// /* Score function of full loglikelihood */ rowvec Dloglikfull(unsigned row, DataPairs &data, const gmat &sigmaMarg, const gmat &sigmaJoint, const gmat &sigmaCond, vmat sigmaU, vec u, bool full=1){ /* Estimation of pi, dpidu and dlogpidu */ data.pi_gen(row, u); data.dpidu_gen(row, u); data.dlogpidu_gen(row, u); irowvec causes = data.causes_get(row); // Failure causes for pair in question rowvec res = zeros<rowvec>(data.ncauses); // Initialising output (score contribution) if ((causes(0) > 0) & (causes(1) > 0)){ /* Both individuals experience failure */ res = dlogdF2du(row, causes, data, sigmaJoint, u); } else if((causes(0) <= 0) & (causes(1) <= 0)){ /* Neither individual experience failure */ if ((causes(0) < 0) & (causes(1) < 0)){ // Full follow-up for both individuals for (unsigned i=1; i<=2; i++){ // Over individuals double lik = 1; rowvec likdu = zeros<rowvec>(data.ncauses); for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes double prob = F1(row, j, i, data); rowvec probdu = dF1du(row, j, i, data); lik -= prob; likdu -= probdu; } res += (1/lik)*likdu; } } else if (((causes(0) < 0) & (causes(1) == 0)) | ((causes(0) == 0) & (causes(1) < 0))){ // Full follow-up for only one individual for (unsigned i=1; i<=2; i++){ // Over individuals double lik = 1; rowvec likdu = zeros<rowvec>(data.ncauses); for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes if (causes(i-1) < 0){ double prob = F1(row, j, i, data); rowvec probdu = dF1du(row, j, i, data); lik -= prob; likdu -= probdu; } else { double prob = F1(row, j, i, data, sigmaMarg, u); rowvec probdu = dF1du(row, j, i, data, sigmaMarg, u); lik -= prob; likdu -= probdu; } } res += (1/lik)*likdu; } } else { // Full follow-up for neither individual double lik = 1; rowvec likdu = zeros<rowvec>(data.ncauses); // Marginal probabilities for (unsigned i=1; i<=2; i++){ // Over individuals for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes double prob = F1(row, j, i, data, sigmaMarg, u); rowvec probdu = dF1du(row, j, i, data, sigmaMarg, u); lik -= prob; // Subtracting likdu -= probdu; } } // Bivariate probabilities for (unsigned k=1; k<=data.ncauses; k++){ // Over failure causes for (unsigned l=1; l<=data.ncauses; l++){ irowvec vcauses(2); vcauses(0) = k; vcauses(1) = l; double prob = F2(row, vcauses, data, sigmaJoint, u); rowvec probdu = dF2du(row, vcauses, data, sigmaJoint, u); lik += prob; // Adding likdu += probdu; } } res = (1/lik)*likdu; } } else { /* One individual experiences failure the other does not */ for (unsigned i=1; i<=2; i++){ // Over individuals unsigned cause = causes(i-1); if (cause > 0){ // Marginal probability of failure res += dlogdF1du(row, cause, i, data, sigmaMarg, u); } else { // Marginal probability of no failure unsigned cond_cause; if (i==1){ cond_cause = causes(1); } else { cond_cause = causes(0); } for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes double lik = 1; rowvec likdu = zeros<rowvec>(data.ncauses); if (cause < 0){ // Uncondtional double prob = F1(row, j, i, data); rowvec probdu = dF1du(row, j, i, data); lik -= prob; likdu -= probdu; } else { // Conditional double prob = F1(row, j, i, cond_cause, data, sigmaCond, u); rowvec probdu = dF1du(row, j, i, cond_cause, data, sigmaCond, u); lik -= prob; likdu -= probdu; } res += (1/lik)*likdu; } } } } /* Contribution from u */ if (full){ vmat sig = sigmaU; // Variance-covariance matrix etc. of u // Adding to the score res += -u.t()*sig.inv; }; return(res); } ///////////////////////////////////////////////////////////////////////////// // FOR TESTING // [[Rcpp::export]] double loglikout(mat sigma, vec u, int ncauses, imat causes, mat alpha, mat dalpha, mat beta, mat gamma){ // Initialising gmats of sigma (Joint, Cond) gmat sigmaJoint = gmat(ncauses, ncauses); gmat sigmaCond = gmat(ncauses, ncauses); gmat sigmaMarg = gmat(ncauses, 1); // Vectors for extracting rows and columns from sigma uvec rcJ(2); /* for joint */ uvec rc1(1); /* for conditional */ uvec rc2(ncauses+1); /* for conditional */ uvec rcu(ncauses); for (int h=0; h<ncauses; h++){ rcu(h) = ncauses + h; }; // Calculating and setting sigmaJoint for (int h=0; h<ncauses; h++){ for (int i=0; i<ncauses; i++){ rcJ(0)=h; rcJ(1)=ncauses+i; vmat x = vmat(sigma, rcJ, rcu); sigmaJoint.set(h,i,x); }; }; Rcpp::Rcout << "here " <<std::endl; // Calculating and setting sigmaMarg for (int h=0; h<ncauses; h++){ rc1(0) = h; vmat x = vmat(sigma, rc1, rcu); sigmaMarg.set(h,1,x); }; // Calculating and setting sigmaCond for (int h=0; h<ncauses; h++){ for (int i=0; i<ncauses; i++){ rc1(0) = h; rc2(0) = i; for (int j=0; j<ncauses; j++){ rc2(j+1) = rcu(j); }; vmat x = vmat(sigma, rc1, rc2); sigmaCond.set(h,i,x); }; }; // vmat of the us mat matU = sigma.submat(rcu,rcu); vmat sigmaU = vmat(matU); Rcpp::Rcout << "there " <<std::endl; // Generating DataPairs DataPairs data = DataPairs(ncauses, causes, alpha, dalpha, beta, gamma); unsigned row = 1; // Estimating likelihood contribution double loglik = loglikfull(row, data, sigmaMarg, sigmaJoint, sigmaCond, sigmaU, u); Rcpp::Rcout << "everywhere " <<std::endl; // Return return loglik; }; //rowvec Dloglikout(unsigned row, mat sigma, mat data, vec u){ // Generating gmats of sigma (Marg, Joint, MargCond, sigU) // Generating DataPairs // Estimating score contribution // rowvec score = Dloglikfull(unsigned row, DataPairs data, gmat sigmaJoint, gmat sigmaMargCond, vmat sigmaU, vec u, bool full=1); // Return // return score; //}; <|endoftext|>
<commit_before>// [[Rcpp::depends(RcppArmadillo)]] #include <RcppArmadillo.h> #include <Rmath.h> #include <vector> #include <cassert> #include "vmat.h" #include "gmat.h" #include "DataPairs.h" #include "quadrule.h" #include "pn.h" #include "functions.h" using namespace Rcpp; using namespace arma; using namespace std; const double twopi = 2*datum::pi; ///////////////////////////////////////////////////////////////////////////////////////////////// /* Full loglikelihood */ double loglikfull(unsigned row, DataPairs &data, const gmat &sigmaMarg, const gmat &sigmaJoint, const gmat &sigmaMargCond, vmat sigmaU, vec u, bool full=1){ data.pi_gen(row, u); // Estimation of pi based on u irowvec causes = data.causes_get(row); // Failure causes for pair in question double res = 0; // Initialising output (loglik contribution) if ((causes(0) > 0) & (causes(1) > 0)){ /* Both individuals experience failure */ res = logdF2(row, causes, data, sigmaJoint, u); } else if((causes(0) <= 0) & (causes(1) <= 0)){ /* Neither individual experience failure */ if ((causes(0) < 0) & (causes(1) < 0)){ // Full follow-up for both individuals for (unsigned i=1; i<=2; i++){ // Over individuals double lik = 1; for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes double prob = F1(row, j, i, data); lik -= prob; } res += log(lik); } } else if (((causes(0) < 0) & (causes(1) == 0)) | ((causes(0) == 0) & (causes(1) < 0))){ // Full follow-up for only one individual for (unsigned i=1; i<=2; i++){ // Over individuals double lik = 1; for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes if (causes(i-1) < 0){ double prob = F1(row, j, i, data); lik -= prob; } else { double prob = F1(row, j, i, data, sigmaMarg, u); lik -= prob; } } res += log(lik); } } else { // Full follow-up for neither individual double lik = 1; // Marginal probabilities for (unsigned i=1; i<=2; i++){ // Over individuals for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes double prob = F1(row, j, i, data, sigmaMarg, u); lik -= prob; // Subtracting } } // Bivariate probabilities for (unsigned k=1; k<=data.ncauses; k++){ // Over failure causes for (unsigned l=1; l<=data.ncauses; l++){ irowvec vcauses(2); vcauses(0) = k; vcauses(1) = l; double prob = F2(row, vcauses, data, sigmaJoint, u); lik += prob; // Adding } } res = log(lik); } } else { /* One individual experiences failure the other does not */ for (unsigned i=1; i<=2; i++){ // Over individuals unsigned cause = causes(i-1); if (cause > 0){ // Marginal probability of failure res += logdF1(row, cause, i, data, sigmaMarg, u); } else { // Marginal probability of no failure unsigned cond_cause; if (i==1){ cond_cause = causes(1); } else { cond_cause = causes(0); } for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes double lik = 1; if (cause < 0){ // Unconditional double prob = F1(row, j, i, data); lik -= prob; } else { // Conditional double prob = F1(row, j, i, cond_cause, data, sigmaMargCond, u); lik -= prob; } res += log(lik); } } } } /* Contribution from u */ if (full){ vmat sig = sigmaU; // Variance-covariance matrix of u double inner = as_scalar(u*sig.inv*u.t()); // PDF of u double logpdfu = log(pow(twopi,-(data.ncauses/2))) + sig.loginvsqdet - 0.5*inner; // Adding to the loglik res += logpdfu; } /* Return */ return(res); } ///////////////////////////////////////////////////////////////////////////////////////////////// /* Score function of full loglikelihood */ rowvec Dloglikfull(unsigned row, DataPairs &data, const gmat &sigmaMarg, const gmat &sigmaJoint, const gmat &sigmaMargCond, vmat sigmaU, vec u, bool full=1){ /* Estimation of pi, dpidu and dlogpidu */ data.pi_gen(row, u); data.dpidu_gen(row, u); data.dlogpidu_gen(row, u); irowvec causes = data.causes_get(row); // Failure causes for pair in question rowvec res(data.ncauses); // Initialising output (score contribution) if ((causes(0) > 0) & (causes(1) > 0)){ /* Both individuals experience failure */ res = dlogdF2du(row, causes, data, sigmaJoint, u); } else if((causes(0) <= 0) & (causes(1) <= 0)){ /* Neither individual experience failure */ if ((causes(0) < 0) & (causes(1) < 0)){ // Full follow-up for both individuals for (unsigned i=1; i<=2; i++){ // Over individuals double lik = 1; for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes double prob = F1(row, j, i, data); lik -= prob; } res += log(lik); } } else if (((causes(0) < 0) & (causes(1) == 0)) | ((causes(0) == 0) & (causes(1) < 0))){ // Full follow-up for only one individual for (unsigned i=1; i<=2; i++){ // Over individuals double lik = 1; for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes if (causes(i-1) < 0){ double prob = F1(row, j, i, data); lik -= prob; } else { double prob = F1(row, j, i, data, sigmaMarg, u); lik -= prob; } } res += log(lik); } } else { // Full follow-up for neither individual double lik = 1; // Marginal probabilities for (unsigned i=1; i<=2; i++){ // Over individuals for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes double prob = F1(row, j, i, data, sigmaMarg, u); lik -= prob; // Subtracting } } // Bivariate probabilities for (unsigned k=1; k<=data.ncauses; k++){ // Over failure causes for (unsigned l=1; l<=data.ncauses; l++){ irowvec vcauses(2); vcauses(0) = k; vcauses(1) = l; double prob = F2(row, vcauses, data, sigmaJoint, u); lik += prob; // Adding } } res = log(lik); } } else { /* One individual experiences failure the other does not */ for (unsigned i=1; i<=2; i++){ // Over individuals unsigned cause = causes(i-1); if (cause > 0){ // Marginal probability of failure res += dlogdF1du(row, cause, i, data, sigmaMarg, u); } else { // Marginal probability of no failure unsigned cond_cause; if (i==1){ cond_cause = causes(1); } else { cond_cause = causes(0); } for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes double lik = 1; if (cause < 0){ // Uncondtional double prob = F1(row, j, i, data); lik -= prob; } else { // Conditional double prob = F1(row, j, i, cond_cause, data, sigmaMargCond, u); lik -= prob; } res += log(lik); } } } } /* Contribution from u */ if (full){ vmat sig = sigmaU; // Variance-covariance matrix etc. of u double inner = as_scalar(u*sig.inv*u.t()); // PDF of u double logpdfu = log(pow(twopi,-(data.ncauses/2))) + sig.loginvsqdet - 0.5*inner; // Adding to the loglik res += logpdfu; } return(res); } <commit_msg>Dloglikfull<commit_after>// [[Rcpp::depends(RcppArmadillo)]] #include <RcppArmadillo.h> #include <Rmath.h> #include <vector> #include <cassert> #include "vmat.h" #include "gmat.h" #include "DataPairs.h" #include "quadrule.h" #include "pn.h" #include "functions.h" using namespace Rcpp; using namespace arma; using namespace std; const double twopi = 2*datum::pi; ///////////////////////////////////////////////////////////////////////////////////////////////// /* Full loglikelihood */ double loglikfull(unsigned row, DataPairs &data, const gmat &sigmaMarg, const gmat &sigmaJoint, const gmat &sigmaMargCond, vmat sigmaU, vec u, bool full=1){ data.pi_gen(row, u); // Estimation of pi based on u irowvec causes = data.causes_get(row); // Failure causes for pair in question double res = 0; // Initialising output (loglik contribution) if ((causes(0) > 0) & (causes(1) > 0)){ /* Both individuals experience failure */ res = logdF2(row, causes, data, sigmaJoint, u); } else if((causes(0) <= 0) & (causes(1) <= 0)){ /* Neither individual experience failure */ if ((causes(0) < 0) & (causes(1) < 0)){ // Full follow-up for both individuals for (unsigned i=1; i<=2; i++){ // Over individuals double lik = 1; for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes double prob = F1(row, j, i, data); lik -= prob; } res += log(lik); } } else if (((causes(0) < 0) & (causes(1) == 0)) | ((causes(0) == 0) & (causes(1) < 0))){ // Full follow-up for only one individual for (unsigned i=1; i<=2; i++){ // Over individuals double lik = 1; for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes if (causes(i-1) < 0){ double prob = F1(row, j, i, data); lik -= prob; } else { double prob = F1(row, j, i, data, sigmaMarg, u); lik -= prob; } } res += log(lik); } } else { // Full follow-up for neither individual double lik = 1; // Marginal probabilities for (unsigned i=1; i<=2; i++){ // Over individuals for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes double prob = F1(row, j, i, data, sigmaMarg, u); lik -= prob; // Subtracting } } // Bivariate probabilities for (unsigned k=1; k<=data.ncauses; k++){ // Over failure causes for (unsigned l=1; l<=data.ncauses; l++){ irowvec vcauses(2); vcauses(0) = k; vcauses(1) = l; double prob = F2(row, vcauses, data, sigmaJoint, u); lik += prob; // Adding } } res = log(lik); } } else { /* One individual experiences failure the other does not */ for (unsigned i=1; i<=2; i++){ // Over individuals unsigned cause = causes(i-1); if (cause > 0){ // Marginal probability of failure res += logdF1(row, cause, i, data, sigmaMarg, u); } else { // Marginal probability of no failure unsigned cond_cause; if (i==1){ cond_cause = causes(1); } else { cond_cause = causes(0); } for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes double lik = 1; if (cause < 0){ // Unconditional double prob = F1(row, j, i, data); lik -= prob; } else { // Conditional double prob = F1(row, j, i, cond_cause, data, sigmaMargCond, u); lik -= prob; } res += log(lik); } } } } /* Contribution from u */ if (full){ vmat sig = sigmaU; // Variance-covariance matrix of u double inner = as_scalar(u*sig.inv*u.t()); // PDF of u double logpdfu = log(pow(twopi,-(data.ncauses/2))) + sig.loginvsqdet - 0.5*inner; // Adding to the loglik res += logpdfu; } /* Return */ return(res); } ///////////////////////////////////////////////////////////////////////////////////////////////// /* Score function of full loglikelihood */ rowvec Dloglikfull(unsigned row, DataPairs &data, const gmat &sigmaMarg, const gmat &sigmaJoint, const gmat &sigmaMargCond, vmat sigmaU, vec u, bool full=1){ /* Estimation of pi, dpidu and dlogpidu */ data.pi_gen(row, u); data.dpidu_gen(row, u); data.dlogpidu_gen(row, u); irowvec causes = data.causes_get(row); // Failure causes for pair in question rowvec res = zeros<rowvec>(ncauses); // Initialising output (score contribution) if ((causes(0) > 0) & (causes(1) > 0)){ /* Both individuals experience failure */ res = dlogdF2du(row, causes, data, sigmaJoint, u); } else if((causes(0) <= 0) & (causes(1) <= 0)){ /* Neither individual experience failure */ if ((causes(0) < 0) & (causes(1) < 0)){ // Full follow-up for both individuals for (unsigned i=1; i<=2; i++){ // Over individuals double lik = 1; rowvec likdu = zeros<rowvec>(ncauses); for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes double prob = F1(row, j, i, data); rowvec probdu = dF1du(row, j, i, data); lik -= prob; likdu -= probdu; } res += (1/lik)*likdu; } } else if (((causes(0) < 0) & (causes(1) == 0)) | ((causes(0) == 0) & (causes(1) < 0))){ // Full follow-up for only one individual for (unsigned i=1; i<=2; i++){ // Over individuals double lik = 1; rowvec likdu = zeros<rowvec>(ncauses); for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes if (causes(i-1) < 0){ double prob = F1(row, j, i, data); rowvec probdu = dF1du(row, j, i, data); lik -= prob; likdu -= probdu; } else { double prob = F1(row, j, i, data, sigmaMarg, u); double probdu = dF1du(row, j, i, data, sigmaMarg, u); lik -= prob; likdu -= probdu; } } res += (1/lik)*likdu; } } else { // Full follow-up for neither individual double lik = 1; rowvec likdu = zeros<rowvec>(ncauses); // Marginal probabilities for (unsigned i=1; i<=2; i++){ // Over individuals for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes double prob = F1(row, j, i, data, sigmaMarg, u); rowvec probdu = dF1du(row, j, i, data, sigmaMarg, u); lik -= prob; // Subtracting likdu -= probdu; } } // Bivariate probabilities for (unsigned k=1; k<=data.ncauses; k++){ // Over failure causes for (unsigned l=1; l<=data.ncauses; l++){ irowvec vcauses(2); vcauses(0) = k; vcauses(1) = l; double prob = F2(row, vcauses, data, sigmaJoint, u); rowvec probdu = dF2du(row, vcauses, data, sigmaJoint, u); lik += prob; // Adding likdu += probdu; } } res = (1/lik)*likdu; } } else { /* One individual experiences failure the other does not */ for (unsigned i=1; i<=2; i++){ // Over individuals unsigned cause = causes(i-1); if (cause > 0){ // Marginal probability of failure res += dlogdF1du(row, cause, i, data, sigmaMarg, u); } else { // Marginal probability of no failure unsigned cond_cause; if (i==1){ cond_cause = causes(1); } else { cond_cause = causes(0); } for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes double lik = 1; rowvec likdu = zeros<rowvec>(ncauses); if (cause < 0){ // Uncondtional double prob = F1(row, j, i, data); rowvec probdu = dF1du(row, j, i, data); lik -= prob; likdu -= probdu; } else { // Conditional double prob = F1(row, j, i, cond_cause, data, sigmaMargCond, u); rowvec probdu = dF1du(row, j, i, cond_cause, data, sigmaMargCond, u); lik -= prob; likdu -= probdu; } res += (1/lik)*likdu; } } } } /* Contribution from u */ if (full){ vmat sig = sigmaU; // Variance-covariance matrix etc. of u // Adding to the score rowvec res += -u.t()*sig.inv; }; return(res); } <|endoftext|>
<commit_before>/** * @file options.cc * @author Konrad Zemek * @copyright (C) 2014 ACK CYFRONET AGH * @copyright This software is released under the MIT license cited in 'LICENSE.txt' */ #include "options.h" #include "veilConfig.h" #include "veilErrors.h" #include "veilException.h" #include "veilfs.h" #include <boost/bind.hpp> #include <boost/foreach.hpp> #include <boost/program_options.hpp> #include <boost/filesystem.hpp> #include <boost/algorithm/string.hpp> #include <boost/xpressive/xpressive.hpp> #include <fuse/fuse_lowlevel.h> #include <iostream> #include <fstream> #include <string> #include <vector> #include <utility> using namespace boost::program_options; namespace veil { namespace client { Options::Options() : m_common("Common config file and environment options") , m_restricted("Global config file restricted options") , m_commandline("General options") , m_fuse("FUSE options") , m_hidden("Hidden commandline options") { setDescriptions(); } Options::~Options() { } void Options::setDescriptions() { // Common options found in environment, global and user config files add_cluster_hostname(m_common); add_cluster_port(m_common); add_peer_certificate_file(m_common); add_no_check_certificate(m_common); add_fuse_group_id(m_common); add_enable_attr_cache(m_common); add_attr_cache_expiration_time(m_common); add_log_dir(m_common); add_fuse_id(m_common); add_jobscheduler_threads(m_common); add_enable_dir_prefetch(m_common); add_enable_parallel_getattr(m_common); add_enable_location_cache(m_common); // Restricted options exclusive to global config file m_restricted.add_options() ("enable_env_option_override", value<bool>()->default_value(true)); add_cluster_ping_interval(m_restricted); add_alive_meta_connections_count(m_restricted); add_alive_data_connections_count(m_restricted); add_write_buffer_max_size(m_restricted); add_read_buffer_max_size(m_restricted); add_write_buffer_max_file_size(m_restricted); add_read_buffer_max_file_size(m_restricted); add_file_buffer_prefered_block_size(m_restricted); // General commandline options m_commandline.add_options() ("help,h", "print help") ("version,V", "print version") ("config", value<std::string>(), "path to user config file"); add_switch_debug(m_commandline); add_switch_debug_gsi(m_commandline); add_switch_no_check_certificate(m_commandline); // FUSE-specific commandline options m_fuse.add_options() (",o", value<std::vector<std::string> >()->value_name("opt,..."), "mount options") (",f", "foreground operation") (",s", "disable multi-threaded operation"); // Hidden commandline options (positional) m_hidden.add_options() ("mountpoint", value<std::string>(), "mount point"); } void Options::parseConfigs(const int argc, const char * const argv[]) { if(argc > 0) argv0 = argv[0]; try { parseCommandLine(argc, argv); } catch(boost::program_options::error &e) { LOG(ERROR) << "Error while parsing command line arguments: " << e.what(); throw VeilException(VEINVAL, e.what()); } variables_map fileConfigMap; try { parseUserConfig(fileConfigMap); } catch(boost::program_options::unknown_option &e) { LOG(ERROR) << "Error while parsing user configuration file: " << e.what(); if(m_restricted.find_nothrow(e.get_option_name(), false)) throw VeilException(VEINVAL, "restricted option '" + e.get_option_name() + "' found in user configuration file"); throw VeilException(VEINVAL, e.what()); } catch(boost::program_options::error &e) { LOG(ERROR) << "Error while parsing user configuration file: " << e.what(); throw VeilException(VEINVAL, e.what()); } try { parseGlobalConfig(fileConfigMap); } catch(boost::program_options::error &e) { LOG(ERROR) << "Error while parsing global configuration file: " << e.what(); throw VeilException(VEINVAL, e.what()); } // If override is allowed then we merge in environment variables first if(fileConfigMap.at("enable_env_option_override").as<bool>()) { parseEnv(); m_vm.insert(fileConfigMap.begin(), fileConfigMap.end()); } else { m_vm.insert(fileConfigMap.begin(), fileConfigMap.end()); parseEnv(); } notify(m_vm); } /** * Parses commandline-options with dashes as commandline_options with * underscores. * @param str The command line argument to parse. * @returns A pair of argument name and argument value parsed from the input * string. The argument name has dashes replaced with underscores. */ static std::pair<std::string, std::string> cmdParser(const std::string &str) { using namespace boost::xpressive; static const sregex rex = sregex::compile("\\s*--([\\w\\-]+)(=(\\S+))?\\s*"); smatch what; if(regex_match(str, what, rex)) return std::make_pair( boost::algorithm::replace_all_copy(what[1].str(), "-", "_"), what.size() > 2 ? what[3].str() : std::string()); return std::pair<std::string, std::string>(); } void Options::parseCommandLine(const int argc, const char * const argv[]) { positional_options_description pos; pos.add("mountpoint", 1); options_description all("Allowed options"); all.add(m_commandline).add(m_fuse).add(m_hidden); store(command_line_parser(argc, argv) .options(all).positional(pos).extra_parser(cmdParser).run(), m_vm); if(m_vm.count("help")) { options_description visible(""); visible.add(m_commandline).add(m_fuse); std::cout << "Usage: " << argv[0] << " [options] mountpoint" << std::endl; std::cout << visible; exit(EXIT_SUCCESS); } if(m_vm.count("version")) { std::cout << "VeilFuse version: " << VeilClient_VERSION_MAJOR << "." << VeilClient_VERSION_MINOR << "." << VeilClient_VERSION_PATCH << std::endl; std::cout << "FUSE library version: " << FUSE_MAJOR_VERSION << "." << FUSE_MINOR_VERSION << std::endl; exit(EXIT_SUCCESS); } } void Options::parseUserConfig(variables_map &fileConfigMap) { using namespace boost::filesystem; if(!m_vm.count("config")) return; const path userConfigPath = absolute(m_vm.at("config").as<std::string>()); std::ifstream userConfig(userConfigPath.c_str()); if(userConfig) LOG(INFO) << "Parsing user configuration file " << userConfigPath; else LOG(WARNING) << "Couldn't open user configuration file " << userConfigPath; store(parse_config_file(userConfig, m_common), fileConfigMap); } void Options::parseGlobalConfig(variables_map &fileConfigMap) { using namespace boost::filesystem; options_description global("Global configuration"); global.add(m_restricted).add(m_common); const path globalConfigPath = path(VeilClient_INSTALL_PATH) / VeilClient_CONFIG_DIR / GLOBAL_CONFIG_FILE; std::ifstream globalConfig(globalConfigPath.c_str()); if(globalConfig) LOG(INFO) << "Parsing global configuration file " << globalConfigPath; else LOG(WARNING) << "Couldn't open global configuration file " << globalConfigPath; store(parse_config_file(globalConfig, global), fileConfigMap); } std::string Options::mapEnvNames(std::string env) const { boost::algorithm::to_lower(env); if(m_common.find_nothrow(env, false) && m_vm.count(env) == 0) { LOG(INFO) << "Using environment configuration variable " << env; return env; } return std::string(); } void Options::parseEnv() { LOG(INFO) << "Parsing environment variables"; store(parse_environment(m_common, boost::bind(&Options::mapEnvNames, this, _1)), m_vm); } struct fuse_args Options::getFuseArgs() const { struct fuse_args args = FUSE_ARGS_INIT(0, 0); fuse_opt_add_arg(&args, argv0.c_str()); fuse_opt_add_arg(&args, "-obig_writes"); if(m_vm.count("-d")) fuse_opt_add_arg(&args, "-d"); if(m_vm.count("-f")) fuse_opt_add_arg(&args, "-f"); if(m_vm.count("-s")) fuse_opt_add_arg(&args, "-s"); if(m_vm.count("-o")) { BOOST_FOREACH(const std::string &opt, m_vm.at("-o").as<std::vector<std::string> >()) fuse_opt_add_arg(&args, ("-o" + opt).c_str()); } if(m_vm.count("mountpoint")) fuse_opt_add_arg(&args, m_vm.at("mountpoint").as<std::string>().c_str()); return args; } } } <commit_msg>Check for "debug" insted of "-d" when passing parameters to FUSE.<commit_after>/** * @file options.cc * @author Konrad Zemek * @copyright (C) 2014 ACK CYFRONET AGH * @copyright This software is released under the MIT license cited in 'LICENSE.txt' */ #include "options.h" #include "veilConfig.h" #include "veilErrors.h" #include "veilException.h" #include "veilfs.h" #include <boost/bind.hpp> #include <boost/foreach.hpp> #include <boost/program_options.hpp> #include <boost/filesystem.hpp> #include <boost/algorithm/string.hpp> #include <boost/xpressive/xpressive.hpp> #include <fuse/fuse_lowlevel.h> #include <iostream> #include <fstream> #include <string> #include <vector> #include <utility> using namespace boost::program_options; namespace veil { namespace client { Options::Options() : m_common("Common config file and environment options") , m_restricted("Global config file restricted options") , m_commandline("General options") , m_fuse("FUSE options") , m_hidden("Hidden commandline options") { setDescriptions(); } Options::~Options() { } void Options::setDescriptions() { // Common options found in environment, global and user config files add_cluster_hostname(m_common); add_cluster_port(m_common); add_peer_certificate_file(m_common); add_no_check_certificate(m_common); add_fuse_group_id(m_common); add_enable_attr_cache(m_common); add_attr_cache_expiration_time(m_common); add_log_dir(m_common); add_fuse_id(m_common); add_jobscheduler_threads(m_common); add_enable_dir_prefetch(m_common); add_enable_parallel_getattr(m_common); add_enable_location_cache(m_common); // Restricted options exclusive to global config file m_restricted.add_options() ("enable_env_option_override", value<bool>()->default_value(true)); add_cluster_ping_interval(m_restricted); add_alive_meta_connections_count(m_restricted); add_alive_data_connections_count(m_restricted); add_write_buffer_max_size(m_restricted); add_read_buffer_max_size(m_restricted); add_write_buffer_max_file_size(m_restricted); add_read_buffer_max_file_size(m_restricted); add_file_buffer_prefered_block_size(m_restricted); // General commandline options m_commandline.add_options() ("help,h", "print help") ("version,V", "print version") ("config", value<std::string>(), "path to user config file"); add_switch_debug(m_commandline); add_switch_debug_gsi(m_commandline); add_switch_no_check_certificate(m_commandline); // FUSE-specific commandline options m_fuse.add_options() (",o", value<std::vector<std::string> >()->value_name("opt,..."), "mount options") (",f", "foreground operation") (",s", "disable multi-threaded operation"); // Hidden commandline options (positional) m_hidden.add_options() ("mountpoint", value<std::string>(), "mount point"); } void Options::parseConfigs(const int argc, const char * const argv[]) { if(argc > 0) argv0 = argv[0]; try { parseCommandLine(argc, argv); } catch(boost::program_options::error &e) { LOG(ERROR) << "Error while parsing command line arguments: " << e.what(); throw VeilException(VEINVAL, e.what()); } variables_map fileConfigMap; try { parseUserConfig(fileConfigMap); } catch(boost::program_options::unknown_option &e) { LOG(ERROR) << "Error while parsing user configuration file: " << e.what(); if(m_restricted.find_nothrow(e.get_option_name(), false)) throw VeilException(VEINVAL, "restricted option '" + e.get_option_name() + "' found in user configuration file"); throw VeilException(VEINVAL, e.what()); } catch(boost::program_options::error &e) { LOG(ERROR) << "Error while parsing user configuration file: " << e.what(); throw VeilException(VEINVAL, e.what()); } try { parseGlobalConfig(fileConfigMap); } catch(boost::program_options::error &e) { LOG(ERROR) << "Error while parsing global configuration file: " << e.what(); throw VeilException(VEINVAL, e.what()); } // If override is allowed then we merge in environment variables first if(fileConfigMap.at("enable_env_option_override").as<bool>()) { parseEnv(); m_vm.insert(fileConfigMap.begin(), fileConfigMap.end()); } else { m_vm.insert(fileConfigMap.begin(), fileConfigMap.end()); parseEnv(); } notify(m_vm); } /** * Parses commandline-options with dashes as commandline_options with * underscores. * @param str The command line argument to parse. * @returns A pair of argument name and argument value parsed from the input * string. The argument name has dashes replaced with underscores. */ static std::pair<std::string, std::string> cmdParser(const std::string &str) { using namespace boost::xpressive; static const sregex rex = sregex::compile("\\s*--([\\w\\-]+)(=(\\S+))?\\s*"); smatch what; if(regex_match(str, what, rex)) return std::make_pair( boost::algorithm::replace_all_copy(what[1].str(), "-", "_"), what.size() > 2 ? what[3].str() : std::string()); return std::pair<std::string, std::string>(); } void Options::parseCommandLine(const int argc, const char * const argv[]) { positional_options_description pos; pos.add("mountpoint", 1); options_description all("Allowed options"); all.add(m_commandline).add(m_fuse).add(m_hidden); store(command_line_parser(argc, argv) .options(all).positional(pos).extra_parser(cmdParser).run(), m_vm); if(m_vm.count("help")) { options_description visible(""); visible.add(m_commandline).add(m_fuse); std::cout << "Usage: " << argv[0] << " [options] mountpoint" << std::endl; std::cout << visible; exit(EXIT_SUCCESS); } if(m_vm.count("version")) { std::cout << "VeilFuse version: " << VeilClient_VERSION_MAJOR << "." << VeilClient_VERSION_MINOR << "." << VeilClient_VERSION_PATCH << std::endl; std::cout << "FUSE library version: " << FUSE_MAJOR_VERSION << "." << FUSE_MINOR_VERSION << std::endl; exit(EXIT_SUCCESS); } } void Options::parseUserConfig(variables_map &fileConfigMap) { using namespace boost::filesystem; if(!m_vm.count("config")) return; const path userConfigPath = absolute(m_vm.at("config").as<std::string>()); std::ifstream userConfig(userConfigPath.c_str()); if(userConfig) LOG(INFO) << "Parsing user configuration file " << userConfigPath; else LOG(WARNING) << "Couldn't open user configuration file " << userConfigPath; store(parse_config_file(userConfig, m_common), fileConfigMap); } void Options::parseGlobalConfig(variables_map &fileConfigMap) { using namespace boost::filesystem; options_description global("Global configuration"); global.add(m_restricted).add(m_common); const path globalConfigPath = path(VeilClient_INSTALL_PATH) / VeilClient_CONFIG_DIR / GLOBAL_CONFIG_FILE; std::ifstream globalConfig(globalConfigPath.c_str()); if(globalConfig) LOG(INFO) << "Parsing global configuration file " << globalConfigPath; else LOG(WARNING) << "Couldn't open global configuration file " << globalConfigPath; store(parse_config_file(globalConfig, global), fileConfigMap); } std::string Options::mapEnvNames(std::string env) const { boost::algorithm::to_lower(env); if(m_common.find_nothrow(env, false) && m_vm.count(env) == 0) { LOG(INFO) << "Using environment configuration variable " << env; return env; } return std::string(); } void Options::parseEnv() { LOG(INFO) << "Parsing environment variables"; store(parse_environment(m_common, boost::bind(&Options::mapEnvNames, this, _1)), m_vm); } struct fuse_args Options::getFuseArgs() const { struct fuse_args args = FUSE_ARGS_INIT(0, 0); fuse_opt_add_arg(&args, argv0.c_str()); fuse_opt_add_arg(&args, "-obig_writes"); if(m_vm.count("debug")) fuse_opt_add_arg(&args, "-d"); if(m_vm.count("-f")) fuse_opt_add_arg(&args, "-f"); if(m_vm.count("-s")) fuse_opt_add_arg(&args, "-s"); if(m_vm.count("-o")) { BOOST_FOREACH(const std::string &opt, m_vm.at("-o").as<std::vector<std::string> >()) fuse_opt_add_arg(&args, ("-o" + opt).c_str()); } if(m_vm.count("mountpoint")) fuse_opt_add_arg(&args, m_vm.at("mountpoint").as<std::string>().c_str()); return args; } } } <|endoftext|>
<commit_before>#include "GLFWController.hpp" #include "ModelView.hpp" #include "AffinePoint.hpp" #include "AffineVector.hpp" #include "ModelViewWithShader.hpp" #include "Block.hpp" #include "DependencyContainer.hpp" #include "otuchaConfig.h" #include "Matrix3x3.hpp" #include "TextureAtlas.hpp" #include "TextureFont.hpp" #include "vec.hpp" #include "VertexBuffer.hpp" #include <memory> #include <iostream> using namespace otucha; void set3DViewingInformation(std::shared_ptr<terasca::ModelView> modelView, double xyz[6]) { modelView->setMCRegionOfInterest(xyz); rffalcon::AffinePoint eye(1.0, 1.0, 1.0); rffalcon::AffinePoint center(0, 0, 0); rffalcon::AffineVector up(0, 1, 0); modelView->setEyeCenterUp(eye, center, up); double zpp = -1.0; double zmin = -99.0; double zmax = -0.01; modelView->setZProjectionPlane(zpp); modelView->setEyeCoordinatesZMinZMax(zmin, zmax); } typedef struct { float x, y, z; float s, t; float r, g, b, a; } Vertex; void addText(std::shared_ptr<rffalcon::VertexBuffer> buffer, std::shared_ptr<rffalcon::TextureFont> font, const std::wstring &text, rffalcon::vec2 pen, const rffalcon::vec4 color) { int textLength = text.length(); for (int index = 0; index < textLength; ++index) { std::shared_ptr<rffalcon::TextureGlyph> glyph = font->getGlyph(text[index]); if (glyph != nullptr) { auto glyph1 = *glyph; float kerning = 0.0f; if (index > 0) { kerning = glyph->getKerning(text[index]); } pen.x += kerning; int x0 = static_cast<int>(pen.x + glyph->offsetX); int y0 = static_cast<int>(pen.y + glyph->offsetY); int x1 = static_cast<int>(x0 + glyph->width); int y1 = static_cast<int>(y0 - glyph->height); GLuint i[6] = { 0, 1, 2, 0, 2, 3 }; std::shared_ptr<std::vector<GLuint>> indices = std::make_shared<std::vector<GLuint>>(i, i+6); Vertex v[4] = { { static_cast<float>(x0), static_cast<float>(y0), 0.0f, glyph->s0, glyph->t0, color.r, color.g, color.b, color.a }, { static_cast<float>(x0), static_cast<float>(y1), 0.0f, glyph->s0, glyph->t1, color.r, color.g, color.b, color.a }, { static_cast<float>(x1), static_cast<float>(y1), 0.0f, glyph->s1, glyph->t1, color.r, color.g, color.b, color.a }, { static_cast<float>(x1), static_cast<float>(y0), 0.0f, glyph->s1, glyph->t0, color.r, color.g, color.b, color.a } }; std::shared_ptr<std::vector<void*>> vertices = std::make_shared<std::vector<void*>>(); vertices->push_back(&v[0]); vertices->push_back(&v[1]); vertices->push_back(&v[2]); vertices->push_back(&v[3]); buffer->push(vertices, indices); pen.x += glyph->advanceX; } } } std::shared_ptr<rffalcon::VertexBuffer> testText(const std::string &appDir) { std::shared_ptr<rffalcon::TextureAtlas> atlas = std::make_shared<rffalcon::TextureAtlas>(512, 512, 3); rffalcon::vec2 pen = { { 5, 5 } }; rffalcon::vec4 black = { { 0, 0, 0, 1 } }; std::shared_ptr<rffalcon::TextureFont> font = std::make_shared<rffalcon::TextureFont>(atlas, 32.0f, appDir + "DejaVuSansMono.ttf"); pen.x = 5; std::wstring text = L"#WORKSINMAIN"; font->loadGlyphs(text); std::shared_ptr<rffalcon::VertexBuffer> buffer = std::make_shared<rffalcon::VertexBuffer>("vertex:3f,texCoord:2f,color:4f"); addText(buffer, font, text, pen, black); glBindTexture(GL_TEXTURE_2D, atlas->getGLTextureId()); return buffer; } int main(int argc, char* argv[]) { // these two lines included for Emscripten which is excluding the constructors otherwise :( rffalcon::Matrix4x4 matrix; rffalcon::Matrix3x3 matrix2; fprintf(stdout, "%s Version %d.%d\n", argv[0], otucha_VERSION_MAJOR, otucha_VERSION_MINOR); terasca::GLFWController c("otucha", terasca::Controller::DEPTH); c.reportVersions(std::cout); std::string appPath(argv[0]); DependencyContainer::getSingleton()->setAppDir(appPath); std::string appDir = DependencyContainer::getSingleton()->getAppDir(); glClearColor(1.0f, 1.0f, 1.0f, 1.0f); double xyz[6]; // Block model std::shared_ptr<terasca::ModelView> blockModelView = std::make_shared<terasca::ModelViewWithShader>(appDir + "simple.vsh", appDir + "simple.fsh"); std::shared_ptr<rffalcon::ModelBase> blockModel = std::make_shared<rffalcon::Block>(-0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f); blockModelView->addModel(blockModel); blockModelView->getMCBoundingBox(xyz); set3DViewingInformation(blockModelView, xyz); // Text model std::shared_ptr<rffalcon::VertexBuffer> textModel = testText(appDir); std::shared_ptr<terasca::ModelView> textModelView = std::make_shared<terasca::ModelViewWithShader>(appDir + "v3f-t2f-c4f.vsh", appDir + "v3f-t2f-c4f.fsh"); textModelView->addModel(textModel); textModelView->setProjectionType(ORTHOGRAPHIC); textModelView->getMCBoundingBox(xyz); set3DViewingInformation(textModelView, xyz); // add models to view, order matters c.addModelView(textModelView); c.addModelView(blockModelView); // test console code to be removed later DependencyContainer::getSingleton()->getConsole()->registerCommand(L"test", [](warbler::t_consoleArgs_ptr args) { std::cout << "Console online" << std::endl; }, std::make_shared<warbler::t_consoleArgTypes>()); DependencyContainer::getSingleton()->getConsole()->executeCommand(L"test"); // end test console code c.run(); return 0; } <commit_msg>struct Vertex<commit_after>#include "GLFWController.hpp" #include "ModelView.hpp" #include "AffinePoint.hpp" #include "AffineVector.hpp" #include "ModelViewWithShader.hpp" #include "Block.hpp" #include "DependencyContainer.hpp" #include "otuchaConfig.h" #include "Matrix3x3.hpp" #include "TextureAtlas.hpp" #include "TextureFont.hpp" #include "vec.hpp" #include "VertexBuffer.hpp" #include <memory> #include <iostream> using namespace otucha; void set3DViewingInformation(std::shared_ptr<terasca::ModelView> modelView, double xyz[6]) { modelView->setMCRegionOfInterest(xyz); rffalcon::AffinePoint eye(1.0, 1.0, 1.0); rffalcon::AffinePoint center(0, 0, 0); rffalcon::AffineVector up(0, 1, 0); modelView->setEyeCenterUp(eye, center, up); double zpp = -1.0; double zmin = -99.0; double zmax = -0.01; modelView->setZProjectionPlane(zpp); modelView->setEyeCoordinatesZMinZMax(zmin, zmax); } struct Vertex { float x, y, z; float s, t; float r, g, b, a; }; void addText(std::shared_ptr<rffalcon::VertexBuffer> buffer, std::shared_ptr<rffalcon::TextureFont> font, const std::wstring &text, rffalcon::vec2 pen, const rffalcon::vec4 color) { int textLength = text.length(); for (int index = 0; index < textLength; ++index) { std::shared_ptr<rffalcon::TextureGlyph> glyph = font->getGlyph(text[index]); if (glyph != nullptr) { auto glyph1 = *glyph; float kerning = 0.0f; if (index > 0) { kerning = glyph->getKerning(text[index]); } pen.x += kerning; int x0 = static_cast<int>(pen.x + glyph->offsetX); int y0 = static_cast<int>(pen.y + glyph->offsetY); int x1 = static_cast<int>(x0 + glyph->width); int y1 = static_cast<int>(y0 - glyph->height); GLuint i[6] = { 0, 1, 2, 0, 2, 3 }; std::shared_ptr<std::vector<GLuint>> indices = std::make_shared<std::vector<GLuint>>(i, i+6); Vertex v[4] = { { static_cast<float>(x0), static_cast<float>(y0), 0.0f, glyph->s0, glyph->t0, color.r, color.g, color.b, color.a }, { static_cast<float>(x0), static_cast<float>(y1), 0.0f, glyph->s0, glyph->t1, color.r, color.g, color.b, color.a }, { static_cast<float>(x1), static_cast<float>(y1), 0.0f, glyph->s1, glyph->t1, color.r, color.g, color.b, color.a }, { static_cast<float>(x1), static_cast<float>(y0), 0.0f, glyph->s1, glyph->t0, color.r, color.g, color.b, color.a } }; std::shared_ptr<std::vector<void*>> vertices = std::make_shared<std::vector<void*>>(); vertices->push_back(&v[0]); vertices->push_back(&v[1]); vertices->push_back(&v[2]); vertices->push_back(&v[3]); buffer->push(vertices, indices); pen.x += glyph->advanceX; } } } std::shared_ptr<rffalcon::VertexBuffer> testText(const std::string &appDir) { std::shared_ptr<rffalcon::TextureAtlas> atlas = std::make_shared<rffalcon::TextureAtlas>(512, 512, 3); rffalcon::vec2 pen = { { 5, 5 } }; rffalcon::vec4 black = { { 0, 0, 0, 1 } }; std::shared_ptr<rffalcon::TextureFont> font = std::make_shared<rffalcon::TextureFont>(atlas, 32.0f, appDir + "DejaVuSansMono.ttf"); pen.x = 5; std::wstring text = L"#WORKSINMAIN"; font->loadGlyphs(text); std::shared_ptr<rffalcon::VertexBuffer> buffer = std::make_shared<rffalcon::VertexBuffer>("vertex:3f,texCoord:2f,color:4f"); addText(buffer, font, text, pen, black); glBindTexture(GL_TEXTURE_2D, atlas->getGLTextureId()); return buffer; } int main(int argc, char* argv[]) { // these two lines included for Emscripten which is excluding the constructors otherwise :( rffalcon::Matrix4x4 matrix; rffalcon::Matrix3x3 matrix2; fprintf(stdout, "%s Version %d.%d\n", argv[0], otucha_VERSION_MAJOR, otucha_VERSION_MINOR); terasca::GLFWController c("otucha", terasca::Controller::DEPTH); c.reportVersions(std::cout); std::string appPath(argv[0]); DependencyContainer::getSingleton()->setAppDir(appPath); std::string appDir = DependencyContainer::getSingleton()->getAppDir(); glClearColor(1.0f, 1.0f, 1.0f, 1.0f); double xyz[6]; // Block model std::shared_ptr<terasca::ModelView> blockModelView = std::make_shared<terasca::ModelViewWithShader>(appDir + "simple.vsh", appDir + "simple.fsh"); std::shared_ptr<rffalcon::ModelBase> blockModel = std::make_shared<rffalcon::Block>(-0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f); blockModelView->addModel(blockModel); blockModelView->getMCBoundingBox(xyz); set3DViewingInformation(blockModelView, xyz); // Text model std::shared_ptr<rffalcon::VertexBuffer> textModel = testText(appDir); std::shared_ptr<terasca::ModelView> textModelView = std::make_shared<terasca::ModelViewWithShader>(appDir + "v3f-t2f-c4f.vsh", appDir + "v3f-t2f-c4f.fsh"); textModelView->addModel(textModel); textModelView->setProjectionType(ORTHOGRAPHIC); textModelView->getMCBoundingBox(xyz); set3DViewingInformation(textModelView, xyz); // add models to view, order matters c.addModelView(textModelView); c.addModelView(blockModelView); // test console code to be removed later DependencyContainer::getSingleton()->getConsole()->registerCommand(L"test", [](warbler::t_consoleArgs_ptr args) { std::cout << "Console online" << std::endl; }, std::make_shared<warbler::t_consoleArgTypes>()); DependencyContainer::getSingleton()->getConsole()->executeCommand(L"test"); // end test console code c.run(); return 0; } <|endoftext|>
<commit_before>#include "output.h" #include "buffer_pool.h" #include "compress.h" #include "cso.h" namespace maxcso { // TODO: Tune, less may be better. static const size_t QUEUE_SIZE = 128; Output::Output(uv_loop_t *loop, const Task &task) : loop_(loop), flags_(task.flags), state_(STATE_INIT), srcSize_(-1), index_(nullptr) { for (size_t i = 0; i < QUEUE_SIZE; ++i) { freeSectors_.push_back(new Sector(task.flags)); } } Output::~Output() { for (Sector *sector : freeSectors_) { delete sector; } for (auto pair : pendingSectors_) { delete pair.second; } freeSectors_.clear(); pendingSectors_.clear(); delete [] index_; index_ = nullptr; } void Output::SetFile(uv_file file, int64_t srcSize) { file_ = file; srcSize_ = srcSize; srcPos_ = 0; const uint32_t sectors = static_cast<uint32_t>(srcSize >> SECTOR_SHIFT); // Start after the header and index, which we'll fill in later. index_ = new uint32_t[sectors + 1]; // Start after the end of the index data and header. dstPos_ = sizeof(CSOHeader) + (sectors + 1) * sizeof(uint32_t); // TODO: We might be able to optimize shift better by running through the data. // That would require either a second pass or keeping the entire result in RAM. // For now, just take worst case (all blocks stored uncompressed.) int64_t worstSize = dstPos_ + srcSize; shift_ = 0; for (int i = 62; i >= 31; --i) { int64_t max = 1LL << i; if (worstSize >= max) { // This means we need i + 1 bits to store the position. // We have to shift enough off to fit into 31. shift_ = i + 1 - 31; break; } } // If the shift is above 11, the padding could make it need more space. // But that would be > 4 TB anyway, so let's not worry about it. align_ = 1 << shift_; Align(dstPos_); state_ |= STATE_HAS_FILE; } int32_t Output::Align(int64_t &pos) { uint32_t off = static_cast<uint32_t>(pos % align_); if (off != 0) { pos += align_ - off; return align_ - off; } return 0; } void Output::Enqueue(int64_t pos, uint8_t *buffer) { Sector *sector = freeSectors_.back(); freeSectors_.pop_back(); // We might not compress all blocks. const bool tryCompress = ShouldCompress(pos); // Sector takes ownership of buffer either way. if (tryCompress) { sector->Process(loop_, pos, buffer, [this, sector](bool status, const char *reason) { HandleReadySector(sector); }); } else { sector->Reserve(pos, buffer); HandleReadySector(sector); } } void Output::HandleReadySector(Sector *sector) { if (sector != nullptr) { if (srcPos_ != sector->Pos()) { // We're not there yet in the file stream. Queue this, get to it later. pendingSectors_[sector->Pos()] = sector; return; } } else { // If no sector was provided, we're looking at the first in the queue. if (pendingSectors_.empty()) { return; } sector = pendingSectors_.begin()->second; if (srcPos_ != sector->Pos()) { return; } // Remove it from the queue, and then run with it. pendingSectors_.erase(pendingSectors_.begin()); } // Check for any sectors that immediately follow the one we're writing. // We'll just write them all together. std::vector<Sector *> sectors; sectors.push_back(sector); // TODO: Try other numbers. static const size_t MAX_BUFS = 4; int64_t nextPos = srcPos_ + SECTOR_SIZE; auto it = pendingSectors_.find(nextPos); while (it != pendingSectors_.end()) { sectors.push_back(it->second); pendingSectors_.erase(it); nextPos += SECTOR_SIZE; it = pendingSectors_.find(nextPos); // Don't do more than 4 at a time. if (sectors.size() >= MAX_BUFS) { break; } } int64_t dstPos = dstPos_; uv_buf_t bufs[MAX_BUFS * 2]; unsigned int nbufs = 0; static char padding[2048] = {0}; for (size_t i = 0; i < sectors.size(); ++i) { bufs[nbufs++] = uv_buf_init(reinterpret_cast<char *>(sectors[i]->BestBuffer()), sectors[i]->BestSize()); // Update the index. const int32_t s = static_cast<int32_t>(sectors[i]->Pos() >> SECTOR_SHIFT); index_[s] = static_cast<int32_t>(dstPos >> shift_); if (!sectors[i]->Compressed()) { index_[s] |= CSO_INDEX_UNCOMPRESSED; } dstPos += sectors[i]->BestSize(); int32_t padSize = Align(dstPos); if (padSize != 0) { // We need uv to write the padding out as well. bufs[nbufs++] = uv_buf_init(padding, padSize); } } // If we're working on the last sectors, then the index is ready to write. if (nextPos == srcSize_) { state_ |= STATE_INDEX_READY; Flush(); } const int64_t totalWrite = dstPos - dstPos_; uv_.fs_write(loop_, sector->WriteReq(), file_, bufs, nbufs, dstPos_, [this, sectors, nextPos, totalWrite](uv_fs_t *req) { for (Sector *sector : sectors) { sector->Release(); freeSectors_.push_back(sector); } if (req->result != totalWrite) { finish_(false, "Data could not be written to output file"); uv_fs_req_cleanup(req); return; } uv_fs_req_cleanup(req); srcPos_ = nextPos; dstPos_ += totalWrite; // TODO: Better (including index?) float prog = static_cast<float>(srcPos_) / static_cast<float>(srcSize_); progress_(prog); if (nextPos == srcSize_) { state_ |= STATE_DATA_WRITTEN; CheckFinish(); } else { // Check if there's more data to write out. HandleReadySector(nullptr); } }); } bool Output::ShouldCompress(int64_t pos) { if (flags_ & TASKFLAG_FORCE_ALL) { return true; } // TODO return true; } bool Output::QueueFull() { return freeSectors_.empty(); } void Output::OnProgress(OutputCallback callback) { progress_ = callback; } void Output::OnFinish(OutputFinishCallback callback) { finish_ = callback; } void Output::Flush() { if (!(state_ & STATE_INDEX_READY)) { finish_(false, "Flush called before index finalized"); return; } CSOHeader *header = new CSOHeader; memcpy(header->magic, CSO_MAGIC, sizeof(header->magic)); header->header_size = sizeof(CSOHeader); header->uncompressed_size = srcSize_; header->sector_size = SECTOR_SIZE; header->version = 1; header->index_shift = shift_; header->unused[0] = 0; header->unused[1] = 0; const uint32_t sectors = static_cast<uint32_t>(srcSize_ >> SECTOR_SHIFT); uv_buf_t bufs[2]; bufs[0] = uv_buf_init(reinterpret_cast<char *>(header), sizeof(CSOHeader)); bufs[1] = uv_buf_init(reinterpret_cast<char *>(index_), (sectors + 1) * sizeof(uint32_t)); const size_t totalBytes = sizeof(CSOHeader) + (sectors + 1) * sizeof(uint32_t); uv_.fs_write(loop_, &flush_, file_, bufs, 2, 0, [this, header, totalBytes](uv_fs_t *req) { if (req->result != totalBytes) { finish_(false, "Unable to write header data"); } else { state_ |= STATE_INDEX_WRITTEN; CheckFinish(); } uv_fs_req_cleanup(req); delete header; }); } void Output::CheckFinish() { if ((state_ & STATE_INDEX_WRITTEN) && (state_ & STATE_DATA_WRITTEN)) { finish_(true, nullptr); } } }; <commit_msg>Write the correct final index entry.<commit_after>#include "output.h" #include "buffer_pool.h" #include "compress.h" #include "cso.h" namespace maxcso { // TODO: Tune, less may be better. static const size_t QUEUE_SIZE = 128; Output::Output(uv_loop_t *loop, const Task &task) : loop_(loop), flags_(task.flags), state_(STATE_INIT), srcSize_(-1), index_(nullptr) { for (size_t i = 0; i < QUEUE_SIZE; ++i) { freeSectors_.push_back(new Sector(task.flags)); } } Output::~Output() { for (Sector *sector : freeSectors_) { delete sector; } for (auto pair : pendingSectors_) { delete pair.second; } freeSectors_.clear(); pendingSectors_.clear(); delete [] index_; index_ = nullptr; } void Output::SetFile(uv_file file, int64_t srcSize) { file_ = file; srcSize_ = srcSize; srcPos_ = 0; const uint32_t sectors = static_cast<uint32_t>(srcSize >> SECTOR_SHIFT); // Start after the header and index, which we'll fill in later. index_ = new uint32_t[sectors + 1]; // Start after the end of the index data and header. dstPos_ = sizeof(CSOHeader) + (sectors + 1) * sizeof(uint32_t); // TODO: We might be able to optimize shift better by running through the data. // That would require either a second pass or keeping the entire result in RAM. // For now, just take worst case (all blocks stored uncompressed.) int64_t worstSize = dstPos_ + srcSize; shift_ = 0; for (int i = 62; i >= 31; --i) { int64_t max = 1LL << i; if (worstSize >= max) { // This means we need i + 1 bits to store the position. // We have to shift enough off to fit into 31. shift_ = i + 1 - 31; break; } } // If the shift is above 11, the padding could make it need more space. // But that would be > 4 TB anyway, so let's not worry about it. align_ = 1 << shift_; Align(dstPos_); state_ |= STATE_HAS_FILE; } int32_t Output::Align(int64_t &pos) { uint32_t off = static_cast<uint32_t>(pos % align_); if (off != 0) { pos += align_ - off; return align_ - off; } return 0; } void Output::Enqueue(int64_t pos, uint8_t *buffer) { Sector *sector = freeSectors_.back(); freeSectors_.pop_back(); // We might not compress all blocks. const bool tryCompress = ShouldCompress(pos); // Sector takes ownership of buffer either way. if (tryCompress) { sector->Process(loop_, pos, buffer, [this, sector](bool status, const char *reason) { HandleReadySector(sector); }); } else { sector->Reserve(pos, buffer); HandleReadySector(sector); } } void Output::HandleReadySector(Sector *sector) { if (sector != nullptr) { if (srcPos_ != sector->Pos()) { // We're not there yet in the file stream. Queue this, get to it later. pendingSectors_[sector->Pos()] = sector; return; } } else { // If no sector was provided, we're looking at the first in the queue. if (pendingSectors_.empty()) { return; } sector = pendingSectors_.begin()->second; if (srcPos_ != sector->Pos()) { return; } // Remove it from the queue, and then run with it. pendingSectors_.erase(pendingSectors_.begin()); } // Check for any sectors that immediately follow the one we're writing. // We'll just write them all together. std::vector<Sector *> sectors; sectors.push_back(sector); // TODO: Try other numbers. static const size_t MAX_BUFS = 4; int64_t nextPos = srcPos_ + SECTOR_SIZE; auto it = pendingSectors_.find(nextPos); while (it != pendingSectors_.end()) { sectors.push_back(it->second); pendingSectors_.erase(it); nextPos += SECTOR_SIZE; it = pendingSectors_.find(nextPos); // Don't do more than 4 at a time. if (sectors.size() >= MAX_BUFS) { break; } } int64_t dstPos = dstPos_; uv_buf_t bufs[MAX_BUFS * 2]; unsigned int nbufs = 0; static char padding[2048] = {0}; for (size_t i = 0; i < sectors.size(); ++i) { bufs[nbufs++] = uv_buf_init(reinterpret_cast<char *>(sectors[i]->BestBuffer()), sectors[i]->BestSize()); // Update the index. const int32_t s = static_cast<int32_t>(sectors[i]->Pos() >> SECTOR_SHIFT); index_[s] = static_cast<int32_t>(dstPos >> shift_); if (!sectors[i]->Compressed()) { index_[s] |= CSO_INDEX_UNCOMPRESSED; } dstPos += sectors[i]->BestSize(); int32_t padSize = Align(dstPos); if (padSize != 0) { // We need uv to write the padding out as well. bufs[nbufs++] = uv_buf_init(padding, padSize); } } // If we're working on the last sectors, then the index is ready to write. if (nextPos == srcSize_) { // Update the final index entry. const int32_t s = static_cast<int32_t>(srcSize_ >> SECTOR_SHIFT); index_[s] = static_cast<int32_t>(dstPos >> shift_); state_ |= STATE_INDEX_READY; Flush(); } const int64_t totalWrite = dstPos - dstPos_; uv_.fs_write(loop_, sector->WriteReq(), file_, bufs, nbufs, dstPos_, [this, sectors, nextPos, totalWrite](uv_fs_t *req) { for (Sector *sector : sectors) { sector->Release(); freeSectors_.push_back(sector); } if (req->result != totalWrite) { finish_(false, "Data could not be written to output file"); uv_fs_req_cleanup(req); return; } uv_fs_req_cleanup(req); srcPos_ = nextPos; dstPos_ += totalWrite; // TODO: Better (including index?) float prog = static_cast<float>(srcPos_) / static_cast<float>(srcSize_); progress_(prog); if (nextPos == srcSize_) { state_ |= STATE_DATA_WRITTEN; CheckFinish(); } else { // Check if there's more data to write out. HandleReadySector(nullptr); } }); } bool Output::ShouldCompress(int64_t pos) { if (flags_ & TASKFLAG_FORCE_ALL) { return true; } // TODO return true; } bool Output::QueueFull() { return freeSectors_.empty(); } void Output::OnProgress(OutputCallback callback) { progress_ = callback; } void Output::OnFinish(OutputFinishCallback callback) { finish_ = callback; } void Output::Flush() { if (!(state_ & STATE_INDEX_READY)) { finish_(false, "Flush called before index finalized"); return; } CSOHeader *header = new CSOHeader; memcpy(header->magic, CSO_MAGIC, sizeof(header->magic)); header->header_size = sizeof(CSOHeader); header->uncompressed_size = srcSize_; header->sector_size = SECTOR_SIZE; header->version = 1; header->index_shift = shift_; header->unused[0] = 0; header->unused[1] = 0; const uint32_t sectors = static_cast<uint32_t>(srcSize_ >> SECTOR_SHIFT); uv_buf_t bufs[2]; bufs[0] = uv_buf_init(reinterpret_cast<char *>(header), sizeof(CSOHeader)); bufs[1] = uv_buf_init(reinterpret_cast<char *>(index_), (sectors + 1) * sizeof(uint32_t)); const size_t totalBytes = sizeof(CSOHeader) + (sectors + 1) * sizeof(uint32_t); uv_.fs_write(loop_, &flush_, file_, bufs, 2, 0, [this, header, totalBytes](uv_fs_t *req) { if (req->result != totalBytes) { finish_(false, "Unable to write header data"); } else { state_ |= STATE_INDEX_WRITTEN; CheckFinish(); } uv_fs_req_cleanup(req); delete header; }); } void Output::CheckFinish() { if ((state_ & STATE_INDEX_WRITTEN) && (state_ & STATE_DATA_WRITTEN)) { finish_(true, nullptr); } } }; <|endoftext|>
<commit_before>/* Copyright (c) 2009, Sebastien Mirolo 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 fortylines 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 Sebastien Mirolo ''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 Sebastien Mirolo BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "payment.hh" #include "todo.hh" #include "aws.hh" void awsPayment::fetch( session& s, const boost::filesystem::path& pathname ) { awsStandardButton button(s.valueOf("awsAccessKey"), s.valueOf("awsSecretKey"), s.valueOf("awsCertificate")); button.description = "Vote for a todo item with your dollars"; button.returnUrl = url(s.valueOf("domainName") + "/todoVoteSuccess"); button.build(todouuid(pathname),1); button.writehtml(std::cout); } <commit_msg>prefix domainName with http protocol<commit_after>/* Copyright (c) 2009, Sebastien Mirolo 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 fortylines 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 Sebastien Mirolo ''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 Sebastien Mirolo BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "payment.hh" #include "todo.hh" #include "aws.hh" void awsPayment::fetch( session& s, const boost::filesystem::path& pathname ) { awsStandardButton button(s.valueOf("awsAccessKey"), s.valueOf("awsSecretKey"), s.valueOf("awsCertificate")); button.description = "Vote for a todo item with your dollars"; button.returnUrl = url(std::string("http://") + s.valueOf("domainName") + "/todoVoteSuccess"); button.build(todouuid(pathname),1); button.writehtml(std::cout); } <|endoftext|>
<commit_before>#include "pb_conn.h" #include "pink_define.h" #include "worker_thread.h" #include "xdebug.h" #include <string> namespace pink { PbConn::PbConn(const int fd, const std::string &ip_port) : PinkConn(fd, ip_port), header_len_(-1), cur_pos_(0), rbuf_len_(0), connStatus_(kHeader), wbuf_len_(0), wbuf_pos_(0) { rbuf_ = (char *)malloc(sizeof(char) * PB_MAX_MESSAGE); wbuf_ = (char *)malloc(sizeof(char) * PB_MAX_MESSAGE); } PbConn::~PbConn() { free(rbuf_); free(wbuf_); } ReadStatus PbConn::GetRequest() { ssize_t nread = 0; nread = read(fd(), rbuf_ + rbuf_len_, PB_MAX_MESSAGE); if (nread == -1) { if (errno == EAGAIN) { return kReadHalf; } else { return kReadError; } } else if (nread == 0) { return kReadClose; } uint32_t integer = 0; bool flag = true; if (nread) { rbuf_len_ += nread; while (flag) { switch (connStatus_) { case kHeader: if (rbuf_len_ - cur_pos_ >= COMMAND_HEADER_LENGTH) { memcpy((char *)(&integer), rbuf_ + cur_pos_, sizeof(uint32_t)); header_len_ = ntohl(integer); log_info("Header_len %u", header_len_); connStatus_ = kPacket; cur_pos_ += COMMAND_HEADER_LENGTH; } else { flag = false; } break; case kPacket: if (rbuf_len_ >= header_len_ + COMMAND_HEADER_LENGTH) { cur_pos_ += header_len_; log_info("k Packet cur_pos_ %d rbuf_len_ %d", cur_pos_, rbuf_len_); connStatus_ = kComplete; } else { flag = false; } break; case kComplete: DealMessage(); connStatus_ = kHeader; log_info("%d %d", cur_pos_, rbuf_len_); if (cur_pos_ == rbuf_len_) { cur_pos_ = 0; rbuf_len_ = 0; } return kReadAll; /* * Add this switch case just for delete compile warning */ case kBuildObuf: break; case kWriteObuf: break; } } } return kReadHalf; } WriteStatus PbConn::SendReply() { BuildObuf(); ssize_t nwritten = 0; while (wbuf_len_ > 0) { nwritten = write(fd(), wbuf_ + wbuf_pos_, wbuf_len_ - wbuf_pos_); if (nwritten <= 0) { break; } wbuf_pos_ += nwritten; if (wbuf_pos_ == wbuf_len_) { wbuf_len_ = 0; wbuf_pos_ = 0; } } if (nwritten == -1) { if (errno == EAGAIN) { return kWriteHalf; } else { // Here we should close the connection return kWriteError; } } if (wbuf_len_ == 0) { return kWriteAll; } else { return kWriteHalf; } } Status PbConn::BuildObuf() { wbuf_len_ = res_->ByteSize(); res_->SerializeToArray(wbuf_ + 4, wbuf_len_); uint32_t u; u = htonl(wbuf_len_); memcpy(wbuf_, &u, sizeof(uint32_t)); wbuf_len_ += COMMAND_HEADER_LENGTH; return Status::OK(); } } <commit_msg>Revert "Fix bug of wbuf_pos without initialization"<commit_after>#include "pb_conn.h" #include "pink_define.h" #include "worker_thread.h" #include "xdebug.h" #include <string> namespace pink { PbConn::PbConn(const int fd, const std::string &ip_port) : PinkConn(fd, ip_port), header_len_(-1), cur_pos_(0), rbuf_len_(0), connStatus_(kHeader) { rbuf_ = (char *)malloc(sizeof(char) * PB_MAX_MESSAGE); wbuf_ = (char *)malloc(sizeof(char) * PB_MAX_MESSAGE); } PbConn::~PbConn() { free(rbuf_); free(wbuf_); } ReadStatus PbConn::GetRequest() { ssize_t nread = 0; nread = read(fd(), rbuf_ + rbuf_len_, PB_MAX_MESSAGE); if (nread == -1) { if (errno == EAGAIN) { return kReadHalf; } else { return kReadError; } } else if (nread == 0) { return kReadClose; } uint32_t integer = 0; bool flag = true; if (nread) { rbuf_len_ += nread; while (flag) { switch (connStatus_) { case kHeader: if (rbuf_len_ - cur_pos_ >= COMMAND_HEADER_LENGTH) { memcpy((char *)(&integer), rbuf_ + cur_pos_, sizeof(uint32_t)); header_len_ = ntohl(integer); log_info("Header_len %u", header_len_); connStatus_ = kPacket; cur_pos_ += COMMAND_HEADER_LENGTH; } else { flag = false; } break; case kPacket: if (rbuf_len_ >= header_len_ + COMMAND_HEADER_LENGTH) { cur_pos_ += header_len_; log_info("k Packet cur_pos_ %d rbuf_len_ %d", cur_pos_, rbuf_len_); connStatus_ = kComplete; } else { flag = false; } break; case kComplete: DealMessage(); connStatus_ = kHeader; log_info("%d %d", cur_pos_, rbuf_len_); if (cur_pos_ == rbuf_len_) { cur_pos_ = 0; rbuf_len_ = 0; } return kReadAll; /* * Add this switch case just for delete compile warning */ case kBuildObuf: break; case kWriteObuf: break; } } } return kReadHalf; } WriteStatus PbConn::SendReply() { BuildObuf(); ssize_t nwritten = 0; while (wbuf_len_ > 0) { nwritten = write(fd(), wbuf_ + wbuf_pos_, wbuf_len_ - wbuf_pos_); if (nwritten <= 0) { break; } wbuf_pos_ += nwritten; if (wbuf_pos_ == wbuf_len_) { wbuf_len_ = 0; wbuf_pos_ = 0; } } if (nwritten == -1) { if (errno == EAGAIN) { return kWriteHalf; } else { // Here we should close the connection return kWriteError; } } if (wbuf_len_ == 0) { return kWriteAll; } else { return kWriteHalf; } } Status PbConn::BuildObuf() { wbuf_len_ = res_->ByteSize(); res_->SerializeToArray(wbuf_ + 4, wbuf_len_); uint32_t u; u = htonl(wbuf_len_); memcpy(wbuf_, &u, sizeof(uint32_t)); wbuf_len_ += COMMAND_HEADER_LENGTH; return Status::OK(); } } <|endoftext|>
<commit_before>#include "pbview.h" #include <cinttypes> #include <cstdio> #include <cstring> #include <ncurses.h> #include <iostream> #include <sstream> #include "config.h" #include "configcontainer.h" #include "dllist.h" #include "download.h" #include "fmtstrformatter.h" #include "help.h" #include "listformatter.h" #include "logger.h" #include "pbcontroller.h" #include "strprintf.h" #include "utils.h" using namespace newsboat; namespace podboat { PbView::PbView(PbController* c) : update_view(true) , ctrl(c) , dllist_form(dllist_str) , help_form(help_str) , keys(0) , colorman(ctrl->get_colormanager()) , downloads_list("dls", dllist_form, ctrl->get_cfgcont()->get_configvalue_as_int("scrolloff")) , help_textview("helptext", help_form) { if (getenv("ESCDELAY") == nullptr) { set_escdelay(25); } } PbView::~PbView() { Stfl::reset(); } void PbView::run(bool auto_download, bool wrap_scroll) { bool quit = false; // Make sure curses is initialized dllist_form.run(-3); // Hide cursor using curses curs_set(0); set_dllist_keymap_hint(); do { if (update_view) { const double total_kbps = ctrl->get_total_kbps(); const auto speed = get_speed_human_readable(total_kbps); auto title = strprintf::fmt( _("Queue (%u downloads in progress, %u total) - %.2f %s total"), static_cast<unsigned int>(ctrl->downloads_in_progress()), static_cast<unsigned int>(ctrl->downloads().size()), speed.first, speed.second); if (ctrl->get_maxdownloads() > 1) { title += strprintf::fmt(_(" - %u parallel downloads"), ctrl->get_maxdownloads()); } dllist_form.set("head", title); LOG(Level::DEBUG, "PbView::run: updating view... " "downloads().size() " "= %" PRIu64, static_cast<uint64_t>(ctrl->downloads().size())); ListFormatter listfmt; const std::string line_format = ctrl->get_cfgcont()->get_configvalue("podlist-format"); dllist_form.run(-3); // compute all widget dimensions const unsigned int width = downloads_list.get_width(); unsigned int i = 0; for (const auto& dl : ctrl->downloads()) { auto lbuf = format_line(line_format, dl, i, width); listfmt.add_line(lbuf); i++; } downloads_list.stfl_replace_lines(listfmt); // If there's no status message, we know there's no error to show // Thus, it's safe to replace with the download's status if (i >= 1 && dllist_form.get("msg").empty()) { const auto idx = downloads_list.get_position(); dllist_form.set("msg", ctrl->downloads()[idx].status_msg()); } update_view = false; } const char* event = dllist_form.run(500); if (auto_download) { if (ctrl->get_maxdownloads() > ctrl->downloads_in_progress()) { ctrl->start_downloads(); } } if (!event || strcmp(event, "TIMEOUT") == 0) { continue; } if (strcmp(event, "RESIZE") == 0) { handle_resize(); continue; } Operation op = keys->get_operation(event, "podboat"); if (dllist_form.get("msg").length() > 0) { dllist_form.set("msg", ""); update_view = true; } switch (op) { case OP_REDRAW: Stfl::reset(); break; case OP_PREV: case OP_SK_UP: downloads_list.move_up(wrap_scroll); update_view = true; break; case OP_NEXT: case OP_SK_DOWN: downloads_list.move_down(wrap_scroll); update_view = true; break; case OP_SK_HOME: downloads_list.move_to_first(); update_view = true; break; case OP_SK_END: downloads_list.move_to_last(); update_view = true; break; case OP_SK_PGUP: downloads_list.move_page_up(wrap_scroll); update_view = true; break; case OP_SK_PGDOWN: downloads_list.move_page_down(wrap_scroll); update_view = true; break; case OP_PB_TOGGLE_DLALL: auto_download = !auto_download; break; case OP_HARDQUIT: case OP_QUIT: if (ctrl->downloads_in_progress() > 0) { dllist_form.set("msg", _("Error: can't quit: download(s) in progress.")); update_view = true; } else { quit = true; } break; case OP_PB_MOREDL: ctrl->increase_parallel_downloads(); break; case OP_PB_LESSDL: ctrl->decrease_parallel_downloads(); break; case OP_PB_DOWNLOAD: { if (ctrl->downloads().size() >= 1) { const auto idx = downloads_list.get_position(); auto& item = ctrl->downloads()[idx]; if (item.status() != DlStatus::DOWNLOADING) { ctrl->start_download(item); } } } break; case OP_PB_PLAY: { if (ctrl->downloads().size() >= 1) { const auto idx = downloads_list.get_position(); DlStatus status = ctrl->downloads()[idx].status(); if (status == DlStatus::FINISHED || status == DlStatus::PLAYED || status == DlStatus::READY) { ctrl->play_file(ctrl->downloads()[idx] .filename()); ctrl->downloads()[idx].set_status( DlStatus::PLAYED); } else { dllist_form.set("msg", _("Error: download needs to be " "finished before the file " "can be played.")); } } } break; case OP_PB_MARK_FINISHED: { auto& downloads = ctrl->downloads(); if (downloads.size() >= 1) { const auto idx = downloads_list.get_position(); DlStatus status = downloads[idx].status(); if (status == DlStatus::PLAYED) { downloads[idx].set_status(DlStatus::FINISHED); if (idx + 1 < downloads.size()) { downloads_list.set_position(idx + 1); } } } } break; case OP_PB_CANCEL: { if (ctrl->downloads().size() >= 1) { const auto idx = downloads_list.get_position(); if (ctrl->downloads()[idx].status() == DlStatus::DOWNLOADING) { ctrl->downloads()[idx].set_status( DlStatus::CANCELLED); } } } break; case OP_PB_DELETE: { auto& downloads = ctrl->downloads(); if (downloads.size() >= 1) { const auto idx = downloads_list.get_position(); if (downloads[idx].status() != DlStatus::DOWNLOADING) { downloads[idx].set_status(DlStatus::DELETED); if (idx + 1 < downloads.size()) { downloads_list.set_position(idx + 1); } } } } break; case OP_PB_PURGE: if (ctrl->downloads_in_progress() > 0) { dllist_form.set("msg", _("Error: unable to perform operation: " "download(s) in progress.")); } else { ctrl->purge_queue(); } update_view = true; break; case OP_HELP: run_help(); break; default: break; } } while (!quit); } void PbView::handle_resize() { std::vector<std::reference_wrapper<newsboat::Stfl::Form>> forms = {dllist_form, help_form}; for (const auto& form : forms) { form.get().run(-3); } update_view = true; } void PbView::apply_colors_to_all_forms() { using namespace std::placeholders; colorman.apply_colors(std::bind(&newsboat::Stfl::Form::set, &dllist_form, _1, _2)); colorman.apply_colors(std::bind(&newsboat::Stfl::Form::set, &help_form, _1, _2)); } std::pair<double, std::string> PbView::get_speed_human_readable(double kbps) { if (kbps < 1024) { return std::make_pair(kbps, _("KB/s")); } else if (kbps < 1024 * 1024) { return std::make_pair(kbps / 1024, _("MB/s")); } else { return std::make_pair(kbps / 1024 / 1024, _("GB/s")); } } void PbView::run_help() { set_help_keymap_hint(); help_form.set("head", _("Help")); const auto descs = keys->get_keymap_descriptions("podboat"); ListFormatter listfmt; for (const auto& desc : descs) { const std::string descline = strprintf::fmt("%-7s %-23s %s", desc.key, desc.cmd, desc.desc); listfmt.add_line(descline); } help_textview.stfl_replace_lines(listfmt.get_lines_count(), listfmt.format_list()); bool quit = false; do { const char* event = help_form.run(0); if (!event) { continue; } if (strcmp(event, "RESIZE") == 0) { handle_resize(); continue; } Operation op = keys->get_operation(event, "help"); switch (op) { case OP_SK_UP: help_textview.scroll_up(); break; case OP_SK_DOWN: help_textview.scroll_down(); break; case OP_SK_HOME: help_textview.scroll_to_top(); break; case OP_SK_END: help_textview.scroll_to_bottom(); break; case OP_SK_PGUP: help_textview.scroll_page_up(); break; case OP_SK_PGDOWN: help_textview.scroll_page_down(); break; case OP_HARDQUIT: case OP_QUIT: quit = true; break; default: break; } } while (!quit); } std::string PbView::prepare_keymaphint(KeyMapHintEntry* hints) { std::string keymap_hint; for (int i = 0; hints[i].op != OP_NIL; ++i) { std::string bound_keys = utils::join(keys->get_keys(hints[i].op, "podboat"), ","); if (bound_keys.empty()) { bound_keys = "<none>"; } keymap_hint.append(bound_keys); keymap_hint.append(":"); keymap_hint.append(hints[i].text); keymap_hint.append(" "); } return keymap_hint; } void PbView::set_help_keymap_hint() { static KeyMapHintEntry hints[] = {{OP_QUIT, _("Quit")}, {OP_NIL, nullptr}}; std::string keymap_hint = prepare_keymaphint(hints); help_form.set("help", keymap_hint); } void PbView::set_dllist_keymap_hint() { static KeyMapHintEntry hints[] = {{OP_QUIT, _("Quit")}, {OP_PB_DOWNLOAD, _("Download")}, {OP_PB_CANCEL, _("Cancel")}, {OP_PB_DELETE, _("Delete")}, {OP_PB_PURGE, _("Purge Finished")}, {OP_PB_TOGGLE_DLALL, _("Toggle Automatic Download")}, {OP_PB_PLAY, _("Play")}, {OP_PB_MARK_FINISHED, _("Mark as Finished")}, {OP_HELP, _("Help")}, {OP_NIL, nullptr} }; std::string keymap_hint = prepare_keymaphint(hints); dllist_form.set("help", keymap_hint); } std::string PbView::format_line(const std::string& podlist_format, const Download& dl, unsigned int pos, unsigned int width) { FmtStrFormatter fmt; const double speed_kbps = dl.kbps(); const auto speed = get_speed_human_readable(speed_kbps); fmt.register_fmt('i', strprintf::fmt("%u", pos + 1)); fmt.register_fmt('d', strprintf::fmt("%.1f", dl.current_size() / (1024 * 1024))); fmt.register_fmt( 't', strprintf::fmt("%.1f", dl.total_size() / (1024 * 1024))); fmt.register_fmt('p', strprintf::fmt("%.1f", dl.percents_finished())); fmt.register_fmt('k', strprintf::fmt("%.2f", speed_kbps)); fmt.register_fmt('K', strprintf::fmt("%.2f %s", speed.first, speed.second)); fmt.register_fmt('S', strprintf::fmt("%s", dl.status_text())); fmt.register_fmt('u', strprintf::fmt("%s", dl.url())); fmt.register_fmt('F', strprintf::fmt("%s", dl.filename())); fmt.register_fmt('b', strprintf::fmt("%s", dl.basename())); auto formattedLine = fmt.do_format(podlist_format, width); formattedLine = utils::quote_for_stfl(formattedLine); return formattedLine; } } // namespace podboat <commit_msg>Podboat: Only regenerate the full downloads list if something changed<commit_after>#include "pbview.h" #include <cinttypes> #include <cstdio> #include <cstring> #include <ncurses.h> #include <iostream> #include <sstream> #include "config.h" #include "configcontainer.h" #include "dllist.h" #include "download.h" #include "fmtstrformatter.h" #include "help.h" #include "listformatter.h" #include "logger.h" #include "pbcontroller.h" #include "strprintf.h" #include "utils.h" using namespace newsboat; namespace podboat { PbView::PbView(PbController* c) : update_view(true) , ctrl(c) , dllist_form(dllist_str) , help_form(help_str) , keys(0) , colorman(ctrl->get_colormanager()) , downloads_list("dls", dllist_form, ctrl->get_cfgcont()->get_configvalue_as_int("scrolloff")) , help_textview("helptext", help_form) { if (getenv("ESCDELAY") == nullptr) { set_escdelay(25); } } PbView::~PbView() { Stfl::reset(); } void PbView::run(bool auto_download, bool wrap_scroll) { bool quit = false; // Make sure curses is initialized dllist_form.run(-3); // Hide cursor using curses curs_set(0); set_dllist_keymap_hint(); do { if (update_view) { const double total_kbps = ctrl->get_total_kbps(); const auto speed = get_speed_human_readable(total_kbps); auto title = strprintf::fmt( _("Queue (%u downloads in progress, %u total) - %.2f %s total"), static_cast<unsigned int>(ctrl->downloads_in_progress()), static_cast<unsigned int>(ctrl->downloads().size()), speed.first, speed.second); if (ctrl->get_maxdownloads() > 1) { title += strprintf::fmt(_(" - %u parallel downloads"), ctrl->get_maxdownloads()); } dllist_form.set("head", title); LOG(Level::DEBUG, "PbView::run: updating view... " "downloads().size() " "= %" PRIu64, static_cast<uint64_t>(ctrl->downloads().size())); ListFormatter listfmt; const std::string line_format = ctrl->get_cfgcont()->get_configvalue("podlist-format"); dllist_form.run(-3); // compute all widget dimensions const unsigned int width = downloads_list.get_width(); unsigned int i = 0; for (const auto& dl : ctrl->downloads()) { auto lbuf = format_line(line_format, dl, i, width); listfmt.add_line(lbuf); i++; } downloads_list.stfl_replace_lines(listfmt); update_view = false; } // If there's no status message, we know there's no error to show // Thus, it's safe to replace with the download's status if (dllist_form.get("msg").empty() && ctrl->downloads().size() > 0) { const auto idx = downloads_list.get_position(); dllist_form.set("msg", ctrl->downloads()[idx].status_msg()); } const char* event = dllist_form.run(500); if (auto_download) { if (ctrl->get_maxdownloads() > ctrl->downloads_in_progress()) { ctrl->start_downloads(); } } if (!event || strcmp(event, "TIMEOUT") == 0) { continue; } if (strcmp(event, "RESIZE") == 0) { handle_resize(); continue; } Operation op = keys->get_operation(event, "podboat"); if (dllist_form.get("msg").length() > 0) { dllist_form.set("msg", ""); update_view = true; } switch (op) { case OP_REDRAW: Stfl::reset(); break; case OP_PREV: case OP_SK_UP: downloads_list.move_up(wrap_scroll); break; case OP_NEXT: case OP_SK_DOWN: downloads_list.move_down(wrap_scroll); break; case OP_SK_HOME: downloads_list.move_to_first(); break; case OP_SK_END: downloads_list.move_to_last(); break; case OP_SK_PGUP: downloads_list.move_page_up(wrap_scroll); break; case OP_SK_PGDOWN: downloads_list.move_page_down(wrap_scroll); break; case OP_PB_TOGGLE_DLALL: auto_download = !auto_download; break; case OP_HARDQUIT: case OP_QUIT: if (ctrl->downloads_in_progress() > 0) { dllist_form.set("msg", _("Error: can't quit: download(s) in progress.")); update_view = true; } else { quit = true; } break; case OP_PB_MOREDL: ctrl->increase_parallel_downloads(); break; case OP_PB_LESSDL: ctrl->decrease_parallel_downloads(); break; case OP_PB_DOWNLOAD: { if (ctrl->downloads().size() >= 1) { const auto idx = downloads_list.get_position(); auto& item = ctrl->downloads()[idx]; if (item.status() != DlStatus::DOWNLOADING) { ctrl->start_download(item); } } } break; case OP_PB_PLAY: { if (ctrl->downloads().size() >= 1) { const auto idx = downloads_list.get_position(); DlStatus status = ctrl->downloads()[idx].status(); if (status == DlStatus::FINISHED || status == DlStatus::PLAYED || status == DlStatus::READY) { ctrl->play_file(ctrl->downloads()[idx] .filename()); ctrl->downloads()[idx].set_status( DlStatus::PLAYED); } else { dllist_form.set("msg", _("Error: download needs to be " "finished before the file " "can be played.")); } } } break; case OP_PB_MARK_FINISHED: { auto& downloads = ctrl->downloads(); if (downloads.size() >= 1) { const auto idx = downloads_list.get_position(); DlStatus status = downloads[idx].status(); if (status == DlStatus::PLAYED) { downloads[idx].set_status(DlStatus::FINISHED); if (idx + 1 < downloads.size()) { downloads_list.set_position(idx + 1); } } } } break; case OP_PB_CANCEL: { if (ctrl->downloads().size() >= 1) { const auto idx = downloads_list.get_position(); if (ctrl->downloads()[idx].status() == DlStatus::DOWNLOADING) { ctrl->downloads()[idx].set_status( DlStatus::CANCELLED); } } } break; case OP_PB_DELETE: { auto& downloads = ctrl->downloads(); if (downloads.size() >= 1) { const auto idx = downloads_list.get_position(); if (downloads[idx].status() != DlStatus::DOWNLOADING) { downloads[idx].set_status(DlStatus::DELETED); if (idx + 1 < downloads.size()) { downloads_list.set_position(idx + 1); } } } } break; case OP_PB_PURGE: if (ctrl->downloads_in_progress() > 0) { dllist_form.set("msg", _("Error: unable to perform operation: " "download(s) in progress.")); } else { ctrl->purge_queue(); } update_view = true; break; case OP_HELP: run_help(); break; default: break; } } while (!quit); } void PbView::handle_resize() { std::vector<std::reference_wrapper<newsboat::Stfl::Form>> forms = {dllist_form, help_form}; for (const auto& form : forms) { form.get().run(-3); } update_view = true; } void PbView::apply_colors_to_all_forms() { using namespace std::placeholders; colorman.apply_colors(std::bind(&newsboat::Stfl::Form::set, &dllist_form, _1, _2)); colorman.apply_colors(std::bind(&newsboat::Stfl::Form::set, &help_form, _1, _2)); } std::pair<double, std::string> PbView::get_speed_human_readable(double kbps) { if (kbps < 1024) { return std::make_pair(kbps, _("KB/s")); } else if (kbps < 1024 * 1024) { return std::make_pair(kbps / 1024, _("MB/s")); } else { return std::make_pair(kbps / 1024 / 1024, _("GB/s")); } } void PbView::run_help() { set_help_keymap_hint(); help_form.set("head", _("Help")); const auto descs = keys->get_keymap_descriptions("podboat"); ListFormatter listfmt; for (const auto& desc : descs) { const std::string descline = strprintf::fmt("%-7s %-23s %s", desc.key, desc.cmd, desc.desc); listfmt.add_line(descline); } help_textview.stfl_replace_lines(listfmt.get_lines_count(), listfmt.format_list()); bool quit = false; do { const char* event = help_form.run(0); if (!event) { continue; } if (strcmp(event, "RESIZE") == 0) { handle_resize(); continue; } Operation op = keys->get_operation(event, "help"); switch (op) { case OP_SK_UP: help_textview.scroll_up(); break; case OP_SK_DOWN: help_textview.scroll_down(); break; case OP_SK_HOME: help_textview.scroll_to_top(); break; case OP_SK_END: help_textview.scroll_to_bottom(); break; case OP_SK_PGUP: help_textview.scroll_page_up(); break; case OP_SK_PGDOWN: help_textview.scroll_page_down(); break; case OP_HARDQUIT: case OP_QUIT: quit = true; break; default: break; } } while (!quit); } std::string PbView::prepare_keymaphint(KeyMapHintEntry* hints) { std::string keymap_hint; for (int i = 0; hints[i].op != OP_NIL; ++i) { std::string bound_keys = utils::join(keys->get_keys(hints[i].op, "podboat"), ","); if (bound_keys.empty()) { bound_keys = "<none>"; } keymap_hint.append(bound_keys); keymap_hint.append(":"); keymap_hint.append(hints[i].text); keymap_hint.append(" "); } return keymap_hint; } void PbView::set_help_keymap_hint() { static KeyMapHintEntry hints[] = {{OP_QUIT, _("Quit")}, {OP_NIL, nullptr}}; std::string keymap_hint = prepare_keymaphint(hints); help_form.set("help", keymap_hint); } void PbView::set_dllist_keymap_hint() { static KeyMapHintEntry hints[] = {{OP_QUIT, _("Quit")}, {OP_PB_DOWNLOAD, _("Download")}, {OP_PB_CANCEL, _("Cancel")}, {OP_PB_DELETE, _("Delete")}, {OP_PB_PURGE, _("Purge Finished")}, {OP_PB_TOGGLE_DLALL, _("Toggle Automatic Download")}, {OP_PB_PLAY, _("Play")}, {OP_PB_MARK_FINISHED, _("Mark as Finished")}, {OP_HELP, _("Help")}, {OP_NIL, nullptr} }; std::string keymap_hint = prepare_keymaphint(hints); dllist_form.set("help", keymap_hint); } std::string PbView::format_line(const std::string& podlist_format, const Download& dl, unsigned int pos, unsigned int width) { FmtStrFormatter fmt; const double speed_kbps = dl.kbps(); const auto speed = get_speed_human_readable(speed_kbps); fmt.register_fmt('i', strprintf::fmt("%u", pos + 1)); fmt.register_fmt('d', strprintf::fmt("%.1f", dl.current_size() / (1024 * 1024))); fmt.register_fmt( 't', strprintf::fmt("%.1f", dl.total_size() / (1024 * 1024))); fmt.register_fmt('p', strprintf::fmt("%.1f", dl.percents_finished())); fmt.register_fmt('k', strprintf::fmt("%.2f", speed_kbps)); fmt.register_fmt('K', strprintf::fmt("%.2f %s", speed.first, speed.second)); fmt.register_fmt('S', strprintf::fmt("%s", dl.status_text())); fmt.register_fmt('u', strprintf::fmt("%s", dl.url())); fmt.register_fmt('F', strprintf::fmt("%s", dl.filename())); fmt.register_fmt('b', strprintf::fmt("%s", dl.basename())); auto formattedLine = fmt.do_format(podlist_format, width); formattedLine = utils::quote_for_stfl(formattedLine); return formattedLine; } } // namespace podboat <|endoftext|>
<commit_before>#include "player.h" Pacman::Pacman() { MobileObject::MobileObject(); x = 0; y = 0; boundX = 0; boundY = 0; velocity = 1; image = NULL; }; void Pacman::Init(float x, float y, int boundX, int boundY, int velocity, float lives, ALLEGRO_BITMAP *image) { MobileObject::Init(x, y, boundX, boundY, image); Pacman::velocity = velocity; Pacman::lives = lives; maxFrame = 6; curFrame = 0; frameCount = 0; //depends on sprite NEED TO BE FILLED WITH CORRECT VALUES frameDelay = 3; frameWidth = 32; frameHeight = 32; animationColumns = 6; //that makes the Pacman rotating; I don't know if this can be done fancier angle = 0; Pacman::image = image; Pacman::SetDir(1); } void Pacman::Movement(int keys) { if(keys == UP) { MobileObject::MoveUp(); angle = -ALLEGRO_PI / 2; } else if(keys == DOWN) { MobileObject::MoveDown(); angle = ALLEGRO_PI / 2; } else if(keys == LEFT) { MobileObject::MoveLeft(); angle = ALLEGRO_PI; } else if(keys == RIGHT) { MobileObject::MoveRight(); angle = 0; } } void Pacman::Destroy() { MobileObject::Destroy(); } void Pacman::Update(int keys) { Pacman::Movement(direction); if((direction != keys) && !((int)x % 32) && !((int)y % 32)) { direction = keys; Pacman::Movement(keys); } if(++frameCount >= frameDelay) { curFrame ++; if(curFrame >= maxFrame) curFrame = 0; else if(curFrame <= 0) curFrame = maxFrame; frameCount = 0; } if(Pacman::x < 0) Pacman::x = WIDTH + 31; else if(Pacman::x > WIDTH+32) Pacman::x = 1; if(Pacman::y < 0) Pacman::y = HEIGHT + 31; else if (Pacman::y > HEIGHT+32) Pacman::y = 1; // Now it's smooth and silky } void Pacman::Render() { MobileObject::Render(); int fx = (curFrame % animationColumns) * frameWidth; int fy = (curFrame / animationColumns) * frameHeight; al_draw_tinted_scaled_rotated_bitmap_region(image, fx, fy, frameWidth, frameHeight, al_map_rgba_f(1, 1, 1, 1.0), frameWidth / 2, frameHeight / 2, x - frameWidth / 2, y - frameHeight / 2, 1, 1, angle, 0); } void Pacman::Collided(int ObjectID) { }<commit_msg>Little fix regarding the teleport<commit_after>#include "player.h" Pacman::Pacman() { MobileObject::MobileObject(); x = 0; y = 0; boundX = 0; boundY = 0; velocity = 1; image = NULL; }; void Pacman::Init(float x, float y, int boundX, int boundY, int velocity, float lives, ALLEGRO_BITMAP *image) { MobileObject::Init(x, y, boundX, boundY, image); Pacman::velocity = velocity; Pacman::lives = lives; maxFrame = 6; curFrame = 0; frameCount = 0; //depends on sprite NEED TO BE FILLED WITH CORRECT VALUES frameDelay = 3; frameWidth = 32; frameHeight = 32; animationColumns = 6; //that makes the Pacman rotating; I don't know if this can be done fancier angle = 0; Pacman::image = image; Pacman::SetDir(1); } void Pacman::Movement(int keys) { if(keys == UP) { MobileObject::MoveUp(); angle = -ALLEGRO_PI / 2; } else if(keys == DOWN) { MobileObject::MoveDown(); angle = ALLEGRO_PI / 2; } else if(keys == LEFT) { MobileObject::MoveLeft(); angle = ALLEGRO_PI; } else if(keys == RIGHT) { MobileObject::MoveRight(); angle = 0; } } void Pacman::Destroy() { MobileObject::Destroy(); } void Pacman::Update(int keys) { Pacman::Movement(direction); if((direction != keys) && !((int)x % 32) && !((int)y % 32)) { direction = keys; Pacman::Movement(keys); } if(++frameCount >= frameDelay) { curFrame ++; if(curFrame >= maxFrame) curFrame = 0; else if(curFrame <= 0) curFrame = maxFrame; frameCount = 0; } if(Pacman::x < 0) Pacman::x = WIDTH + 32; else if(Pacman::x > WIDTH+32) Pacman::x = 1; if(Pacman::y < 0) Pacman::y = HEIGHT + 32; else if (Pacman::y > HEIGHT+32) Pacman::y = 1; // Now it's smooth and silky } void Pacman::Render() { MobileObject::Render(); int fx = (curFrame % animationColumns) * frameWidth; int fy = (curFrame / animationColumns) * frameHeight; al_draw_tinted_scaled_rotated_bitmap_region(image, fx, fy, frameWidth, frameHeight, al_map_rgba_f(1, 1, 1, 1.0), frameWidth / 2, frameHeight / 2, x - frameWidth / 2, y - frameHeight / 2, 1, 1, angle, 0); } void Pacman::Collided(int ObjectID) { }<|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <iostream> #include "libtorrent/policy.hpp" #include "libtorrent/torrent.hpp" #include "libtorrent/socket.hpp" #include "libtorrent/peer_connection.hpp" namespace { enum { // we try to maintain 4 requested blocks in the download // queue request_queue = 16 }; using namespace libtorrent; // TODO: replace these two functions with std::find_first_of template<class It1, class It2> bool has_intersection(It1 start1, It1 end1, It2 start2, It2 end2) { for (;start1 != end1; ++start1) for (;start2 != end2; ++start2) if (*start1 == *start2) return true; return false; } piece_block find_first_common(const std::vector<piece_block>& queue, const std::vector<piece_block>& busy) { for (std::vector<piece_block>::const_reverse_iterator i = queue.rbegin(); i != queue.rend(); ++i) { for (std::vector<piece_block>::const_iterator j = busy.begin(); j != busy.end(); ++j) { if ((*j) == (*i)) return *i; } } assert(false); } void request_a_block(torrent& t, peer_connection& c) { int num_requests = request_queue - c.download_queue().size(); // if our request queue is already full, we // don't have to make any new requests yet if (num_requests <= 0) return; piece_picker& p = t.picker(); std::vector<piece_block> interesting_pieces; interesting_pieces.reserve(100); // picks the interesting pieces from this peer // the integer is the number of pieces that // should be guaranteed to be available for download // (if this number is too big, too many pieces are // picked and cpu-time is wasted) p.pick_pieces(c.get_bitfield(), interesting_pieces, num_requests); // this vector is filled with the interestin pieces // that some other peer is currently downloading // we should then compare this peer's download speed // with the other's, to see if we should abort another // peer_connection in favour of this one std::vector<piece_block> busy_pieces; busy_pieces.reserve(10); for (std::vector<piece_block>::iterator i = interesting_pieces.begin(); i != interesting_pieces.end(); ++i) { if (p.is_downloading(*i)) { busy_pieces.push_back(*i); continue; } // ok, we found a piece that's not being downloaded // by somebody else. request it from this peer c.request_block(*i); num_requests--; if (num_requests <= 0) return; } if (busy_pieces.empty()) return; // first look for blocks that are just queued // and not actually sent to us yet // (then we can cancel those and request them // from this peer instead) peer_connection* peer = 0; float down_speed = 0.f; // find the peer with the lowest download // speed that also has a piece thatt this // peer could send us for (torrent::peer_iterator i = t.begin(); i != t.end(); ++i) { const std::vector<piece_block>& queue = (*i)->download_queue(); if ((*i)->statistics().down_peak() > down_speed && has_intersection(busy_pieces.begin(), busy_pieces.end(), queue.begin(), queue.end())) { peer = *i; down_speed = (*i)->statistics().down_peak(); } } assert(peer != 0); // this peer doesn't have a faster connection than the // slowest peer. Don't take over any blocks if (c.statistics().down_peak() <= down_speed) return; // find a suitable block to take over from this peer piece_block block = find_first_common(peer->download_queue(), busy_pieces); peer->cancel_block(block); c.request_block(block); // the one we interrupted may need to request a new piece request_a_block(t, *peer); num_requests--; } } namespace libtorrent { /* TODO: make two proxy classes that filter out all unneccesary members from torrent and peer_connection to make it easier to use them in the policy useful member functions: void torrent::connect_to_peer(address, peer_id); piece_picker& torrent::picker(); std::vector<peer_connection*>::const_iterator torrent::begin() const std::vector<peer_connection*>::const_iterator torrent::end() const void peer_connection::interested(); void peer_connection::not_interested(); void peer_connection::choke(); void peer_connection::unchoke(); void peer_connection::request_piece(int index); const std::vector<int>& peer_connection::download_queue(); */ policy::policy(torrent* t) : m_num_peers(0) , m_torrent(t) {} // this is called when a connection is made, before any // handshake (it's possible to ban certain ip:s). bool policy::accept_connection(const address& remote) { m_num_peers++; return true; } void policy::peer_from_tracker(const address& remote, const peer_id& id) { try { m_torrent->connect_to_peer(remote, id); m_num_peers++; } catch(network_error&) {} } // this is called when we are choked by a peer // i.e. a peer lets us know that we will not receive // anything for a while void policy::choked(peer_connection& c) { c.choke(); } void policy::piece_finished(peer_connection& c, int index, bool successfully_verified) { // TODO: if verification failed, mark the peers that were involved // in some way } void policy::block_finished(peer_connection& c, piece_block b) { if (c.has_peer_choked()) return; request_a_block(*m_torrent, c); } // this is called when we are unchoked by a peer // i.e. a peer lets us know that we will receive // data from now on void policy::unchoked(peer_connection& c) { c.unchoke(); if (c.is_interesting()) request_a_block(*m_torrent, c); } void policy::interested(peer_connection& c) { c.unchoke(); } void policy::not_interested(peer_connection& c) { } void policy::connection_closed(const peer_connection& c) { } void policy::peer_is_interesting(peer_connection& c) { c.interested(); if (c.has_peer_choked()) return; request_a_block(*m_torrent, c); } } <commit_msg>bugfix<commit_after>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <iostream> #include "libtorrent/policy.hpp" #include "libtorrent/torrent.hpp" #include "libtorrent/socket.hpp" #include "libtorrent/peer_connection.hpp" namespace { enum { // we try to maintain 4 requested blocks in the download // queue request_queue = 16 }; using namespace libtorrent; // TODO: replace these two functions with std::find_first_of template<class It1, class It2> bool has_intersection(It1 start1, It1 end1, It2 start2, It2 end2) { for (;start1 != end1; ++start1) for (;start2 != end2; ++start2) if (*start1 == *start2) return true; return false; } piece_block find_first_common(const std::vector<piece_block>& queue, const std::vector<piece_block>& busy) { for (std::vector<piece_block>::const_reverse_iterator i = queue.rbegin(); i != queue.rend(); ++i) { for (std::vector<piece_block>::const_iterator j = busy.begin(); j != busy.end(); ++j) { if ((*j) == (*i)) return *i; } } assert(false); } void request_a_block(torrent& t, peer_connection& c) { int num_requests = request_queue - c.download_queue().size(); // if our request queue is already full, we // don't have to make any new requests yet if (num_requests <= 0) return; piece_picker& p = t.picker(); std::vector<piece_block> interesting_pieces; interesting_pieces.reserve(100); // picks the interesting pieces from this peer // the integer is the number of pieces that // should be guaranteed to be available for download // (if this number is too big, too many pieces are // picked and cpu-time is wasted) p.pick_pieces(c.get_bitfield(), interesting_pieces, num_requests); // this vector is filled with the interestin pieces // that some other peer is currently downloading // we should then compare this peer's download speed // with the other's, to see if we should abort another // peer_connection in favour of this one std::vector<piece_block> busy_pieces; busy_pieces.reserve(10); for (std::vector<piece_block>::iterator i = interesting_pieces.begin(); i != interesting_pieces.end(); ++i) { if (p.is_downloading(*i)) { busy_pieces.push_back(*i); continue; } // ok, we found a piece that's not being downloaded // by somebody else. request it from this peer c.request_block(*i); num_requests--; if (num_requests <= 0) return; } if (busy_pieces.empty()) return; // first look for blocks that are just queued // and not actually sent to us yet // (then we can cancel those and request them // from this peer instead) peer_connection* peer = 0; float down_speed = -1.f; // find the peer with the lowest download // speed that also has a piece thatt this // peer could send us for (torrent::peer_iterator i = t.begin(); i != t.end(); ++i) { const std::vector<piece_block>& queue = (*i)->download_queue(); if ((*i)->statistics().down_peak() > down_speed && has_intersection(busy_pieces.begin(), busy_pieces.end(), queue.begin(), queue.end())) { peer = *i; down_speed = (*i)->statistics().down_peak(); } } assert(peer != 0); // this peer doesn't have a faster connection than the // slowest peer. Don't take over any blocks if (c.statistics().down_peak() <= down_speed) return; // find a suitable block to take over from this peer piece_block block = find_first_common(peer->download_queue(), busy_pieces); peer->cancel_block(block); c.request_block(block); // the one we interrupted may need to request a new piece request_a_block(t, *peer); num_requests--; } } namespace libtorrent { /* TODO: make two proxy classes that filter out all unneccesary members from torrent and peer_connection to make it easier to use them in the policy useful member functions: void torrent::connect_to_peer(address, peer_id); piece_picker& torrent::picker(); std::vector<peer_connection*>::const_iterator torrent::begin() const std::vector<peer_connection*>::const_iterator torrent::end() const void peer_connection::interested(); void peer_connection::not_interested(); void peer_connection::choke(); void peer_connection::unchoke(); void peer_connection::request_piece(int index); const std::vector<int>& peer_connection::download_queue(); */ policy::policy(torrent* t) : m_num_peers(0) , m_torrent(t) {} // this is called when a connection is made, before any // handshake (it's possible to ban certain ip:s). bool policy::accept_connection(const address& remote) { m_num_peers++; return true; } void policy::peer_from_tracker(const address& remote, const peer_id& id) { try { m_torrent->connect_to_peer(remote, id); m_num_peers++; } catch(network_error&) {} } // this is called when we are choked by a peer // i.e. a peer lets us know that we will not receive // anything for a while void policy::choked(peer_connection& c) { c.choke(); } void policy::piece_finished(peer_connection& c, int index, bool successfully_verified) { // TODO: if verification failed, mark the peers that were involved // in some way } void policy::block_finished(peer_connection& c, piece_block b) { if (c.has_peer_choked()) return; request_a_block(*m_torrent, c); } // this is called when we are unchoked by a peer // i.e. a peer lets us know that we will receive // data from now on void policy::unchoked(peer_connection& c) { c.unchoke(); if (c.is_interesting()) request_a_block(*m_torrent, c); } void policy::interested(peer_connection& c) { c.unchoke(); } void policy::not_interested(peer_connection& c) { } void policy::connection_closed(const peer_connection& c) { } void policy::peer_is_interesting(peer_connection& c) { c.interested(); if (c.has_peer_choked()) return; request_a_block(*m_torrent, c); } } <|endoftext|>
<commit_before> #include "reader.h" #include <cassert> #include <cstring> #include <stack> #define BUFF_CAP 4096 #define MAX_SEQ 524288 using std::istream; using std::stack; namespace AMOS { Reader::Reader(istream& input): input(&input), buff_written(0) { buff = new char[BUFF_CAP]; buff_cap = BUFF_CAP; states.push(OUT); } bool Reader::has_next() { if (buff_written == 0) { return buffer_next() > 0; } return buff_written > 0; } int Reader::skip_next() { int skipped = 0; if (buff_written == 0) { skipped = buffer_next(); if (skipped == -1) { return -1; } } else { skipped = buff_written; } //cerr << "SKIP " << buff << endl; buffer_clear(); return skipped; } ObjectType Reader::next_type() { return next_type_; } class Read* Reader::next_read() { //cerr << "NEXT_READ" << endl; if (!has_next()) { return nullptr; } while (next_type() != ObjectType::Read) { //cerr << "WRONG TYPE" << endl; skip_next(); if (!has_next()) { return nullptr; } } //cout << "READ " << buff << endl; skip_next(); // add code for parsing read return nullptr; } int Reader::buffer_clear() { //cerr << "FLUSH " << buff << endl; int was_written = buff_written; buff_written = 0; buff_marks.clear(); return was_written; } int Reader::buffer_double() { buff = (char *) realloc(buff, buff_cap * 2); if (buff == nullptr) { buff_cap = 0; buff_written = 0; return -1; } buff_cap *= 2; return buff_cap; } int Reader::buffer_next() { assert(states.size() == 1); assert(buff_written == 0); if (input->eof()) return 0; while (true) { auto line = buff + buff_written; input->getline(line, buff_cap - buff_written); int line_start = buff_written; buff_written += strlen(line); if (input->eof()) { return -1; } if (input->fail()) { return -1; } int seq_start = 0; auto state = states.top(); switch (state) { case OUT: if (strncmp(line, "{RED", 4) == 0) { states.push(IN); next_type_ = ObjectType::Read; } else if (strncmp(line, "{OVL", 4) == 0) { states.push(IN); next_type_ = ObjectType::Overlap; } else if (strncmp(line, "{UNV", 4) == 0) { states.push(IN); next_type_ = ObjectType::Universal; } else if (strncmp(line, "{LIB", 4) == 0) { states.push(IN); next_type_ = ObjectType::Library; } else if (strncmp(line, "{FRG", 4) == 0) { states.push(IN); next_type_ = ObjectType::Fragment; } else { assert(false); } buff_marks.push_back(BufferMark(ObjectDef, line_start, buff_written)); break; case IN: if (line[0] == '}') { states.pop(); } else if (strncmp(line, "seq:", 4) == 0) { states.push(IN_SEQ); seq_start = line_start; } else if (strncmp(line, "qlt:", 4) == 0) { states.push(IN_QLT); seq_start = line_start; } else if (strncmp(line, "com:", 4) == 0) { states.push(IN_COM); seq_start = line_start; } else if (strncmp(line, "{DST", 4) == 0) { buff_marks.push_back(BufferMark(ObjectDef, line_start, buff_written)); states.push(IN); } else { buff_marks.push_back(BufferMark(AttrDef, line_start, buff_written)); } break; case IN_SEQ: case IN_QLT: case IN_COM: if (line[0] == '.') { buff_marks.push_back(BufferMark(ObjectDef, seq_start, buff_written)); states.pop(); } break; default: assert(false); } if (states.size() == 1) { //cerr << "FILL " << buff << endl; return buff_written; } } return -1; } //int get_reads(std::vector<const Read*>& container, FILE *fd) { //int records = 0; //char line[buff_cap] = {0}; //ReaderState state = OUT; //Read* curr_read = new Read(); //char curr_seq[MAX_SEQ] = {0}; //int curr_seq_len = 0; //int line_len = 0; //long last_pos = ftell(fd); //const char **dst_str = nullptr; //while (!feof(fd)) { //// read next line and update pointers //fgets(line, buff_cap, fd); //long curr_pos = ftell(fd); //assert(curr_pos - last_pos < buff_cap); //line_len = curr_pos - last_pos; //last_pos = curr_pos; //// strip \n //line[line_len - 1] = 0; //line_len--; //switch (state) { //case OUT: //if (strstr(line, "{RED") != nullptr) { //state = IN_READ; //} //break; //case IN_READ: //if (sscanf(line, " iid: %d ", &curr_read->iid)) { //state = IN_READ; //} else if (strstr(line, "seq:") != nullptr) { //dst_str = &(curr_read->seq); //state = IN_SEQ; //} else if (strstr(line, "qlt:") != nullptr) { //dst_str = &(curr_read->qlt); //state = IN_QLT; //} else if (sscanf(line, " clr: %d, %d ", &curr_read->clr_lo, &curr_read->clr_hi)) { //state = IN_READ; //} else if (line[0] == '}') { //state = OUT; //container.push_back(curr_read); //curr_read = new Read(); //records++; //} //break; //case IN_SEQ: //case IN_QLT: //if (line[0] == '.') { //assert(dst_str != nullptr); //char *cpy = new char[curr_seq_len + 1]; //strncpy(cpy, curr_seq, curr_seq_len + 1); //curr_seq_len = 0; //*dst_str = cpy; // assign copied string to the destination //dst_str = nullptr; //state = IN_READ; //} else { //assert(line_len < MAX_SEQ - curr_seq_len); //strcpy(curr_seq + curr_seq_len, line); //curr_seq_len += line_len; //} //break; //default: //assert(false); //} //} //delete curr_read; //return records; //} //int get_overlaps(std::vector<const Overlap*>& container, FILE* fd) { //int records = 0; //char line[buff_cap] = {0}; //ReaderState state = OUT; //Overlap* curr_overlap = new Overlap(); //int line_len = 0; //long last_pos = ftell(fd); //const char **dst_str = nullptr; //while (!feof(fd)) { //// read next line and update pointers //fgets(line, buff_cap, fd); //long curr_pos = ftell(fd); //assert(curr_pos - last_pos < buff_cap); //line_len = curr_pos - last_pos; //last_pos = curr_pos; //// strip \n //line[line_len - 1] = 0; //line_len--; //switch (state) { //case OUT: //if (strstr(line, "{OVL") != nullptr) { //state = IN_OVL; //} //break; //case IN_OVL: //if (sscanf(line, " rds: %d, %d ", &curr_overlap->read1, &curr_overlap->read2)) { //state = IN_OVL; //} else if (sscanf(line, " adj: %c", &curr_overlap->adjacency)) { //state = IN_OVL; //} else if (sscanf(line, " ahg: %d", &curr_overlap->a_hang)) { //state = IN_OVL; //} else if (sscanf(line, " bhg: %d", &curr_overlap->b_hang)) { //state = IN_OVL; //} else if (sscanf(line, " scr: %d", &curr_overlap->score)) { //state = IN_OVL; //} else if (line[0] == '}') { //state = OUT; //container.push_back(curr_overlap); //curr_overlap = new Overlap(); //records++; //} //break; //default: //assert(false); //} //} //delete curr_overlap; //return records; //} } <commit_msg>remove commented out code<commit_after> #include "reader.h" #include <cassert> #include <cstring> #include <stack> #define BUFF_CAP 4096 #define MAX_SEQ 524288 using std::istream; using std::stack; namespace AMOS { Reader::Reader(istream& input): input(&input), buff_written(0) { buff = new char[BUFF_CAP]; buff_cap = BUFF_CAP; states.push(OUT); } bool Reader::has_next() { if (buff_written == 0) { return buffer_next() > 0; } return buff_written > 0; } int Reader::skip_next() { int skipped = 0; if (buff_written == 0) { skipped = buffer_next(); if (skipped == -1) { return -1; } } else { skipped = buff_written; } //cerr << "SKIP " << buff << endl; buffer_clear(); return skipped; } ObjectType Reader::next_type() { return next_type_; } class Read* Reader::next_read() { //cerr << "NEXT_READ" << endl; if (!has_next()) { return nullptr; } while (next_type() != ObjectType::Read) { //cerr << "WRONG TYPE" << endl; skip_next(); if (!has_next()) { return nullptr; } } //cout << "READ " << buff << endl; skip_next(); // add code for parsing read return nullptr; } int Reader::buffer_clear() { //cerr << "FLUSH " << buff << endl; int was_written = buff_written; buff_written = 0; buff_marks.clear(); return was_written; } int Reader::buffer_double() { buff = (char *) realloc(buff, buff_cap * 2); if (buff == nullptr) { buff_cap = 0; buff_written = 0; return -1; } buff_cap *= 2; return buff_cap; } int Reader::buffer_next() { assert(states.size() == 1); assert(buff_written == 0); if (input->eof()) return 0; while (true) { auto line = buff + buff_written; input->getline(line, buff_cap - buff_written); int line_start = buff_written; buff_written += strlen(line); if (input->eof()) { return -1; } if (input->fail()) { return -1; } int seq_start = 0; auto state = states.top(); switch (state) { case OUT: if (strncmp(line, "{RED", 4) == 0) { states.push(IN); next_type_ = ObjectType::Read; } else if (strncmp(line, "{OVL", 4) == 0) { states.push(IN); next_type_ = ObjectType::Overlap; } else if (strncmp(line, "{UNV", 4) == 0) { states.push(IN); next_type_ = ObjectType::Universal; } else if (strncmp(line, "{LIB", 4) == 0) { states.push(IN); next_type_ = ObjectType::Library; } else if (strncmp(line, "{FRG", 4) == 0) { states.push(IN); next_type_ = ObjectType::Fragment; } else { assert(false); } buff_marks.push_back(BufferMark(ObjectDef, line_start, buff_written)); break; case IN: if (line[0] == '}') { states.pop(); } else if (strncmp(line, "seq:", 4) == 0) { states.push(IN_SEQ); seq_start = line_start; } else if (strncmp(line, "qlt:", 4) == 0) { states.push(IN_QLT); seq_start = line_start; } else if (strncmp(line, "com:", 4) == 0) { states.push(IN_COM); seq_start = line_start; } else if (strncmp(line, "{DST", 4) == 0) { buff_marks.push_back(BufferMark(ObjectDef, line_start, buff_written)); states.push(IN); } else { buff_marks.push_back(BufferMark(AttrDef, line_start, buff_written)); } break; case IN_SEQ: case IN_QLT: case IN_COM: if (line[0] == '.') { buff_marks.push_back(BufferMark(ObjectDef, seq_start, buff_written)); states.pop(); } break; default: assert(false); } if (states.size() == 1) { //cerr << "FILL " << buff << endl; return buff_written; } } return -1; } } <|endoftext|>
<commit_before>/* * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland * All rights reserved. * * This library/application is free software; you can redistribute and/or modify it under the terms of * the license that is included with this library/application in the file license.txt. */ //--- interface include -------------------------------------------------------- #include "MT_Storage.h" //--- standard modules used ---------------------------------------------------- #include "Threads.h" #include "PoolAllocator.h" #include "SysLog.h" #include "Dbg.h" //--- c-library modules used --------------------------------------------------- #if !defined(WIN32) #include <stdlib.h> #endif THREADKEY MT_Storage::fgAllocatorKey = 0; #define FindAllocator(wdallocator) \ GETTLSDATA(MT_Storage::fgAllocatorKey, wdallocator, Allocator) void TLSDestructor(void *) { // destructor function for thread local storage } static Mutex *gsAllocatorInit = 0; // protect all data structures used by MT_Storage #if 0 #define TrackLockerInit(lockvar) , lockvar(0) #define TrackLockerDef(lockvar) volatile long lockvar class EXPORTDECL_MTFOUNDATION CurrLockerEntry { volatile long &frLockerId; public: CurrLockerEntry(volatile long &rLockerId, const char *pFile, long lLine) : frLockerId(rLockerId) { CheckException(pFile, lLine); frLockerId = Thread::MyId(); } ~CurrLockerEntry() { frLockerId = 0; } inline void CheckException(const char *pFile, long lLine) { if ( frLockerId != 0 ) { long lOther = frLockerId; char buf[256]; snprintf(buf, sizeof(buf), "\n%s:%d Another Locker entered already! otherThreadId:%d currentThreadId:%d\n", pFile, lLine, lOther, Thread::MyId()); SysLog::WriteToStderr(buf, strlen(buf)); } } }; #define TrackLocker(lockvar) CurrLockerEntry aEntry(lockvar, __FILE__, __LINE__) #else #define TrackLockerInit(lockvar) #define TrackLockerDef(lockvar) #define TrackLocker(lockvar) #endif class MTPoolAllocator: public PoolAllocator { public: //! create and initialize a pool allocator //! \param poolid use poolid to distinguish more than one pool //! \param poolSize size of pre-allocated pool in kBytes, default 1MByte MTPoolAllocator(long poolid, u_long poolSize = 1024, u_long maxKindOfBucket = 10) : PoolAllocator(poolid, poolSize, maxKindOfBucket) TrackLockerInit(fCurrLockerId) {} //! destroy a pool only if its empty, i.e. all allocated bytes are freed virtual ~MTPoolAllocator() { } //! implement hook for freeing memory virtual inline void Free(void *vp) { TrackLocker(fCurrLockerId); PoolAllocator::Free(vp); } protected: TrackLockerDef(fCurrLockerId); //!implement hook for allocating memory using bucketing virtual inline void *Alloc(u_long allocSize) { TrackLocker(fCurrLockerId); return PoolAllocator::Alloc(allocSize); } }; #ifdef MEM_DEBUG //------------- Utilities for Memory Tracking (multi threaded) -------------- MT_MemTracker::MT_MemTracker(const char *name) : MemTracker(name) { if ( !CREATEMUTEX(fMutex) ) { SysLog::Error("Mutex create failed"); } } MT_MemTracker::~MT_MemTracker() { if ( !DELETEMUTEX(fMutex) ) { SysLog::Error("Mutex delete failed"); } } void MT_MemTracker::TrackAlloc(u_long allocSz) { if ( !LOCKMUTEX(fMutex) ) { SysLog::Error("Mutex lock failed"); } MemTracker::TrackAlloc(allocSz); if ( !UNLOCKMUTEX(fMutex) ) { SysLog::Error("Mutex unlock failed"); } } void MT_MemTracker::TrackFree(u_long allocSz) { if ( !LOCKMUTEX(fMutex) ) { SysLog::Error("Mutex lock failed"); } MemTracker::TrackFree(allocSz); if ( !UNLOCKMUTEX(fMutex) ) { SysLog::Error("Mutex unlock failed"); } } l_long MT_MemTracker::CurrentlyAllocated() { l_long l; if ( !LOCKMUTEX(fMutex) ) { SysLog::Error("Mutex lock failed"); } l = fAllocated; if ( !UNLOCKMUTEX(fMutex) ) { SysLog::Error("Mutex lock failed"); } return l; } void MT_MemTracker::PrintStatistic() { if ( !LOCKMUTEX(fMutex) ) { SysLog::Error("Mutex lock failed"); } MemTracker::PrintStatistic(); if ( !UNLOCKMUTEX(fMutex) ) { SysLog::Error("Mutex lock failed"); } } #endif class EXPORTDECL_MTFOUNDATION MTStorageHooks : public StorageHooks { public: virtual void Initialize(); virtual void Finalize(); virtual Allocator *Global(); virtual Allocator *Current(); #ifdef MEM_DEBUG virtual MemTracker *MakeMemTracker(const char *name); #endif static bool fgInitialized; }; static MTStorageHooks sgMTHooks; //---- MT_Storage ------------------------------------------ struct AllocList { Allocator *wdallocator; AllocList *next; }; static AllocList *fgPoolAllocatorList = 0; bool MTStorageHooks::fgInitialized = false; // flag for memorizing initialization void MT_Storage::Initialize() { StartTrace(MT_Storage.Initialize); // must be called before threading is activated static bool once = false; if (!once) { gsAllocatorInit = new Mutex("AllocatorInit"); Storage::SetHooks(&sgMTHooks); Storage::Initialize(); // re-init with MT hook #ifdef MEM_DEBUG // switch to thread safe memory tracker Allocator *a = Storage::Global(); if (a) { a->ReplaceMemTracker(Storage::MakeMemTracker("MTGlobalAllocator")); } #endif once = true; } } void MT_Storage::RefAllocator(Allocator *wdallocator) { StartTrace1(MT_Storage.RefAllocator, "Id:" << (wdallocator ? wdallocator->GetId() : -1L)); if ( wdallocator ) { Initialize(); // used to initialize gsAllocatorInit Mutex // in mt case we need to control ref counting with mutexes MutexEntry me(*gsAllocatorInit); me.Use(); AllocList *elmt = (AllocList *)::calloc(1, sizeof(AllocList)); // catch memory allocation problem if (!elmt) { static const char crashmsg[] = "FATAL: MT_Storage::RefAllocator calloc failed. I will crash :-(\n"; SysLog::WriteToStderr(crashmsg, sizeof(crashmsg)); SysLog::Error("allocation failed for RefAllocator"); return; } // normal case everything ok wdallocator->Ref(); Trace("refcount is now:" << wdallocator->RefCnt()); // update linked list elmt->wdallocator = wdallocator; elmt->next = fgPoolAllocatorList; fgPoolAllocatorList = elmt; } // silently ignore misuse of this api } void MT_Storage::UnrefAllocator(Allocator *wdallocator) { StartTrace1(MT_Storage.UnrefAllocator, "Id:" << (wdallocator ? wdallocator->GetId() : -1L)); if (wdallocator) { // just to be robust wdallocator == 0 should not happen Initialize(); // used to initialize gsAllocatorInit Mutex MutexEntry me(*gsAllocatorInit); me.Use(); wdallocator->Unref(); Trace("refcount is now:" << wdallocator->RefCnt()); if ( wdallocator->RefCnt() <= 0 ) { // remove pool allocator AllocList *elmt = fgPoolAllocatorList; AllocList *prev = fgPoolAllocatorList; while (elmt && (elmt->wdallocator != wdallocator)) { prev = elmt; elmt = elmt->next; } if ( elmt ) { if ( elmt == fgPoolAllocatorList ) { fgPoolAllocatorList = elmt->next; } else { prev->next = elmt->next; } delete elmt->wdallocator; ::free(elmt); } } } // silently ignore misuse of this api } bool MT_Storage::RegisterThread(Allocator *wdallocator) { StartTrace(MT_Storage.RegisterThread); // can only be used once for the same thread Allocator *oldAllocator = 0; // determine which allocator to use FindAllocator(oldAllocator); if (!oldAllocator) { return ! SETTLSDATA(MT_Storage::fgAllocatorKey, wdallocator); } return false; } Allocator *MT_Storage::MakePoolAllocator(u_long poolStorageSize, u_long numOfPoolBucketSizes, long lPoolId) { StartTrace(MT_Storage.MakePoolAllocator); Allocator *newPoolAllocator = new MTPoolAllocator(lPoolId, poolStorageSize, numOfPoolBucketSizes); if (!newPoolAllocator) { String msg("allocation of PoolStorage: "); msg << (long)poolStorageSize << ", " << (long)numOfPoolBucketSizes << " failed"; SysLog::Error(msg); return newPoolAllocator; } if (newPoolAllocator->RefCnt() <= -1) { // we managed to allocate a pool allocator // but the object failed to allocate the pool storage delete newPoolAllocator; newPoolAllocator = 0; } return newPoolAllocator; } void MTStorageHooks::Finalize() { Initialize(); // used to initialize gsAllocatorInit Mutex // terminate pool allocators MutexEntry me(*gsAllocatorInit); me.Use(); while (fgPoolAllocatorList) { AllocList *elmt = fgPoolAllocatorList; delete elmt->wdallocator; fgPoolAllocatorList = elmt->next; ::free(elmt); } Storage::DoFinalize(); } Allocator *MTStorageHooks::Global() { return Storage::DoGlobal(); } #ifdef MEM_DEBUG MemTracker *MTStorageHooks::MakeMemTracker(const char *name) { return new MT_MemTracker(name); } #endif Allocator *MTStorageHooks::Current() { Allocator *wdallocator = 0; // Storage::Current() might be called before Storage::Global() // therefore need to initialize here too Storage::Initialize(); // determine which allocator to use FindAllocator(wdallocator); if (wdallocator) { return wdallocator; } return Storage::DoGlobal(); } void MTStorageHooks::Initialize() { if ( !fgInitialized ) { // need mutex??? not yet, we do not run MT // setup key used to store allocator in thread local storage if (THRKEYCREATE(MT_Storage::fgAllocatorKey, TLSDestructor)) { SysLog::Error("could not create TLS key"); } fgInitialized = true; Storage::DoInitialize(); } } <commit_msg>initializing message buffer<commit_after>/* * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland * All rights reserved. * * This library/application is free software; you can redistribute and/or modify it under the terms of * the license that is included with this library/application in the file license.txt. */ //--- interface include -------------------------------------------------------- #include "MT_Storage.h" //--- standard modules used ---------------------------------------------------- #include "Threads.h" #include "PoolAllocator.h" #include "SysLog.h" #include "Dbg.h" //--- c-library modules used --------------------------------------------------- #if !defined(WIN32) #include <stdlib.h> #endif THREADKEY MT_Storage::fgAllocatorKey = 0; #define FindAllocator(wdallocator) \ GETTLSDATA(MT_Storage::fgAllocatorKey, wdallocator, Allocator) void TLSDestructor(void *) { // destructor function for thread local storage } static Mutex *gsAllocatorInit = 0; // protect all data structures used by MT_Storage #if 0 #define TrackLockerInit(lockvar) , lockvar(0) #define TrackLockerDef(lockvar) volatile long lockvar class EXPORTDECL_MTFOUNDATION CurrLockerEntry { volatile long &frLockerId; public: CurrLockerEntry(volatile long &rLockerId, const char *pFile, long lLine) : frLockerId(rLockerId) { CheckException(pFile, lLine); frLockerId = Thread::MyId(); } ~CurrLockerEntry() { frLockerId = 0; } inline void CheckException(const char *pFile, long lLine) { if ( frLockerId != 0 ) { long lOther = frLockerId; char buf[256] = { 0 }; snprintf(buf, sizeof(buf), "\n%s:%d Another Locker entered already! otherThreadId:%d currentThreadId:%d\n", pFile, lLine, lOther, Thread::MyId()); SysLog::WriteToStderr(buf, strlen(buf)); } } }; #define TrackLocker(lockvar) CurrLockerEntry aEntry(lockvar, __FILE__, __LINE__) #else #define TrackLockerInit(lockvar) #define TrackLockerDef(lockvar) #define TrackLocker(lockvar) #endif class MTPoolAllocator: public PoolAllocator { public: //! create and initialize a pool allocator //! \param poolid use poolid to distinguish more than one pool //! \param poolSize size of pre-allocated pool in kBytes, default 1MByte MTPoolAllocator(long poolid, u_long poolSize = 1024, u_long maxKindOfBucket = 10) : PoolAllocator(poolid, poolSize, maxKindOfBucket) TrackLockerInit(fCurrLockerId) {} //! destroy a pool only if its empty, i.e. all allocated bytes are freed virtual ~MTPoolAllocator() { } //! implement hook for freeing memory virtual inline void Free(void *vp) { TrackLocker(fCurrLockerId); PoolAllocator::Free(vp); } protected: TrackLockerDef(fCurrLockerId); //!implement hook for allocating memory using bucketing virtual inline void *Alloc(u_long allocSize) { TrackLocker(fCurrLockerId); return PoolAllocator::Alloc(allocSize); } }; #ifdef MEM_DEBUG //------------- Utilities for Memory Tracking (multi threaded) -------------- MT_MemTracker::MT_MemTracker(const char *name) : MemTracker(name) { if ( !CREATEMUTEX(fMutex) ) { SysLog::Error("Mutex create failed"); } } MT_MemTracker::~MT_MemTracker() { if ( !DELETEMUTEX(fMutex) ) { SysLog::Error("Mutex delete failed"); } } void MT_MemTracker::TrackAlloc(u_long allocSz) { if ( !LOCKMUTEX(fMutex) ) { SysLog::Error("Mutex lock failed"); } MemTracker::TrackAlloc(allocSz); if ( !UNLOCKMUTEX(fMutex) ) { SysLog::Error("Mutex unlock failed"); } } void MT_MemTracker::TrackFree(u_long allocSz) { if ( !LOCKMUTEX(fMutex) ) { SysLog::Error("Mutex lock failed"); } MemTracker::TrackFree(allocSz); if ( !UNLOCKMUTEX(fMutex) ) { SysLog::Error("Mutex unlock failed"); } } l_long MT_MemTracker::CurrentlyAllocated() { l_long l; if ( !LOCKMUTEX(fMutex) ) { SysLog::Error("Mutex lock failed"); } l = fAllocated; if ( !UNLOCKMUTEX(fMutex) ) { SysLog::Error("Mutex lock failed"); } return l; } void MT_MemTracker::PrintStatistic() { if ( !LOCKMUTEX(fMutex) ) { SysLog::Error("Mutex lock failed"); } MemTracker::PrintStatistic(); if ( !UNLOCKMUTEX(fMutex) ) { SysLog::Error("Mutex lock failed"); } } #endif class EXPORTDECL_MTFOUNDATION MTStorageHooks : public StorageHooks { public: virtual void Initialize(); virtual void Finalize(); virtual Allocator *Global(); virtual Allocator *Current(); #ifdef MEM_DEBUG virtual MemTracker *MakeMemTracker(const char *name); #endif static bool fgInitialized; }; static MTStorageHooks sgMTHooks; //---- MT_Storage ------------------------------------------ struct AllocList { Allocator *wdallocator; AllocList *next; }; static AllocList *fgPoolAllocatorList = 0; bool MTStorageHooks::fgInitialized = false; // flag for memorizing initialization void MT_Storage::Initialize() { StartTrace(MT_Storage.Initialize); // must be called before threading is activated static bool once = false; if (!once) { gsAllocatorInit = new Mutex("AllocatorInit"); Storage::SetHooks(&sgMTHooks); Storage::Initialize(); // re-init with MT hook #ifdef MEM_DEBUG // switch to thread safe memory tracker Allocator *a = Storage::Global(); if (a) { a->ReplaceMemTracker(Storage::MakeMemTracker("MTGlobalAllocator")); } #endif once = true; } } void MT_Storage::RefAllocator(Allocator *wdallocator) { StartTrace1(MT_Storage.RefAllocator, "Id:" << (wdallocator ? wdallocator->GetId() : -1L)); if ( wdallocator ) { Initialize(); // used to initialize gsAllocatorInit Mutex // in mt case we need to control ref counting with mutexes MutexEntry me(*gsAllocatorInit); me.Use(); AllocList *elmt = (AllocList *)::calloc(1, sizeof(AllocList)); // catch memory allocation problem if (!elmt) { static const char crashmsg[] = "FATAL: MT_Storage::RefAllocator calloc failed. I will crash :-(\n"; SysLog::WriteToStderr(crashmsg, sizeof(crashmsg)); SysLog::Error("allocation failed for RefAllocator"); return; } // normal case everything ok wdallocator->Ref(); Trace("refcount is now:" << wdallocator->RefCnt()); // update linked list elmt->wdallocator = wdallocator; elmt->next = fgPoolAllocatorList; fgPoolAllocatorList = elmt; } // silently ignore misuse of this api } void MT_Storage::UnrefAllocator(Allocator *wdallocator) { StartTrace1(MT_Storage.UnrefAllocator, "Id:" << (wdallocator ? wdallocator->GetId() : -1L)); if (wdallocator) { // just to be robust wdallocator == 0 should not happen Initialize(); // used to initialize gsAllocatorInit Mutex MutexEntry me(*gsAllocatorInit); me.Use(); wdallocator->Unref(); Trace("refcount is now:" << wdallocator->RefCnt()); if ( wdallocator->RefCnt() <= 0 ) { // remove pool allocator AllocList *elmt = fgPoolAllocatorList; AllocList *prev = fgPoolAllocatorList; while (elmt && (elmt->wdallocator != wdallocator)) { prev = elmt; elmt = elmt->next; } if ( elmt ) { if ( elmt == fgPoolAllocatorList ) { fgPoolAllocatorList = elmt->next; } else { prev->next = elmt->next; } delete elmt->wdallocator; ::free(elmt); } } } // silently ignore misuse of this api } bool MT_Storage::RegisterThread(Allocator *wdallocator) { StartTrace(MT_Storage.RegisterThread); // can only be used once for the same thread Allocator *oldAllocator = 0; // determine which allocator to use FindAllocator(oldAllocator); if (!oldAllocator) { return ! SETTLSDATA(MT_Storage::fgAllocatorKey, wdallocator); } return false; } Allocator *MT_Storage::MakePoolAllocator(u_long poolStorageSize, u_long numOfPoolBucketSizes, long lPoolId) { StartTrace(MT_Storage.MakePoolAllocator); Allocator *newPoolAllocator = new MTPoolAllocator(lPoolId, poolStorageSize, numOfPoolBucketSizes); if (!newPoolAllocator) { String msg("allocation of PoolStorage: "); msg << (long)poolStorageSize << ", " << (long)numOfPoolBucketSizes << " failed"; SysLog::Error(msg); return newPoolAllocator; } if (newPoolAllocator->RefCnt() <= -1) { // we managed to allocate a pool allocator // but the object failed to allocate the pool storage delete newPoolAllocator; newPoolAllocator = 0; } return newPoolAllocator; } void MTStorageHooks::Finalize() { Initialize(); // used to initialize gsAllocatorInit Mutex // terminate pool allocators MutexEntry me(*gsAllocatorInit); me.Use(); while (fgPoolAllocatorList) { AllocList *elmt = fgPoolAllocatorList; delete elmt->wdallocator; fgPoolAllocatorList = elmt->next; ::free(elmt); } Storage::DoFinalize(); } Allocator *MTStorageHooks::Global() { return Storage::DoGlobal(); } #ifdef MEM_DEBUG MemTracker *MTStorageHooks::MakeMemTracker(const char *name) { return new MT_MemTracker(name); } #endif Allocator *MTStorageHooks::Current() { Allocator *wdallocator = 0; // Storage::Current() might be called before Storage::Global() // therefore need to initialize here too Storage::Initialize(); // determine which allocator to use FindAllocator(wdallocator); if (wdallocator) { return wdallocator; } return Storage::DoGlobal(); } void MTStorageHooks::Initialize() { if ( !fgInitialized ) { // need mutex??? not yet, we do not run MT // setup key used to store allocator in thread local storage if (THRKEYCREATE(MT_Storage::fgAllocatorKey, TLSDestructor)) { SysLog::Error("could not create TLS key"); } fgInitialized = true; Storage::DoInitialize(); } } <|endoftext|>
<commit_before>#include "SystemCPU.hpp" #include <iostream> using namespace std; int main() { while (true) { SystemCpu syscpu; cout << syscpu.getCpuModeInfo() << endl; } system("pause"); } TCHAR* SystemCpu::getCpuModeInfo() { HKEY key; TCHAR data[1024]; DWORD dwSize; dwSize = sizeof(data) / sizeof(TCHAR); if (RegOpenKey(HKEY_LOCAL_MACHINE, TEXT("HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0"), &key) != ERROR_SUCCESS) throw -1; if (RegQueryValueEx(key, TEXT("ProcessorNameString"), NULL, NULL, (LPBYTE)data, &dwSize) != ERROR_SUCCESS) throw -2; RegCloseKey(key); return data; } int SystemCpu::getUsage(double &val) { FILETIME sysIdle, sysKernel, sysUser; // sysKernel include IdleTime if (GetSystemTimes(&sysIdle, &sysKernel, &sysUser) == 0) // GetSystemTimes func FAILED return value is zero; return 0; if (prevSysIdle.dwLowDateTime != 0 && prevSysIdle.dwHighDateTime != 0) { ULONGLONG sysIdleDiff, sysKernelDiff, sysUserDiff; sysIdleDiff = SubtractTimes(sysIdle, prevSysIdle); sysKernelDiff = SubtractTimes(sysKernel, prevSysKernel); sysUserDiff = SubtractTimes(sysUser, prevSysUser); ULONGLONG sysTotal = sysKernelDiff + sysUserDiff; ULONGLONG kernelTotal = sysKernelDiff - sysIdleDiff; // kernelTime - IdleTime = kernelTime, because sysKernel include IdleTime if (sysTotal > 0) // sometimes kernelTime > idleTime val = (double)(((kernelTotal + sysUserDiff) * 100.0) / sysTotal); } prevSysIdle = sysIdle; prevSysKernel = sysKernel; prevSysUser = sysUser; return 1; } // 100 - total = IDLE CPU Usage int SystemCpu::getIdleUsage(double &val) { double curUsage; if (getUsage(curUsage) == 0) return 0; val = 100.0 - curUsage; return 1; } // TIME DIFF FUNC ULONGLONG SystemCpu::SubtractTimes(const FILETIME one, const FILETIME two) { LARGE_INTEGER a, b; a.LowPart = one.dwLowDateTime; a.HighPart = one.dwHighDateTime; b.LowPart = two.dwLowDateTime; b.HighPart = two.dwHighDateTime; return a.QuadPart - b.QuadPart; }<commit_msg>main func remove in SystemCpu.cpp<commit_after>#include "SystemCPU.hpp" TCHAR* SystemCpu::getCpuModeInfo() { HKEY key; TCHAR data[1024]; DWORD dwSize; dwSize = sizeof(data) / sizeof(TCHAR); if (RegOpenKey(HKEY_LOCAL_MACHINE, TEXT("HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0"), &key) != ERROR_SUCCESS) throw -1; if (RegQueryValueEx(key, TEXT("ProcessorNameString"), NULL, NULL, (LPBYTE)data, &dwSize) != ERROR_SUCCESS) throw -2; RegCloseKey(key); return data; } int SystemCpu::getUsage(double &val) { FILETIME sysIdle, sysKernel, sysUser; // sysKernel include IdleTime if (GetSystemTimes(&sysIdle, &sysKernel, &sysUser) == 0) // GetSystemTimes func FAILED return value is zero; return 0; if (prevSysIdle.dwLowDateTime != 0 && prevSysIdle.dwHighDateTime != 0) { ULONGLONG sysIdleDiff, sysKernelDiff, sysUserDiff; sysIdleDiff = SubtractTimes(sysIdle, prevSysIdle); sysKernelDiff = SubtractTimes(sysKernel, prevSysKernel); sysUserDiff = SubtractTimes(sysUser, prevSysUser); ULONGLONG sysTotal = sysKernelDiff + sysUserDiff; ULONGLONG kernelTotal = sysKernelDiff - sysIdleDiff; // kernelTime - IdleTime = kernelTime, because sysKernel include IdleTime if (sysTotal > 0) // sometimes kernelTime > idleTime val = (double)(((kernelTotal + sysUserDiff) * 100.0) / sysTotal); } prevSysIdle = sysIdle; prevSysKernel = sysKernel; prevSysUser = sysUser; return 1; } // 100 - total = IDLE CPU Usage int SystemCpu::getIdleUsage(double &val) { double curUsage; if (getUsage(curUsage) == 0) return 0; val = 100.0 - curUsage; return 1; } // TIME DIFF FUNC ULONGLONG SystemCpu::SubtractTimes(const FILETIME one, const FILETIME two) { LARGE_INTEGER a, b; a.LowPart = one.dwLowDateTime; a.HighPart = one.dwHighDateTime; b.LowPart = two.dwLowDateTime; b.HighPart = two.dwHighDateTime; return a.QuadPart - b.QuadPart; }<|endoftext|>
<commit_before>#include "results.h" #include "engine.h" #include <cstdint> #include <string> #include <vector> #include <napi.h> // all/mask percent to js Napi::Array ToJs(const Napi::Env &env, const std::string &name, const uint_fast32_t diffsPerc, const uint_fast32_t percentResult) { Napi::Array resultsJs = Napi::Array::New(env); if (percentResult >= diffsPerc) { Napi::Object obj = Napi::Object::New(env); obj.Set("name", name); obj.Set("percent", percentResult); resultsJs.Set(0u, obj); } return resultsJs; } // regions percent to js Napi::Array ToJs(const Napi::Env &env, const uint_fast32_t regionsLen, const std::vector<Region> &regionVec, const std::vector<uint_fast32_t> &percentResultVec) { Napi::Array resultsJs = Napi::Array::New(env); for (uint_fast32_t r = 0, j = 0, percent = 0; r < regionsLen; r++) { percent = percentResultVec[r]; Region region = regionVec[r]; if (region.percent > percent) continue; Napi::Object obj = Napi::Object::New(env); obj.Set("name", region.name); obj.Set("percent", percent); resultsJs.Set(j++, obj); } return resultsJs; } // all/mask bounds to js Napi::Array ToJs(const Napi::Env &env, const std::string &name, const uint_fast32_t diffsPerc, const BoundsResult &boundsResult) { Napi::Array resultsJs = Napi::Array::New(env); if (boundsResult.percent >= diffsPerc) { Napi::Object obj = Napi::Object::New(env); obj.Set("name", name); obj.Set("percent", boundsResult.percent); obj.Set("minX", boundsResult.minX); obj.Set("maxX", boundsResult.maxX); obj.Set("minY", boundsResult.minY); obj.Set("maxY", boundsResult.maxY); resultsJs.Set(0u, obj); } return resultsJs; } // regions bounds to js Napi::Array ToJs(const Napi::Env &env, const uint_fast32_t regionsLen, const std::vector<Region> &regionVec, const std::vector<BoundsResult> &boundsResultVec) { Napi::Array resultsJs = Napi::Array::New(env); for (uint_fast32_t r = 0, j = 0; r < regionsLen; r++) { BoundsResult boundsResult = boundsResultVec[r]; Region region = regionVec[r]; if (region.percent > boundsResult.percent) continue; Napi::Object obj = Napi::Object::New(env); obj.Set("name", region.name); obj.Set("percent", boundsResult.percent); obj.Set("minX", boundsResult.minX); obj.Set("maxX", boundsResult.maxX); obj.Set("minY", boundsResult.minY); obj.Set("maxY", boundsResult.maxY); resultsJs.Set(j++, obj); } return resultsJs; }<commit_msg>removed temp var<commit_after>#include "results.h" #include "engine.h" #include <cstdint> #include <string> #include <vector> #include <napi.h> // all/mask percent to js Napi::Array ToJs(const Napi::Env &env, const std::string &name, const uint_fast32_t diffsPerc, const uint_fast32_t percentResult) { Napi::Array resultsJs = Napi::Array::New(env); if (percentResult >= diffsPerc) { Napi::Object obj = Napi::Object::New(env); obj.Set("name", name); obj.Set("percent", percentResult); resultsJs.Set(0u, obj); } return resultsJs; } // regions percent to js Napi::Array ToJs(const Napi::Env &env, const uint_fast32_t regionsLen, const std::vector<Region> &regionVec, const std::vector<uint_fast32_t> &percentResultVec) { Napi::Array resultsJs = Napi::Array::New(env); for (uint_fast32_t r = 0, j = 0; r < regionsLen; r++) { if (regionVec[r].percent > percentResultVec[r]) continue; Napi::Object obj = Napi::Object::New(env); obj.Set("name", regionVec[r].name); obj.Set("percent", percentResultVec[r]); resultsJs.Set(j++, obj); } return resultsJs; } // all/mask bounds to js Napi::Array ToJs(const Napi::Env &env, const std::string &name, const uint_fast32_t diffsPerc, const BoundsResult &boundsResult) { Napi::Array resultsJs = Napi::Array::New(env); if (boundsResult.percent >= diffsPerc) { Napi::Object obj = Napi::Object::New(env); obj.Set("name", name); obj.Set("percent", boundsResult.percent); obj.Set("minX", boundsResult.minX); obj.Set("maxX", boundsResult.maxX); obj.Set("minY", boundsResult.minY); obj.Set("maxY", boundsResult.maxY); resultsJs.Set(0u, obj); } return resultsJs; } // regions bounds to js Napi::Array ToJs(const Napi::Env &env, const uint_fast32_t regionsLen, const std::vector<Region> &regionVec, const std::vector<BoundsResult> &boundsResultVec) { Napi::Array resultsJs = Napi::Array::New(env); for (uint_fast32_t r = 0, j = 0; r < regionsLen; r++) { if (regionVec[r].percent > boundsResultVec[r].percent) continue; Napi::Object obj = Napi::Object::New(env); obj.Set("name", regionVec[r].name); obj.Set("percent", boundsResultVec[r].percent); obj.Set("minX", boundsResultVec[r].minX); obj.Set("maxX", boundsResultVec[r].maxX); obj.Set("minY", boundsResultVec[r].minY); obj.Set("maxY", boundsResultVec[r].maxY); resultsJs.Set(j++, obj); } return resultsJs; }<|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 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 MAPNIK_CSV_UTILS_DATASOURCE_HPP #define MAPNIK_CSV_UTILS_DATASOURCE_HPP // mapnik #include <mapnik/debug.hpp> #include <mapnik/geometry.hpp> #include <mapnik/geometry_correct.hpp> #include <mapnik/wkt/wkt_factory.hpp> #include <mapnik/json/geometry_parser.hpp> #include <mapnik/util/conversions.hpp> #include <mapnik/csv/csv_grammar.hpp> #include <mapnik/util/trim.hpp> #include <mapnik/datasource.hpp> #pragma GCC diagnostic push #include <mapnik/warning_ignore.hpp> #include <boost/algorithm/string.hpp> #pragma GCC diagnostic pop #include <string> #include <cstdio> #include <algorithm> namespace csv_utils { static const mapnik::csv_line_grammar<char const*> line_g; static const mapnik::csv_white_space_skipper skipper{}; template <typename Iterator> static mapnik::csv_line parse_line(Iterator start, Iterator end, char separator, char quote, std::size_t num_columns) { mapnik::csv_line values; if (num_columns > 0) values.reserve(num_columns); if (!boost::spirit::qi::phrase_parse(start, end, (line_g)(separator, quote), skipper, values)) { throw mapnik::datasource_exception("Failed to parse CSV line:\n" + std::string(start, end)); } return values; } static inline mapnik::csv_line parse_line(std::string const& line_str, char separator, char quote) { auto start = line_str.c_str(); auto end = start + line_str.length(); return parse_line(start, end, separator, quote, 0); } static inline bool is_likely_number(std::string const& value) { return (std::strspn( value.c_str(), "e-.+0123456789" ) == value.size()); } struct ignore_case_equal_pred { bool operator () (unsigned char a, unsigned char b) const { return std::tolower(a) == std::tolower(b); } }; inline bool ignore_case_equal(std::string const& s0, std::string const& s1) { return std::equal(s0.begin(), s0.end(), s1.begin(), ignore_case_equal_pred()); } template <class CharT, class Traits, class Allocator> std::basic_istream<CharT, Traits>& getline_csv(std::istream& is, std::basic_string<CharT,Traits,Allocator>& s, CharT delim, CharT quote) { typename std::basic_string<CharT,Traits,Allocator>::size_type nread = 0; typename std::basic_istream<CharT, Traits>::sentry sentry(is, true); if (sentry) { std::basic_streambuf<CharT, Traits>* buf = is.rdbuf(); s.clear(); bool has_quote = false; while (nread < s.max_size()) { int c1 = buf->sbumpc(); if (Traits::eq_int_type(c1, Traits::eof())) { is.setstate(std::ios_base::eofbit); break; } else { ++nread; CharT c = Traits::to_char_type(c1); if (Traits::eq(c, quote)) has_quote = !has_quote; if (!Traits::eq(c, delim) || has_quote) s.push_back(c); else break;// Character is extracted but not appended. } } } if (nread == 0 || nread >= s.max_size()) is.setstate(std::ios_base::failbit); return is; } } namespace detail { template <typename T> std::size_t file_length(T & stream) { stream.seekg(0, std::ios::end); return stream.tellg(); } template <typename T> std::tuple<char, bool, char, char> autodect_csv_flavour(T & stream, std::size_t file_length) { // autodetect newlines/quotes/separators char newline = '\n'; // default bool has_newline = false; bool has_quote = false; char quote = '"'; // default char separator = ','; // default // local counters int num_commas = 0; int num_tabs = 0; int num_pipes = 0; int num_semicolons = 0; static std::size_t const max_size = 4000; std::size_t size = std::min(file_length, max_size); std::vector<char> buffer; buffer.resize(size); stream.read(buffer.data(), size); for (auto c : buffer) { switch (c) { case '\r': newline = '\r'; has_newline = true; break; case '\n': has_newline = true; break; case '\'': case '"': if (!has_quote) { quote = c; has_quote = true; } break; case ',': if (!has_newline) ++num_commas; break; case '\t': if (!has_newline) ++num_tabs; break; case '|': if (!has_newline) ++num_pipes; break; case ';': if (!has_newline) ++num_semicolons; break; } } // detect separator if (num_tabs > 0 && num_tabs > num_commas) { separator = '\t'; MAPNIK_LOG_DEBUG(csv) << "csv_datasource: auto detected tab separator"; } else // pipes/semicolons { if (num_pipes > num_commas) { separator = '|'; MAPNIK_LOG_DEBUG(csv) << "csv_datasource: auto detected '|' separator"; } else if (num_semicolons > num_commas) { separator = ';'; MAPNIK_LOG_DEBUG(csv) << "csv_datasource: auto detected ';' separator"; } } if (has_newline) { std::istringstream ss(buffer.data()); std::size_t num_columns = 0; for (std::string line; csv_utils::getline_csv(ss, line, newline, quote) && !ss.eof(); ) { if (line.size() == 0) continue; auto columns = csv_utils::parse_line(line, separator, quote); if (num_columns > 0 && num_columns != columns.size()) { quote = (quote == '"') ? '\'' : '"'; break; } num_columns = columns.size(); } } return std::make_tuple(newline, has_newline, separator, quote); } struct geometry_column_locator { geometry_column_locator() : type(UNKNOWN), index(-1), index2(-1) {} enum { UNKNOWN = 0, WKT, GEOJSON, LON_LAT } type; std::size_t index; std::size_t index2; }; static inline void locate_geometry_column(std::string const& header, std::size_t index, geometry_column_locator & locator) { std::string lower_val(header); std::transform(lower_val.begin(), lower_val.end(), lower_val.begin(), ::tolower); if (lower_val == "wkt" || (lower_val.find("geom") != std::string::npos)) { locator.type = geometry_column_locator::WKT; locator.index = index; } else if (lower_val == "geojson") { locator.type = geometry_column_locator::GEOJSON; locator.index = index; } else if (lower_val == "x" || lower_val == "lon" || lower_val == "lng" || lower_val == "long" || (lower_val.find("longitude") != std::string::npos)) { locator.index = index; locator.type = geometry_column_locator::LON_LAT; } else if (lower_val == "y" || lower_val == "lat" || (lower_val.find("latitude") != std::string::npos)) { locator.index2 = index; locator.type = geometry_column_locator::LON_LAT; } } static inline bool valid(geometry_column_locator const& locator, std::size_t max_size) { if (locator.type == geometry_column_locator::UNKNOWN) return false; if (locator.index >= max_size) return false; if (locator.type == geometry_column_locator::LON_LAT && locator.index2 >= max_size) return false; return true; } static inline mapnik::geometry::geometry<double> extract_geometry(std::vector<std::string> const& row, geometry_column_locator const& locator) { mapnik::geometry::geometry<double> geom; if (locator.type == geometry_column_locator::WKT) { auto wkt_value = row.at(locator.index); if (mapnik::from_wkt(wkt_value, geom)) { // correct orientations .. mapnik::geometry::correct(geom); } else { throw mapnik::datasource_exception("Failed to parse WKT: '" + wkt_value + "'"); } } else if (locator.type == geometry_column_locator::GEOJSON) { auto json_value = row.at(locator.index); if (!mapnik::json::from_geojson(json_value, geom)) { throw mapnik::datasource_exception("Failed to parse GeoJSON: '" + json_value + "'"); } } else if (locator.type == geometry_column_locator::LON_LAT) { double x, y; auto long_value = row.at(locator.index); auto lat_value = row.at(locator.index2); if (!mapnik::util::string2double(long_value,x)) { throw mapnik::datasource_exception("Failed to parse Longitude: '" + long_value + "'"); } if (!mapnik::util::string2double(lat_value,y)) { throw mapnik::datasource_exception("Failed to parse Latitude: '" + lat_value + "'"); } geom = mapnik::geometry::point<double>(x,y); } return geom; } template <typename Feature, typename Headers, typename Values, typename Locator, typename Transcoder> void process_properties(Feature & feature, Headers const& headers, Values const& values, Locator const& locator, Transcoder const& tr) { auto val_beg = values.begin(); auto val_end = values.end(); auto num_headers = headers.size(); for (std::size_t i = 0; i < num_headers; ++i) { std::string const& fld_name = headers.at(i); if (val_beg == val_end) { feature.put(fld_name,tr.transcode("")); continue; } std::string value = mapnik::util::trim_copy(*val_beg++); int value_length = value.length(); if (locator.index == i && (locator.type == detail::geometry_column_locator::WKT || locator.type == detail::geometry_column_locator::GEOJSON) ) continue; bool matched = false; bool has_dot = value.find(".") != std::string::npos; if (value.empty() || (value_length > 20) || (value_length > 1 && !has_dot && value[0] == '0')) { matched = true; feature.put(fld_name,std::move(tr.transcode(value.c_str()))); } else if (csv_utils::is_likely_number(value)) { bool has_e = value.find("e") != std::string::npos; if (has_dot || has_e) { double float_val = 0.0; if (mapnik::util::string2double(value,float_val)) { matched = true; feature.put(fld_name,float_val); } } else { mapnik::value_integer int_val = 0; if (mapnik::util::string2int(value,int_val)) { matched = true; feature.put(fld_name,int_val); } } } if (!matched) { if (csv_utils::ignore_case_equal(value, "true")) { feature.put(fld_name, true); } else if (csv_utils::ignore_case_equal(value, "false")) { feature.put(fld_name, false); } else // fallback to string { feature.put(fld_name,std::move(tr.transcode(value.c_str()))); } } } } }// ns detail #endif // MAPNIK_CSV_UTILS_DATASOURCE_HPP <commit_msg>csv_utils - fix istringstream initialiser by using explicit iterators pair std::string ctor<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 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 MAPNIK_CSV_UTILS_DATASOURCE_HPP #define MAPNIK_CSV_UTILS_DATASOURCE_HPP // mapnik #include <mapnik/debug.hpp> #include <mapnik/geometry.hpp> #include <mapnik/geometry_correct.hpp> #include <mapnik/wkt/wkt_factory.hpp> #include <mapnik/json/geometry_parser.hpp> #include <mapnik/util/conversions.hpp> #include <mapnik/csv/csv_grammar.hpp> #include <mapnik/util/trim.hpp> #include <mapnik/datasource.hpp> #pragma GCC diagnostic push #include <mapnik/warning_ignore.hpp> #include <boost/algorithm/string.hpp> #pragma GCC diagnostic pop #include <string> #include <cstdio> #include <algorithm> namespace csv_utils { static const mapnik::csv_line_grammar<char const*> line_g; static const mapnik::csv_white_space_skipper skipper{}; template <typename Iterator> static mapnik::csv_line parse_line(Iterator start, Iterator end, char separator, char quote, std::size_t num_columns) { mapnik::csv_line values; if (num_columns > 0) values.reserve(num_columns); if (!boost::spirit::qi::phrase_parse(start, end, (line_g)(separator, quote), skipper, values)) { throw mapnik::datasource_exception("Failed to parse CSV line:\n" + std::string(start, end)); } return values; } static inline mapnik::csv_line parse_line(std::string const& line_str, char separator, char quote) { auto start = line_str.c_str(); auto end = start + line_str.length(); return parse_line(start, end, separator, quote, 0); } static inline bool is_likely_number(std::string const& value) { return (std::strspn( value.c_str(), "e-.+0123456789" ) == value.size()); } struct ignore_case_equal_pred { bool operator () (unsigned char a, unsigned char b) const { return std::tolower(a) == std::tolower(b); } }; inline bool ignore_case_equal(std::string const& s0, std::string const& s1) { return std::equal(s0.begin(), s0.end(), s1.begin(), ignore_case_equal_pred()); } template <class CharT, class Traits, class Allocator> std::basic_istream<CharT, Traits>& getline_csv(std::istream& is, std::basic_string<CharT,Traits,Allocator>& s, CharT delim, CharT quote) { typename std::basic_string<CharT,Traits,Allocator>::size_type nread = 0; typename std::basic_istream<CharT, Traits>::sentry sentry(is, true); if (sentry) { std::basic_streambuf<CharT, Traits>* buf = is.rdbuf(); s.clear(); bool has_quote = false; while (nread < s.max_size()) { int c1 = buf->sbumpc(); if (Traits::eq_int_type(c1, Traits::eof())) { is.setstate(std::ios_base::eofbit); break; } else { ++nread; CharT c = Traits::to_char_type(c1); if (Traits::eq(c, quote)) has_quote = !has_quote; if (!Traits::eq(c, delim) || has_quote) s.push_back(c); else break;// Character is extracted but not appended. } } } if (nread == 0 || nread >= s.max_size()) is.setstate(std::ios_base::failbit); return is; } } namespace detail { template <typename T> std::size_t file_length(T & stream) { stream.seekg(0, std::ios::end); return stream.tellg(); } template <typename T> std::tuple<char, bool, char, char> autodect_csv_flavour(T & stream, std::size_t file_length) { // autodetect newlines/quotes/separators char newline = '\n'; // default bool has_newline = false; bool has_quote = false; char quote = '"'; // default char separator = ','; // default // local counters int num_commas = 0; int num_tabs = 0; int num_pipes = 0; int num_semicolons = 0; static std::size_t const max_size = 4000; std::size_t size = std::min(file_length, max_size); std::vector<char> buffer; buffer.resize(size); stream.read(buffer.data(), size); for (auto c : buffer) { switch (c) { case '\r': newline = '\r'; has_newline = true; break; case '\n': has_newline = true; break; case '\'': case '"': if (!has_quote) { quote = c; has_quote = true; } break; case ',': if (!has_newline) ++num_commas; break; case '\t': if (!has_newline) ++num_tabs; break; case '|': if (!has_newline) ++num_pipes; break; case ';': if (!has_newline) ++num_semicolons; break; } } // detect separator if (num_tabs > 0 && num_tabs > num_commas) { separator = '\t'; MAPNIK_LOG_DEBUG(csv) << "csv_datasource: auto detected tab separator"; } else // pipes/semicolons { if (num_pipes > num_commas) { separator = '|'; MAPNIK_LOG_DEBUG(csv) << "csv_datasource: auto detected '|' separator"; } else if (num_semicolons > num_commas) { separator = ';'; MAPNIK_LOG_DEBUG(csv) << "csv_datasource: auto detected ';' separator"; } } if (has_newline) { std::istringstream ss(std::string(buffer.begin(), buffer.end())); std::size_t num_columns = 0; for (std::string line; csv_utils::getline_csv(ss, line, newline, quote) && !ss.eof(); ) { if (line.size() == 0) continue; auto columns = csv_utils::parse_line(line, separator, quote); if (num_columns > 0 && num_columns != columns.size()) { quote = (quote == '"') ? '\'' : '"'; break; } num_columns = columns.size(); } } return std::make_tuple(newline, has_newline, separator, quote); } struct geometry_column_locator { geometry_column_locator() : type(UNKNOWN), index(-1), index2(-1) {} enum { UNKNOWN = 0, WKT, GEOJSON, LON_LAT } type; std::size_t index; std::size_t index2; }; static inline void locate_geometry_column(std::string const& header, std::size_t index, geometry_column_locator & locator) { std::string lower_val(header); std::transform(lower_val.begin(), lower_val.end(), lower_val.begin(), ::tolower); if (lower_val == "wkt" || (lower_val.find("geom") != std::string::npos)) { locator.type = geometry_column_locator::WKT; locator.index = index; } else if (lower_val == "geojson") { locator.type = geometry_column_locator::GEOJSON; locator.index = index; } else if (lower_val == "x" || lower_val == "lon" || lower_val == "lng" || lower_val == "long" || (lower_val.find("longitude") != std::string::npos)) { locator.index = index; locator.type = geometry_column_locator::LON_LAT; } else if (lower_val == "y" || lower_val == "lat" || (lower_val.find("latitude") != std::string::npos)) { locator.index2 = index; locator.type = geometry_column_locator::LON_LAT; } } static inline bool valid(geometry_column_locator const& locator, std::size_t max_size) { if (locator.type == geometry_column_locator::UNKNOWN) return false; if (locator.index >= max_size) return false; if (locator.type == geometry_column_locator::LON_LAT && locator.index2 >= max_size) return false; return true; } static inline mapnik::geometry::geometry<double> extract_geometry(std::vector<std::string> const& row, geometry_column_locator const& locator) { mapnik::geometry::geometry<double> geom; if (locator.type == geometry_column_locator::WKT) { auto wkt_value = row.at(locator.index); if (mapnik::from_wkt(wkt_value, geom)) { // correct orientations .. mapnik::geometry::correct(geom); } else { throw mapnik::datasource_exception("Failed to parse WKT: '" + wkt_value + "'"); } } else if (locator.type == geometry_column_locator::GEOJSON) { auto json_value = row.at(locator.index); if (!mapnik::json::from_geojson(json_value, geom)) { throw mapnik::datasource_exception("Failed to parse GeoJSON: '" + json_value + "'"); } } else if (locator.type == geometry_column_locator::LON_LAT) { double x, y; auto long_value = row.at(locator.index); auto lat_value = row.at(locator.index2); if (!mapnik::util::string2double(long_value,x)) { throw mapnik::datasource_exception("Failed to parse Longitude: '" + long_value + "'"); } if (!mapnik::util::string2double(lat_value,y)) { throw mapnik::datasource_exception("Failed to parse Latitude: '" + lat_value + "'"); } geom = mapnik::geometry::point<double>(x,y); } return geom; } template <typename Feature, typename Headers, typename Values, typename Locator, typename Transcoder> void process_properties(Feature & feature, Headers const& headers, Values const& values, Locator const& locator, Transcoder const& tr) { auto val_beg = values.begin(); auto val_end = values.end(); auto num_headers = headers.size(); for (std::size_t i = 0; i < num_headers; ++i) { std::string const& fld_name = headers.at(i); if (val_beg == val_end) { feature.put(fld_name,tr.transcode("")); continue; } std::string value = mapnik::util::trim_copy(*val_beg++); int value_length = value.length(); if (locator.index == i && (locator.type == detail::geometry_column_locator::WKT || locator.type == detail::geometry_column_locator::GEOJSON) ) continue; bool matched = false; bool has_dot = value.find(".") != std::string::npos; if (value.empty() || (value_length > 20) || (value_length > 1 && !has_dot && value[0] == '0')) { matched = true; feature.put(fld_name,std::move(tr.transcode(value.c_str()))); } else if (csv_utils::is_likely_number(value)) { bool has_e = value.find("e") != std::string::npos; if (has_dot || has_e) { double float_val = 0.0; if (mapnik::util::string2double(value,float_val)) { matched = true; feature.put(fld_name,float_val); } } else { mapnik::value_integer int_val = 0; if (mapnik::util::string2int(value,int_val)) { matched = true; feature.put(fld_name,int_val); } } } if (!matched) { if (csv_utils::ignore_case_equal(value, "true")) { feature.put(fld_name, true); } else if (csv_utils::ignore_case_equal(value, "false")) { feature.put(fld_name, false); } else // fallback to string { feature.put(fld_name,std::move(tr.transcode(value.c_str()))); } } } } }// ns detail #endif // MAPNIK_CSV_UTILS_DATASOURCE_HPP <|endoftext|>