text
stringlengths
54
60.6k
<commit_before>// Copyright 2016-2019 Envoy Project Authors // Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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. // NOLINT(namespace-envoy) #include "proxy_wasm_intrinsics.h" // Required Proxy-Wasm ABI version. extern "C" PROXY_WASM_KEEPALIVE void proxy_abi_version_0_2_0() {} static std::unordered_map<std::string, RootFactory> *root_factories = nullptr; static std::unordered_map<std::string, ContextFactory> *context_factories = nullptr; static std::unordered_map<int32_t, std::unique_ptr<ContextBase>> context_map; static std::unordered_map<std::string, RootContext *> root_context_map; RegisterContextFactory::RegisterContextFactory(ContextFactory context_factory, RootFactory root_factory, std::string_view root_id) { if (!root_factories) { root_factories = new std::unordered_map<std::string, RootFactory>; context_factories = new std::unordered_map<std::string, ContextFactory>; } if (context_factory) (*context_factories)[std::string(root_id)] = context_factory; if (root_factory) (*root_factories)[std::string(root_id)] = root_factory; } static Context *ensureContext(uint32_t context_id, uint32_t root_context_id) { auto e = context_map.insert(std::make_pair(context_id, nullptr)); if (e.second) { RootContext *root = context_map[root_context_id].get()->asRoot(); std::string root_id = std::string(root->root_id()); if (!context_factories) { e.first->second = std::make_unique<Context>(context_id, root); return e.first->second->asContext(); } auto factory = context_factories->find(root_id); if (factory == context_factories->end()) { e.first->second = std::make_unique<Context>(context_id, root); return e.first->second->asContext(); } else { e.first->second = factory->second(context_id, root); } } return e.first->second->asContext(); } static RootContext *ensureRootContext(uint32_t context_id) { auto it = context_map.find(context_id); if (it != context_map.end()) { return it->second->asRoot(); } const char *root_id_ptr = nullptr; size_t root_id_size = 0; CHECK_RESULT(proxy_get_property("plugin_root_id", sizeof("plugin_root_id") - 1, &root_id_ptr, &root_id_size)); auto root_id = std::make_unique<WasmData>(root_id_ptr, root_id_size); auto root_id_string = root_id->toString(); if (!root_factories) { auto context = std::make_unique<RootContext>(context_id, root_id->view()); RootContext *root_context = context->asRoot(); context_map[context_id] = std::move(context); root_context_map[root_id_string] = root_context; return root_context; } auto factory = root_factories->find(root_id_string); RootContext *root_context; if (factory != root_factories->end()) { auto context = factory->second(context_id, root_id->view()); root_context = context->asRoot(); root_context_map[root_id_string] = root_context; context_map[context_id] = std::move(context); } else { auto context = std::make_unique<RootContext>(context_id, root_id->view()); root_context = context->asRoot(); context_map[context_id] = std::move(context); root_context_map[root_id_string] = root_context; } return root_context; } ContextBase *getContextBase(uint32_t context_id) { auto it = context_map.find(context_id); if (it == context_map.end()) { return nullptr; } return it->second.get(); } Context *getContext(uint32_t context_id) { auto it = context_map.find(context_id); if (it == context_map.end() || !it->second->asContext()) { return nullptr; } return it->second->asContext(); } RootContext *getRootContext(uint32_t context_id) { auto it = context_map.find(context_id); if (it == context_map.end() || !it->second->asRoot()) { return nullptr; } return it->second->asRoot(); } RootContext *getRoot(std::string_view root_id) { auto it = root_context_map.find(std::string(root_id)); if (it != root_context_map.end()) { return it->second; } return nullptr; } extern "C" PROXY_WASM_KEEPALIVE uint32_t proxy_on_vm_start(uint32_t root_context_id, uint32_t vm_configuration_size) { return getRootContext(root_context_id)->onStart(vm_configuration_size); } extern "C" PROXY_WASM_KEEPALIVE uint32_t proxy_validate_configuration(uint32_t root_context_id, uint32_t configuration_size) { return getRootContext(root_context_id)->validateConfiguration(configuration_size) ? 1 : 0; } extern "C" PROXY_WASM_KEEPALIVE uint32_t proxy_on_configure(uint32_t root_context_id, uint32_t configuration_size) { return getRootContext(root_context_id)->onConfigure(configuration_size) ? 1 : 0; } extern "C" PROXY_WASM_KEEPALIVE void proxy_on_tick(uint32_t root_context_id) { getRootContext(root_context_id)->onTick(); } extern "C" PROXY_WASM_KEEPALIVE void proxy_on_context_create(uint32_t context_id, uint32_t parent_context_id) { if (parent_context_id) { ensureContext(context_id, parent_context_id)->onCreate(); } else { ensureRootContext(context_id)->onCreate(); } } extern "C" PROXY_WASM_KEEPALIVE FilterStatus proxy_on_new_connection(uint32_t context_id) { return getContext(context_id)->onNewConnection(); } extern "C" PROXY_WASM_KEEPALIVE FilterStatus proxy_on_downstream_data(uint32_t context_id, uint32_t data_length, uint32_t end_of_stream) { return getContext(context_id) ->onDownstreamData(static_cast<size_t>(data_length), end_of_stream != 0); } extern "C" PROXY_WASM_KEEPALIVE FilterStatus proxy_on_upstream_data(uint32_t context_id, uint32_t data_length, uint32_t end_of_stream) { return getContext(context_id) ->onUpstreamData(static_cast<size_t>(data_length), end_of_stream != 0); } extern "C" PROXY_WASM_KEEPALIVE void proxy_on_downstream_connection_close(uint32_t context_id, uint32_t close_type) { return getContext(context_id)->onDownstreamConnectionClose(static_cast<CloseType>(close_type)); } extern "C" PROXY_WASM_KEEPALIVE void proxy_on_upstream_connection_close(uint32_t context_id, uint32_t close_type) { return getContext(context_id)->onUpstreamConnectionClose(static_cast<CloseType>(close_type)); } extern "C" PROXY_WASM_KEEPALIVE FilterHeadersStatus proxy_on_request_headers(uint32_t context_id, uint32_t headers, uint32_t end_of_stream) { return getContext(context_id)->onRequestHeaders(headers, end_of_stream != 0); } extern "C" PROXY_WASM_KEEPALIVE FilterMetadataStatus proxy_on_request_metadata(uint32_t context_id, uint32_t elements) { return getContext(context_id)->onRequestMetadata(elements); } extern "C" PROXY_WASM_KEEPALIVE FilterDataStatus proxy_on_request_body(uint32_t context_id, uint32_t body_buffer_length, uint32_t end_of_stream) { return getContext(context_id) ->onRequestBody(static_cast<size_t>(body_buffer_length), end_of_stream != 0); } extern "C" PROXY_WASM_KEEPALIVE FilterTrailersStatus proxy_on_request_trailers(uint32_t context_id, uint32_t trailers) { return getContext(context_id)->onRequestTrailers(trailers); } extern "C" PROXY_WASM_KEEPALIVE FilterHeadersStatus proxy_on_response_headers(uint32_t context_id, uint32_t headers, uint32_t end_of_stream) { return getContext(context_id)->onResponseHeaders(headers, end_of_stream != 0); } extern "C" PROXY_WASM_KEEPALIVE FilterMetadataStatus proxy_on_response_metadata(uint32_t context_id, uint32_t elements) { return getContext(context_id)->onResponseMetadata(elements); } extern "C" PROXY_WASM_KEEPALIVE FilterDataStatus proxy_on_response_body(uint32_t context_id, uint32_t body_buffer_length, uint32_t end_of_stream) { return getContext(context_id) ->onResponseBody(static_cast<size_t>(body_buffer_length), end_of_stream != 0); } extern "C" PROXY_WASM_KEEPALIVE FilterTrailersStatus proxy_on_response_trailers(uint32_t context_id, uint32_t trailers) { return getContext(context_id)->onResponseTrailers(trailers); } extern "C" PROXY_WASM_KEEPALIVE uint32_t proxy_on_done(uint32_t context_id) { return getContextBase(context_id)->onDoneBase(); } extern "C" PROXY_WASM_KEEPALIVE void proxy_on_log(uint32_t context_id) { getContext(context_id)->onLog(); } extern "C" PROXY_WASM_KEEPALIVE void proxy_on_delete(uint32_t context_id) { getContextBase(context_id)->onDelete(); context_map.erase(context_id); } extern "C" PROXY_WASM_KEEPALIVE void proxy_on_http_call_response(uint32_t context_id, uint32_t token, uint32_t headers, uint32_t body_size, uint32_t trailers) { getRootContext(context_id) ->onHttpCallResponse(token, headers, static_cast<size_t>(body_size), trailers); } extern "C" PROXY_WASM_KEEPALIVE void proxy_on_grpc_receive_initial_metadata(uint32_t context_id, uint32_t token, uint32_t headers) { getRootContext(context_id)->onGrpcReceiveInitialMetadata(token, headers); } extern "C" PROXY_WASM_KEEPALIVE void proxy_on_grpc_receive_trailing_metadata(uint32_t context_id, uint32_t token, uint32_t trailers) { getRootContext(context_id)->onGrpcReceiveTrailingMetadata(token, trailers); } extern "C" PROXY_WASM_KEEPALIVE void proxy_on_grpc_receive(uint32_t context_id, uint32_t token, uint32_t response_size) { getRootContext(context_id)->onGrpcReceive(token, static_cast<size_t>(response_size)); } extern "C" PROXY_WASM_KEEPALIVE void proxy_on_grpc_close(uint32_t context_id, uint32_t token, uint32_t status_code) { getRootContext(context_id)->onGrpcClose(token, static_cast<GrpcStatus>(status_code)); } extern "C" PROXY_WASM_KEEPALIVE void proxy_on_queue_ready(uint32_t context_id, uint32_t token) { getRootContext(context_id)->onQueueReady(token); } extern "C" PROXY_WASM_KEEPALIVE void proxy_on_foreign_function(uint32_t context_id, uint32_t foreign_function_id, uint32_t data_size) { getContextBase(context_id)->onForeignFunction(foreign_function_id, data_size); } <commit_msg>Change ABI version to 0.2.1 (#45)<commit_after>// Copyright 2016-2019 Envoy Project Authors // Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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. // NOLINT(namespace-envoy) #include "proxy_wasm_intrinsics.h" // Required Proxy-Wasm ABI version. extern "C" PROXY_WASM_KEEPALIVE void proxy_abi_version_0_2_1() {} static std::unordered_map<std::string, RootFactory> *root_factories = nullptr; static std::unordered_map<std::string, ContextFactory> *context_factories = nullptr; static std::unordered_map<int32_t, std::unique_ptr<ContextBase>> context_map; static std::unordered_map<std::string, RootContext *> root_context_map; RegisterContextFactory::RegisterContextFactory(ContextFactory context_factory, RootFactory root_factory, std::string_view root_id) { if (!root_factories) { root_factories = new std::unordered_map<std::string, RootFactory>; context_factories = new std::unordered_map<std::string, ContextFactory>; } if (context_factory) (*context_factories)[std::string(root_id)] = context_factory; if (root_factory) (*root_factories)[std::string(root_id)] = root_factory; } static Context *ensureContext(uint32_t context_id, uint32_t root_context_id) { auto e = context_map.insert(std::make_pair(context_id, nullptr)); if (e.second) { RootContext *root = context_map[root_context_id].get()->asRoot(); std::string root_id = std::string(root->root_id()); if (!context_factories) { e.first->second = std::make_unique<Context>(context_id, root); return e.first->second->asContext(); } auto factory = context_factories->find(root_id); if (factory == context_factories->end()) { e.first->second = std::make_unique<Context>(context_id, root); return e.first->second->asContext(); } else { e.first->second = factory->second(context_id, root); } } return e.first->second->asContext(); } static RootContext *ensureRootContext(uint32_t context_id) { auto it = context_map.find(context_id); if (it != context_map.end()) { return it->second->asRoot(); } const char *root_id_ptr = nullptr; size_t root_id_size = 0; CHECK_RESULT(proxy_get_property("plugin_root_id", sizeof("plugin_root_id") - 1, &root_id_ptr, &root_id_size)); auto root_id = std::make_unique<WasmData>(root_id_ptr, root_id_size); auto root_id_string = root_id->toString(); if (!root_factories) { auto context = std::make_unique<RootContext>(context_id, root_id->view()); RootContext *root_context = context->asRoot(); context_map[context_id] = std::move(context); root_context_map[root_id_string] = root_context; return root_context; } auto factory = root_factories->find(root_id_string); RootContext *root_context; if (factory != root_factories->end()) { auto context = factory->second(context_id, root_id->view()); root_context = context->asRoot(); root_context_map[root_id_string] = root_context; context_map[context_id] = std::move(context); } else { auto context = std::make_unique<RootContext>(context_id, root_id->view()); root_context = context->asRoot(); context_map[context_id] = std::move(context); root_context_map[root_id_string] = root_context; } return root_context; } ContextBase *getContextBase(uint32_t context_id) { auto it = context_map.find(context_id); if (it == context_map.end()) { return nullptr; } return it->second.get(); } Context *getContext(uint32_t context_id) { auto it = context_map.find(context_id); if (it == context_map.end() || !it->second->asContext()) { return nullptr; } return it->second->asContext(); } RootContext *getRootContext(uint32_t context_id) { auto it = context_map.find(context_id); if (it == context_map.end() || !it->second->asRoot()) { return nullptr; } return it->second->asRoot(); } RootContext *getRoot(std::string_view root_id) { auto it = root_context_map.find(std::string(root_id)); if (it != root_context_map.end()) { return it->second; } return nullptr; } extern "C" PROXY_WASM_KEEPALIVE uint32_t proxy_on_vm_start(uint32_t root_context_id, uint32_t vm_configuration_size) { return getRootContext(root_context_id)->onStart(vm_configuration_size); } extern "C" PROXY_WASM_KEEPALIVE uint32_t proxy_validate_configuration(uint32_t root_context_id, uint32_t configuration_size) { return getRootContext(root_context_id)->validateConfiguration(configuration_size) ? 1 : 0; } extern "C" PROXY_WASM_KEEPALIVE uint32_t proxy_on_configure(uint32_t root_context_id, uint32_t configuration_size) { return getRootContext(root_context_id)->onConfigure(configuration_size) ? 1 : 0; } extern "C" PROXY_WASM_KEEPALIVE void proxy_on_tick(uint32_t root_context_id) { getRootContext(root_context_id)->onTick(); } extern "C" PROXY_WASM_KEEPALIVE void proxy_on_context_create(uint32_t context_id, uint32_t parent_context_id) { if (parent_context_id) { ensureContext(context_id, parent_context_id)->onCreate(); } else { ensureRootContext(context_id)->onCreate(); } } extern "C" PROXY_WASM_KEEPALIVE FilterStatus proxy_on_new_connection(uint32_t context_id) { return getContext(context_id)->onNewConnection(); } extern "C" PROXY_WASM_KEEPALIVE FilterStatus proxy_on_downstream_data(uint32_t context_id, uint32_t data_length, uint32_t end_of_stream) { return getContext(context_id) ->onDownstreamData(static_cast<size_t>(data_length), end_of_stream != 0); } extern "C" PROXY_WASM_KEEPALIVE FilterStatus proxy_on_upstream_data(uint32_t context_id, uint32_t data_length, uint32_t end_of_stream) { return getContext(context_id) ->onUpstreamData(static_cast<size_t>(data_length), end_of_stream != 0); } extern "C" PROXY_WASM_KEEPALIVE void proxy_on_downstream_connection_close(uint32_t context_id, uint32_t close_type) { return getContext(context_id)->onDownstreamConnectionClose(static_cast<CloseType>(close_type)); } extern "C" PROXY_WASM_KEEPALIVE void proxy_on_upstream_connection_close(uint32_t context_id, uint32_t close_type) { return getContext(context_id)->onUpstreamConnectionClose(static_cast<CloseType>(close_type)); } extern "C" PROXY_WASM_KEEPALIVE FilterHeadersStatus proxy_on_request_headers(uint32_t context_id, uint32_t headers, uint32_t end_of_stream) { return getContext(context_id)->onRequestHeaders(headers, end_of_stream != 0); } extern "C" PROXY_WASM_KEEPALIVE FilterMetadataStatus proxy_on_request_metadata(uint32_t context_id, uint32_t elements) { return getContext(context_id)->onRequestMetadata(elements); } extern "C" PROXY_WASM_KEEPALIVE FilterDataStatus proxy_on_request_body(uint32_t context_id, uint32_t body_buffer_length, uint32_t end_of_stream) { return getContext(context_id) ->onRequestBody(static_cast<size_t>(body_buffer_length), end_of_stream != 0); } extern "C" PROXY_WASM_KEEPALIVE FilterTrailersStatus proxy_on_request_trailers(uint32_t context_id, uint32_t trailers) { return getContext(context_id)->onRequestTrailers(trailers); } extern "C" PROXY_WASM_KEEPALIVE FilterHeadersStatus proxy_on_response_headers(uint32_t context_id, uint32_t headers, uint32_t end_of_stream) { return getContext(context_id)->onResponseHeaders(headers, end_of_stream != 0); } extern "C" PROXY_WASM_KEEPALIVE FilterMetadataStatus proxy_on_response_metadata(uint32_t context_id, uint32_t elements) { return getContext(context_id)->onResponseMetadata(elements); } extern "C" PROXY_WASM_KEEPALIVE FilterDataStatus proxy_on_response_body(uint32_t context_id, uint32_t body_buffer_length, uint32_t end_of_stream) { return getContext(context_id) ->onResponseBody(static_cast<size_t>(body_buffer_length), end_of_stream != 0); } extern "C" PROXY_WASM_KEEPALIVE FilterTrailersStatus proxy_on_response_trailers(uint32_t context_id, uint32_t trailers) { return getContext(context_id)->onResponseTrailers(trailers); } extern "C" PROXY_WASM_KEEPALIVE uint32_t proxy_on_done(uint32_t context_id) { return getContextBase(context_id)->onDoneBase(); } extern "C" PROXY_WASM_KEEPALIVE void proxy_on_log(uint32_t context_id) { getContext(context_id)->onLog(); } extern "C" PROXY_WASM_KEEPALIVE void proxy_on_delete(uint32_t context_id) { getContextBase(context_id)->onDelete(); context_map.erase(context_id); } extern "C" PROXY_WASM_KEEPALIVE void proxy_on_http_call_response(uint32_t context_id, uint32_t token, uint32_t headers, uint32_t body_size, uint32_t trailers) { getRootContext(context_id) ->onHttpCallResponse(token, headers, static_cast<size_t>(body_size), trailers); } extern "C" PROXY_WASM_KEEPALIVE void proxy_on_grpc_receive_initial_metadata(uint32_t context_id, uint32_t token, uint32_t headers) { getRootContext(context_id)->onGrpcReceiveInitialMetadata(token, headers); } extern "C" PROXY_WASM_KEEPALIVE void proxy_on_grpc_receive_trailing_metadata(uint32_t context_id, uint32_t token, uint32_t trailers) { getRootContext(context_id)->onGrpcReceiveTrailingMetadata(token, trailers); } extern "C" PROXY_WASM_KEEPALIVE void proxy_on_grpc_receive(uint32_t context_id, uint32_t token, uint32_t response_size) { getRootContext(context_id)->onGrpcReceive(token, static_cast<size_t>(response_size)); } extern "C" PROXY_WASM_KEEPALIVE void proxy_on_grpc_close(uint32_t context_id, uint32_t token, uint32_t status_code) { getRootContext(context_id)->onGrpcClose(token, static_cast<GrpcStatus>(status_code)); } extern "C" PROXY_WASM_KEEPALIVE void proxy_on_queue_ready(uint32_t context_id, uint32_t token) { getRootContext(context_id)->onQueueReady(token); } extern "C" PROXY_WASM_KEEPALIVE void proxy_on_foreign_function(uint32_t context_id, uint32_t foreign_function_id, uint32_t data_size) { getContextBase(context_id)->onForeignFunction(foreign_function_id, data_size); } <|endoftext|>
<commit_before> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2015 Francois Beaune, The appleseedhq Organization // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Interface header. #include "projectbuilder.h" // appleseed-max headers. #include "maxsceneentities.h" #include "utilities.h" // appleseed.renderer headers. #include "renderer/api/camera.h" #include "renderer/api/environment.h" #include "renderer/api/frame.h" #include "renderer/api/object.h" #include "renderer/api/project.h" #include "renderer/api/scene.h" #include "renderer/api/utility.h" // appleseed.foundation headers. #include "foundation/math/scalar.h" #include "foundation/math/transform.h" #include "foundation/platform/compiler.h" #include "foundation/utility/containers/dictionary.h" // 3ds Max headers. #include <bitmap.h> #include <object.h> #include <render.h> #include <triobj.h> // Standard headers. #include <cassert> #include <cstddef> #include <limits> #include <string> #include <vector> namespace asf = foundation; namespace asr = renderer; namespace { asf::auto_release_ptr<asr::Camera> build_camera( INode* view_node, const ViewParams& view_params, Bitmap* bitmap, const TimeValue time) { asr::ParamArray params; if (view_params.projType == PROJ_PERSPECTIVE) { params.insert("film_dimensions", make_vec_string(bitmap->Width(), bitmap->Height())); params.insert("horizontal_fov", asf::rad_to_deg(view_params.fov)); } else { assert(view_params.projType == PROJ_PARALLEL); const float ViewDefaultWidth = 400.0f; const float aspect = static_cast<float>(bitmap->Height()) / bitmap->Width(); const float film_width = ViewDefaultWidth * view_params.zoom; const float film_height = film_width * aspect; params.insert("film_dimensions", make_vec_string(film_width, film_height)); } asf::Matrix4d camera_matrix = max_to_as(Inverse(view_params.affineTM)); if (view_node) { const ObjectState& os = view_node->EvalWorldState(time); switch (os.obj->SuperClassID()) { case CAMERA_CLASS_ID: { CameraObject* cam = static_cast<CameraObject*>(os.obj); Interval validity_interval; validity_interval.SetInfinite(); Matrix3 cam_to_world = view_node->GetObjTMAfterWSM(time, &validity_interval); cam_to_world.NoScale(); camera_matrix = max_to_as(cam_to_world); CameraState cam_state; cam->EvalCameraState(time, validity_interval, &cam_state); if (cam_state.manualClip) params.insert("near_z", cam_state.hither); } break; case LIGHT_CLASS_ID: { // todo: implement. } break; default: assert(!"Unexpected super class ID for camera."); } } asf::auto_release_ptr<renderer::Camera> camera = view_params.projType == PROJ_PERSPECTIVE ? asr::PinholeCameraFactory().create("camera", params) : asr::OrthographicCameraFactory().create("camera", params); camera->transform_sequence().set_transform( 0.0, asf::Transformd::from_local_to_parent(camera_matrix)); return camera; } TriObject* get_tri_object_from_node( const ObjectState& object_state, const TimeValue time, bool& must_delete) { assert(object_state.obj); must_delete = false; const Class_ID TriObjectClassID(TRIOBJ_CLASS_ID, 0); if (!object_state.obj->CanConvertToType(TriObjectClassID)) return 0; TriObject* tri_object = static_cast<TriObject*>(object_state.obj->ConvertToType(time, TriObjectClassID)); must_delete = tri_object != object_state.obj; return tri_object; } void add_object( asr::Assembly& assembly, INode* node, const TimeValue time) { // Retrieve the name of the referenced object. Object* max_object = node->GetObjectRef(); const std::string object_name = utf8_encode(max_object->GetObjectName()); // Create the object if it doesn't already exist in the appleseed scene. if (assembly.objects().get_by_name(object_name.c_str()) == 0) { // Retrieve the ObjectState at the desired time. const ObjectState object_state = node->EvalWorldState(time); // Convert the object to a TriObject. bool must_delete_tri_object; TriObject* tri_object = get_tri_object_from_node(object_state, time, must_delete_tri_object); if (tri_object == 0) { // todo: emit a message? return; } // Create a new mesh object. asf::auto_release_ptr<asr::MeshObject> object( asr::MeshObjectFactory::create(object_name.c_str(), asr::ParamArray())); { Mesh& mesh = tri_object->GetMesh(); // Copy vertices to the mesh object. object->reserve_vertices(mesh.getNumVerts()); for (int i = 0, e = mesh.getNumVerts(); i < e; ++i) { const Point3& v = mesh.getVert(i); //object->push_vertex(max_to_as(v)); object->push_vertex(asf::Vector3d(v.x, v.y, v.z)); } // Copy triangles to mesh object. object->reserve_triangles(mesh.getNumFaces()); for (int i = 0, e = mesh.getNumFaces(); i < e; ++i) { Face& face = mesh.faces[i]; const asr::Triangle triangle( face.getVert(0), face.getVert(1), face.getVert(2)); object->push_triangle(triangle); } // Delete the TriObject if necessary. if (must_delete_tri_object) tri_object->DeleteMe(); } // Insert the object into the assembly. assembly.objects().insert(asf::auto_release_ptr<asr::Object>(object)); } // Figure out a unique name for this instance. std::string instance_name = utf8_encode(node->GetName()); if (assembly.object_instances().get_by_name(instance_name.c_str()) != 0) instance_name = asr::make_unique_name(instance_name, assembly.object_instances()); // Create an instance of the object and insert it into the assembly. assembly.object_instances().insert( asr::ObjectInstanceFactory::create( instance_name.c_str(), asr::ParamArray(), object_name.c_str(), asf::Transformd::from_local_to_parent( max_to_as(node->GetObjTMAfterWSM(time))), asf::StringDictionary())); } void populate_assembly( asr::Assembly& assembly, const MaxSceneEntities& entities, const TimeValue time) { for (size_t i = 0, e = entities.m_instances.size(); i < e; ++i) add_object(assembly, entities.m_instances[i], time); } } asf::auto_release_ptr<asr::Project> build_project( const MaxSceneEntities& entities, INode* view_node, const ViewParams& view_params, Bitmap* bitmap, const TimeValue time) { // Create an empty project. asf::auto_release_ptr<asr::Project> project( asr::ProjectFactory::create("project")); // Add default configurations to the project. project->add_default_configurations(); // Set the number of samples. project->configurations() .get_by_name("final")->get_parameters() .insert_path("uniform_pixel_renderer.samples", "1"); // Create a scene. asf::auto_release_ptr<asr::Scene> scene(asr::SceneFactory::create()); // Create an assembly. asf::auto_release_ptr<asr::Assembly> assembly( asr::AssemblyFactory().create("assembly", asr::ParamArray())); // Populate the assembly with entities from the 3ds Max scene. populate_assembly(assembly.ref(), entities, time); // Create an instance of the assembly and insert it into the scene. asf::auto_release_ptr<asr::AssemblyInstance> assembly_instance( asr::AssemblyInstanceFactory::create( "assembly_inst", asr::ParamArray(), "assembly")); assembly_instance ->transform_sequence() .set_transform(0.0, asf::Transformd::identity()); scene->assembly_instances().insert(assembly_instance); // Insert the assembly into the scene. scene->assemblies().insert(assembly); // Create a default environment and bind it to the scene. scene->set_environment( asr::EnvironmentFactory::create("environment", asr::ParamArray())); // Create a camera. scene->set_camera( build_camera( view_node, view_params, bitmap, time)); // Create a frame and bind it to the project. project->set_frame( asr::FrameFactory::create( "beauty", asr::ParamArray() .insert("camera", scene->get_camera()->get_name()) .insert("resolution", make_vec_string(bitmap->Width(), bitmap->Height())) .insert("color_space", "linear_rgb"))); // Bind the scene to the project. project->set_scene(scene); return project; } <commit_msg>Temporarily disable broken instancing support<commit_after> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2015 Francois Beaune, The appleseedhq Organization // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Interface header. #include "projectbuilder.h" // appleseed-max headers. #include "maxsceneentities.h" #include "utilities.h" // appleseed.renderer headers. #include "renderer/api/camera.h" #include "renderer/api/environment.h" #include "renderer/api/frame.h" #include "renderer/api/object.h" #include "renderer/api/project.h" #include "renderer/api/scene.h" #include "renderer/api/utility.h" // appleseed.foundation headers. #include "foundation/math/scalar.h" #include "foundation/math/transform.h" #include "foundation/platform/compiler.h" #include "foundation/utility/containers/dictionary.h" // 3ds Max headers. #include <bitmap.h> #include <object.h> #include <render.h> #include <triobj.h> // Standard headers. #include <cassert> #include <cstddef> #include <limits> #include <string> #include <vector> namespace asf = foundation; namespace asr = renderer; namespace { asf::auto_release_ptr<asr::Camera> build_camera( INode* view_node, const ViewParams& view_params, Bitmap* bitmap, const TimeValue time) { asr::ParamArray params; if (view_params.projType == PROJ_PERSPECTIVE) { params.insert("film_dimensions", make_vec_string(bitmap->Width(), bitmap->Height())); params.insert("horizontal_fov", asf::rad_to_deg(view_params.fov)); } else { assert(view_params.projType == PROJ_PARALLEL); const float ViewDefaultWidth = 400.0f; const float aspect = static_cast<float>(bitmap->Height()) / bitmap->Width(); const float film_width = ViewDefaultWidth * view_params.zoom; const float film_height = film_width * aspect; params.insert("film_dimensions", make_vec_string(film_width, film_height)); } asf::Matrix4d camera_matrix = max_to_as(Inverse(view_params.affineTM)); if (view_node) { const ObjectState& os = view_node->EvalWorldState(time); switch (os.obj->SuperClassID()) { case CAMERA_CLASS_ID: { CameraObject* cam = static_cast<CameraObject*>(os.obj); Interval validity_interval; validity_interval.SetInfinite(); Matrix3 cam_to_world = view_node->GetObjTMAfterWSM(time, &validity_interval); cam_to_world.NoScale(); camera_matrix = max_to_as(cam_to_world); CameraState cam_state; cam->EvalCameraState(time, validity_interval, &cam_state); if (cam_state.manualClip) params.insert("near_z", cam_state.hither); } break; case LIGHT_CLASS_ID: { // todo: implement. } break; default: assert(!"Unexpected super class ID for camera."); } } asf::auto_release_ptr<renderer::Camera> camera = view_params.projType == PROJ_PERSPECTIVE ? asr::PinholeCameraFactory().create("camera", params) : asr::OrthographicCameraFactory().create("camera", params); camera->transform_sequence().set_transform( 0.0, asf::Transformd::from_local_to_parent(camera_matrix)); return camera; } TriObject* get_tri_object_from_node( const ObjectState& object_state, const TimeValue time, bool& must_delete) { assert(object_state.obj); must_delete = false; const Class_ID TriObjectClassID(TRIOBJ_CLASS_ID, 0); if (!object_state.obj->CanConvertToType(TriObjectClassID)) return 0; TriObject* tri_object = static_cast<TriObject*>(object_state.obj->ConvertToType(time, TriObjectClassID)); must_delete = tri_object != object_state.obj; return tri_object; } void add_object( asr::Assembly& assembly, INode* node, const TimeValue time) { // Retrieve the name of the referenced object. Object* max_object = node->GetObjectRef(); std::string object_name = utf8_encode(max_object->GetObjectName()); // todo: handle instancing. if (assembly.objects().get_by_name(object_name.c_str()) != 0) object_name = asr::make_unique_name(object_name, assembly.objects()); // Create the object if it doesn't already exist in the appleseed scene. if (assembly.objects().get_by_name(object_name.c_str()) == 0) { // Retrieve the ObjectState at the desired time. const ObjectState object_state = node->EvalWorldState(time); // Convert the object to a TriObject. bool must_delete_tri_object; TriObject* tri_object = get_tri_object_from_node(object_state, time, must_delete_tri_object); if (tri_object == 0) { // todo: emit a message? return; } // Create a new mesh object. asf::auto_release_ptr<asr::MeshObject> object( asr::MeshObjectFactory::create(object_name.c_str(), asr::ParamArray())); { Mesh& mesh = tri_object->GetMesh(); // Copy vertices to the mesh object. object->reserve_vertices(mesh.getNumVerts()); for (int i = 0, e = mesh.getNumVerts(); i < e; ++i) { const Point3& v = mesh.getVert(i); //object->push_vertex(max_to_as(v)); object->push_vertex(asf::Vector3d(v.x, v.y, v.z)); } // Copy triangles to mesh object. object->reserve_triangles(mesh.getNumFaces()); for (int i = 0, e = mesh.getNumFaces(); i < e; ++i) { Face& face = mesh.faces[i]; const asr::Triangle triangle( face.getVert(0), face.getVert(1), face.getVert(2)); object->push_triangle(triangle); } // Delete the TriObject if necessary. if (must_delete_tri_object) tri_object->DeleteMe(); } // Insert the object into the assembly. assembly.objects().insert(asf::auto_release_ptr<asr::Object>(object)); } // Figure out a unique name for this instance. std::string instance_name = utf8_encode(node->GetName()); if (assembly.object_instances().get_by_name(instance_name.c_str()) != 0) instance_name = asr::make_unique_name(instance_name, assembly.object_instances()); // Create an instance of the object and insert it into the assembly. assembly.object_instances().insert( asr::ObjectInstanceFactory::create( instance_name.c_str(), asr::ParamArray(), object_name.c_str(), asf::Transformd::from_local_to_parent( max_to_as(node->GetObjTMAfterWSM(time))), asf::StringDictionary())); } void populate_assembly( asr::Assembly& assembly, const MaxSceneEntities& entities, const TimeValue time) { for (size_t i = 0, e = entities.m_instances.size(); i < e; ++i) add_object(assembly, entities.m_instances[i], time); } } asf::auto_release_ptr<asr::Project> build_project( const MaxSceneEntities& entities, INode* view_node, const ViewParams& view_params, Bitmap* bitmap, const TimeValue time) { // Create an empty project. asf::auto_release_ptr<asr::Project> project( asr::ProjectFactory::create("project")); // Add default configurations to the project. project->add_default_configurations(); // Set the number of samples. project->configurations() .get_by_name("final")->get_parameters() .insert_path("uniform_pixel_renderer.samples", "1"); // Create a scene. asf::auto_release_ptr<asr::Scene> scene(asr::SceneFactory::create()); // Create an assembly. asf::auto_release_ptr<asr::Assembly> assembly( asr::AssemblyFactory().create("assembly", asr::ParamArray())); // Populate the assembly with entities from the 3ds Max scene. populate_assembly(assembly.ref(), entities, time); // Create an instance of the assembly and insert it into the scene. asf::auto_release_ptr<asr::AssemblyInstance> assembly_instance( asr::AssemblyInstanceFactory::create( "assembly_inst", asr::ParamArray(), "assembly")); assembly_instance ->transform_sequence() .set_transform(0.0, asf::Transformd::identity()); scene->assembly_instances().insert(assembly_instance); // Insert the assembly into the scene. scene->assemblies().insert(assembly); // Create a default environment and bind it to the scene. scene->set_environment( asr::EnvironmentFactory::create("environment", asr::ParamArray())); // Create a camera. scene->set_camera( build_camera( view_node, view_params, bitmap, time)); // Create a frame and bind it to the project. project->set_frame( asr::FrameFactory::create( "beauty", asr::ParamArray() .insert("camera", scene->get_camera()->get_name()) .insert("resolution", make_vec_string(bitmap->Width(), bitmap->Height())) .insert("color_space", "linear_rgb"))); // Bind the scene to the project. project->set_scene(scene); return project; } <|endoftext|>
<commit_before>/* author: Nathan Turner date:3/27/16 ussage: ./waf --run scratch/udpchain.cc */ #include "ns3/core-module.h" #include "ns3/network-module.h" #include "ns3/csma-module.h" #include "ns3/internet-module.h" #include "ns3/point-to-point-module.h" #include "ns3/applications-module.h" #include "ns3/ipv4-global-routing-helper.h" // Default Network Topology // // A B C D // | | | | // ================ // LAN 10.1.1.0 using namespace ns3; NS_LOG_COMPONENT_DEFINE ("Lab4: udpchain"); int main (int argc, char *argv[]) { bool verbose = true; // uint32_t nCsma = 5; CommandLine cmd; cmd.AddValue ("verbose", "Tell echo applications to log if true", verbose); cmd.Parse (argc,argv); if (verbose) { LogComponentEnable ("UdpEchoClientApplication", LOG_LEVEL_INFO); LogComponentEnable ("UdpEchoServerApplication", LOG_LEVEL_INFO); export NS_LOG=UdpEchoClientApplication=level_all; } // NodeContainer p2pNodes; // p2pNodes.Create (2); NodeContainer csmaNodes; // csmaNodes.Add (p2pNodes.Get (1)); csmaNodes.Create (4); // PointToPointHelper pointToPoint; // pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("5Mbps")); // pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms")); // NetDeviceContainer p2pDevices; // p2pDevices = pointToPoint.Install (p2pNodes); CsmaHelper csma; csma.SetChannelAttribute ("DataRate", StringValue ("1Mbps")); csma.SetChannelAttribute ("Delay", TimeValue (MilliSeconds (10))); NetDeviceContainer csmaDevices; csmaDevices = csma.Install (csmaNodes); InternetStackHelper stack; stack.Install (csmaNodes); Ipv4AddressHelper address; address.SetBase ("10.1.1.0", "255.255.255.0"); // Ipv4InterfaceContainer p2pInterfaces; // p2pInterfaces = address.Assign (p2pDevices); // address.SetBase ("10.1.2.0", "255.255.255.0"); Ipv4InterfaceContainer csmaInterfaces; csmaInterfaces = address.Assign (csmaDevices); UdpEchoServerHelper echoServer (9); ApplicationContainer serverApps = echoServer.Install (csmaNodes.Get (3)); serverApps.Start (Seconds (1.0)); serverApps.Stop (Seconds (10.0)); UdpEchoClientHelper echoClient (csmaInterfaces.GetAddress (3), 9); echoClient.SetAttribute ("MaxPackets", UintegerValue (5)); echoClient.SetAttribute ("Interval", TimeValue (Seconds (1.0))); echoClient.SetAttribute ("PacketSize", UintegerValue (1024)); ApplicationContainer clientApps = echoClient.Install (csmaNodes.Get (0)); clientApps.Start (Seconds (2.0)); clientApps.Stop (Seconds (10.0)); Ipv4GlobalRoutingHelper::PopulateRoutingTables (); // pointToPoint.EnablePcapAll ("second"); csma.EnablePcap ("udpchain", csmaDevices.Get (0), true); csma.EnablePcap ("udpchain", csmaDevices.Get (1), true); csma.EnablePcap ("udpchain", csmaDevices.Get (2), true); csma.EnablePcap ("udpchain", csmaDevices.Get (3), true); Simulator::Run (); Simulator::Destroy (); return 0; } <commit_msg>updated lab4<commit_after>/* author: Nathan Turner date:3/27/16 ussage: ./waf --run scratch/udpchain.cc */ #include "ns3/core-module.h" #include "ns3/network-module.h" #include "ns3/csma-module.h" #include "ns3/internet-module.h" #include "ns3/point-to-point-module.h" #include "ns3/applications-module.h" #include "ns3/ipv4-global-routing-helper.h" // Default Network Topology // // A B C D // | | | | // ================ // LAN 10.1.1.0 using namespace ns3; NS_LOG_COMPONENT_DEFINE ("Lab4: udpchain"); int main (int argc, char *argv[]) { bool verbose = true; CommandLine cmd; cmd.AddValue ("verbose", "Tell echo applications to log if true", verbose); cmd.Parse (argc,argv); if (verbose) { LogComponentEnable ("UdpEchoClientApplication", LOG_LEVEL_INFO); LogComponentEnable ("UdpEchoServerApplication", LOG_LEVEL_INFO); export NS_LOG=UdpEchoClientApplication=level_all; } NodeContainer csmaNodes; csmaNodes.Create (4); CsmaHelper csma; csma.SetChannelAttribute ("DataRate", StringValue ("1Mbps")); csma.SetChannelAttribute ("Delay", TimeValue (MilliSeconds (10))); NetDeviceContainer csmaDevices; csmaDevices = csma.Install (csmaNodes); InternetStackHelper stack; stack.Install (csmaNodes); Ipv4AddressHelper address; address.SetBase ("10.1.1.0", "255.255.255.0"); Ipv4InterfaceContainer csmaInterfaces; csmaInterfaces = address.Assign (csmaDevices); UdpEchoServerHelper echoServer (9); ApplicationContainer serverApps = echoServer.Install (csmaNodes.Get (3)); serverApps.Start (Seconds (1.0)); serverApps.Stop (Seconds (10.0)); UdpEchoClientHelper echoClient (csmaInterfaces.GetAddress (3), 9); echoClient.SetAttribute ("MaxPackets", UintegerValue (5)); echoClient.SetAttribute ("Interval", TimeValue (Seconds (1.0))); echoClient.SetAttribute ("PacketSize", UintegerValue (1024)); ApplicationContainer clientApps = echoClient.Install (csmaNodes.Get (0)); clientApps.Start (Seconds (2.0)); clientApps.Stop (Seconds (10.0)); Ipv4GlobalRoutingHelper::PopulateRoutingTables (); // pointToPoint.EnablePcapAll ("second"); csma.EnablePcap ("udpchain", csmaDevices.Get (0), true); csma.EnablePcap ("udpchain", csmaDevices.Get (1), true); csma.EnablePcap ("udpchain", csmaDevices.Get (2), true); csma.EnablePcap ("udpchain", csmaDevices.Get (3), true); Simulator::Run (); Simulator::Destroy (); return 0; } <|endoftext|>
<commit_before>#include "System.h" System::System() { this->m_inputHandler = NULL; this->m_window = NULL; } System::~System() { } int System::Shutdown() { int result = 0; //Destroy the display window SDL_DestroyWindow(m_window); //Quit SDL subsystems SDL_Quit(); this->m_graphicsHandler->Shutdown(); delete this->m_graphicsHandler; delete this->m_camera; this->m_inputHandler->Shutdown(); delete this->m_inputHandler; this->m_physicsHandler.ShutDown(); //Shutdown Network module this->m_networkModule.Shutdown(); return result; } int System::Initialize() { int result = 1; this->m_fullscreen = false; this->m_running = true; this->m_window = NULL; //Get the instance if this application this->m_hinstance = GetModuleHandle(NULL); if (SDL_Init(SDL_INIT_VIDEO) < 0) { printf("SDL failed in initializing the window! SDL_Error: %hS\n", SDL_GetError()); } else { printf("SDL succeeded in initializing the window!\n"); } m_window = SDL_CreateWindow("SSD Application", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); if (m_window == NULL) { printf("Window creation failed! SDL_ERROR: %hS\n", SDL_GetError()); } else { printf("Window creation succeeded!\n"); SDL_SysWMinfo wmInfo; SDL_VERSION(&wmInfo.version); SDL_GetWindowWMInfo(m_window, &wmInfo); m_hwnd = wmInfo.info.win.window; } this->m_graphicsHandler = new GraphicsHandler(); if (this->m_graphicsHandler->Initialize(&this->m_hwnd, DirectX::XMINT2(SCREEN_WIDTH, SCREEN_HEIGHT))) { printf("GraphicsHandler did not work. RIP!\n"); } this->m_camera = new Camera(); this->m_camera->Initialize(); Camera* oldCam = this->m_graphicsHandler->SetCamera(this->m_camera); delete oldCam; oldCam = nullptr; //Initialize the PhysicsHandler this->m_physicsHandler.Initialize(); //Initialize the InputHandler this->m_inputHandler = new InputHandler(); this->m_inputHandler->Initialize(SCREEN_WIDTH, SCREEN_HEIGHT); //Init the network module this->m_networkModule.Initialize(); return result; } //Do not place things here without talking to the system designers. Place any update method in the System::Update(float dt) method int System::Run() { int result = 0; LARGE_INTEGER frequency, currTime, prevTime, elapsedTime; QueryPerformanceFrequency(&frequency); //QueryPerformanceCounter(&prevTime); QueryPerformanceCounter(&currTime); while (this->m_running) { prevTime = currTime; QueryPerformanceCounter(&currTime); elapsedTime.QuadPart = currTime.QuadPart - prevTime.QuadPart; elapsedTime.QuadPart *= 1000000; elapsedTime.QuadPart /= frequency.QuadPart; //Update the network module this->m_networkModule.Update(); this->m_physicsHandler.Update(); //Prepare the InputHandler this->m_inputHandler->Update(); //Handle events and update inputhandler through said events result = this->HandleEvents(); SDL_PumpEvents(); //Update game if (this->m_inputHandler->IsKeyPressed(SDL_SCANCODE_ESCAPE)) { this->m_running = false; } if (!this->Update((float)elapsedTime.QuadPart)) { this->m_running = false; } if (this->m_inputHandler->IsKeyPressed(SDL_SCANCODE_F)) { this->FullscreenToggle(); } //std::cout << int(totalTime) << "\n"; //Render this->m_graphicsHandler->Render(); } if (this->m_fullscreen) this->FullscreenToggle(); return result; } int System::Update(float deltaTime) { int result = 1; int translateCameraX = 0, translateCameraY = 0, translateCameraZ = 0; int rotateCameraY = 0; std::list<CameraPacket> cList; //Check for camera updates from the network if (!this->m_networkModule.PacketBuffer_isEmpty()) { cList = this->m_networkModule.PacketBuffer_GetCameraPackets(); std::list<CameraPacket>::iterator iter; for (iter = cList.begin(); iter != cList.end();) { this->m_camera->SetCameraPos(iter->pos); } } if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_W)) { translateCameraZ++; } if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_S)) { translateCameraZ--; } if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_SPACE)) { translateCameraY++; if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_LSHIFT)) { translateCameraY *= -1; } } if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_D)) { translateCameraX++; } if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_A)) { translateCameraX--; } if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_E)) { rotateCameraY++; } if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_Q)) { rotateCameraY--; } if (translateCameraY || translateCameraX || translateCameraZ || rotateCameraY) { DirectX::XMFLOAT3 posTranslation = DirectX::XMFLOAT3(float(translateCameraX) * (deltaTime / 1000000.0f), float(translateCameraY) * (deltaTime / 1000000.0f), float(translateCameraZ) * (deltaTime / 1000000.0f)); this->m_camera->AddToCameraPos(posTranslation); this->m_camera->AddToLookAt(posTranslation); float rotationAmount = DirectX::XM_PI / 8; rotationAmount *= deltaTime / 1000000.0f; DirectX::XMFLOAT4 newRotation = DirectX::XMFLOAT4(0.0f, rotateCameraY * DirectX::XMScalarSin(rotationAmount / 2.0f), 0.0f, DirectX::XMScalarCos(rotationAmount / 2.0f)); this->m_camera->SetRotation(newRotation); this->m_camera->Update(); //Send updates over the network if (this->m_networkModule.GetNrOfConnectedClients() != 0) { DirectX::XMFLOAT4 updatePos; this->m_camera->GetCameraPos(updatePos); this->m_networkModule.SendCameraPacket(updatePos); } } //Network if(this->m_inputHandler->IsKeyPressed(SDL_SCANCODE_J)) { if (this->m_networkModule.GetNrOfConnectedClients() <= 0) //If the network module is NOT connected to other clients { if (this->m_networkModule.Join(this->m_ip)) //If we succsefully connected { printf("Joined client with the ip %s\n", this->m_ip); } else { printf("Failed to connect to the client\n", this->m_ip); } } else { printf("Join failed since this module is already connected to other clients\n"); } } if (this->m_inputHandler->IsKeyPressed(SDL_SCANCODE_K)) { this->m_networkModule.SendFlagPacket(DISCONNECT_REQUEST); } return result; } int System::HandleEvents() { SDL_Event m_event; while (SDL_PollEvent(&m_event)) { switch (m_event.type) { #pragma region case SDL_WINDOWEVENT: { switch (m_event.window.event) { case SDL_WINDOWEVENT_ENTER: { //OnMouseFocus(); break; } case SDL_WINDOWEVENT_LEAVE: { //OnMouseBlur(); break; } case SDL_WINDOWEVENT_FOCUS_GAINED: { //OnInputFocus(); break; } case SDL_WINDOWEVENT_FOCUS_LOST: { //OnInputBlur(); break; } case SDL_WINDOWEVENT_SHOWN: { break; } case SDL_WINDOWEVENT_HIDDEN: { break; } case SDL_WINDOWEVENT_EXPOSED: { break; } case SDL_WINDOWEVENT_MOVED: { break; } case SDL_WINDOWEVENT_RESIZED: { break; } case SDL_WINDOWEVENT_SIZE_CHANGED: { break; } case SDL_WINDOWEVENT_MINIMIZED: { break; } case SDL_WINDOWEVENT_MAXIMIZED: { break; } case SDL_WINDOWEVENT_RESTORED: { break; } case SDL_WINDOWEVENT_CLOSE: { break; } } break; } #pragma endregion window events case SDL_MOUSEMOTION: { break; } case SDL_QUIT: { //The big X in the corner this->m_running = false; break; } #pragma region case SDL_KEYDOWN: { //OnKeyDown(Event->key.keysym.sym, Event->key.keysym.mod, Event->key.keysym.scancode); this->m_inputHandler->SetKeyState(m_event.key.keysym.scancode, true); break; } case SDL_KEYUP: { //OnKeyUp(Event->key.keysym.sym, Event->key.keysym.mod, Event->key.keysym.scancode); this->m_inputHandler->SetKeyState(m_event.key.keysym.scancode, false); break; } case SDL_MOUSEBUTTONDOWN: { this->m_inputHandler->SetMouseState(m_event.button.button, true); break; } case SDL_MOUSEBUTTONUP: { this->m_inputHandler->SetMouseState(m_event.button.button, false); break; } #pragma endregion Key / Button events case SDL_MOUSEWHEEL: { this->m_inputHandler->ApplyMouseWheel(m_event.wheel.x, m_event.wheel.y); break; } } } return 1; } int System::FullscreenToggle() { int result = 0; this->m_fullscreen = SDL_GetWindowFlags(this->m_window) & SDL_WINDOW_FULLSCREEN; SDL_SetWindowFullscreen(this->m_window, this->m_fullscreen ? 0 : SDL_WINDOW_FULLSCREEN); this->m_fullscreen = SDL_GetWindowFlags(this->m_window) & SDL_WINDOW_FULLSCREEN; return result; } <commit_msg>FIX the loop that iterates cList<commit_after>#include "System.h" System::System() { this->m_inputHandler = NULL; this->m_window = NULL; } System::~System() { } int System::Shutdown() { int result = 0; //Destroy the display window SDL_DestroyWindow(m_window); //Quit SDL subsystems SDL_Quit(); this->m_graphicsHandler->Shutdown(); delete this->m_graphicsHandler; delete this->m_camera; this->m_inputHandler->Shutdown(); delete this->m_inputHandler; this->m_physicsHandler.ShutDown(); //Shutdown Network module this->m_networkModule.Shutdown(); return result; } int System::Initialize() { int result = 1; this->m_fullscreen = false; this->m_running = true; this->m_window = NULL; //Get the instance if this application this->m_hinstance = GetModuleHandle(NULL); if (SDL_Init(SDL_INIT_VIDEO) < 0) { printf("SDL failed in initializing the window! SDL_Error: %hS\n", SDL_GetError()); } else { printf("SDL succeeded in initializing the window!\n"); } m_window = SDL_CreateWindow("SSD Application", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); if (m_window == NULL) { printf("Window creation failed! SDL_ERROR: %hS\n", SDL_GetError()); } else { printf("Window creation succeeded!\n"); SDL_SysWMinfo wmInfo; SDL_VERSION(&wmInfo.version); SDL_GetWindowWMInfo(m_window, &wmInfo); m_hwnd = wmInfo.info.win.window; } this->m_graphicsHandler = new GraphicsHandler(); if (this->m_graphicsHandler->Initialize(&this->m_hwnd, DirectX::XMINT2(SCREEN_WIDTH, SCREEN_HEIGHT))) { printf("GraphicsHandler did not work. RIP!\n"); } this->m_camera = new Camera(); this->m_camera->Initialize(); Camera* oldCam = this->m_graphicsHandler->SetCamera(this->m_camera); delete oldCam; oldCam = nullptr; //Initialize the PhysicsHandler this->m_physicsHandler.Initialize(); //Initialize the InputHandler this->m_inputHandler = new InputHandler(); this->m_inputHandler->Initialize(SCREEN_WIDTH, SCREEN_HEIGHT); //Init the network module this->m_networkModule.Initialize(); return result; } //Do not place things here without talking to the system designers. Place any update method in the System::Update(float dt) method int System::Run() { int result = 0; LARGE_INTEGER frequency, currTime, prevTime, elapsedTime; QueryPerformanceFrequency(&frequency); //QueryPerformanceCounter(&prevTime); QueryPerformanceCounter(&currTime); while (this->m_running) { prevTime = currTime; QueryPerformanceCounter(&currTime); elapsedTime.QuadPart = currTime.QuadPart - prevTime.QuadPart; elapsedTime.QuadPart *= 1000000; elapsedTime.QuadPart /= frequency.QuadPart; //Update the network module this->m_networkModule.Update(); this->m_physicsHandler.Update(); //Prepare the InputHandler this->m_inputHandler->Update(); //Handle events and update inputhandler through said events result = this->HandleEvents(); SDL_PumpEvents(); //Update game if (this->m_inputHandler->IsKeyPressed(SDL_SCANCODE_ESCAPE)) { this->m_running = false; } if (!this->Update((float)elapsedTime.QuadPart)) { this->m_running = false; } if (this->m_inputHandler->IsKeyPressed(SDL_SCANCODE_F)) { this->FullscreenToggle(); } //std::cout << int(totalTime) << "\n"; //Render this->m_graphicsHandler->Render(); } if (this->m_fullscreen) this->FullscreenToggle(); return result; } int System::Update(float deltaTime) { int result = 1; int translateCameraX = 0, translateCameraY = 0, translateCameraZ = 0; int rotateCameraY = 0; std::list<CameraPacket> cList; //Check for camera updates from the network if (!this->m_networkModule.PacketBuffer_isEmpty()) { cList = this->m_networkModule.PacketBuffer_GetCameraPackets(); std::list<CameraPacket>::iterator iter; for (iter = cList.begin(); iter != cList.end();) { this->m_camera->SetCameraPos(iter->pos); iter++; } } if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_W)) { translateCameraZ++; } if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_S)) { translateCameraZ--; } if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_SPACE)) { translateCameraY++; if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_LSHIFT)) { translateCameraY *= -1; } } if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_D)) { translateCameraX++; } if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_A)) { translateCameraX--; } if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_E)) { rotateCameraY++; } if (this->m_inputHandler->IsKeyDown(SDL_SCANCODE_Q)) { rotateCameraY--; } if (translateCameraY || translateCameraX || translateCameraZ || rotateCameraY) { DirectX::XMFLOAT3 posTranslation = DirectX::XMFLOAT3(float(translateCameraX) * (deltaTime / 1000000.0f), float(translateCameraY) * (deltaTime / 1000000.0f), float(translateCameraZ) * (deltaTime / 1000000.0f)); this->m_camera->AddToCameraPos(posTranslation); this->m_camera->AddToLookAt(posTranslation); float rotationAmount = DirectX::XM_PI / 8; rotationAmount *= deltaTime / 1000000.0f; DirectX::XMFLOAT4 newRotation = DirectX::XMFLOAT4(0.0f, rotateCameraY * DirectX::XMScalarSin(rotationAmount / 2.0f), 0.0f, DirectX::XMScalarCos(rotationAmount / 2.0f)); this->m_camera->SetRotation(newRotation); this->m_camera->Update(); //Send updates over the network if (this->m_networkModule.GetNrOfConnectedClients() != 0) { DirectX::XMFLOAT4 updatePos; this->m_camera->GetCameraPos(updatePos); this->m_networkModule.SendCameraPacket(updatePos); } } //Network if(this->m_inputHandler->IsKeyPressed(SDL_SCANCODE_J)) { if (this->m_networkModule.GetNrOfConnectedClients() <= 0) //If the network module is NOT connected to other clients { if (this->m_networkModule.Join(this->m_ip)) //If we succsefully connected { printf("Joined client with the ip %s\n", this->m_ip); } else { printf("Failed to connect to the client\n", this->m_ip); } } else { printf("Join failed since this module is already connected to other clients\n"); } } if (this->m_inputHandler->IsKeyPressed(SDL_SCANCODE_K)) { this->m_networkModule.SendFlagPacket(DISCONNECT_REQUEST); } return result; } int System::HandleEvents() { SDL_Event m_event; while (SDL_PollEvent(&m_event)) { switch (m_event.type) { #pragma region case SDL_WINDOWEVENT: { switch (m_event.window.event) { case SDL_WINDOWEVENT_ENTER: { //OnMouseFocus(); break; } case SDL_WINDOWEVENT_LEAVE: { //OnMouseBlur(); break; } case SDL_WINDOWEVENT_FOCUS_GAINED: { //OnInputFocus(); break; } case SDL_WINDOWEVENT_FOCUS_LOST: { //OnInputBlur(); break; } case SDL_WINDOWEVENT_SHOWN: { break; } case SDL_WINDOWEVENT_HIDDEN: { break; } case SDL_WINDOWEVENT_EXPOSED: { break; } case SDL_WINDOWEVENT_MOVED: { break; } case SDL_WINDOWEVENT_RESIZED: { break; } case SDL_WINDOWEVENT_SIZE_CHANGED: { break; } case SDL_WINDOWEVENT_MINIMIZED: { break; } case SDL_WINDOWEVENT_MAXIMIZED: { break; } case SDL_WINDOWEVENT_RESTORED: { break; } case SDL_WINDOWEVENT_CLOSE: { break; } } break; } #pragma endregion window events case SDL_MOUSEMOTION: { break; } case SDL_QUIT: { //The big X in the corner this->m_running = false; break; } #pragma region case SDL_KEYDOWN: { //OnKeyDown(Event->key.keysym.sym, Event->key.keysym.mod, Event->key.keysym.scancode); this->m_inputHandler->SetKeyState(m_event.key.keysym.scancode, true); break; } case SDL_KEYUP: { //OnKeyUp(Event->key.keysym.sym, Event->key.keysym.mod, Event->key.keysym.scancode); this->m_inputHandler->SetKeyState(m_event.key.keysym.scancode, false); break; } case SDL_MOUSEBUTTONDOWN: { this->m_inputHandler->SetMouseState(m_event.button.button, true); break; } case SDL_MOUSEBUTTONUP: { this->m_inputHandler->SetMouseState(m_event.button.button, false); break; } #pragma endregion Key / Button events case SDL_MOUSEWHEEL: { this->m_inputHandler->ApplyMouseWheel(m_event.wheel.x, m_event.wheel.y); break; } } } return 1; } int System::FullscreenToggle() { int result = 0; this->m_fullscreen = SDL_GetWindowFlags(this->m_window) & SDL_WINDOW_FULLSCREEN; SDL_SetWindowFullscreen(this->m_window, this->m_fullscreen ? 0 : SDL_WINDOW_FULLSCREEN); this->m_fullscreen = SDL_GetWindowFlags(this->m_window) & SDL_WINDOW_FULLSCREEN; return result; } <|endoftext|>
<commit_before>#include "stdafx.h" #include "ViewDistanceCalc.h" #include "GL3DProgram.h" ViewDistanceCalc::ViewDistanceCalc() { viewDistance = 0.0; framesDrawn = 0; } //Should be called every draw cycle //calculates the view distance //applies to fog distance automatically void ViewDistanceCalc::CalculateAndApply(float & fogDistance,float currentFPS) { //Constants used for adjustment //How long the visual learning rate is const static int maxFrameLearn = 400; //Target frame rates const float maxFrameRate = 55; //This should be a bit higher than what you actually want const float acceptableFrameRate = 35; framesDrawn++; //only calibrate for the first 2000 frames if (framesDrawn > maxFrameLearn) { fogDistance = GetViewDistance()*.80f; return; } //A value between 0 and 1 which indicates how fast //the view distance can be adjusted float confidenceFactor = framesDrawn/(float)maxFrameLearn; //confidenceFactor^3 is used to slow the learning rate very early on confidenceFactor = 1-confidenceFactor; confidenceFactor = confidenceFactor*confidenceFactor*confidenceFactor; //If lower than the acceptable framerate, lower the view distance quickly if (currentFPS < acceptableFrameRate) viewDistance -= confidenceFactor*(acceptableFrameRate-currentFPS)/acceptableFrameRate*.05f; else if (currentFPS > maxFrameRate) viewDistance += confidenceFactor*(currentFPS-acceptableFrameRate)/acceptableFrameRate*.02f; if (viewDistance < 0.0) viewDistance = 0.0; if (viewDistance > 1.0) viewDistance = 1.0; //Fog has to end before view distance //because view distance is not perfect fogDistance = GetViewDistance()*.80f; } //Retrieve a pair of coordinates representing the appropriate draw section pair<vec2,vec2> ViewDistanceCalc::VoxDrawCoordinates(vec2 userPosition, float userAngle, float viewDistance) { //New strategy for determining draw box //Create a rectangle with the user on the bottom center, with the top of the rectangle //far away from the user in his view direction //Use the points of this rotated rectangle //to choose a min/max point of the voxel draw rectangle //Width code is highly experimental and will certainly have to be played with float rectHeight = viewDistance; //the full length of the rectangle float rectHalfWidth = pow(rectHeight/40.0f,3.0f)+rectHeight/5.0f+7.0f; //Half the width of the rectangle float rectHalfDiagonal =(float)( M_PI/2.0f-atan2(rectHeight,rectHalfWidth)); //The angle of the diagonal (to the center of the width side) float rectDiagonalLength = sqrt(rectHalfWidth*rectHalfWidth+rectHeight*rectHeight); vec2 testPoints[4] = { //Use the edges of a rectangle with the viewer in the bottom center //First the bottom left userPosition + vec2(cos(M_PI/2.0f+userAngle),sin(M_PI/2.0f+userAngle))*rectHalfWidth, //Next bottom right userPosition + vec2(cos(-M_PI/2.0f+userAngle),sin(-M_PI/2.0f+userAngle))*rectHalfWidth, //Top Left userPosition + vec2(cos(rectHalfDiagonal+userAngle),sin(rectHalfDiagonal+userAngle))*rectDiagonalLength, //Top Right userPosition + vec2(cos(-rectHalfDiagonal+userAngle),sin(-rectHalfDiagonal+userAngle))*rectDiagonalLength, }; vec2 minPoint = testPoints[0]; vec2 maxPoint = testPoints[0]; for (int i = 1; i < 4; i++) { minPoint = glm::min(minPoint,testPoints[i]); maxPoint = glm::max(maxPoint,testPoints[i]); } minPoint = glm::floor(minPoint); maxPoint = glm::ceil(maxPoint); //Limit points to valid ranges (vec2() creates a zero vector) //minPoint = glm::max(vec2(),minPoint); //maxPoint = glm::min(mapExtents-vec2(1,1),maxPoint); return pair<vec2,vec2>(minPoint,maxPoint); } IntRect ViewDistanceCalc::GetDrawRegion(vec2 playerPosition, float playerFacing) { return VoxDrawCoordinates(playerPosition,playerFacing,GetViewDistance()); } float ViewDistanceCalc::GetViewDistance() { //viewDistance is between 0 to 1, so apply scale now return viewDistance*(MAX_DRAW_DISTANCE-MIN_DRAW_DISTANCE)+MIN_DRAW_DISTANCE; }<commit_msg>Modified the view distance to push the transparency out further<commit_after>#include "stdafx.h" #include "ViewDistanceCalc.h" #include "GL3DProgram.h" ViewDistanceCalc::ViewDistanceCalc() { viewDistance = 0.0; framesDrawn = 0; } //Should be called every draw cycle //calculates the view distance //applies to fog distance automatically void ViewDistanceCalc::CalculateAndApply(float & fogDistance,float currentFPS) { //Constants used for adjustment //How long the visual learning rate is const static int maxFrameLearn = 400; //Target frame rates const float maxFrameRate = 55; //This should be a bit higher than what you actually want const float acceptableFrameRate = 35; framesDrawn++; //only calibrate for the first 2000 frames if (framesDrawn > maxFrameLearn) { fogDistance = GetViewDistance()*.80f; return; } //A value between 0 and 1 which indicates how fast //the view distance can be adjusted float confidenceFactor = framesDrawn/(float)maxFrameLearn; //confidenceFactor^3 is used to slow the learning rate very early on confidenceFactor = 1-confidenceFactor; confidenceFactor = confidenceFactor*confidenceFactor*confidenceFactor; //If lower than the acceptable framerate, lower the view distance quickly if (currentFPS < acceptableFrameRate) viewDistance -= confidenceFactor*(acceptableFrameRate-currentFPS)/acceptableFrameRate*.05f; else if (currentFPS > maxFrameRate) viewDistance += confidenceFactor*(currentFPS-acceptableFrameRate)/acceptableFrameRate*.02f; if (viewDistance < 0.0) viewDistance = 0.0; if (viewDistance > 1.0) viewDistance = 1.0; //Fog has to end before view distance //because view distance is not perfect //fogDistance = GetViewDistance()*.80f; fogDistance = GetViewDistance(); } //Retrieve a pair of coordinates representing the appropriate draw section pair<vec2,vec2> ViewDistanceCalc::VoxDrawCoordinates(vec2 userPosition, float userAngle, float viewDistance) { //New strategy for determining draw box //Create a rectangle with the user on the bottom center, with the top of the rectangle //far away from the user in his view direction //Use the points of this rotated rectangle //to choose a min/max point of the voxel draw rectangle //Width code is highly experimental and will certainly have to be played with float rectHeight = viewDistance; //the full length of the rectangle float rectHalfWidth = pow(rectHeight/40.0f,3.0f)+rectHeight/5.0f+7.0f; //Half the width of the rectangle float rectHalfDiagonal =(float)( M_PI/2.0f-atan2(rectHeight,rectHalfWidth)); //The angle of the diagonal (to the center of the width side) float rectDiagonalLength = sqrt(rectHalfWidth*rectHalfWidth+rectHeight*rectHeight); vec2 testPoints[4] = { //Use the edges of a rectangle with the viewer in the bottom center //First the bottom left userPosition + vec2(cos(M_PI/2.0f+userAngle),sin(M_PI/2.0f+userAngle))*rectHalfWidth, //Next bottom right userPosition + vec2(cos(-M_PI/2.0f+userAngle),sin(-M_PI/2.0f+userAngle))*rectHalfWidth, //Top Left userPosition + vec2(cos(rectHalfDiagonal+userAngle),sin(rectHalfDiagonal+userAngle))*rectDiagonalLength, //Top Right userPosition + vec2(cos(-rectHalfDiagonal+userAngle),sin(-rectHalfDiagonal+userAngle))*rectDiagonalLength, }; vec2 minPoint = testPoints[0]; vec2 maxPoint = testPoints[0]; for (int i = 1; i < 4; i++) { minPoint = glm::min(minPoint,testPoints[i]); maxPoint = glm::max(maxPoint,testPoints[i]); } minPoint = glm::floor(minPoint); maxPoint = glm::ceil(maxPoint); //Limit points to valid ranges (vec2() creates a zero vector) //minPoint = glm::max(vec2(),minPoint); //maxPoint = glm::min(mapExtents-vec2(1,1),maxPoint); return pair<vec2,vec2>(minPoint,maxPoint); } IntRect ViewDistanceCalc::GetDrawRegion(vec2 playerPosition, float playerFacing) { return VoxDrawCoordinates(playerPosition,playerFacing,GetViewDistance()); } float ViewDistanceCalc::GetViewDistance() { //viewDistance is between 0 to 1, so apply scale now return viewDistance*(MAX_DRAW_DISTANCE-MIN_DRAW_DISTANCE)+MIN_DRAW_DISTANCE; }<|endoftext|>
<commit_before>#pragma once #include "Renderer.hpp" #include "exprs.hpp" namespace DS { namespace CAS { namespace Expressions { namespace Visitors { namespace Render { template<typename T> class Infix : public DS::CAS::Expressions::Visitors::Renderer<T> { public: Infix(std::shared_ptr<Numbers::NumberFormatter> formatter) : Renderer<T>(formatter) {} virtual ~Infix() {} virtual bool visitAdd(const Add&); virtual bool visitDivide(const Divide&); virtual bool visitFactorial(const Factorial&); virtual bool visitLiteral(const Literal&); virtual bool visitModulus(const Modulus&); virtual bool visitMultiply(const Multiply&); virtual bool visitNegate(const Negate&); virtual bool visitPower(const Power&); virtual bool visitSymbol(const Symbol&); protected: virtual bool noParenthesisInDivision(void) const = 0; virtual bool noParenthesisInExponent(void) const = 0; virtual bool parenthesisInNegateDivision(void) const = 0; virtual T renderParenthesis(const T& arg) = 0; virtual T renderComma(const T& leftArg, const T& rightArg) = 0; virtual T renderAdjacent(const T& leftArg, const T& rightArg) = 0; virtual T renderString(const string& arg) = 0; virtual T renderBinaryOp(const string& op, const T& leftArg, const T& rightArg, bool spaces) = 0; virtual T renderUnaryOp(const string& op, const T& arg, bool leftRight) = 0; virtual T renderSuperscript(const T& base, const T& super) = 0; virtual T renderFraction(const T& top, const T& bottom) = 0; }; template<typename T> bool Infix<T>::visitAdd(const Add& exp) { unsigned int nc = exp.numberOfChildren(); T resultLeft, resultRight; for (unsigned int currentChild = nc-1; (currentChild+1) >= 1; currentChild--) { resultLeft = getPop(this->childResults); if (exp.getSignForChild(currentChild) == Expressions::Sign::n && exp.getChild(currentChild)->id() == ID::add) resultLeft = renderParenthesis(resultLeft); if (currentChild != nc-1) { if (exp.getSignForChild(currentChild+1) == Expressions::Sign::p) resultRight = renderBinaryOp("+", resultLeft, resultRight, true); else resultRight = renderBinaryOp("-", resultLeft, resultRight, true); } else resultRight = resultLeft; } if (exp.getSignForChild(0) == Expressions::Sign::n) resultRight = renderUnaryOp("-", resultRight, false); this->childResults.push(resultRight); return true; } template<typename T> bool Infix<T>::visitDivide(const Divide& exp) { T denominator = getPop(this->childResults); T numerator = getPop(this->childResults); if (!noParenthesisInDivision()) { Expressions::ID numID = exp.getChild(0)->id(); Expressions::ID denID = exp.getChild(1)->id(); if (numID == Expressions::ID::add) numerator = renderParenthesis(numerator); if (denID == Expressions::ID::add || denID == Expressions::ID::divide || denID == Expressions::ID::modulus || denID == Expressions::ID::multiply) denominator = renderParenthesis(denominator); } this->childResults.push(renderFraction(numerator, denominator)); return true; } template<typename T> bool Infix<T>::visitFactorial(const Factorial& exp) { T arg = getPop(this->childResults); Expressions::ID id = exp.getChild(0)->id(); if (id == Expressions::ID::add || id == Expressions::ID::divide || id == Expressions::ID::modulus || id == Expressions::ID::multiply || id == Expressions::ID::negate || id == Expressions::ID::power) arg = renderParenthesis(arg); this->childResults.push(renderUnaryOp("!", arg, true)); return true; } template<typename T> bool Infix<T>::visitLiteral(const Literal& exp) { const CAS::Numbers::Number& number = exp.getNumber(); if (number.isReal()) this->childResults.push(renderString(this->formatter->formatRealPart(number))); else if (number.isImaginary()) { string iNumber = this->formatter->formatImaginaryPart(number); if (iNumber == "1") iNumber = ""; if (iNumber == "-1") iNumber = "-"; this->childResults.push(renderString(iNumber + "i")); } else throw logic_error("Attempting to render a number with non-zero real and imaginary parts in Visitors::Render::Infix::visitLiteral()"); return true; } template<typename T> bool Infix<T>::visitModulus(const Modulus& exp) { T denominator = getPop(this->childResults); T numerator = getPop(this->childResults); Expressions::ID numID = exp.getChild(0)->id(); Expressions::ID denID = exp.getChild(1)->id(); if (numID == Expressions::ID::add || numID == Expressions::ID::negate) numerator = renderParenthesis(numerator); if (denID == Expressions::ID::add || denID == Expressions::ID::divide || denID == Expressions::ID::modulus || denID == Expressions::ID::multiply) denominator = renderParenthesis(denominator); this->childResults.push(renderBinaryOp("%", numerator, denominator, false)); return true; } template<typename T> bool Infix<T>::visitMultiply(const Multiply& exp) { unsigned int nc = exp.numberOfChildren(); T resultLeft, resultRight; for (unsigned int currentChild = nc-1; (currentChild+1) >= 1; currentChild--) { resultLeft = getPop(this->childResults); Expressions::ID id = exp.getChild(currentChild)->id(); if (id == Expressions::ID::add || id == Expressions::ID::modulus) resultLeft = renderParenthesis(resultLeft); if (currentChild != nc-1) resultRight = renderBinaryOp("*", resultLeft, resultRight, false); else resultRight = resultLeft; } this->childResults.push(resultRight); return true; } template<typename T> bool Infix<T>::visitNegate(const Negate& exp) { T arg = getPop(this->childResults); Expressions::ID id = exp.getChild(0)->id(); if (id == Expressions::ID::add || (id == Expressions::ID::divide && parenthesisInNegateDivision())) arg = renderParenthesis(arg); this->childResults.push(renderUnaryOp("-", arg, false)); return true; } template<typename T> bool Infix<T>::visitPower(const Power& exp) { T exponent = getPop(this->childResults); T base = getPop(this->childResults); Expressions::ID id = exp.getChild(0)->id(); // base if (id == Expressions::ID::add || id == Expressions::ID::divide || id == Expressions::ID::modulus || id == Expressions::ID::multiply || id == Expressions::ID::negate || id == Expressions::ID::power) base = renderParenthesis(base); if (!noParenthesisInExponent()) { id = exp.getChild(1)->id(); if (id == Expressions::ID::add || id == Expressions::ID::divide || id == Expressions::ID::modulus || id == Expressions::ID::multiply) exponent = renderParenthesis(exponent); } this->childResults.push(renderSuperscript(base, exponent)); return true; } template<typename T> bool Infix<T>::visitSymbol(const Symbol& exp) { unsigned int nc = exp.numberOfChildren(); if (!nc) { this->childResults.push(renderString(exp.getName())); return true; } T resultLeft, resultRight; for (unsigned int currentChild = nc-1; (currentChild+1) >= 1; currentChild--) { resultLeft = getPop(this->childResults); if (currentChild != nc-1) resultRight = renderComma(resultLeft, resultRight); else resultRight = resultLeft; } resultRight = renderParenthesis(resultRight); T name = renderString(exp.getName()); this->childResults.push(renderAdjacent(name, resultRight)); return true; } } /* namespace Render */ } /* namespace Visitors */ } /* namespace Expressions */ } /* namespace CAS */ } /* namespace DS */ <commit_msg>Fix a rendering bug<commit_after>#pragma once #include "Renderer.hpp" #include "exprs.hpp" namespace DS { namespace CAS { namespace Expressions { namespace Visitors { namespace Render { template<typename T> class Infix : public DS::CAS::Expressions::Visitors::Renderer<T> { public: Infix(std::shared_ptr<Numbers::NumberFormatter> formatter) : Renderer<T>(formatter) {} virtual ~Infix() {} virtual bool visitAdd(const Add&); virtual bool visitDivide(const Divide&); virtual bool visitFactorial(const Factorial&); virtual bool visitLiteral(const Literal&); virtual bool visitModulus(const Modulus&); virtual bool visitMultiply(const Multiply&); virtual bool visitNegate(const Negate&); virtual bool visitPower(const Power&); virtual bool visitSymbol(const Symbol&); protected: virtual bool noParenthesisInDivision(void) const = 0; virtual bool noParenthesisInExponent(void) const = 0; virtual bool parenthesisInNegateDivision(void) const = 0; virtual T renderParenthesis(const T& arg) = 0; virtual T renderComma(const T& leftArg, const T& rightArg) = 0; virtual T renderAdjacent(const T& leftArg, const T& rightArg) = 0; virtual T renderString(const string& arg) = 0; virtual T renderBinaryOp(const string& op, const T& leftArg, const T& rightArg, bool spaces) = 0; virtual T renderUnaryOp(const string& op, const T& arg, bool leftRight) = 0; virtual T renderSuperscript(const T& base, const T& super) = 0; virtual T renderFraction(const T& top, const T& bottom) = 0; }; template<typename T> bool Infix<T>::visitAdd(const Add& exp) { unsigned int nc = exp.numberOfChildren(); T resultLeft, resultRight; for (unsigned int currentChild = nc-1; (currentChild+1) >= 1; currentChild--) { resultLeft = getPop(this->childResults); if (exp.getSignForChild(currentChild) == Expressions::Sign::n && exp.getChild(currentChild)->id() == ID::add) resultLeft = renderParenthesis(resultLeft); if (currentChild != nc-1) { if (exp.getSignForChild(currentChild+1) == Expressions::Sign::p) resultRight = renderBinaryOp("+", resultLeft, resultRight, true); else resultRight = renderBinaryOp("-", resultLeft, resultRight, true); } else resultRight = resultLeft; } if (exp.getSignForChild(0) == Expressions::Sign::n) resultRight = renderUnaryOp("-", resultRight, false); this->childResults.push(resultRight); return true; } template<typename T> bool Infix<T>::visitDivide(const Divide& exp) { T denominator = getPop(this->childResults); T numerator = getPop(this->childResults); if (!noParenthesisInDivision()) { Expressions::ID numID = exp.getChild(0)->id(); Expressions::ID denID = exp.getChild(1)->id(); if (numID == Expressions::ID::add) numerator = renderParenthesis(numerator); if (denID == Expressions::ID::add || denID == Expressions::ID::divide || denID == Expressions::ID::modulus || denID == Expressions::ID::multiply) denominator = renderParenthesis(denominator); } this->childResults.push(renderFraction(numerator, denominator)); return true; } template<typename T> bool Infix<T>::visitFactorial(const Factorial& exp) { T arg = getPop(this->childResults); Expressions::ID id = exp.getChild(0)->id(); if (id == Expressions::ID::add || id == Expressions::ID::divide || id == Expressions::ID::modulus || id == Expressions::ID::multiply || id == Expressions::ID::negate || id == Expressions::ID::power) arg = renderParenthesis(arg); this->childResults.push(renderUnaryOp("!", arg, true)); return true; } template<typename T> bool Infix<T>::visitLiteral(const Literal& exp) { const CAS::Numbers::Number& number = exp.getNumber(); if (number.isReal()) this->childResults.push(renderString(this->formatter->formatRealPart(number))); else if (number.isImaginary()) { string iNumber = this->formatter->formatImaginaryPart(number); if (iNumber == "1") iNumber = ""; if (iNumber == "-1") iNumber = "-"; this->childResults.push(renderString(iNumber + "i")); } else throw logic_error("Attempting to render a number with non-zero real and imaginary parts in Visitors::Render::Infix::visitLiteral()"); return true; } template<typename T> bool Infix<T>::visitModulus(const Modulus& exp) { T denominator = getPop(this->childResults); T numerator = getPop(this->childResults); Expressions::ID numID = exp.getChild(0)->id(); Expressions::ID denID = exp.getChild(1)->id(); if (numID == Expressions::ID::add || numID == Expressions::ID::negate) numerator = renderParenthesis(numerator); if (denID == Expressions::ID::add || denID == Expressions::ID::divide || denID == Expressions::ID::modulus || denID == Expressions::ID::multiply) denominator = renderParenthesis(denominator); this->childResults.push(renderBinaryOp("%", numerator, denominator, false)); return true; } template<typename T> bool Infix<T>::visitMultiply(const Multiply& exp) { unsigned int nc = exp.numberOfChildren(); T resultLeft, resultRight; for (unsigned int currentChild = nc-1; (currentChild+1) >= 1; currentChild--) { resultLeft = getPop(this->childResults); Expressions::ID id = exp.getChild(currentChild)->id(); if (id == Expressions::ID::add || id == Expressions::ID::modulus) resultLeft = renderParenthesis(resultLeft); if (currentChild != nc-1) resultRight = renderBinaryOp("*", resultLeft, resultRight, false); else resultRight = resultLeft; } this->childResults.push(resultRight); return true; } template<typename T> bool Infix<T>::visitNegate(const Negate& exp) { T arg = getPop(this->childResults); Expressions::ID id = exp.getChild(0)->id(); if (id == Expressions::ID::add || (id == Expressions::ID::divide && parenthesisInNegateDivision())) arg = renderParenthesis(arg); this->childResults.push(renderUnaryOp("-", arg, false)); return true; } template<typename T> bool Infix<T>::visitPower(const Power& exp) { T exponent = getPop(this->childResults); T base = getPop(this->childResults); Expressions::ID id = exp.getChild(0)->id(); // base if (id == Expressions::ID::add || id == Expressions::ID::divide || id == Expressions::ID::modulus || id == Expressions::ID::multiply || id == Expressions::ID::negate || id == Expressions::ID::power) base = renderParenthesis(base); if (!noParenthesisInExponent()) { id = exp.getChild(1)->id(); if (id == Expressions::ID::add || id == Expressions::ID::divide || id == Expressions::ID::modulus || id == Expressions::ID::multiply || id == Expressions::ID::negate) exponent = renderParenthesis(exponent); } this->childResults.push(renderSuperscript(base, exponent)); return true; } template<typename T> bool Infix<T>::visitSymbol(const Symbol& exp) { unsigned int nc = exp.numberOfChildren(); if (!nc) { this->childResults.push(renderString(exp.getName())); return true; } T resultLeft, resultRight; for (unsigned int currentChild = nc-1; (currentChild+1) >= 1; currentChild--) { resultLeft = getPop(this->childResults); if (currentChild != nc-1) resultRight = renderComma(resultLeft, resultRight); else resultRight = resultLeft; } resultRight = renderParenthesis(resultRight); T name = renderString(exp.getName()); this->childResults.push(renderAdjacent(name, resultRight)); return true; } } /* namespace Render */ } /* namespace Visitors */ } /* namespace Expressions */ } /* namespace CAS */ } /* namespace DS */ <|endoftext|>
<commit_before>/** For conditions of distribution and use, see copyright notice in LICENSE @file ConsoleAPI.cpp @brief Console core API. */ #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "ConsoleAPI.h" #include "ConsoleWidget.h" #include "ShellInputThread.h" #include "Application.h" #include "Profiler.h" #include "Framework.h" #include "InputAPI.h" #include "UiAPI.h" #include "UiGraphicsView.h" #include "LoggingFunctions.h" #include "FunctionInvoker.h" #include <stdlib.h> #include <QFile> #include <QTextStream> #ifdef ANDROID #include <android/log.h> #endif #include "MemoryLeakCheck.h" ConsoleAPI::ConsoleAPI(Framework *fw) : QObject(fw), framework(fw), enabledLogChannels(LogLevelErrorWarnInfo), logFile(0), logFileText(0) { if (!fw->IsHeadless()) consoleWidget = new ConsoleWidget(framework); inputContext = framework->Input()->RegisterInputContext("Console", 100); inputContext->SetTakeKeyboardEventsOverQt(true); connect(inputContext.get(), SIGNAL(KeyEventReceived(KeyEvent *)), SLOT(HandleKeyEvent(KeyEvent *))); RegisterCommand("help", "Lists all registered commands.", this, SLOT(ListCommands())); RegisterCommand("clear", "Clears the console log.", this, SLOT(ClearLog())); RegisterCommand("setLogLevel", "Sets the current log level. Call with one of the parameters \"error\", \"warning\", \"info\", or \"debug\".", this, SLOT(SetLogLevel(const QString &))); #ifdef WIN32 RegisterCommand("createConsole", "Creates the native Windows console if Tundra was started without such.", this, SLOT(CreateNativeConsole())); RegisterCommand("removeConsole", "Removes the native Windows console if applicable.", this, SLOT(RemoveNativeConsole())); #endif /// \todo Visual Leak Detector shows a memory leak originating from this allocation although the shellInputThread is released in the destructor. Perhaps a shared pointer is held elsewhere. shellInputThread = MAKE_SHARED(ShellInputThread); QStringList logLevel = fw->CommandLineParameters("--loglevel"); if (logLevel.size() >= 1) SetLogLevel(logLevel[logLevel.size()-1]); if (logLevel.size() > 1) LogWarning("Ignoring multiple --loglevel command line parameters!"); QStringList logFile = fw->CommandLineParameters("--logfile"); if (logFile.size() >= 1) SetLogFile(logFile[logFile.size()-1]); if (logFile.size() > 1) LogWarning("Ignoring multiple --logfile command line parameters!"); } ConsoleAPI::~ConsoleAPI() { Reset(); } void ConsoleAPI::Reset() { commands.clear(); inputContext.reset(); SAFE_DELETE(consoleWidget); shellInputThread.reset(); SAFE_DELETE(logFileText); SAFE_DELETE(logFile); } QVariant ConsoleCommand::Invoke(const QStringList &params) { QVariant returnValue; // If we have a target QObject, invoke it. if (target) { // Check if we're invoking function with default arguments. QString func = functionName; int numRequiredArgs = FunctionInvoker::NumArgsForFunction(target, functionName); if (params.size() < numRequiredArgs && !functionNameDefaultArgs.isEmpty()) func = functionNameDefaultArgs; QString errorMessage; FunctionInvoker::Invoke(target, func, params, &returnValue, &errorMessage); if (!errorMessage.isEmpty()) LogError("ConsoleCommand::Invoke returned an error: " + errorMessage); } // Also, there may exist a script-registered handler that implements this console command - invoke it. emit Invoked(params); return returnValue; } QStringList ConsoleAPI::AvailableCommands() const { QStringList ret; for(CommandMap::const_iterator iter = commands.begin(); iter != commands.end(); ++iter) ret << iter->first; return ret; } ConsoleCommand *ConsoleAPI::RegisterCommand(const QString &name, const QString &desc) { if (name.isEmpty()) { LogError("ConsoleAPI::RegisterCommand: Command name can not be an empty string."); return 0; } if (commands.find(name) != commands.end()) { LogWarning("ConsoleAPI::RegisterCommand: Command " + name + " is already registered."); return commands[name].get(); } shared_ptr<ConsoleCommand> command = MAKE_SHARED(ConsoleCommand, name, desc, (QObject *)0, "", ""); commands[name] = command; return command.get(); } void ConsoleAPI::RegisterCommand(const QString &name, const QString &desc, QObject *receiver, const char *memberSlot, const char *memberSlotDefaultArgs) { if (name.isEmpty()) { LogError("ConsoleAPI::RegisterCommand: Command name can not be an empty string."); return; } if (commands.find(name) != commands.end()) { LogWarning("ConsoleAPI::RegisterCommand: Command " + name + " is already registered."); return; } shared_ptr<ConsoleCommand> command = MAKE_SHARED(ConsoleCommand, name, desc, receiver, memberSlot+1, memberSlotDefaultArgs ? memberSlotDefaultArgs+1 : ""); commands[name] = command; } void ConsoleAPI::UnregisterCommand(const QString &name) { CommandMap::iterator it = commands.find(name); if (it == commands.end()) { LogWarning("ConsoleAPI: Trying to unregister non-existing command " + name + "."); return; } commands.erase(it); } /// Splits a string of form "MyFunctionName(param1, param2, param3, ...)" into /// a commandName = "MyFunctionName" and a list of parameters as a StringList. void ParseCommand(QString command, QString &commandName, QStringList &parameterList) { command = command.trimmed(); if (command.isEmpty()) return; int split = command.indexOf("("); if (split == -1) { commandName = command; return; } commandName = command.left(split).trimmed(); // Take into account the possible ending ")" and strip it away from the parameter list. // Remove it only if it's the last character in the string, as f.ex. some code execution console // command could contain ')' in the syntax. int endOfSplit = command.lastIndexOf(")"); if (endOfSplit != -1 && endOfSplit == command.length()-1) command.remove(endOfSplit, 1); parameterList = command.mid(split+1).split(","); // Trim parameters in order to avoid errors if/when converting strings to other data types. for(int i = 0; i < parameterList.size(); ++i) parameterList[i] = parameterList[i].trimmed(); } void ConsoleAPI::ExecuteCommand(const QString &command) { PROFILE(ConsoleAPI_ExecuteCommand); QString commandName; QStringList parameterList; ParseCommand(command, commandName, parameterList); if (commandName.isEmpty()) return; CommandMap::iterator iter = commands.find(commandName); if (iter == commands.end()) { LogError("Cannot find a console command \"" + commandName + "\"!"); return; } iter->second->Invoke(parameterList); } void ConsoleAPI::Print(const QString &message) { if (consoleWidget) consoleWidget->PrintToConsole(message); ///\todo Temporary hack which appends line ending in case it's not there (output of console commands in headless mode) if (!message.endsWith("\n")) { #ifndef ANDROID printf("%s\n", message.toStdString().c_str()); #else __android_log_print(ANDROID_LOG_INFO, "Tundra", "%s\n", message.toStdString().c_str()); #endif if (logFileText) { (*logFileText) << message << "\n"; /// \note If we want to guarantee that each message gets to the log even in the presence of a crash, we must flush() /// after each write. Tested that on Windows 7, if you kill the process using Ctrl-C on command line, or from /// task manager, the log will not contain all the text, so this is required for correctness. /// But this flush() after each message also causes a *serious* performance drawback. /// One way to try avoiding this issue is to move to using C API for file writing, and at atexit() and other crash /// handlers, close the file handle gracefully. logFileText->flush(); } } else { #ifndef ANDROID printf("%s", message.toStdString().c_str()); #else __android_log_print(ANDROID_LOG_INFO, "Tundra", "%s", message.toStdString().c_str()); #endif if (logFileText) { (*logFileText) << message; logFileText->flush(); // See comment about flush() above. } } } void ConsoleAPI::ListCommands() { Print("Available console commands (case-insensitive):"); for(CommandMap::iterator iter = commands.begin(); iter != commands.end(); ++iter) Print(iter->first + " - " + iter->second->Description()); } void ConsoleAPI::ClearLog() { if (consoleWidget) consoleWidget->ClearLog(); #ifdef _WINDOWS (void)system("cls"); #else (void)system("clear"); #endif } void ConsoleAPI::SetLogLevel(const QString &level) { if (level.compare("error", Qt::CaseInsensitive) == 0) SetEnabledLogChannels(LogLevelErrorsOnly); else if (level.compare("warning", Qt::CaseInsensitive) == 0) SetEnabledLogChannels(LogLevelErrorWarning); else if (level.compare("info", Qt::CaseInsensitive) == 0) SetEnabledLogChannels(LogLevelErrorWarnInfo); else if (level.compare("debug", Qt::CaseInsensitive) == 0) SetEnabledLogChannels(LogLevelErrorWarnInfoDebug); else LogError("Unknown parameter \"" + level + "\" specified to ConsoleAPI::SetLogLevel!"); } void ConsoleAPI::SetLogFile(const QString &wildCardFilename) { QString filename = Application::ParseWildCardFilename(wildCardFilename); // An empty log file closes the log output writing. if (filename.isEmpty()) { SAFE_DELETE(logFileText); SAFE_DELETE(logFile); return; } logFile = new QFile(filename); bool isOpen = logFile->open(QIODevice::WriteOnly | QIODevice::Text); if (!isOpen) { LogError("Failed to open file \"" + filename + "\" for logging! (parsed from string \"" + wildCardFilename + "\")"); SAFE_DELETE(logFile); } else { printf("Opened logging file \"%s\".\n", filename.toStdString().c_str()); logFileText = new QTextStream(logFile); } } void ConsoleAPI::Update(f64 /*frametime*/) { PROFILE(ConsoleAPI_Update); std::string input = shellInputThread->GetLine(); if (input.length() > 0) ExecuteCommand(input.c_str()); } void ConsoleAPI::ToggleConsole() { if (consoleWidget) consoleWidget->ToggleConsole(); } void ConsoleAPI::HandleKeyEvent(KeyEvent *e) { if (e->sequence == framework->Input()->KeyBinding("ToggleConsole", QKeySequence(Qt::Key_F1))) ToggleConsole(); } void ConsoleAPI::CreateNativeConsole() { #ifdef WIN32 if (Application::ShowConsoleWindow(false)) shellInputThread = MAKE_SHARED(ShellInputThread); // Recreate ShellInputThread so that we will have working input. #endif } void ConsoleAPI::RemoveNativeConsole() { #ifdef WIN32 FreeConsole(); #endif } void ConsoleAPI::LogInfo(const QString &message) { ::LogInfo(message); } void ConsoleAPI::LogWarning(const QString &message) { ::LogWarning(message); } void ConsoleAPI::LogError(const QString &message) { ::LogError(message); } void ConsoleAPI::LogDebug(const QString &message) { ::LogDebug(message); } void ConsoleAPI::Log(u32 logChannel, const QString &message) { if (IsLogChannelEnabled(logChannel)) Print(message); } void ConsoleAPI::SetEnabledLogChannels(u32 newChannels) { enabledLogChannels = newChannels; } bool ConsoleAPI::IsLogChannelEnabled(u32 logChannel) const { return (enabledLogChannels & logChannel) != 0; } u32 ConsoleAPI::EnabledLogChannels() const { return enabledLogChannels; } <commit_msg>ConsoleAPI::ClearLog: Check that native console exists. If not and we call cls, we see a console flashing briefly on the screen which is undesirable.<commit_after>/** For conditions of distribution and use, see copyright notice in LICENSE @file ConsoleAPI.cpp @brief Console core API. */ #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "ConsoleAPI.h" #include "ConsoleWidget.h" #include "ShellInputThread.h" #include "Application.h" #include "Profiler.h" #include "Framework.h" #include "InputAPI.h" #include "UiAPI.h" #include "UiGraphicsView.h" #include "LoggingFunctions.h" #include "FunctionInvoker.h" #include <stdlib.h> #include <QFile> #include <QTextStream> #ifdef ANDROID #include <android/log.h> #endif #include "MemoryLeakCheck.h" ConsoleAPI::ConsoleAPI(Framework *fw) : QObject(fw), framework(fw), enabledLogChannels(LogLevelErrorWarnInfo), logFile(0), logFileText(0) { if (!fw->IsHeadless()) consoleWidget = new ConsoleWidget(framework); inputContext = framework->Input()->RegisterInputContext("Console", 100); inputContext->SetTakeKeyboardEventsOverQt(true); connect(inputContext.get(), SIGNAL(KeyEventReceived(KeyEvent *)), SLOT(HandleKeyEvent(KeyEvent *))); RegisterCommand("help", "Lists all registered commands.", this, SLOT(ListCommands())); RegisterCommand("clear", "Clears the console log.", this, SLOT(ClearLog())); RegisterCommand("setLogLevel", "Sets the current log level. Call with one of the parameters \"error\", \"warning\", \"info\", or \"debug\".", this, SLOT(SetLogLevel(const QString &))); #ifdef WIN32 RegisterCommand("createConsole", "Creates the native Windows console if Tundra was started without such.", this, SLOT(CreateNativeConsole())); RegisterCommand("removeConsole", "Removes the native Windows console if applicable.", this, SLOT(RemoveNativeConsole())); #endif /// \todo Visual Leak Detector shows a memory leak originating from this allocation although the shellInputThread is released in the destructor. Perhaps a shared pointer is held elsewhere. shellInputThread = MAKE_SHARED(ShellInputThread); QStringList logLevel = fw->CommandLineParameters("--loglevel"); if (logLevel.size() >= 1) SetLogLevel(logLevel[logLevel.size()-1]); if (logLevel.size() > 1) LogWarning("Ignoring multiple --loglevel command line parameters!"); QStringList logFile = fw->CommandLineParameters("--logfile"); if (logFile.size() >= 1) SetLogFile(logFile[logFile.size()-1]); if (logFile.size() > 1) LogWarning("Ignoring multiple --logfile command line parameters!"); } ConsoleAPI::~ConsoleAPI() { Reset(); } void ConsoleAPI::Reset() { commands.clear(); inputContext.reset(); SAFE_DELETE(consoleWidget); shellInputThread.reset(); SAFE_DELETE(logFileText); SAFE_DELETE(logFile); } QVariant ConsoleCommand::Invoke(const QStringList &params) { QVariant returnValue; // If we have a target QObject, invoke it. if (target) { // Check if we're invoking function with default arguments. QString func = functionName; int numRequiredArgs = FunctionInvoker::NumArgsForFunction(target, functionName); if (params.size() < numRequiredArgs && !functionNameDefaultArgs.isEmpty()) func = functionNameDefaultArgs; QString errorMessage; FunctionInvoker::Invoke(target, func, params, &returnValue, &errorMessage); if (!errorMessage.isEmpty()) LogError("ConsoleCommand::Invoke returned an error: " + errorMessage); } // Also, there may exist a script-registered handler that implements this console command - invoke it. emit Invoked(params); return returnValue; } QStringList ConsoleAPI::AvailableCommands() const { QStringList ret; for(CommandMap::const_iterator iter = commands.begin(); iter != commands.end(); ++iter) ret << iter->first; return ret; } ConsoleCommand *ConsoleAPI::RegisterCommand(const QString &name, const QString &desc) { if (name.isEmpty()) { LogError("ConsoleAPI::RegisterCommand: Command name can not be an empty string."); return 0; } if (commands.find(name) != commands.end()) { LogWarning("ConsoleAPI::RegisterCommand: Command " + name + " is already registered."); return commands[name].get(); } shared_ptr<ConsoleCommand> command = MAKE_SHARED(ConsoleCommand, name, desc, (QObject *)0, "", ""); commands[name] = command; return command.get(); } void ConsoleAPI::RegisterCommand(const QString &name, const QString &desc, QObject *receiver, const char *memberSlot, const char *memberSlotDefaultArgs) { if (name.isEmpty()) { LogError("ConsoleAPI::RegisterCommand: Command name can not be an empty string."); return; } if (commands.find(name) != commands.end()) { LogWarning("ConsoleAPI::RegisterCommand: Command " + name + " is already registered."); return; } shared_ptr<ConsoleCommand> command = MAKE_SHARED(ConsoleCommand, name, desc, receiver, memberSlot+1, memberSlotDefaultArgs ? memberSlotDefaultArgs+1 : ""); commands[name] = command; } void ConsoleAPI::UnregisterCommand(const QString &name) { CommandMap::iterator it = commands.find(name); if (it == commands.end()) { LogWarning("ConsoleAPI: Trying to unregister non-existing command " + name + "."); return; } commands.erase(it); } /// Splits a string of form "MyFunctionName(param1, param2, param3, ...)" into /// a commandName = "MyFunctionName" and a list of parameters as a StringList. void ParseCommand(QString command, QString &commandName, QStringList &parameterList) { command = command.trimmed(); if (command.isEmpty()) return; int split = command.indexOf("("); if (split == -1) { commandName = command; return; } commandName = command.left(split).trimmed(); // Take into account the possible ending ")" and strip it away from the parameter list. // Remove it only if it's the last character in the string, as f.ex. some code execution console // command could contain ')' in the syntax. int endOfSplit = command.lastIndexOf(")"); if (endOfSplit != -1 && endOfSplit == command.length()-1) command.remove(endOfSplit, 1); parameterList = command.mid(split+1).split(","); // Trim parameters in order to avoid errors if/when converting strings to other data types. for(int i = 0; i < parameterList.size(); ++i) parameterList[i] = parameterList[i].trimmed(); } void ConsoleAPI::ExecuteCommand(const QString &command) { PROFILE(ConsoleAPI_ExecuteCommand); QString commandName; QStringList parameterList; ParseCommand(command, commandName, parameterList); if (commandName.isEmpty()) return; CommandMap::iterator iter = commands.find(commandName); if (iter == commands.end()) { LogError("Cannot find a console command \"" + commandName + "\"!"); return; } iter->second->Invoke(parameterList); } void ConsoleAPI::Print(const QString &message) { if (consoleWidget) consoleWidget->PrintToConsole(message); ///\todo Temporary hack which appends line ending in case it's not there (output of console commands in headless mode) if (!message.endsWith("\n")) { #ifndef ANDROID printf("%s\n", message.toStdString().c_str()); #else __android_log_print(ANDROID_LOG_INFO, "Tundra", "%s\n", message.toStdString().c_str()); #endif if (logFileText) { (*logFileText) << message << "\n"; /// \note If we want to guarantee that each message gets to the log even in the presence of a crash, we must flush() /// after each write. Tested that on Windows 7, if you kill the process using Ctrl-C on command line, or from /// task manager, the log will not contain all the text, so this is required for correctness. /// But this flush() after each message also causes a *serious* performance drawback. /// One way to try avoiding this issue is to move to using C API for file writing, and at atexit() and other crash /// handlers, close the file handle gracefully. logFileText->flush(); } } else { #ifndef ANDROID printf("%s", message.toStdString().c_str()); #else __android_log_print(ANDROID_LOG_INFO, "Tundra", "%s", message.toStdString().c_str()); #endif if (logFileText) { (*logFileText) << message; logFileText->flush(); // See comment about flush() above. } } } void ConsoleAPI::ListCommands() { Print("Available console commands (case-insensitive):"); for(CommandMap::iterator iter = commands.begin(); iter != commands.end(); ++iter) Print(iter->first + " - " + iter->second->Description()); } void ConsoleAPI::ClearLog() { if (consoleWidget) consoleWidget->ClearLog(); #ifdef _WINDOWS // Check that native console exists. If not and we call cls, we see a console flashing briefly on the screen which is undesirable. if (GetConsoleWindow()) (void)system("cls"); #else (void)system("clear"); #endif } void ConsoleAPI::SetLogLevel(const QString &level) { if (level.compare("error", Qt::CaseInsensitive) == 0) SetEnabledLogChannels(LogLevelErrorsOnly); else if (level.compare("warning", Qt::CaseInsensitive) == 0) SetEnabledLogChannels(LogLevelErrorWarning); else if (level.compare("info", Qt::CaseInsensitive) == 0) SetEnabledLogChannels(LogLevelErrorWarnInfo); else if (level.compare("debug", Qt::CaseInsensitive) == 0) SetEnabledLogChannels(LogLevelErrorWarnInfoDebug); else LogError("Unknown parameter \"" + level + "\" specified to ConsoleAPI::SetLogLevel!"); } void ConsoleAPI::SetLogFile(const QString &wildCardFilename) { QString filename = Application::ParseWildCardFilename(wildCardFilename); // An empty log file closes the log output writing. if (filename.isEmpty()) { SAFE_DELETE(logFileText); SAFE_DELETE(logFile); return; } logFile = new QFile(filename); bool isOpen = logFile->open(QIODevice::WriteOnly | QIODevice::Text); if (!isOpen) { LogError("Failed to open file \"" + filename + "\" for logging! (parsed from string \"" + wildCardFilename + "\")"); SAFE_DELETE(logFile); } else { printf("Opened logging file \"%s\".\n", filename.toStdString().c_str()); logFileText = new QTextStream(logFile); } } void ConsoleAPI::Update(f64 /*frametime*/) { PROFILE(ConsoleAPI_Update); std::string input = shellInputThread->GetLine(); if (input.length() > 0) ExecuteCommand(input.c_str()); } void ConsoleAPI::ToggleConsole() { if (consoleWidget) consoleWidget->ToggleConsole(); } void ConsoleAPI::HandleKeyEvent(KeyEvent *e) { if (e->sequence == framework->Input()->KeyBinding("ToggleConsole", QKeySequence(Qt::Key_F1))) ToggleConsole(); } void ConsoleAPI::CreateNativeConsole() { #ifdef WIN32 if (Application::ShowConsoleWindow(false)) shellInputThread = MAKE_SHARED(ShellInputThread); // Recreate ShellInputThread so that we will have working input. #endif } void ConsoleAPI::RemoveNativeConsole() { #ifdef WIN32 FreeConsole(); #endif } void ConsoleAPI::LogInfo(const QString &message) { ::LogInfo(message); } void ConsoleAPI::LogWarning(const QString &message) { ::LogWarning(message); } void ConsoleAPI::LogError(const QString &message) { ::LogError(message); } void ConsoleAPI::LogDebug(const QString &message) { ::LogDebug(message); } void ConsoleAPI::Log(u32 logChannel, const QString &message) { if (IsLogChannelEnabled(logChannel)) Print(message); } void ConsoleAPI::SetEnabledLogChannels(u32 newChannels) { enabledLogChannels = newChannels; } bool ConsoleAPI::IsLogChannelEnabled(u32 logChannel) const { return (enabledLogChannels & logChannel) != 0; } u32 ConsoleAPI::EnabledLogChannels() const { return enabledLogChannels; } <|endoftext|>
<commit_before>// Powiter // /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* *Created by Alexandre GAUTHIER-FOICHAT on 6/1/2012. *contact: immarespond at gmail dot com * */ #include "ExrDecoder.h" #ifdef __POWITER_WIN32__ #include <fstream> #endif #include <QtGui/QImage> #include <QtCore/QByteArray> #include <QtCore/QMutex> #include <ImfPixelType.h> #include <ImfChannelList.h> #ifdef __POWITER_WIN32__ #include <ImfStdIO.h> #endif #include "Readers/Reader.h" #include "Gui/KnobGui.h" #include "Engine/Node.h" #include "Gui/NodeGui.h" #include "Gui/ViewerGL.h" #include "Engine/Lut.h" #include "Engine/Row.h" #include "Engine/ImageInfo.h" #ifndef OPENEXR_IMF_NAMESPACE #define OPENEXR_IMF_NAMESPACE Imf #endif namespace Imf_ = OPENEXR_IMF_NAMESPACE; using std::cout; using std::endl; struct ExrDecoder::Implementation { Implementation(); Imf::InputFile* _inputfile; std::map<Powiter::Channel, std::string> _channel_map; std::vector<std::string> _views; int _dataOffset; #ifdef __POWITER_WIN32__ std::ifstream* _inputStr; Imf::StdIFStream* _inputStdStream; #endif QMutex _lock; }; namespace EXR { static Powiter::Channel fromExrChannel(const std::string& from) { if (from == "R" || from == "r" || from == "Red" || from == "RED" || from == "red" || from == "y" || from == "Y") { return Powiter::Channel_red; } if (from == "G" || from == "g" || from == "Green" || from == "GREEN" || from == "green" || from == "ry" || from == "RY") { return Powiter::Channel_green; } if (from == "B" || from == "b" || from == "Blue" || from == "BLUE" || from == "blue" || from == "by" || from == "BY") { return Powiter::Channel_blue; } if (from == "A" || from == "a" || from == "Alpha" || from == "ALPHA" || from == "alpha") { return Powiter::Channel_alpha; } if (from == "Z" || from == "z" || from == "Depth" || from == "DEPTH" || from == "depth") { return Powiter::Channel_Z; } // The following may throw if from is not a channel name which begins with "Channel_" return Powiter::getChannelByName(from); } class ChannelExtractor { public: ChannelExtractor(const std::string& name, const std::vector<std::string>& views) : _mappedChannel(Powiter::Channel_black), _valid(false) { _valid = extractExrChannelName(name.c_str(), views); } ~ChannelExtractor() {} Powiter::Channel _mappedChannel; bool _valid; std::string _chan; std::string _layer; std::string _view; std::string exrName() const{ if (!_layer.empty()) return _layer + "." + _chan; return _chan; } bool isValid() const {return _valid;} private: static bool IsView(const std::string& name, const std::vector<std::string>& views) { for ( size_t i = 0; i < views.size(); ++i ){ if ( views[i] == name ){ return true; } } return false; } bool extractExrChannelName(const QString& channelname, const std::vector<std::string>& views){ _chan.clear(); _layer.clear(); _view.clear(); QStringList splits = channelname.split(QChar('.'),QString::SkipEmptyParts); QStringList newSplits; //remove prepending digits for (int i = 0; i < splits.size(); ++i) { QString str = splits.at(i); int j = 0; while (j < str.size() && str.at(j).isDigit()) { ++j; } str = str.remove(0, j); if(!str.isEmpty()){ //remove non alphanumeric chars QString finalStr; for (int k = 0; k < str.size(); ++k) { QChar c = str.at(k); if (!c.isLetterOrNumber()) { c = '_'; } finalStr.append(c); } newSplits << finalStr; } } if (newSplits.size() > 1){ for (int i = 0; i < (newSplits.size() - 1);++i) { std::vector<std::string>::const_iterator foundView = std::find(views.begin(), views.end(),newSplits.at(i).toStdString()); if (foundView != views.end()) { _view = *foundView; } else { if (!_layer.empty()) _layer += "_"; _layer += newSplits.at(i).toStdString(); } } _chan = newSplits.back().toStdString(); } else { _chan = newSplits.at(0).toStdString(); } try{ _mappedChannel = EXR::fromExrChannel(_chan); } catch (const std::exception &e) { std::cout << e.what() << endl; return false; } return true; } }; } // namespace EXR Powiter::Status ExrDecoder::readHeader(const QString& filename){ _imp->_channel_map.clear(); _imp->_views.clear(); try { #ifdef __POWITER_WIN32__ QByteArray ba = filename.toLocal8Bit(); if(_imp->_inputStr){ delete _imp->_inputStr; } if(_imp->_inputStdStream){ delete _imp->_inputStdStream; } if(_imp->_inputfile){ delete _imp->_inputfile; } _imp->_inputStr = new std::ifstream(PowiterWindows::s2ws(ba.data()),std::ios_base::binary); _imp->_inputStdStream = new Imf_::StdIFStream(*_inputStr,ba.data()); _imp->_inputfile = new Imf_::InputFile(*_inputStdStream); #else QByteArray ba = filename.toLatin1(); if(_imp->_inputfile){ delete _imp->_inputfile; } _imp->_inputfile = new Imf_::InputFile(ba.constData()); #endif // multiview is only supported with OpenEXR >= 1.7.0 #ifdef INCLUDED_IMF_STRINGVECTOR_ATTRIBUTE_H // use ImfStringVectorAttribute.h's #include guard const Imf_::StringAttribute* stringMultiView = 0; const Imf_::StringVectorAttribute* vectorMultiView = 0; try { vectorMultiView = inputfile->header().findTypedAttribute<Imf_::StringVectorAttribute>("multiView"); if (!vectorMultiView) { Imf_::Header::ConstIterator it = inputfile->header().find("multiView"); if (it != inputfile->header().end() && !strcmp(it.attribute().typeName(), "stringvector")) vectorMultiView = static_cast<const Imf_::StringVectorAttribute*>(&it.attribute()); } stringMultiView = inputfile->header().findTypedAttribute<Imf_::StringAttribute>("multiView"); } catch (...) { return StatFailed; } if (vectorMultiView) { std::vector<std::string> s = vectorMultiView->value(); bool setHero = false; for (size_t i = 0; i < s.size(); ++i) { if (s[i].length()) { _views.push_back(s[i]); if (!setHero) { heroview = s[i]; setHero = true; } } } } #endif // !OPENEXR_NO_MULTIVIEW std::map<Imf_::PixelType, int> pixelTypes; // convert exr channels to powiter channels Powiter::ChannelSet mask; const Imf_::ChannelList& imfchannels = _imp->_inputfile->header().channels(); Imf_::ChannelList::ConstIterator chan; for (chan = imfchannels.begin(); chan != imfchannels.end(); ++chan) { std::string chanName(chan.name()); if(chanName.empty()) continue; pixelTypes[chan.channel().type]++; EXR::ChannelExtractor exrExctractor(chan.name(), _imp->_views); std::set<Powiter::Channel> channels; if (exrExctractor.isValid()) { channels.insert(exrExctractor._mappedChannel); //cout << "size : "<< channels.size() << endl; for (std::set<Powiter::Channel>::const_iterator it = channels.begin(); it != channels.end(); ++it) { Powiter::Channel channel = *it; //cout <<" channel_map[" << Powiter::getChannelName(channel) << "] = " << chan.name() << endl; bool writeChannelMapping = true; ChannelsMap::const_iterator found = _imp->_channel_map.find(channel); if(found != _imp->_channel_map.end()){ int existingLength = found->second.size(); int newLength = chanName.size(); if ((existingLength > 0) && found->second.at(0) == '.' && existingLength == (newLength + 1)) { writeChannelMapping = true; } else if (existingLength > newLength) { writeChannelMapping = false; } } if(writeChannelMapping){ _imp->_channel_map.insert(make_pair(channel,chanName)); } mask += channel; } }else { cout << "Cannot decode channel " << chan.name() << endl; } } const Imath::Box2i& datawin = _imp->_inputfile->header().dataWindow(); const Imath::Box2i& dispwin = _imp->_inputfile->header().displayWindow(); Imath::Box2i formatwin(dispwin); formatwin.min.x = 0; formatwin.min.y = 0; _imp->_dataOffset = 0; if (dispwin.min.x != 0) { // Shift both to get dispwindow over to 0,0. _imp->_dataOffset = -dispwin.min.x; formatwin.max.x = dispwin.max.x + _imp->_dataOffset; } formatwin.max.y = dispwin.max.y - dispwin.min.y; double aspect = _imp->_inputfile->header().pixelAspectRatio(); Format imageFormat(0,0,formatwin.max.x + 1 ,formatwin.max.y + 1,"",aspect); Box2D rod; int left = datawin.min.x + _imp->_dataOffset; int bottom = dispwin.max.y - datawin.max.y; int right = datawin.max.x + _imp->_dataOffset; int top = dispwin.max.y - datawin.min.y; if (datawin.min.x != dispwin.min.x || datawin.max.x != dispwin.max.x || datawin.min.y != dispwin.min.y || datawin.max.y != dispwin.max.y) { --left; --bottom; ++right; ++top; // _readerInfo->setBlackOutside(true); } rod.set(left, bottom, right+1, top+1); setReaderInfo(imageFormat, rod, mask); return Powiter::StatOK; } catch (const std::exception& exc) { cout << "OpenEXR error: " << exc.what() << endl; delete _imp->_inputfile; _imp->_inputfile = 0; return Powiter::StatFailed; } } ExrDecoder::ExrDecoder(Reader* op) : Decoder(op) , _imp(new Implementation) { } ExrDecoder::Implementation::Implementation() : _inputfile(0) , _dataOffset(0) #ifdef __POWITER_WIN32__ , _inputStr(NULL) , _inputStdStream(NULL) #endif { } void ExrDecoder::initializeColorSpace(){ _lut=Powiter::Color::getLut(Powiter::Color::LUT_DEFAULT_FLOAT); // linear color-space for exr files } ExrDecoder::~ExrDecoder(){ #ifdef __POWITER_WIN32__ delete _imp->_inputStr ; delete _imp->_inputStdStream ; #endif delete _imp->_inputfile; } void ExrDecoder::render(SequenceTime /*time*/,Powiter::Row* out){ const Powiter::ChannelSet& channels = out->channels(); const Imath::Box2i& dispwin = _imp->_inputfile->header().displayWindow(); const Imath::Box2i& datawin = _imp->_inputfile->header().dataWindow(); int exrY = dispwin.max.y - out->y(); int r = out->right(); int x = out->left(); const int X = std::max(x, datawin.min.x + _imp->_dataOffset); const int R = std::min(r, datawin.max.x + _imp->_dataOffset +1); // if we're below or above the data window if(exrY < datawin.min.y || exrY > datawin.max.y || R <= X) { out->eraseAll(); return; } Imf_::FrameBuffer fbuf; foreachChannels(z, channels){ // blacking out the extra padding we added float* dest = out->begin(z) - out->left(); for (int xx = x; xx < X; xx++) dest[xx] = 0; for (int xx = R; xx < r; xx++) dest[xx] = 0; ChannelsMap::const_iterator found = _imp->_channel_map.find(z); if(found != _imp->_channel_map.end()){ if(found->second != "BY" && found->second != "RY"){ // if it is NOT a subsampled buffer fbuf.insert(found->second.c_str(),Imf_::Slice(Imf_::FLOAT, (char*)(dest /*+_dataOffset*/),sizeof(float), 0)); }else{ fbuf.insert(found->second.c_str(),Imf_::Slice(Imf_::FLOAT, (char*)(dest /*+_dataOffset*/),sizeof(float), 0,2,2)); } }else{ //not found in the file, we zero it out // we're responsible for filling all channels requested by the row float fillValue = 0.f; if (z == Powiter::Channel_alpha) { fillValue = 1.f; } out->fill(z,fillValue); } } { QMutexLocker locker(&_imp->_lock); try { _imp->_inputfile->setFrameBuffer(fbuf); _imp->_inputfile->readPixels(exrY); } catch (const std::exception& exc) { cout << exc.what() << endl; return; } } // colorspace conversion const float* alpha = out->begin(Powiter::Channel_alpha); foreachChannels(z, channels){ float* to = out->begin(z) - out->left(); const float* from = out->begin(z) - out->left(); if(from){ from_float(z,to + X ,from + X,alpha, R-X,1); } } } <commit_msg>Missing ImfInputFile #include in ExrDecoder.cpp<commit_after>// Powiter // /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* *Created by Alexandre GAUTHIER-FOICHAT on 6/1/2012. *contact: immarespond at gmail dot com * */ #include "ExrDecoder.h" #ifdef __POWITER_WIN32__ #include <fstream> #endif #include <QtGui/QImage> #include <QtCore/QByteArray> #include <QtCore/QMutex> #include <ImfPixelType.h> #include <ImfChannelList.h> #include <ImfInputFile.h> #ifdef __POWITER_WIN32__ #include <ImfStdIO.h> #endif #include "Readers/Reader.h" #include "Gui/KnobGui.h" #include "Engine/Node.h" #include "Gui/NodeGui.h" #include "Gui/ViewerGL.h" #include "Engine/Lut.h" #include "Engine/Row.h" #include "Engine/ImageInfo.h" #ifndef OPENEXR_IMF_NAMESPACE #define OPENEXR_IMF_NAMESPACE Imf #endif namespace Imf_ = OPENEXR_IMF_NAMESPACE; using std::cout; using std::endl; struct ExrDecoder::Implementation { Implementation(); Imf::InputFile* _inputfile; std::map<Powiter::Channel, std::string> _channel_map; std::vector<std::string> _views; int _dataOffset; #ifdef __POWITER_WIN32__ std::ifstream* _inputStr; Imf::StdIFStream* _inputStdStream; #endif QMutex _lock; }; namespace EXR { static Powiter::Channel fromExrChannel(const std::string& from) { if (from == "R" || from == "r" || from == "Red" || from == "RED" || from == "red" || from == "y" || from == "Y") { return Powiter::Channel_red; } if (from == "G" || from == "g" || from == "Green" || from == "GREEN" || from == "green" || from == "ry" || from == "RY") { return Powiter::Channel_green; } if (from == "B" || from == "b" || from == "Blue" || from == "BLUE" || from == "blue" || from == "by" || from == "BY") { return Powiter::Channel_blue; } if (from == "A" || from == "a" || from == "Alpha" || from == "ALPHA" || from == "alpha") { return Powiter::Channel_alpha; } if (from == "Z" || from == "z" || from == "Depth" || from == "DEPTH" || from == "depth") { return Powiter::Channel_Z; } // The following may throw if from is not a channel name which begins with "Channel_" return Powiter::getChannelByName(from); } class ChannelExtractor { public: ChannelExtractor(const std::string& name, const std::vector<std::string>& views) : _mappedChannel(Powiter::Channel_black), _valid(false) { _valid = extractExrChannelName(name.c_str(), views); } ~ChannelExtractor() {} Powiter::Channel _mappedChannel; bool _valid; std::string _chan; std::string _layer; std::string _view; std::string exrName() const{ if (!_layer.empty()) return _layer + "." + _chan; return _chan; } bool isValid() const {return _valid;} private: static bool IsView(const std::string& name, const std::vector<std::string>& views) { for ( size_t i = 0; i < views.size(); ++i ){ if ( views[i] == name ){ return true; } } return false; } bool extractExrChannelName(const QString& channelname, const std::vector<std::string>& views){ _chan.clear(); _layer.clear(); _view.clear(); QStringList splits = channelname.split(QChar('.'),QString::SkipEmptyParts); QStringList newSplits; //remove prepending digits for (int i = 0; i < splits.size(); ++i) { QString str = splits.at(i); int j = 0; while (j < str.size() && str.at(j).isDigit()) { ++j; } str = str.remove(0, j); if(!str.isEmpty()){ //remove non alphanumeric chars QString finalStr; for (int k = 0; k < str.size(); ++k) { QChar c = str.at(k); if (!c.isLetterOrNumber()) { c = '_'; } finalStr.append(c); } newSplits << finalStr; } } if (newSplits.size() > 1){ for (int i = 0; i < (newSplits.size() - 1);++i) { std::vector<std::string>::const_iterator foundView = std::find(views.begin(), views.end(),newSplits.at(i).toStdString()); if (foundView != views.end()) { _view = *foundView; } else { if (!_layer.empty()) _layer += "_"; _layer += newSplits.at(i).toStdString(); } } _chan = newSplits.back().toStdString(); } else { _chan = newSplits.at(0).toStdString(); } try{ _mappedChannel = EXR::fromExrChannel(_chan); } catch (const std::exception &e) { std::cout << e.what() << endl; return false; } return true; } }; } // namespace EXR Powiter::Status ExrDecoder::readHeader(const QString& filename){ _imp->_channel_map.clear(); _imp->_views.clear(); try { #ifdef __POWITER_WIN32__ QByteArray ba = filename.toLocal8Bit(); if(_imp->_inputStr){ delete _imp->_inputStr; } if(_imp->_inputStdStream){ delete _imp->_inputStdStream; } if(_imp->_inputfile){ delete _imp->_inputfile; } _imp->_inputStr = new std::ifstream(PowiterWindows::s2ws(ba.data()),std::ios_base::binary); _imp->_inputStdStream = new Imf_::StdIFStream(*_inputStr,ba.data()); _imp->_inputfile = new Imf_::InputFile(*_inputStdStream); #else QByteArray ba = filename.toLatin1(); if(_imp->_inputfile){ delete _imp->_inputfile; } _imp->_inputfile = new Imf_::InputFile(ba.constData()); #endif // multiview is only supported with OpenEXR >= 1.7.0 #ifdef INCLUDED_IMF_STRINGVECTOR_ATTRIBUTE_H // use ImfStringVectorAttribute.h's #include guard const Imf_::StringAttribute* stringMultiView = 0; const Imf_::StringVectorAttribute* vectorMultiView = 0; try { vectorMultiView = inputfile->header().findTypedAttribute<Imf_::StringVectorAttribute>("multiView"); if (!vectorMultiView) { Imf_::Header::ConstIterator it = inputfile->header().find("multiView"); if (it != inputfile->header().end() && !strcmp(it.attribute().typeName(), "stringvector")) vectorMultiView = static_cast<const Imf_::StringVectorAttribute*>(&it.attribute()); } stringMultiView = inputfile->header().findTypedAttribute<Imf_::StringAttribute>("multiView"); } catch (...) { return StatFailed; } if (vectorMultiView) { std::vector<std::string> s = vectorMultiView->value(); bool setHero = false; for (size_t i = 0; i < s.size(); ++i) { if (s[i].length()) { _views.push_back(s[i]); if (!setHero) { heroview = s[i]; setHero = true; } } } } #endif // !OPENEXR_NO_MULTIVIEW std::map<Imf_::PixelType, int> pixelTypes; // convert exr channels to powiter channels Powiter::ChannelSet mask; const Imf_::ChannelList& imfchannels = _imp->_inputfile->header().channels(); Imf_::ChannelList::ConstIterator chan; for (chan = imfchannels.begin(); chan != imfchannels.end(); ++chan) { std::string chanName(chan.name()); if(chanName.empty()) continue; pixelTypes[chan.channel().type]++; EXR::ChannelExtractor exrExctractor(chan.name(), _imp->_views); std::set<Powiter::Channel> channels; if (exrExctractor.isValid()) { channels.insert(exrExctractor._mappedChannel); //cout << "size : "<< channels.size() << endl; for (std::set<Powiter::Channel>::const_iterator it = channels.begin(); it != channels.end(); ++it) { Powiter::Channel channel = *it; //cout <<" channel_map[" << Powiter::getChannelName(channel) << "] = " << chan.name() << endl; bool writeChannelMapping = true; ChannelsMap::const_iterator found = _imp->_channel_map.find(channel); if(found != _imp->_channel_map.end()){ int existingLength = found->second.size(); int newLength = chanName.size(); if ((existingLength > 0) && found->second.at(0) == '.' && existingLength == (newLength + 1)) { writeChannelMapping = true; } else if (existingLength > newLength) { writeChannelMapping = false; } } if(writeChannelMapping){ _imp->_channel_map.insert(make_pair(channel,chanName)); } mask += channel; } }else { cout << "Cannot decode channel " << chan.name() << endl; } } const Imath::Box2i& datawin = _imp->_inputfile->header().dataWindow(); const Imath::Box2i& dispwin = _imp->_inputfile->header().displayWindow(); Imath::Box2i formatwin(dispwin); formatwin.min.x = 0; formatwin.min.y = 0; _imp->_dataOffset = 0; if (dispwin.min.x != 0) { // Shift both to get dispwindow over to 0,0. _imp->_dataOffset = -dispwin.min.x; formatwin.max.x = dispwin.max.x + _imp->_dataOffset; } formatwin.max.y = dispwin.max.y - dispwin.min.y; double aspect = _imp->_inputfile->header().pixelAspectRatio(); Format imageFormat(0,0,formatwin.max.x + 1 ,formatwin.max.y + 1,"",aspect); Box2D rod; int left = datawin.min.x + _imp->_dataOffset; int bottom = dispwin.max.y - datawin.max.y; int right = datawin.max.x + _imp->_dataOffset; int top = dispwin.max.y - datawin.min.y; if (datawin.min.x != dispwin.min.x || datawin.max.x != dispwin.max.x || datawin.min.y != dispwin.min.y || datawin.max.y != dispwin.max.y) { --left; --bottom; ++right; ++top; // _readerInfo->setBlackOutside(true); } rod.set(left, bottom, right+1, top+1); setReaderInfo(imageFormat, rod, mask); return Powiter::StatOK; } catch (const std::exception& exc) { cout << "OpenEXR error: " << exc.what() << endl; delete _imp->_inputfile; _imp->_inputfile = 0; return Powiter::StatFailed; } } ExrDecoder::ExrDecoder(Reader* op) : Decoder(op) , _imp(new Implementation) { } ExrDecoder::Implementation::Implementation() : _inputfile(0) , _dataOffset(0) #ifdef __POWITER_WIN32__ , _inputStr(NULL) , _inputStdStream(NULL) #endif { } void ExrDecoder::initializeColorSpace(){ _lut=Powiter::Color::getLut(Powiter::Color::LUT_DEFAULT_FLOAT); // linear color-space for exr files } ExrDecoder::~ExrDecoder(){ #ifdef __POWITER_WIN32__ delete _imp->_inputStr ; delete _imp->_inputStdStream ; #endif delete _imp->_inputfile; } void ExrDecoder::render(SequenceTime /*time*/,Powiter::Row* out){ const Powiter::ChannelSet& channels = out->channels(); const Imath::Box2i& dispwin = _imp->_inputfile->header().displayWindow(); const Imath::Box2i& datawin = _imp->_inputfile->header().dataWindow(); int exrY = dispwin.max.y - out->y(); int r = out->right(); int x = out->left(); const int X = std::max(x, datawin.min.x + _imp->_dataOffset); const int R = std::min(r, datawin.max.x + _imp->_dataOffset +1); // if we're below or above the data window if(exrY < datawin.min.y || exrY > datawin.max.y || R <= X) { out->eraseAll(); return; } Imf_::FrameBuffer fbuf; foreachChannels(z, channels){ // blacking out the extra padding we added float* dest = out->begin(z) - out->left(); for (int xx = x; xx < X; xx++) dest[xx] = 0; for (int xx = R; xx < r; xx++) dest[xx] = 0; ChannelsMap::const_iterator found = _imp->_channel_map.find(z); if(found != _imp->_channel_map.end()){ if(found->second != "BY" && found->second != "RY"){ // if it is NOT a subsampled buffer fbuf.insert(found->second.c_str(),Imf_::Slice(Imf_::FLOAT, (char*)(dest /*+_dataOffset*/),sizeof(float), 0)); }else{ fbuf.insert(found->second.c_str(),Imf_::Slice(Imf_::FLOAT, (char*)(dest /*+_dataOffset*/),sizeof(float), 0,2,2)); } }else{ //not found in the file, we zero it out // we're responsible for filling all channels requested by the row float fillValue = 0.f; if (z == Powiter::Channel_alpha) { fillValue = 1.f; } out->fill(z,fillValue); } } { QMutexLocker locker(&_imp->_lock); try { _imp->_inputfile->setFrameBuffer(fbuf); _imp->_inputfile->readPixels(exrY); } catch (const std::exception& exc) { cout << exc.what() << endl; return; } } // colorspace conversion const float* alpha = out->begin(Powiter::Channel_alpha); foreachChannels(z, channels){ float* to = out->begin(z) - out->left(); const float* from = out->begin(z) - out->left(); if(from){ from_float(z,to + X ,from + X,alpha, R-X,1); } } } <|endoftext|>
<commit_before>#pragma once #include "Renderer.h" #include "Camera.h" #include "View.h" #include "Renderables/Renderable.h" #include "Math/Vector3.h" #include "GLBlaat/GL.h" #include "GLBlaat/GLTexture.h" #include "GLBlaat/GLTextureManager.h" #include "GLBlaat/GLFramebuffer.h" #include "GLBlaat/GLUtility.h" #include <cassert> #include <iostream> #include <limits> namespace NQVTK { // ------------------------------------------------------------------------ Renderer::Renderer() : camera(0), view(0), tm(0), fboTarget(0) { viewportX = 0; viewportY = 0; viewportWidth = 1; viewportHeight = 1; lightOffsetDirection = 270.0; lightRelativeToCamera = true; } // ------------------------------------------------------------------------ Renderer::~Renderer() { delete camera; delete view; delete tm; } // ------------------------------------------------------------------------ bool Renderer::Initialize() { glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); // Make sure we have a camera GetCamera(); if (!tm) { tm = GLTextureManager::New(); if (!tm) { std::cerr << "Failed to create texture manager! " << "Check hardware requirements..." << std::endl; return false; } } tm->BeginNewPass(); return true; } // ------------------------------------------------------------------------ void Renderer::Move(int x, int y) { SetViewport(x, y, viewportWidth, viewportHeight); } // ------------------------------------------------------------------------ void Renderer::Resize(int w, int h) { SetViewport(viewportX, viewportY, w, h); } // ------------------------------------------------------------------------ void Renderer::SetViewport(int x, int y, int w, int h) { viewportX = x; viewportY = y; viewportWidth = w; viewportHeight = h; glViewport(viewportX, viewportY, viewportWidth, viewportHeight); GetCamera()->aspect = static_cast<double>(w) / static_cast<double>(h); // NOTE: The target is never resized by the renderer it's assigned to, // it should be managed by its owner! } // ------------------------------------------------------------------------ void Renderer::Clear() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } // ------------------------------------------------------------------------ void Renderer::SetScene(Scene *scene) { assert(scene); SetView(new View(scene)); } // ------------------------------------------------------------------------ void Renderer::SetView(View *view) { assert(view); if (view == this->view) return; delete this->view; this->view = view; } // ------------------------------------------------------------------------ Camera *Renderer::GetCamera() { // Create a default camera if we don't have one if (!camera) { camera = new Camera(); } return camera; } // ------------------------------------------------------------------------ void Renderer::SetCamera(Camera *cam) { if (camera) delete camera; camera = cam; } // ------------------------------------------------------------------------ GLFramebuffer *Renderer::SetTarget(GLFramebuffer *target) { GLFramebuffer *oldTarget = this->fboTarget; this->fboTarget = target; return oldTarget; } // ------------------------------------------------------------------------ void Renderer::DrawCamera() { // Get bounds for all visible renderables // TODO: this could be moved to the scene or the view const double inf = std::numeric_limits<double>::infinity(); double bounds[] = {inf, -inf, inf, -inf, inf, -inf}; if (view) { unsigned int numRenderables = view->GetNumberOfRenderables(); for (unsigned int i = 0; i < numRenderables; ++i) { Renderable *renderable = view->GetRenderable(i); if (view->GetVisibility(i)) { double rbounds[6]; renderable->GetBounds(rbounds); for (int i = 0; i < 3; ++i) { if (rbounds[i*2] < bounds[i*2]) bounds[i*2] = rbounds[i*2]; if (rbounds[i*2+1] > bounds[i*2+1]) bounds[i*2+1] = rbounds[i*2+1]; } } } } camera->SetZPlanes(bounds); // Set up the camera (matrices) camera->Draw(); } // ------------------------------------------------------------------------ void Renderer::ResetTextures() { // Reset texture manager binding cache tm->BeginNewPass(); } // ------------------------------------------------------------------------ void Renderer::UpdateLighting() { if (lightRelativeToCamera) { camera->Update(); const double DEGREES_TO_RADIANS = 0.0174532925199433; Vector3 viewDir = (camera->focus - camera->position); Vector3 sideDir = viewDir.cross(camera->up).normalized(); Vector3 upDir = sideDir.cross(viewDir).normalized(); Vector3 offset = -sin(lightOffsetDirection * DEGREES_TO_RADIANS) * sideDir - cos(lightOffsetDirection * DEGREES_TO_RADIANS) * upDir; offset *= viewDir.length() / 2.0; lightPos = camera->position + offset; } // Update OpenGL light direction Vector3 lightDir = (lightPos - camera->focus).normalized(); float ldir[] = { static_cast<float>(lightDir.x), static_cast<float>(lightDir.y), static_cast<float>(lightDir.z), 0.0f}; glLightfv(GL_LIGHT0, GL_POSITION, ldir); } // ------------------------------------------------------------------------ void Renderer::PrepareForRenderable(int objectId, Renderable *renderable) { } // ------------------------------------------------------------------------ void Renderer::DrawRenderables() { if (!view) return; // Iterate over all renderables in the scene and draw them for (int objectId = 0; objectId < view->GetNumberOfRenderables(); ++objectId) { // Visibility implies that the renderable is not null if (view->GetVisibility(objectId)) { Renderable *renderable = view->GetRenderable(objectId); PrepareForRenderable(objectId, renderable); renderable->Draw(); } } } // ------------------------------------------------------------------------ void Renderer::DrawTexture(GLTexture *tex, double xmin, double xmax, double ymin, double ymax) { if (!tex) return; glPushAttrib(GL_ALL_ATTRIB_BITS); glColor3d(1.0, 1.0, 1.0); glDisable(GL_DEPTH_TEST); glMatrixMode(GL_TEXTURE); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); tex->BindToCurrent(); glEnable(tex->GetTextureTarget()); if (tex->GetTextureTarget() == GL_TEXTURE_RECTANGLE_ARB) { glBegin(GL_QUADS); glTexCoord2d(0.0, 0.0); glVertex3d(xmin, ymin, 0.0); glTexCoord2d(tex->GetWidth(), 0.0); glVertex3d(xmax, ymin, 0.0); glTexCoord2d(tex->GetWidth(), tex->GetHeight()); glVertex3d(xmax, ymax, 0.0); glTexCoord2d(0.0, tex->GetHeight()); glVertex3d(xmin, ymax, 0.0); glEnd(); } else { glBegin(GL_QUADS); glTexCoord2d(0.0, 0.0); glVertex3d(xmin, ymin, 0.0); glTexCoord2d(1.0, 0.0); glVertex3d(xmax, ymin, 0.0); glTexCoord2d(1.0, 1.0); glVertex3d(xmax, ymax, 0.0); glTexCoord2d(0.0, 1.0); glVertex3d(xmin, ymax, 0.0); glEnd(); } glDisable(tex->GetTextureTarget()); tex->UnbindCurrent(); glPopAttrib(); } } <commit_msg>Enable scene to be set to null.<commit_after>#pragma once #include "Renderer.h" #include "Camera.h" #include "View.h" #include "Renderables/Renderable.h" #include "Math/Vector3.h" #include "GLBlaat/GL.h" #include "GLBlaat/GLTexture.h" #include "GLBlaat/GLTextureManager.h" #include "GLBlaat/GLFramebuffer.h" #include "GLBlaat/GLUtility.h" #include <cassert> #include <iostream> #include <limits> namespace NQVTK { // ------------------------------------------------------------------------ Renderer::Renderer() : camera(0), view(0), tm(0), fboTarget(0) { viewportX = 0; viewportY = 0; viewportWidth = 1; viewportHeight = 1; lightOffsetDirection = 270.0; lightRelativeToCamera = true; } // ------------------------------------------------------------------------ Renderer::~Renderer() { delete camera; delete view; delete tm; } // ------------------------------------------------------------------------ bool Renderer::Initialize() { glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); // Make sure we have a camera GetCamera(); if (!tm) { tm = GLTextureManager::New(); if (!tm) { std::cerr << "Failed to create texture manager! " << "Check hardware requirements..." << std::endl; return false; } } tm->BeginNewPass(); return true; } // ------------------------------------------------------------------------ void Renderer::Move(int x, int y) { SetViewport(x, y, viewportWidth, viewportHeight); } // ------------------------------------------------------------------------ void Renderer::Resize(int w, int h) { SetViewport(viewportX, viewportY, w, h); } // ------------------------------------------------------------------------ void Renderer::SetViewport(int x, int y, int w, int h) { viewportX = x; viewportY = y; viewportWidth = w; viewportHeight = h; glViewport(viewportX, viewportY, viewportWidth, viewportHeight); GetCamera()->aspect = static_cast<double>(w) / static_cast<double>(h); // NOTE: The target is never resized by the renderer it's assigned to, // it should be managed by its owner! } // ------------------------------------------------------------------------ void Renderer::Clear() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } // ------------------------------------------------------------------------ void Renderer::SetScene(Scene *scene) { if (scene) { SetView(new View(scene)); } else { SetView(0); } } // ------------------------------------------------------------------------ void Renderer::SetView(View *view) { if (view == this->view) return; delete this->view; this->view = view; } // ------------------------------------------------------------------------ Camera *Renderer::GetCamera() { // Create a default camera if we don't have one if (!camera) { camera = new Camera(); } return camera; } // ------------------------------------------------------------------------ void Renderer::SetCamera(Camera *cam) { if (camera) delete camera; camera = cam; } // ------------------------------------------------------------------------ GLFramebuffer *Renderer::SetTarget(GLFramebuffer *target) { GLFramebuffer *oldTarget = this->fboTarget; this->fboTarget = target; return oldTarget; } // ------------------------------------------------------------------------ void Renderer::DrawCamera() { // Get bounds for all visible renderables // TODO: this could be moved to the scene or the view const double inf = std::numeric_limits<double>::infinity(); double bounds[] = {inf, -inf, inf, -inf, inf, -inf}; if (view) { unsigned int numRenderables = view->GetNumberOfRenderables(); for (unsigned int i = 0; i < numRenderables; ++i) { Renderable *renderable = view->GetRenderable(i); if (view->GetVisibility(i)) { double rbounds[6]; renderable->GetBounds(rbounds); for (int i = 0; i < 3; ++i) { if (rbounds[i*2] < bounds[i*2]) bounds[i*2] = rbounds[i*2]; if (rbounds[i*2+1] > bounds[i*2+1]) bounds[i*2+1] = rbounds[i*2+1]; } } } } camera->SetZPlanes(bounds); // Set up the camera (matrices) camera->Draw(); } // ------------------------------------------------------------------------ void Renderer::ResetTextures() { // Reset texture manager binding cache tm->BeginNewPass(); } // ------------------------------------------------------------------------ void Renderer::UpdateLighting() { if (lightRelativeToCamera) { camera->Update(); const double DEGREES_TO_RADIANS = 0.0174532925199433; Vector3 viewDir = (camera->focus - camera->position); Vector3 sideDir = viewDir.cross(camera->up).normalized(); Vector3 upDir = sideDir.cross(viewDir).normalized(); Vector3 offset = -sin(lightOffsetDirection * DEGREES_TO_RADIANS) * sideDir - cos(lightOffsetDirection * DEGREES_TO_RADIANS) * upDir; offset *= viewDir.length() / 2.0; lightPos = camera->position + offset; } // Update OpenGL light direction Vector3 lightDir = (lightPos - camera->focus).normalized(); float ldir[] = { static_cast<float>(lightDir.x), static_cast<float>(lightDir.y), static_cast<float>(lightDir.z), 0.0f}; glLightfv(GL_LIGHT0, GL_POSITION, ldir); } // ------------------------------------------------------------------------ void Renderer::PrepareForRenderable(int objectId, Renderable *renderable) { } // ------------------------------------------------------------------------ void Renderer::DrawRenderables() { if (!view) return; // Iterate over all renderables in the scene and draw them for (int objectId = 0; objectId < view->GetNumberOfRenderables(); ++objectId) { // Visibility implies that the renderable is not null if (view->GetVisibility(objectId)) { Renderable *renderable = view->GetRenderable(objectId); PrepareForRenderable(objectId, renderable); renderable->Draw(); } } } // ------------------------------------------------------------------------ void Renderer::DrawTexture(GLTexture *tex, double xmin, double xmax, double ymin, double ymax) { if (!tex) return; glPushAttrib(GL_ALL_ATTRIB_BITS); glColor3d(1.0, 1.0, 1.0); glDisable(GL_DEPTH_TEST); glMatrixMode(GL_TEXTURE); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); tex->BindToCurrent(); glEnable(tex->GetTextureTarget()); if (tex->GetTextureTarget() == GL_TEXTURE_RECTANGLE_ARB) { glBegin(GL_QUADS); glTexCoord2d(0.0, 0.0); glVertex3d(xmin, ymin, 0.0); glTexCoord2d(tex->GetWidth(), 0.0); glVertex3d(xmax, ymin, 0.0); glTexCoord2d(tex->GetWidth(), tex->GetHeight()); glVertex3d(xmax, ymax, 0.0); glTexCoord2d(0.0, tex->GetHeight()); glVertex3d(xmin, ymax, 0.0); glEnd(); } else { glBegin(GL_QUADS); glTexCoord2d(0.0, 0.0); glVertex3d(xmin, ymin, 0.0); glTexCoord2d(1.0, 0.0); glVertex3d(xmax, ymin, 0.0); glTexCoord2d(1.0, 1.0); glVertex3d(xmax, ymax, 0.0); glTexCoord2d(0.0, 1.0); glVertex3d(xmin, ymax, 0.0); glEnd(); } glDisable(tex->GetTextureTarget()); tex->UnbindCurrent(); glPopAttrib(); } } <|endoftext|>
<commit_before>#include "BinaryTree.h" template<class Node> Tree<Node>::Tree() { root->x = 0; root->left = root->right = NULL; } template<class Node> Tree<Node>::Tree(Node* node) { root->x = node->x; root->left = node->left; root->right = node->right; } template<class Node> Tree<Node>::Tree(const Tree &node) { root->x = node.root->x; root->left = node.root->left; root->right = node.root->right; } template<class Node> int Tree<Node>::x_()const { return root->x; } template<class Node> Node* Tree<Node>::left_()const { return root->left; } template<class Node> Node* Tree<Node>::right_()const { return root->right; } template<class Node> void Tree<Node>::add(Node* newEl) { Node* El = NULL; Node* curEl = root; while (curEl != NULL) { El = curEl; if (newEl->x >= curEl->x) curEl = curEl->right; else curEl = curEl->left; } if (newEl->x >= El->x) El->right = newEl; else El->left = newEl; } template<class Node> Tree Tree<Node>::search(int x) { Node* curEl = root; while (curEl != NULL) { if (curEl->x == x) return curEl; else { if (x >= curEl->x) curEl = curEl->right; else curEl = curEl->left; } } return nullptr; } template<class Node> void Tree<Node>::fIn(string filename) { ifstream fin; fin.open(filename); Node* newEl = NULL; if (!fin.is_open()) cout << "The file isn't find" << endl; if (fin.eof()) return; else fin >> root->x; while (!fin.eof()) { fin >> newEl->x; add(newEl); } fin.close(); } template<class Node> void Tree<Node>::fOut(string filename)const { ofstream fout; fout.open(filename); Out(root); fout.close(); } template<class Node> void Tree<Node>::Out(Node* curEl)const { curEl = root; if (curEl != NULL) { cout << curEl->x; Out(curEl->left); Out(curEl->right); } } <commit_msg>Update BinaryTree.cpp<commit_after>#include "BinaryTree.h" template<class Node> Tree<Node>::Tree() { root->x = 0; root->left = root->right = NULL; } template<class Node> Tree<Node>::Tree(Node* node) { root->x = node->x; root->left = node->left; root->right = node->right; } template<class Node> Tree<Node>::Tree(const Tree &node) { root->x = node.root->x; root->left = node.root->left; root->right = node.root->right; } template<class Node> int Tree<Node>::x_()const { return root->x; } template<class Node> Node* Tree<Node>::left_()const { return root->left; } template<class Node> Node* Tree<Node>::right_()const { return root->right; } template<class Node> void Tree<Node>::add(Node* newEl) { Node* El = NULL; Node* curEl = root; while (curEl != NULL) { El = curEl; if (newEl->x >= curEl->x) curEl = curEl->right; else curEl = curEl->left; } if (newEl->x >= El->x) El->right = newEl; else El->left = newEl; } template<class Node> Tree Tree<Node>::search(int x) { Node* curEl = root; while (curEl != NULL) { if (curEl->x == x) return curEl; else { if (x >= curEl->x) curEl = curEl->right; else curEl = curEl->left; } } return nullptr; } template<class Node> void Tree<Node>::fIn(string filename) { ifstream fin; fin.open(filename); Node* newEl = NULL; if (!fin.is_open()) cout << "The file isn't find" << endl; if (fin.eof()) return; else fin >> root->x; while (!fin.eof()) { fin >> newEl->x; add(newEl); } fin.close(); } template<class Node> void Tree<Node>::fOut(string filename)const { ofstream fout; fout.open(filename); Out(root); fout.close(); } template<class Node> void Tree<Node>::Out(Node* curEl)const { curEl = root; if (curEl != NULL) { cout << curEl->x << endl; Out(curEl->left); Out(curEl->right); } } <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2008, Image Engine Design Inc. 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 Image Engine Design nor the names of any // other contributors to this software 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 <boost/python.hpp> #include <cassert> #include "boost/static_assert.hpp" #include "IECore/LineSegment.h" #include "IECore/bindings/LineSegmentBinding.h" using namespace boost::python; namespace IECore { template<class L> static const char *typeName() { BOOST_STATIC_ASSERT( sizeof(L) == 0 ); return ""; } template<> static const char *typeName<LineSegment2f>() { return "LineSegment2f"; } template<> static const char *typeName<LineSegment2d>() { return "LineSegment2d"; } template<> static const char *typeName<LineSegment3f>() { return "LineSegment3f"; } template<> static const char *typeName<LineSegment3d>() { return "LineSegment3d"; } template<class L> static std::string repr( L &x ) { std::stringstream s; s << "IECore." << typeName<L>() << "( "; object item0( x.p0 ); assert( item.attr0( "__repr__" ) != object() ); s << call_method< std::string >( item0.ptr(), "__repr__" ) << ", "; object item1( x.p1 ); assert( item.attr1( "__repr__" ) != object() ); s << call_method< std::string >( item1.ptr(), "__repr__" ) << " )"; return s.str(); } template<class L> static tuple closestPoints( const L &l, const L &l2 ) { typename L::Point a, b; a = l.closestPoints( l2, b ); return make_tuple( a, b ); } template<typename Vec> static void bind3D() { typedef typename Vec::BaseType BaseType; typedef LineSegment<Vec> L; typedef Imath::Matrix44<BaseType> M; const char *name = typeName< L >(); class_<L>( name ) .def( init<L>() ) .def( init<Vec, Vec>() ) .def_readwrite( "p0", &L::p0 ) .def_readwrite( "p1", &L::p1 ) .def( "__repr__", &repr<L> ) .def( "__call__", &L::operator() ) .def( "direction", &L::direction ) .def( "normalizedDirection", &L::normalizedDirection ) .def( "length", &L::length ) .def( "length2", &L::length2 ) .def( "closestPointTo", &L::closestPointTo ) .def( "closestPoints", &closestPoints<L> ) .def( "distanceTo", (typename L::BaseType (L::*)( const Vec & ) const)&L::distanceTo ) .def( "distanceTo", (typename L::BaseType (L::*)( const L & ) const)&L::distanceTo ) .def( "distance2To", (typename L::BaseType (L::*)( const Vec & ) const)&L::distance2To ) .def( "distance2To", (typename L::BaseType (L::*)( const L & ) const)&L::distance2To ) .def( self *= M() ) .def( self * M() ) .def( self == self ) .def( self != self ) /// \todo Bind the intersect methods when we have a binding for ImathPlane ; } template<typename Vec> static void bind2D() { typedef typename Vec::BaseType BaseType; typedef LineSegment<Vec> L; typedef Imath::Matrix33<BaseType> M; const char *name = typeName< L >(); class_<L>( name ) .def( init<L>() ) .def( init<Vec, Vec>() ) .def_readwrite( "p0", &L::p0 ) .def_readwrite( "p1", &L::p1 ) .def( "__repr__", &repr<L> ) .def( "__call__", &L::operator() ) .def( "direction", &L::direction ) .def( "normalizedDirection", &L::normalizedDirection ) .def( "length", &L::length ) .def( "length2", &L::length2 ) .def( "closestPointTo", &L::closestPointTo ) .def( "distanceTo", (typename L::BaseType (L::*)( const Vec & ) const)&L::distanceTo ) .def( "distance2To", (typename L::BaseType (L::*)( const Vec & ) const)&L::distance2To ) .def( self *= M() ) .def( self * M() ) .def( self == self ) .def( self != self ) ; } void bindLineSegment() { bind3D<Imath::V3f>(); bind3D<Imath::V3d>(); bind2D<Imath::V2f>(); bind2D<Imath::V2d>(); } } // namespace IECore <commit_msg>Fixed typos.<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2008, Image Engine Design Inc. 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 Image Engine Design nor the names of any // other contributors to this software 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 <boost/python.hpp> #include <cassert> #include "boost/static_assert.hpp" #include "IECore/LineSegment.h" #include "IECore/bindings/LineSegmentBinding.h" using namespace boost::python; namespace IECore { template<class L> static const char *typeName() { BOOST_STATIC_ASSERT( sizeof(L) == 0 ); return ""; } template<> static const char *typeName<LineSegment2f>() { return "LineSegment2f"; } template<> static const char *typeName<LineSegment2d>() { return "LineSegment2d"; } template<> static const char *typeName<LineSegment3f>() { return "LineSegment3f"; } template<> static const char *typeName<LineSegment3d>() { return "LineSegment3d"; } template<class L> static std::string repr( L &x ) { std::stringstream s; s << "IECore." << typeName<L>() << "( "; object item0( x.p0 ); assert( item0.attr( "__repr__" ) != object() ); s << call_method< std::string >( item0.ptr(), "__repr__" ) << ", "; object item1( x.p1 ); assert( item1.attr( "__repr__" ) != object() ); s << call_method< std::string >( item1.ptr(), "__repr__" ) << " )"; return s.str(); } template<class L> static tuple closestPoints( const L &l, const L &l2 ) { typename L::Point a, b; a = l.closestPoints( l2, b ); return make_tuple( a, b ); } template<typename Vec> static void bind3D() { typedef typename Vec::BaseType BaseType; typedef LineSegment<Vec> L; typedef Imath::Matrix44<BaseType> M; const char *name = typeName< L >(); class_<L>( name ) .def( init<L>() ) .def( init<Vec, Vec>() ) .def_readwrite( "p0", &L::p0 ) .def_readwrite( "p1", &L::p1 ) .def( "__repr__", &repr<L> ) .def( "__call__", &L::operator() ) .def( "direction", &L::direction ) .def( "normalizedDirection", &L::normalizedDirection ) .def( "length", &L::length ) .def( "length2", &L::length2 ) .def( "closestPointTo", &L::closestPointTo ) .def( "closestPoints", &closestPoints<L> ) .def( "distanceTo", (typename L::BaseType (L::*)( const Vec & ) const)&L::distanceTo ) .def( "distanceTo", (typename L::BaseType (L::*)( const L & ) const)&L::distanceTo ) .def( "distance2To", (typename L::BaseType (L::*)( const Vec & ) const)&L::distance2To ) .def( "distance2To", (typename L::BaseType (L::*)( const L & ) const)&L::distance2To ) .def( self *= M() ) .def( self * M() ) .def( self == self ) .def( self != self ) /// \todo Bind the intersect methods when we have a binding for ImathPlane ; } template<typename Vec> static void bind2D() { typedef typename Vec::BaseType BaseType; typedef LineSegment<Vec> L; typedef Imath::Matrix33<BaseType> M; const char *name = typeName< L >(); class_<L>( name ) .def( init<L>() ) .def( init<Vec, Vec>() ) .def_readwrite( "p0", &L::p0 ) .def_readwrite( "p1", &L::p1 ) .def( "__repr__", &repr<L> ) .def( "__call__", &L::operator() ) .def( "direction", &L::direction ) .def( "normalizedDirection", &L::normalizedDirection ) .def( "length", &L::length ) .def( "length2", &L::length2 ) .def( "closestPointTo", &L::closestPointTo ) .def( "distanceTo", (typename L::BaseType (L::*)( const Vec & ) const)&L::distanceTo ) .def( "distance2To", (typename L::BaseType (L::*)( const Vec & ) const)&L::distance2To ) .def( self *= M() ) .def( self * M() ) .def( self == self ) .def( self != self ) ; } void bindLineSegment() { bind3D<Imath::V3f>(); bind3D<Imath::V3d>(); bind2D<Imath::V2f>(); bind2D<Imath::V2d>(); } } // namespace IECore <|endoftext|>
<commit_before><commit_msg>Sketcher: [skip ci] fix computing of hotspot of sketcher icons on macOS<commit_after><|endoftext|>
<commit_before>#include "Railfence.h" /** * Sets the key to use * @param key - the key to use * @return - True if the key is valid and False otherwise */ bool Railfence::setKey(const string& mykey) { // validate the key, check if its empty if ((!mykey.empty())) { key = atoi(mykey.c_str()); return true; } else return false; } /** * Encrypts a plaintext string * @param plaintext - the plaintext string * @return - the encrypted ciphertext string */ string Railfence::encrypt(const string& plaintext) { string ciphertext = ""; vector<string> ctext(key, ""); // To contain the letters in the string for Railfence for (unsigned int i = 0; i < plaintext.size(); i++) { ctext.at(i % key).push_back(plaintext.at(i)); // Repeat and loop through each vector string and pushback a character } for (vector<string>::iterator it = ctext.begin(); it != ctext.end(); ++it) { ciphertext.append(*it); // Concatenate all the strings in order } return ciphertext; } /** * Decrypts a string of ciphertext * @param cipherText - the ciphertext * @return - the plaintext */ string Railfence::decrypt(const string& cipherText) { string plaintext = ""; vector<string> ptext(key, ""); // To contain the letters in the string for Railfence int textlength = cipherText.size() / key; // Store length of the string that is split by the size of the key int remainder = cipherText.size() % key; // Used to fill the remaining characters onto the first row int stringcount = 0; ptext.at(0).append(cipherText.substr(0,textlength + remainder)); // Append the first row with the remainder stringcount = textlength + remainder; for (unsigned int i = 1; i < key; i++) { ptext.at(i).append(cipherText.substr(stringcount,textlength)); // Append each vector row with the string split by key (textlength) stringcount += textlength; } // Go through every vector element, check if string is not empty, push back the first character and erase it. for (unsigned int i = 0; i <= textlength; i++) { for (unsigned int j = 0; j < key; j++) { if (!ptext.at(j).empty()) { plaintext.push_back(ptext.at(j).at(0)); ptext.at(j).erase(0,1); } } } return plaintext; } <commit_msg>Railfence - Fixed bug length<commit_after>#include "Railfence.h" /** * Sets the key to use * @param key - the key to use * @return - True if the key is valid and False otherwise */ bool Railfence::setKey(const string& mykey) { // validate the key, check if its empty if ((!mykey.empty())) { key = atoi(mykey.c_str()); return true; } else return false; } /** * Encrypts a plaintext string * @param plaintext - the plaintext string * @return - the encrypted ciphertext string */ string Railfence::encrypt(const string& plaintext) { string ciphertext = ""; vector<string> ctext(key, ""); // To contain the letters in the string for Railfence for (unsigned int i = 0; i < plaintext.size(); i++) { ctext.at(i % key).push_back(plaintext.at(i)); // Repeat and loop through each vector string and pushback a character } for (vector<string>::iterator it = ctext.begin(); it != ctext.end(); ++it) { ciphertext.append(*it); // Concatenate all the strings in order } return ciphertext; } /** * Decrypts a string of ciphertext * @param cipherText - the ciphertext * @return - the plaintext */ string Railfence::decrypt(const string& cipherText) { string plaintext = ""; vector<string> ptext(key, ""); // To contain the letters in the string for Railfence int textlength = cipherText.size() / key; // Store length of the string that is split by the size of the key int remainder = cipherText.size() % key; // Used to fill the remaining characters onto the first row int stringcount = 0; ptext.at(0).append(cipherText.substr(0,textlength + remainder)); // Append the first row with the remainder stringcount = textlength + remainder; for (unsigned int i = 1; i < key; i++) { ptext.at(i).append(cipherText.substr(stringcount,textlength)); // Append each vector row with the string split by key (textlength) stringcount += textlength; } // Go through every vector element, check if string is not empty, push back the first character and erase it. for (unsigned int i = 0; i < textlength + remainder; i++) { for (unsigned int j = 0; j < key; j++) { if (!ptext.at(j).empty()) { plaintext.push_back(ptext.at(j).at(0)); ptext.at(j).erase(0,1); } } } return plaintext; } <|endoftext|>
<commit_before>{ TProof::Open("pod://"); if (!gProof) return; TDSet *manual_dset = new TDSet("TTree", "deuterons"); TString user[3] = {"m/mpuccio","m/masera","s/sbufalin"}; for (int i = 0; i < 3; ++i) { TString ddset = Form("Find;BasePath=/alice/cern.ch/user/%s/NucleiPbPb2011test/output;FileName=*/root_archive.zip;Anchor=mpuccio_Flowdnt.root;Tree=/deuterons;Mode=local",user[i].Data()); TFileCollection *fc = gProof->GetDataSet(ddset.Data()); // Create TDSet manually (terrible hack): apparently PROOF is stupid // and cannot create it correctly TFileInfo *fi; TIter next( fc->GetList() ); while (( fi = (TFileInfo *)next() )) { const char *fn = fi->GetCurrentUrl()->GetUrl(); Printf("adding: %s", fn); manual_dset->Add( fn ); } } gSystem->Load("AODSelector.cxx++g"); const double kCent[5] = {0.,10.,20.,40.,60.}; const double kBins[29] = { 0.4f,0.5f,0.6f,0.7f,0.8f,0.9f,1.0f,1.1f,1.2f,1.4f, 1.6f,1.8f,2.0f,2.2f,2.4f,2.6f,2.8f,3.0f,3.2f,3.4f, 3.6f,3.8f,4.0f,4.2f,4.4f,5.0f,6.0f,8.0f,10.f }; AODSelector *sel = new AODSelector(); sel->SetPtBins(29,kBins); sel->SetCentBins(5,kCent); sel->SetOutputOption("deuterons3cent",kTRUE); // Process the TDset gProof->Process(manual_dset, sel); } <commit_msg>Correct way to invoke macro compilation<commit_after>{ TProof::Open("pod://"); if (!gProof) return; TDSet *manual_dset = new TDSet("TTree", "deuterons"); TString user[3] = {"m/mpuccio","m/masera","s/sbufalin"}; for (int i = 0; i < 3; ++i) { TString ddset = Form("Find;BasePath=/alice/cern.ch/user/%s/NucleiPbPb2011test/output;FileName=*/root_archive.zip;Anchor=mpuccio_Flowdnt.root;Tree=/deuterons;Mode=local",user[i].Data()); TFileCollection *fc = gProof->GetDataSet(ddset.Data()); // Create TDSet manually (terrible hack): apparently PROOF is stupid // and cannot create it correctly TFileInfo *fi; TIter next( fc->GetList() ); while (( fi = (TFileInfo *)next() )) { const char *fn = fi->GetCurrentUrl()->GetUrl(); Printf("adding: %s", fn); manual_dset->Add( fn ); } } gROOT->LoadMacro("AODSelector.cxx++g"); const double kCent[5] = {0.,10.,20.,40.,60.}; const double kBins[29] = { 0.4f,0.5f,0.6f,0.7f,0.8f,0.9f,1.0f,1.1f,1.2f,1.4f, 1.6f,1.8f,2.0f,2.2f,2.4f,2.6f,2.8f,3.0f,3.2f,3.4f, 3.6f,3.8f,4.0f,4.2f,4.4f,5.0f,6.0f,8.0f,10.f }; AODSelector *sel = new AODSelector(); sel->SetPtBins(29,kBins); sel->SetCentBins(5,kCent); sel->SetOutputOption("deuterons3cent",kTRUE); // Process the TDset gProof->Process(manual_dset, sel); } <|endoftext|>
<commit_before>// File: SalomeApp_PreferencesDlg.cxx // Author: Sergey TELKOV #include "SalomeApp_PreferencesDlg.h" #include "SalomeApp_Preferences.h" #include <qvbox.h> #include <qlayout.h> /*! Constructor. */ SalomeApp_PreferencesDlg::SalomeApp_PreferencesDlg( SalomeApp_Preferences* prefs, QWidget* parent ) : QtxDialog( parent, 0, true, false, OK | Close | Apply ), myPrefs( prefs ) { setCaption( tr( "CAPTION" ) ); QVBoxLayout* main = new QVBoxLayout( mainFrame(), 5 ); QVBox* base = new QVBox( mainFrame() ); main->addWidget( base ); myPrefs->reparent( base, QPoint( 0, 0 ), true ); setFocusProxy( myPrefs ); setButtonPosition( Right, Close ); setDialogFlags( AlignOnce ); connect( this, SIGNAL( dlgHelp() ), this, SLOT( onHelp() ) ); connect( this, SIGNAL( dlgApply() ), this, SLOT( onApply() ) ); } /*! Destructor. */ SalomeApp_PreferencesDlg::~SalomeApp_PreferencesDlg() { if ( !myPrefs ) return; myPrefs->reparent( 0, QPoint( 0, 0 ), false ); myPrefs = 0; } /*!Show dialog.*/ void SalomeApp_PreferencesDlg::show() { myPrefs->retrieve(); myPrefs->toBackup(); QtxDialog::show(); } /*!Store preferences on accept.*/ void SalomeApp_PreferencesDlg::accept() { QtxDialog::accept(); myPrefs->store(); } /*!Reject. Restore preferences from backup.*/ void SalomeApp_PreferencesDlg::reject() { QtxDialog::reject(); myPrefs->fromBackup(); } /*!Do nothing.*/ void SalomeApp_PreferencesDlg::onHelp() { } /*!Store preferences on apply.*/ void SalomeApp_PreferencesDlg::onApply() { myPrefs->store(); } <commit_msg>PAL10121 - apply in preferences dialog didn't work<commit_after>// File: SalomeApp_PreferencesDlg.cxx // Author: Sergey TELKOV #include "SalomeApp_PreferencesDlg.h" #include "SalomeApp_Preferences.h" #include <qvbox.h> #include <qlayout.h> /*! Constructor. */ SalomeApp_PreferencesDlg::SalomeApp_PreferencesDlg( SalomeApp_Preferences* prefs, QWidget* parent ) : QtxDialog( parent, 0, true, false, OK | Close | Apply ), myPrefs( prefs ) { setCaption( tr( "CAPTION" ) ); QVBoxLayout* main = new QVBoxLayout( mainFrame(), 5 ); QVBox* base = new QVBox( mainFrame() ); main->addWidget( base ); myPrefs->reparent( base, QPoint( 0, 0 ), true ); setFocusProxy( myPrefs ); setButtonPosition( Right, Close ); setDialogFlags( AlignOnce ); connect( this, SIGNAL( dlgHelp() ), this, SLOT( onHelp() ) ); connect( this, SIGNAL( dlgApply() ), this, SLOT( onApply() ) ); } /*! Destructor. */ SalomeApp_PreferencesDlg::~SalomeApp_PreferencesDlg() { if ( !myPrefs ) return; myPrefs->reparent( 0, QPoint( 0, 0 ), false ); myPrefs = 0; } /*!Show dialog.*/ void SalomeApp_PreferencesDlg::show() { myPrefs->retrieve(); myPrefs->toBackup(); QtxDialog::show(); } /*!Store preferences on accept.*/ void SalomeApp_PreferencesDlg::accept() { QtxDialog::accept(); myPrefs->store(); } /*!Reject. Restore preferences from backup.*/ void SalomeApp_PreferencesDlg::reject() { QtxDialog::reject(); myPrefs->fromBackup(); } /*!Do nothing.*/ void SalomeApp_PreferencesDlg::onHelp() { } /*!Store preferences on apply.*/ void SalomeApp_PreferencesDlg::onApply() { myPrefs->store(); myPrefs->toBackup(); } <|endoftext|>
<commit_before>/******************************************************************** * Copyright © 2016 Computational Molecular Biology Group, * * Freie Universität Berlin (GER) * * * * This file is part of ReaDDy. * * * * ReaDDy is free software: you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as * * published by the Free Software Foundation, either version 3 of * * the License, or (at your option) any later version. * * * * 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 Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General * * Public License along with this program. If not, see * * <http://www.gnu.org/licenses/>. * ********************************************************************/ /** * @file CPUCalculateForces.cpp * @author clonker * @date 1/3/18 */ #include "readdy/kernel/cpu/actions/CPUCalculateForces.h" namespace readdy { namespace kernel { namespace cpu { namespace actions { void CPUCalculateForces::perform(const util::PerformanceNode &node) { auto t = node.timeit(); const auto &ctx = kernel->context(); auto &stateModel = kernel->getCPUKernelStateModel(); auto neighborList = stateModel.getNeighborList(); auto data = stateModel.getParticleData(); auto taf = kernel->getTopologyActionFactory(); auto &topologies = stateModel.topologies(); stateModel.energy() = 0; stateModel.virial() = Matrix33{{{0, 0, 0, 0, 0, 0, 0, 0, 0}}}; const auto &potOrder1 = ctx.potentials().potentialsOrder1(); const auto &potOrder2 = ctx.potentials().potentialsOrder2(); if (!potOrder1.empty() || !potOrder2.empty() || !stateModel.topologies().empty()) { { // todo maybe optimize this by transposing data structure auto tClear = node.subnode("clear forces").timeit(); std::for_each(data->begin(), data->end(), [](auto &entry) { entry.force = {0, 0, 0}; }); } { auto &pool = data->pool(); std::vector<std::promise<scalar>> promises; std::vector<std::promise<Matrix33>> virialPromises; // 1st order pot + topologies = 2*pool size // 2nd order pot <= nl.nCells size_t nThreads = pool.size(); auto numberTasks = (!potOrder1.empty() ? nThreads : 0) + (!potOrder2.empty() ? nThreads : 0) + (!topologies.empty() ? nThreads : 0); { const auto &nTasks = node.subnode("create tasks"); auto tTasks = nTasks.timeit(); size_t nCells = neighborList->nCells(); promises.reserve(numberTasks); virialPromises.reserve(!potOrder2.empty() ? nThreads : 0); if (!potOrder1.empty()) { // 1st order pot auto tO1 = nTasks.subnode("order1").timeit(); std::vector<std::function<void(std::size_t)>> tasks; tasks.reserve(nThreads); const std::size_t grainSize = data->size() / nThreads; auto it = data->begin(); for (auto i = 0_z; i < nThreads - 1; ++i) { auto itNext = std::min(it + grainSize, data->end()); if (it != itNext) { promises.emplace_back(); auto dataBounds = std::make_tuple(it, itNext); tasks.push_back(pool.pack(calculate_order1, dataBounds, std::ref(promises.back()), data, ctx.potentials().potentialsOrder1(), ctx.shortestDifferenceFun())); } it = itNext; } if (it != data->end()) { promises.emplace_back(); auto dataBounds = std::make_tuple(it, data->end()); tasks.push_back(pool.pack(calculate_order1, dataBounds, std::ref(promises.back()), data, ctx.potentials().potentialsOrder1(), ctx.shortestDifferenceFun())); } { auto tPush = nTasks.subnode("execute order 1 tasks and wait").timeit(); auto futures = pool.pushAll(std::move(tasks)); std::vector<util::thread::joining_future<void>> joiningFutures; std::transform(futures.begin(), futures.end(), std::back_inserter(joiningFutures), [](auto &&future) { return util::thread::joining_future<void>{std::move(future)}; }); } } if (!topologies.empty()) { auto tTops = nTasks.subnode("topologies").timeit(); std::vector<std::function<void(std::size_t)>> tasks; tasks.reserve(nThreads); const std::size_t grainSize = topologies.size() / nThreads; auto it = topologies.cbegin(); for (auto i = 0_z; i < nThreads - 1; ++i) { auto itNext = std::min(it + grainSize, topologies.cend()); if (it != itNext) { promises.emplace_back(); auto bounds = std::make_tuple(it, itNext); tasks.push_back( pool.pack(calculate_topologies, bounds, taf, std::ref(promises.back()))); } it = itNext; } if (it != topologies.cend()) { promises.emplace_back(); auto bounds = std::make_tuple(it, topologies.cend()); tasks.push_back(pool.pack(calculate_topologies, bounds, taf, std::ref(promises.back()))); } { auto tPush = nTasks.subnode("execute topology tasks and wait").timeit(); auto futures = pool.pushAll(std::move(tasks)); std::vector<util::thread::joining_future<void>> joiningFutures; std::transform(futures.begin(), futures.end(), std::back_inserter(joiningFutures), [](auto &&future) { return util::thread::joining_future<void>{std::move(future)}; }); } } if (!potOrder2.empty()) { auto tO2 = nTasks.subnode("order2").timeit(); std::vector<std::function<void(std::size_t)>> tasks; tasks.reserve(nThreads); auto granularity = nThreads; const std::size_t grainSize = nCells / granularity; auto it = 0_z; for (auto i = 0_z; i < granularity - 1; ++i) { auto itNext = std::min(it + grainSize, nCells); if (it != itNext) { promises.emplace_back(); virialPromises.emplace_back(); if(ctx.recordVirial()) { tasks.push_back(pool.pack( calculate_order2<true>, std::make_tuple(it, itNext), data, std::cref(*neighborList), std::ref(promises.back()), std::ref(virialPromises.back()), ctx.potentials().potentialsOrder2(), ctx.shortestDifferenceFun() )); } else { tasks.push_back(pool.pack( calculate_order2<false>, std::make_tuple(it, itNext), data, std::cref(*neighborList), std::ref(promises.back()), std::ref(virialPromises.back()), ctx.potentials().potentialsOrder2(), ctx.shortestDifferenceFun() )); } } it = itNext; } if (it != nCells) { promises.emplace_back(); virialPromises.emplace_back(); if(ctx.recordVirial()) { tasks.push_back(pool.pack( calculate_order2<true>, std::make_tuple(it, nCells), data, std::cref(*neighborList), std::ref(promises.back()), std::ref(virialPromises.back()), ctx.potentials().potentialsOrder2(), ctx.shortestDifferenceFun() )); } else { tasks.push_back(pool.pack( calculate_order2<false>, std::make_tuple(it, nCells), data, std::cref(*neighborList), std::ref(promises.back()), std::ref(virialPromises.back()), ctx.potentials().potentialsOrder2(), ctx.shortestDifferenceFun() )); } } { auto tPush = nTasks.subnode("execute order 2 tasks and wait").timeit(); auto futures = pool.pushAll(std::move(tasks)); std::vector<util::thread::joining_future<void>> joiningFutures; std::transform(futures.begin(), futures.end(), std::back_inserter(joiningFutures), [](auto &&future) { return util::thread::joining_future<void>{std::move(future)}; }); } } } { auto tFutures = node.subnode("get energy futures").timeit(); for (auto &f : promises) { stateModel.energy() += f.get_future().get(); } } { auto tVirialFutures = node.subnode("get virial futures").timeit(); for (auto &f : virialPromises) { stateModel.virial() += f.get_future().get(); } } } } } template<bool COMPUTE_VIRIAL> void CPUCalculateForces::calculate_order2(std::size_t, nl_bounds nlBounds, CPUStateModel::data_type *data, const CPUStateModel::neighbor_list &nl, std::promise<scalar> &energyPromise, std::promise<Matrix33> &virialPromise, model::potentials::PotentialRegistry::potential_o2_registry pot2, model::Context::shortest_dist_fun d) { scalar energyUpdate = 0.0; Matrix33 virialUpdate{{{0, 0, 0, 0, 0, 0, 0, 0, 0}}}; // // 2nd order potentials // for (auto cell = std::get<0>(nlBounds); cell < std::get<1>(nlBounds); ++cell) { for (auto particleIt = nl.particlesBegin(cell); particleIt != nl.particlesEnd(cell); ++particleIt) { auto &entry = data->entry_at(*particleIt); if (entry.deactivated) { log::critical("deactivated particle in neighbor list!"); continue; } nl.forEachNeighbor(*particleIt, cell, [&](auto neighborIndex) { auto &neighbor = data->entry_at(neighborIndex); if (!neighbor.deactivated) { auto &force = entry.force; const auto &myPos = entry.pos; // // 2nd order potentials // scalar mySecondOrderEnergy = 0.; auto potit = pot2.find(std::tie(entry.type, neighbor.type)); if (potit != pot2.end()) { auto x_ij = d(myPos, neighbor.pos); auto distSquared = x_ij * x_ij; for (const auto &potential : potit->second) { if (distSquared < potential->getCutoffRadiusSquared()) { Vec3 forceUpdate{0, 0, 0}; potential->calculateForceAndEnergy(forceUpdate, mySecondOrderEnergy, x_ij); force += forceUpdate; if(COMPUTE_VIRIAL && *particleIt < neighborIndex) { virialUpdate += math::outerProduct(-1.*x_ij, force); } } } } // The contribution of second order potentials must be halved since we parallelize over particles. // Thus every particle pair potential is seen twice energyUpdate += 0.5 * mySecondOrderEnergy; } else { log::critical("disabled neighbour"); } }); } } energyPromise.set_value(energyUpdate); virialPromise.set_value(virialUpdate); } void CPUCalculateForces::calculate_topologies(std::size_t, top_bounds topBounds, model::top::TopologyActionFactory *taf, std::promise<scalar> &energyPromise) { scalar energyUpdate = 0.0; for (auto it = std::get<0>(topBounds); it != std::get<1>(topBounds); ++it) { const auto &top = *it; if (!top->isDeactivated()) { for (const auto &bondedPot : top->getBondedPotentials()) { auto energy = bondedPot->createForceAndEnergyAction(taf)->perform(top.get()); energyUpdate += energy; } for (const auto &anglePot : top->getAnglePotentials()) { auto energy = anglePot->createForceAndEnergyAction(taf)->perform(top.get()); energyUpdate += energy; } for (const auto &torsionPot : top->getTorsionPotentials()) { auto energy = torsionPot->createForceAndEnergyAction(taf)->perform(top.get()); energyUpdate += energy; } } } energyPromise.set_value(energyUpdate); } void CPUCalculateForces::calculate_order1(std::size_t, data_bounds dataBounds, std::promise<scalar> &energyPromise, CPUStateModel::data_type *data, model::potentials::PotentialRegistry::potential_o1_registry pot1, model::Context::shortest_dist_fun d) { scalar energyUpdate = 0.0; // // 1st order potentials // for (auto it = std::get<0>(dataBounds); it != std::get<1>(dataBounds); ++it) { auto &entry = *it; if (!entry.deactivated) { auto &force = entry.force; force = {c_::zero, c_::zero, c_::zero}; const auto &myPos = entry.pos; auto find_it = pot1.find(entry.type); if (find_it != pot1.end()) { for (const auto &potential : find_it->second) { potential->calculateForceAndEnergy(force, energyUpdate, myPos); } } } } energyPromise.set_value(energyUpdate); } } } } } <commit_msg>fix in virial computation<commit_after>/******************************************************************** * Copyright © 2016 Computational Molecular Biology Group, * * Freie Universität Berlin (GER) * * * * This file is part of ReaDDy. * * * * ReaDDy is free software: you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as * * published by the Free Software Foundation, either version 3 of * * the License, or (at your option) any later version. * * * * 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 Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General * * Public License along with this program. If not, see * * <http://www.gnu.org/licenses/>. * ********************************************************************/ /** * @file CPUCalculateForces.cpp * @author clonker * @date 1/3/18 */ #include "readdy/kernel/cpu/actions/CPUCalculateForces.h" namespace readdy { namespace kernel { namespace cpu { namespace actions { void CPUCalculateForces::perform(const util::PerformanceNode &node) { auto t = node.timeit(); const auto &ctx = kernel->context(); auto &stateModel = kernel->getCPUKernelStateModel(); auto neighborList = stateModel.getNeighborList(); auto data = stateModel.getParticleData(); auto taf = kernel->getTopologyActionFactory(); auto &topologies = stateModel.topologies(); stateModel.energy() = 0; stateModel.virial() = Matrix33{{{0, 0, 0, 0, 0, 0, 0, 0, 0}}}; const auto &potOrder1 = ctx.potentials().potentialsOrder1(); const auto &potOrder2 = ctx.potentials().potentialsOrder2(); if (!potOrder1.empty() || !potOrder2.empty() || !stateModel.topologies().empty()) { { // todo maybe optimize this by transposing data structure auto tClear = node.subnode("clear forces").timeit(); std::for_each(data->begin(), data->end(), [](auto &entry) { entry.force = {0, 0, 0}; }); } { auto &pool = data->pool(); std::vector<std::promise<scalar>> promises; std::vector<std::promise<Matrix33>> virialPromises; // 1st order pot + topologies = 2*pool size // 2nd order pot <= nl.nCells size_t nThreads = pool.size(); auto numberTasks = (!potOrder1.empty() ? nThreads : 0) + (!potOrder2.empty() ? nThreads : 0) + (!topologies.empty() ? nThreads : 0); { const auto &nTasks = node.subnode("create tasks"); auto tTasks = nTasks.timeit(); size_t nCells = neighborList->nCells(); promises.reserve(numberTasks); virialPromises.reserve(!potOrder2.empty() ? nThreads : 0); if (!potOrder1.empty()) { // 1st order pot auto tO1 = nTasks.subnode("order1").timeit(); std::vector<std::function<void(std::size_t)>> tasks; tasks.reserve(nThreads); const std::size_t grainSize = data->size() / nThreads; auto it = data->begin(); for (auto i = 0_z; i < nThreads - 1; ++i) { auto itNext = std::min(it + grainSize, data->end()); if (it != itNext) { promises.emplace_back(); auto dataBounds = std::make_tuple(it, itNext); tasks.push_back(pool.pack(calculate_order1, dataBounds, std::ref(promises.back()), data, ctx.potentials().potentialsOrder1(), ctx.shortestDifferenceFun())); } it = itNext; } if (it != data->end()) { promises.emplace_back(); auto dataBounds = std::make_tuple(it, data->end()); tasks.push_back(pool.pack(calculate_order1, dataBounds, std::ref(promises.back()), data, ctx.potentials().potentialsOrder1(), ctx.shortestDifferenceFun())); } { auto tPush = nTasks.subnode("execute order 1 tasks and wait").timeit(); auto futures = pool.pushAll(std::move(tasks)); std::vector<util::thread::joining_future<void>> joiningFutures; std::transform(futures.begin(), futures.end(), std::back_inserter(joiningFutures), [](auto &&future) { return util::thread::joining_future<void>{std::move(future)}; }); } } if (!topologies.empty()) { auto tTops = nTasks.subnode("topologies").timeit(); std::vector<std::function<void(std::size_t)>> tasks; tasks.reserve(nThreads); const std::size_t grainSize = topologies.size() / nThreads; auto it = topologies.cbegin(); for (auto i = 0_z; i < nThreads - 1; ++i) { auto itNext = std::min(it + grainSize, topologies.cend()); if (it != itNext) { promises.emplace_back(); auto bounds = std::make_tuple(it, itNext); tasks.push_back( pool.pack(calculate_topologies, bounds, taf, std::ref(promises.back()))); } it = itNext; } if (it != topologies.cend()) { promises.emplace_back(); auto bounds = std::make_tuple(it, topologies.cend()); tasks.push_back(pool.pack(calculate_topologies, bounds, taf, std::ref(promises.back()))); } { auto tPush = nTasks.subnode("execute topology tasks and wait").timeit(); auto futures = pool.pushAll(std::move(tasks)); std::vector<util::thread::joining_future<void>> joiningFutures; std::transform(futures.begin(), futures.end(), std::back_inserter(joiningFutures), [](auto &&future) { return util::thread::joining_future<void>{std::move(future)}; }); } } if (!potOrder2.empty()) { auto tO2 = nTasks.subnode("order2").timeit(); std::vector<std::function<void(std::size_t)>> tasks; tasks.reserve(nThreads); auto granularity = nThreads; const std::size_t grainSize = nCells / granularity; auto it = 0_z; for (auto i = 0_z; i < granularity - 1; ++i) { auto itNext = std::min(it + grainSize, nCells); if (it != itNext) { promises.emplace_back(); virialPromises.emplace_back(); if(ctx.recordVirial()) { tasks.push_back(pool.pack( calculate_order2<true>, std::make_tuple(it, itNext), data, std::cref(*neighborList), std::ref(promises.back()), std::ref(virialPromises.back()), ctx.potentials().potentialsOrder2(), ctx.shortestDifferenceFun() )); } else { tasks.push_back(pool.pack( calculate_order2<false>, std::make_tuple(it, itNext), data, std::cref(*neighborList), std::ref(promises.back()), std::ref(virialPromises.back()), ctx.potentials().potentialsOrder2(), ctx.shortestDifferenceFun() )); } } it = itNext; } if (it != nCells) { promises.emplace_back(); virialPromises.emplace_back(); if(ctx.recordVirial()) { tasks.push_back(pool.pack( calculate_order2<true>, std::make_tuple(it, nCells), data, std::cref(*neighborList), std::ref(promises.back()), std::ref(virialPromises.back()), ctx.potentials().potentialsOrder2(), ctx.shortestDifferenceFun() )); } else { tasks.push_back(pool.pack( calculate_order2<false>, std::make_tuple(it, nCells), data, std::cref(*neighborList), std::ref(promises.back()), std::ref(virialPromises.back()), ctx.potentials().potentialsOrder2(), ctx.shortestDifferenceFun() )); } } { auto tPush = nTasks.subnode("execute order 2 tasks and wait").timeit(); auto futures = pool.pushAll(std::move(tasks)); std::vector<util::thread::joining_future<void>> joiningFutures; std::transform(futures.begin(), futures.end(), std::back_inserter(joiningFutures), [](auto &&future) { return util::thread::joining_future<void>{std::move(future)}; }); } } } { auto tFutures = node.subnode("get energy futures").timeit(); for (auto &f : promises) { stateModel.energy() += f.get_future().get(); } } { auto tVirialFutures = node.subnode("get virial futures").timeit(); for (auto &f : virialPromises) { stateModel.virial() += f.get_future().get(); } } } } } template<bool COMPUTE_VIRIAL> void CPUCalculateForces::calculate_order2(std::size_t, nl_bounds nlBounds, CPUStateModel::data_type *data, const CPUStateModel::neighbor_list &nl, std::promise<scalar> &energyPromise, std::promise<Matrix33> &virialPromise, model::potentials::PotentialRegistry::potential_o2_registry pot2, model::Context::shortest_dist_fun d) { scalar energyUpdate = 0.0; Matrix33 virialUpdate{{{0, 0, 0, 0, 0, 0, 0, 0, 0}}}; // // 2nd order potentials // for (auto cell = std::get<0>(nlBounds); cell < std::get<1>(nlBounds); ++cell) { for (auto particleIt = nl.particlesBegin(cell); particleIt != nl.particlesEnd(cell); ++particleIt) { auto &entry = data->entry_at(*particleIt); if (entry.deactivated) { log::critical("deactivated particle in neighbor list!"); continue; } nl.forEachNeighbor(*particleIt, cell, [&](auto neighborIndex) { auto &neighbor = data->entry_at(neighborIndex); if (!neighbor.deactivated) { auto &force = entry.force; const auto &myPos = entry.pos; // // 2nd order potentials // scalar mySecondOrderEnergy = 0.; auto potit = pot2.find(std::tie(entry.type, neighbor.type)); if (potit != pot2.end()) { auto x_ij = d(myPos, neighbor.pos); auto distSquared = x_ij * x_ij; for (const auto &potential : potit->second) { if (distSquared < potential->getCutoffRadiusSquared()) { Vec3 forceUpdate{0, 0, 0}; potential->calculateForceAndEnergy(forceUpdate, mySecondOrderEnergy, x_ij); force += forceUpdate; if(COMPUTE_VIRIAL && *particleIt < neighborIndex) { virialUpdate += math::outerProduct(-1.*x_ij, forceUpdate); } } } } // The contribution of second order potentials must be halved since we parallelize over particles. // Thus every particle pair potential is seen twice energyUpdate += 0.5 * mySecondOrderEnergy; } else { log::critical("disabled neighbour"); } }); } } energyPromise.set_value(energyUpdate); virialPromise.set_value(virialUpdate); } void CPUCalculateForces::calculate_topologies(std::size_t, top_bounds topBounds, model::top::TopologyActionFactory *taf, std::promise<scalar> &energyPromise) { scalar energyUpdate = 0.0; for (auto it = std::get<0>(topBounds); it != std::get<1>(topBounds); ++it) { const auto &top = *it; if (!top->isDeactivated()) { for (const auto &bondedPot : top->getBondedPotentials()) { auto energy = bondedPot->createForceAndEnergyAction(taf)->perform(top.get()); energyUpdate += energy; } for (const auto &anglePot : top->getAnglePotentials()) { auto energy = anglePot->createForceAndEnergyAction(taf)->perform(top.get()); energyUpdate += energy; } for (const auto &torsionPot : top->getTorsionPotentials()) { auto energy = torsionPot->createForceAndEnergyAction(taf)->perform(top.get()); energyUpdate += energy; } } } energyPromise.set_value(energyUpdate); } void CPUCalculateForces::calculate_order1(std::size_t, data_bounds dataBounds, std::promise<scalar> &energyPromise, CPUStateModel::data_type *data, model::potentials::PotentialRegistry::potential_o1_registry pot1, model::Context::shortest_dist_fun d) { scalar energyUpdate = 0.0; // // 1st order potentials // for (auto it = std::get<0>(dataBounds); it != std::get<1>(dataBounds); ++it) { auto &entry = *it; if (!entry.deactivated) { auto &force = entry.force; force = {c_::zero, c_::zero, c_::zero}; const auto &myPos = entry.pos; auto find_it = pot1.find(entry.type); if (find_it != pot1.end()) { for (const auto &potential : find_it->second) { potential->calculateForceAndEnergy(force, energyUpdate, myPos); } } } } energyPromise.set_value(energyUpdate); } } } } } <|endoftext|>
<commit_before>#pragma once //std #include <algorithm> //glm #include <glm\glm.hpp> #include <glm\ext.hpp> //mandala #include "collision.hpp" #include "input_event.hpp" #include "gui_node.hpp" #include "gpu.hpp" #if defined(DEBUG) #include "line_renderer.hpp" #endif namespace mandala { void gui_node_t::orphan() { if (parent.get() == nullptr) { throw std::exception("cannot orphan a node with no parent"); } auto parent_children_itr = std::find(parent->children.begin(), parent->children.end(), parent); if (parent_children_itr == parent->children.end()) { throw std::exception("parent does not have this node as a child"); } //remove node from parent's child list parent->children.erase(parent_children_itr); //TODO: might be able to forego dirtying parent if removing this node doesn't //affect positioning of sibling elements or sizing of parent element //if (dock_mode != gui_dock_mode_e::NONE) //mark parent as dirty parent->dirty(); //unparent parent = nullptr; //uproot root = nullptr; //mark as dirty dirty(); } void gui_node_t::adopt(const boost::shared_ptr<gui_node_t>& node) { if (node == nullptr) { throw std::invalid_argument("node cannot be null"); } if (node.get() == this) { throw std::invalid_argument("nodes cannot adopt themselves"); } if (node->has_parent()) { //orphan node from parent node->orphan(); } const auto children_itr = std::find(children.begin(), children.end(), node); if (children_itr != children.end()) { throw std::exception("node is already a child"); } //add node to child list children.push_back(node); //set node's new parent node->parent = shared_from_this(); //set node's new root node->root = root ? root : shared_from_this(); //mark as dirty dirty(); } void gui_node_t::clean() { std::function<void(boost::shared_ptr<gui_node_t>&, aabb2_t&)> clean_node = [&clean_node](boost::shared_ptr<gui_node_t>& node, aabb2_t& sibling_bounds) { node->on_clean_begin(); auto absolute_desired_size = node->desired_size; if (node->get_size_modes_real().get_x() == gui_size_mode_e::RELATIVE) { if (node->has_parent()) { absolute_desired_size.x *= node->parent->bounds.size().x - node->parent->padding.horizontal(); } else { absolute_desired_size.x *= sibling_bounds.size().x; } } if (node->get_size_modes_real().get_y() == gui_size_mode_e::RELATIVE) { if (node->has_parent()) { absolute_desired_size.y *= node->parent->bounds.size().y - node->parent->padding.vertical(); } else { absolute_desired_size.y *= sibling_bounds.size().y; } } if (node->get_size_modes_real().get_x() == gui_size_mode_e::AXIS_SCALE) { switch (node->dock_mode) { case gui_dock_mode_e::LEFT: case gui_dock_mode_e::RIGHT: absolute_desired_size.x = sibling_bounds.height() * node->desired_size.x; break; case gui_dock_mode_e::NONE: absolute_desired_size.x *= absolute_desired_size.y; break; default: break; } } else if (node->get_size_modes_real().get_y() == gui_size_mode_e::AXIS_SCALE) { switch (node->dock_mode) { case gui_dock_mode_e::BOTTOM: case gui_dock_mode_e::TOP: absolute_desired_size.y = sibling_bounds.width() * node->desired_size.y; break; case gui_dock_mode_e::NONE: absolute_desired_size.y *= absolute_desired_size.x; break; default: break; } } switch (node->dock_mode) { case gui_dock_mode_e::BOTTOM: node->bounds.min = sibling_bounds.min; node->bounds.max.x = sibling_bounds.max.x; node->bounds.max.y = sibling_bounds.min.y + absolute_desired_size.y + node->padding.vertical(); node->bounds -= node->margin; sibling_bounds.min.y += node->bounds.height() + node->margin.vertical(); break; case gui_dock_mode_e::FILL: node->bounds = sibling_bounds - node->margin; break; case gui_dock_mode_e::LEFT: node->bounds.min = sibling_bounds.min; node->bounds.max.x = sibling_bounds.min.x + absolute_desired_size.x + node->padding.horizontal(); node->bounds.max.y = sibling_bounds.max.y; node->bounds -= node->margin; sibling_bounds.min.x += node->bounds.width() + node->margin.horizontal(); break; case gui_dock_mode_e::RIGHT: node->bounds.min.x = sibling_bounds.max.x - absolute_desired_size.x - node->padding.horizontal(); node->bounds.min.y = sibling_bounds.min.y; node->bounds.max = sibling_bounds.max; node->bounds -= node->margin; sibling_bounds.max.x -= node->bounds.width() + node->margin.horizontal(); break; case gui_dock_mode_e::TOP: node->bounds.min.x = sibling_bounds.min.x; node->bounds.min.y = sibling_bounds.max.y - absolute_desired_size.y - node->padding.vertical(); node->bounds.max = sibling_bounds.max; node->bounds -= node->margin; sibling_bounds.max.y -= node->bounds.height() + node->margin.vertical(); break; default: node->bounds.min = vec2_t(0); node->bounds.max = absolute_desired_size; if (node->has_parent()) { node->bounds += vec2_t(node->parent->padding.left, node->parent->padding.bottom); } vec2_t anchor_location; vec2_t anchor_translation; if ((node->anchor_flags & GUI_ANCHOR_FLAG_HORIZONTAL) == GUI_ANCHOR_FLAG_HORIZONTAL) { anchor_location.x = (sibling_bounds.max.x - sibling_bounds.min.x) / 2; anchor_translation.x = -((absolute_desired_size.x / 2) + ((node->margin.right - node->margin.left) / 2)); } else { if ((node->anchor_flags & GUI_ANCHOR_FLAG_LEFT) == GUI_ANCHOR_FLAG_LEFT) { anchor_location.x = sibling_bounds.min.x; anchor_translation.x = node->margin.left; } else if ((node->anchor_flags & GUI_ANCHOR_FLAG_RIGHT) == GUI_ANCHOR_FLAG_RIGHT) { anchor_location.x = sibling_bounds.max.x; anchor_translation.x = -(absolute_desired_size.x + node->margin.right); } } if ((node->anchor_flags & GUI_ANCHOR_FLAG_VERTICAL) == GUI_ANCHOR_FLAG_VERTICAL) { anchor_location.y = (sibling_bounds.max.y - sibling_bounds.min.y) / 2; anchor_translation.y = -((absolute_desired_size.y / 2) + ((node->margin.top - node->margin.bottom) / 2)); } else { if ((node->anchor_flags & GUI_ANCHOR_FLAG_BOTTOM) == GUI_ANCHOR_FLAG_BOTTOM) { anchor_location.y = sibling_bounds.min.y; anchor_translation.y = node->margin.bottom; } else if ((node->anchor_flags & GUI_ANCHOR_FLAG_TOP) == GUI_ANCHOR_FLAG_TOP) { anchor_location.y = sibling_bounds.max.y; anchor_translation.y = -(absolute_desired_size.y + node->margin.top); } } node->bounds += anchor_location + anchor_translation + node->anchor_offset; break; } node->size = node->bounds.size(); auto children_bounds = node->bounds - node->padding; for (auto child : node->children) { clean_node(child, children_bounds); } node->is_dirty = false; node->on_clean_end(); }; //HACK: something is amiss with this way of doing things. //margins can be accumulated with every tick unless we //pad the bounds passed into clean_node. this seems incorrect, //but will work for now. auto padded_bounds = bounds + margin; clean_node(shared_from_this(), padded_bounds); } void gui_node_t::tick(float32_t dt) { on_tick_begin(dt); for (auto child : children) { child->tick(dt); } on_tick_end(dt); } bool gui_node_t::on_input_event(input_event_t& input_event) { for (auto children_itr = children.begin(); children_itr != children.end(); ++children_itr) { if ((*children_itr)->on_input_event(input_event)) { return true; } } return false; } const gui_size_modes_t gui_node_t::get_size_modes_real() const { auto real_size_modes = size_modes; if (real_size_modes.get_x() == gui_size_mode_e::INHERIT) { if (parent) { real_size_modes.set_x(parent->get_size_modes_real().get_x()); } else { real_size_modes.set_x(gui_size_mode_e::ABSOLUTE); } } if (real_size_modes.get_y() == gui_size_mode_e::INHERIT) { if (parent) { real_size_modes.set_y(parent->get_size_modes_real().get_y()); } else { real_size_modes.set_y(gui_size_mode_e::ABSOLUTE); } } return real_size_modes; } void gui_node_t::dirty() { if (is_dirty) { return; } is_dirty = true; if (parent) { parent->dirty(); } } void gui_node_t::render(mat4_t world_matrix, mat4_t view_projection_matrix) { if (is_hidden) { return; } //TODO: debug rendering? bool should_clip = this->should_clip; //temporary variable in case value changes during render calls somehow if (should_clip) { //stencil auto gpu_stencil_state = gpu.stencil.get_state(); gpu_stencil_state.is_enabled = true; gpu_stencil_state.function.func = gpu_t::stencil_function_e::NEVER; gpu_stencil_state.function.ref = 1; gpu_stencil_state.function.mask = 0xFF; gpu_stencil_state.operations.fail = gpu_t::stencil_operation_e::REPLACE; gpu_stencil_state.operations.zfail = gpu_t::stencil_operation_e::KEEP; gpu_stencil_state.operations.zpass = gpu_t::stencil_operation_e::KEEP; gpu_stencil_state.mask = 0xFF; gpu.stencil.push_state(gpu_stencil_state); //color auto gpu_color_state = gpu.color.get_state(); gpu_color_state.mask.r = false; gpu_color_state.mask.g = false; gpu_color_state.mask.b = false; gpu_color_state.mask.a = false; gpu.color.push_state(gpu_color_state); //depth auto gpu_depth_state = gpu.depth.get_state(); gpu_depth_state.should_write_mask = false; gpu.depth.push_state(gpu_depth_state); gpu.clear(gpu_t::CLEAR_FLAG_DEPTH | gpu_t::CLEAR_FLAG_STENCIL); render_rectangle(world_matrix, view_projection_matrix, rectangle_t(bounds), true); gpu.color.pop_state(); gpu.depth.pop_state(); gpu_stencil_state.mask = 0; gpu_stencil_state.function.func = gpu_t::stencil_function_e::NOTEQUAL; gpu_stencil_state.function.ref = 0; gpu_stencil_state.function.mask = 0xFF; gpu.stencil.pop_state(); gpu.stencil.push_state(gpu_stencil_state); } //TODO: configure this to be enable-able in-game #if defined(DEBUG) render_rectangle(world_matrix, view_projection_matrix, rectangle_t(bounds)); #endif on_render_begin(world_matrix, view_projection_matrix); for (auto& child : children) { child->render(world_matrix, view_projection_matrix); } on_render_end(world_matrix, view_projection_matrix); if (should_clip) { gpu.stencil.pop_state(); } } } <commit_msg>fix for bad anchoring when using horizontal or vertical anchor flags<commit_after>#pragma once //std #include <algorithm> //glm #include <glm\glm.hpp> #include <glm\ext.hpp> //mandala #include "collision.hpp" #include "input_event.hpp" #include "gui_node.hpp" #include "gpu.hpp" #if defined(DEBUG) #include "line_renderer.hpp" #endif namespace mandala { void gui_node_t::orphan() { if (parent.get() == nullptr) { throw std::exception("cannot orphan a node with no parent"); } auto parent_children_itr = std::find(parent->children.begin(), parent->children.end(), parent); if (parent_children_itr == parent->children.end()) { throw std::exception("parent does not have this node as a child"); } //remove node from parent's child list parent->children.erase(parent_children_itr); //TODO: might be able to forego dirtying parent if removing this node doesn't //affect positioning of sibling elements or sizing of parent element //if (dock_mode != gui_dock_mode_e::NONE) //mark parent as dirty parent->dirty(); //unparent parent = nullptr; //uproot root = nullptr; //mark as dirty dirty(); } void gui_node_t::adopt(const boost::shared_ptr<gui_node_t>& node) { if (node == nullptr) { throw std::invalid_argument("node cannot be null"); } if (node.get() == this) { throw std::invalid_argument("nodes cannot adopt themselves"); } if (node->has_parent()) { //orphan node from parent node->orphan(); } const auto children_itr = std::find(children.begin(), children.end(), node); if (children_itr != children.end()) { throw std::exception("node is already a child"); } //add node to child list children.push_back(node); //set node's new parent node->parent = shared_from_this(); //set node's new root node->root = root ? root : shared_from_this(); //mark as dirty dirty(); } void gui_node_t::clean() { std::function<void(boost::shared_ptr<gui_node_t>&, aabb2_t&)> clean_node = [&clean_node](boost::shared_ptr<gui_node_t>& node, aabb2_t& sibling_bounds) { node->on_clean_begin(); auto absolute_desired_size = node->desired_size; if (node->get_size_modes_real().get_x() == gui_size_mode_e::RELATIVE) { if (node->has_parent()) { absolute_desired_size.x *= node->parent->bounds.size().x - node->parent->padding.horizontal(); } else { absolute_desired_size.x *= sibling_bounds.size().x; } } if (node->get_size_modes_real().get_y() == gui_size_mode_e::RELATIVE) { if (node->has_parent()) { absolute_desired_size.y *= node->parent->bounds.size().y - node->parent->padding.vertical(); } else { absolute_desired_size.y *= sibling_bounds.size().y; } } if (node->get_size_modes_real().get_x() == gui_size_mode_e::AXIS_SCALE) { switch (node->dock_mode) { case gui_dock_mode_e::LEFT: case gui_dock_mode_e::RIGHT: absolute_desired_size.x = sibling_bounds.height() * node->desired_size.x; break; case gui_dock_mode_e::NONE: absolute_desired_size.x *= absolute_desired_size.y; break; default: break; } } else if (node->get_size_modes_real().get_y() == gui_size_mode_e::AXIS_SCALE) { switch (node->dock_mode) { case gui_dock_mode_e::BOTTOM: case gui_dock_mode_e::TOP: absolute_desired_size.y = sibling_bounds.width() * node->desired_size.y; break; case gui_dock_mode_e::NONE: absolute_desired_size.y *= absolute_desired_size.x; break; default: break; } } switch (node->dock_mode) { case gui_dock_mode_e::BOTTOM: node->bounds.min = sibling_bounds.min; node->bounds.max.x = sibling_bounds.max.x; node->bounds.max.y = sibling_bounds.min.y + absolute_desired_size.y + node->padding.vertical(); node->bounds -= node->margin; sibling_bounds.min.y += node->bounds.height() + node->margin.vertical(); break; case gui_dock_mode_e::FILL: node->bounds = sibling_bounds - node->margin; break; case gui_dock_mode_e::LEFT: node->bounds.min = sibling_bounds.min; node->bounds.max.x = sibling_bounds.min.x + absolute_desired_size.x + node->padding.horizontal(); node->bounds.max.y = sibling_bounds.max.y; node->bounds -= node->margin; sibling_bounds.min.x += node->bounds.width() + node->margin.horizontal(); break; case gui_dock_mode_e::RIGHT: node->bounds.min.x = sibling_bounds.max.x - absolute_desired_size.x - node->padding.horizontal(); node->bounds.min.y = sibling_bounds.min.y; node->bounds.max = sibling_bounds.max; node->bounds -= node->margin; sibling_bounds.max.x -= node->bounds.width() + node->margin.horizontal(); break; case gui_dock_mode_e::TOP: node->bounds.min.x = sibling_bounds.min.x; node->bounds.min.y = sibling_bounds.max.y - absolute_desired_size.y - node->padding.vertical(); node->bounds.max = sibling_bounds.max; node->bounds -= node->margin; sibling_bounds.max.y -= node->bounds.height() + node->margin.vertical(); break; default: node->bounds.min = vec2_t(0); node->bounds.max = absolute_desired_size; vec2_t anchor_location; vec2_t anchor_translation; if ((node->anchor_flags & GUI_ANCHOR_FLAG_HORIZONTAL) == GUI_ANCHOR_FLAG_HORIZONTAL) { anchor_location.x = sibling_bounds.min.x + (sibling_bounds.width() / 2); anchor_translation.x = -((absolute_desired_size.x / 2) + ((node->margin.right - node->margin.left) / 2)); } else { if ((node->anchor_flags & GUI_ANCHOR_FLAG_LEFT) == GUI_ANCHOR_FLAG_LEFT) { anchor_location.x = sibling_bounds.min.x; anchor_translation.x = node->margin.left; } else if ((node->anchor_flags & GUI_ANCHOR_FLAG_RIGHT) == GUI_ANCHOR_FLAG_RIGHT) { anchor_location.x = sibling_bounds.max.x; anchor_translation.x = -(absolute_desired_size.x + node->margin.right); } } if ((node->anchor_flags & GUI_ANCHOR_FLAG_VERTICAL) == GUI_ANCHOR_FLAG_VERTICAL) { anchor_location.y = sibling_bounds.min.y + (sibling_bounds.height() / 2); anchor_translation.y = -((absolute_desired_size.y / 2) + ((node->margin.top - node->margin.bottom) / 2)); } else { if ((node->anchor_flags & GUI_ANCHOR_FLAG_BOTTOM) == GUI_ANCHOR_FLAG_BOTTOM) { anchor_location.y = sibling_bounds.min.y; anchor_translation.y = node->margin.bottom; } else if ((node->anchor_flags & GUI_ANCHOR_FLAG_TOP) == GUI_ANCHOR_FLAG_TOP) { anchor_location.y = sibling_bounds.max.y; anchor_translation.y = -(absolute_desired_size.y + node->margin.top); } } node->bounds += anchor_location + anchor_translation + node->anchor_offset; break; } node->size = node->bounds.size(); auto children_bounds = node->bounds - node->padding; for (auto child : node->children) { clean_node(child, children_bounds); } node->is_dirty = false; node->on_clean_end(); }; //HACK: something is amiss with this way of doing things. //margins can be accumulated with every tick unless we //pad the bounds passed into clean_node. this seems incorrect, //but will work for now. auto padded_bounds = bounds + margin; clean_node(shared_from_this(), padded_bounds); } void gui_node_t::tick(float32_t dt) { on_tick_begin(dt); for (auto child : children) { child->tick(dt); } on_tick_end(dt); } bool gui_node_t::on_input_event(input_event_t& input_event) { for (auto children_itr = children.begin(); children_itr != children.end(); ++children_itr) { if ((*children_itr)->on_input_event(input_event)) { return true; } } return false; } const gui_size_modes_t gui_node_t::get_size_modes_real() const { auto real_size_modes = size_modes; if (real_size_modes.get_x() == gui_size_mode_e::INHERIT) { if (parent) { real_size_modes.set_x(parent->get_size_modes_real().get_x()); } else { real_size_modes.set_x(gui_size_mode_e::ABSOLUTE); } } if (real_size_modes.get_y() == gui_size_mode_e::INHERIT) { if (parent) { real_size_modes.set_y(parent->get_size_modes_real().get_y()); } else { real_size_modes.set_y(gui_size_mode_e::ABSOLUTE); } } return real_size_modes; } void gui_node_t::dirty() { if (is_dirty) { return; } is_dirty = true; if (parent) { parent->dirty(); } } void gui_node_t::render(mat4_t world_matrix, mat4_t view_projection_matrix) { if (is_hidden) { return; } //TODO: debug rendering? bool should_clip = this->should_clip; //temporary variable in case value changes during render calls somehow if (should_clip) { //stencil auto gpu_stencil_state = gpu.stencil.get_state(); gpu_stencil_state.is_enabled = true; gpu_stencil_state.function.func = gpu_t::stencil_function_e::NEVER; gpu_stencil_state.function.ref = 1; gpu_stencil_state.function.mask = 0xFF; gpu_stencil_state.operations.fail = gpu_t::stencil_operation_e::REPLACE; gpu_stencil_state.operations.zfail = gpu_t::stencil_operation_e::KEEP; gpu_stencil_state.operations.zpass = gpu_t::stencil_operation_e::KEEP; gpu_stencil_state.mask = 0xFF; gpu.stencil.push_state(gpu_stencil_state); //color auto gpu_color_state = gpu.color.get_state(); gpu_color_state.mask.r = false; gpu_color_state.mask.g = false; gpu_color_state.mask.b = false; gpu_color_state.mask.a = false; gpu.color.push_state(gpu_color_state); //depth auto gpu_depth_state = gpu.depth.get_state(); gpu_depth_state.should_write_mask = false; gpu.depth.push_state(gpu_depth_state); gpu.clear(gpu_t::CLEAR_FLAG_DEPTH | gpu_t::CLEAR_FLAG_STENCIL); render_rectangle(world_matrix, view_projection_matrix, rectangle_t(bounds), true); gpu.color.pop_state(); gpu.depth.pop_state(); gpu_stencil_state.mask = 0; gpu_stencil_state.function.func = gpu_t::stencil_function_e::NOTEQUAL; gpu_stencil_state.function.ref = 0; gpu_stencil_state.function.mask = 0xFF; gpu.stencil.pop_state(); gpu.stencil.push_state(gpu_stencil_state); } //TODO: configure this to be enable-able in-game #if defined(DEBUG) render_rectangle(world_matrix, view_projection_matrix, rectangle_t(bounds)); #endif on_render_begin(world_matrix, view_projection_matrix); for (auto& child : children) { child->render(world_matrix, view_projection_matrix); } on_render_end(world_matrix, view_projection_matrix); if (should_clip) { gpu.stencil.pop_state(); } } } <|endoftext|>
<commit_before>//===- TraceValues.cpp - Value Tracing for debugging -------------*- C++ -*--=// // // Support for inserting LLVM code to print values at basic block and method // exits. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Instrumentation/TraceValues.h" #include "llvm/GlobalVariable.h" #include "llvm/ConstantVals.h" #include "llvm/DerivedTypes.h" #include "llvm/iMemory.h" #include "llvm/iTerminators.h" #include "llvm/iOther.h" #include "llvm/BasicBlock.h" #include "llvm/Function.h" #include "llvm/Module.h" #include "llvm/Pass.h" #include "llvm/Assembly/Writer.h" #include "Support/StringExtras.h" #include <sstream> using std::vector; using std::string; namespace { class InsertTraceCode : public MethodPass { bool TraceBasicBlockExits, TraceFunctionExits; Function *PrintfFunc; public: InsertTraceCode(bool traceBasicBlockExits, bool traceFunctionExits) : TraceBasicBlockExits(traceBasicBlockExits), TraceFunctionExits(traceFunctionExits) {} // Add a prototype for printf if it is not already in the program. // bool doInitialization(Module *M); //-------------------------------------------------------------------------- // Function InsertCodeToTraceValues // // Inserts tracing code for all live values at basic block and/or method // exits as specified by `traceBasicBlockExits' and `traceFunctionExits'. // static bool doit(Function *M, bool traceBasicBlockExits, bool traceFunctionExits, Function *Printf); // runOnMethod - This method does the work. Always successful. // bool runOnMethod(Function *F) { return doit(F, TraceBasicBlockExits, TraceFunctionExits, PrintfFunc); } }; } // end anonymous namespace Pass *createTraceValuesPassForMethod() { // Just trace methods return new InsertTraceCode(false, true); } Pass *createTraceValuesPassForBasicBlocks() { // Trace BB's and methods return new InsertTraceCode(true, true); } // Add a prototype for printf if it is not already in the program. // bool InsertTraceCode::doInitialization(Module *M) { const Type *SBP = PointerType::get(Type::SByteTy); const FunctionType *MTy = FunctionType::get(Type::IntTy, vector<const Type*>(1, SBP), true); PrintfFunc = M->getOrInsertFunction("printf", MTy); return false; } static inline GlobalVariable *getStringRef(Module *M, const string &str) { // Create a constant internal string reference... Constant *Init = ConstantArray::get(str); // Create the global variable and record it in the module // The GV will be renamed to a unique name if needed. GlobalVariable *GV = new GlobalVariable(Init->getType(), true, true, Init, "trstr"); M->getGlobalList().push_back(GV); return GV; } // // Check if this instruction has any uses outside its basic block, // or if it used by either a Call or Return instruction. // static inline bool LiveAtBBExit(const Instruction* I) { const BasicBlock *BB = I->getParent(); for (Value::use_const_iterator U = I->use_begin(); U != I->use_end(); ++U) if (const Instruction *UI = dyn_cast<Instruction>(*U)) if (UI->getParent() != BB || isa<ReturnInst>(UI)) return true; return false; } static inline bool TraceThisOpCode(unsigned opCode) { // Explicitly test for opCodes *not* to trace so that any new opcodes will // be traced by default (VoidTy's are already excluded) // return (opCode < Instruction::FirstOtherOp && opCode != Instruction::Alloca && opCode != Instruction::PHINode && opCode != Instruction::Cast); } static bool ShouldTraceValue(const Instruction *I) { return I->getType() != Type::VoidTy && LiveAtBBExit(I) && TraceThisOpCode(I->getOpcode()); } static string getPrintfCodeFor(const Value *V) { if (V == 0) return ""; switch (V->getType()->getPrimitiveID()) { case Type::BoolTyID: case Type::UByteTyID: case Type::UShortTyID: case Type::UIntTyID: case Type::ULongTyID: case Type::SByteTyID: case Type::ShortTyID: case Type::IntTyID: case Type::LongTyID: return "%d"; case Type::FloatTyID: case Type::DoubleTyID: return "%g"; case Type::LabelTyID: case Type::PointerTyID: return "%p"; default: assert(0 && "Illegal value to print out..."); return ""; } } static void InsertPrintInst(Value *V, BasicBlock *BB, BasicBlock::iterator &BBI, string Message, Function *Printf) { // Escape Message by replacing all % characters with %% chars. unsigned Offset = 0; while ((Offset = Message.find('%', Offset)) != string::npos) { Message.replace(Offset, 2, "%%"); Offset += 2; // Skip over the new %'s } Module *Mod = BB->getParent()->getParent(); // Turn the marker string into a global variable... GlobalVariable *fmtVal = getStringRef(Mod, Message+getPrintfCodeFor(V)+"\n"); // Turn the format string into an sbyte * Instruction *GEP = new GetElementPtrInst(fmtVal, vector<Value*>(2,ConstantUInt::get(Type::UIntTy, 0)), "trstr"); BBI = BB->getInstList().insert(BBI, GEP)+1; // Insert the first print instruction to print the string flag: vector<Value*> PrintArgs; PrintArgs.push_back(GEP); if (V) PrintArgs.push_back(V); Instruction *I = new CallInst(Printf, PrintArgs, "trace"); BBI = BB->getInstList().insert(BBI, I)+1; } static void InsertVerbosePrintInst(Value *V, BasicBlock *BB, BasicBlock::iterator &BBI, const string &Message, Function *Printf) { std::ostringstream OutStr; if (V) WriteAsOperand(OutStr, V); InsertPrintInst(V, BB, BBI, Message+OutStr.str()+" = ", Printf); } // Insert print instructions at the end of the basic block *bb // for each value in valueVec[] that is live at the end of that basic block, // or that is stored to memory in this basic block. // If the value is stored to memory, we load it back before printing // We also return all such loaded values in the vector valuesStoredInFunction // for printing at the exit from the method. (Note that in each invocation // of the method, this will only get the last value stored for each static // store instruction). // *bb must be the block in which the value is computed; // this is not checked here. // static void TraceValuesAtBBExit(BasicBlock *BB, Function *Printf, vector<Instruction*> *valuesStoredInFunction) { // Get an iterator to point to the insertion location, which is // just before the terminator instruction. // BasicBlock::iterator InsertPos = BB->end()-1; assert((*InsertPos)->isTerminator()); // If the terminator is a conditional branch, insert the trace code just // before the instruction that computes the branch condition (just to // avoid putting a call between the CC-setting instruction and the branch). // Use laterInstrSet to mark instructions that come after the setCC instr // because those cannot be traced at the location we choose. // Instruction *SetCC = 0; if (BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator())) if (!Branch->isUnconditional()) if (Instruction *I = dyn_cast<Instruction>(Branch->getCondition())) if (I->getParent() == BB) { SetCC = I; while (*InsertPos != SetCC) --InsertPos; // Back up until we can insert before the setcc } // Copy all of the instructions into a vector to avoid problems with Setcc const vector<Instruction*> Insts(BB->begin(), InsertPos); std::ostringstream OutStr; WriteAsOperand(OutStr, BB, false); InsertPrintInst(0, BB, InsertPos, "LEAVING BB:" + OutStr.str(), Printf); // Insert a print instruction for each value. // for (vector<Instruction*>::const_iterator II = Insts.begin(), IE = Insts.end(); II != IE; ++II) { Instruction *I = *II; if (StoreInst *SI = dyn_cast<StoreInst>(I)) { assert(valuesStoredInFunction && "Should not be printing a store instruction at method exit"); LoadInst *LI = new LoadInst(SI->getPointerOperand(), SI->copyIndices(), "reload"); InsertPos = BB->getInstList().insert(InsertPos, LI) + 1; valuesStoredInFunction->push_back(LI); } if (ShouldTraceValue(I)) InsertVerbosePrintInst(I, BB, InsertPos, " ", Printf); } } static inline void InsertCodeToShowFunctionEntry(Function *M, Function *Printf){ // Get an iterator to point to the insertion location BasicBlock *BB = M->getEntryNode(); BasicBlock::iterator BBI = BB->begin(); std::ostringstream OutStr; WriteAsOperand(OutStr, M, true); InsertPrintInst(0, BB, BBI, "ENTERING METHOD: " + OutStr.str(), Printf); // Now print all the incoming arguments const Function::ArgumentListType &argList = M->getArgumentList(); unsigned ArgNo = 0; for (Function::ArgumentListType::const_iterator I = argList.begin(), E = argList.end(); I != E; ++I, ++ArgNo) { InsertVerbosePrintInst((Value*)*I, BB, BBI, " Arg #" + utostr(ArgNo), Printf); } } static inline void InsertCodeToShowFunctionExit(BasicBlock *BB, Function *Printf) { // Get an iterator to point to the insertion location BasicBlock::iterator BBI = BB->end()-1; ReturnInst *Ret = cast<ReturnInst>(*BBI); std::ostringstream OutStr; WriteAsOperand(OutStr, BB->getParent(), true); InsertPrintInst(0, BB, BBI, "LEAVING METHOD: " + OutStr.str(), Printf); // print the return value, if any if (BB->getParent()->getReturnType() != Type::VoidTy) InsertPrintInst(Ret->getReturnValue(), BB, BBI, " Returning: ", Printf); } bool InsertTraceCode::doit(Function *M, bool traceBasicBlockExits, bool traceFunctionEvents, Function *Printf) { if (!traceBasicBlockExits && !traceFunctionEvents) return false; vector<Instruction*> valuesStoredInFunction; vector<BasicBlock*> exitBlocks; if (traceFunctionEvents) InsertCodeToShowFunctionEntry(M, Printf); for (Function::iterator BI = M->begin(); BI != M->end(); ++BI) { BasicBlock *BB = *BI; if (isa<ReturnInst>(BB->getTerminator())) exitBlocks.push_back(BB); // record this as an exit block if (traceBasicBlockExits) TraceValuesAtBBExit(BB, Printf, &valuesStoredInFunction); } if (traceFunctionEvents) for (unsigned i=0; i < exitBlocks.size(); ++i) { #if 0 TraceValuesAtBBExit(valuesStoredInFunction, exitBlocks[i], module, /*indent*/ 0, /*isFunctionExit*/ true, /*valuesStoredInFunction*/ NULL); #endif InsertCodeToShowFunctionExit(exitBlocks[i], Printf); } return true; } <commit_msg>* s/Method/Function * Fix bug where the character after a % was being discarded<commit_after>//===- TraceValues.cpp - Value Tracing for debugging -------------*- C++ -*--=// // // Support for inserting LLVM code to print values at basic block and function // exits. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Instrumentation/TraceValues.h" #include "llvm/GlobalVariable.h" #include "llvm/ConstantVals.h" #include "llvm/DerivedTypes.h" #include "llvm/iMemory.h" #include "llvm/iTerminators.h" #include "llvm/iOther.h" #include "llvm/BasicBlock.h" #include "llvm/Function.h" #include "llvm/Module.h" #include "llvm/Pass.h" #include "llvm/Assembly/Writer.h" #include "Support/StringExtras.h" #include <sstream> using std::vector; using std::string; namespace { class InsertTraceCode : public MethodPass { bool TraceBasicBlockExits, TraceFunctionExits; Function *PrintfFunc; public: InsertTraceCode(bool traceBasicBlockExits, bool traceFunctionExits) : TraceBasicBlockExits(traceBasicBlockExits), TraceFunctionExits(traceFunctionExits) {} // Add a prototype for printf if it is not already in the program. // bool doInitialization(Module *M); //-------------------------------------------------------------------------- // Function InsertCodeToTraceValues // // Inserts tracing code for all live values at basic block and/or function // exits as specified by `traceBasicBlockExits' and `traceFunctionExits'. // static bool doit(Function *M, bool traceBasicBlockExits, bool traceFunctionExits, Function *Printf); // runOnFunction - This method does the work. // bool runOnMethod(Function *F) { return doit(F, TraceBasicBlockExits, TraceFunctionExits, PrintfFunc); } }; } // end anonymous namespace Pass *createTraceValuesPassForMethod() { // Just trace functions return new InsertTraceCode(false, true); } Pass *createTraceValuesPassForBasicBlocks() { // Trace BB's and functions return new InsertTraceCode(true, true); } // Add a prototype for printf if it is not already in the program. // bool InsertTraceCode::doInitialization(Module *M) { const Type *SBP = PointerType::get(Type::SByteTy); const FunctionType *MTy = FunctionType::get(Type::IntTy, vector<const Type*>(1, SBP), true); PrintfFunc = M->getOrInsertFunction("printf", MTy); return false; } static inline GlobalVariable *getStringRef(Module *M, const string &str) { // Create a constant internal string reference... Constant *Init = ConstantArray::get(str); // Create the global variable and record it in the module // The GV will be renamed to a unique name if needed. GlobalVariable *GV = new GlobalVariable(Init->getType(), true, true, Init, "trstr"); M->getGlobalList().push_back(GV); return GV; } // // Check if this instruction has any uses outside its basic block, // or if it used by either a Call or Return instruction. // static inline bool LiveAtBBExit(const Instruction* I) { const BasicBlock *BB = I->getParent(); for (Value::use_const_iterator U = I->use_begin(); U != I->use_end(); ++U) if (const Instruction *UI = dyn_cast<Instruction>(*U)) if (UI->getParent() != BB || isa<ReturnInst>(UI)) return true; return false; } static inline bool TraceThisOpCode(unsigned opCode) { // Explicitly test for opCodes *not* to trace so that any new opcodes will // be traced by default (VoidTy's are already excluded) // return (opCode < Instruction::FirstOtherOp && opCode != Instruction::Alloca && opCode != Instruction::PHINode && opCode != Instruction::Cast); } static bool ShouldTraceValue(const Instruction *I) { return I->getType() != Type::VoidTy && LiveAtBBExit(I) && TraceThisOpCode(I->getOpcode()); } static string getPrintfCodeFor(const Value *V) { if (V == 0) return ""; if (V->getType()->isFloatingPoint()) return "%g"; else if (V->getType() == Type::LabelTy || isa<PointerType>(V->getType())) return "0x%p"; else if (V->getType()->isIntegral() || V->getType() == Type::BoolTy) return "%d"; assert(0 && "Illegal value to print out..."); return ""; } static void InsertPrintInst(Value *V, BasicBlock *BB, BasicBlock::iterator &BBI, string Message, Function *Printf) { // Escape Message by replacing all % characters with %% chars. unsigned Offset = 0; while ((Offset = Message.find('%', Offset)) != string::npos) { Message.replace(Offset, 1, "%%"); Offset += 2; // Skip over the new %'s } Module *Mod = BB->getParent()->getParent(); // Turn the marker string into a global variable... GlobalVariable *fmtVal = getStringRef(Mod, Message+getPrintfCodeFor(V)+"\n"); // Turn the format string into an sbyte * Instruction *GEP = new GetElementPtrInst(fmtVal, vector<Value*>(2,ConstantUInt::get(Type::UIntTy, 0)), "trstr"); BBI = BB->getInstList().insert(BBI, GEP)+1; // Insert the first print instruction to print the string flag: vector<Value*> PrintArgs; PrintArgs.push_back(GEP); if (V) PrintArgs.push_back(V); Instruction *I = new CallInst(Printf, PrintArgs, "trace"); BBI = BB->getInstList().insert(BBI, I)+1; } static void InsertVerbosePrintInst(Value *V, BasicBlock *BB, BasicBlock::iterator &BBI, const string &Message, Function *Printf) { std::ostringstream OutStr; if (V) WriteAsOperand(OutStr, V); InsertPrintInst(V, BB, BBI, Message+OutStr.str()+" = ", Printf); } // Insert print instructions at the end of the basic block *bb // for each value in valueVec[] that is live at the end of that basic block, // or that is stored to memory in this basic block. // If the value is stored to memory, we load it back before printing // We also return all such loaded values in the vector valuesStoredInFunction // for printing at the exit from the function. (Note that in each invocation // of the function, this will only get the last value stored for each static // store instruction). // *bb must be the block in which the value is computed; // this is not checked here. // static void TraceValuesAtBBExit(BasicBlock *BB, Function *Printf, vector<Instruction*> *valuesStoredInFunction) { // Get an iterator to point to the insertion location, which is // just before the terminator instruction. // BasicBlock::iterator InsertPos = BB->end()-1; assert((*InsertPos)->isTerminator()); // If the terminator is a conditional branch, insert the trace code just // before the instruction that computes the branch condition (just to // avoid putting a call between the CC-setting instruction and the branch). // Use laterInstrSet to mark instructions that come after the setCC instr // because those cannot be traced at the location we choose. // Instruction *SetCC = 0; if (BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator())) if (!Branch->isUnconditional()) if (Instruction *I = dyn_cast<Instruction>(Branch->getCondition())) if (I->getParent() == BB) { SetCC = I; while (*InsertPos != SetCC) --InsertPos; // Back up until we can insert before the setcc } // Copy all of the instructions into a vector to avoid problems with Setcc const vector<Instruction*> Insts(BB->begin(), InsertPos); std::ostringstream OutStr; WriteAsOperand(OutStr, BB, false); InsertPrintInst(0, BB, InsertPos, "LEAVING BB:" + OutStr.str(), Printf); // Insert a print instruction for each value. // for (vector<Instruction*>::const_iterator II = Insts.begin(), IE = Insts.end(); II != IE; ++II) { Instruction *I = *II; if (StoreInst *SI = dyn_cast<StoreInst>(I)) { assert(valuesStoredInFunction && "Should not be printing a store instruction at function exit"); LoadInst *LI = new LoadInst(SI->getPointerOperand(), SI->copyIndices(), "reload"); InsertPos = BB->getInstList().insert(InsertPos, LI) + 1; valuesStoredInFunction->push_back(LI); } if (ShouldTraceValue(I)) InsertVerbosePrintInst(I, BB, InsertPos, " ", Printf); } } static inline void InsertCodeToShowFunctionEntry(Function *M, Function *Printf){ // Get an iterator to point to the insertion location BasicBlock *BB = M->getEntryNode(); BasicBlock::iterator BBI = BB->begin(); std::ostringstream OutStr; WriteAsOperand(OutStr, M, true); InsertPrintInst(0, BB, BBI, "ENTERING FUNCTION: " + OutStr.str(), Printf); // Now print all the incoming arguments const Function::ArgumentListType &argList = M->getArgumentList(); unsigned ArgNo = 0; for (Function::ArgumentListType::const_iterator I = argList.begin(), E = argList.end(); I != E; ++I, ++ArgNo) { InsertVerbosePrintInst((Value*)*I, BB, BBI, " Arg #" + utostr(ArgNo), Printf); } } static inline void InsertCodeToShowFunctionExit(BasicBlock *BB, Function *Printf) { // Get an iterator to point to the insertion location BasicBlock::iterator BBI = BB->end()-1; ReturnInst *Ret = cast<ReturnInst>(*BBI); std::ostringstream OutStr; WriteAsOperand(OutStr, BB->getParent(), true); InsertPrintInst(0, BB, BBI, "LEAVING FUNCTION: " + OutStr.str(), Printf); // print the return value, if any if (BB->getParent()->getReturnType() != Type::VoidTy) InsertPrintInst(Ret->getReturnValue(), BB, BBI, " Returning: ", Printf); } bool InsertTraceCode::doit(Function *M, bool traceBasicBlockExits, bool traceFunctionEvents, Function *Printf) { if (!traceBasicBlockExits && !traceFunctionEvents) return false; vector<Instruction*> valuesStoredInFunction; vector<BasicBlock*> exitBlocks; if (traceFunctionEvents) InsertCodeToShowFunctionEntry(M, Printf); for (Function::iterator BI = M->begin(); BI != M->end(); ++BI) { BasicBlock *BB = *BI; if (isa<ReturnInst>(BB->getTerminator())) exitBlocks.push_back(BB); // record this as an exit block if (traceBasicBlockExits) TraceValuesAtBBExit(BB, Printf, &valuesStoredInFunction); } if (traceFunctionEvents) for (unsigned i=0; i < exitBlocks.size(); ++i) { #if 0 TraceValuesAtBBExit(valuesStoredInFunction, exitBlocks[i], module, /*indent*/ 0, /*isFunctionExit*/ true, /*valuesStoredInFunction*/ NULL); #endif InsertCodeToShowFunctionExit(exitBlocks[i], Printf); } return true; } <|endoftext|>
<commit_before>#include "clientmodel.h" #include "guiconstants.h" #include "optionsmodel.h" #include "addresstablemodel.h" #include "transactiontablemodel.h" #include "alert.h" #include "main.h" #include "ui_interface.h" #include <QDateTime> #include <QTimer> static const int64 nClientStartupTime = GetTime(); ClientModel::ClientModel(OptionsModel *optionsModel, QObject *parent) : QObject(parent), optionsModel(optionsModel), cachedNumBlocks(0), cachedNumBlocksOfPeers(0), numBlocksAtStartup(-1), pollTimer(0) { pollTimer = new QTimer(this); pollTimer->setInterval(MODEL_UPDATE_DELAY); pollTimer->start(); connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer())); subscribeToCoreSignals(); } ClientModel::~ClientModel() { //unsubscribeFromCoreSignals(); } int ClientModel::getNumConnections() const { return vNodes.size(); } int ClientModel::getNumBlocks() const { return nBestHeight; } int ClientModel::getNumBlocksAtStartup() { if (numBlocksAtStartup == -1) numBlocksAtStartup = getNumBlocks(); return numBlocksAtStartup; } QDateTime ClientModel::getLastBlockDate() const { return QDateTime::fromTime_t(pindexBest->GetBlockTime()); } void ClientModel::updateTimer() { // Some quantities (such as number of blocks) change so fast that we don't want to be notified for each change. // Periodically check and update with a timer. int newNumBlocks = getNumBlocks(); int newNumBlocksOfPeers = getNumBlocksOfPeers(); if(cachedNumBlocks != newNumBlocks || cachedNumBlocksOfPeers != newNumBlocksOfPeers) { cachedNumBlocks = newNumBlocks; cachedNumBlocksOfPeers = newNumBlocksOfPeers; // ensure we return the maximum of newNumBlocksOfPeers and newNumBlocks to not create weird displays in the GUI emit numBlocksChanged(newNumBlocks, std::max(newNumBlocksOfPeers, newNumBlocks)); } } void ClientModel::updateNumConnections(int numConnections) { emit numConnectionsChanged(numConnections); } void ClientModel::updateWalletAdded(const QString &name) { emit walletAdded(name); } void ClientModel::updateWalletRemoved(const QString &name) { emit walletRemoved(name); } void ClientModel::updateAlert(const QString &hash, int status) { // Show error message notification for new alert if(status == CT_NEW) { uint256 hash_256; hash_256.SetHex(hash.toStdString()); CAlert alert = CAlert::getAlertByHash(hash_256); if(!alert.IsNull()) { emit message(tr("Network Alert"), QString::fromStdString(alert.strStatusBar), CClientUIInterface::ICON_ERROR); } } emit alertsChanged(getStatusBarWarnings()); } bool ClientModel::isTestNet() const { return fTestNet; } bool ClientModel::inInitialBlockDownload() const { return IsInitialBlockDownload(); } enum BlockSource ClientModel::getBlockSource() const { //Tranz Need to add -reindex. //if (fReindex) // return BLOCK_SOURCE_REINDEX; //if (fImporting) // return BLOCK_SOURCE_DISK; return BLOCK_SOURCE_NETWORK; } int ClientModel::getNumBlocksOfPeers() const { return GetNumBlocksOfPeers(); } QString ClientModel::getStatusBarWarnings() const { return QString::fromStdString(GetWarnings("statusbar")); } OptionsModel *ClientModel::getOptionsModel() { return optionsModel; } QString ClientModel::formatFullVersion() const { return QString::fromStdString(FormatFullVersion()); } QString ClientModel::formatBuildDate() const { return QString::fromStdString(CLIENT_DATE); } bool ClientModel::isReleaseVersion() const { return CLIENT_VERSION_IS_RELEASE; } QString ClientModel::clientName() const { return QString::fromStdString(CLIENT_NAME); } QString ClientModel::formatClientStartupTime() const { return QDateTime::fromTime_t(nClientStartupTime).toString(); } // Handlers for core signals static void NotifyBlocksChanged(ClientModel *clientmodel) { // This notification is too frequent. Don't trigger a signal. // Don't remove it, though, as it might be useful later. } static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections) { // Too noisy: OutputDebugStringF("NotifyNumConnectionsChanged %i\n", newNumConnections); QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection, Q_ARG(int, newNumConnections)); } static void NotifyAlertChanged(ClientModel *clientmodel, const uint256 &hash, ChangeType status) { OutputDebugStringF("NotifyAlertChanged %s status=%i\n", hash.GetHex().c_str(), status); QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(hash.GetHex())), Q_ARG(int, status)); } static void NotifyWalletAdded(ClientModel *clientmodel, const std::string &name) { OutputDebugStringF("NotifyWalletAdded %s \n", name.c_str()); QMetaObject::invokeMethod(clientmodel, "updateWalletAdded", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(name))); } static void NotifyWalletRemoved(ClientModel *clientmodel, const std::string &name) { OutputDebugStringF("NotifyWalletRemoved %s \n", name.c_str()); QMetaObject::invokeMethod(clientmodel, "updateWalletRemoved", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(name))); } void ClientModel::subscribeToCoreSignals() { // Connect signals to client uiInterface.NotifyBlocksChanged.connect(boost::bind(NotifyBlocksChanged, this)); uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this, _1, _2)); uiInterface.NotifyWalletAdded.connect(boost::bind(NotifyWalletAdded,this,_1)); uiInterface.NotifyWalletRemoved.connect(boost::bind(NotifyWalletRemoved,this,_1)); } void ClientModel::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.NotifyBlocksChanged.disconnect(boost::bind(NotifyBlocksChanged, this)); uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this, _1, _2)); uiInterface.NotifyWalletAdded.disconnect(boost::bind(NotifyWalletAdded,this,_1)); uiInterface.NotifyWalletRemoved.disconnect(boost::bind(NotifyWalletRemoved,this,_1)); } <commit_msg>V1.3<commit_after>#include "clientmodel.h" #include "guiconstants.h" #include "optionsmodel.h" #include "addresstablemodel.h" #include "transactiontablemodel.h" #include "alert.h" #include "main.h" #include "ui_interface.h" #include <QDateTime> #include <QTimer> static const int64 nClientStartupTime = GetTime(); ClientModel::ClientModel(OptionsModel *optionsModel, QObject *parent) : QObject(parent), optionsModel(optionsModel), cachedNumBlocks(0), cachedNumBlocksOfPeers(0), numBlocksAtStartup(-1), pollTimer(0) { pollTimer = new QTimer(this); pollTimer->setInterval(MODEL_UPDATE_DELAY); pollTimer->start(); connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer())); subscribeToCoreSignals(); } ClientModel::~ClientModel() { //unsubscribeFromCoreSignals(); } int ClientModel::getNumConnections() const { return vNodes.size(); } int ClientModel::getNumBlocks() const { return nBestHeight; } int ClientModel::getNumBlocksAtStartup() { if (numBlocksAtStartup == -1) numBlocksAtStartup = getNumBlocks(); return numBlocksAtStartup; } QDateTime ClientModel::getLastBlockDate() const { if (pindexBest) return QDateTime::fromTime_t(pindexBest->GetBlockTime()); else return QDateTime::fromTime_t(1374635824); // Genesis block's time } void ClientModel::updateTimer() { // Some quantities (such as number of blocks) change so fast that we don't want to be notified for each change. // Periodically check and update with a timer. int newNumBlocks = getNumBlocks(); int newNumBlocksOfPeers = getNumBlocksOfPeers(); if(cachedNumBlocks != newNumBlocks || cachedNumBlocksOfPeers != newNumBlocksOfPeers) { cachedNumBlocks = newNumBlocks; cachedNumBlocksOfPeers = newNumBlocksOfPeers; // ensure we return the maximum of newNumBlocksOfPeers and newNumBlocks to not create weird displays in the GUI emit numBlocksChanged(newNumBlocks, std::max(newNumBlocksOfPeers, newNumBlocks)); } } void ClientModel::updateNumConnections(int numConnections) { emit numConnectionsChanged(numConnections); } void ClientModel::updateWalletAdded(const QString &name) { emit walletAdded(name); } void ClientModel::updateWalletRemoved(const QString &name) { emit walletRemoved(name); } void ClientModel::updateAlert(const QString &hash, int status) { // Show error message notification for new alert if(status == CT_NEW) { uint256 hash_256; hash_256.SetHex(hash.toStdString()); CAlert alert = CAlert::getAlertByHash(hash_256); if(!alert.IsNull()) { emit message(tr("Network Alert"), QString::fromStdString(alert.strStatusBar), CClientUIInterface::ICON_ERROR); } } emit alertsChanged(getStatusBarWarnings()); } bool ClientModel::isTestNet() const { return fTestNet; } bool ClientModel::inInitialBlockDownload() const { return IsInitialBlockDownload(); } enum BlockSource ClientModel::getBlockSource() const { //Tranz Need to add -reindex. //if (fReindex) // return BLOCK_SOURCE_REINDEX; //if (fImporting) // return BLOCK_SOURCE_DISK; return BLOCK_SOURCE_NETWORK; } int ClientModel::getNumBlocksOfPeers() const { return GetNumBlocksOfPeers(); } QString ClientModel::getStatusBarWarnings() const { return QString::fromStdString(GetWarnings("statusbar")); } OptionsModel *ClientModel::getOptionsModel() { return optionsModel; } QString ClientModel::formatFullVersion() const { return QString::fromStdString(FormatFullVersion()); } QString ClientModel::formatBuildDate() const { return QString::fromStdString(CLIENT_DATE); } bool ClientModel::isReleaseVersion() const { return CLIENT_VERSION_IS_RELEASE; } QString ClientModel::clientName() const { return QString::fromStdString(CLIENT_NAME); } QString ClientModel::formatClientStartupTime() const { return QDateTime::fromTime_t(nClientStartupTime).toString(); } // Handlers for core signals static void NotifyBlocksChanged(ClientModel *clientmodel) { // This notification is too frequent. Don't trigger a signal. // Don't remove it, though, as it might be useful later. } static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections) { // Too noisy: OutputDebugStringF("NotifyNumConnectionsChanged %i\n", newNumConnections); QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection, Q_ARG(int, newNumConnections)); } static void NotifyAlertChanged(ClientModel *clientmodel, const uint256 &hash, ChangeType status) { OutputDebugStringF("NotifyAlertChanged %s status=%i\n", hash.GetHex().c_str(), status); QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(hash.GetHex())), Q_ARG(int, status)); } static void NotifyWalletAdded(ClientModel *clientmodel, const std::string &name) { OutputDebugStringF("NotifyWalletAdded %s \n", name.c_str()); QMetaObject::invokeMethod(clientmodel, "updateWalletAdded", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(name))); } static void NotifyWalletRemoved(ClientModel *clientmodel, const std::string &name) { OutputDebugStringF("NotifyWalletRemoved %s \n", name.c_str()); QMetaObject::invokeMethod(clientmodel, "updateWalletRemoved", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(name))); } void ClientModel::subscribeToCoreSignals() { // Connect signals to client uiInterface.NotifyBlocksChanged.connect(boost::bind(NotifyBlocksChanged, this)); uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this, _1, _2)); uiInterface.NotifyWalletAdded.connect(boost::bind(NotifyWalletAdded,this,_1)); uiInterface.NotifyWalletRemoved.connect(boost::bind(NotifyWalletRemoved,this,_1)); } void ClientModel::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.NotifyBlocksChanged.disconnect(boost::bind(NotifyBlocksChanged, this)); uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this, _1, _2)); uiInterface.NotifyWalletAdded.disconnect(boost::bind(NotifyWalletAdded,this,_1)); uiInterface.NotifyWalletRemoved.disconnect(boost::bind(NotifyWalletRemoved,this,_1)); } <|endoftext|>
<commit_before>// Copyright (c) 2011-2018 The Bitcoin Core developers // Copyright (c) 2014-2017 The Dash Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <clientmodel.h> #include <bantablemodel.h> #include <guiconstants.h> #include <guiutil.h> #include <peertablemodel.h> #include <chain.h> #include <chainparams.h> #include <checkpoints.h> #include <clientversion.h> #include <net.h> #include <txmempool.h> #include <ui_interface.h> #include <util.h> #include <validation.h> #include <masternodeman.h> #include <masternode-sync.h> #include <privatesend.h> #include <stdint.h> #include <QDebug> #include <QTimer> class CBlockIndex; static const int64_t nClientStartupTime = GetTime(); static int64_t nLastHeaderTipUpdateNotification = 0; static int64_t nLastBlockTipUpdateNotification = 0; ClientModel::ClientModel(OptionsModel *_optionsModel, QObject *parent) : QObject(parent), optionsModel(_optionsModel), peerTableModel(0), cachedMasternodeCountString(""), banTableModel(0), pollTimer(0) { cachedBestHeaderHeight = -1; cachedBestHeaderTime = -1; peerTableModel = new PeerTableModel(this); banTableModel = new BanTableModel(this); pollTimer = new QTimer(this); connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer())); pollTimer->start(MODEL_UPDATE_DELAY); pollMnTimer = new QTimer(this); connect(pollMnTimer, SIGNAL(timeout()), this, SLOT(updateMnTimer())); // no need to update as frequent as data for balances/txes/blocks pollMnTimer->start(MODEL_UPDATE_DELAY * 4); subscribeToCoreSignals(); } ClientModel::~ClientModel() { unsubscribeFromCoreSignals(); } int ClientModel::getNumConnections(unsigned int flags) const { CConnman::NumConnections connections = CConnman::CONNECTIONS_NONE; if(flags == CONNECTIONS_IN) connections = CConnman::CONNECTIONS_IN; else if (flags == CONNECTIONS_OUT) connections = CConnman::CONNECTIONS_OUT; else if (flags == CONNECTIONS_ALL) connections = CConnman::CONNECTIONS_ALL; if(g_connman) return g_connman->GetNodeCount(connections); return 0; } QString ClientModel::getMasternodeCountString() const { // return tr("Total: %1 (PS compatible: %2 / Enabled: %3) (IPv4: %4, IPv6: %5, TOR: %6)").arg(QString::number((int)mnodeman.size())) return tr("Total: %1 (PS compatible: %2 / Enabled: %3)") .arg(QString::number((int)mnodeman.size())) .arg(QString::number((int)mnodeman.CountEnabled(MIN_PRIVATESEND_PEER_PROTO_VERSION))) .arg(QString::number((int)mnodeman.CountEnabled())); // .arg(QString::number((int)mnodeman.CountByIP(NET_IPV4))) // .arg(QString::number((int)mnodeman.CountByIP(NET_IPV6))) // .arg(QString::number((int)mnodeman.CountByIP(NET_TOR))); } int ClientModel::getNumBlocks() const { LOCK(cs_main); return chainActive.Height(); } int ClientModel::getHeaderTipHeight() const { if (cachedBestHeaderHeight == -1) { // make sure we initially populate the cache via a cs_main lock // otherwise we need to wait for a tip update LOCK(cs_main); if (pindexBestHeader) { cachedBestHeaderHeight = pindexBestHeader->nHeight; } } return cachedBestHeaderHeight; } int64_t ClientModel::getHeaderTipTime() const { if (cachedBestHeaderTime == -1) { LOCK(cs_main); if (pindexBestHeader) { cachedBestHeaderTime = pindexBestHeader->GetBlockTime(); } } return cachedBestHeaderTime; } quint64 ClientModel::getTotalBytesRecv() const { if(!g_connman) return 0; return g_connman->GetTotalBytesRecv(); } quint64 ClientModel::getTotalBytesSent() const { if(!g_connman) return 0; return g_connman->GetTotalBytesSent(); } QDateTime ClientModel::getLastBlockDate() const { LOCK(cs_main); if (chainActive.Tip()) return QDateTime::fromTime_t(chainActive.Tip()->GetBlockTime()); return QDateTime::fromTime_t(Params().GenesisBlock().GetBlockTime()); // Genesis block's time of current network } long ClientModel::getMempoolSize() const { return mempool.size(); } size_t ClientModel::getMempoolDynamicUsage() const { return mempool.DynamicMemoryUsage(); } double ClientModel::getVerificationProgress(const CBlockIndex *tipIn) const { CBlockIndex *tip = const_cast<CBlockIndex *>(tipIn); if (!tip) { LOCK(cs_main); tip = chainActive.Tip(); } return Checkpoints::GuessVerificationProgress(Params().Checkpoints(), tip); } void ClientModel::updateTimer() { // no locking required at this point // the following calls will acquire the required lock Q_EMIT mempoolSizeChanged(getMempoolSize(), getMempoolDynamicUsage()); Q_EMIT bytesChanged(getTotalBytesRecv(), getTotalBytesSent()); } void ClientModel::updateMnTimer() { QString newMasternodeCountString = getMasternodeCountString(); if (cachedMasternodeCountString != newMasternodeCountString) { cachedMasternodeCountString = newMasternodeCountString; Q_EMIT strMasternodesChanged(cachedMasternodeCountString); } } void ClientModel::updateNumConnections(int numConnections) { Q_EMIT numConnectionsChanged(numConnections); } void ClientModel::updateNetworkActive(bool networkActive) { Q_EMIT networkActiveChanged(networkActive); } void ClientModel::updateAlert() { Q_EMIT alertsChanged(getStatusBarWarnings()); } bool ClientModel::inInitialBlockDownload() const { return IsInitialBlockDownload(); } enum BlockSource ClientModel::getBlockSource() const { if (fReindex) return BLOCK_SOURCE_REINDEX; else if (fImporting) return BLOCK_SOURCE_DISK; else if (getNumConnections() > 0) return BLOCK_SOURCE_NETWORK; return BLOCK_SOURCE_NONE; } void ClientModel::setNetworkActive(bool active) { if (g_connman) { g_connman->SetNetworkActive(active); } } bool ClientModel::getNetworkActive() const { if (g_connman) { return g_connman->GetNetworkActive(); } return false; } QString ClientModel::getStatusBarWarnings() const { return QString::fromStdString(GetWarnings("gui")); } OptionsModel *ClientModel::getOptionsModel() { return optionsModel; } PeerTableModel *ClientModel::getPeerTableModel() { return peerTableModel; } BanTableModel *ClientModel::getBanTableModel() { return banTableModel; } QString ClientModel::formatFullVersion() const { return QString::fromStdString(FormatFullVersion()); } QString ClientModel::formatSubVersion() const { return QString::fromStdString(strSubVersion); } bool ClientModel::isReleaseVersion() const { return CLIENT_VERSION_IS_RELEASE; } QString ClientModel::formatClientStartupTime() const { return QDateTime::fromTime_t(nClientStartupTime).toString(); } QString ClientModel::dataDir() const { return GUIUtil::boostPathToQString(GetDataDir()); } void ClientModel::updateBanlist() { banTableModel->refresh(); } // Handlers for core signals static void ShowProgress(ClientModel *clientmodel, const std::string &title, int nProgress) { // emits signal "showProgress" QMetaObject::invokeMethod(clientmodel, "showProgress", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(title)), Q_ARG(int, nProgress)); } static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections) { // Too noisy: qDebug() << "NotifyNumConnectionsChanged: " + QString::number(newNumConnections); QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection, Q_ARG(int, newNumConnections)); } static void NotifyNetworkActiveChanged(ClientModel *clientmodel, bool networkActive) { QMetaObject::invokeMethod(clientmodel, "updateNetworkActive", Qt::QueuedConnection, Q_ARG(bool, networkActive)); } static void NotifyAlertChanged(ClientModel *clientmodel) { qDebug() << "NotifyAlertChanged"; QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection); } static void BannedListChanged(ClientModel *clientmodel) { qDebug() << QString("%1: Requesting update for peer banlist").arg(__func__); QMetaObject::invokeMethod(clientmodel, "updateBanlist", Qt::QueuedConnection); } static void BlockTipChanged(ClientModel *clientmodel, bool initialSync, const CBlockIndex *pIndex, bool fHeader) { // lock free async UI updates in case we have a new block tip // during initial sync, only update the UI if the last update // was > 250ms (MODEL_UPDATE_DELAY) ago int64_t now = 0; if (initialSync) now = GetTimeMillis(); int64_t& nLastUpdateNotification = fHeader ? nLastHeaderTipUpdateNotification : nLastBlockTipUpdateNotification; if (fHeader) { // cache best headers time and height to reduce future cs_main locks clientmodel->cachedBestHeaderHeight = pIndex->nHeight; clientmodel->cachedBestHeaderTime = pIndex->GetBlockTime(); } // if we are in-sync, update the UI regardless of last update time if (!initialSync || now - nLastUpdateNotification > MODEL_UPDATE_DELAY) { //pass a async signal to the UI thread QMetaObject::invokeMethod(clientmodel, "numBlocksChanged", Qt::QueuedConnection, Q_ARG(int, pIndex->nHeight), Q_ARG(QDateTime, QDateTime::fromTime_t(pIndex->GetBlockTime())), Q_ARG(double, clientmodel->getVerificationProgress(pIndex)), Q_ARG(bool, fHeader)); nLastUpdateNotification = now; } } static void NotifyAdditionalDataSyncProgressChanged(ClientModel *clientmodel, double nSyncProgress) { QMetaObject::invokeMethod(clientmodel, "additionalDataSyncProgressChanged", Qt::QueuedConnection, Q_ARG(double, nSyncProgress)); } void ClientModel::subscribeToCoreSignals() { // Connect signals to client uiInterface.ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2)); uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyNetworkActiveChanged.connect(boost::bind(NotifyNetworkActiveChanged, this, _1)); uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this)); uiInterface.BannedListChanged.connect(boost::bind(BannedListChanged, this)); uiInterface.NotifyBlockTip.connect(boost::bind(BlockTipChanged, this, _1, _2, false)); uiInterface.NotifyHeaderTip.connect(boost::bind(BlockTipChanged, this, _1, _2, true)); uiInterface.NotifyAdditionalDataSyncProgressChanged.connect(boost::bind(NotifyAdditionalDataSyncProgressChanged, this, _1)); } void ClientModel::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2)); uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyNetworkActiveChanged.disconnect(boost::bind(NotifyNetworkActiveChanged, this, _1)); uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this)); uiInterface.BannedListChanged.disconnect(boost::bind(BannedListChanged, this)); uiInterface.NotifyBlockTip.disconnect(boost::bind(BlockTipChanged, this, _1, _2, false)); uiInterface.NotifyHeaderTip.disconnect(boost::bind(BlockTipChanged, this, _1, _2, true)); uiInterface.NotifyAdditionalDataSyncProgressChanged.disconnect(boost::bind(NotifyAdditionalDataSyncProgressChanged, this, _1)); } <commit_msg>Set both time/height header caches at the same time<commit_after>// Copyright (c) 2011-2018 The Bitcoin Core developers // Copyright (c) 2014-2017 The Dash Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <clientmodel.h> #include <bantablemodel.h> #include <guiconstants.h> #include <guiutil.h> #include <peertablemodel.h> #include <chain.h> #include <chainparams.h> #include <checkpoints.h> #include <clientversion.h> #include <net.h> #include <txmempool.h> #include <ui_interface.h> #include <util.h> #include <validation.h> #include <masternodeman.h> #include <masternode-sync.h> #include <privatesend.h> #include <stdint.h> #include <QDebug> #include <QTimer> class CBlockIndex; static const int64_t nClientStartupTime = GetTime(); static int64_t nLastHeaderTipUpdateNotification = 0; static int64_t nLastBlockTipUpdateNotification = 0; ClientModel::ClientModel(OptionsModel *_optionsModel, QObject *parent) : QObject(parent), optionsModel(_optionsModel), peerTableModel(0), cachedMasternodeCountString(""), banTableModel(0), pollTimer(0) { cachedBestHeaderHeight = -1; cachedBestHeaderTime = -1; peerTableModel = new PeerTableModel(this); banTableModel = new BanTableModel(this); pollTimer = new QTimer(this); connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer())); pollTimer->start(MODEL_UPDATE_DELAY); pollMnTimer = new QTimer(this); connect(pollMnTimer, SIGNAL(timeout()), this, SLOT(updateMnTimer())); // no need to update as frequent as data for balances/txes/blocks pollMnTimer->start(MODEL_UPDATE_DELAY * 4); subscribeToCoreSignals(); } ClientModel::~ClientModel() { unsubscribeFromCoreSignals(); } int ClientModel::getNumConnections(unsigned int flags) const { CConnman::NumConnections connections = CConnman::CONNECTIONS_NONE; if(flags == CONNECTIONS_IN) connections = CConnman::CONNECTIONS_IN; else if (flags == CONNECTIONS_OUT) connections = CConnman::CONNECTIONS_OUT; else if (flags == CONNECTIONS_ALL) connections = CConnman::CONNECTIONS_ALL; if(g_connman) return g_connman->GetNodeCount(connections); return 0; } QString ClientModel::getMasternodeCountString() const { // return tr("Total: %1 (PS compatible: %2 / Enabled: %3) (IPv4: %4, IPv6: %5, TOR: %6)").arg(QString::number((int)mnodeman.size())) return tr("Total: %1 (PS compatible: %2 / Enabled: %3)") .arg(QString::number((int)mnodeman.size())) .arg(QString::number((int)mnodeman.CountEnabled(MIN_PRIVATESEND_PEER_PROTO_VERSION))) .arg(QString::number((int)mnodeman.CountEnabled())); // .arg(QString::number((int)mnodeman.CountByIP(NET_IPV4))) // .arg(QString::number((int)mnodeman.CountByIP(NET_IPV6))) // .arg(QString::number((int)mnodeman.CountByIP(NET_TOR))); } int ClientModel::getNumBlocks() const { LOCK(cs_main); return chainActive.Height(); } int ClientModel::getHeaderTipHeight() const { if (cachedBestHeaderHeight == -1) { // make sure we initially populate the cache via a cs_main lock // otherwise we need to wait for a tip update LOCK(cs_main); if (pindexBestHeader) { cachedBestHeaderHeight = pindexBestHeader->nHeight; cachedBestHeaderTime = pindexBestHeader->GetBlockTime(); } } return cachedBestHeaderHeight; } int64_t ClientModel::getHeaderTipTime() const { if (cachedBestHeaderTime == -1) { LOCK(cs_main); if (pindexBestHeader) { cachedBestHeaderHeight = pindexBestHeader->nHeight; cachedBestHeaderTime = pindexBestHeader->GetBlockTime(); } } return cachedBestHeaderTime; } quint64 ClientModel::getTotalBytesRecv() const { if(!g_connman) return 0; return g_connman->GetTotalBytesRecv(); } quint64 ClientModel::getTotalBytesSent() const { if(!g_connman) return 0; return g_connman->GetTotalBytesSent(); } QDateTime ClientModel::getLastBlockDate() const { LOCK(cs_main); if (chainActive.Tip()) return QDateTime::fromTime_t(chainActive.Tip()->GetBlockTime()); return QDateTime::fromTime_t(Params().GenesisBlock().GetBlockTime()); // Genesis block's time of current network } long ClientModel::getMempoolSize() const { return mempool.size(); } size_t ClientModel::getMempoolDynamicUsage() const { return mempool.DynamicMemoryUsage(); } double ClientModel::getVerificationProgress(const CBlockIndex *tipIn) const { CBlockIndex *tip = const_cast<CBlockIndex *>(tipIn); if (!tip) { LOCK(cs_main); tip = chainActive.Tip(); } return Checkpoints::GuessVerificationProgress(Params().Checkpoints(), tip); } void ClientModel::updateTimer() { // no locking required at this point // the following calls will acquire the required lock Q_EMIT mempoolSizeChanged(getMempoolSize(), getMempoolDynamicUsage()); Q_EMIT bytesChanged(getTotalBytesRecv(), getTotalBytesSent()); } void ClientModel::updateMnTimer() { QString newMasternodeCountString = getMasternodeCountString(); if (cachedMasternodeCountString != newMasternodeCountString) { cachedMasternodeCountString = newMasternodeCountString; Q_EMIT strMasternodesChanged(cachedMasternodeCountString); } } void ClientModel::updateNumConnections(int numConnections) { Q_EMIT numConnectionsChanged(numConnections); } void ClientModel::updateNetworkActive(bool networkActive) { Q_EMIT networkActiveChanged(networkActive); } void ClientModel::updateAlert() { Q_EMIT alertsChanged(getStatusBarWarnings()); } bool ClientModel::inInitialBlockDownload() const { return IsInitialBlockDownload(); } enum BlockSource ClientModel::getBlockSource() const { if (fReindex) return BLOCK_SOURCE_REINDEX; else if (fImporting) return BLOCK_SOURCE_DISK; else if (getNumConnections() > 0) return BLOCK_SOURCE_NETWORK; return BLOCK_SOURCE_NONE; } void ClientModel::setNetworkActive(bool active) { if (g_connman) { g_connman->SetNetworkActive(active); } } bool ClientModel::getNetworkActive() const { if (g_connman) { return g_connman->GetNetworkActive(); } return false; } QString ClientModel::getStatusBarWarnings() const { return QString::fromStdString(GetWarnings("gui")); } OptionsModel *ClientModel::getOptionsModel() { return optionsModel; } PeerTableModel *ClientModel::getPeerTableModel() { return peerTableModel; } BanTableModel *ClientModel::getBanTableModel() { return banTableModel; } QString ClientModel::formatFullVersion() const { return QString::fromStdString(FormatFullVersion()); } QString ClientModel::formatSubVersion() const { return QString::fromStdString(strSubVersion); } bool ClientModel::isReleaseVersion() const { return CLIENT_VERSION_IS_RELEASE; } QString ClientModel::formatClientStartupTime() const { return QDateTime::fromTime_t(nClientStartupTime).toString(); } QString ClientModel::dataDir() const { return GUIUtil::boostPathToQString(GetDataDir()); } void ClientModel::updateBanlist() { banTableModel->refresh(); } // Handlers for core signals static void ShowProgress(ClientModel *clientmodel, const std::string &title, int nProgress) { // emits signal "showProgress" QMetaObject::invokeMethod(clientmodel, "showProgress", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(title)), Q_ARG(int, nProgress)); } static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections) { // Too noisy: qDebug() << "NotifyNumConnectionsChanged: " + QString::number(newNumConnections); QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection, Q_ARG(int, newNumConnections)); } static void NotifyNetworkActiveChanged(ClientModel *clientmodel, bool networkActive) { QMetaObject::invokeMethod(clientmodel, "updateNetworkActive", Qt::QueuedConnection, Q_ARG(bool, networkActive)); } static void NotifyAlertChanged(ClientModel *clientmodel) { qDebug() << "NotifyAlertChanged"; QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection); } static void BannedListChanged(ClientModel *clientmodel) { qDebug() << QString("%1: Requesting update for peer banlist").arg(__func__); QMetaObject::invokeMethod(clientmodel, "updateBanlist", Qt::QueuedConnection); } static void BlockTipChanged(ClientModel *clientmodel, bool initialSync, const CBlockIndex *pIndex, bool fHeader) { // lock free async UI updates in case we have a new block tip // during initial sync, only update the UI if the last update // was > 250ms (MODEL_UPDATE_DELAY) ago int64_t now = 0; if (initialSync) now = GetTimeMillis(); int64_t& nLastUpdateNotification = fHeader ? nLastHeaderTipUpdateNotification : nLastBlockTipUpdateNotification; if (fHeader) { // cache best headers time and height to reduce future cs_main locks clientmodel->cachedBestHeaderHeight = pIndex->nHeight; clientmodel->cachedBestHeaderTime = pIndex->GetBlockTime(); } // if we are in-sync, update the UI regardless of last update time if (!initialSync || now - nLastUpdateNotification > MODEL_UPDATE_DELAY) { //pass a async signal to the UI thread QMetaObject::invokeMethod(clientmodel, "numBlocksChanged", Qt::QueuedConnection, Q_ARG(int, pIndex->nHeight), Q_ARG(QDateTime, QDateTime::fromTime_t(pIndex->GetBlockTime())), Q_ARG(double, clientmodel->getVerificationProgress(pIndex)), Q_ARG(bool, fHeader)); nLastUpdateNotification = now; } } static void NotifyAdditionalDataSyncProgressChanged(ClientModel *clientmodel, double nSyncProgress) { QMetaObject::invokeMethod(clientmodel, "additionalDataSyncProgressChanged", Qt::QueuedConnection, Q_ARG(double, nSyncProgress)); } void ClientModel::subscribeToCoreSignals() { // Connect signals to client uiInterface.ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2)); uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyNetworkActiveChanged.connect(boost::bind(NotifyNetworkActiveChanged, this, _1)); uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this)); uiInterface.BannedListChanged.connect(boost::bind(BannedListChanged, this)); uiInterface.NotifyBlockTip.connect(boost::bind(BlockTipChanged, this, _1, _2, false)); uiInterface.NotifyHeaderTip.connect(boost::bind(BlockTipChanged, this, _1, _2, true)); uiInterface.NotifyAdditionalDataSyncProgressChanged.connect(boost::bind(NotifyAdditionalDataSyncProgressChanged, this, _1)); } void ClientModel::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2)); uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyNetworkActiveChanged.disconnect(boost::bind(NotifyNetworkActiveChanged, this, _1)); uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this)); uiInterface.BannedListChanged.disconnect(boost::bind(BannedListChanged, this)); uiInterface.NotifyBlockTip.disconnect(boost::bind(BlockTipChanged, this, _1, _2, false)); uiInterface.NotifyHeaderTip.disconnect(boost::bind(BlockTipChanged, this, _1, _2, true)); uiInterface.NotifyAdditionalDataSyncProgressChanged.disconnect(boost::bind(NotifyAdditionalDataSyncProgressChanged, this, _1)); } <|endoftext|>
<commit_before>// Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file license.txt or http://www.opensource.org/licenses/mit-license.php. #include <boost/algorithm/string.hpp> #include <boost/interprocess/ipc/message_queue.hpp> #include <boost/tokenizer.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include "headers.h" using namespace boost::interprocess; using namespace boost::posix_time; using namespace boost; using namespace std; void ipcShutdown() { message_queue::remove("BitcoinURL"); } void ipcThread(void* parg) { message_queue* mq = (message_queue*)parg; char strBuf[257]; size_t nSize; unsigned int nPriority; loop { ptime d = boost::posix_time::microsec_clock::universal_time() + millisec(100); if(mq->timed_receive(&strBuf, sizeof(strBuf), nSize, nPriority, d)) { ThreadSafeHandleURL(std::string(strBuf, nSize)); Sleep(1000); } if (fShutdown) { ipcShutdown(); break; } } ipcShutdown(); } void ipcInit() { message_queue* mq; char strBuf[257]; size_t nSize; unsigned int nPriority; try { mq = new message_queue(open_or_create, "BitcoinURL", 2, 256); // Make sure we don't lose any bitcoin: URIs for (int i = 0; i < 2; i++) { ptime d = boost::posix_time::microsec_clock::universal_time() + millisec(1); if(mq->timed_receive(&strBuf, sizeof(strBuf), nSize, nPriority, d)) { ThreadSafeHandleURL(std::string(strBuf, nSize)); } else break; } // Make sure only one bitcoin instance is listening message_queue::remove("BitcoinURL"); mq = new message_queue(open_or_create, "BitcoinURL", 2, 256); } catch (interprocess_exception &ex) { return; } if (!CreateThread(ipcThread, mq)) { delete mq; } } <commit_msg>Do not start bitcoin: thread on OSX. fixes #889<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file license.txt or http://www.opensource.org/licenses/mit-license.php. #include <boost/algorithm/string.hpp> #include <boost/interprocess/ipc/message_queue.hpp> #include <boost/tokenizer.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include "headers.h" using namespace boost::interprocess; using namespace boost::posix_time; using namespace boost; using namespace std; void ipcShutdown() { message_queue::remove("BitcoinURL"); } void ipcThread(void* parg) { message_queue* mq = (message_queue*)parg; char strBuf[257]; size_t nSize; unsigned int nPriority; loop { ptime d = boost::posix_time::microsec_clock::universal_time() + millisec(100); if(mq->timed_receive(&strBuf, sizeof(strBuf), nSize, nPriority, d)) { ThreadSafeHandleURL(std::string(strBuf, nSize)); Sleep(1000); } if (fShutdown) { ipcShutdown(); break; } } ipcShutdown(); } void ipcInit() { #ifdef MAC_OSX // TODO: implement bitcoin: URI handling the Mac Way return; #endif message_queue* mq; char strBuf[257]; size_t nSize; unsigned int nPriority; try { mq = new message_queue(open_or_create, "BitcoinURL", 2, 256); // Make sure we don't lose any bitcoin: URIs for (int i = 0; i < 2; i++) { ptime d = boost::posix_time::microsec_clock::universal_time() + millisec(1); if(mq->timed_receive(&strBuf, sizeof(strBuf), nSize, nPriority, d)) { ThreadSafeHandleURL(std::string(strBuf, nSize)); } else break; } // Make sure only one bitcoin instance is listening message_queue::remove("BitcoinURL"); mq = new message_queue(open_or_create, "BitcoinURL", 2, 256); } catch (interprocess_exception &ex) { return; } if (!CreateThread(ipcThread, mq)) { delete mq; } } <|endoftext|>
<commit_before>// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "walletframe.h" #include "bitcoingui.h" #include "walletview.h" #include <cstdio> #include <QHBoxLayout> #include <QLabel> WalletFrame::WalletFrame(BitcoinGUI *_gui) : QFrame(_gui), gui(_gui) { // Leave HBox hook for adding a list view later QHBoxLayout *walletFrameLayout = new QHBoxLayout(this); setContentsMargins(0,0,0,0); walletStack = new QStackedWidget(this); walletFrameLayout->setContentsMargins(0,0,0,0); walletFrameLayout->addWidget(walletStack); QLabel *noWallet = new QLabel(tr("No wallet has been loaded.")); noWallet->setAlignment(Qt::AlignCenter); walletStack->addWidget(noWallet); } WalletFrame::~WalletFrame() { } void WalletFrame::setClientModel(ClientModel *clientModel) { this->clientModel = clientModel; } bool WalletFrame::addWallet(const QString& name, WalletModel *walletModel) { if (!gui || !clientModel || !walletModel || mapWalletViews.count(name) > 0) return false; WalletView *walletView = new WalletView(this); walletView->setBitcoinGUI(gui); walletView->setClientModel(clientModel); walletView->setWalletModel(walletModel); walletView->showOutOfSyncWarning(bOutOfSync); /* TODO we should goto the currently selected page once dynamically adding wallets is supported */ walletView->gotoOverviewPage(); walletStack->addWidget(walletView); mapWalletViews[name] = walletView; // Ensure a walletView is able to show the main window connect(walletView, SIGNAL(showNormalIfMinimized()), gui, SLOT(showNormalIfMinimized())); return true; } bool WalletFrame::setCurrentWallet(const QString& name) { if (mapWalletViews.count(name) == 0) return false; WalletView *walletView = mapWalletViews.value(name); walletStack->setCurrentWidget(walletView); walletView->updateEncryptionStatus(); return true; } bool WalletFrame::removeWallet(const QString &name) { if (mapWalletViews.count(name) == 0) return false; WalletView *walletView = mapWalletViews.take(name); walletStack->removeWidget(walletView); return true; } void WalletFrame::removeAllWallets() { QMap<QString, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) walletStack->removeWidget(i.value()); mapWalletViews.clear(); } bool WalletFrame::handlePaymentRequest(const SendCoinsRecipient &recipient) { WalletView *walletView = currentWalletView(); if (!walletView) return false; return walletView->handlePaymentRequest(recipient); } void WalletFrame::showOutOfSyncWarning(bool fShow) { bOutOfSync = fShow; QMap<QString, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->showOutOfSyncWarning(fShow); } void WalletFrame::gotoOverviewPage() { QMap<QString, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->gotoOverviewPage(); } void WalletFrame::gotoHistoryPage() { QMap<QString, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->gotoHistoryPage(); } void WalletFrame::gotoReceiveCoinsPage() { QMap<QString, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->gotoReceiveCoinsPage(); } void WalletFrame::gotoSendCoinsPage(QString addr) { QMap<QString, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->gotoSendCoinsPage(addr); } void WalletFrame::gotoSignMessageTab(QString addr) { WalletView *walletView = currentWalletView(); if (walletView) walletView->gotoSignMessageTab(addr); } void WalletFrame::gotoVerifyMessageTab(QString addr) { WalletView *walletView = currentWalletView(); if (walletView) walletView->gotoVerifyMessageTab(addr); } void WalletFrame::encryptWallet(bool status) { WalletView *walletView = currentWalletView(); if (walletView) walletView->encryptWallet(status); } void WalletFrame::backupWallet() { WalletView *walletView = currentWalletView(); if (walletView) walletView->backupWallet(); } void WalletFrame::changePassphrase() { WalletView *walletView = currentWalletView(); if (walletView) walletView->changePassphrase(); } void WalletFrame::unlockWallet() { WalletView *walletView = currentWalletView(); if (walletView) walletView->unlockWallet(); } void WalletFrame::lockWallet() { WalletView *walletView = currentWalletView(); if (walletView) walletView->lockWallet(); } void WalletFrame::usedSendingAddresses() { WalletView *walletView = currentWalletView(); if (walletView) walletView->usedSendingAddresses(); } void WalletFrame::usedReceivingAddresses() { WalletView *walletView = currentWalletView(); if (walletView) walletView->usedReceivingAddresses(); } WalletView *WalletFrame::currentWalletView() { return qobject_cast<WalletView*>(walletStack->currentWidget()); } <commit_msg>Update walletframe.cpp<commit_after>// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "walletframe.h" #include "bitcoingui.h" #include "walletview.h" #include <cstdio> #include <iostream> #include <QHBoxLayout> #include <QLabel> WalletFrame::WalletFrame(BitcoinGUI *_gui) : QFrame(_gui), gui(_gui) { // Leave HBox hook for adding a list view later QHBoxLayout *walletFrameLayout = new QHBoxLayout(this); setContentsMargins(0,0,0,0); walletStack = new QStackedWidget(this); walletFrameLayout->setContentsMargins(0,0,0,0); walletFrameLayout->addWidget(walletStack); QLabel *noWallet = new QLabel(tr("No wallet has been loaded.")); noWallet->setAlignment(Qt::AlignCenter); walletStack->addWidget(noWallet); } WalletFrame::~WalletFrame() { } void WalletFrame::setClientModel(ClientModel *clientModel) { this->clientModel = clientModel; } bool WalletFrame::addWallet(const QString& name, WalletModel *walletModel) { if (!gui || !clientModel || !walletModel || mapWalletViews.count(name) > 0) return false; WalletView *walletView = new WalletView(this); walletView->setBitcoinGUI(gui); walletView->setClientModel(clientModel); walletView->setWalletModel(walletModel); walletView->showOutOfSyncWarning(bOutOfSync); /* TODO we should goto the currently selected page once dynamically adding wallets is supported */ walletView->gotoOverviewPage(); walletStack->addWidget(walletView); mapWalletViews[name] = walletView; // Ensure a walletView is able to show the main window connect(walletView, SIGNAL(showNormalIfMinimized()), gui, SLOT(showNormalIfMinimized())); return true; } bool WalletFrame::setCurrentWallet(const QString& name) { if (mapWalletViews.count(name) == 0) return false; WalletView *walletView = mapWalletViews.value(name); walletStack->setCurrentWidget(walletView); walletView->updateEncryptionStatus(); return true; } bool WalletFrame::removeWallet(const QString &name) { if (mapWalletViews.count(name) == 0) return false; WalletView *walletView = mapWalletViews.take(name); walletStack->removeWidget(walletView); return true; } void WalletFrame::removeAllWallets() { QMap<QString, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) walletStack->removeWidget(i.value()); mapWalletViews.clear(); } bool WalletFrame::handlePaymentRequest(const SendCoinsRecipient &recipient) { WalletView *walletView = currentWalletView(); if (!walletView) return false; return walletView->handlePaymentRequest(recipient); } void WalletFrame::showOutOfSyncWarning(bool fShow) { bOutOfSync = fShow; QMap<QString, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->showOutOfSyncWarning(fShow); } void WalletFrame::gotoOverviewPage() { QMap<QString, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->gotoOverviewPage(); } void WalletFrame::gotoHistoryPage() { QMap<QString, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->gotoHistoryPage(); } void WalletFrame::gotoReceiveCoinsPage() { QMap<QString, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->gotoReceiveCoinsPage(); } void WalletFrame::gotoSendCoinsPage(QString addr) { QMap<QString, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->gotoSendCoinsPage(addr); } void WalletFrame::gotoSignMessageTab(QString addr) { WalletView *walletView = currentWalletView(); if (walletView) walletView->gotoSignMessageTab(addr); } void WalletFrame::gotoVerifyMessageTab(QString addr) { WalletView *walletView = currentWalletView(); if (walletView) walletView->gotoVerifyMessageTab(addr); } void WalletFrame::encryptWallet(bool status) { WalletView *walletView = currentWalletView(); if (walletView) walletView->encryptWallet(status); } void WalletFrame::backupWallet() { WalletView *walletView = currentWalletView(); if (walletView) walletView->backupWallet(); } void WalletFrame::changePassphrase() { WalletView *walletView = currentWalletView(); if (walletView) walletView->changePassphrase(); } void WalletFrame::unlockWallet() { WalletView *walletView = currentWalletView(); if (walletView) walletView->unlockWallet(); } void WalletFrame::printPaperWallets() { WalletView *walletView = currentWalletView(); if (walletView) walletView->printPaperWallets(); } void WalletFrame::lockWallet() { WalletView *walletView = currentWalletView(); if (walletView) walletView->lockWallet(); } void WalletFrame::usedSendingAddresses() { WalletView *walletView = currentWalletView(); if (walletView) walletView->usedSendingAddresses(); } void WalletFrame::usedReceivingAddresses() { WalletView *walletView = currentWalletView(); if (walletView) walletView->usedReceivingAddresses(); } WalletView *WalletFrame::currentWalletView() { return qobject_cast<WalletView*>(walletStack->currentWidget()); } <|endoftext|>
<commit_before>/* Copyright (C) 2014 Marcus Soll All rights reserved. You may use this file under the terms of BSD license as follows: Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Jolla Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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 "randomaiplayer.h" #include <QTime> RandomAIPlayer::RandomAIPlayer(QObject *parent) : Player(parent) { qsrand(QTime(0,0,0).secsTo(QTime::currentTime())); } void RandomAIPlayer::doTurn() { emit sendMessage("???"); emit turn(qrand()%8, qrand()%8); } bool RandomAIPlayer::isHuman() { return false; } void RandomAIPlayer::getBoard(Gameboard board, int player) { } void RandomAIPlayer::humanInput(int x, int y) { } <commit_msg>Changed Messages of Random AI<commit_after>/* Copyright (C) 2014 Marcus Soll All rights reserved. You may use this file under the terms of BSD license as follows: Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Jolla Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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 "randomaiplayer.h" #include <QTime> RandomAIPlayer::RandomAIPlayer(QObject *parent) : Player(parent) { qsrand(QTime(0,0,0).secsTo(QTime::currentTime())); } void RandomAIPlayer::doTurn() { int random = qrand()%10; if(random == 0) { emit sendMessage("What am I doing?"); } else { QString s = ""; for(int i = 0; i < random; --random) { s = QString("%1%2").arg(s).arg("?"); } emit sendMessage(s); } emit turn(qrand()%8, qrand()%8); } bool RandomAIPlayer::isHuman() { return false; } void RandomAIPlayer::getBoard(Gameboard board, int player) { } void RandomAIPlayer::humanInput(int x, int y) { } <|endoftext|>
<commit_before>/* Copyright (C) 2017 Alexandr Akulich <[email protected]> This file is a part of TelegramQt library. 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. */ #ifndef TELEGRAMDEBUG_P_HPP #define TELEGRAMDEBUG_P_HPP #include "Debug.hpp" #include "TLNumbers.hpp" #include "TLValues.hpp" TELEGRAMQT_INTERNAL_EXPORT QDebug operator<<(QDebug d, const TLValue &v); template <int Size> TELEGRAMQT_INTERNAL_EXPORT QDebug operator<<(QDebug d, const TLNumber<Size> &n); namespace Telegram { namespace MTProto { struct FullMessageHeader; struct IgnoredMessageNotification; } // MTProto namespace namespace Debug { class TELEGRAMQT_INTERNAL_EXPORT Spacer { public: Spacer(); ~Spacer(); const char *innerSpaces(); const char *outerSpaces(); private: static int m_spacing; static const int m_step = 4; bool m_hasInnerCalls = false; }; } // Debug namespace template <typename T> QString toHex(T number) { return QStringLiteral("%1").arg(number, sizeof(number) * 2, 0x10, QLatin1Char('0')); } } // Telegram namespace TELEGRAMQT_INTERNAL_EXPORT QDebug operator<<(QDebug d, const Telegram::MTProto::FullMessageHeader &header); TELEGRAMQT_INTERNAL_EXPORT QDebug operator<<(QDebug d, const Telegram::MTProto::IgnoredMessageNotification &notification); #endif // TELEGRAMDEBUG_P_HPP <commit_msg>Introduce a private FUNC_INFO shortcut macro<commit_after>/* Copyright (C) 2017 Alexandr Akulich <[email protected]> This file is a part of TelegramQt library. 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. */ #ifndef TELEGRAMDEBUG_P_HPP #define TELEGRAMDEBUG_P_HPP #include "Debug.hpp" #include "TLNumbers.hpp" #include "TLValues.hpp" // Macro for stream debug output #define CALL_INFO this << __func__ TELEGRAMQT_INTERNAL_EXPORT QDebug operator<<(QDebug d, const TLValue &v); template <int Size> TELEGRAMQT_INTERNAL_EXPORT QDebug operator<<(QDebug d, const TLNumber<Size> &n); namespace Telegram { namespace MTProto { struct FullMessageHeader; struct IgnoredMessageNotification; } // MTProto namespace namespace Debug { class TELEGRAMQT_INTERNAL_EXPORT Spacer { public: Spacer(); ~Spacer(); const char *innerSpaces(); const char *outerSpaces(); private: static int m_spacing; static const int m_step = 4; bool m_hasInnerCalls = false; }; } // Debug namespace template <typename T> QString toHex(T number) { return QStringLiteral("%1").arg(number, sizeof(number) * 2, 0x10, QLatin1Char('0')); } } // Telegram namespace TELEGRAMQT_INTERNAL_EXPORT QDebug operator<<(QDebug d, const Telegram::MTProto::FullMessageHeader &header); TELEGRAMQT_INTERNAL_EXPORT QDebug operator<<(QDebug d, const Telegram::MTProto::IgnoredMessageNotification &notification); #endif // TELEGRAMDEBUG_P_HPP <|endoftext|>
<commit_before>/* * Copyright 2012 BrewPi/Elco Jacobs. * * This file is part of BrewPi. * * BrewPi is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BrewPi is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with BrewPi. If not, see <http://www.gnu.org/licenses/>. */ #include "Brewpi.h" #include "TemperatureFormats.h" #include <string.h> #include <limits.h> #include "TempControl.h" /** * Before (no-optimize) Program Memory Usage : 26230 bytes 80.0 % Full Data Memory Usage : 1081 bytes 42.2 % Full * After Program Memory Usage : 26058 bytes 79.5 % Full Data Memory Usage : 1087 bytes 42.5 % Full */ #define OPTIMIZE_TEMPERATURE_FORMATS_fixedPointToString 1 && OPTIMIZE_TEMPERATURE_FORMATS #define OPTIMIZE_TEMPERATURE_FORMATS_convertAntConstrain 1 && OPTIMIZE_TEMPERATURE_FORMATS // result can have maximum length of : sign + 3 digits integer part + point + 3 digits fraction part + '\0' = 9 bytes; // only 1, 2 or 3 decimals allowed. // returns pointer to the string // fixed7_23 is used to prevent overflow char * tempToString(char s[9], fixed23_9 rawValue, uint8_t numDecimals, uint8_t maxLength){ if(rawValue == INT_MIN){ strcpy_P(s, PSTR("null")); return s; } if(tempControl.cc.tempFormat == 'F'){ rawValue = (rawValue * 9) / 5 + (32 << 9); // convert to Fahrenheit first } return fixedPointToString(s, rawValue, numDecimals, maxLength); } char * fixedPointToString(char s[9], fixed7_9 rawValue, uint8_t numDecimals, uint8_t maxLength){ return fixedPointToString(s, (fixed23_9)rawValue, numDecimals, maxLength); } // this gets rid of vsnprintf_P void mysnprintf_P(char* buf, int len, const char* fmt, ...) { va_list args; va_start (args, fmt ); vsnprintf_P(buf, len, fmt, args); va_end (args); } char * fixedPointToString(char s[9], fixed23_9 rawValue, uint8_t numDecimals, uint8_t maxLength){ s[0] = ' '; if(rawValue < 0l){ s[0] = '-'; rawValue = -rawValue; } int intPart = rawValue >> 9; uint16_t fracPart; #if OPTIMIZE_TEMPERATURE_FORMATS_fixedPointToString const char* fmt; uint16_t scale; switch (numDecimals) { case 1: fmt = PSTR("%d.%01d"); scale = 10; break; case 2: fmt = PSTR("%d.%02d"); scale = 100; break; default: fmt = PSTR("%d.%03d"); scale = 1000; } fracPart = ((rawValue & 0x01FF) * scale + 256) >> 9; // add 256 for rounding if(fracPart >= scale){ intPart++; fracPart = 0; } mysnprintf_P(&s[1], maxLength-1, fmt, intPart, fracPart); #else if(numDecimals == 1){ fracPart = ((rawValue & 0x01FF) * 10 + 256) >> 9; // add 256 for rounding if(fracPart >= 10){ intPart++; fracPart = 0; // has already overflowed into integer part. } snprintf_P(&s[1], maxLength-1, PSTR("%d.%01d"), intPart, fracPart); } else if(numDecimals == 2){ fracPart = ((rawValue & 0x01FF) * 100 + 256) >> 9; if(fracPart >= 100){ intPart++; fracPart = 0; // has already overflowed into integer part. } snprintf_P(&s[1], maxLength-1, PSTR("%d.%02d"), intPart, fracPart); } else{ fracPart = ((rawValue & 0x01FF) * 1000 + 256) >> 9; if(fracPart>=1000){ intPart++; fracPart = 0; // has already overflowed into integer part. } snprintf_P(&s[1], maxLength-1, PSTR("%d.%03d"), intPart, fracPart); } #endif return s; } fixed7_9 convertAndConstrain(fixed23_9 rawTemp, int16_t offset) { if(tempControl.cc.tempFormat == 'F'){ rawTemp = ((rawTemp - offset) * 5) / 9; // convert to store as Celsius } return constrainTemp16(rawTemp); } fixed7_9 stringToTemp(const char * numberString){ fixed23_9 rawTemp = stringToFixedPoint(numberString); #ifdef OPTIMIZE_TEMPERATURE_FORMATS_convertAntConstrain return convertAndConstrain(rawTemp, 32<<9); #else if(tempControl.cc.tempFormat == 'F'){ rawTemp = ((rawTemp - (32 << 9)) * 5) / 9; // convert to store as Celsius } return constrainTemp16(rawTemp); #endif } fixed23_9 stringToFixedPoint(const char * numberString){ // receive new temperature as null terminated string: "19.20" fixed23_9 intPart = 0; fixed23_9 fracPart = 0; char * fractPtr = 0; //pointer to the point in the string bool negative = 0; if(numberString[0] == '-'){ numberString++; negative = true; // by processing the sign here, we don't have to include strtol } // find the point in the string to split in the integer part and the fraction part fractPtr = strchrnul(numberString, '.'); // returns pointer to the point. intPart = atol(numberString); if(fractPtr != 0){ // decimal point was found fractPtr++; // add 1 to pointer to skip point uint8_t numDecimals = strlen(fractPtr); fracPart = atol(fractPtr); fracPart = fracPart << 9; // 9 bits for fraction part while(numDecimals > 0){ fracPart = (fracPart + 5) / 10; // divide by 10 rounded numDecimals--; } } fixed23_9 absVal = ((intPart<<9) +fracPart); return negative ? -absVal:absVal; } char * tempDiffToString(char s[9], fixed23_9 rawValue, uint8_t numDecimals, uint8_t maxLength){ if(tempControl.cc.tempFormat == 'F'){ rawValue = (rawValue * 9) / 5; // convert to Fahrenheit first } return fixedPointToString(s, rawValue, numDecimals, maxLength); } fixed7_9 stringToTempDiff(const char * numberString){ fixed23_9 rawTempDiff = stringToFixedPoint(numberString); #ifdef OPTIMIZE_TEMPERATURE_FORMATS_convertAntConstrain return convertAndConstrain(rawTempDiff, 0); #else if(tempControl.cc.tempFormat == 'F'){ rawTempDiff = (rawTempDiff * 5) / 9; // convert to store as Celsius } return constrainTemp16(rawTempDiff); #endif } int fixedToTenths(fixed23_9 temperature){ if(tempControl.cc.tempFormat == 'F'){ temperature = temperature*9/5 + 32*512; // Convert to Fahrenheit fixed point first } return (int) ((10 * temperature + 256) / 512); // return rounded result in tenth of degrees } fixed7_9 tenthsToFixed(int temperature){ if(tempControl.cc.tempFormat == 'F'){ return (( ( (fixed23_9) temperature - 320) * 512 * 5) / 9 + 5) / 10; // convert to Celsius and return rounded result in fixed point } else{ return ((fixed23_9) temperature * 512 + 5) / 10; // return rounded result in fixed point } } fixed7_9 constrainTemp(fixed23_9 valLong, fixed7_9 lower, fixed7_9 upper){ fixed7_9 val = constrainTemp16(valLong); if(val < lower){ return lower; } if(val > upper){ return upper; } return (fixed7_9)valLong; } fixed7_9 constrainTemp16(fixed23_9 val) { int16_t upper = val>>16; if (!upper) return fixed7_9(val); if (upper<0) return INT_MIN; else return INT_MAX; }<commit_msg>removed optimize conditionals in TemperatureFormats.cpp<commit_after>/* * Copyright 2012 BrewPi/Elco Jacobs. * * This file is part of BrewPi. * * BrewPi is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BrewPi is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with BrewPi. If not, see <http://www.gnu.org/licenses/>. */ #include "Brewpi.h" #include "TemperatureFormats.h" #include <string.h> #include <limits.h> #include "TempControl.h" // result can have maximum length of : sign + 3 digits integer part + point + 3 digits fraction part + '\0' = 9 bytes; // only 1, 2 or 3 decimals allowed. // returns pointer to the string // fixed7_23 is used to prevent overflow char * tempToString(char s[9], fixed23_9 rawValue, uint8_t numDecimals, uint8_t maxLength){ if(rawValue == INT_MIN){ strcpy_P(s, PSTR("null")); return s; } if(tempControl.cc.tempFormat == 'F'){ rawValue = (rawValue * 9) / 5 + (32 << 9); // convert to Fahrenheit first } return fixedPointToString(s, rawValue, numDecimals, maxLength); } char * fixedPointToString(char s[9], fixed7_9 rawValue, uint8_t numDecimals, uint8_t maxLength){ return fixedPointToString(s, (fixed23_9)rawValue, numDecimals, maxLength); } // this gets rid of vsnprintf_P void mysnprintf_P(char* buf, int len, const char* fmt, ...) { va_list args; va_start (args, fmt ); vsnprintf_P(buf, len, fmt, args); va_end (args); } char * fixedPointToString(char s[9], fixed23_9 rawValue, uint8_t numDecimals, uint8_t maxLength){ s[0] = ' '; if(rawValue < 0l){ s[0] = '-'; rawValue = -rawValue; } int intPart = rawValue >> 9; uint16_t fracPart; const char* fmt; uint16_t scale; switch (numDecimals) { case 1: fmt = PSTR("%d.%01d"); scale = 10; break; case 2: fmt = PSTR("%d.%02d"); scale = 100; break; default: fmt = PSTR("%d.%03d"); scale = 1000; } fracPart = ((rawValue & 0x01FF) * scale + 256) >> 9; // add 256 for rounding if(fracPart >= scale){ intPart++; fracPart = 0; } mysnprintf_P(&s[1], maxLength-1, fmt, intPart, fracPart); return s; } fixed7_9 convertAndConstrain(fixed23_9 rawTemp, int16_t offset) { if(tempControl.cc.tempFormat == 'F'){ rawTemp = ((rawTemp - offset) * 5) / 9; // convert to store as Celsius } return constrainTemp16(rawTemp); } fixed7_9 stringToTemp(const char * numberString){ fixed23_9 rawTemp = stringToFixedPoint(numberString); return convertAndConstrain(rawTemp, 32<<9); } fixed23_9 stringToFixedPoint(const char * numberString){ // receive new temperature as null terminated string: "19.20" fixed23_9 intPart = 0; fixed23_9 fracPart = 0; char * fractPtr = 0; //pointer to the point in the string bool negative = 0; if(numberString[0] == '-'){ numberString++; negative = true; // by processing the sign here, we don't have to include strtol } // find the point in the string to split in the integer part and the fraction part fractPtr = strchrnul(numberString, '.'); // returns pointer to the point. intPart = atol(numberString); if(fractPtr != 0){ // decimal point was found fractPtr++; // add 1 to pointer to skip point uint8_t numDecimals = strlen(fractPtr); fracPart = atol(fractPtr); fracPart = fracPart << 9; // 9 bits for fraction part while(numDecimals > 0){ fracPart = (fracPart + 5) / 10; // divide by 10 rounded numDecimals--; } } fixed23_9 absVal = ((intPart<<9) +fracPart); return negative ? -absVal:absVal; } char * tempDiffToString(char s[9], fixed23_9 rawValue, uint8_t numDecimals, uint8_t maxLength){ if(tempControl.cc.tempFormat == 'F'){ rawValue = (rawValue * 9) / 5; // convert to Fahrenheit first } return fixedPointToString(s, rawValue, numDecimals, maxLength); } fixed7_9 stringToTempDiff(const char * numberString){ fixed23_9 rawTempDiff = stringToFixedPoint(numberString); return convertAndConstrain(rawTempDiff, 0); } int fixedToTenths(fixed23_9 temperature){ if(tempControl.cc.tempFormat == 'F'){ temperature = temperature*9/5 + 32*512; // Convert to Fahrenheit fixed point first } return (int) ((10 * temperature + 256) / 512); // return rounded result in tenth of degrees } fixed7_9 tenthsToFixed(int temperature){ if(tempControl.cc.tempFormat == 'F'){ return (( ( (fixed23_9) temperature - 320) * 512 * 5) / 9 + 5) / 10; // convert to Celsius and return rounded result in fixed point } else{ return ((fixed23_9) temperature * 512 + 5) / 10; // return rounded result in fixed point } } fixed7_9 constrainTemp(fixed23_9 valLong, fixed7_9 lower, fixed7_9 upper){ fixed7_9 val = constrainTemp16(valLong); if(val < lower){ return lower; } if(val > upper){ return upper; } return (fixed7_9)valLong; } fixed7_9 constrainTemp16(fixed23_9 val) { int16_t upper = val>>16; if (!upper) return fixed7_9(val); if (upper<0) return INT_MIN; else return INT_MAX; }<|endoftext|>
<commit_before>#include "MacauPrior.h" #include <SmurffCpp/IO/MatrixIO.h> #include <SmurffCpp/IO/GenericIO.h> #include <SmurffCpp/Utils/Distribution.h> #include <SmurffCpp/Utils/Error.h> #include <SmurffCpp/Utils/counters.h> #include <SmurffCpp/Utils/linop.h> #include <ios> using namespace smurff; MacauPrior::MacauPrior() : NormalPrior() { } MacauPrior::MacauPrior(std::shared_ptr<Session> session, uint32_t mode) : NormalPrior(session, mode, "MacauPrior") { beta_precision = SideInfoConfig::BETA_PRECISION_DEFAULT_VALUE; tol = SideInfoConfig::TOL_DEFAULT_VALUE; enable_beta_precision_sampling = Config::ENABLE_BETA_PRECISION_SAMPLING_DEFAULT_VALUE; } MacauPrior::~MacauPrior() { } void MacauPrior::init() { NormalPrior::init(); THROWERROR_ASSERT_MSG(Features->rows() == num_item(), "Number of rows in train must be equal to number of rows in features"); if (use_FtF) { std::uint64_t dim = num_feat(); FtF_plus_precision.resize(dim, dim); Features->At_mul_A(FtF_plus_precision); FtF_plus_precision.diagonal().array() += beta_precision; } Uhat.resize(num_latent(), Features->rows()); Uhat.setZero(); m_beta = std::make_shared<Eigen::MatrixXd>(num_latent(), num_feat()); beta().setZero(); BBt = beta() * beta().transpose(); m_session->model().setLinkMatrix(m_mode, m_beta); } void MacauPrior::update_prior() { /* >> compute_uhat: 0.5012 (12%) in 110 >> main: 4.1396 (100%) in 1 >> rest of update_prior: 0.1684 (4%) in 110 >> sample hyper mu/Lambda: 0.3804 (9%) in 110 >> sample_beta: 1.4927 (36%) in 110 >> sample_latents: 3.8824 (94%) in 220 >> step: 3.9824 (96%) in 111 >> update_prior: 2.5436 (61%) in 110 */ COUNTER("update_prior"); { COUNTER("rest of update_prior"); } // sampling Gaussian { COUNTER("sample hyper mu/Lambda"); //uses: U, Uhat // writes: Udelta // complexity: num_latent x num_items Udelta = U() - Uhat; // uses: Udelta // complexity: num_latent x num_items std::tie(mu, Lambda) = CondNormalWishart(Udelta, mu0, b0, WI + beta_precision * BBt, df + num_feat()); } // uses: U, F // writes: Ft_y // uses: U, F // writes: Ft_y // complexity: num_latent x num_feat x num_item compute_Ft_y(Ft_y); sample_beta(); { COUNTER("compute_uhat"); // Uhat = beta * F // uses: beta, F // output: Uhat // complexity: num_feat x num_latent x num_item Features->compute_uhat(Uhat, beta()); } if (enable_beta_precision_sampling) { // uses: beta // writes: FtF COUNTER("sample_beta_precision"); double old_beta = beta_precision; beta_precision = sample_beta_precision(BBt, Lambda, beta_precision_nu0, beta_precision_mu0, beta().cols()); FtF_plus_precision.diagonal().array() += beta_precision - old_beta; } } void MacauPrior::sample_beta() { COUNTER("sample_beta"); if (use_FtF) { // uses: FtF, Ft_y, // writes: m_beta // complexity: num_feat^3 beta() = FtF_plus_precision.llt().solve(Ft_y.transpose()).transpose(); } else { // uses: Features, beta_precision, Ft_y, // writes: beta // complexity: num_feat x num_feat x num_iter blockcg_iter = Features->solve_blockcg(beta(), beta_precision, Ft_y, tol, 32, 8, throw_on_cholesky_error); } // complexity: num_feat x num_feat x num_latent BBt = beta() * beta().transpose(); std::cout << "beta: " << beta().rows() << " x " << beta().cols() << std::endl; std::cout << "BBt: " << BBt.rows() << " x " << BBt.cols() << std::endl; } const Eigen::VectorXd MacauPrior::getMu(int n) const { return mu + Uhat.col(n); } void MacauPrior::compute_Ft_y(Eigen::MatrixXd& Ft_y) { COUNTER("compute Ft_y"); // Ft_y = (U .- mu + Normal(0, Lambda^-1)) * F + std::sqrt(beta_precision) * Normal(0, Lambda^-1) // Ft_y is [ num_latent x num_feat ] matrix //HyperU: num_latent x num_item HyperU = (U() + MvNormal_prec(Lambda, num_item())).colwise() - mu; Ft_y = Features->A_mul_B(HyperU); // num_latent x num_feat //-- add beta_precision HyperU2 = MvNormal_prec(Lambda, num_feat()); // num_latent x num_feat Ft_y += std::sqrt(beta_precision) * HyperU2; } void MacauPrior::addSideInfo(const std::shared_ptr<ISideInfo>& side_info_a, double beta_precision_a, double tolerance_a, bool direct_a, bool enable_beta_precision_sampling_a, bool throw_on_cholesky_error_a) { //FIXME: remove old code // old code // side information Features = side_info_a; beta_precision = beta_precision_a; tol = tolerance_a; use_FtF = direct_a; enable_beta_precision_sampling = enable_beta_precision_sampling_a; throw_on_cholesky_error = throw_on_cholesky_error_a; // new code // side information side_info_values.push_back(side_info_a); beta_precision_values.push_back(beta_precision_a); tol_values.push_back(tolerance_a); direct_values.push_back(direct_a); enable_beta_precision_sampling_values.push_back(enable_beta_precision_sampling_a); throw_on_cholesky_error_values.push_back(throw_on_cholesky_error_a); // other code // Hyper-prior for beta_precision (mean 1.0, var of 1e+3): beta_precision_mu0 = 1.0; beta_precision_nu0 = 1e-3; } bool MacauPrior::save(std::shared_ptr<const StepFile> sf) const { NormalPrior::save(sf); std::string path = sf->makeLinkMatrixFileName(m_mode); smurff::matrix_io::eigen::write_matrix(path, beta()); return true; } void MacauPrior::restore(std::shared_ptr<const StepFile> sf) { NormalPrior::restore(sf); std::string path = sf->getLinkMatrixFileName(m_mode); smurff::matrix_io::eigen::read_matrix(path, beta()); } std::ostream& MacauPrior::info(std::ostream &os, std::string indent) { NormalPrior::info(os, indent); os << indent << " SideInfo: "; Features->print(os); os << indent << " Method: "; if (use_FtF) { os << "Cholesky Decomposition"; double needs_gb = (double)num_feat() / 1024. * (double)num_feat() / 1024. / 1024.; if (needs_gb > 1.0) os << " (needing " << needs_gb << " GB of memory)"; os << std::endl; } else { os << "CG Solver with tolerance: " << std::scientific << tol << std::fixed << std::endl; } os << indent << " BetaPrecision: "; if (enable_beta_precision_sampling) { os << "sampled around "; } else { os << "fixed at "; } os << beta_precision << std::endl; return os; } std::ostream &MacauPrior::status(std::ostream &os, std::string indent) const { os << indent << m_name << ": " << std::endl; indent += " "; os << indent << "blockcg iter = " << blockcg_iter << std::endl; os << indent << "FtF_plus_precision= " << FtF_plus_precision.norm() << std::endl; os << indent << "HyperU = " << HyperU.norm() << std::endl; os << indent << "HyperU2 = " << HyperU2.norm() << std::endl; os << indent << "Beta = " << beta().norm() << std::endl; os << indent << "beta_precision = " << beta_precision << std::endl; os << indent << "Ft_y = " << Ft_y.norm() << std::endl; return os; } std::pair<double, double> MacauPrior::posterior_beta_precision(const Eigen::MatrixXd & BBt, Eigen::MatrixXd & Lambda_u, double nu, double mu, int N) { double nux = nu + N * BBt.cols(); double mux = mu * nux / (nu + mu * (BBt.selfadjointView<Eigen::Lower>() * Lambda_u).trace()); double b = nux / 2; double c = 2 * mux / nux; return std::make_pair(b, c); } double MacauPrior::sample_beta_precision(const Eigen::MatrixXd & BBt, Eigen::MatrixXd & Lambda_u, double nu, double mu, int N) { auto gamma_post = posterior_beta_precision(BBt, Lambda_u, nu, mu, N); return rgamma(gamma_post.first, gamma_post.second); } <commit_msg>FIX: renmove debug printing<commit_after>#include "MacauPrior.h" #include <SmurffCpp/IO/MatrixIO.h> #include <SmurffCpp/IO/GenericIO.h> #include <SmurffCpp/Utils/Distribution.h> #include <SmurffCpp/Utils/Error.h> #include <SmurffCpp/Utils/counters.h> #include <SmurffCpp/Utils/linop.h> #include <ios> using namespace smurff; MacauPrior::MacauPrior() : NormalPrior() { } MacauPrior::MacauPrior(std::shared_ptr<Session> session, uint32_t mode) : NormalPrior(session, mode, "MacauPrior") { beta_precision = SideInfoConfig::BETA_PRECISION_DEFAULT_VALUE; tol = SideInfoConfig::TOL_DEFAULT_VALUE; enable_beta_precision_sampling = Config::ENABLE_BETA_PRECISION_SAMPLING_DEFAULT_VALUE; } MacauPrior::~MacauPrior() { } void MacauPrior::init() { NormalPrior::init(); THROWERROR_ASSERT_MSG(Features->rows() == num_item(), "Number of rows in train must be equal to number of rows in features"); if (use_FtF) { std::uint64_t dim = num_feat(); FtF_plus_precision.resize(dim, dim); Features->At_mul_A(FtF_plus_precision); FtF_plus_precision.diagonal().array() += beta_precision; } Uhat.resize(num_latent(), Features->rows()); Uhat.setZero(); m_beta = std::make_shared<Eigen::MatrixXd>(num_latent(), num_feat()); beta().setZero(); BBt = beta() * beta().transpose(); m_session->model().setLinkMatrix(m_mode, m_beta); } void MacauPrior::update_prior() { /* >> compute_uhat: 0.5012 (12%) in 110 >> main: 4.1396 (100%) in 1 >> rest of update_prior: 0.1684 (4%) in 110 >> sample hyper mu/Lambda: 0.3804 (9%) in 110 >> sample_beta: 1.4927 (36%) in 110 >> sample_latents: 3.8824 (94%) in 220 >> step: 3.9824 (96%) in 111 >> update_prior: 2.5436 (61%) in 110 */ COUNTER("update_prior"); { COUNTER("rest of update_prior"); } // sampling Gaussian { COUNTER("sample hyper mu/Lambda"); //uses: U, Uhat // writes: Udelta // complexity: num_latent x num_items Udelta = U() - Uhat; // uses: Udelta // complexity: num_latent x num_items std::tie(mu, Lambda) = CondNormalWishart(Udelta, mu0, b0, WI + beta_precision * BBt, df + num_feat()); } // uses: U, F // writes: Ft_y // uses: U, F // writes: Ft_y // complexity: num_latent x num_feat x num_item compute_Ft_y(Ft_y); sample_beta(); { COUNTER("compute_uhat"); // Uhat = beta * F // uses: beta, F // output: Uhat // complexity: num_feat x num_latent x num_item Features->compute_uhat(Uhat, beta()); } if (enable_beta_precision_sampling) { // uses: beta // writes: FtF COUNTER("sample_beta_precision"); double old_beta = beta_precision; beta_precision = sample_beta_precision(BBt, Lambda, beta_precision_nu0, beta_precision_mu0, beta().cols()); FtF_plus_precision.diagonal().array() += beta_precision - old_beta; } } void MacauPrior::sample_beta() { COUNTER("sample_beta"); if (use_FtF) { // uses: FtF, Ft_y, // writes: m_beta // complexity: num_feat^3 beta() = FtF_plus_precision.llt().solve(Ft_y.transpose()).transpose(); } else { // uses: Features, beta_precision, Ft_y, // writes: beta // complexity: num_feat x num_feat x num_iter blockcg_iter = Features->solve_blockcg(beta(), beta_precision, Ft_y, tol, 32, 8, throw_on_cholesky_error); } // complexity: num_feat x num_feat x num_latent BBt = beta() * beta().transpose(); } const Eigen::VectorXd MacauPrior::getMu(int n) const { return mu + Uhat.col(n); } void MacauPrior::compute_Ft_y(Eigen::MatrixXd& Ft_y) { COUNTER("compute Ft_y"); // Ft_y = (U .- mu + Normal(0, Lambda^-1)) * F + std::sqrt(beta_precision) * Normal(0, Lambda^-1) // Ft_y is [ num_latent x num_feat ] matrix //HyperU: num_latent x num_item HyperU = (U() + MvNormal_prec(Lambda, num_item())).colwise() - mu; Ft_y = Features->A_mul_B(HyperU); // num_latent x num_feat //-- add beta_precision HyperU2 = MvNormal_prec(Lambda, num_feat()); // num_latent x num_feat Ft_y += std::sqrt(beta_precision) * HyperU2; } void MacauPrior::addSideInfo(const std::shared_ptr<ISideInfo>& side_info_a, double beta_precision_a, double tolerance_a, bool direct_a, bool enable_beta_precision_sampling_a, bool throw_on_cholesky_error_a) { //FIXME: remove old code // old code // side information Features = side_info_a; beta_precision = beta_precision_a; tol = tolerance_a; use_FtF = direct_a; enable_beta_precision_sampling = enable_beta_precision_sampling_a; throw_on_cholesky_error = throw_on_cholesky_error_a; // new code // side information side_info_values.push_back(side_info_a); beta_precision_values.push_back(beta_precision_a); tol_values.push_back(tolerance_a); direct_values.push_back(direct_a); enable_beta_precision_sampling_values.push_back(enable_beta_precision_sampling_a); throw_on_cholesky_error_values.push_back(throw_on_cholesky_error_a); // other code // Hyper-prior for beta_precision (mean 1.0, var of 1e+3): beta_precision_mu0 = 1.0; beta_precision_nu0 = 1e-3; } bool MacauPrior::save(std::shared_ptr<const StepFile> sf) const { NormalPrior::save(sf); std::string path = sf->makeLinkMatrixFileName(m_mode); smurff::matrix_io::eigen::write_matrix(path, beta()); return true; } void MacauPrior::restore(std::shared_ptr<const StepFile> sf) { NormalPrior::restore(sf); std::string path = sf->getLinkMatrixFileName(m_mode); smurff::matrix_io::eigen::read_matrix(path, beta()); } std::ostream& MacauPrior::info(std::ostream &os, std::string indent) { NormalPrior::info(os, indent); os << indent << " SideInfo: "; Features->print(os); os << indent << " Method: "; if (use_FtF) { os << "Cholesky Decomposition"; double needs_gb = (double)num_feat() / 1024. * (double)num_feat() / 1024. / 1024.; if (needs_gb > 1.0) os << " (needing " << needs_gb << " GB of memory)"; os << std::endl; } else { os << "CG Solver with tolerance: " << std::scientific << tol << std::fixed << std::endl; } os << indent << " BetaPrecision: "; if (enable_beta_precision_sampling) { os << "sampled around "; } else { os << "fixed at "; } os << beta_precision << std::endl; return os; } std::ostream &MacauPrior::status(std::ostream &os, std::string indent) const { os << indent << m_name << ": " << std::endl; indent += " "; os << indent << "blockcg iter = " << blockcg_iter << std::endl; os << indent << "FtF_plus_precision= " << FtF_plus_precision.norm() << std::endl; os << indent << "HyperU = " << HyperU.norm() << std::endl; os << indent << "HyperU2 = " << HyperU2.norm() << std::endl; os << indent << "Beta = " << beta().norm() << std::endl; os << indent << "beta_precision = " << beta_precision << std::endl; os << indent << "Ft_y = " << Ft_y.norm() << std::endl; return os; } std::pair<double, double> MacauPrior::posterior_beta_precision(const Eigen::MatrixXd & BBt, Eigen::MatrixXd & Lambda_u, double nu, double mu, int N) { double nux = nu + N * BBt.cols(); double mux = mu * nux / (nu + mu * (BBt.selfadjointView<Eigen::Lower>() * Lambda_u).trace()); double b = nux / 2; double c = 2 * mux / nux; return std::make_pair(b, c); } double MacauPrior::sample_beta_precision(const Eigen::MatrixXd & BBt, Eigen::MatrixXd & Lambda_u, double nu, double mu, int N) { auto gamma_post = posterior_beta_precision(BBt, Lambda_u, nu, mu, N); return rgamma(gamma_post.first, gamma_post.second); } <|endoftext|>
<commit_before>/* * Assorted commonly used Vulkan helper functions * * Copyright (C) 2016 by Sascha Willems - www.saschawillems.de * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) */ #include "VulkanTools.h" namespace vks { namespace tools { std::string errorString(VkResult errorCode) { switch (errorCode) { #define STR(r) case VK_ ##r: return #r STR(NOT_READY); STR(TIMEOUT); STR(EVENT_SET); STR(EVENT_RESET); STR(INCOMPLETE); STR(ERROR_OUT_OF_HOST_MEMORY); STR(ERROR_OUT_OF_DEVICE_MEMORY); STR(ERROR_INITIALIZATION_FAILED); STR(ERROR_DEVICE_LOST); STR(ERROR_MEMORY_MAP_FAILED); STR(ERROR_LAYER_NOT_PRESENT); STR(ERROR_EXTENSION_NOT_PRESENT); STR(ERROR_FEATURE_NOT_PRESENT); STR(ERROR_INCOMPATIBLE_DRIVER); STR(ERROR_TOO_MANY_OBJECTS); STR(ERROR_FORMAT_NOT_SUPPORTED); STR(ERROR_SURFACE_LOST_KHR); STR(ERROR_NATIVE_WINDOW_IN_USE_KHR); STR(SUBOPTIMAL_KHR); STR(ERROR_OUT_OF_DATE_KHR); STR(ERROR_INCOMPATIBLE_DISPLAY_KHR); STR(ERROR_VALIDATION_FAILED_EXT); STR(ERROR_INVALID_SHADER_NV); #undef STR default: return "UNKNOWN_ERROR"; } } std::string physicalDeviceTypeString(VkPhysicalDeviceType type) { switch (type) { #define STR(r) case VK_PHYSICAL_DEVICE_TYPE_ ##r: return #r STR(OTHER); STR(INTEGRATED_GPU); STR(DISCRETE_GPU); STR(VIRTUAL_GPU); #undef STR default: return "UNKNOWN_DEVICE_TYPE"; } } VkBool32 getSupportedDepthFormat(VkPhysicalDevice physicalDevice, VkFormat *depthFormat) { // Since all depth formats may be optional, we need to find a suitable depth format to use // Start with the highest precision packed format std::vector<VkFormat> depthFormats = { VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D32_SFLOAT, VK_FORMAT_D24_UNORM_S8_UINT, VK_FORMAT_D16_UNORM_S8_UINT, VK_FORMAT_D16_UNORM }; for (auto& format : depthFormats) { VkFormatProperties formatProps; vkGetPhysicalDeviceFormatProperties(physicalDevice, format, &formatProps); // Format must support depth stencil attachment for optimal tiling if (formatProps.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) { *depthFormat = format; return true; } } return false; } // Create an image memory barrier for changing the layout of // an image and put it into an active command buffer // See chapter 11.4 "Image Layout" for details void setImageLayout( VkCommandBuffer cmdbuffer, VkImage image, VkImageAspectFlags aspectMask, VkImageLayout oldImageLayout, VkImageLayout newImageLayout, VkImageSubresourceRange subresourceRange, VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask) { // Create an image barrier object VkImageMemoryBarrier imageMemoryBarrier = vks::initializers::imageMemoryBarrier(); imageMemoryBarrier.oldLayout = oldImageLayout; imageMemoryBarrier.newLayout = newImageLayout; imageMemoryBarrier.image = image; imageMemoryBarrier.subresourceRange = subresourceRange; // Source layouts (old) // Source access mask controls actions that have to be finished on the old layout // before it will be transitioned to the new layout switch (oldImageLayout) { case VK_IMAGE_LAYOUT_UNDEFINED: // Image layout is undefined (or does not matter) // Only valid as initial layout // No flags required, listed only for completeness imageMemoryBarrier.srcAccessMask = 0; break; case VK_IMAGE_LAYOUT_PREINITIALIZED: // Image is preinitialized // Only valid as initial layout for linear images, preserves memory contents // Make sure host writes have been finished imageMemoryBarrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; break; case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL: // Image is a color attachment // Make sure any writes to the color buffer have been finished imageMemoryBarrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; break; case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL: // Image is a depth/stencil attachment // Make sure any writes to the depth/stencil buffer have been finished imageMemoryBarrier.srcAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; break; case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL: // Image is a transfer source // Make sure any reads from the image have been finished imageMemoryBarrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT; break; case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL: // Image is a transfer destination // Make sure any writes to the image have been finished imageMemoryBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; break; case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL: // Image is read by a shader // Make sure any shader reads from the image have been finished imageMemoryBarrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT; break; } // Target layouts (new) // Destination access mask controls the dependency for the new image layout switch (newImageLayout) { case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL: // Image will be used as a transfer destination // Make sure any writes to the image have been finished imageMemoryBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; break; case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL: // Image will be used as a transfer source // Make sure any reads from the image have been finished imageMemoryBarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; break; case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL: // Image will be used as a color attachment // Make sure any writes to the color buffer have been finished imageMemoryBarrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; break; case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL: // Image layout will be used as a depth/stencil attachment // Make sure any writes to depth/stencil buffer have been finished imageMemoryBarrier.dstAccessMask = imageMemoryBarrier.dstAccessMask | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; break; case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL: // Image will be read in a shader (sampler, input attachment) // Make sure any writes to the image have been finished if (imageMemoryBarrier.srcAccessMask == 0) { imageMemoryBarrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT; } imageMemoryBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; break; } // Put barrier inside setup command buffer vkCmdPipelineBarrier( cmdbuffer, srcStageMask, dstStageMask, 0, 0, nullptr, 0, nullptr, 1, &imageMemoryBarrier); } // Fixed sub resource on first mip level and layer void setImageLayout( VkCommandBuffer cmdbuffer, VkImage image, VkImageAspectFlags aspectMask, VkImageLayout oldImageLayout, VkImageLayout newImageLayout, VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask) { VkImageSubresourceRange subresourceRange = {}; subresourceRange.aspectMask = aspectMask; subresourceRange.baseMipLevel = 0; subresourceRange.levelCount = 1; subresourceRange.layerCount = 1; setImageLayout(cmdbuffer, image, aspectMask, oldImageLayout, newImageLayout, subresourceRange); } void insertImageMemoryBarrier( VkCommandBuffer cmdbuffer, VkImage image, VkAccessFlags srcAccessMask, VkAccessFlags dstAccessMask, VkImageLayout oldImageLayout, VkImageLayout newImageLayout, VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask, VkImageSubresourceRange subresourceRange) { VkImageMemoryBarrier imageMemoryBarrier = vks::initializers::imageMemoryBarrier(); imageMemoryBarrier.srcAccessMask = srcAccessMask; imageMemoryBarrier.dstAccessMask = dstAccessMask; imageMemoryBarrier.oldLayout = oldImageLayout; imageMemoryBarrier.newLayout = newImageLayout; imageMemoryBarrier.image = image; imageMemoryBarrier.subresourceRange = subresourceRange; vkCmdPipelineBarrier( cmdbuffer, srcStageMask, dstStageMask, 0, 0, nullptr, 0, nullptr, 1, &imageMemoryBarrier); } void exitFatal(std::string message, std::string caption) { #if defined(_WIN32) MessageBox(NULL, message.c_str(), caption.c_str(), MB_OK | MB_ICONERROR); #elif defined(__ANDROID__) LOGE("Fatal error: %s", message.c_str()); #else std::cerr << message << "\n"; #endif exit(1); } std::string readTextFile(const char *fileName) { std::string fileContent; std::ifstream fileStream(fileName, std::ios::in); if (!fileStream.is_open()) { printf("File %s not found\n", fileName); return ""; } std::string line = ""; while (!fileStream.eof()) { getline(fileStream, line); fileContent.append(line + "\n"); } fileStream.close(); return fileContent; } #if defined(__ANDROID__) // Android shaders are stored as assets in the apk // So they need to be loaded via the asset manager VkShaderModule loadShader(AAssetManager* assetManager, const char *fileName, VkDevice device, VkShaderStageFlagBits stage) { // Load shader from compressed asset AAsset* asset = AAssetManager_open(assetManager, fileName, AASSET_MODE_STREAMING); assert(asset); size_t size = AAsset_getLength(asset); assert(size > 0); char *shaderCode = new char[size]; AAsset_read(asset, shaderCode, size); AAsset_close(asset); VkShaderModule shaderModule; VkShaderModuleCreateInfo moduleCreateInfo; moduleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; moduleCreateInfo.pNext = NULL; moduleCreateInfo.codeSize = size; moduleCreateInfo.pCode = (uint32_t*)shaderCode; moduleCreateInfo.flags = 0; VK_CHECK_RESULT(vkCreateShaderModule(device, &moduleCreateInfo, NULL, &shaderModule)); delete[] shaderCode; return shaderModule; } #else VkShaderModule loadShader(const char *fileName, VkDevice device, VkShaderStageFlagBits stage) { std::ifstream is(fileName, std::ios::binary | std::ios::in | std::ios::ate); if (is.is_open()) { size_t size = is.tellg(); is.seekg(0, std::ios::beg); char* shaderCode = new char[size]; is.read(shaderCode, size); is.close(); assert(size > 0); VkShaderModule shaderModule; VkShaderModuleCreateInfo moduleCreateInfo{}; moduleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; moduleCreateInfo.codeSize = size; moduleCreateInfo.pCode = (uint32_t*)shaderCode; VK_CHECK_RESULT(vkCreateShaderModule(device, &moduleCreateInfo, NULL, &shaderModule)); delete[] shaderCode; return shaderModule; } else { std::cerr << "Error: Could not open shader file \"" << fileName << "\"" << std::endl; return VK_NULL_HANDLE; } } #endif VkShaderModule loadShaderGLSL(const char *fileName, VkDevice device, VkShaderStageFlagBits stage) { std::string shaderSrc = readTextFile(fileName); const char *shaderCode = shaderSrc.c_str(); size_t size = strlen(shaderCode); assert(size > 0); VkShaderModule shaderModule; VkShaderModuleCreateInfo moduleCreateInfo; moduleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; moduleCreateInfo.pNext = NULL; moduleCreateInfo.codeSize = 3 * sizeof(uint32_t) + size + 1; moduleCreateInfo.pCode = (uint32_t*)malloc(moduleCreateInfo.codeSize); moduleCreateInfo.flags = 0; // Magic SPV number ((uint32_t *)moduleCreateInfo.pCode)[0] = 0x07230203; ((uint32_t *)moduleCreateInfo.pCode)[1] = 0; ((uint32_t *)moduleCreateInfo.pCode)[2] = stage; memcpy(((uint32_t *)moduleCreateInfo.pCode + 3), shaderCode, size + 1); VK_CHECK_RESULT(vkCreateShaderModule(device, &moduleCreateInfo, NULL, &shaderModule)); return shaderModule; } bool fileExists(const std::string &filename) { std::ifstream f(filename.c_str()); return !f.fail(); } } }<commit_msg>Default route for image layout switch statements (fixes gcc compiler warnings, refs #103)<commit_after>/* * Assorted commonly used Vulkan helper functions * * Copyright (C) 2016 by Sascha Willems - www.saschawillems.de * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) */ #include "VulkanTools.h" namespace vks { namespace tools { std::string errorString(VkResult errorCode) { switch (errorCode) { #define STR(r) case VK_ ##r: return #r STR(NOT_READY); STR(TIMEOUT); STR(EVENT_SET); STR(EVENT_RESET); STR(INCOMPLETE); STR(ERROR_OUT_OF_HOST_MEMORY); STR(ERROR_OUT_OF_DEVICE_MEMORY); STR(ERROR_INITIALIZATION_FAILED); STR(ERROR_DEVICE_LOST); STR(ERROR_MEMORY_MAP_FAILED); STR(ERROR_LAYER_NOT_PRESENT); STR(ERROR_EXTENSION_NOT_PRESENT); STR(ERROR_FEATURE_NOT_PRESENT); STR(ERROR_INCOMPATIBLE_DRIVER); STR(ERROR_TOO_MANY_OBJECTS); STR(ERROR_FORMAT_NOT_SUPPORTED); STR(ERROR_SURFACE_LOST_KHR); STR(ERROR_NATIVE_WINDOW_IN_USE_KHR); STR(SUBOPTIMAL_KHR); STR(ERROR_OUT_OF_DATE_KHR); STR(ERROR_INCOMPATIBLE_DISPLAY_KHR); STR(ERROR_VALIDATION_FAILED_EXT); STR(ERROR_INVALID_SHADER_NV); #undef STR default: return "UNKNOWN_ERROR"; } } std::string physicalDeviceTypeString(VkPhysicalDeviceType type) { switch (type) { #define STR(r) case VK_PHYSICAL_DEVICE_TYPE_ ##r: return #r STR(OTHER); STR(INTEGRATED_GPU); STR(DISCRETE_GPU); STR(VIRTUAL_GPU); #undef STR default: return "UNKNOWN_DEVICE_TYPE"; } } VkBool32 getSupportedDepthFormat(VkPhysicalDevice physicalDevice, VkFormat *depthFormat) { // Since all depth formats may be optional, we need to find a suitable depth format to use // Start with the highest precision packed format std::vector<VkFormat> depthFormats = { VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D32_SFLOAT, VK_FORMAT_D24_UNORM_S8_UINT, VK_FORMAT_D16_UNORM_S8_UINT, VK_FORMAT_D16_UNORM }; for (auto& format : depthFormats) { VkFormatProperties formatProps; vkGetPhysicalDeviceFormatProperties(physicalDevice, format, &formatProps); // Format must support depth stencil attachment for optimal tiling if (formatProps.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) { *depthFormat = format; return true; } } return false; } // Create an image memory barrier for changing the layout of // an image and put it into an active command buffer // See chapter 11.4 "Image Layout" for details void setImageLayout( VkCommandBuffer cmdbuffer, VkImage image, VkImageAspectFlags aspectMask, VkImageLayout oldImageLayout, VkImageLayout newImageLayout, VkImageSubresourceRange subresourceRange, VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask) { // Create an image barrier object VkImageMemoryBarrier imageMemoryBarrier = vks::initializers::imageMemoryBarrier(); imageMemoryBarrier.oldLayout = oldImageLayout; imageMemoryBarrier.newLayout = newImageLayout; imageMemoryBarrier.image = image; imageMemoryBarrier.subresourceRange = subresourceRange; // Source layouts (old) // Source access mask controls actions that have to be finished on the old layout // before it will be transitioned to the new layout switch (oldImageLayout) { case VK_IMAGE_LAYOUT_UNDEFINED: // Image layout is undefined (or does not matter) // Only valid as initial layout // No flags required, listed only for completeness imageMemoryBarrier.srcAccessMask = 0; break; case VK_IMAGE_LAYOUT_PREINITIALIZED: // Image is preinitialized // Only valid as initial layout for linear images, preserves memory contents // Make sure host writes have been finished imageMemoryBarrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; break; case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL: // Image is a color attachment // Make sure any writes to the color buffer have been finished imageMemoryBarrier.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; break; case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL: // Image is a depth/stencil attachment // Make sure any writes to the depth/stencil buffer have been finished imageMemoryBarrier.srcAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; break; case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL: // Image is a transfer source // Make sure any reads from the image have been finished imageMemoryBarrier.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT; break; case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL: // Image is a transfer destination // Make sure any writes to the image have been finished imageMemoryBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; break; case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL: // Image is read by a shader // Make sure any shader reads from the image have been finished imageMemoryBarrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT; break; default: // Other source layouts aren't handled (yet) break; } // Target layouts (new) // Destination access mask controls the dependency for the new image layout switch (newImageLayout) { case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL: // Image will be used as a transfer destination // Make sure any writes to the image have been finished imageMemoryBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; break; case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL: // Image will be used as a transfer source // Make sure any reads from the image have been finished imageMemoryBarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; break; case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL: // Image will be used as a color attachment // Make sure any writes to the color buffer have been finished imageMemoryBarrier.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; break; case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL: // Image layout will be used as a depth/stencil attachment // Make sure any writes to depth/stencil buffer have been finished imageMemoryBarrier.dstAccessMask = imageMemoryBarrier.dstAccessMask | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT; break; case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL: // Image will be read in a shader (sampler, input attachment) // Make sure any writes to the image have been finished if (imageMemoryBarrier.srcAccessMask == 0) { imageMemoryBarrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT; } imageMemoryBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; break; default: // Other source layouts aren't handled (yet) break; } // Put barrier inside setup command buffer vkCmdPipelineBarrier( cmdbuffer, srcStageMask, dstStageMask, 0, 0, nullptr, 0, nullptr, 1, &imageMemoryBarrier); } // Fixed sub resource on first mip level and layer void setImageLayout( VkCommandBuffer cmdbuffer, VkImage image, VkImageAspectFlags aspectMask, VkImageLayout oldImageLayout, VkImageLayout newImageLayout, VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask) { VkImageSubresourceRange subresourceRange = {}; subresourceRange.aspectMask = aspectMask; subresourceRange.baseMipLevel = 0; subresourceRange.levelCount = 1; subresourceRange.layerCount = 1; setImageLayout(cmdbuffer, image, aspectMask, oldImageLayout, newImageLayout, subresourceRange); } void insertImageMemoryBarrier( VkCommandBuffer cmdbuffer, VkImage image, VkAccessFlags srcAccessMask, VkAccessFlags dstAccessMask, VkImageLayout oldImageLayout, VkImageLayout newImageLayout, VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask, VkImageSubresourceRange subresourceRange) { VkImageMemoryBarrier imageMemoryBarrier = vks::initializers::imageMemoryBarrier(); imageMemoryBarrier.srcAccessMask = srcAccessMask; imageMemoryBarrier.dstAccessMask = dstAccessMask; imageMemoryBarrier.oldLayout = oldImageLayout; imageMemoryBarrier.newLayout = newImageLayout; imageMemoryBarrier.image = image; imageMemoryBarrier.subresourceRange = subresourceRange; vkCmdPipelineBarrier( cmdbuffer, srcStageMask, dstStageMask, 0, 0, nullptr, 0, nullptr, 1, &imageMemoryBarrier); } void exitFatal(std::string message, std::string caption) { #if defined(_WIN32) MessageBox(NULL, message.c_str(), caption.c_str(), MB_OK | MB_ICONERROR); #elif defined(__ANDROID__) LOGE("Fatal error: %s", message.c_str()); #else std::cerr << message << "\n"; #endif exit(1); } std::string readTextFile(const char *fileName) { std::string fileContent; std::ifstream fileStream(fileName, std::ios::in); if (!fileStream.is_open()) { printf("File %s not found\n", fileName); return ""; } std::string line = ""; while (!fileStream.eof()) { getline(fileStream, line); fileContent.append(line + "\n"); } fileStream.close(); return fileContent; } #if defined(__ANDROID__) // Android shaders are stored as assets in the apk // So they need to be loaded via the asset manager VkShaderModule loadShader(AAssetManager* assetManager, const char *fileName, VkDevice device, VkShaderStageFlagBits stage) { // Load shader from compressed asset AAsset* asset = AAssetManager_open(assetManager, fileName, AASSET_MODE_STREAMING); assert(asset); size_t size = AAsset_getLength(asset); assert(size > 0); char *shaderCode = new char[size]; AAsset_read(asset, shaderCode, size); AAsset_close(asset); VkShaderModule shaderModule; VkShaderModuleCreateInfo moduleCreateInfo; moduleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; moduleCreateInfo.pNext = NULL; moduleCreateInfo.codeSize = size; moduleCreateInfo.pCode = (uint32_t*)shaderCode; moduleCreateInfo.flags = 0; VK_CHECK_RESULT(vkCreateShaderModule(device, &moduleCreateInfo, NULL, &shaderModule)); delete[] shaderCode; return shaderModule; } #else VkShaderModule loadShader(const char *fileName, VkDevice device, VkShaderStageFlagBits stage) { std::ifstream is(fileName, std::ios::binary | std::ios::in | std::ios::ate); if (is.is_open()) { size_t size = is.tellg(); is.seekg(0, std::ios::beg); char* shaderCode = new char[size]; is.read(shaderCode, size); is.close(); assert(size > 0); VkShaderModule shaderModule; VkShaderModuleCreateInfo moduleCreateInfo{}; moduleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; moduleCreateInfo.codeSize = size; moduleCreateInfo.pCode = (uint32_t*)shaderCode; VK_CHECK_RESULT(vkCreateShaderModule(device, &moduleCreateInfo, NULL, &shaderModule)); delete[] shaderCode; return shaderModule; } else { std::cerr << "Error: Could not open shader file \"" << fileName << "\"" << std::endl; return VK_NULL_HANDLE; } } #endif VkShaderModule loadShaderGLSL(const char *fileName, VkDevice device, VkShaderStageFlagBits stage) { std::string shaderSrc = readTextFile(fileName); const char *shaderCode = shaderSrc.c_str(); size_t size = strlen(shaderCode); assert(size > 0); VkShaderModule shaderModule; VkShaderModuleCreateInfo moduleCreateInfo; moduleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; moduleCreateInfo.pNext = NULL; moduleCreateInfo.codeSize = 3 * sizeof(uint32_t) + size + 1; moduleCreateInfo.pCode = (uint32_t*)malloc(moduleCreateInfo.codeSize); moduleCreateInfo.flags = 0; // Magic SPV number ((uint32_t *)moduleCreateInfo.pCode)[0] = 0x07230203; ((uint32_t *)moduleCreateInfo.pCode)[1] = 0; ((uint32_t *)moduleCreateInfo.pCode)[2] = stage; memcpy(((uint32_t *)moduleCreateInfo.pCode + 3), shaderCode, size + 1); VK_CHECK_RESULT(vkCreateShaderModule(device, &moduleCreateInfo, NULL, &shaderModule)); return shaderModule; } bool fileExists(const std::string &filename) { std::ifstream f(filename.c_str()); return !f.fail(); } } }<|endoftext|>
<commit_before> // g++-4.4 bench_gemm.cpp -I .. -O2 -DNDEBUG -lrt -fopenmp && OMP_NUM_THREADS=2 ./a.out // icpc bench_gemm.cpp -I .. -O3 -DNDEBUG -lrt -openmp && OMP_NUM_THREADS=2 ./a.out #include <iostream> #include <Eigen/Core> #include <bench/BenchTimer.h> using namespace std; using namespace Eigen; #ifndef SCALAR // #define SCALAR std::complex<float> #define SCALAR float #endif typedef SCALAR Scalar; typedef NumTraits<Scalar>::Real RealScalar; typedef Matrix<RealScalar,Dynamic,Dynamic> A; typedef Matrix</*Real*/Scalar,Dynamic,Dynamic> B; typedef Matrix<Scalar,Dynamic,Dynamic> C; typedef Matrix<RealScalar,Dynamic,Dynamic> M; #ifdef HAVE_BLAS extern "C" { #include <bench/btl/libs/C_BLAS/blas.h> } static float fone = 1; static float fzero = 0; static double done = 1; static double szero = 0; static std::complex<float> cfone = 1; static std::complex<float> cfzero = 0; static std::complex<double> cdone = 1; static std::complex<double> cdzero = 0; static char notrans = 'N'; static char trans = 'T'; static char nonunit = 'N'; static char lower = 'L'; static char right = 'R'; static int intone = 1; void blas_gemm(const MatrixXf& a, const MatrixXf& b, MatrixXf& c) { int M = c.rows(); int N = c.cols(); int K = a.cols(); int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows(); sgemm_(&notrans,&notrans,&M,&N,&K,&fone, const_cast<float*>(a.data()),&lda, const_cast<float*>(b.data()),&ldb,&fone, c.data(),&ldc); } EIGEN_DONT_INLINE void blas_gemm(const MatrixXd& a, const MatrixXd& b, MatrixXd& c) { int M = c.rows(); int N = c.cols(); int K = a.cols(); int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows(); dgemm_(&notrans,&notrans,&M,&N,&K,&done, const_cast<double*>(a.data()),&lda, const_cast<double*>(b.data()),&ldb,&done, c.data(),&ldc); } void blas_gemm(const MatrixXcf& a, const MatrixXcf& b, MatrixXcf& c) { int M = c.rows(); int N = c.cols(); int K = a.cols(); int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows(); cgemm_(&notrans,&notrans,&M,&N,&K,(float*)&cfone, const_cast<float*>((const float*)a.data()),&lda, const_cast<float*>((const float*)b.data()),&ldb,(float*)&cfone, (float*)c.data(),&ldc); } void blas_gemm(const MatrixXcd& a, const MatrixXcd& b, MatrixXcd& c) { int M = c.rows(); int N = c.cols(); int K = a.cols(); int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows(); zgemm_(&notrans,&notrans,&M,&N,&K,(double*)&cdone, const_cast<double*>((const double*)a.data()),&lda, const_cast<double*>((const double*)b.data()),&ldb,(double*)&cdone, (double*)c.data(),&ldc); } #endif void matlab_cplx_cplx(const M& ar, const M& ai, const M& br, const M& bi, M& cr, M& ci) { cr.noalias() += ar * br; cr.noalias() -= ai * bi; ci.noalias() += ar * bi; ci.noalias() += ai * br; } void matlab_real_cplx(const M& a, const M& br, const M& bi, M& cr, M& ci) { cr.noalias() += a * br; ci.noalias() += a * bi; } void matlab_cplx_real(const M& ar, const M& ai, const M& b, M& cr, M& ci) { cr.noalias() += ar * b; ci.noalias() += ai * b; } template<typename A, typename B, typename C> EIGEN_DONT_INLINE void gemm(const A& a, const B& b, C& c) { c.noalias() += a * b; } int main(int argc, char ** argv) { std::ptrdiff_t l1 = internal::queryL1CacheSize(); std::ptrdiff_t l2 = internal::queryTopLevelCacheSize(); std::cout << "L1 cache size = " << (l1>0 ? l1/1024 : -1) << " KB\n"; std::cout << "L2/L3 cache size = " << (l2>0 ? l2/1024 : -1) << " KB\n"; typedef internal::gebp_traits<Scalar,Scalar> Traits; std::cout << "Register blocking = " << Traits::mr << " x " << Traits::nr << "\n"; int rep = 1; // number of repetitions per try int tries = 2; // number of tries, we keep the best int s = 2048; int cache_size = -1; bool need_help = false; for (int i=1; i<argc; ++i) { if(argv[i][0]=='s') s = atoi(argv[i]+1); else if(argv[i][0]=='c') cache_size = atoi(argv[i]+1); else if(argv[i][0]=='t') tries = atoi(argv[i]+1); else if(argv[i][0]=='p') rep = atoi(argv[i]+1); else need_help = true; } if(need_help) { std::cout << argv[0] << " s<matrix size> c<cache size> t<nb tries> p<nb repeats>\n"; return 1; } if(cache_size>0) setCpuCacheSizes(cache_size,96*cache_size); int m = s; int n = s; int p = s; A a(m,p); a.setRandom(); B b(p,n); b.setRandom(); C c(m,n); c.setOnes(); std::cout << "Matrix sizes = " << m << "x" << p << " * " << p << "x" << n << "\n"; std::ptrdiff_t mc(m), nc(n), kc(p); computeProductBlockingSizes<Scalar,Scalar>(kc, mc, nc); std::cout << "blocking size (mc x kc) = " << mc << " x " << kc << "\n"; C r = c; // check the parallel product is correct #if defined EIGEN_HAS_OPENMP int procs = omp_get_max_threads(); if(procs>1) { #ifdef HAVE_BLAS blas_gemm(a,b,r); #else omp_set_num_threads(1); r.noalias() += a * b; omp_set_num_threads(procs); #endif c.noalias() += a * b; if(!r.isApprox(c)) std::cerr << "Warning, your parallel product is crap!\n\n"; } #elif defined HAVE_BLAS blas_gemm(a,b,r); c.noalias() += a * b; if(!r.isApprox(c)) std::cerr << "Warning, your product is crap!\n\n"; // std::cerr << r << "\n\n" << c << "\n\n"; #else gemm(a,b,c); r.noalias() += a.cast<Scalar>() * b.cast<Scalar>(); if(!r.isApprox(c)) std::cerr << "Warning, your product is crap!\n\n"; // std::cerr << c << "\n\n"; // std::cerr << r << "\n\n"; #endif #ifdef HAVE_BLAS BenchTimer tblas; BENCH(tblas, tries, rep, blas_gemm(a,b,c)); std::cout << "blas cpu " << tblas.best(CPU_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tblas.best(CPU_TIMER))*1e-9 << " GFLOPS \t(" << tblas.total(CPU_TIMER) << "s)\n"; std::cout << "blas real " << tblas.best(REAL_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tblas.best(REAL_TIMER))*1e-9 << " GFLOPS \t(" << tblas.total(REAL_TIMER) << "s)\n"; #endif BenchTimer tmt; BENCH(tmt, tries, rep, gemm(a,b,c)); std::cout << "eigen cpu " << tmt.best(CPU_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tmt.best(CPU_TIMER))*1e-9 << " GFLOPS \t(" << tmt.total(CPU_TIMER) << "s)\n"; std::cout << "eigen real " << tmt.best(REAL_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tmt.best(REAL_TIMER))*1e-9 << " GFLOPS \t(" << tmt.total(REAL_TIMER) << "s)\n"; #ifdef EIGEN_HAS_OPENMP if(procs>1) { BenchTimer tmono; //omp_set_num_threads(1); Eigen::setNbThreads(1); BENCH(tmono, tries, rep, gemm(a,b,c)); std::cout << "eigen mono cpu " << tmono.best(CPU_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tmono.best(CPU_TIMER))*1e-9 << " GFLOPS \t(" << tmono.total(CPU_TIMER) << "s)\n"; std::cout << "eigen mono real " << tmono.best(REAL_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tmono.best(REAL_TIMER))*1e-9 << " GFLOPS \t(" << tmono.total(REAL_TIMER) << "s)\n"; std::cout << "mt speed up x" << tmono.best(CPU_TIMER) / tmt.best(REAL_TIMER) << " => " << (100.0*tmono.best(CPU_TIMER) / tmt.best(REAL_TIMER))/procs << "%\n"; } #endif #ifdef DECOUPLED if((NumTraits<A::Scalar>::IsComplex) && (NumTraits<B::Scalar>::IsComplex)) { M ar(m,p); ar.setRandom(); M ai(m,p); ai.setRandom(); M br(p,n); br.setRandom(); M bi(p,n); bi.setRandom(); M cr(m,n); cr.setRandom(); M ci(m,n); ci.setRandom(); BenchTimer t; BENCH(t, tries, rep, matlab_cplx_cplx(ar,ai,br,bi,cr,ci)); std::cout << "\"matlab\" cpu " << t.best(CPU_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/t.best(CPU_TIMER))*1e-9 << " GFLOPS \t(" << t.total(CPU_TIMER) << "s)\n"; std::cout << "\"matlab\" real " << t.best(REAL_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/t.best(REAL_TIMER))*1e-9 << " GFLOPS \t(" << t.total(REAL_TIMER) << "s)\n"; } if((!NumTraits<A::Scalar>::IsComplex) && (NumTraits<B::Scalar>::IsComplex)) { M a(m,p); a.setRandom(); M br(p,n); br.setRandom(); M bi(p,n); bi.setRandom(); M cr(m,n); cr.setRandom(); M ci(m,n); ci.setRandom(); BenchTimer t; BENCH(t, tries, rep, matlab_real_cplx(a,br,bi,cr,ci)); std::cout << "\"matlab\" cpu " << t.best(CPU_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/t.best(CPU_TIMER))*1e-9 << " GFLOPS \t(" << t.total(CPU_TIMER) << "s)\n"; std::cout << "\"matlab\" real " << t.best(REAL_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/t.best(REAL_TIMER))*1e-9 << " GFLOPS \t(" << t.total(REAL_TIMER) << "s)\n"; } if((NumTraits<A::Scalar>::IsComplex) && (!NumTraits<B::Scalar>::IsComplex)) { M ar(m,p); ar.setRandom(); M ai(m,p); ai.setRandom(); M b(p,n); b.setRandom(); M cr(m,n); cr.setRandom(); M ci(m,n); ci.setRandom(); BenchTimer t; BENCH(t, tries, rep, matlab_cplx_real(ar,ai,b,cr,ci)); std::cout << "\"matlab\" cpu " << t.best(CPU_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/t.best(CPU_TIMER))*1e-9 << " GFLOPS \t(" << t.total(CPU_TIMER) << "s)\n"; std::cout << "\"matlab\" real " << t.best(REAL_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/t.best(REAL_TIMER))*1e-9 << " GFLOPS \t(" << t.total(REAL_TIMER) << "s)\n"; } #endif return 0; } <commit_msg>fix bench_gemm<commit_after> // g++-4.4 bench_gemm.cpp -I .. -O2 -DNDEBUG -lrt -fopenmp && OMP_NUM_THREADS=2 ./a.out // icpc bench_gemm.cpp -I .. -O3 -DNDEBUG -lrt -openmp && OMP_NUM_THREADS=2 ./a.out #include <iostream> #include <Eigen/Core> #include <bench/BenchTimer.h> using namespace std; using namespace Eigen; #ifndef SCALAR // #define SCALAR std::complex<float> #define SCALAR float #endif typedef SCALAR Scalar; typedef NumTraits<Scalar>::Real RealScalar; typedef Matrix<RealScalar,Dynamic,Dynamic> A; typedef Matrix</*Real*/Scalar,Dynamic,Dynamic> B; typedef Matrix<Scalar,Dynamic,Dynamic> C; typedef Matrix<RealScalar,Dynamic,Dynamic> M; #ifdef HAVE_BLAS extern "C" { #include <bench/btl/libs/C_BLAS/blas.h> } static float fone = 1; static float fzero = 0; static double done = 1; static double szero = 0; static std::complex<float> cfone = 1; static std::complex<float> cfzero = 0; static std::complex<double> cdone = 1; static std::complex<double> cdzero = 0; static char notrans = 'N'; static char trans = 'T'; static char nonunit = 'N'; static char lower = 'L'; static char right = 'R'; static int intone = 1; void blas_gemm(const MatrixXf& a, const MatrixXf& b, MatrixXf& c) { int M = c.rows(); int N = c.cols(); int K = a.cols(); int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows(); sgemm_(&notrans,&notrans,&M,&N,&K,&fone, const_cast<float*>(a.data()),&lda, const_cast<float*>(b.data()),&ldb,&fone, c.data(),&ldc); } EIGEN_DONT_INLINE void blas_gemm(const MatrixXd& a, const MatrixXd& b, MatrixXd& c) { int M = c.rows(); int N = c.cols(); int K = a.cols(); int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows(); dgemm_(&notrans,&notrans,&M,&N,&K,&done, const_cast<double*>(a.data()),&lda, const_cast<double*>(b.data()),&ldb,&done, c.data(),&ldc); } void blas_gemm(const MatrixXcf& a, const MatrixXcf& b, MatrixXcf& c) { int M = c.rows(); int N = c.cols(); int K = a.cols(); int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows(); cgemm_(&notrans,&notrans,&M,&N,&K,(float*)&cfone, const_cast<float*>((const float*)a.data()),&lda, const_cast<float*>((const float*)b.data()),&ldb,(float*)&cfone, (float*)c.data(),&ldc); } void blas_gemm(const MatrixXcd& a, const MatrixXcd& b, MatrixXcd& c) { int M = c.rows(); int N = c.cols(); int K = a.cols(); int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows(); zgemm_(&notrans,&notrans,&M,&N,&K,(double*)&cdone, const_cast<double*>((const double*)a.data()),&lda, const_cast<double*>((const double*)b.data()),&ldb,(double*)&cdone, (double*)c.data(),&ldc); } #endif void matlab_cplx_cplx(const M& ar, const M& ai, const M& br, const M& bi, M& cr, M& ci) { cr.noalias() += ar * br; cr.noalias() -= ai * bi; ci.noalias() += ar * bi; ci.noalias() += ai * br; } void matlab_real_cplx(const M& a, const M& br, const M& bi, M& cr, M& ci) { cr.noalias() += a * br; ci.noalias() += a * bi; } void matlab_cplx_real(const M& ar, const M& ai, const M& b, M& cr, M& ci) { cr.noalias() += ar * b; ci.noalias() += ai * b; } template<typename A, typename B, typename C> EIGEN_DONT_INLINE void gemm(const A& a, const B& b, C& c) { c.noalias() += a * b; } int main(int argc, char ** argv) { std::ptrdiff_t l1 = internal::queryL1CacheSize(); std::ptrdiff_t l2 = internal::queryTopLevelCacheSize(); std::cout << "L1 cache size = " << (l1>0 ? l1/1024 : -1) << " KB\n"; std::cout << "L2/L3 cache size = " << (l2>0 ? l2/1024 : -1) << " KB\n"; typedef internal::gebp_traits<Scalar,Scalar> Traits; std::cout << "Register blocking = " << Traits::mr << " x " << Traits::nr << "\n"; int rep = 1; // number of repetitions per try int tries = 2; // number of tries, we keep the best int s = 2048; int cache_size = -1; bool need_help = false; for (int i=1; i<argc; ++i) { if(argv[i][0]=='s') s = atoi(argv[i]+1); else if(argv[i][0]=='c') cache_size = atoi(argv[i]+1); else if(argv[i][0]=='t') tries = atoi(argv[i]+1); else if(argv[i][0]=='p') rep = atoi(argv[i]+1); else need_help = true; } if(need_help) { std::cout << argv[0] << " s<matrix size> c<cache size> t<nb tries> p<nb repeats>\n"; return 1; } if(cache_size>0) setCpuCacheSizes(cache_size,96*cache_size); int m = s; int n = s; int p = s; A a(m,p); a.setRandom(); B b(p,n); b.setRandom(); C c(m,n); c.setOnes(); C rc = c; std::cout << "Matrix sizes = " << m << "x" << p << " * " << p << "x" << n << "\n"; std::ptrdiff_t mc(m), nc(n), kc(p); internal::computeProductBlockingSizes<Scalar,Scalar>(kc, mc, nc); std::cout << "blocking size (mc x kc) = " << mc << " x " << kc << "\n"; C r = c; // check the parallel product is correct #if defined EIGEN_HAS_OPENMP int procs = omp_get_max_threads(); if(procs>1) { #ifdef HAVE_BLAS blas_gemm(a,b,r); #else omp_set_num_threads(1); r.noalias() += a * b; omp_set_num_threads(procs); #endif c.noalias() += a * b; if(!r.isApprox(c)) std::cerr << "Warning, your parallel product is crap!\n\n"; } #elif defined HAVE_BLAS blas_gemm(a,b,r); c.noalias() += a * b; if(!r.isApprox(c)) std::cerr << "Warning, your product is crap!\n\n"; #else gemm(a,b,c); r.noalias() += a.cast<Scalar>() * b.cast<Scalar>(); if(!r.isApprox(c)) std::cerr << "Warning, your product is crap!\n\n"; #endif #ifdef HAVE_BLAS BenchTimer tblas; c = rc; BENCH(tblas, tries, rep, blas_gemm(a,b,c)); std::cout << "blas cpu " << tblas.best(CPU_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tblas.best(CPU_TIMER))*1e-9 << " GFLOPS \t(" << tblas.total(CPU_TIMER) << "s)\n"; std::cout << "blas real " << tblas.best(REAL_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tblas.best(REAL_TIMER))*1e-9 << " GFLOPS \t(" << tblas.total(REAL_TIMER) << "s)\n"; #endif BenchTimer tmt; c = rc; BENCH(tmt, tries, rep, gemm(a,b,c)); std::cout << "eigen cpu " << tmt.best(CPU_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tmt.best(CPU_TIMER))*1e-9 << " GFLOPS \t(" << tmt.total(CPU_TIMER) << "s)\n"; std::cout << "eigen real " << tmt.best(REAL_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tmt.best(REAL_TIMER))*1e-9 << " GFLOPS \t(" << tmt.total(REAL_TIMER) << "s)\n"; #ifdef EIGEN_HAS_OPENMP if(procs>1) { BenchTimer tmono; omp_set_num_threads(1); Eigen::internal::setNbThreads(1); c = rc; BENCH(tmono, tries, rep, gemm(a,b,c)); std::cout << "eigen mono cpu " << tmono.best(CPU_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tmono.best(CPU_TIMER))*1e-9 << " GFLOPS \t(" << tmono.total(CPU_TIMER) << "s)\n"; std::cout << "eigen mono real " << tmono.best(REAL_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tmono.best(REAL_TIMER))*1e-9 << " GFLOPS \t(" << tmono.total(REAL_TIMER) << "s)\n"; std::cout << "mt speed up x" << tmono.best(CPU_TIMER) / tmt.best(REAL_TIMER) << " => " << (100.0*tmono.best(CPU_TIMER) / tmt.best(REAL_TIMER))/procs << "%\n"; } #endif #ifdef DECOUPLED if((NumTraits<A::Scalar>::IsComplex) && (NumTraits<B::Scalar>::IsComplex)) { M ar(m,p); ar.setRandom(); M ai(m,p); ai.setRandom(); M br(p,n); br.setRandom(); M bi(p,n); bi.setRandom(); M cr(m,n); cr.setRandom(); M ci(m,n); ci.setRandom(); BenchTimer t; BENCH(t, tries, rep, matlab_cplx_cplx(ar,ai,br,bi,cr,ci)); std::cout << "\"matlab\" cpu " << t.best(CPU_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/t.best(CPU_TIMER))*1e-9 << " GFLOPS \t(" << t.total(CPU_TIMER) << "s)\n"; std::cout << "\"matlab\" real " << t.best(REAL_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/t.best(REAL_TIMER))*1e-9 << " GFLOPS \t(" << t.total(REAL_TIMER) << "s)\n"; } if((!NumTraits<A::Scalar>::IsComplex) && (NumTraits<B::Scalar>::IsComplex)) { M a(m,p); a.setRandom(); M br(p,n); br.setRandom(); M bi(p,n); bi.setRandom(); M cr(m,n); cr.setRandom(); M ci(m,n); ci.setRandom(); BenchTimer t; BENCH(t, tries, rep, matlab_real_cplx(a,br,bi,cr,ci)); std::cout << "\"matlab\" cpu " << t.best(CPU_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/t.best(CPU_TIMER))*1e-9 << " GFLOPS \t(" << t.total(CPU_TIMER) << "s)\n"; std::cout << "\"matlab\" real " << t.best(REAL_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/t.best(REAL_TIMER))*1e-9 << " GFLOPS \t(" << t.total(REAL_TIMER) << "s)\n"; } if((NumTraits<A::Scalar>::IsComplex) && (!NumTraits<B::Scalar>::IsComplex)) { M ar(m,p); ar.setRandom(); M ai(m,p); ai.setRandom(); M b(p,n); b.setRandom(); M cr(m,n); cr.setRandom(); M ci(m,n); ci.setRandom(); BenchTimer t; BENCH(t, tries, rep, matlab_cplx_real(ar,ai,b,cr,ci)); std::cout << "\"matlab\" cpu " << t.best(CPU_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/t.best(CPU_TIMER))*1e-9 << " GFLOPS \t(" << t.total(CPU_TIMER) << "s)\n"; std::cout << "\"matlab\" real " << t.best(REAL_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/t.best(REAL_TIMER))*1e-9 << " GFLOPS \t(" << t.total(REAL_TIMER) << "s)\n"; } #endif return 0; } <|endoftext|>
<commit_before>#pragma once #include <cstdio> // declaration of ::fileno #include <fstream> // for basic_filebuf template #include <cerrno> #if defined(__GLIBCXX__) || (defined(__GLIBCPP__) && __GLIBCPP__>=20020514) // GCC >= 3.1.0 # include <ext/stdio_filebuf.h> #endif #if defined(__GLIBCXX__) // GCC >= 3.4.0 # include <ext/stdio_sync_filebuf.h> #endif #if defined(_LIBCPP_VERSION) // Generate a static data member of type Tag::type in which to store // the address of a private member. It is crucial that Tag does not // depend on the /value/ of the the stored address in any way so that // we can access it from ordinary code without directly touching // private data. template < class Tag > struct stowed { static typename Tag::type value; }; template < class Tag > typename Tag::type stowed< Tag >::value; // Generate a static data member whose constructor initializes // stowed< Tag >::value. This type will only be named in an explicit // instantiation, where it is legal to pass the address of a private // member. template < class Tag, typename Tag::type x > struct stow_private { stow_private() { stowed< Tag >::value = x; } static stow_private instance; }; template < class Tag, typename Tag::type x > stow_private< Tag, x > stow_private< Tag, x >::instance; struct filebuf_file { typedef FILE*( std::filebuf::*type ); }; template struct stow_private< filebuf_file, &std::filebuf::__file_ >; #endif //! Similar to fileno(3), but taking a C++ stream as argument instead of a //! FILE*. Note that there is no way for the library to track what you do with //! the descriptor, so be careful. //! \return The integer file descriptor associated with the stream, or -1 if //! that stream is invalid. In the latter case, for the sake of keeping the //! code as similar to fileno(3), errno is set to EBADF. //! \see The <A HREF="http://www.ginac.de/~kreckel/fileno/">upstream page at //! http://www.ginac.de/~kreckel/fileno/</A> of this code provides more //! detailed information. template <typename charT, typename traits> inline int fileno_hack(const std::basic_ios<charT, traits>& stream) { // Some C++ runtime libraries shipped with ancient GCC, Sun Pro, // Sun WS/Forte 5/6, Compaq C++ supported non-standard file descriptor // access basic_filebuf<>::fd(). Alas, starting from GCC 3.1, the GNU C++ // runtime removes all non-standard std::filebuf methods and provides an // extension template class __gnu_cxx::stdio_filebuf on all systems where // that appears to make sense (i.e. at least all Unix systems). Starting // from GCC 3.4, there is an __gnu_cxx::stdio_sync_filebuf, in addition. // Sorry, darling, I must get brutal to fetch the darn file descriptor! // Please complain to your compiler/libstdc++ vendor... #if defined(__GLIBCXX__) || defined(__GLIBCPP__) // OK, stop reading here, because it's getting obscene. Cross fingers! # if defined(__GLIBCXX__) // >= GCC 3.4.0 // This applies to cin, cout and cerr when not synced with stdio: typedef __gnu_cxx::stdio_filebuf<charT, traits> unix_filebuf_t; unix_filebuf_t* fbuf = dynamic_cast<unix_filebuf_t*>(stream.rdbuf()); if (fbuf != NULL) { return fbuf->fd(); } // This applies to filestreams: typedef std::basic_filebuf<charT, traits> filebuf_t; filebuf_t* bbuf = dynamic_cast<filebuf_t*>(stream.rdbuf()); if (bbuf != NULL) { // This subclass is only there for accessing the FILE*. Ouuwww, sucks! struct my_filebuf : public std::basic_filebuf<charT, traits> { // Note: _M_file is of type __basic_file<char> which has a // FILE* as its first (but private) member variable. FILE* c_file() { return *(FILE**)(&this->_M_file); } }; FILE* c_file = static_cast<my_filebuf*>(bbuf)->c_file(); if (c_file != NULL) { // Could be NULL for failed ifstreams. return ::fileno(c_file); } } // This applies to cin, cout and cerr when synced with stdio: typedef __gnu_cxx::stdio_sync_filebuf<charT, traits> sync_filebuf_t; sync_filebuf_t* sbuf = dynamic_cast<sync_filebuf_t*>(stream.rdbuf()); if (sbuf != NULL) { # if (__GLIBCXX__<20040906) // GCC < 3.4.2 // This subclass is only there for accessing the FILE*. // See GCC PR#14600 and PR#16411. struct my_filebuf : public sync_filebuf_t { my_filebuf(); // Dummy ctor keeps the compiler happy. // Note: stdio_sync_filebuf has a FILE* as its first (but private) // member variable. However, it is derived from basic_streambuf<> // and the FILE* is the first non-inherited member variable. FILE* c_file() { return *(FILE**)((char*)this + sizeof(std::basic_streambuf<charT, traits>)); } }; return ::fileno(static_cast<my_filebuf*>(sbuf)->c_file()); # else return ::fileno(sbuf->file()); # endif } # else // GCC < 3.4.0 used __GLIBCPP__ # if (__GLIBCPP__>=20020514) // GCC >= 3.1.0 // This applies to cin, cout and cerr: typedef __gnu_cxx::stdio_filebuf<charT, traits> unix_filebuf_t; unix_filebuf_t* buf = dynamic_cast<unix_filebuf_t*>(stream.rdbuf()); if (buf != NULL) { return buf->fd(); } // This applies to filestreams: typedef std::basic_filebuf<charT, traits> filebuf_t; filebuf_t* bbuf = dynamic_cast<filebuf_t*>(stream.rdbuf()); if (bbuf != NULL) { // This subclass is only there for accessing the FILE*. Ouuwww, sucks! struct my_filebuf : public std::basic_filebuf<charT, traits> { // Note: _M_file is of type __basic_file<char> which has a // FILE* as its first (but private) member variable. FILE* c_file() { return *(FILE**)(&this->_M_file); } }; FILE* c_file = static_cast<my_filebuf*>(bbuf)->c_file(); if (c_file != NULL) { // Could be NULL for failed ifstreams. return ::fileno(c_file); } } # else // GCC 3.0.x typedef std::basic_filebuf<charT, traits> filebuf_t; filebuf_t* fbuf = dynamic_cast<filebuf_t*>(stream.rdbuf()); if (fbuf != NULL) { struct my_filebuf : public filebuf_t { // Note: basic_filebuf<charT, traits> has a __basic_file<charT>* as // its first (but private) member variable. Since it is derived // from basic_streambuf<charT, traits> we can guess its offset. // __basic_file<charT> in turn has a FILE* as its first (but // private) member variable. Get it by brute force. Oh, geez! FILE* c_file() { std::__basic_file<charT>* ptr_M_file = *(std::__basic_file<charT>**)((char*)this + sizeof(std::basic_streambuf<charT, traits>)); # if _GLIBCPP_BASIC_FILE_INHERITANCE // __basic_file<charT> inherits from __basic_file_base<charT> return *(FILE**)((char*)ptr_M_file + sizeof(std::__basic_file_base<charT>)); # else // __basic_file<charT> is base class, but with vptr. return *(FILE**)((char*)ptr_M_file + sizeof(void*)); # endif } }; return ::fileno(static_cast<my_filebuf*>(fbuf)->c_file()); } # endif # endif #elif defined(_LIBCPP_VERSION) return ::fileno(stream.rdbuf()->*stowed< filebuf_file >::value); #else # error "Does anybody know how to fetch the bloody file descriptor?" return stream.rdbuf()->fd(); // Maybe a good start? #endif #if !defined(_LIBCPP_VERSION) errno = EBADF; #endif return -1; } #if defined(_LIBCPP_VERSION) //! 8-Bit character instantiation: fileno(ios). template <> int fileno_hack<char>(const std::ios& stream) { return fileno_hack(stream); } //! Wide character instantiation: fileno(wios). template <> int fileno_hack<wchar_t>(const std::wios& stream) { return fileno_hack(stream); } #endif <commit_msg>Remove unused file fileno.hpp.<commit_after><|endoftext|>
<commit_before>#ifndef SOLAIRE_CONTAINER_HPP #define SOLAIRE_CONTAINER_HPP //Copyright 2015 Adam Smith // //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. // Contact : // Email : [email protected] // GitHub repository : https://github.com/SolaireLibrary/SolaireCPP /*! \file Container.hpp \brief \author Created : Adam Smith Last modified : Adam Smith \date Created : 3rd December 2015 Last Modified : 10th January 2016 */ #include "Solaire/Core/Iterator.hpp" #include "Solaire/Core/Allocator.hpp" namespace Solaire { template<class T> SOLAIRE_EXPORT_INTERFACE StaticContainer { public: typedef T Type; typedef T* Pointer; typedef T& Reference; typedef const T* ConstPointer; typedef const T& ConstReference; protected: virtual Pointer SOLAIRE_EXPORT_CALL getPtr(int32_t) throw() = 0; virtual SharedAllocation<Iterator<T>> SOLAIRE_EXPORT_CALL begin_() throw() = 0; virtual SharedAllocation<Iterator<T>> SOLAIRE_EXPORT_CALL end_() throw() = 0; virtual SharedAllocation<Iterator<T>> SOLAIRE_EXPORT_CALL rbegin_() throw() = 0; virtual SharedAllocation<Iterator<T>> SOLAIRE_EXPORT_CALL rend_() throw() = 0; public: virtual SOLAIRE_EXPORT_CALL ~StaticContainer() throw() {} virtual bool SOLAIRE_EXPORT_CALL isContiguous() const throw() = 0; virtual int32_t SOLAIRE_EXPORT_CALL size() const throw() = 0; virtual Allocator& SOLAIRE_EXPORT_CALL getAllocator() const throw() = 0; SOLAIRE_FORCE_INLINE Reference operator[](const int32_t aIndex) throw() { return *getPtr(aIndex); } SOLAIRE_FORCE_INLINE ConstReference operator[](const int32_t aIndex) const throw() { return *const_cast<StaticContainer<T>*>(this)->getPtr(aIndex); } SOLAIRE_FORCE_INLINE STLIterator<T> begin() throw() { return STLIterator<T>(begin_()); } SOLAIRE_FORCE_INLINE STLIterator<T> end() throw() { return STLIterator<T>(end_()); } SOLAIRE_FORCE_INLINE STLIterator<const T> begin() const throw() { return STLIterator<T>(const_cast<StaticContainer<T>*>(this)->begin_()); } SOLAIRE_FORCE_INLINE STLIterator<const T> end() const throw() { return STLIterator<T>(const_cast<StaticContainer<T>*>(this)->end_()); } SOLAIRE_FORCE_INLINE STLIterator<T> rbegin() throw() { return STLIterator<T>(rbegin_()); } SOLAIRE_FORCE_INLINE STLIterator<T> rend() throw() { return STLIterator<T>(rend_()); } SOLAIRE_FORCE_INLINE STLIterator<const T> rbegin() const throw() { return STLIterator<T>(const_cast<StaticContainer<T>*>(this)->rbegin_()); } SOLAIRE_FORCE_INLINE STLIterator<const T> rend() const throw() { return STLIterator<T>(const_cast<StaticContainer<T>*>(this)->rend_()); } SOLAIRE_FORCE_INLINE operator StaticContainer<const T>&() throw() { return *reinterpret_cast<StaticContainer<const T>*>(this); } SOLAIRE_FORCE_INLINE operator const StaticContainer<const T>&() const throw() { return *reinterpret_cast<StaticContainer<const T>*>(this); } inline bool operator==(const StaticContainer<const T>& aOther) const throw() { const int32_t length = size(); if(length != aOther.size()) return false; if(std::is_fundamental<T>::value && isContiguous() && aOther.isContiguous()) { return std::memcmp(getPtr(0), aOther.getPtr(0), sizeof(T) * length) == 0; }else { for(int32_t i = 0; i < length; ++i) { if(getPtr(i) != aOther.getPtr(i)) return false; } return true; } } inline bool operator!=(const StaticContainer<const T>& aOther) const throw() { const int32_t length = size(); if(length != aOther.size()) return true; if(std::is_fundamental<T>::value && isContiguous() && aOther.isContiguous()) { return std::memcmp(getPtr(0), aOther.getPtr(0), sizeof(T) * length) != 0; }else { for(int32_t i = 0; i < length; ++i) { if(getPtr(i) != aOther.getPtr(i)) return true; } return false; } } SOLAIRE_FORCE_INLINE int32_t FindFirstOf(const T& aValue) const throw() { return FindNextOf(0, aValue); } inline int32_t FindNextOf(const int32_t aIndex, const T& aValue) const throw() { const int32_t length = size(); if(isContiguous()) { const T* const ptr = getPtr(0); for(int32_t i = aIndex; i < length; ++i) { if(ptr[i] == aValue) return i; } }else { for(int32_t i = aIndex; i < length; ++i) { if(*getPtr(i) == aValue) return i; } } return length; } inline int32_t FindLastOf(const T& aValue) const throw() { const int32_t end = size(); int32_t i = FindFirstOf(aValue); int32_t j = i; while(i != end) { j = i; i = FindNextOf(i + 1, aValue); } return j; } }; template<class T> SOLAIRE_EXPORT_INTERFACE Stack : public StaticContainer<T> { public: virtual SOLAIRE_EXPORT_CALL ~Stack() throw() {} virtual T& SOLAIRE_EXPORT_CALL pushBack(const T&) throw() = 0; virtual T SOLAIRE_EXPORT_CALL popBack() throw() = 0; virtual void SOLAIRE_EXPORT_CALL clear() throw() = 0; SOLAIRE_FORCE_INLINE T& SOLAIRE_DEFAULT_CALL back() throw() { return StaticContainer<T>::operator[](StaticContainer<T>::size() - 1); } SOLAIRE_FORCE_INLINE const T& SOLAIRE_DEFAULT_CALL back() const throw() { return StaticContainer<T>::operator[](StaticContainer<T>::size() - 1); } SOLAIRE_FORCE_INLINE operator Stack<const T>&() throw() { return *reinterpret_cast<Stack<const T>*>(this); } SOLAIRE_FORCE_INLINE operator const Stack<const T>&() const throw() { return *reinterpret_cast<Stack<const T>*>(this); } }; template<class T> SOLAIRE_EXPORT_INTERFACE Deque : public Stack<T> { public: virtual SOLAIRE_EXPORT_CALL ~Deque() throw() {} virtual T& SOLAIRE_EXPORT_CALL pushFront(const T&) throw() = 0; virtual T SOLAIRE_EXPORT_CALL popFront() throw() = 0; SOLAIRE_FORCE_INLINE T& SOLAIRE_DEFAULT_CALL front() throw() { return StaticContainer<T>::operator[](0); } SOLAIRE_FORCE_INLINE const T& SOLAIRE_DEFAULT_CALL front() const throw() { return StaticContainer<T>::operator[](0); } SOLAIRE_FORCE_INLINE operator Deque<const T>&() throw() { return *reinterpret_cast<Deque<const T>*>(this); } SOLAIRE_FORCE_INLINE operator const Deque<const T>&() const throw() { return *reinterpret_cast<Deque<const T>*>(this); } }; template<class T> SOLAIRE_EXPORT_INTERFACE List : public Deque<T> { public: virtual SOLAIRE_EXPORT_CALL ~List() throw() {} virtual T& SOLAIRE_EXPORT_CALL insertBefore(const int32_t, const T&) throw() = 0; virtual T& SOLAIRE_EXPORT_CALL insertAfter(const int32_t, const T&) throw() = 0; virtual bool SOLAIRE_EXPORT_CALL erase(const int32_t) throw() = 0; SOLAIRE_FORCE_INLINE operator List<const T>&() throw() { return *reinterpret_cast<List<const T>*>(this); } SOLAIRE_FORCE_INLINE operator const List<const T>&() const throw() { return *reinterpret_cast<List<const T>*>(this); } }; typedef StaticContainer<const char> StringConstant; typedef List<char> String; } #endif <commit_msg>Fixed find function naming<commit_after>#ifndef SOLAIRE_CONTAINER_HPP #define SOLAIRE_CONTAINER_HPP //Copyright 2015 Adam Smith // //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. // Contact : // Email : [email protected] // GitHub repository : https://github.com/SolaireLibrary/SolaireCPP /*! \file Container.hpp \brief \author Created : Adam Smith Last modified : Adam Smith \date Created : 3rd December 2015 Last Modified : 10th January 2016 */ #include "Solaire/Core/Iterator.hpp" #include "Solaire/Core/Allocator.hpp" namespace Solaire { template<class T> SOLAIRE_EXPORT_INTERFACE StaticContainer { public: typedef T Type; typedef T* Pointer; typedef T& Reference; typedef const T* ConstPointer; typedef const T& ConstReference; protected: virtual Pointer SOLAIRE_EXPORT_CALL getPtr(int32_t) throw() = 0; virtual SharedAllocation<Iterator<T>> SOLAIRE_EXPORT_CALL begin_() throw() = 0; virtual SharedAllocation<Iterator<T>> SOLAIRE_EXPORT_CALL end_() throw() = 0; virtual SharedAllocation<Iterator<T>> SOLAIRE_EXPORT_CALL rbegin_() throw() = 0; virtual SharedAllocation<Iterator<T>> SOLAIRE_EXPORT_CALL rend_() throw() = 0; public: virtual SOLAIRE_EXPORT_CALL ~StaticContainer() throw() {} virtual bool SOLAIRE_EXPORT_CALL isContiguous() const throw() = 0; virtual int32_t SOLAIRE_EXPORT_CALL size() const throw() = 0; virtual Allocator& SOLAIRE_EXPORT_CALL getAllocator() const throw() = 0; SOLAIRE_FORCE_INLINE Reference operator[](const int32_t aIndex) throw() { return *getPtr(aIndex); } SOLAIRE_FORCE_INLINE ConstReference operator[](const int32_t aIndex) const throw() { return *const_cast<StaticContainer<T>*>(this)->getPtr(aIndex); } SOLAIRE_FORCE_INLINE STLIterator<T> begin() throw() { return STLIterator<T>(begin_()); } SOLAIRE_FORCE_INLINE STLIterator<T> end() throw() { return STLIterator<T>(end_()); } SOLAIRE_FORCE_INLINE STLIterator<const T> begin() const throw() { return STLIterator<T>(const_cast<StaticContainer<T>*>(this)->begin_()); } SOLAIRE_FORCE_INLINE STLIterator<const T> end() const throw() { return STLIterator<T>(const_cast<StaticContainer<T>*>(this)->end_()); } SOLAIRE_FORCE_INLINE STLIterator<T> rbegin() throw() { return STLIterator<T>(rbegin_()); } SOLAIRE_FORCE_INLINE STLIterator<T> rend() throw() { return STLIterator<T>(rend_()); } SOLAIRE_FORCE_INLINE STLIterator<const T> rbegin() const throw() { return STLIterator<T>(const_cast<StaticContainer<T>*>(this)->rbegin_()); } SOLAIRE_FORCE_INLINE STLIterator<const T> rend() const throw() { return STLIterator<T>(const_cast<StaticContainer<T>*>(this)->rend_()); } SOLAIRE_FORCE_INLINE operator StaticContainer<const T>&() throw() { return *reinterpret_cast<StaticContainer<const T>*>(this); } SOLAIRE_FORCE_INLINE operator const StaticContainer<const T>&() const throw() { return *reinterpret_cast<StaticContainer<const T>*>(this); } inline bool operator==(const StaticContainer<const T>& aOther) const throw() { const int32_t length = size(); if(length != aOther.size()) return false; if(std::is_fundamental<T>::value && isContiguous() && aOther.isContiguous()) { return std::memcmp(getPtr(0), aOther.getPtr(0), sizeof(T) * length) == 0; }else { for(int32_t i = 0; i < length; ++i) { if(getPtr(i) != aOther.getPtr(i)) return false; } return true; } } inline bool operator!=(const StaticContainer<const T>& aOther) const throw() { const int32_t length = size(); if(length != aOther.size()) return true; if(std::is_fundamental<T>::value && isContiguous() && aOther.isContiguous()) { return std::memcmp(getPtr(0), aOther.getPtr(0), sizeof(T) * length) != 0; }else { for(int32_t i = 0; i < length; ++i) { if(getPtr(i) != aOther.getPtr(i)) return true; } return false; } } SOLAIRE_FORCE_INLINE int32_t findFirstOf(const T& aValue) const throw() { return findNextOf(0, aValue); } inline int32_t findNextOf(const int32_t aIndex, const T& aValue) const throw() { const int32_t length = size(); if(isContiguous()) { const T* const ptr = getPtr(0); for(int32_t i = aIndex; i < length; ++i) { if(ptr[i] == aValue) return i; } }else { for(int32_t i = aIndex; i < length; ++i) { if(*getPtr(i) == aValue) return i; } } return length; } inline int32_t findLastOf(const T& aValue) const throw() { const int32_t end = size(); int32_t i = findFirstOf(aValue); int32_t j = i; while(i != end) { j = i; i = findNextOf(i + 1, aValue); } return j; } }; template<class T> SOLAIRE_EXPORT_INTERFACE Stack : public StaticContainer<T> { public: virtual SOLAIRE_EXPORT_CALL ~Stack() throw() {} virtual T& SOLAIRE_EXPORT_CALL pushBack(const T&) throw() = 0; virtual T SOLAIRE_EXPORT_CALL popBack() throw() = 0; virtual void SOLAIRE_EXPORT_CALL clear() throw() = 0; SOLAIRE_FORCE_INLINE T& SOLAIRE_DEFAULT_CALL back() throw() { return StaticContainer<T>::operator[](StaticContainer<T>::size() - 1); } SOLAIRE_FORCE_INLINE const T& SOLAIRE_DEFAULT_CALL back() const throw() { return StaticContainer<T>::operator[](StaticContainer<T>::size() - 1); } SOLAIRE_FORCE_INLINE operator Stack<const T>&() throw() { return *reinterpret_cast<Stack<const T>*>(this); } SOLAIRE_FORCE_INLINE operator const Stack<const T>&() const throw() { return *reinterpret_cast<Stack<const T>*>(this); } }; template<class T> SOLAIRE_EXPORT_INTERFACE Deque : public Stack<T> { public: virtual SOLAIRE_EXPORT_CALL ~Deque() throw() {} virtual T& SOLAIRE_EXPORT_CALL pushFront(const T&) throw() = 0; virtual T SOLAIRE_EXPORT_CALL popFront() throw() = 0; SOLAIRE_FORCE_INLINE T& SOLAIRE_DEFAULT_CALL front() throw() { return StaticContainer<T>::operator[](0); } SOLAIRE_FORCE_INLINE const T& SOLAIRE_DEFAULT_CALL front() const throw() { return StaticContainer<T>::operator[](0); } SOLAIRE_FORCE_INLINE operator Deque<const T>&() throw() { return *reinterpret_cast<Deque<const T>*>(this); } SOLAIRE_FORCE_INLINE operator const Deque<const T>&() const throw() { return *reinterpret_cast<Deque<const T>*>(this); } }; template<class T> SOLAIRE_EXPORT_INTERFACE List : public Deque<T> { public: virtual SOLAIRE_EXPORT_CALL ~List() throw() {} virtual T& SOLAIRE_EXPORT_CALL insertBefore(const int32_t, const T&) throw() = 0; virtual T& SOLAIRE_EXPORT_CALL insertAfter(const int32_t, const T&) throw() = 0; virtual bool SOLAIRE_EXPORT_CALL erase(const int32_t) throw() = 0; SOLAIRE_FORCE_INLINE operator List<const T>&() throw() { return *reinterpret_cast<List<const T>*>(this); } SOLAIRE_FORCE_INLINE operator const List<const T>&() const throw() { return *reinterpret_cast<List<const T>*>(this); } }; typedef StaticContainer<const char> StringConstant; typedef List<char> String; } #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: formatclipboard.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2004-08-05 11:03:14 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2004 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "formatclipboard.hxx" #ifndef _E3D_GLOBL3D_HXX #include <svx/globl3d.hxx> #endif // header for class SfxItemIter #ifndef _SFXITEMITER_HXX #include <svtools/itemiter.hxx> #endif // header for class SfxStyleSheet #ifndef _SFXSTYLE_HXX #include <svtools/style.hxx> #endif /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ SdFormatClipboard::SdFormatClipboard() : m_pItemSet(0) , m_bPersistentCopy(false) , m_nType_Inventor(0) , m_nType_Identifier(0) { } SdFormatClipboard::~SdFormatClipboard() { if(m_pItemSet) delete m_pItemSet; } bool SdFormatClipboard::HasContent() const { return m_pItemSet!=0; } bool SdFormatClipboard::CanCopyThisType( UINT32 nObjectInventor, UINT16 nObjectIdentifier ) const { if( nObjectInventor != SdrInventor && nObjectInventor != E3dInventor ) return false; switch(nObjectIdentifier) { case OBJ_NONE: case OBJ_GRUP: return false; break; case OBJ_LINE: case OBJ_RECT: case OBJ_CIRC: case OBJ_SECT: case OBJ_CARC: case OBJ_CCUT: case OBJ_POLY: case OBJ_PLIN: case OBJ_PATHLINE: case OBJ_PATHFILL: case OBJ_FREELINE: case OBJ_FREEFILL: case OBJ_SPLNLINE: case OBJ_SPLNFILL: case OBJ_TEXT: case OBJ_TEXTEXT: case OBJ_TITLETEXT: return true; break; case OBJ_OUTLINETEXT: case OBJ_GRAF: case OBJ_OLE2: case OBJ_EDGE: case OBJ_CAPTION: return false; break; case OBJ_PATHPOLY: case OBJ_PATHPLIN: return true; break; case OBJ_PAGE: case OBJ_MEASURE: case OBJ_DUMMY: case OBJ_FRAME: case OBJ_UNO: case OBJ_CUSTOMSHAPE: return false; break; default: return false; break; } return true; } bool SdFormatClipboard::HasContentForThisType( UINT32 nObjectInventor, UINT16 nObjectIdentifier ) const { if( !HasContent() ) return false; if( !CanCopyThisType( nObjectInventor, nObjectIdentifier ) ) return false; return true; } void SdFormatClipboard::Copy( ::sd::View& rDrawView, bool bPersistentCopy ) { this->Erase(); m_bPersistentCopy = bPersistentCopy; const SdrMarkList& rMarkList = rDrawView.GetMarkedObjectList(); if( rMarkList.GetMarkCount() >= 1 ) { BOOL bOnlyHardAttr = FALSE; m_pItemSet = new SfxItemSet( rDrawView.GetAttrFromMarked(bOnlyHardAttr) ); SdrObject* pObj = rMarkList.GetMark(0)->GetObj(); m_nType_Inventor = pObj->GetObjInventor(); m_nType_Identifier = pObj->GetObjIdentifier(); } } void SdFormatClipboard::Paste( ::sd::View& rDrawView , bool bNoCharacterFormats, bool bNoParagraphFormats ) { if( !rDrawView.AreObjectsMarked() ) { if(!m_bPersistentCopy) this->Erase(); return; } SdrObject* pObj = 0; bool bWrongTargetType = false; { const SdrMarkList& rMarkList = rDrawView.GetMarkedObjectList(); if( rMarkList.GetMarkCount() != 1 ) bWrongTargetType = true; else { pObj = rMarkList.GetMark(0)->GetObj(); if( pObj && pObj->GetStyleSheet() ) bWrongTargetType = !this->HasContentForThisType( pObj->GetObjInventor(), pObj->GetObjIdentifier() ); } } if( bWrongTargetType ) { if(!m_bPersistentCopy) this->Erase(); return; } if(m_pItemSet) { //modify source itemset { BOOL bOnlyHardAttr = FALSE; SfxItemSet aTargetSet( pObj->GetStyleSheet()->GetItemSet() ); USHORT nWhich=0; SfxItemState nSourceState; SfxItemState nTargetState; const SfxPoolItem* pSourceItem=0; const SfxPoolItem* pTargetItem=0; SfxItemIter aSourceIter(*m_pItemSet); pSourceItem = aSourceIter.FirstItem(); while( pSourceItem!=NULL ) { if (!IsInvalidItem(pSourceItem)) { nWhich = pSourceItem->Which(); if(nWhich) { nSourceState = m_pItemSet->GetItemState( nWhich ); nTargetState = aTargetSet.GetItemState( nWhich ); pTargetItem = aTargetSet.GetItem( nWhich ); ::com::sun::star::uno::Any aSourceValue, aTargetValue; if(!pTargetItem) m_pItemSet->ClearItem(nWhich); else if( (*pSourceItem) == (*pTargetItem) ) { //do not set items which have the same content in source and target m_pItemSet->ClearItem(nWhich); } } } pSourceItem = aSourceIter.NextItem(); }//end while } BOOL bReplaceAll = TRUE; rDrawView.SetAttrToMarked(*m_pItemSet, bReplaceAll); } if(!m_bPersistentCopy) this->Erase(); } void SdFormatClipboard::Erase() { if(m_pItemSet) { delete m_pItemSet; m_pItemSet = 0; } m_nType_Inventor=0; m_nType_Identifier=0; m_bPersistentCopy = false; } <commit_msg>INTEGRATION: CWS sch05 (1.3.112); FILE MERGED 2004/11/25 14:18:11 iha 1.3.112.1: #i37758# formatpaintbrush didn't not work with custom shapes<commit_after>/************************************************************************* * * $RCSfile: formatclipboard.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2004-12-10 17:22:43 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2004 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "formatclipboard.hxx" #ifndef _E3D_GLOBL3D_HXX #include <svx/globl3d.hxx> #endif // header for class SfxItemIter #ifndef _SFXITEMITER_HXX #include <svtools/itemiter.hxx> #endif // header for class SfxStyleSheet #ifndef _SFXSTYLE_HXX #include <svtools/style.hxx> #endif /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ SdFormatClipboard::SdFormatClipboard() : m_pItemSet(0) , m_bPersistentCopy(false) , m_nType_Inventor(0) , m_nType_Identifier(0) { } SdFormatClipboard::~SdFormatClipboard() { if(m_pItemSet) delete m_pItemSet; } bool SdFormatClipboard::HasContent() const { return m_pItemSet!=0; } bool SdFormatClipboard::CanCopyThisType( UINT32 nObjectInventor, UINT16 nObjectIdentifier ) const { if( nObjectInventor != SdrInventor && nObjectInventor != E3dInventor ) return false; switch(nObjectIdentifier) { case OBJ_NONE: case OBJ_GRUP: return false; break; case OBJ_LINE: case OBJ_RECT: case OBJ_CIRC: case OBJ_SECT: case OBJ_CARC: case OBJ_CCUT: case OBJ_POLY: case OBJ_PLIN: case OBJ_PATHLINE: case OBJ_PATHFILL: case OBJ_FREELINE: case OBJ_FREEFILL: case OBJ_SPLNLINE: case OBJ_SPLNFILL: case OBJ_TEXT: case OBJ_TEXTEXT: case OBJ_TITLETEXT: return true; break; case OBJ_OUTLINETEXT: case OBJ_GRAF: case OBJ_OLE2: case OBJ_EDGE: case OBJ_CAPTION: return false; break; case OBJ_PATHPOLY: case OBJ_PATHPLIN: return true; break; case OBJ_PAGE: case OBJ_MEASURE: case OBJ_DUMMY: case OBJ_FRAME: case OBJ_UNO: return false; break; case OBJ_CUSTOMSHAPE: return true; break; default: return false; break; } return true; } bool SdFormatClipboard::HasContentForThisType( UINT32 nObjectInventor, UINT16 nObjectIdentifier ) const { if( !HasContent() ) return false; if( !CanCopyThisType( nObjectInventor, nObjectIdentifier ) ) return false; return true; } void SdFormatClipboard::Copy( ::sd::View& rDrawView, bool bPersistentCopy ) { this->Erase(); m_bPersistentCopy = bPersistentCopy; const SdrMarkList& rMarkList = rDrawView.GetMarkedObjectList(); if( rMarkList.GetMarkCount() >= 1 ) { BOOL bOnlyHardAttr = FALSE; m_pItemSet = new SfxItemSet( rDrawView.GetAttrFromMarked(bOnlyHardAttr) ); SdrObject* pObj = rMarkList.GetMark(0)->GetObj(); m_nType_Inventor = pObj->GetObjInventor(); m_nType_Identifier = pObj->GetObjIdentifier(); } } void SdFormatClipboard::Paste( ::sd::View& rDrawView , bool bNoCharacterFormats, bool bNoParagraphFormats ) { if( !rDrawView.AreObjectsMarked() ) { if(!m_bPersistentCopy) this->Erase(); return; } SdrObject* pObj = 0; bool bWrongTargetType = false; { const SdrMarkList& rMarkList = rDrawView.GetMarkedObjectList(); if( rMarkList.GetMarkCount() != 1 ) bWrongTargetType = true; else { pObj = rMarkList.GetMark(0)->GetObj(); if( pObj && pObj->GetStyleSheet() ) bWrongTargetType = !this->HasContentForThisType( pObj->GetObjInventor(), pObj->GetObjIdentifier() ); } } if( bWrongTargetType ) { if(!m_bPersistentCopy) this->Erase(); return; } if(m_pItemSet) { //modify source itemset { BOOL bOnlyHardAttr = FALSE; SfxItemSet aTargetSet( pObj->GetStyleSheet()->GetItemSet() ); USHORT nWhich=0; SfxItemState nSourceState; SfxItemState nTargetState; const SfxPoolItem* pSourceItem=0; const SfxPoolItem* pTargetItem=0; SfxItemIter aSourceIter(*m_pItemSet); pSourceItem = aSourceIter.FirstItem(); while( pSourceItem!=NULL ) { if (!IsInvalidItem(pSourceItem)) { nWhich = pSourceItem->Which(); if(nWhich) { nSourceState = m_pItemSet->GetItemState( nWhich ); nTargetState = aTargetSet.GetItemState( nWhich ); pTargetItem = aTargetSet.GetItem( nWhich ); ::com::sun::star::uno::Any aSourceValue, aTargetValue; if(!pTargetItem) m_pItemSet->ClearItem(nWhich); else if( (*pSourceItem) == (*pTargetItem) ) { //do not set items which have the same content in source and target m_pItemSet->ClearItem(nWhich); } } } pSourceItem = aSourceIter.NextItem(); }//end while } BOOL bReplaceAll = TRUE; rDrawView.SetAttrToMarked(*m_pItemSet, bReplaceAll); } if(!m_bPersistentCopy) this->Erase(); } void SdFormatClipboard::Erase() { if(m_pItemSet) { delete m_pItemSet; m_pItemSet = 0; } m_nType_Inventor=0; m_nType_Identifier=0; m_bPersistentCopy = false; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: XMLExportDDELinks.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: hr $ $Date: 2004-03-08 11:53:09 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "filt_pch.hxx" #endif #pragma hdrstop // INCLUDE --------------------------------------------------------------- #ifndef _SC_XMLEXPORTDDELINKS_HXX #include "XMLExportDDELinks.hxx" #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include <xmloff/xmlnmspe.hxx> #endif #ifndef _XMLOFF_NMSPMAP_HXX #include <xmloff/nmspmap.hxx> #endif #ifndef _XMLOFF_XMLUCONV_HXX #include <xmloff/xmluconv.hxx> #endif #ifndef SC_XMLEXPRT_HXX #include "xmlexprt.hxx" #endif #ifndef SC_UNONAMES_HXX #include "unonames.hxx" #endif #ifndef SC_DOCUMENT_HXX #include "document.hxx" #endif #ifndef SC_MATRIX_HXX #include "scmatrix.hxx" #endif #ifndef _COM_SUN_STAR_SHEET_XDDELINK_HPP_ #include <com/sun/star/sheet/XDDELink.hpp> #endif class ScMatrix; using namespace com::sun::star; using namespace xmloff::token; ScXMLExportDDELinks::ScXMLExportDDELinks(ScXMLExport& rTempExport) : rExport(rTempExport) { } ScXMLExportDDELinks::~ScXMLExportDDELinks() { } sal_Bool ScXMLExportDDELinks::CellsEqual(const sal_Bool bPrevEmpty, const sal_Bool bPrevString, const String& sPrevValue, const double& fPrevValue, const sal_Bool bEmpty, const sal_Bool bString, const String& sValue, const double& fValue) { if (bEmpty == bPrevEmpty) if (bEmpty) return sal_True; else if (bString == bPrevString) if (bString) return (sPrevValue == sValue); else return (fPrevValue == fValue); else return sal_False; else return sal_False; } void ScXMLExportDDELinks::WriteCell(const sal_Bool bEmpty, const sal_Bool bString, const String& sValue, const double& fValue, const sal_Int32 nRepeat) { rtl::OUStringBuffer sBuffer; if (!bEmpty) if (bString) { rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_VALUE_TYPE, XML_STRING); rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_STRING_VALUE, rtl::OUString(sValue)); } else { rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_VALUE_TYPE, XML_FLOAT); rExport.GetMM100UnitConverter().convertDouble(sBuffer, fValue); rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_VALUE, sBuffer.makeStringAndClear()); } if (nRepeat > 1) { rExport.GetMM100UnitConverter().convertNumber(sBuffer, nRepeat); rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_NUMBER_COLUMNS_REPEATED, sBuffer.makeStringAndClear()); } SvXMLElementExport(rExport, XML_NAMESPACE_TABLE, XML_TABLE_CELL, sal_True, sal_True); } void ScXMLExportDDELinks::WriteTable(const sal_Int32 nPos) { const ScMatrix* pMatrix = NULL; if (rExport.GetDocument()) pMatrix = rExport.GetDocument()->GetDdeLinkResultMatrix( static_cast<USHORT>(nPos) ); if (pMatrix) { USHORT nuCol, nuRow; pMatrix->GetDimensions( nuCol, nuRow ); sal_Int32 nRowCount = nuRow; sal_Int32 nColCount = nuCol; SvXMLElementExport aTableElem(rExport, XML_NAMESPACE_TABLE, XML_TABLE, sal_True, sal_True); rtl::OUStringBuffer sBuffer; if (nColCount > 1) { rExport.GetMM100UnitConverter().convertNumber(sBuffer, nColCount); rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_NUMBER_COLUMNS_REPEATED, sBuffer.makeStringAndClear()); } { SvXMLElementExport aElemCol(rExport, XML_NAMESPACE_TABLE, XML_TABLE_COLUMN, sal_True, sal_True); } sal_Bool bPrevString(sal_True); sal_Bool bPrevEmpty(sal_True); double fPrevValue; String sPrevValue; sal_Int32 nRepeatColsCount(1); for(sal_Int32 nRow = 0; nRow < nRowCount; nRow++) { SvXMLElementExport aElemRow(rExport, XML_NAMESPACE_TABLE, XML_TABLE_ROW, sal_True, sal_True); for(sal_Int32 nColumn = 0; nColumn < nColCount; nColumn++) { BOOL bIsString = FALSE; const MatValue* pMatVal = pMatrix->Get( static_cast<USHORT>(nColumn), static_cast<USHORT>(nRow), bIsString ); if (nColumn == 0) { bPrevEmpty = !pMatVal; bPrevString = bIsString; if( bIsString ) sPrevValue = pMatVal->GetString(); else fPrevValue = pMatVal->fVal; } else { double fValue; String sValue; sal_Bool bEmpty = !pMatVal; sal_Bool bString = bIsString; if( bIsString ) sValue = pMatVal->GetString(); else fValue = pMatVal->fVal; if (CellsEqual(bPrevEmpty, bPrevString, sPrevValue, fPrevValue, bEmpty, bString, sValue, fValue)) nRepeatColsCount++; else { WriteCell(bPrevEmpty, bPrevString, sPrevValue, fPrevValue, nRepeatColsCount); nRepeatColsCount = 1; bPrevEmpty = bEmpty; fPrevValue = fValue; sPrevValue = sValue; } } } WriteCell(bPrevEmpty, bPrevString, sPrevValue, fPrevValue, nRepeatColsCount); nRepeatColsCount = 1; } } } void ScXMLExportDDELinks::WriteDDELinks(uno::Reference<sheet::XSpreadsheetDocument>& xSpreadDoc) { uno::Reference <beans::XPropertySet> xPropertySet (xSpreadDoc, uno::UNO_QUERY); if (xPropertySet.is()) { uno::Any aDDELinks = xPropertySet->getPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNO_DDELINKS))); uno::Reference<container::XIndexAccess> xIndex; if (aDDELinks >>= xIndex) { sal_Int32 nCount = xIndex->getCount(); if (nCount) { SvXMLElementExport aElemDDEs(rExport, XML_NAMESPACE_TABLE, XML_DDE_LINKS, sal_True, sal_True); for (sal_uInt16 nDDELink = 0; nDDELink < nCount; nDDELink++) { uno::Any aDDELink = xIndex->getByIndex(nDDELink); uno::Reference<sheet::XDDELink> xDDELink; if (aDDELink >>= xDDELink) { SvXMLElementExport aElemDDE(rExport, XML_NAMESPACE_TABLE, XML_DDE_LINK, sal_True, sal_True); { rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_DDE_APPLICATION, xDDELink->getApplication()); rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_DDE_TOPIC, xDDELink->getTopic()); rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_DDE_ITEM, xDDELink->getItem()); rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_AUTOMATIC_UPDATE, XML_TRUE); BYTE nMode; if (rExport.GetDocument() && rExport.GetDocument()->GetDdeLinkMode(nDDELink, nMode)) { switch (nMode) { case SC_DDE_ENGLISH : rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_CONVERSION_MODE, XML_INTO_ENGLISH_NUMBER); case SC_DDE_TEXT : rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_CONVERSION_MODE, XML_LET_TEXT); } } SvXMLElementExport(rExport, XML_NAMESPACE_OFFICE, XML_DDE_SOURCE, sal_True, sal_True); } WriteTable(nDDELink); } } } } } } <commit_msg>INTEGRATION: CWS rowlimit (1.8.324); FILE MERGED 2004/03/17 12:24:59 er 1.8.324.3: #i1967# type correctness (ScMatrix parameters are SCSIZE now) 2004/03/15 17:24:10 er 1.8.324.2: RESYNC: (1.8-1.9); FILE MERGED 2004/01/19 19:09:23 jmarmion 1.8.324.1: #i1967# SCCOL,SCROW,SCTAB replace USHORT; SCsCOL,SCsROW,SCsTAB replace short.<commit_after>/************************************************************************* * * $RCSfile: XMLExportDDELinks.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: obo $ $Date: 2004-06-04 11:09:20 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "filt_pch.hxx" #endif #pragma hdrstop // INCLUDE --------------------------------------------------------------- #ifndef _SC_XMLEXPORTDDELINKS_HXX #include "XMLExportDDELinks.hxx" #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include <xmloff/xmlnmspe.hxx> #endif #ifndef _XMLOFF_NMSPMAP_HXX #include <xmloff/nmspmap.hxx> #endif #ifndef _XMLOFF_XMLUCONV_HXX #include <xmloff/xmluconv.hxx> #endif #ifndef SC_XMLEXPRT_HXX #include "xmlexprt.hxx" #endif #ifndef SC_UNONAMES_HXX #include "unonames.hxx" #endif #ifndef SC_DOCUMENT_HXX #include "document.hxx" #endif #ifndef SC_MATRIX_HXX #include "scmatrix.hxx" #endif #ifndef _COM_SUN_STAR_SHEET_XDDELINK_HPP_ #include <com/sun/star/sheet/XDDELink.hpp> #endif class ScMatrix; using namespace com::sun::star; using namespace xmloff::token; ScXMLExportDDELinks::ScXMLExportDDELinks(ScXMLExport& rTempExport) : rExport(rTempExport) { } ScXMLExportDDELinks::~ScXMLExportDDELinks() { } sal_Bool ScXMLExportDDELinks::CellsEqual(const sal_Bool bPrevEmpty, const sal_Bool bPrevString, const String& sPrevValue, const double& fPrevValue, const sal_Bool bEmpty, const sal_Bool bString, const String& sValue, const double& fValue) { if (bEmpty == bPrevEmpty) if (bEmpty) return sal_True; else if (bString == bPrevString) if (bString) return (sPrevValue == sValue); else return (fPrevValue == fValue); else return sal_False; else return sal_False; } void ScXMLExportDDELinks::WriteCell(const sal_Bool bEmpty, const sal_Bool bString, const String& sValue, const double& fValue, const sal_Int32 nRepeat) { rtl::OUStringBuffer sBuffer; if (!bEmpty) if (bString) { rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_VALUE_TYPE, XML_STRING); rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_STRING_VALUE, rtl::OUString(sValue)); } else { rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_VALUE_TYPE, XML_FLOAT); rExport.GetMM100UnitConverter().convertDouble(sBuffer, fValue); rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_VALUE, sBuffer.makeStringAndClear()); } if (nRepeat > 1) { rExport.GetMM100UnitConverter().convertNumber(sBuffer, nRepeat); rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_NUMBER_COLUMNS_REPEATED, sBuffer.makeStringAndClear()); } SvXMLElementExport(rExport, XML_NAMESPACE_TABLE, XML_TABLE_CELL, sal_True, sal_True); } void ScXMLExportDDELinks::WriteTable(const sal_Int32 nPos) { const ScMatrix* pMatrix = NULL; if (rExport.GetDocument()) pMatrix = rExport.GetDocument()->GetDdeLinkResultMatrix( static_cast<USHORT>(nPos) ); if (pMatrix) { SCSIZE nuCol; SCSIZE nuRow; pMatrix->GetDimensions( nuCol, nuRow ); sal_Int32 nRowCount = static_cast<sal_Int32>(nuRow); sal_Int32 nColCount = static_cast<sal_Int32>(nuCol); SvXMLElementExport aTableElem(rExport, XML_NAMESPACE_TABLE, XML_TABLE, sal_True, sal_True); rtl::OUStringBuffer sBuffer; if (nColCount > 1) { rExport.GetMM100UnitConverter().convertNumber(sBuffer, nColCount); rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_NUMBER_COLUMNS_REPEATED, sBuffer.makeStringAndClear()); } { SvXMLElementExport aElemCol(rExport, XML_NAMESPACE_TABLE, XML_TABLE_COLUMN, sal_True, sal_True); } sal_Bool bPrevString(sal_True); sal_Bool bPrevEmpty(sal_True); double fPrevValue; String sPrevValue; sal_Int32 nRepeatColsCount(1); for(sal_Int32 nRow = 0; nRow < nRowCount; nRow++) { SvXMLElementExport aElemRow(rExport, XML_NAMESPACE_TABLE, XML_TABLE_ROW, sal_True, sal_True); for(sal_Int32 nColumn = 0; nColumn < nColCount; nColumn++) { BOOL bIsString = FALSE; const MatValue* pMatVal = pMatrix->Get( static_cast<SCSIZE>(nColumn), static_cast<SCSIZE>(nRow), bIsString ); if (nColumn == 0) { bPrevEmpty = !pMatVal; bPrevString = bIsString; if( bIsString ) sPrevValue = pMatVal->GetString(); else fPrevValue = pMatVal->fVal; } else { double fValue; String sValue; sal_Bool bEmpty = !pMatVal; sal_Bool bString = bIsString; if( bIsString ) sValue = pMatVal->GetString(); else fValue = pMatVal->fVal; if (CellsEqual(bPrevEmpty, bPrevString, sPrevValue, fPrevValue, bEmpty, bString, sValue, fValue)) nRepeatColsCount++; else { WriteCell(bPrevEmpty, bPrevString, sPrevValue, fPrevValue, nRepeatColsCount); nRepeatColsCount = 1; bPrevEmpty = bEmpty; fPrevValue = fValue; sPrevValue = sValue; } } } WriteCell(bPrevEmpty, bPrevString, sPrevValue, fPrevValue, nRepeatColsCount); nRepeatColsCount = 1; } } } void ScXMLExportDDELinks::WriteDDELinks(uno::Reference<sheet::XSpreadsheetDocument>& xSpreadDoc) { uno::Reference <beans::XPropertySet> xPropertySet (xSpreadDoc, uno::UNO_QUERY); if (xPropertySet.is()) { uno::Any aDDELinks = xPropertySet->getPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNO_DDELINKS))); uno::Reference<container::XIndexAccess> xIndex; if (aDDELinks >>= xIndex) { sal_Int32 nCount = xIndex->getCount(); if (nCount) { SvXMLElementExport aElemDDEs(rExport, XML_NAMESPACE_TABLE, XML_DDE_LINKS, sal_True, sal_True); for (sal_uInt16 nDDELink = 0; nDDELink < nCount; nDDELink++) { uno::Any aDDELink = xIndex->getByIndex(nDDELink); uno::Reference<sheet::XDDELink> xDDELink; if (aDDELink >>= xDDELink) { SvXMLElementExport aElemDDE(rExport, XML_NAMESPACE_TABLE, XML_DDE_LINK, sal_True, sal_True); { rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_DDE_APPLICATION, xDDELink->getApplication()); rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_DDE_TOPIC, xDDELink->getTopic()); rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_DDE_ITEM, xDDELink->getItem()); rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_AUTOMATIC_UPDATE, XML_TRUE); BYTE nMode; if (rExport.GetDocument() && rExport.GetDocument()->GetDdeLinkMode(nDDELink, nMode)) { switch (nMode) { case SC_DDE_ENGLISH : rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_CONVERSION_MODE, XML_INTO_ENGLISH_NUMBER); case SC_DDE_TEXT : rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_CONVERSION_MODE, XML_LET_TEXT); } } SvXMLElementExport(rExport, XML_NAMESPACE_OFFICE, XML_DDE_SOURCE, sal_True, sal_True); } WriteTable(nDDELink); } } } } } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: XMLExportDDELinks.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-08 19:53:56 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SC_XMLEXPORTDDELINKS_HXX #define _SC_XMLEXPORTDDELINKS_HXX #ifndef _COM_SUN_STAR_SHEET_XSPREADSHEETDOCUMENT_HPP_ #include <com/sun/star/sheet/XSpreadsheetDocument.hpp> #endif class String; class ScXMLExport; class ScXMLExportDDELinks { ScXMLExport& rExport; sal_Bool CellsEqual(const sal_Bool bPrevEmpty, const sal_Bool bPrevString, const String& sPrevValue, const double& fPrevValue, const sal_Bool bEmpty, const sal_Bool bString, const String& sValue, const double& fValue); void WriteCell(const sal_Bool bEmpty, const sal_Bool bString, const String& sValue, const double& fValue, const sal_Int32 nRepeat); void WriteTable(const sal_Int32 nPos); public: ScXMLExportDDELinks(ScXMLExport& rExport); ~ScXMLExportDDELinks(); void WriteDDELinks(::com::sun::star::uno::Reference < ::com::sun::star::sheet::XSpreadsheetDocument >& xSpreadDoc); }; #endif <commit_msg>INTEGRATION: CWS changefileheader (1.5.700); FILE MERGED 2008/04/01 12:36:30 thb 1.5.700.2: #i85898# Stripping all external header guards 2008/03/31 17:14:55 rt 1.5.700.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: XMLExportDDELinks.hxx,v $ * $Revision: 1.6 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SC_XMLEXPORTDDELINKS_HXX #define _SC_XMLEXPORTDDELINKS_HXX #include <com/sun/star/sheet/XSpreadsheetDocument.hpp> class String; class ScXMLExport; class ScXMLExportDDELinks { ScXMLExport& rExport; sal_Bool CellsEqual(const sal_Bool bPrevEmpty, const sal_Bool bPrevString, const String& sPrevValue, const double& fPrevValue, const sal_Bool bEmpty, const sal_Bool bString, const String& sValue, const double& fValue); void WriteCell(const sal_Bool bEmpty, const sal_Bool bString, const String& sValue, const double& fValue, const sal_Int32 nRepeat); void WriteTable(const sal_Int32 nPos); public: ScXMLExportDDELinks(ScXMLExport& rExport); ~ScXMLExportDDELinks(); void WriteDDELinks(::com::sun::star::uno::Reference < ::com::sun::star::sheet::XSpreadsheetDocument >& xSpreadDoc); }; #endif <|endoftext|>
<commit_before>// /$$$$$$$ /$$$$$$$$ /$$$$$$ /$$$$$$ /$$$$$$ /$$$$$$$$ /$$$$$$ /$$$$$$$ // | $$__ $$| $$_____/ /$$__ $$|_ $$_/ /$$__ $$|__ $$__//$$__ $$| $$__ $$ // | $$ \ $$| $$ | $$ \__/ | $$ | $$ \__/ | $$ | $$ \ $$| $$ \ $$ // | $$$$$$$/| $$$$$ | $$$$$$ | $$ | $$$$$$ | $$ | $$ | $$| $$$$$$$/ // | $$__ $$| $$__/ \____ $$ | $$ \____ $$ | $$ | $$ | $$| $$__ $$ // | $$ \ $$| $$ /$$ \ $$ | $$ /$$ \ $$ | $$ | $$ | $$| $$ \ $$ // | $$ | $$| $$$$$$$$| $$$$$$/ /$$$$$$| $$$$$$/ | $$ | $$$$$$/| $$ | $$ // |__/ |__/|________/ \______/ |______/ \______/ |__/ \______/ |__/ |__/ #include <Windows.h> #include <iostream> #include <fstream> #include <string> #include <sstream> #include <exception> #include <bitset> #include <stdlib.h> // Bitwise operations for extracting data from return stream #define S1(k,n) ((k) & ((1<<(n))-1)) #define F10(k,m,n) S1((k)>>(m),((n)-(m))) // Set global serial port handle HANDLE Resipod; DCB ResipodParam = { 0 }; // Not C++ recommended to make this global, but I am lazy // and don't want to figure out how to return a byte array byte receive[] = { 0x0,0x0,0x0 }; void GetResistance() { byte command[] = { 0xC1,0xD2,0x21 }; DWORD bytesWrite = 0; DWORD bytesRead = 0; WriteFile(Resipod, command, 3, &bytesWrite, NULL); ReadFile(Resipod, receive, 3, &bytesRead, NULL); if (receive[0] != 0x02) { std::cout << "Received value does not contain correct start byte. Non-fatal error.\n"; } } int InitializePort() { int userComPort = 3; std::cout << "Enter COM port number that Resipod is connected to: "; std::cin >> userComPort; std::wstringstream comPort; comPort << "\\\\.\\COM" << userComPort; std::cout << "\nChecking port COM" << userComPort << "..."; Resipod = CreateFile(comPort.str().c_str(), GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if (Resipod == INVALID_HANDLE_VALUE) { DWORD dwError = GetLastError(); if (dwError == ERROR_ACCESS_DENIED || dwError == ERROR_GEN_FAILURE || dwError == ERROR_SHARING_VIOLATION || dwError == ERROR_SEM_TIMEOUT) { std::cout << "resource in use and not usable\n"; } else { std::cout << "error opening port\n"; } return(0); } else { std::cout << "success!\n"; ResipodParam.DCBlength = sizeof(ResipodParam); // Hardcode serial parameters based on Resipod data ResipodParam.BaudRate = CBR_19200; ResipodParam.ByteSize = 8; ResipodParam.StopBits = 1; ResipodParam.Parity = NOPARITY; ResipodParam.fOutX = FALSE; ResipodParam.fInX = FALSE; ResipodParam.fTXContinueOnXoff = FALSE; SetCommState(Resipod, &ResipodParam); // Set some timeout values COMMTIMEOUTS timeouts = { 0 }; timeouts.ReadIntervalTimeout = 200; timeouts.ReadTotalTimeoutConstant = 1000; timeouts.ReadTotalTimeoutMultiplier = 1; timeouts.WriteTotalTimeoutConstant = 200; timeouts.WriteTotalTimeoutMultiplier = 1; // Get ID on port to see if it is a Proceq device /*byte command[] = { 0xC1,0xD2,0x21 }; byte getID[] = { 0x10,0x49,0x44,0x0D }; char receiveID[8] = {0}; char correctID[8] = "Resipod"; DWORD bytesWriteID = 0; DWORD bytesReadID = 0; WriteFile(Resipod, command, 3, &bytesWriteID, NULL); ReadFile(Resipod, receiveID, 3, &bytesReadID, NULL); WriteFile(Resipod, getID, 5, &bytesWriteID, NULL); ReadFile(Resipod, receiveID, 8, &bytesReadID, NULL); if (SetCommTimeouts(Resipod, &timeouts) == 0) { std::cout << "timeout\n"; } else { std::cout << receiveID << "\n"; if (strcmp(receiveID, correctID)) { return(j); } }*/ } return(userComPort); } void DisplayHeader() { std::cout << " /$$$$$$$ /$$$$$$$$ /$$$$$$ /$$$$$$ /$$$$$$ /$$$$$$$$ /$$$$$$ /$$$$$$$\n"; std::cout << " | $$__ $$| $$_____/ /$$__ $$|_ $$_/ /$$__ $$|__ $$__//$$__ $$| $$__ $$\n"; std::cout << " | $$ \\ $$| $$ | $$ \\__/ | $$ | $$ \\__/ | $$ | $$ \\ $$| $$ \\ $$\n"; std::cout << " | $$$$$$$/| $$$$$ | $$$$$$ | $$ | $$$$$$ | $$ | $$ | $$| $$$$$$$/\n"; std::cout << " | $$__ $$| $$__/ \\____ $$ | $$ \\____ $$ | $$ | $$ | $$| $$__ $$\n"; std::cout << " | $$ \\ $$| $$ /$$ \\ $$ | $$ /$$ \\ $$ | $$ | $$ | $$| $$ \\ $$\n"; std::cout << " | $$ | $$| $$$$$$$$| $$$$$$/ /$$$$$$| $$$$$$/ | $$ | $$$$$$/| $$ | $$\n"; std::cout << " |__/ |__/|________/ \\______/ |______/ \\______/ |__/ \\______/ |__/ |__/\n"; std::cout << "\n\n Current code is in testing phase. Do NOT use for research purposes...\n\n"; } int main() { char TestInterface; char dummy; DisplayHeader(); std::cout << "Initializing serial port interface..."; int PortOpen = InitializePort(); if (PortOpen = 0) { std::cout << "no Resipod device found!\n"; std::cout << "Press any key to terminate program..."; std::cin >> dummy; return(EXIT_FAILURE); } else { std::cout << "success!\n\n"; std::cout << "Resipod device is on COM" << PortOpen << "\n"; } std::cout << "Current test program will obtain three readings at an interval of 3 seconds.\n"; std::cout << "Press any key when ready to test interface..."; std::cin >> TestInterface; for (int i = 1; i < 4; i++) { std::cout << "\n\n\nStarting measurement #" << i << "...\n\n"; GetResistance(); std::cout << " Checking first byte received\n"; std::cout << "--------------------------------\n"; std::cout << std::bitset<8>(0x02) << " - expected from device\n"; std::cout << std::bitset<8>(receive[0]) << " - received from device\n"; std::cout << "--------------------------------\n"; if (receive[0] = 0x02) { std::cout << "Bytes match, next values should be correct.\n"; } else { std::cout << "Bytes do not match! Next values unlikely to be correct!\n"; } unsigned output1 = (receive[2] << 8) | (receive[1]); std::cout << std::bitset<16>(output1) << "\n"; int reading = F10(output1, 0, 11); double resistance = reading; bool divide10 = F10(output1, 11, 12); if (divide10) { resistance = reading / 10.0; } std::cout << "Decimal number: " << reading << "\n"; std::cout << "Binary number: " << std::bitset<16>(reading) << "\n"; std::cout << "Resistance: " << resistance << " ohms\n\n\n"; std::cin >> reading; } }<commit_msg>First viable release version with user control<commit_after>// /$$$$$$$ /$$$$$$$$ /$$$$$$ /$$$$$$ /$$$$$$ /$$$$$$$$ /$$$$$$ /$$$$$$$ // | $$__ $$| $$_____/ /$$__ $$|_ $$_/ /$$__ $$|__ $$__//$$__ $$| $$__ $$ // | $$ \ $$| $$ | $$ \__/ | $$ | $$ \__/ | $$ | $$ \ $$| $$ \ $$ // | $$$$$$$/| $$$$$ | $$$$$$ | $$ | $$$$$$ | $$ | $$ | $$| $$$$$$$/ // | $$__ $$| $$__/ \____ $$ | $$ \____ $$ | $$ | $$ | $$| $$__ $$ // | $$ \ $$| $$ /$$ \ $$ | $$ /$$ \ $$ | $$ | $$ | $$| $$ \ $$ // | $$ | $$| $$$$$$$$| $$$$$$/ /$$$$$$| $$$$$$/ | $$ | $$$$$$/| $$ | $$ // |__/ |__/|________/ \______/ |______/ \______/ |__/ \______/ |__/ |__/ #include <Windows.h> #include <iostream> #include <string> #include <sstream> #include <exception> #include <bitset> #include <stdlib.h> #include <fstream> #include <chrono> #include <ctime> // Bitwise operations for extracting data from return stream #define S1(k,n) ((k) & ((1<<(n))-1)) #define F10(k,m,n) S1((k)>>(m),((n)-(m))) // Set global serial port handle HANDLE Resipod; DCB ResipodParam = { 0 }; // Get timer ready HANDLE timer = NULL; LARGE_INTEGER timerValue; double GetResistance() { byte command[] = { 0xC1,0xD2,0x21 }; byte receive[] = { 0x0, 0x0, 0x0 }; DWORD bytesWrite = 0; DWORD bytesRead = 0; WriteFile(Resipod, command, 3, &bytesWrite, NULL); ReadFile(Resipod, receive, 3, &bytesRead, NULL); if (receive[0] != 0x02) { return(-1.0); } unsigned output1 = (receive[2] << 8) | (receive[1]); int reading = F10(output1, 0, 11); double resistance = reading; bool divide10 = F10(output1, 11, 12); if (divide10) { resistance = reading / 10.0; } return(resistance); } int InitializePort() { int userComPort = 3; std::cout << "Enter COM port number that Resipod is connected to: "; std::cin >> userComPort; std::wstringstream comPort; comPort << "\\\\.\\COM" << userComPort; std::cout << "\nChecking port COM" << userComPort << "..."; Resipod = CreateFile(comPort.str().c_str(), GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if (Resipod == INVALID_HANDLE_VALUE) { DWORD dwError = GetLastError(); if (dwError == ERROR_ACCESS_DENIED || dwError == ERROR_GEN_FAILURE || dwError == ERROR_SHARING_VIOLATION || dwError == ERROR_SEM_TIMEOUT) { std::cout << "resource in use and not usable\n"; } else { std::cout << "error opening port\n"; } return(0); } else { std::cout << "success!\n"; ResipodParam.DCBlength = sizeof(ResipodParam); // Hardcode serial parameters based on Resipod data ResipodParam.BaudRate = CBR_19200; ResipodParam.ByteSize = 8; ResipodParam.StopBits = 1; ResipodParam.Parity = NOPARITY; ResipodParam.fOutX = FALSE; ResipodParam.fInX = FALSE; ResipodParam.fTXContinueOnXoff = FALSE; SetCommState(Resipod, &ResipodParam); // Set some timeout values COMMTIMEOUTS timeouts = { 0 }; timeouts.ReadIntervalTimeout = 200; timeouts.ReadTotalTimeoutConstant = 1000; timeouts.ReadTotalTimeoutMultiplier = 1; timeouts.WriteTotalTimeoutConstant = 200; timeouts.WriteTotalTimeoutMultiplier = 1; // Get ID on port to see if it is a Proceq device /*byte command[] = { 0xC1,0xD2,0x21 }; byte getID[] = { 0x10,0x49,0x44,0x0D }; char receiveID[8] = {0}; char correctID[8] = "Resipod"; DWORD bytesWriteID = 0; DWORD bytesReadID = 0; WriteFile(Resipod, command, 3, &bytesWriteID, NULL); ReadFile(Resipod, receiveID, 3, &bytesReadID, NULL); WriteFile(Resipod, getID, 5, &bytesWriteID, NULL); ReadFile(Resipod, receiveID, 8, &bytesReadID, NULL); if (SetCommTimeouts(Resipod, &timeouts) == 0) { std::cout << "timeout\n"; } else { std::cout << receiveID << "\n"; if (strcmp(receiveID, correctID)) { return(j); } }*/ } return(userComPort); } void DisplayHeader() { std::cout << " /$$$$$$$ /$$$$$$$$ /$$$$$$ /$$$$$$ /$$$$$$ /$$$$$$$$ /$$$$$$ /$$$$$$$\n"; std::cout << " | $$__ $$| $$_____/ /$$__ $$|_ $$_/ /$$__ $$|__ $$__//$$__ $$| $$__ $$\n"; std::cout << " | $$ \\ $$| $$ | $$ \\__/ | $$ | $$ \\__/ | $$ | $$ \\ $$| $$ \\ $$\n"; std::cout << " | $$$$$$$/| $$$$$ | $$$$$$ | $$ | $$$$$$ | $$ | $$ | $$| $$$$$$$/\n"; std::cout << " | $$__ $$| $$__/ \\____ $$ | $$ \\____ $$ | $$ | $$ | $$| $$__ $$\n"; std::cout << " | $$ \\ $$| $$ /$$ \\ $$ | $$ /$$ \\ $$ | $$ | $$ | $$| $$ \\ $$\n"; std::cout << " | $$ | $$| $$$$$$$$| $$$$$$/ /$$$$$$| $$$$$$/ | $$ | $$$$$$/| $$ | $$\n"; std::cout << " |__/ |__/|________/ \\______/ |______/ \\______/ |__/ \\______/ |__/ |__/\n"; //std::cout << "\n\n Current code is in testing phase. Do NOT use for research purposes...\n\n"; } void DisplayMainMenu(){ std::cout << "##################################################################################\n"; std::cout << "# Main Menu #\n"; std::cout << "# 1) Take single immediate reading #\n"; std::cout << "# 2) Take multiple evenly spaced readings for defined length of time (NO!) #\n"; std::cout << "# 3) Take multiple evenly spaced readings for undefined length of time #\n"; std::cout << "# 4) Exit #\n"; std::cout << "# #\n"; std::cout << "##################################################################################\n"; } void UndefinedLengthTest(){ system("cls"); std::ofstream dataFile; std::string operatorName, projectName, specimenID, fileName; int lengthType, intervalType; double lengthTest, intervalTest; char dum; std::cout << "DEFINED LENGTH TEST SETUP\n"; std::cout << "Data file will be stored in same directory as this executable.\nYou may add any extension to it.\nDate and time are automatically pulled from this computer and added to data file.\n"; std::cout << "Filename: "; std::cin >> fileName; dataFile.open(fileName, std::ios::out); std::cout << "Operator Name: "; std::cin >> operatorName; dataFile << operatorName << std::endl; std::cout << "\nProject Name: "; std::cin >> projectName; dataFile << projectName << std::endl; std::cout << "\nSpecimen Name/ID: "; std::cin >> specimenID; dataFile << specimenID << std::endl; std::time_t curTime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); dataFile << curTime << std::endl; dataFile << "Time (min), Resistance (kOhms)" << std::endl; // Future work for defined length test function /*std::cout << "\nWould you like to enter the length of testing in\n1) minutes\n2) hours\n3) days\n4) weeks\nChoice: "; std::cin >> lengthType; std::cout << "\nHow long should the test run "; switch (lengthType){ case 1: std::cout << "(minutes): "; std::cin >> lengthTest; break; case 2: std::cout << "(hours): "; std::cin >> lengthTest; break; case 3: std::cout << "(days): "; std::cin >> lengthTest; break; case 4: std::cout << "(weeks): "; std::cin >> lengthTest; break; default: std::cout << "(INVALID CHOICE, RETURN TO MAIN MENU): "; std::cin >> lengthTest; return; break; }*/ std::cout << "\nWould you like to enter the interval of sampling in\n1) hertz\n2) minutes\nChoice: "; std::cin >> intervalType; switch (intervalType){ case 1: std::cout << "\nEnter sampling interval (Hz): "; std::cin >> intervalTest; intervalTest = 1.0 / intervalTest; break; case 2: std::cout << "\nEnter sampling interval (minutes): "; std::cin >> intervalTest; intervalTest = intervalTest * 60.0; break; default: std::cout << "\nINVALID CHOICE, RETURN TO MAIN MENU"; std::cin >> intervalTest; return; break; } // Get timer value ready. Value is in 100 nanosecond intervals timerValue.QuadPart = intervalTest*1E7; std::cout << "\nPress any key to start test..."; std::cin >> dum; bool stopRecording = false; int count = 0; timer = CreateWaitableTimer(NULL, TRUE, NULL); double tempResistance, tempTime; while (stopRecording == false){ SetWaitableTimer(timer, &timerValue, 0, NULL, NULL, 0); tempResistance = GetResistance(); tempTime = (double)(count*intervalTest) / 60; dataFile << tempTime << ", "; dataFile << tempResistance << std::endl; system("cls"); std::cout << "CURRENT TEST STATUS\n"; std::cout << tempTime << " minutes into testing.\n"; std::cout << count + 1 << " data points saved so far.\n"; std::cout << tempResistance << " kOhms (most current data point).\n\n"; std::cout << "Hit (ESC) key to stop data recording. Program will stop after next data point is collected..."; // Duct tape way to get a decent timer function if (WaitForSingleObject(timer, INFINITE) != WAIT_OBJECT_0) dataFile << "Timer function failed due to error code " << GetLastError(); else{ if (GetAsyncKeyState(VK_ESCAPE)){ stopRecording = true; } } } } int main() { char TestInterface; char dummy; int choice; DisplayHeader(); std::cout << "Initializing serial port interface..."; int PortOpen = InitializePort(); if (PortOpen = 0) { std::cout << "no Resipod device found!\n"; std::cout << "Press any key to terminate program..."; std::cin >> dummy; return(EXIT_FAILURE); } else { std::cout << "success!\n\n"; std::cout << "Resipod device is on COM" << PortOpen << "\n"; std::cout << "Press any key to continue..."; std::cin >> dummy; } do{ system("cls"); DisplayHeader(); DisplayMainMenu(); char dum; std::cout << "\n\n\nEnter choice: "; std::cin >> choice; switch (choice){ case 1: double resistance; std::cout << "\n\nMeasuring resistance..."; resistance = GetResistance(); if (resistance > 0){ std::cout << "success!\n\nResistance measured: " << resistance << " kOhms\n"; std::cout << "Press any key to return to main menu..."; std::cin >> dum; } else{ std::cout << "failure!\n\nReturn byte incorrect. Try again or check serial parameters...\n"; std::cout << "Press any key to return to main menu..."; std::cin >> dum; } break; case 2: //DefinedLengthTest(); std::cout << "\nNOT PROGRAMMED YET, RETURNING TO MAIN MENU! PRESS ANY KEY..."; std::cin >> dum; break; case 3: UndefinedLengthTest(); break; case 4: break; default: break; } } while (choice != 4); }<|endoftext|>
<commit_before>// ------------------------------------------------------------------------- // @FileName : NFIWS.h // @Author : Stone.xin // @Date : 2016-12-22 // @Module : NFIWS // ------------------------------------------------------------------------- #include "NFCWS.h" #include <string.h> #include <atomic> bool NFCWS::Execute() { m_EndPoint.poll(); return false; } int NFCWS::Initialization(const unsigned int nMaxClient, const unsigned short nPort, const int nCpuCount) { mnPort = nPort; mnMaxConnect = nMaxClient; mnCpuCount = nCpuCount; m_EndPoint.listen(nPort); m_EndPoint.start_accept(); return 0; } bool NFCWS::Final() { CloseSocketAll(); m_EndPoint.stop(); return true; } bool NFCWS::SendMsgToAllClient(const char * msg, const uint32_t nLen) { if (nLen <= 0) { return false; } session_list::iterator it = mmObject.begin(); while (it!=mmObject.end()) { WSObjectPtr pWSObject = it->second; if (pWSObject && !pWSObject->NeedRemove()) { try { m_EndPoint.send(it->first, msg, nLen, websocketpp::frame::opcode::TEXT); } catch (websocketpp::exception& e) { std::cout<<"websocket exception: "<<e.what()<<std::endl; return false; } } it++; } return true; } bool NFCWS::SendMsgToClient(const char * msg, const uint32_t nLen, std::vector<websocketpp::connection_hdl> vList) { for (auto vIt:vList) { auto pWSObject = GetNetObject(vIt); if (pWSObject && !pWSObject->NeedRemove()) { try { m_EndPoint.send(vIt, msg, nLen, websocketpp::frame::opcode::TEXT); } catch (websocketpp::exception& e) { std::cout << "websocket exception: " << e.what() << std::endl; return false; } } } } bool NFCWS::SendMsgToClient(const char * msg, const uint32_t nLen, websocketpp::connection_hdl hd) { auto pWSObject = GetNetObject(hd); if (pWSObject && !pWSObject->NeedRemove()) { try { m_EndPoint.send(hd, msg, nLen, websocketpp::frame::opcode::TEXT); } catch (websocketpp::exception& e) { std::cout << "websocket exception: " << e.what() << std::endl; return false; } } return true; } bool NFCWS::AddNetObject(websocketpp::connection_hdl hd,WSObjectPtr pWSObject) { auto pObject = GetNetObject(hd); if (pObject) { return false; } mmObject.emplace(session_list::value_type(hd,pWSObject)); return true; } WSObjectPtr NFCWS::GetNetObject(websocketpp::connection_hdl hd) { session_list::iterator it = mmObject.find(hd); if (it == mmObject.end()) { return nullptr; } return it->second; } void NFCWS::ExecuteClose() { for each (auto vIt in mvRemoveObject) { CloseObject(vIt); } mvRemoveObject.clear(); } bool NFCWS::CloseSocketAll() { session_list::iterator it = mmObject.begin(); for (it; it != mmObject.end(); ++it) { mvRemoveObject.push_back(it->first); } ExecuteClose(); mmObject.clear(); return true; } void NFCWS::CloseObject(websocketpp::connection_hdl hd, int nCloseCode/* =1000 */, const std::string& strCloseReason/* ="" */) { m_EndPoint.close(hd, nCloseCode, strCloseReason); } void NFCWS::OnMessageHandler(websocketpp::connection_hdl hd, NFWebSockConf::message_ptr msg) { auto pObject = GetNetObject(hd); if (!pObject) { return; } if (mRecvCB) { mRecvCB(hd,msg->get_payload()); } } void NFCWS::OnOpenHandler(websocketpp::connection_hdl hd) { WSObjectPtr pWSObject(NF_NEW(WSObject)); if (AddNetObject(hd,pWSObject)) { if (mEventCB) { mEventCB(hd, NF_WS_EVENT_OPEN); } } } bool NFCWS::RemoveConnection(websocketpp::connection_hdl hd, NF_WS_EVENT evt, int nCloseCode /* = 1000 */, const std::string& strCloseReason /* = "" */) { session_list::iterator it = mmObject.find(hd); if (it != mmObject.end()) { mvRemoveObject.push_back(hd); return true; } return false; } void NFCWS::OnCloseHandler(websocketpp::connection_hdl hd) { RemoveConnection(hd, NF_WS_EVENT_CLOSE); } void NFCWS::OnFailHandler(websocketpp::connection_hdl hd) { RemoveConnection(hd, NF_WS_EVENT_FAIL); } void NFCWS::OnInterruptHandler(websocketpp::connection_hdl hd) { RemoveConnection(hd, NF_WS_EVENT_INTERRUPT); } bool NFCWS::OnPongHandler(websocketpp::connection_hdl hd, std::string str) { return true; } void NFCWS::OnPongTimeOutHandler(websocketpp::connection_hdl hd, std::string str) { RemoveConnection(hd, NF_WS_EVENT_PONG_TIMEOUT); } <commit_msg>use poll_one instead of poll<commit_after>// ------------------------------------------------------------------------- // @FileName : NFIWS.h // @Author : Stone.xin // @Date : 2016-12-22 // @Module : NFIWS // ------------------------------------------------------------------------- #include "NFCWS.h" #include <string.h> #include <atomic> bool NFCWS::Execute() { m_EndPoint.poll_one(); return false; } int NFCWS::Initialization(const unsigned int nMaxClient, const unsigned short nPort, const int nCpuCount) { mnPort = nPort; mnMaxConnect = nMaxClient; mnCpuCount = nCpuCount; m_EndPoint.listen(nPort); m_EndPoint.start_accept(); return 0; } bool NFCWS::Final() { CloseSocketAll(); m_EndPoint.stop_listening(); return true; } bool NFCWS::SendMsgToAllClient(const char * msg, const uint32_t nLen) { if (nLen <= 0) { return false; } session_list::iterator it = mmObject.begin(); while (it!=mmObject.end()) { WSObjectPtr pWSObject = it->second; if (pWSObject && !pWSObject->NeedRemove()) { try { m_EndPoint.send(it->first, msg, nLen, websocketpp::frame::opcode::TEXT); } catch (websocketpp::exception& e) { std::cout<<"websocket exception: "<<e.what()<<std::endl; return false; } } it++; } return true; } bool NFCWS::SendMsgToClient(const char * msg, const uint32_t nLen, std::vector<websocketpp::connection_hdl> vList) { for (auto vIt:vList) { auto pWSObject = GetNetObject(vIt); if (pWSObject && !pWSObject->NeedRemove()) { try { m_EndPoint.send(vIt, msg, nLen, websocketpp::frame::opcode::TEXT); } catch (websocketpp::exception& e) { std::cout << "websocket exception: " << e.what() << std::endl; return false; } } } } bool NFCWS::SendMsgToClient(const char * msg, const uint32_t nLen, websocketpp::connection_hdl hd) { auto pWSObject = GetNetObject(hd); if (pWSObject && !pWSObject->NeedRemove()) { try { m_EndPoint.send(hd, msg, nLen, websocketpp::frame::opcode::TEXT); } catch (websocketpp::exception& e) { std::cout << "websocket exception: " << e.what() << std::endl; return false; } } return true; } bool NFCWS::AddNetObject(websocketpp::connection_hdl hd,WSObjectPtr pWSObject) { auto pObject = GetNetObject(hd); if (pObject) { return false; } mmObject.emplace(session_list::value_type(hd,pWSObject)); return true; } WSObjectPtr NFCWS::GetNetObject(websocketpp::connection_hdl hd) { session_list::iterator it = mmObject.find(hd); if (it == mmObject.end()) { return nullptr; } return it->second; } void NFCWS::ExecuteClose() { for each (auto vIt in mvRemoveObject) { CloseObject(vIt); } mvRemoveObject.clear(); } bool NFCWS::CloseSocketAll() { session_list::iterator it = mmObject.begin(); for (it; it != mmObject.end(); ++it) { mvRemoveObject.push_back(it->first); } ExecuteClose(); mmObject.clear(); return true; } void NFCWS::CloseObject(websocketpp::connection_hdl hd, int nCloseCode/* =1000 */, const std::string& strCloseReason/* ="" */) { m_EndPoint.close(hd, nCloseCode, strCloseReason); } void NFCWS::OnMessageHandler(websocketpp::connection_hdl hd, NFWebSockConf::message_ptr msg) { auto pObject = GetNetObject(hd); if (!pObject) { return; } if (mRecvCB) { mRecvCB(hd,msg->get_payload()); } } void NFCWS::OnOpenHandler(websocketpp::connection_hdl hd) { WSObjectPtr pWSObject(NF_NEW(WSObject)); if (AddNetObject(hd,pWSObject)) { if (mEventCB) { mEventCB(hd, NF_WS_EVENT_OPEN); } } } bool NFCWS::RemoveConnection(websocketpp::connection_hdl hd, NF_WS_EVENT evt, int nCloseCode /* = 1000 */, const std::string& strCloseReason /* = "" */) { session_list::iterator it = mmObject.find(hd); if (it != mmObject.end()) { mvRemoveObject.push_back(hd); return true; } return false; } void NFCWS::OnCloseHandler(websocketpp::connection_hdl hd) { RemoveConnection(hd, NF_WS_EVENT_CLOSE); } void NFCWS::OnFailHandler(websocketpp::connection_hdl hd) { RemoveConnection(hd, NF_WS_EVENT_FAIL); } void NFCWS::OnInterruptHandler(websocketpp::connection_hdl hd) { RemoveConnection(hd, NF_WS_EVENT_INTERRUPT); } bool NFCWS::OnPongHandler(websocketpp::connection_hdl hd, std::string str) { return true; } void NFCWS::OnPongTimeOutHandler(websocketpp::connection_hdl hd, std::string str) { RemoveConnection(hd, NF_WS_EVENT_PONG_TIMEOUT); } <|endoftext|>
<commit_before>// // Name: Contours.cpp // Purpose: Contour-related code, which interfaces vtlib to the // QuikGrid library. // // Copyright (c) 2004-2008 Virtual Terrain Project // Free for all uses, see license.txt for details. // #include "vtlib/vtlib.h" #if SUPPORT_QUIKGRID #include "vtdata/QuikGrid.h" #include "Contours.h" #include <vtlib/core/TiledGeom.h> // // This callback function will receive points output from QuikGrid. // void ReceiveContourPoint(void *context, float x, float y, bool bStart) { vtContourConverter *cc = (vtContourConverter *) context; cc->Coord(x, y, bStart); } ///////////////////////////////////////////////////////////////////////////// // class vtContourConverter vtContourConverter::vtContourConverter() { m_pMF = NULL; m_pGrid = NULL; } vtContourConverter::~vtContourConverter() { delete m_pMF; delete m_pGrid; } /** * Set up the class to do draping on a terrain. * * \param pTerr The terrain you will generate the contour lines on. * \param color The colors of the generated lines. * \param fHeight The height above the terrain to drape the lines. Generally * you will want to use a small offset value here, to keep the lines from * colliding with the terrain itself. * \return A geometry node which contains the contours. */ vtGeom *vtContourConverter::Setup(vtTerrain *pTerr, const RGBf &color, float fHeight) { if (!pTerr) return NULL; // Make a note of this terrain and its attributes m_pTerrain = pTerr; m_pHF = pTerr->GetHeightFieldGrid3d(); int tileLod0Size = 0; if (!m_pHF) { vtTiledGeom *tiledGeom = pTerr->GetTiledGeom(); m_ext = tiledGeom->GetEarthExtents(); //get highest LOD int minLod = 0; for(int i = 0; i < tiledGeom->rows * tiledGeom->rows; i++) if (tiledGeom->m_elev_info.lodmap.m_min[i] > minLod) minLod = tiledGeom->m_elev_info.lodmap.m_min[i]; tileLod0Size = pow(2.0, minLod); m_spacing = DPoint2(m_ext.Width() / (tiledGeom->cols * tileLod0Size), m_ext.Height() / (tiledGeom->rows *tileLod0Size)); } else { m_ext = m_pHF->GetEarthExtents(); m_spacing = m_pHF->GetSpacing(); } m_fHeight = fHeight; // Create material and geometry to contain the vector geometry vtMaterialArray *pMats = new vtMaterialArray; pMats->AddRGBMaterial1(color, false, false, true); m_pGeom = new vtGeom; m_pGeom->SetName2("Contour Geometry"); m_pGeom->SetMaterials(pMats); pMats->Release(); // pass ownership // copy data from our grid to a QuikGrid object int nx, ny; if (m_pHF) m_pHF->GetDimensions(nx, ny); else { vtTiledGeom *tiledGeom = pTerr->GetTiledGeom(); nx = tiledGeom->cols * tileLod0Size + 1; ny = tiledGeom->rows * tileLod0Size + 1; } m_pGrid = new SurfaceGrid(nx,ny); int i, j; if (m_pHF) { for (i = 0; i < nx; i++) { for (j = 0; j < ny; j++) { // use the true elevation, for true contours m_pGrid->zset(i, j, m_pHF->GetElevation(i, j, true)); } } } else { vtTiledGeom *tiledGeom = pTerr->GetTiledGeom(); float topBottom = tiledGeom->m_WorldExtents.top - tiledGeom->m_WorldExtents.bottom; float rightLeft = tiledGeom->m_WorldExtents.right - tiledGeom->m_WorldExtents.left; float rlxwidth = rightLeft / (tiledGeom->cols * tileLod0Size + 1); float tbywidth = topBottom / (tiledGeom->rows * tileLod0Size + 1); float altitude; for (i = 0; i < nx; i++) { for (j = 0; j < ny; j++) { // use the true elevation, for true contours tiledGeom->FindAltitudeAtPoint(FPoint3(i*rlxwidth, 0, j*tbywidth),altitude, true); m_pGrid->zset(i, j, altitude); } } } m_pMF = new vtMeshFactory(m_pGeom, vtMesh::LINE_STRIP, 0, 30000, 0); return m_pGeom; } /** * Generate a contour line to be draped on the terrain. * * \param fAlt The altitude (elevation) of the line to be generated. */ void vtContourConverter::GenerateContour(float fAlt) { SetQuikGridCallbackFunction(ReceiveContourPoint, this); Contour(*m_pGrid, fAlt); } /** * Generate a set of contour lines to be draped on the terrain. * * \param fInterval The vertical spacing between the contours. For example, * if the elevation range of your data is from 50 to 350 meters, then * an fIterval of 100 will place contour bands at 100,200,300 meters. */ void vtContourConverter::GenerateContours(float fInterval) { float fMin, fMax; if (m_pHF) m_pHF->GetHeightExtents(fMin, fMax); else m_pTerrain->GetTiledGeom()->GetHeightExtents(fMin, fMax); int start = (int) (fMin / fInterval) + 1; int stop = (int) (fMax / fInterval); SetQuikGridCallbackFunction(ReceiveContourPoint, this); for (int i = start; i <= stop; i++) Contour(*m_pGrid, i * fInterval); } void vtContourConverter::Coord(float x, float y, bool bStart) { if (bStart) Flush(); DPoint2 p2; p2.x = m_ext.left + x * m_spacing.x; p2.y = m_ext.bottom + y * m_spacing.y; m_line.Append(p2); } /** * Finishes the contour generation process. Call once when you are done * using the class to generate contours. */ void vtContourConverter::Finish() { Flush(); // Add the geometry to the terrain's scaled features, so that it will scale // up/down with the terrain's vertical exaggeration. m_pTerrain->GetScaledFeatures()->AddChild(m_pGeom); } void vtContourConverter::Flush() { if (m_line.GetSize() > 2) { bool bInterpolate = false; // no need; it already hugs the ground bool bCurve = false; // no need; it's already quite smooth bool bUseTrueElevation = true; // use true elevation, not scaled m_pTerrain->AddSurfaceLineToMesh(m_pMF, m_line, m_fHeight, bInterpolate, bCurve, bUseTrueElevation); } m_line.Empty(); } #endif // SUPPORT_QUIKGRID <commit_msg>avoid small compiler warning in contour module<commit_after>// // Name: Contours.cpp // Purpose: Contour-related code, which interfaces vtlib to the // QuikGrid library. // // Copyright (c) 2004-2008 Virtual Terrain Project // Free for all uses, see license.txt for details. // #include "vtlib/vtlib.h" #if SUPPORT_QUIKGRID #include "vtdata/QuikGrid.h" #include "Contours.h" #include <vtlib/core/TiledGeom.h> // // This callback function will receive points output from QuikGrid. // void ReceiveContourPoint(void *context, float x, float y, bool bStart) { vtContourConverter *cc = (vtContourConverter *) context; cc->Coord(x, y, bStart); } ///////////////////////////////////////////////////////////////////////////// // class vtContourConverter vtContourConverter::vtContourConverter() { m_pMF = NULL; m_pGrid = NULL; } vtContourConverter::~vtContourConverter() { delete m_pMF; delete m_pGrid; } /** * Set up the class to do draping on a terrain. * * \param pTerr The terrain you will generate the contour lines on. * \param color The colors of the generated lines. * \param fHeight The height above the terrain to drape the lines. Generally * you will want to use a small offset value here, to keep the lines from * colliding with the terrain itself. * \return A geometry node which contains the contours. */ vtGeom *vtContourConverter::Setup(vtTerrain *pTerr, const RGBf &color, float fHeight) { if (!pTerr) return NULL; // Make a note of this terrain and its attributes m_pTerrain = pTerr; m_pHF = pTerr->GetHeightFieldGrid3d(); int tileLod0Size = 0; if (!m_pHF) { vtTiledGeom *tiledGeom = pTerr->GetTiledGeom(); m_ext = tiledGeom->GetEarthExtents(); //get highest LOD int minLod = 0; for(int i = 0; i < tiledGeom->rows * tiledGeom->rows; i++) if (tiledGeom->m_elev_info.lodmap.m_min[i] > minLod) minLod = tiledGeom->m_elev_info.lodmap.m_min[i]; tileLod0Size = 1 << minLod; m_spacing = DPoint2(m_ext.Width() / (tiledGeom->cols * tileLod0Size), m_ext.Height() / (tiledGeom->rows *tileLod0Size)); } else { m_ext = m_pHF->GetEarthExtents(); m_spacing = m_pHF->GetSpacing(); } m_fHeight = fHeight; // Create material and geometry to contain the vector geometry vtMaterialArray *pMats = new vtMaterialArray; pMats->AddRGBMaterial1(color, false, false, true); m_pGeom = new vtGeom; m_pGeom->SetName2("Contour Geometry"); m_pGeom->SetMaterials(pMats); pMats->Release(); // pass ownership // copy data from our grid to a QuikGrid object int nx, ny; if (m_pHF) m_pHF->GetDimensions(nx, ny); else { vtTiledGeom *tiledGeom = pTerr->GetTiledGeom(); nx = tiledGeom->cols * tileLod0Size + 1; ny = tiledGeom->rows * tileLod0Size + 1; } m_pGrid = new SurfaceGrid(nx,ny); int i, j; if (m_pHF) { for (i = 0; i < nx; i++) { for (j = 0; j < ny; j++) { // use the true elevation, for true contours m_pGrid->zset(i, j, m_pHF->GetElevation(i, j, true)); } } } else { vtTiledGeom *tiledGeom = pTerr->GetTiledGeom(); float topBottom = tiledGeom->m_WorldExtents.top - tiledGeom->m_WorldExtents.bottom; float rightLeft = tiledGeom->m_WorldExtents.right - tiledGeom->m_WorldExtents.left; float rlxwidth = rightLeft / (tiledGeom->cols * tileLod0Size + 1); float tbywidth = topBottom / (tiledGeom->rows * tileLod0Size + 1); float altitude; for (i = 0; i < nx; i++) { for (j = 0; j < ny; j++) { // use the true elevation, for true contours tiledGeom->FindAltitudeAtPoint(FPoint3(i*rlxwidth, 0, j*tbywidth),altitude, true); m_pGrid->zset(i, j, altitude); } } } m_pMF = new vtMeshFactory(m_pGeom, vtMesh::LINE_STRIP, 0, 30000, 0); return m_pGeom; } /** * Generate a contour line to be draped on the terrain. * * \param fAlt The altitude (elevation) of the line to be generated. */ void vtContourConverter::GenerateContour(float fAlt) { SetQuikGridCallbackFunction(ReceiveContourPoint, this); Contour(*m_pGrid, fAlt); } /** * Generate a set of contour lines to be draped on the terrain. * * \param fInterval The vertical spacing between the contours. For example, * if the elevation range of your data is from 50 to 350 meters, then * an fIterval of 100 will place contour bands at 100,200,300 meters. */ void vtContourConverter::GenerateContours(float fInterval) { float fMin, fMax; if (m_pHF) m_pHF->GetHeightExtents(fMin, fMax); else m_pTerrain->GetTiledGeom()->GetHeightExtents(fMin, fMax); int start = (int) (fMin / fInterval) + 1; int stop = (int) (fMax / fInterval); SetQuikGridCallbackFunction(ReceiveContourPoint, this); for (int i = start; i <= stop; i++) Contour(*m_pGrid, i * fInterval); } void vtContourConverter::Coord(float x, float y, bool bStart) { if (bStart) Flush(); DPoint2 p2; p2.x = m_ext.left + x * m_spacing.x; p2.y = m_ext.bottom + y * m_spacing.y; m_line.Append(p2); } /** * Finishes the contour generation process. Call once when you are done * using the class to generate contours. */ void vtContourConverter::Finish() { Flush(); // Add the geometry to the terrain's scaled features, so that it will scale // up/down with the terrain's vertical exaggeration. m_pTerrain->GetScaledFeatures()->AddChild(m_pGeom); } void vtContourConverter::Flush() { if (m_line.GetSize() > 2) { bool bInterpolate = false; // no need; it already hugs the ground bool bCurve = false; // no need; it's already quite smooth bool bUseTrueElevation = true; // use true elevation, not scaled m_pTerrain->AddSurfaceLineToMesh(m_pMF, m_line, m_fHeight, bInterpolate, bCurve, bUseTrueElevation); } m_line.Empty(); } #endif // SUPPORT_QUIKGRID <|endoftext|>
<commit_before><commit_msg>fix typo<commit_after><|endoftext|>
<commit_before>#include <iostream> #include <thread> #include <chrono> #include <random> #include <time.h> #include <assert.h> #include "IntervalTree.h" using namespace std; typedef Interval<bool> interval; typedef vector<interval> intervalVector; typedef IntervalTree<bool> intervalTree; template<typename K> K randKey(K floor, K ceiling) { K range = ceiling - floor; return floor + range * ((double) rand() / (double) (RAND_MAX + 1.0)); } template<class T, typename K> Interval<T,K> randomInterval(K maxStart, K maxLength, K maxStop, const T& value) { K start = randKey<K>(0, maxStart); K stop = min<K>(randKey<K>(start, start + maxLength), maxStop); return Interval<T,K>(start, stop, value); } int main() { typedef vector<std::size_t> countsVector; // a simple sanity check intervalVector sanityIntervals; sanityIntervals.push_back(interval(60, 80, true)); sanityIntervals.push_back(interval(20, 40, true)); intervalTree sanityTree(sanityIntervals); intervalVector sanityResults; sanityTree.findOverlapping(30, 50, sanityResults); assert(sanityResults.size() == 1); sanityResults.clear(); sanityTree.findContained(15, 45, sanityResults); assert(sanityResults.size() == 1); srand((unsigned)time(NULL)); intervalVector intervals; intervalVector queries; // generate a test set of target intervals for (int i = 0; i < 10000; ++i) { intervals.push_back(randomInterval<bool, unsigned long>(100000, 1000, 100000 + 1, true)); } // and queries for (int i = 0; i < 5000; ++i) { queries.push_back(randomInterval<bool, unsigned long>(100000, 1000, 100000 + 1, true)); } typedef chrono::high_resolution_clock Clock; typedef chrono::milliseconds milliseconds; // using brute-force search countsVector bruteforcecounts; Clock::time_point t0 = Clock::now(); for (intervalVector::iterator q = queries.begin(); q != queries.end(); ++q) { intervalVector results; for (intervalVector::iterator i = intervals.begin(); i != intervals.end(); ++i) { if (i->start >= q->start && i->stop <= q->stop) { results.push_back(*i); } } bruteforcecounts.push_back(results.size()); } Clock::time_point t1 = Clock::now(); milliseconds ms = chrono::duration_cast<milliseconds>(t1 - t0); cout << "brute force:\t" << ms.count() << "ms" << endl; // using the interval tree intervalTree tree = intervalTree(intervals); countsVector treecounts; t0 = Clock::now(); for (intervalVector::iterator q = queries.begin(); q != queries.end(); ++q) { intervalVector results; tree.findContained(q->start, q->stop, results); treecounts.push_back(results.size()); } t1 = Clock::now(); ms = std::chrono::duration_cast<milliseconds>(t1 - t0); cout << "interval tree:\t" << ms.count() << "ms" << endl; // check that the same number of results are returned countsVector::iterator b = bruteforcecounts.begin(); for (countsVector::iterator t = treecounts.begin(); t != treecounts.end(); ++t, ++b) { assert(*b == *t); } return 0; } <commit_msg>Add code to run the test framework<commit_after>#include <iostream> #include <thread> #include <chrono> #include <random> #include <time.h> #include <assert.h> #include "IntervalTree.h" #define CATCH_CONFIG_RUNNER // Mark this as file as the test-runner for catch #include "catch.hpp" // Include the catch unit test framework using namespace std; typedef Interval<bool> interval; typedef vector<interval> intervalVector; typedef IntervalTree<bool> intervalTree; template<typename K> K randKey(K floor, K ceiling) { K range = ceiling - floor; return floor + range * ((double) rand() / (double) (RAND_MAX + 1.0)); } template<class T, typename K> Interval<T,K> randomInterval(K maxStart, K maxLength, K maxStop, const T& value) { K start = randKey<K>(0, maxStart); K stop = min<K>(randKey<K>(start, start + maxLength), maxStop); return Interval<T,K>(start, stop, value); } int main(int argc, char**argv) { typedef vector<std::size_t> countsVector; // a simple sanity check intervalVector sanityIntervals; sanityIntervals.push_back(interval(60, 80, true)); sanityIntervals.push_back(interval(20, 40, true)); intervalTree sanityTree(sanityIntervals); intervalVector sanityResults; sanityTree.findOverlapping(30, 50, sanityResults); assert(sanityResults.size() == 1); sanityResults.clear(); sanityTree.findContained(15, 45, sanityResults); assert(sanityResults.size() == 1); srand((unsigned)time(NULL)); intervalVector intervals; intervalVector queries; // generate a test set of target intervals for (int i = 0; i < 10000; ++i) { intervals.push_back(randomInterval<bool, unsigned long>(100000, 1000, 100000 + 1, true)); } // and queries for (int i = 0; i < 5000; ++i) { queries.push_back(randomInterval<bool, unsigned long>(100000, 1000, 100000 + 1, true)); } typedef chrono::high_resolution_clock Clock; typedef chrono::milliseconds milliseconds; // using brute-force search countsVector bruteforcecounts; Clock::time_point t0 = Clock::now(); for (intervalVector::iterator q = queries.begin(); q != queries.end(); ++q) { intervalVector results; for (intervalVector::iterator i = intervals.begin(); i != intervals.end(); ++i) { if (i->start >= q->start && i->stop <= q->stop) { results.push_back(*i); } } bruteforcecounts.push_back(results.size()); } Clock::time_point t1 = Clock::now(); milliseconds ms = chrono::duration_cast<milliseconds>(t1 - t0); cout << "brute force:\t" << ms.count() << "ms" << endl; // using the interval tree intervalTree tree = intervalTree(intervals); countsVector treecounts; t0 = Clock::now(); for (intervalVector::iterator q = queries.begin(); q != queries.end(); ++q) { intervalVector results; tree.findContained(q->start, q->stop, results); treecounts.push_back(results.size()); } t1 = Clock::now(); ms = std::chrono::duration_cast<milliseconds>(t1 - t0); cout << "interval tree:\t" << ms.count() << "ms" << endl; // check that the same number of results are returned countsVector::iterator b = bruteforcecounts.begin(); for (countsVector::iterator t = treecounts.begin(); t != treecounts.end(); ++t, ++b) { assert(*b == *t); } return Catch::Session().run( argc, argv ); } <|endoftext|>
<commit_before>#include <iostream> #include <thread> #include <chrono> #include <random> #include <time.h> #include <assert.h> #include "IntervalTree.h" using namespace std; typedef Interval<bool,int> interval; typedef vector<interval> intervalVector; typedef IntervalTree<bool,int> intervalTree; template<typename K> K randKey(K floor, K ceiling) { K range = ceiling - floor; return floor + range * ((double) rand() / (double) (RAND_MAX + 1.0)); } template<class T, typename K> Interval<T,K> randomInterval(K maxStart, K maxLength, K maxStop, const T& value) { K start = randKey<K>(0, maxStart); K stop = min<K>(randKey<K>(start, start + maxLength), maxStop); return Interval<T,K>(start, stop, value); } int main() { typedef vector<std::size_t> countsVector; srand((unsigned)time(NULL)); intervalVector intervals; intervalVector queries; // generate a test set of target intervals for (int i = 0; i < 10000; ++i) { intervals.push_back(randomInterval<bool,int>(100000, 1000, 100000 + 1, true)); } // and queries for (int i = 0; i < 5000; ++i) { queries.push_back(randomInterval<bool,int>(100000, 1000, 100000 + 1, true)); } typedef chrono::high_resolution_clock Clock; typedef chrono::milliseconds milliseconds; // using brute-force search countsVector bruteforcecounts; Clock::time_point t0 = Clock::now(); for (intervalVector::iterator q = queries.begin(); q != queries.end(); ++q) { intervalVector results; for (intervalVector::iterator i = intervals.begin(); i != intervals.end(); ++i) { if (i->start >= q->start && i->stop <= q->stop) { results.push_back(*i); } } bruteforcecounts.push_back(results.size()); } Clock::time_point t1 = Clock::now(); milliseconds ms = chrono::duration_cast<milliseconds>(t1 - t0); cout << "brute force:\t" << ms.count() << "ms" << endl; // using the interval tree //IntervalTree<bool> tree(intervals); intervalTree tree; tree = intervalTree(intervals); countsVector treecounts; t0 = Clock::now(); for (intervalVector::iterator q = queries.begin(); q != queries.end(); ++q) { intervalVector results; tree.findContained(q->start, q->stop, results); treecounts.push_back(results.size()); } t1 = Clock::now(); ms = std::chrono::duration_cast<milliseconds>(t1 - t0); cout << "interval tree:\t" << ms.count() << "ms" << endl; // check that the same number of results are returned countsVector::iterator b = bruteforcecounts.begin(); for (countsVector::iterator t = treecounts.begin(); t != treecounts.end(); ++t, ++b) { assert(*b == *t); } return 0; } <commit_msg>Cleanup.<commit_after>#include <iostream> #include <thread> #include <chrono> #include <random> #include <time.h> #include <assert.h> #include "IntervalTree.h" using namespace std; typedef Interval<bool,int> interval; typedef vector<interval> intervalVector; typedef IntervalTree<bool,int> intervalTree; template<typename K> K randKey(K floor, K ceiling) { K range = ceiling - floor; return floor + range * ((double) rand() / (double) (RAND_MAX + 1.0)); } template<class T, typename K> Interval<T,K> randomInterval(K maxStart, K maxLength, K maxStop, const T& value) { K start = randKey<K>(0, maxStart); K stop = min<K>(randKey<K>(start, start + maxLength), maxStop); return Interval<T,K>(start, stop, value); } int main() { typedef vector<std::size_t> countsVector; srand((unsigned)time(NULL)); intervalVector intervals; intervalVector queries; // generate a test set of target intervals for (int i = 0; i < 10000; ++i) { intervals.push_back(randomInterval<bool,int>(100000, 1000, 100000 + 1, true)); } // and queries for (int i = 0; i < 5000; ++i) { queries.push_back(randomInterval<bool,int>(100000, 1000, 100000 + 1, true)); } typedef chrono::high_resolution_clock Clock; typedef chrono::milliseconds milliseconds; // using brute-force search countsVector bruteforcecounts; Clock::time_point t0 = Clock::now(); for (intervalVector::iterator q = queries.begin(); q != queries.end(); ++q) { intervalVector results; for (intervalVector::iterator i = intervals.begin(); i != intervals.end(); ++i) { if (i->start >= q->start && i->stop <= q->stop) { results.push_back(*i); } } bruteforcecounts.push_back(results.size()); } Clock::time_point t1 = Clock::now(); milliseconds ms = chrono::duration_cast<milliseconds>(t1 - t0); cout << "brute force:\t" << ms.count() << "ms" << endl; // using the interval tree intervalTree tree = intervalTree(intervals); countsVector treecounts; t0 = Clock::now(); for (intervalVector::iterator q = queries.begin(); q != queries.end(); ++q) { intervalVector results; tree.findContained(q->start, q->stop, results); treecounts.push_back(results.size()); } t1 = Clock::now(); ms = std::chrono::duration_cast<milliseconds>(t1 - t0); cout << "interval tree:\t" << ms.count() << "ms" << endl; // check that the same number of results are returned countsVector::iterator b = bruteforcecounts.begin(); for (countsVector::iterator t = treecounts.begin(); t != treecounts.end(); ++t, ++b) { assert(*b == *t); } return 0; } <|endoftext|>
<commit_before>#include "utils.h" #include "crypto/sha2.h" #include "flaggedarrayset.h" #include "relayprocess.h" #include <stdio.h> #include <sys/time.h> #include <algorithm> #include <random> #include <string.h> #include <unistd.h> void do_nothing(...) {} #ifdef BENCH #define PRINT_TIME do_nothing #else #define PRINT_TIME printf #endif std::linear_congruential_engine<std::uint_fast32_t, 48271, 0, 2147483647> engine(42); void fill_txv(std::vector<unsigned char>& block, std::vector<std::shared_ptr<std::vector<unsigned char> > >& txVectors, float includeP) { std::vector<unsigned char>::const_iterator readit = block.begin(); move_forward(readit, sizeof(struct bitcoin_msg_header), block.end()); move_forward(readit, 80, block.end()); uint32_t txcount = read_varint(readit, block.end()); std::uniform_real_distribution<double> distribution(0.0, 1.0); for (uint32_t i = 0; i < txcount; i++) { std::vector<unsigned char>::const_iterator txstart = readit; move_forward(readit, 4, block.end()); uint32_t txins = read_varint(readit, block.end()); for (uint32_t j = 0; j < txins; j++) { move_forward(readit, 36, block.end()); uint32_t scriptlen = read_varint(readit, block.end()); move_forward(readit, scriptlen + 4, block.end()); } uint32_t txouts = read_varint(readit, block.end()); for (uint32_t j = 0; j < txouts; j++) { move_forward(readit, 8, block.end()); uint32_t scriptlen = read_varint(readit, block.end()); move_forward(readit, scriptlen, block.end()); } move_forward(readit, 4, block.end()); if (distribution(engine) < includeP) txVectors.push_back(std::make_shared<std::vector<unsigned char> >(txstart, readit)); } std::shuffle(txVectors.begin(), txVectors.end(), engine); } int pipefd[2]; uint32_t block_tx_count; std::shared_ptr<std::vector<unsigned char> > decompressed_block; RelayNodeCompressor receiver; void recv_block() { struct timeval start, decompressed; gettimeofday(&start, NULL); auto res = receiver.decompress_relay_block(pipefd[0], block_tx_count); gettimeofday(&decompressed, NULL); if (std::get<2>(res)) { printf("ERROR Decompressing block %s\n", std::get<2>(res)); exit(2); } else PRINT_TIME("Decompressed block in %lu ms\n", int64_t(decompressed.tv_sec - start.tv_sec)*1000 + (int64_t(decompressed.tv_usec) - start.tv_usec)/1000); decompressed_block = std::get<1>(res); } void test_compress_block(std::vector<unsigned char>& data, std::vector<std::shared_ptr<std::vector<unsigned char> > > txVectors) { std::vector<unsigned char> fullhash(32); getblockhash(fullhash, data, sizeof(struct bitcoin_msg_header)); RelayNodeCompressor sender, tester; receiver.reset(); for (auto& v : txVectors) { unsigned int made = sender.get_relay_transaction(v).use_count(); if (made) receiver.recv_tx(v); if (made != tester.get_relay_transaction(v).use_count()) { printf("get_relay_transaction behavior not consistent???\n"); exit(5); } } unsigned int i = 0; sender.for_each_sent_tx([&](std::shared_ptr<std::vector<unsigned char> > tx) { ssize_t index = std::max((ssize_t)0, (ssize_t)txVectors.size() - 1525) + i++; if (tx != txVectors[index]) { printf("for_each_sent_tx was not in order!\n"); exit(6); } if (tester.send_tx_cache.remove(0) != txVectors[index]) { printf("for_each_sent_tx output did not match remove(0)\n"); exit(7); } }); struct timeval start, compressed; gettimeofday(&start, NULL); auto res = sender.maybe_compress_block(fullhash, data, true); gettimeofday(&compressed, NULL); PRINT_TIME("Compressed from %lu to %lu in %ld ms with %lu txn pre-relayed\n", data.size(), std::get<0>(res)->size(), int64_t(compressed.tv_sec - start.tv_sec)*1000 + (int64_t(compressed.tv_usec) - start.tv_usec)/1000, txVectors.size()); struct relay_msg_header header; memcpy(&header, &(*std::get<0>(res))[0], sizeof(header)); block_tx_count = ntohl(header.length); if (pipe(pipefd)) { printf("Failed to create pipe?\n"); exit(3); } std::thread recv(recv_block); write(pipefd[1], &(*std::get<0>(res))[sizeof(header)], std::get<0>(res)->size() - sizeof(header)); recv.join(); if (*decompressed_block != data) { printf("Re-constructed block did not match!\n"); exit(4); } close(pipefd[0]); close(pipefd[1]); } void run_test(std::vector<unsigned char>& data) { std::vector<std::shared_ptr<std::vector<unsigned char> > > txVectors; test_compress_block(data, txVectors); fill_txv(data, txVectors, 1.0); test_compress_block(data, txVectors); txVectors.clear(); fill_txv(data, txVectors, 0.5); test_compress_block(data, txVectors); txVectors.clear(); fill_txv(data, txVectors, 0.9); test_compress_block(data, txVectors); } int main() { std::vector<unsigned char> data(sizeof(struct bitcoin_msg_header)); std::vector<unsigned char> lastBlock; std::vector<std::shared_ptr<std::vector<unsigned char> > > allTxn; FILE* f = fopen("block.txt", "r"); while (true) { char hex[2]; if (fread(hex, 1, 1, f) != 1) break; else if (hex[0] == '\n') { if (data.size()) { #ifdef BENCH for (int i = 0; i < 1000; i++) #endif run_test(data); fill_txv(data, allTxn, 0.9); lastBlock = data; } data = std::vector<unsigned char>(sizeof(struct bitcoin_msg_header)); } else if (fread(hex + 1, 1, 1, f) != 1) break; else { if (hex[0] >= 'a') hex[0] -= 'a' - '9' - 1; if (hex[1] >= 'a') hex[1] -= 'a' - '9' - 1; data.push_back((hex[0] - '0') << 4 | (hex[1] - '0')); } } #ifdef BENCH for (int i = 0; i < 1000; i++) #endif test_compress_block(lastBlock, allTxn); return 0; } <commit_msg>Run slightly fewer iterations<commit_after>#include "utils.h" #include "crypto/sha2.h" #include "flaggedarrayset.h" #include "relayprocess.h" #include <stdio.h> #include <sys/time.h> #include <algorithm> #include <random> #include <string.h> #include <unistd.h> void do_nothing(...) {} #ifdef BENCH #define PRINT_TIME do_nothing #else #define PRINT_TIME printf #endif std::linear_congruential_engine<std::uint_fast32_t, 48271, 0, 2147483647> engine(42); void fill_txv(std::vector<unsigned char>& block, std::vector<std::shared_ptr<std::vector<unsigned char> > >& txVectors, float includeP) { std::vector<unsigned char>::const_iterator readit = block.begin(); move_forward(readit, sizeof(struct bitcoin_msg_header), block.end()); move_forward(readit, 80, block.end()); uint32_t txcount = read_varint(readit, block.end()); std::uniform_real_distribution<double> distribution(0.0, 1.0); for (uint32_t i = 0; i < txcount; i++) { std::vector<unsigned char>::const_iterator txstart = readit; move_forward(readit, 4, block.end()); uint32_t txins = read_varint(readit, block.end()); for (uint32_t j = 0; j < txins; j++) { move_forward(readit, 36, block.end()); uint32_t scriptlen = read_varint(readit, block.end()); move_forward(readit, scriptlen + 4, block.end()); } uint32_t txouts = read_varint(readit, block.end()); for (uint32_t j = 0; j < txouts; j++) { move_forward(readit, 8, block.end()); uint32_t scriptlen = read_varint(readit, block.end()); move_forward(readit, scriptlen, block.end()); } move_forward(readit, 4, block.end()); if (distribution(engine) < includeP) txVectors.push_back(std::make_shared<std::vector<unsigned char> >(txstart, readit)); } std::shuffle(txVectors.begin(), txVectors.end(), engine); } int pipefd[2]; uint32_t block_tx_count; std::shared_ptr<std::vector<unsigned char> > decompressed_block; RelayNodeCompressor receiver; void recv_block() { struct timeval start, decompressed; gettimeofday(&start, NULL); auto res = receiver.decompress_relay_block(pipefd[0], block_tx_count); gettimeofday(&decompressed, NULL); if (std::get<2>(res)) { printf("ERROR Decompressing block %s\n", std::get<2>(res)); exit(2); } else PRINT_TIME("Decompressed block in %lu ms\n", int64_t(decompressed.tv_sec - start.tv_sec)*1000 + (int64_t(decompressed.tv_usec) - start.tv_usec)/1000); decompressed_block = std::get<1>(res); } void test_compress_block(std::vector<unsigned char>& data, std::vector<std::shared_ptr<std::vector<unsigned char> > > txVectors) { std::vector<unsigned char> fullhash(32); getblockhash(fullhash, data, sizeof(struct bitcoin_msg_header)); RelayNodeCompressor sender, tester; receiver.reset(); for (auto& v : txVectors) { unsigned int made = sender.get_relay_transaction(v).use_count(); if (made) receiver.recv_tx(v); if (made != tester.get_relay_transaction(v).use_count()) { printf("get_relay_transaction behavior not consistent???\n"); exit(5); } } unsigned int i = 0; sender.for_each_sent_tx([&](std::shared_ptr<std::vector<unsigned char> > tx) { ssize_t index = std::max((ssize_t)0, (ssize_t)txVectors.size() - 1525) + i++; if (tx != txVectors[index]) { printf("for_each_sent_tx was not in order!\n"); exit(6); } if (tester.send_tx_cache.remove(0) != txVectors[index]) { printf("for_each_sent_tx output did not match remove(0)\n"); exit(7); } }); struct timeval start, compressed; gettimeofday(&start, NULL); auto res = sender.maybe_compress_block(fullhash, data, true); gettimeofday(&compressed, NULL); PRINT_TIME("Compressed from %lu to %lu in %ld ms with %lu txn pre-relayed\n", data.size(), std::get<0>(res)->size(), int64_t(compressed.tv_sec - start.tv_sec)*1000 + (int64_t(compressed.tv_usec) - start.tv_usec)/1000, txVectors.size()); struct relay_msg_header header; memcpy(&header, &(*std::get<0>(res))[0], sizeof(header)); block_tx_count = ntohl(header.length); if (pipe(pipefd)) { printf("Failed to create pipe?\n"); exit(3); } std::thread recv(recv_block); write(pipefd[1], &(*std::get<0>(res))[sizeof(header)], std::get<0>(res)->size() - sizeof(header)); recv.join(); if (*decompressed_block != data) { printf("Re-constructed block did not match!\n"); exit(4); } close(pipefd[0]); close(pipefd[1]); } void run_test(std::vector<unsigned char>& data) { std::vector<std::shared_ptr<std::vector<unsigned char> > > txVectors; test_compress_block(data, txVectors); fill_txv(data, txVectors, 1.0); test_compress_block(data, txVectors); txVectors.clear(); fill_txv(data, txVectors, 0.5); test_compress_block(data, txVectors); txVectors.clear(); fill_txv(data, txVectors, 0.9); test_compress_block(data, txVectors); } int main() { std::vector<unsigned char> data(sizeof(struct bitcoin_msg_header)); std::vector<unsigned char> lastBlock; std::vector<std::shared_ptr<std::vector<unsigned char> > > allTxn; FILE* f = fopen("block.txt", "r"); while (true) { char hex[2]; if (fread(hex, 1, 1, f) != 1) break; else if (hex[0] == '\n') { if (data.size()) { #ifdef BENCH for (int i = 0; i < 300; i++) #endif run_test(data); fill_txv(data, allTxn, 0.9); lastBlock = data; } data = std::vector<unsigned char>(sizeof(struct bitcoin_msg_header)); } else if (fread(hex + 1, 1, 1, f) != 1) break; else { if (hex[0] >= 'a') hex[0] -= 'a' - '9' - 1; if (hex[1] >= 'a') hex[1] -= 'a' - '9' - 1; data.push_back((hex[0] - '0') << 4 | (hex[1] - '0')); } } #ifdef BENCH for (int i = 0; i < 300; i++) #endif test_compress_block(lastBlock, allTxn); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2010 - 2013 Leap Motion. All rights reserved. Proprietary and confidential. #include "stdafx.h" #include "ScopeTest.h" #include "GlobalCoreContext.h" #include "Autowired.h" TEST_F(ScopeTest, VerifyGlobalExists) { // Verify that we at least get a global scope AutoGlobalContext global; EXPECT_TRUE(nullptr != global.get()) << "Failed to autowire the global context"; } <commit_msg>expanded on scoping test<commit_after>// Copyright (c) 2010 - 2013 Leap Motion. All rights reserved. Proprietary and confidential. #include "stdafx.h" #include "ScopeTest.h" #include "GlobalCoreContext.h" #include "Autowired.h" TEST_F(ScopeTest, VerifyGlobalExists) { // Verify that we at least get a global scope AutoGlobalContext global; EXPECT_TRUE(nullptr != global.get()) << "Failed to autowire the global context"; } class A : public ContextMember {}; class B : public ContextMember {}; TEST_F(ScopeTest, VerifyInherit) { AutoCurrentContext ctxt; //Add a member to the current context ctxt->Add<A>(); std::shared_ptr<CoreContext> pContext = ctxt->CreateAnonymous(); //Create and switch to a sub-context { CurrentContextPusher pusher; pContext->SetCurrent(); EXPECT_TRUE(ctxt.get() != pContext.get()) << "Failed to create a sub-context"; //try and autowire a member from the parent context Autowired<A> autoA; EXPECT_FALSE(!autoA.get()) << "Autowired member not wired from parent context"; //add a member in the subcontext pContext->Add<B>(); } Autowired<B> autoB; EXPECT_TRUE(!autoB.get()) << "Autowired member wired from sub-context"; }<|endoftext|>
<commit_before>//System includes #include <fstream> #include <iostream> #include <ctime> #include <string> #include <cstdlib> #include <iomanip> // Point #include "point.h" // Ugly fixes #include <assert.h> // Kratos Independent #define KRATOS_INDEPENDENT #ifndef KRATOS_INDEPENDENT #define KRATOS_ERROR std::cout // Kratos includes #include "spatial_containers/spatial_containers.h" #endif // KRATOS_INDEPENDENT #include "points_bins.h" #include "points_hash.h" double GetCurrentTime() { #ifndef _OPENMP return std::clock() / static_cast<double>(CLOCKS_PER_SEC); #else return omp_get_wtime(); #endif } template< class T, std::size_t dim > class PointDistance2 { public: double operator()(T const& p1, T const& p2) { double dist = 0.0; for (std::size_t i = 0; i < dim; i++) { double tmp = p1[i] - p2[i]; dist += tmp*tmp; } return dist; } }; template<class SearchStructureType, class PointType, class IteratorType, class DistanceIterator> void RunTestsOldInterface(char const Title[], IteratorType PBegin, IteratorType PEnd, IteratorType results0, DistanceIterator distances0, std::size_t MaxResults, PointType* allPoints, double radius0, std::size_t numsearch, std::size_t bucket_size) { double t0, t1; std::size_t n; std::size_t npoints = PEnd - PBegin; std::vector<std::size_t> numresArray(numsearch); PointType& point0 = allPoints[0]; std::size_t numsearch_nearest = 10 * numsearch; t0 = GetCurrentTime(); SearchStructureType nodes_tree(PBegin, PEnd); t1 = GetCurrentTime(); std::cout << Title << "\t" << t1 - t0 << "\t"; t0 = GetCurrentTime(); #pragma omp parallel for for (std::size_t i = 0; i < numsearch; i++) { n = nodes_tree.SearchInRadius(point0, radius0, results0, distances0, MaxResults); } t1 = GetCurrentTime(); std::cout << t1 - t0 << "\t"; t0 = GetCurrentTime(); for (std::size_t i = 0; i < numsearch; i++) { n = nodes_tree.SearchInRadius(point0, radius0, results0, distances0, MaxResults); } t1 = GetCurrentTime(); std::cout << t1 - t0 << "\t"; PointType** PNearestArray = new PointType*[numsearch]; std::vector<double> distancesArrayNearest(numsearch); PointType* PNearest = PNearestArray[0]; t0 = GetCurrentTime(); for (std::size_t i = 0; i < 10; i++) { nodes_tree.SearchNearestPoint(allPoints, numsearch, PNearestArray, distancesArrayNearest); } t1 = GetCurrentTime(); std::cout << t1 - t0 << "\t"; double distance = 0; t0 = GetCurrentTime(); for (std::size_t i = 0; i < numsearch_nearest; i++) { PNearest = nodes_tree.SearchNearestPoint(point0, distance); } t1 = GetCurrentTime(); std::cout << t1 - t0 << "\t"; std::cout << n << "\t" << *PNearestArray[0] << std::endl; }; template<class BinsType> void RunTestsNewInterface(char const Title[], std::vector<Point<3>> & points_vector, const Point<3> & search_point, double radius, std::size_t numsearch, std::size_t numsearch_nearest) { double t0 = GetCurrentTime(); BinsType bins(points_vector.begin(), points_vector.end()); double t1 = GetCurrentTime(); std::cout << "Points Bin" << "\t" << t1 - t0 << "\t"; std::vector<PointsBins<Point<3>>::ResultType> results; PointsBins<Point<3>>::ResultType nearest_point_result; t0 = GetCurrentTime(); #pragma omp parallel for firstprivate(results) for (std::size_t i = 0; i < numsearch; i++) { results.clear(); bins.SearchInRadius(search_point, radius, results); } t1 = GetCurrentTime(); std::cout << t1 - t0 << "\t"; t0 = GetCurrentTime(); for (std::size_t i = 0; i < numsearch; i++) { results.clear(); bins.SearchInRadius(search_point, radius, results); } t1 = GetCurrentTime(); std::cout << t1 - t0 << "\t"; t0 = GetCurrentTime(); #pragma omp parallel for firstprivate(nearest_point_result) for (std::size_t i = 0; i < numsearch_nearest; i++) { nearest_point_result = bins.SearchNearest(search_point); } t1 = GetCurrentTime(); std::cout << t1 - t0 << "\t"; t0 = GetCurrentTime(); for (std::size_t i = 0; i < numsearch_nearest; i++) { nearest_point_result = bins.SearchNearest(search_point); } t1 = GetCurrentTime(); std::cout << t1 - t0 << "\t" << results.size() << "\t" << *nearest_point_result.Get(); std::cout << std::endl; } int RunPointSearchComparison(std::string Filename, double Radius) { constexpr std::size_t Dim = 3; typedef Point<Dim> PointType; typedef PointType * PtrPointType; typedef PtrPointType * PointVector; typedef PtrPointType * PointIterator; typedef double* DistanceVector; typedef double* DistanceIterator; #ifndef KRATOS_INDEPENDENT typedef Kratos::Bucket<Dim, PointType, PointVector, PtrPointType, PointIterator, DistanceIterator, PointDistance2<PointType, Dim>> bucket_type; //Bucket; typedef Kratos::Bins<Dim, PointType, PointVector, PtrPointType, PointIterator, DistanceIterator, PointDistance2<PointType, Dim>> StaticBinsType; //StaticBins; typedef Kratos::BinsDynamic<Dim, PointType, PointVector, PtrPointType, PointIterator, DistanceIterator, PointDistance2<PointType, Dim>> DynamicBinsType; //DynamicBins; typedef Kratos::Tree< Kratos::KDTreePartition<bucket_type>> kdtree_type; //Kdtree; typedef Kratos::Tree< Kratos::KDTreePartitionAverageSplit<bucket_type>> kdtree_average_split_type; //Kdtree; typedef Kratos::Tree< Kratos::KDTreePartitionMidPointSplit<bucket_type>> kdtree_midpoint_split_type; //Kdtree; typedef Kratos::Tree< Kratos::OCTreePartition<bucket_type>> OctreeType; //Octree; typedef Kratos::Tree< Kratos::KDTreePartitionMidPointSplit<StaticBinsType>> kdtree_StaticBinsType; //KdtreeBins; typedef Kratos::Tree< Kratos::OCTreePartition<StaticBinsType>> octree_StaticBinsType; //OctreeBins; typedef Kratos::Tree< Kratos::KDTreePartitionMidPointSplit<DynamicBinsType>> kdtree_DynamicBinsType; //KdtreeBins; typedef Kratos::Tree< Kratos::OCTreePartition<DynamicBinsType>> octree_bins_type; //OctreeBins; #endif // KRATOS_INDEPENDENT // Input data std::cout << std::setprecision(4) << std::fixed; PointVector points; std::ifstream input; input.open(Filename.c_str()); if (!input) { std::cout << "Cannot open data file" << std::endl; return 0; } std::cout << "Comparison for " << Filename << std::endl; PointType point; std::size_t npoints; input >> npoints; points = new PointType*[npoints]; std::size_t pid; for (std::size_t i = 0; i < npoints; i++) { input >> pid; input >> point; points[i] = new PointType(point); points[i]->id = pid; } PointType min_point(*points[0]); PointType max_point(*points[0]); PointType mid_point; min_point.id = 0; max_point.id = 0; mid_point.id = 0; for (std::size_t i = 0; i < npoints; i++) { for (std::size_t j = 0; j < 3; j++) { if (min_point[j] > (*points[i])[j]) min_point[j] = (*points[i])[j]; if (max_point[j] < (*points[i])[j]) max_point[j] = (*points[i])[j]; } } for (std::size_t i = 0; i < Dim; i++) { mid_point.coord[i] = (max_point[i] + min_point[i]) / 2.00; } // Output data Info PointType & search_point = mid_point; std::size_t numsearch = 100000; std::size_t numsearch_nearest = numsearch * 10; std::cout << " min point : " << min_point << std::endl; std::cout << " max point : " << max_point << std::endl; std::cout << " search_point : " << search_point << std::endl; std::cout << " search radius : " << Radius << std::endl; std::cout << std::endl; std::cout << " Number of Points : " << npoints << std::endl; std::cout << " Number of Repetitions : " << numsearch << std::endl; std::cout << std::endl; std::cout << "SS\t\tGEN\tSIROMP\tSIRSER\tSNPOMP\tSNPSER\tNOFR\tNP" << std::endl; // Data Setup PointType * allPoints; allPoints = new PointType[numsearch]; std::size_t max_results = npoints; for (std::size_t i = 0; i < 1; i++) { allPoints[i] = search_point; } //Prepare the search point, search radius and resut arrays DistanceIterator distances = new double[npoints]; PointIterator p_results = new PtrPointType[max_results]; // Point-Based Search Structures std::vector<Point<3>> points_vector; for (std::size_t i = 0; i < npoints; i++) { points_vector.push_back(*(points[i])); } // New Interface RunTestsNewInterface<PointsBins<Point<3>>>("PointBins", points_vector, search_point, Radius, numsearch, numsearch_nearest); // Old Interface #ifndef KRATOS_INDEPENDENT RunTestsOldInterface<StaticBinsType>("StaticBins", points, points + npoints, p_results, distances, max_results, allPoints, Radius, numsearch, 1); RunTestsOldInterface<DynamicBinsType>("DynamicBins", points, points + npoints, p_results, distances, max_results, allPoints, Radius, numsearch, 1); RunTestsOldInterface<OctreeType>("OcTree\t", points, points + npoints, p_results, distances, max_results, allPoints, Radius, numsearch, 10); //RunTestsOldInterface<kdtree_type>("KdTree\t", points, points + npoints, p_results, distances, max_results, allPoints, radius, numsearch, 10); //RunTestsOldInterface<kdtree_average_split_type>("KdTreeAverage", points, points + npoints, resultsArray, distancesArray, max_results, allPoints, radiusArray, numsearch, 10); //RunTestsOldInterface<kdtree_midpoint_split_type>("KdTreeMidpoint", points, points + npoints, resultsArray, distancesArray, max_results, allPoints, radiusArray, numsearch, 10); #endif // KRATOS_INDEPENDENT return 0; } int main(int arg, char* argv[]) { std::string filename; double radius = 0.01; if (arg > 1) { std::cout << "Argument not founded " << std::endl; filename = argv[1]; if (arg == 3) { radius = atof(argv[2]) / 1000000; } return 0; } filename = "genericCube100x100x100.5051.pts"; RunPointSearchComparison(filename, radius); filename = "offsetCube79x79x79.1603.pts"; RunPointSearchComparison(filename, radius); filename = "clusterCube6x6x6X4913.490.pts"; RunPointSearchComparison(filename, radius); filename = "line100000.5.pts"; RunPointSearchComparison(filename, radius); return 0; } <commit_msg>Adding the omp.h include<commit_after>//System includes #include <fstream> #include <iostream> #include <ctime> #include <string> #include <cstdlib> #include <iomanip> #ifdef _OPENMP #include <omp.h> #endif // Point #include "point.h" // Ugly fixes #include <assert.h> // Kratos Independent #define KRATOS_INDEPENDENT #ifndef KRATOS_INDEPENDENT #define KRATOS_ERROR std::cout // Kratos includes #include "spatial_containers/spatial_containers.h" #endif // KRATOS_INDEPENDENT #include "points_bins.h" #include "points_hash.h" double GetCurrentTime() { #ifndef _OPENMP return std::clock() / static_cast<double>(CLOCKS_PER_SEC); #else return omp_get_wtime(); #endif } template< class T, std::size_t dim > class PointDistance2 { public: double operator()(T const& p1, T const& p2) { double dist = 0.0; for (std::size_t i = 0; i < dim; i++) { double tmp = p1[i] - p2[i]; dist += tmp*tmp; } return dist; } }; template<class SearchStructureType, class PointType, class IteratorType, class DistanceIterator> void RunTestsOldInterface(char const Title[], IteratorType PBegin, IteratorType PEnd, IteratorType results0, DistanceIterator distances0, std::size_t MaxResults, PointType* allPoints, double radius0, std::size_t numsearch, std::size_t bucket_size) { double t0, t1; std::size_t n; std::size_t npoints = PEnd - PBegin; std::vector<std::size_t> numresArray(numsearch); PointType& point0 = allPoints[0]; std::size_t numsearch_nearest = 10 * numsearch; t0 = GetCurrentTime(); SearchStructureType nodes_tree(PBegin, PEnd); t1 = GetCurrentTime(); std::cout << Title << "\t" << t1 - t0 << "\t"; t0 = GetCurrentTime(); #pragma omp parallel for for (std::size_t i = 0; i < numsearch; i++) { n = nodes_tree.SearchInRadius(point0, radius0, results0, distances0, MaxResults); } t1 = GetCurrentTime(); std::cout << t1 - t0 << "\t"; t0 = GetCurrentTime(); for (std::size_t i = 0; i < numsearch; i++) { n = nodes_tree.SearchInRadius(point0, radius0, results0, distances0, MaxResults); } t1 = GetCurrentTime(); std::cout << t1 - t0 << "\t"; PointType** PNearestArray = new PointType*[numsearch]; std::vector<double> distancesArrayNearest(numsearch); PointType* PNearest = PNearestArray[0]; t0 = GetCurrentTime(); for (std::size_t i = 0; i < 10; i++) { nodes_tree.SearchNearestPoint(allPoints, numsearch, PNearestArray, distancesArrayNearest); } t1 = GetCurrentTime(); std::cout << t1 - t0 << "\t"; double distance = 0; t0 = GetCurrentTime(); for (std::size_t i = 0; i < numsearch_nearest; i++) { PNearest = nodes_tree.SearchNearestPoint(point0, distance); } t1 = GetCurrentTime(); std::cout << t1 - t0 << "\t"; std::cout << n << "\t" << *PNearestArray[0] << std::endl; }; template<class BinsType> void RunTestsNewInterface(char const Title[], std::vector<Point<3>> & points_vector, const Point<3> & search_point, double radius, std::size_t numsearch, std::size_t numsearch_nearest) { double t0 = GetCurrentTime(); BinsType bins(points_vector.begin(), points_vector.end()); double t1 = GetCurrentTime(); std::cout << "Points Bin" << "\t" << t1 - t0 << "\t"; std::vector<PointsBins<Point<3>>::ResultType> results; PointsBins<Point<3>>::ResultType nearest_point_result; t0 = GetCurrentTime(); #pragma omp parallel for firstprivate(results) for (std::size_t i = 0; i < numsearch; i++) { results.clear(); bins.SearchInRadius(search_point, radius, results); } t1 = GetCurrentTime(); std::cout << t1 - t0 << "\t"; t0 = GetCurrentTime(); for (std::size_t i = 0; i < numsearch; i++) { results.clear(); bins.SearchInRadius(search_point, radius, results); } t1 = GetCurrentTime(); std::cout << t1 - t0 << "\t"; t0 = GetCurrentTime(); #pragma omp parallel for firstprivate(nearest_point_result) for (std::size_t i = 0; i < numsearch_nearest; i++) { nearest_point_result = bins.SearchNearest(search_point); } t1 = GetCurrentTime(); std::cout << t1 - t0 << "\t"; t0 = GetCurrentTime(); for (std::size_t i = 0; i < numsearch_nearest; i++) { nearest_point_result = bins.SearchNearest(search_point); } t1 = GetCurrentTime(); std::cout << t1 - t0 << "\t" << results.size() << "\t" << *nearest_point_result.Get(); std::cout << std::endl; } int RunPointSearchComparison(std::string Filename, double Radius) { constexpr std::size_t Dim = 3; typedef Point<Dim> PointType; typedef PointType * PtrPointType; typedef PtrPointType * PointVector; typedef PtrPointType * PointIterator; typedef double* DistanceVector; typedef double* DistanceIterator; #ifndef KRATOS_INDEPENDENT typedef Kratos::Bucket<Dim, PointType, PointVector, PtrPointType, PointIterator, DistanceIterator, PointDistance2<PointType, Dim>> bucket_type; //Bucket; typedef Kratos::Bins<Dim, PointType, PointVector, PtrPointType, PointIterator, DistanceIterator, PointDistance2<PointType, Dim>> StaticBinsType; //StaticBins; typedef Kratos::BinsDynamic<Dim, PointType, PointVector, PtrPointType, PointIterator, DistanceIterator, PointDistance2<PointType, Dim>> DynamicBinsType; //DynamicBins; typedef Kratos::Tree< Kratos::KDTreePartition<bucket_type>> kdtree_type; //Kdtree; typedef Kratos::Tree< Kratos::KDTreePartitionAverageSplit<bucket_type>> kdtree_average_split_type; //Kdtree; typedef Kratos::Tree< Kratos::KDTreePartitionMidPointSplit<bucket_type>> kdtree_midpoint_split_type; //Kdtree; typedef Kratos::Tree< Kratos::OCTreePartition<bucket_type>> OctreeType; //Octree; typedef Kratos::Tree< Kratos::KDTreePartitionMidPointSplit<StaticBinsType>> kdtree_StaticBinsType; //KdtreeBins; typedef Kratos::Tree< Kratos::OCTreePartition<StaticBinsType>> octree_StaticBinsType; //OctreeBins; typedef Kratos::Tree< Kratos::KDTreePartitionMidPointSplit<DynamicBinsType>> kdtree_DynamicBinsType; //KdtreeBins; typedef Kratos::Tree< Kratos::OCTreePartition<DynamicBinsType>> octree_bins_type; //OctreeBins; #endif // KRATOS_INDEPENDENT // Input data std::cout << std::setprecision(4) << std::fixed; PointVector points; std::ifstream input; input.open(Filename.c_str()); if (!input) { std::cout << "Cannot open data file" << std::endl; return 0; } std::cout << "Comparison for " << Filename << std::endl; PointType point; std::size_t npoints; input >> npoints; points = new PointType*[npoints]; std::size_t pid; for (std::size_t i = 0; i < npoints; i++) { input >> pid; input >> point; points[i] = new PointType(point); points[i]->id = pid; } PointType min_point(*points[0]); PointType max_point(*points[0]); PointType mid_point; min_point.id = 0; max_point.id = 0; mid_point.id = 0; for (std::size_t i = 0; i < npoints; i++) { for (std::size_t j = 0; j < 3; j++) { if (min_point[j] > (*points[i])[j]) min_point[j] = (*points[i])[j]; if (max_point[j] < (*points[i])[j]) max_point[j] = (*points[i])[j]; } } for (std::size_t i = 0; i < Dim; i++) { mid_point.coord[i] = (max_point[i] + min_point[i]) / 2.00; } // Output data Info PointType & search_point = mid_point; std::size_t numsearch = 100000; std::size_t numsearch_nearest = numsearch * 10; std::cout << " min point : " << min_point << std::endl; std::cout << " max point : " << max_point << std::endl; std::cout << " search_point : " << search_point << std::endl; std::cout << " search radius : " << Radius << std::endl; std::cout << std::endl; std::cout << " Number of Points : " << npoints << std::endl; std::cout << " Number of Repetitions : " << numsearch << std::endl; std::cout << std::endl; std::cout << "SS\t\tGEN\tSIROMP\tSIRSER\tSNPOMP\tSNPSER\tNOFR\tNP" << std::endl; // Data Setup PointType * allPoints; allPoints = new PointType[numsearch]; std::size_t max_results = npoints; for (std::size_t i = 0; i < 1; i++) { allPoints[i] = search_point; } //Prepare the search point, search radius and resut arrays DistanceIterator distances = new double[npoints]; PointIterator p_results = new PtrPointType[max_results]; // Point-Based Search Structures std::vector<Point<3>> points_vector; for (std::size_t i = 0; i < npoints; i++) { points_vector.push_back(*(points[i])); } // New Interface RunTestsNewInterface<PointsBins<Point<3>>>("PointBins", points_vector, search_point, Radius, numsearch, numsearch_nearest); // Old Interface #ifndef KRATOS_INDEPENDENT RunTestsOldInterface<StaticBinsType>("StaticBins", points, points + npoints, p_results, distances, max_results, allPoints, Radius, numsearch, 1); RunTestsOldInterface<DynamicBinsType>("DynamicBins", points, points + npoints, p_results, distances, max_results, allPoints, Radius, numsearch, 1); RunTestsOldInterface<OctreeType>("OcTree\t", points, points + npoints, p_results, distances, max_results, allPoints, Radius, numsearch, 10); //RunTestsOldInterface<kdtree_type>("KdTree\t", points, points + npoints, p_results, distances, max_results, allPoints, radius, numsearch, 10); //RunTestsOldInterface<kdtree_average_split_type>("KdTreeAverage", points, points + npoints, resultsArray, distancesArray, max_results, allPoints, radiusArray, numsearch, 10); //RunTestsOldInterface<kdtree_midpoint_split_type>("KdTreeMidpoint", points, points + npoints, resultsArray, distancesArray, max_results, allPoints, radiusArray, numsearch, 10); #endif // KRATOS_INDEPENDENT return 0; } int main(int arg, char* argv[]) { std::string filename; double radius = 0.01; if (arg > 1) { std::cout << "Argument not founded " << std::endl; filename = argv[1]; if (arg == 3) { radius = atof(argv[2]) / 1000000; } return 0; } filename = "genericCube100x100x100.5051.pts"; RunPointSearchComparison(filename, radius); filename = "offsetCube79x79x79.1603.pts"; RunPointSearchComparison(filename, radius); filename = "clusterCube6x6x6X4913.490.pts"; RunPointSearchComparison(filename, radius); filename = "line100000.5.pts"; RunPointSearchComparison(filename, radius); return 0; } <|endoftext|>
<commit_before>/* * Polyphase channelizer * * Copyright (C) 2012-2014 Tom Tsou <[email protected]> * Copyright (C) 2015 Ettus Research LLC * * SPDX-License-Identifier: AGPL-3.0+ * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * See the COPYING file in the main directory for details. */ #include <malloc.h> #include <math.h> #include <assert.h> #include <string.h> #include <cstdio> #include "Logger.h" #include "ChannelizerBase.h" extern "C" { #include "fft.h" } static float sinc(float x) { if (x == 0.0f) return 0.999999999999f; return sin(M_PI * x) / (M_PI * x); } /* * There are more efficient reversal algorithms, but we only reverse at * initialization so we don't care. */ static void reverse(float *buf, size_t len) { float tmp[2 * len]; memcpy(tmp, buf, 2 * len * sizeof(float)); for (size_t i = 0; i < len; i++) { buf[2 * i + 0] = tmp[2 * (len - 1 - i) + 0]; buf[2 * i + 1] = tmp[2 * (len - 1 - i) + 1]; } } /* * Create polyphase filterbank * * Implementation based material found in, * * "harris, fred, Multirate Signal Processing, Upper Saddle River, NJ, * Prentice Hall, 2006." */ bool ChannelizerBase::initFilters() { size_t protoLen = m * hLen; float *proto; float sum = 0.0f, scale = 0.0f; float midpt = (float) (protoLen - 1.0) / 2.0; /* * Allocate 'M' partition filters and the temporary prototype * filter. Coefficients are real only and must be 16-byte memory * aligned for SSE usage. */ proto = new float[protoLen]; if (!proto) return false; subFilters = (float **) malloc(sizeof(float *) * m); if (!subFilters) { delete[] proto; return false; } for (size_t i = 0; i < m; i++) { subFilters[i] = (float *) memalign(16, hLen * 2 * sizeof(float)); } /* * Generate the prototype filter with a Blackman-harris window. * Scale coefficients with DC filter gain set to unity divided * by the number of channels. */ float a0 = 0.35875; float a1 = 0.48829; float a2 = 0.14128; float a3 = 0.01168; for (size_t i = 0; i < protoLen; i++) { proto[i] = sinc(((float) i - midpt) / (float) m); proto[i] *= a0 - a1 * cos(2 * M_PI * i / (protoLen - 1)) + a2 * cos(4 * M_PI * i / (protoLen - 1)) - a3 * cos(6 * M_PI * i / (protoLen - 1)); sum += proto[i]; } scale = (float) m / sum; /* * Populate partition filters and reverse the coefficients per * convolution requirements. */ for (size_t i = 0; i < hLen; i++) { for (size_t n = 0; n < m; n++) { subFilters[n][2 * i + 0] = proto[i * m + n] * scale; subFilters[n][2 * i + 1] = 0.0f; } } for (size_t i = 0; i < m; i++) reverse(subFilters[i], hLen); delete[] proto; return true; } bool ChannelizerBase::initFFT() { size_t size; if (fftInput || fftOutput || fftHandle) return false; size = blockLen * m * 2 * sizeof(float); fftInput = (float *) fft_malloc(size); memset(fftInput, 0, size); size = (blockLen + hLen) * m * 2 * sizeof(float); fftOutput = (float *) fft_malloc(size); memset(fftOutput, 0, size); if (!fftInput | !fftOutput) { LOG(ALERT) << "Memory allocation error"; return false; } fftHandle = init_fft(0, m, blockLen, blockLen + hLen, fftInput, fftOutput, hLen); return true; } bool ChannelizerBase::mapBuffers() { if (!fftHandle) { LOG(ALERT) << "FFT buffers not initialized"; return false; } hInputs = (float **) malloc(sizeof(float *) * m); hOutputs = (float **) malloc(sizeof(float *) * m); if (!hInputs | !hOutputs) return false; for (size_t i = 0; i < m; i++) { hInputs[i] = &fftOutput[2 * (i * (blockLen + hLen) + hLen)]; hOutputs[i] = &fftInput[2 * (i * blockLen)]; } return true; } /* * Setup filterbank internals */ bool ChannelizerBase::init() { /* * Filterbank coefficients, fft plan, history, and output sample * rate conversion blocks */ if (!initFilters()) { LOG(ALERT) << "Failed to initialize channelizing filter"; return false; } hist = (float **) malloc(sizeof(float *) * m); for (size_t i = 0; i < m; i++) { hist[i] = new float[2 * hLen]; memset(hist[i], 0, 2 * hLen * sizeof(float)); } if (!initFFT()) { LOG(ALERT) << "Failed to initialize FFT"; return false; } mapBuffers(); return true; } /* Check vector length validity */ bool ChannelizerBase::checkLen(size_t innerLen, size_t outerLen) { if (outerLen != innerLen * m) { LOG(ALERT) << "Invalid outer length " << innerLen << " is not multiple of " << blockLen; return false; } if (innerLen != blockLen) { LOG(ALERT) << "Invalid inner length " << outerLen << " does not equal " << blockLen; return false; } return true; } /* * Setup channelizer parameters */ ChannelizerBase::ChannelizerBase(size_t m, size_t blockLen, size_t hLen) : subFilters(NULL), hInputs(NULL), hOutputs(NULL), hist(NULL), fftInput(NULL), fftOutput(NULL), fftHandle(NULL) { this->m = m; this->hLen = hLen; this->blockLen = blockLen; } ChannelizerBase::~ChannelizerBase() { free_fft(fftHandle); for (size_t i = 0; i < m; i++) { free(subFilters[i]); delete[] hist[i]; } fft_free(fftInput); fft_free(fftOutput); free(hInputs); free(hOutputs); free(hist); } <commit_msg>ChannelizerBase: Fix memory leak<commit_after>/* * Polyphase channelizer * * Copyright (C) 2012-2014 Tom Tsou <[email protected]> * Copyright (C) 2015 Ettus Research LLC * * SPDX-License-Identifier: AGPL-3.0+ * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * See the COPYING file in the main directory for details. */ #include <malloc.h> #include <math.h> #include <assert.h> #include <string.h> #include <cstdio> #include "Logger.h" #include "ChannelizerBase.h" extern "C" { #include "fft.h" } static float sinc(float x) { if (x == 0.0f) return 0.999999999999f; return sin(M_PI * x) / (M_PI * x); } /* * There are more efficient reversal algorithms, but we only reverse at * initialization so we don't care. */ static void reverse(float *buf, size_t len) { float tmp[2 * len]; memcpy(tmp, buf, 2 * len * sizeof(float)); for (size_t i = 0; i < len; i++) { buf[2 * i + 0] = tmp[2 * (len - 1 - i) + 0]; buf[2 * i + 1] = tmp[2 * (len - 1 - i) + 1]; } } /* * Create polyphase filterbank * * Implementation based material found in, * * "harris, fred, Multirate Signal Processing, Upper Saddle River, NJ, * Prentice Hall, 2006." */ bool ChannelizerBase::initFilters() { size_t protoLen = m * hLen; float *proto; float sum = 0.0f, scale = 0.0f; float midpt = (float) (protoLen - 1.0) / 2.0; /* * Allocate 'M' partition filters and the temporary prototype * filter. Coefficients are real only and must be 16-byte memory * aligned for SSE usage. */ proto = new float[protoLen]; if (!proto) return false; subFilters = (float **) malloc(sizeof(float *) * m); if (!subFilters) { delete[] proto; return false; } for (size_t i = 0; i < m; i++) { subFilters[i] = (float *) memalign(16, hLen * 2 * sizeof(float)); } /* * Generate the prototype filter with a Blackman-harris window. * Scale coefficients with DC filter gain set to unity divided * by the number of channels. */ float a0 = 0.35875; float a1 = 0.48829; float a2 = 0.14128; float a3 = 0.01168; for (size_t i = 0; i < protoLen; i++) { proto[i] = sinc(((float) i - midpt) / (float) m); proto[i] *= a0 - a1 * cos(2 * M_PI * i / (protoLen - 1)) + a2 * cos(4 * M_PI * i / (protoLen - 1)) - a3 * cos(6 * M_PI * i / (protoLen - 1)); sum += proto[i]; } scale = (float) m / sum; /* * Populate partition filters and reverse the coefficients per * convolution requirements. */ for (size_t i = 0; i < hLen; i++) { for (size_t n = 0; n < m; n++) { subFilters[n][2 * i + 0] = proto[i * m + n] * scale; subFilters[n][2 * i + 1] = 0.0f; } } for (size_t i = 0; i < m; i++) reverse(subFilters[i], hLen); delete[] proto; return true; } bool ChannelizerBase::initFFT() { size_t size; if (fftInput || fftOutput || fftHandle) return false; size = blockLen * m * 2 * sizeof(float); fftInput = (float *) fft_malloc(size); memset(fftInput, 0, size); size = (blockLen + hLen) * m * 2 * sizeof(float); fftOutput = (float *) fft_malloc(size); memset(fftOutput, 0, size); if (!fftInput | !fftOutput) { LOG(ALERT) << "Memory allocation error"; return false; } fftHandle = init_fft(0, m, blockLen, blockLen + hLen, fftInput, fftOutput, hLen); return true; } bool ChannelizerBase::mapBuffers() { if (!fftHandle) { LOG(ALERT) << "FFT buffers not initialized"; return false; } hInputs = (float **) malloc(sizeof(float *) * m); hOutputs = (float **) malloc(sizeof(float *) * m); if (!hInputs | !hOutputs) return false; for (size_t i = 0; i < m; i++) { hInputs[i] = &fftOutput[2 * (i * (blockLen + hLen) + hLen)]; hOutputs[i] = &fftInput[2 * (i * blockLen)]; } return true; } /* * Setup filterbank internals */ bool ChannelizerBase::init() { /* * Filterbank coefficients, fft plan, history, and output sample * rate conversion blocks */ if (!initFilters()) { LOG(ALERT) << "Failed to initialize channelizing filter"; return false; } hist = (float **) malloc(sizeof(float *) * m); for (size_t i = 0; i < m; i++) { hist[i] = new float[2 * hLen]; memset(hist[i], 0, 2 * hLen * sizeof(float)); } if (!initFFT()) { LOG(ALERT) << "Failed to initialize FFT"; return false; } mapBuffers(); return true; } /* Check vector length validity */ bool ChannelizerBase::checkLen(size_t innerLen, size_t outerLen) { if (outerLen != innerLen * m) { LOG(ALERT) << "Invalid outer length " << innerLen << " is not multiple of " << blockLen; return false; } if (innerLen != blockLen) { LOG(ALERT) << "Invalid inner length " << outerLen << " does not equal " << blockLen; return false; } return true; } /* * Setup channelizer parameters */ ChannelizerBase::ChannelizerBase(size_t m, size_t blockLen, size_t hLen) : subFilters(NULL), hInputs(NULL), hOutputs(NULL), hist(NULL), fftInput(NULL), fftOutput(NULL), fftHandle(NULL) { this->m = m; this->hLen = hLen; this->blockLen = blockLen; } ChannelizerBase::~ChannelizerBase() { free_fft(fftHandle); for (size_t i = 0; i < m; i++) { free(subFilters[i]); delete[] hist[i]; } free(subFilters); fft_free(fftInput); fft_free(fftOutput); free(hInputs); free(hOutputs); free(hist); } <|endoftext|>
<commit_before>/** * \file scheme.cpp * \date 2015 */ #include <string> #include <iostream> #include <uscheme/defs.hpp> void usage(void) { std::cout << "\n" "usage: scheme [-h]\n" "\n" "Scheme interpreter using libuscheme.\n" "\n" "libuscheme version: " << uscheme::version() << "\n" << "\n"; } void usage_and_die(void) { usage(); exit(1); } int main(int argc, const char* argv[]) { if (argc != 2) { usage_and_die(); } std::string arg1(argv[1]); if (arg1 != "-h") { usage_and_die(); } else { usage(); } return 0; } <commit_msg>Add copyright to scheme.cpp<commit_after>/* Copyright (c) 2015, Aaditya Kalsi 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. */ /** * \file scheme.cpp * \date 2015 */ #include <string> #include <iostream> #include <uscheme/defs.hpp> void usage(void) { std::cout << "\n" "usage: scheme [-h]\n" "\n" "Scheme interpreter using libuscheme.\n" "\n" "libuscheme version: " << uscheme::version() << "\n" << "\n"; } void usage_and_die(void) { usage(); exit(1); } int main(int argc, const char* argv[]) { if (argc != 2) { usage_and_die(); } std::string arg1(argv[1]); if (arg1 != "-h") { usage_and_die(); } else { usage(); } return 0; } <|endoftext|>
<commit_before>/* * Copyright 2006-2008 The FLWOR Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <iostream> #include <cassert> #include <zorba/zorba.h> #include <zorba/debugger_client.h> #include <zorba/debugger_default_event_handler.h> #include <simplestore/simplestore.h> #include <zorbautils/thread.h> #include <zorbaerrors/errors.h> #ifdef WIN32 #include <windows.h> #define sleep(s) Sleep(s*1000) #endif using namespace zorba; class MyDebuggerEventHandler: public DefaultDebuggerEventHandler { public: virtual ~MyDebuggerEventHandler(){} void started() { std::cerr << "Query started" << std::endl; } void idle() { std::cerr << "Query idle" << std::endl; } void suspended( QueryLocation &aLocation, SuspendedBy aCause ) { std::cerr << "Suspended at line: " << aLocation.getLineBegin(); } void resumed() { std::cerr << "Query resumed" << std::endl; } void terminated() { std::cerr << "Query terminated" << std::endl; } void evaluated( String &anExpr, String &aResult, String &aReturnType, String &anError ) { if ( anError == "" ) { std::cerr << anExpr << ": " << aResult << std::endl; } else { std::cerr << anError << std::endl; } } }; ZORBA_THREAD_RETURN runClient( void* ) { sleep(3); MyDebuggerEventHandler lEventHandler; ZorbaDebuggerClient * lClient = ZorbaDebuggerClient::createClient( 8000, 9000 ); lClient->registerEventHandler( &lEventHandler ); lClient->run(); sleep(1); lClient->quit(); delete lClient; return 0; } bool debugger_example_1(Zorba *aZorba) { XQuery_t lQuery = aZorba->createQuery(); lQuery->setDebugMode(true); lQuery->compile("for $i in ( 1 to 10 ) return $i"); lQuery->debug(); lQuery->close(); return true; } bool debugger_example_2(Zorba *aZorba) { XQuery_t lQuery = aZorba->createQuery(); lQuery->setFileName("foo.xq"); lQuery->setDebugMode(true); assert(lQuery->getDebugMode()); lQuery->compile("1+2"); lQuery->debug( 8000, 9000 ); lQuery->close(); return true; } bool debugger_example_3(Zorba *aZorba) { try { XQuery_t lQuery = aZorba->createQuery(); lQuery->compile("1+2"); lQuery->debug(); lQuery->close(); } catch( error::ZorbaError &e ) { return true; } return false; } int debugger( int argc, char *argv[] ) { simplestore::SimpleStore *lStore = simplestore::SimpleStoreManager::getStore(); Zorba *lZorba = Zorba::getInstance( lStore ); bool res = false; { Thread lThread(runClient, 0); std::cout << "executing example 1" << std::endl; res = debugger_example_1(lZorba); lThread.join(); if ( !res ) return 1; std::cout << std::endl; } { Thread lThread(runClient, 0); std::cout << "executing example 2" << std::endl; res = debugger_example_2(lZorba); lThread.join(); if ( !res ) return 1; std::cout << std::endl; } { std::cout << "executing example 3" << std::endl; res = debugger_example_3(lZorba); if ( !res ) return 1; std::cout << std::endl; } lZorba->shutdown(); simplestore::SimpleStoreManager::shutdownStore(lStore); return 0; } <commit_msg>Remove illegal dependency: zorbautils/thread.h<commit_after>/* * Copyright 2006-2008 The FLWOR Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <iostream> #include <cassert> #include <zorba/zorba.h> #include <zorba/debugger_client.h> #include <zorba/debugger_default_event_handler.h> #include <simplestore/simplestore.h> #include <zorbaerrors/errors.h> #ifdef WIN32 #include <windows.h> #define sleep(s) Sleep(s*1000) #endif #ifdef ZORBA_HAVE_PTHREAD_H #include <pthread.h> #define ZORBA_THREAD_RETURN void * #else #define ZORBA_THREAD_RETURN DWORD WINAPI #endif using namespace zorba; class MyDebuggerEventHandler: public DefaultDebuggerEventHandler { public: virtual ~MyDebuggerEventHandler(){} void started() { std::cerr << "Query started" << std::endl; } void idle() { std::cerr << "Query idle" << std::endl; } void suspended( QueryLocation &aLocation, SuspendedBy aCause ) { std::cerr << "Suspended at line: " << aLocation.getLineBegin(); } void resumed() { std::cerr << "Query resumed" << std::endl; } void terminated() { std::cerr << "Query terminated" << std::endl; } void evaluated( String &anExpr, String &aResult, String &aReturnType, String &anError ) { if ( anError == "" ) { std::cerr << anExpr << ": " << aResult << std::endl; } else { std::cerr << anError << std::endl; } } }; ZORBA_THREAD_RETURN runClient( void* ) { sleep(3); MyDebuggerEventHandler lEventHandler; ZorbaDebuggerClient * lClient = ZorbaDebuggerClient::createClient( 8000, 9000 ); lClient->registerEventHandler( &lEventHandler ); lClient->run(); sleep(1); lClient->quit(); delete lClient; return 0; } bool debugger_example_1(Zorba *aZorba) { XQuery_t lQuery = aZorba->createQuery(); lQuery->setDebugMode(true); lQuery->compile("for $i in ( 1 to 10 ) return $i"); lQuery->debug(); lQuery->close(); return true; } bool debugger_example_2(Zorba *aZorba) { XQuery_t lQuery = aZorba->createQuery(); lQuery->setFileName("foo.xq"); lQuery->setDebugMode(true); assert(lQuery->getDebugMode()); lQuery->compile("1+2"); lQuery->debug( 8000, 9000 ); lQuery->close(); return true; } bool debugger_example_3(Zorba *aZorba) { try { XQuery_t lQuery = aZorba->createQuery(); lQuery->compile("1+2"); lQuery->debug(); lQuery->close(); } catch( error::ZorbaError &e ) { return true; } return false; } int debugger( int argc, char *argv[] ) { simplestore::SimpleStore *lStore = simplestore::SimpleStoreManager::getStore(); Zorba *lZorba = Zorba::getInstance( lStore ); bool res = false; { #ifdef ZORBA_HAVE_PTHREAD_H pthread_t lThread; if ( pthread_create( &lThread, 0, runClient, 0 ) != 0 ) #else HANDLE lThread; if ( ( lThread = CreateThread(0, 0, runClient, 0, 0, 0) ) == 0 ) #endif { std::cerr << "Couldn't start the thread" << std::endl; return 1; } std::cout << "executing example 1" << std::endl; res = debugger_example_1(lZorba); #ifdef ZORBA_HAVE_PTHREAD_H pthread_join( lThread, 0 ); #else WaitForSingleObject( lThread, INFINITE ); #endif if ( !res ) return 1; std::cout << std::endl; } { std::cout << "executing example 2" << std::endl; #ifdef ZORBA_HAVE_PTHREAD_H pthread_t lThread; if ( pthread_create( &lThread, 0, runClient, 0 ) != 0 ) #else HANDLE lThread; if ( ( lThread = CreateThread(0, 0, runClient, 0, 0, 0) ) == 0 ) #endif { std::cerr << "Couldn't start the thread" << std::endl; return 1; } res = debugger_example_2(lZorba); #ifdef ZORBA_HAVE_PTHREAD_H pthread_join( lThread, 0 ); #else WaitForSingleObject( lThread, INFINITE ); #endif if ( !res ) return 1; std::cout << std::endl; } { std::cout << "executing example 3" << std::endl; res = debugger_example_3(lZorba); if ( !res ) return 1; std::cout << std::endl; } lZorba->shutdown(); simplestore::SimpleStoreManager::shutdownStore(lStore); return 0; } <|endoftext|>
<commit_before>/* * Copyright 2006-2008 The FLWOR Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <iostream> #include <cassert> #include <zorba/zorba.h> #include <zorba/debugger_client.h> #include <zorba/debugger_default_event_handler.h> #include <simplestore/simplestore.h> #ifdef WIN32 #include <windows.h> #define sleep(s) Sleep(s*1000) #endif #ifdef ZORBA_HAVE_PTHREAD_H #include <pthread.h> #define ZORBA_THREAD_RETURN void * #else #define ZORBA_THREAD_RETURN DWORD WINAPI #endif using namespace zorba; class MyDebuggerEventHandler: public DefaultDebuggerEventHandler { public: virtual ~MyDebuggerEventHandler(){} void started() { std::cerr << "Query started" << std::endl; } void idle() { std::cerr << "Query idle" << std::endl; } void suspended( QueryLocation &aLocation, SuspendedBy aCause ) { std::cerr << "Suspended at line: " << aLocation.getLineBegin(); } void resumed() { std::cerr << "Query resumed" << std::endl; } void terminated() { std::cerr << "Query terminated" << std::endl; } void evaluated(String &anExpr, std::list< std::pair<String, String> > &aValuesAndTypes) { std::list<std::pair<String, String> >::iterator it; for(it=aValuesAndTypes.begin(); it!=aValuesAndTypes.end(); ++it) { std::cerr << it->first << " " << it->second << std::endl; } } void evaluated(String &anExpr, String &anError) { std::cerr << "An error happened: " << anError << std::endl; } }; ZORBA_THREAD_RETURN runClient( void* ) { sleep(1); MyDebuggerEventHandler lEventHandler; ZorbaDebuggerClient * lClient = ZorbaDebuggerClient::createClient( 8000, 9000 ); lClient->registerEventHandler( &lEventHandler ); lClient->run(); sleep(1); lClient->terminate(); delete lClient; return 0; } bool debugger_example_1(Zorba *aZorba) { XQuery_t lQuery = aZorba->createQuery(); lQuery->setDebugMode(true); lQuery->compile("for $i in ( 1 to 10 ) return $i"); lQuery->debug(); lQuery->close(); return true; } bool debugger_example_3(Zorba *aZorba) { try { XQuery_t lQuery = aZorba->createQuery(); lQuery->compile("1+2"); lQuery->debug(); lQuery->close(); } catch( ZorbaException &e ) { return true; } return false; } int debugger( int argc, char *argv[] ) { simplestore::SimpleStore *lStore = simplestore::SimpleStoreManager::getStore(); Zorba *lZorba = Zorba::getInstance( lStore ); bool res = false; { #ifdef ZORBA_HAVE_PTHREAD_H pthread_t lThread; if ( pthread_create( &lThread, 0, runClient, 0 ) != 0 ) #else HANDLE lThread; if ( ( lThread = CreateThread(0, 0, runClient, 0, 0, 0) ) == 0 ) #endif { std::cerr << "Couldn't start the thread" << std::endl; return 1; } std::cout << "executing example 1" << std::endl; res = debugger_example_1(lZorba); #ifdef ZORBA_HAVE_PTHREAD_H pthread_cancel( lThread ); #else CloseHandle( lThread );; #endif if ( !res ) return 1; std::cout << std::endl; } { std::cout << "executing example 3" << std::endl; res = debugger_example_3(lZorba); if ( !res ) return 1; std::cout << std::endl; } lZorba->shutdown(); simplestore::SimpleStoreManager::shutdownStore(lStore); return 0; } <commit_msg>fixed a warning<commit_after>/* * Copyright 2006-2008 The FLWOR Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <iostream> #include <cassert> #include <zorba/zorba.h> #include <zorba/debugger_client.h> #include <zorba/debugger_default_event_handler.h> #include <simplestore/simplestore.h> #ifdef WIN32 #include <windows.h> #define sleep(s) Sleep(s*1000) #endif #ifdef ZORBA_HAVE_PTHREAD_H #include <pthread.h> #define ZORBA_THREAD_RETURN void * #else #define ZORBA_THREAD_RETURN DWORD WINAPI #endif using namespace zorba; class MyDebuggerEventHandler: public DefaultDebuggerEventHandler { public: virtual ~MyDebuggerEventHandler(){} void started() { std::cerr << "Query started" << std::endl; } void idle() { std::cerr << "Query idle" << std::endl; } void suspended( QueryLocation &aLocation, SuspendedBy aCause ) { std::cerr << "Suspended at line: " << aLocation.getLineBegin(); } void resumed() { std::cerr << "Query resumed" << std::endl; } void terminated() { std::cerr << "Query terminated" << std::endl; } void evaluated(String &anExpr, std::list< std::pair<String, String> > &aValuesAndTypes) { std::list<std::pair<String, String> >::iterator it; for(it=aValuesAndTypes.begin(); it!=aValuesAndTypes.end(); ++it) { std::cerr << it->first << " " << it->second << std::endl; } } void evaluated(String &anExpr, String &anError) { std::cerr << "An error happened: " << anError << std::endl; } }; ZORBA_THREAD_RETURN runClient( void* ) { sleep(1); MyDebuggerEventHandler lEventHandler; ZorbaDebuggerClient * lClient = ZorbaDebuggerClient::createClient( 8000, 9000 ); lClient->registerEventHandler( &lEventHandler ); lClient->run(); sleep(1); lClient->terminate(); delete lClient; return 0; } bool debugger_example_1(Zorba *aZorba) { XQuery_t lQuery = aZorba->createQuery(); lQuery->setDebugMode(true); lQuery->compile("for $i in ( 1 to 10 ) return $i"); lQuery->debug(); lQuery->close(); return true; } bool debugger_example_3(Zorba *aZorba) { try { XQuery_t lQuery = aZorba->createQuery(); lQuery->compile("1+2"); lQuery->debug(); lQuery->close(); } catch( ZorbaException & ) { return true; } return false; } int debugger( int argc, char *argv[] ) { simplestore::SimpleStore *lStore = simplestore::SimpleStoreManager::getStore(); Zorba *lZorba = Zorba::getInstance( lStore ); bool res = false; { #ifdef ZORBA_HAVE_PTHREAD_H pthread_t lThread; if ( pthread_create( &lThread, 0, runClient, 0 ) != 0 ) #else HANDLE lThread; if ( ( lThread = CreateThread(0, 0, runClient, 0, 0, 0) ) == 0 ) #endif { std::cerr << "Couldn't start the thread" << std::endl; return 1; } std::cout << "executing example 1" << std::endl; res = debugger_example_1(lZorba); #ifdef ZORBA_HAVE_PTHREAD_H pthread_cancel( lThread ); #else CloseHandle( lThread );; #endif if ( !res ) return 1; std::cout << std::endl; } { std::cout << "executing example 3" << std::endl; res = debugger_example_3(lZorba); if ( !res ) return 1; std::cout << std::endl; } lZorba->shutdown(); simplestore::SimpleStoreManager::shutdownStore(lStore); return 0; } <|endoftext|>
<commit_before>/** @file @brief Implementation @date 2014 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2014 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 "DevicesWithParameters.h" #include "GetSerialPortState.h" #include <osvr/VRPNServer/VRPNDeviceRegistration.h> #include <osvr/USBSerial/USBSerial.h> // Library/third-party includes #include <json/reader.h> #include <json/value.h> #include <vrpn_YEI_3Space.h> // Standard includes #include <vector> #include <memory> #include <string> #include <string.h> namespace { /// @brief Manage an array of dynamically allocated c-strings, terminated with a /// null entry. class CStringArray : boost::noncopyable { public: typedef std::unique_ptr<char[]> UniqueCharArray; void push_back(std::string const &str) { // Remove null terminator from array if (m_arrayHasNullTerminator()) { m_data.pop_back(); } { const size_t stringLength = str.size() + 1; UniqueCharArray copy(new char[stringLength]); memcpy(copy.get(), str.c_str(), stringLength); m_dataOwnership.push_back(std::move(copy)); } m_data.push_back(m_dataOwnership.back().get()); } const char **get_array() { // Ensure null terminator on array if (!m_arrayHasNullTerminator()) { m_data.push_back(nullptr); } return m_data.data(); } private: bool m_arrayHasNullTerminator() const { return !m_data.empty() && nullptr == m_data.back(); } std::vector<const char *> m_data; std::vector<UniqueCharArray> m_dataOwnership; }; } // namespace void createYEI(VRPNMultiserverData &data, OSVR_PluginRegContext ctx, const char *params) { Json::Reader reader; Json::Value root; if (!reader.parse(params, root)) { throw std::runtime_error("Could not parse configuration: " + reader.getFormattedErrorMessages()); } osvr::usbserial::USBSerialDevice serialDevice(root["vendorID"].asString(), root["productID"].asString()); std::string port = normalizeAndVerifySerialPort(serialDevice.getPort()); bool calibrate_gyros_on_setup = root.get("calibrateGyrosOnSetup", false).asBool(); bool tare_on_setup = root.get("tareOnSetup", false).asBool(); double frames_per_second = root.get("framesPerSecond", 250).asFloat(); Json::Value commands = root.get("resetCommands", Json::arrayValue); CStringArray reset_commands; for (Json::ArrayIndex i = 0, e = commands.size(); i < e; ++i) { reset_commands.push_back(commands[i].asString()); } osvr::vrpnserver::VRPNDeviceRegistration reg(ctx); reg.registerDevice(new vrpn_YEI_3Space_Sensor( reg.useDecoratedName(data.getName("YEI_3Space_Sensor")).c_str(), reg.getVRPNConnection(), port.c_str(), 115200, calibrate_gyros_on_setup, tare_on_setup, frames_per_second, 0, 0, 1, 0, reset_commands.get_array())); } <commit_msg>iterate over connected serial devices(YEI trackers) and register them<commit_after>/** @file @brief Implementation @date 2014 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2014 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 "DevicesWithParameters.h" #include "GetSerialPortState.h" #include <osvr/VRPNServer/VRPNDeviceRegistration.h> #include <osvr/USBSerial/USBSerialEnum.h> // Library/third-party includes #include <json/reader.h> #include <json/value.h> #include <vrpn_YEI_3Space.h> // Standard includes #include <vector> #include <memory> #include <string> #include <string.h> namespace { /// @brief Manage an array of dynamically allocated c-strings, terminated with a /// null entry. class CStringArray : boost::noncopyable { public: typedef std::unique_ptr<char[]> UniqueCharArray; void push_back(std::string const &str) { // Remove null terminator from array if (m_arrayHasNullTerminator()) { m_data.pop_back(); } { const size_t stringLength = str.size() + 1; UniqueCharArray copy(new char[stringLength]); memcpy(copy.get(), str.c_str(), stringLength); m_dataOwnership.push_back(std::move(copy)); } m_data.push_back(m_dataOwnership.back().get()); } const char **get_array() { // Ensure null terminator on array if (!m_arrayHasNullTerminator()) { m_data.push_back(nullptr); } return m_data.data(); } private: bool m_arrayHasNullTerminator() const { return !m_data.empty() && nullptr == m_data.back(); } std::vector<const char *> m_data; std::vector<UniqueCharArray> m_dataOwnership; }; } // namespace void createYEI(VRPNMultiserverData &data, OSVR_PluginRegContext ctx, const char *params) { Json::Reader reader; Json::Value root; if (!reader.parse(params, root)) { throw std::runtime_error("Could not parse configuration: " + reader.getFormattedErrorMessages()); } uint16_t vID = 0x9AC; uint16_t pID = 0x3F2; for (auto dev : osvr::usbserial::Enumerator(vID, pID)){ std::string port = normalizeAndVerifySerialPort(dev->getPort()); bool calibrate_gyros_on_setup = root.get("calibrateGyrosOnSetup", false).asBool(); bool tare_on_setup = root.get("tareOnSetup", false).asBool(); double frames_per_second = root.get("framesPerSecond", 250).asFloat(); Json::Value commands = root.get("resetCommands", Json::arrayValue); CStringArray reset_commands; for (Json::ArrayIndex i = 0, e = commands.size(); i < e; ++i) { reset_commands.push_back(commands[i].asString()); } osvr::vrpnserver::VRPNDeviceRegistration reg(ctx); reg.registerDevice(new vrpn_YEI_3Space_Sensor( reg.useDecoratedName(data.getName("YEI_3Space_Sensor")).c_str(), reg.getVRPNConnection(), port.c_str(), 115200, calibrate_gyros_on_setup, tare_on_setup, frames_per_second, 0, 0, 1, 0, reset_commands.get_array())); } } <|endoftext|>
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * LXQt - a lightweight, Qt based, desktop toolset * https://lxqt.org/ * * Copyright: 2018 LXQt team * * This program or library is free software; you can redistribute it * and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include "configothertoolkits.h" #include <QFile> #include <QTextStream> #include <QStandardPaths> #include <QMetaEnum> #include <QToolBar> #include <QDir> #include <QFileInfo> #include <QFont> #include <QDateTime> #include <QMessageBox> #include <sys/types.h> #include <signal.h> static const char *GTK2_CONFIG = R"GTK2_CONFIG( # Created by lxqt-config-appearance (DO NOT EDIT!) gtk-theme-name = "%1" gtk-icon-theme-name = "%2" gtk-font-name = "%3" gtk-button-images = %4 gtk-menu-images = %4 gtk-toolbar-style = %5 )GTK2_CONFIG"; static const char *GTK3_CONFIG = R"GTK3_CONFIG( # Created by lxqt-config-appearance (DO NOT EDIT!) [Settings] gtk-theme-name = %1 gtk-icon-theme-name = %2 # GTK3 ignores bold or italic attributes. gtk-font-name = %3 gtk-menu-images = %4 gtk-button-images = %4 gtk-toolbar-style = %5 )GTK3_CONFIG"; static const char *XSETTINGS_CONFIG = R"XSETTINGS_CONFIG( # Created by lxqt-config-appearance (DO NOT EDIT!) Net/IconThemeName "%2" Net/ThemeName "%1" Gtk/FontName "%3" Gtk/MenuImages %4 Gtk/ButtonImages %4 Gtk/ToolbarStyle "%5" )XSETTINGS_CONFIG"; ConfigOtherToolKits::ConfigOtherToolKits(LXQt::Settings *settings, LXQt::Settings *configAppearanceSettings, QObject *parent) : QObject(parent) { mSettings = settings; mConfigAppearanceSettings = configAppearanceSettings; if(tempFile.open()) { mXsettingsdProc.setProcessChannelMode(QProcess::ForwardedChannels); mXsettingsdProc.start("xsettingsd", QStringList() << "-c" << tempFile.fileName()); if(!mXsettingsdProc.waitForStarted()) return; tempFile.close(); } } ConfigOtherToolKits::~ConfigOtherToolKits() { mXsettingsdProc.close(); } static QString get_environment_var(const char *envvar, const char *defaultValue) { QString homeDir = QStandardPaths::writableLocation(QStandardPaths::HomeLocation); QString mDirPath = QString::fromLocal8Bit(qgetenv(envvar)); if(mDirPath.isEmpty()) mDirPath = homeDir + defaultValue; else { for(QString path : mDirPath.split(":") ) { mDirPath = path; break; } } return mDirPath; } static QString _get_config_path(QString path) { QString homeDir = QStandardPaths::writableLocation(QStandardPaths::HomeLocation); path.replace("$XDG_CONFIG_HOME", get_environment_var("XDG_CONFIG_HOME", "/.config")); path.replace("$GTK2_RC_FILES", get_environment_var("GTK2_RC_FILES", "/.gtkrc-2.0")); // If $GTK2_RC_FILES is undefined, "~/.gtkrc-2.0" will be used. path.replace("~", homeDir); return path; } QString ConfigOtherToolKits::getGTKConfigPath(QString version) { if(version == "2.0") return _get_config_path("$GTK2_RC_FILES"); return _get_config_path(QString("$XDG_CONFIG_HOME/gtk-%1/settings.ini").arg(version)); } static bool grep(QFile &file, QByteArray text) { if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return false; while (!file.atEnd()) { QByteArray line = file.readLine().trimmed(); if(line.startsWith(text)) { return true; } } file.close(); return false; } bool ConfigOtherToolKits::backupGTKSettings(QString version) { QString gtkrcPath = getGTKConfigPath(version); QFile file(gtkrcPath); if(file.exists() && !grep(file, "# Created by lxqt-config-appearance (DO NOT EDIT!)")) { QString backupPath = gtkrcPath + "-" + QString::number(QDateTime::currentSecsSinceEpoch()) + "~"; file.copy(backupPath); QMessageBox::warning(nullptr, tr("GTK themes"), tr("<p>'%1' has been overwritten.</p><p>You can find a copy of your old settings in '%2'</p>") .arg(getGTKConfigPath(version)) .arg(backupPath) , QMessageBox::Ok); return true; } return false; } void ConfigOtherToolKits::setConfig() { if(!mConfigAppearanceSettings->contains("ControlGTKThemeEnabled")) mConfigAppearanceSettings->setValue("ControlGTKThemeEnabled", false); bool controlGTKThemeEnabled = mConfigAppearanceSettings->value("ControlGTKThemeEnabled").toBool(); if(! controlGTKThemeEnabled) return; updateConfigFromSettings(); mConfig.styleTheme = getGTKThemeFromRCFile("3.0"); setGTKConfig("3.0"); mConfig.styleTheme = getGTKThemeFromRCFile("2.0"); setGTKConfig("2.0"); setXSettingsConfig(); } void ConfigOtherToolKits::setXSettingsConfig() { // setGTKConfig is called before calling setXSettingsConfig, // then updateConfigFromSettings is not required. //updateConfigFromSettings(); //mConfig.styleTheme = getGTKThemeFromRCFile(version); // Reload settings. xsettingsd must be installed. // xsettingsd settings are written to stdin. if(QProcess::Running == mXsettingsdProc.state()) { QFile file(tempFile.fileName()); if(file.open(QIODevice::WriteOnly)) { file.write( getConfig(XSETTINGS_CONFIG).toLocal8Bit() ); file.flush(); file.close(); } int pid = mXsettingsdProc.processId(); kill(pid, SIGHUP); } } void ConfigOtherToolKits::setGTKConfig(QString version, QString theme) { updateConfigFromSettings(); if(!theme.isEmpty()) mConfig.styleTheme = theme; backupGTKSettings(version); QString gtkrcPath = getGTKConfigPath(version); if(version == "2.0") writeConfig(gtkrcPath, GTK2_CONFIG); else writeConfig(gtkrcPath, GTK3_CONFIG); } QString ConfigOtherToolKits::getConfig(const char *configString) { return QString(configString).arg(mConfig.styleTheme, mConfig.iconTheme, mConfig.fontName, mConfig.buttonStyle==0 ? "0":"1", mConfig.toolButtonStyle ); } void ConfigOtherToolKits::writeConfig(QString path, const char *configString) { path = _get_config_path(path); QFile file(path); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { return; } QTextStream out(&file); out << getConfig(configString); out.flush(); file.close(); } QStringList ConfigOtherToolKits::getGTKThemes(QString version) { QStringList themeList; QString configFile = version=="2.0" ? "gtk-2.0/gtkrc" : QString("gtk-%1/gtk.css").arg(version); QStringList dataPaths = QStandardPaths::standardLocations(QStandardPaths::GenericDataLocation); for(QString dataPath : dataPaths) { QDir themesPath(dataPath + "/themes"); QStringList themes = themesPath.entryList(QDir::Dirs); for(QString theme : themes) { QFileInfo themePath(QString("%1/themes/%2/%3").arg(dataPath, theme, configFile)); if(themePath.exists()) themeList.append(theme); } } return themeList; } QString ConfigOtherToolKits::getGTKThemeFromRCFile(QString version) { if(version == "2.0") { QString gtkrcPath = _get_config_path("$GTK2_RC_FILES"); QFile file(gtkrcPath); if(file.exists()) { if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return QString(); while (!file.atEnd()) { QByteArray line = file.readLine().trimmed(); if(line.startsWith("gtk-theme-name")) { QList<QByteArray> parts = line.split('='); if(parts.size()>=2) { file.close(); return parts[1].replace('"', "").trimmed(); } } } file.close(); } } else { QString gtkrcPath = _get_config_path(QString("$XDG_CONFIG_HOME/gtk-%1/settings.ini").arg(version)); QFile file(gtkrcPath); if(file.exists()) { if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return QString(); bool settingsFound = false; while (!file.atEnd()) { QByteArray line = file.readLine().trimmed(); if(line.startsWith("[Settings]")) settingsFound = true; else if(line.startsWith("[") && line.endsWith("]")) settingsFound = false; else if(settingsFound && line.startsWith("gtk-theme-name")) { QList<QByteArray> parts = line.split('='); if(parts.size()>=2) { file.close(); return parts[1].trimmed(); } } } file.close(); } } return QString(); } void ConfigOtherToolKits::updateConfigFromSettings() { mSettings->beginGroup(QLatin1String("Qt")); QFont font; font.fromString(mSettings->value("font").toString()); // Font name from: https://developer.gnome.org/pango/stable/pango-Fonts.html#pango-font-description-from-string // FAMILY-LIST [SIZE]", where FAMILY-LIST is a comma separated list of families optionally terminated by a comma, // STYLE_OPTIONS is a whitespace separated list of words where each word describes one of style, variant, weight, stretch, or gravity, and // SIZE is a decimal number (size in points) or optionally followed by the unit modifier "px" for absolute size. mConfig.fontName = QString("%1%2%3 %4") .arg(font.family()) //%1 .arg(font.style()==QFont::StyleNormal?"":" Italic") //%2 .arg(font.weight()==QFont::Normal?"":" Bold") //%3 .arg(font.pointSize()); //%4 mSettings->endGroup(); mConfig.iconTheme = mSettings->value("icon_theme").toString(); { // Tool button style QByteArray tb_style = mSettings->value("tool_button_style").toByteArray(); // convert toolbar style name to value QMetaEnum me = QToolBar::staticMetaObject.property(QToolBar::staticMetaObject.indexOfProperty("toolButtonStyle")).enumerator(); int val = me.keyToValue(tb_style.constData()); mConfig.buttonStyle = 1; switch(val) { case Qt::ToolButtonIconOnly: mConfig.toolButtonStyle = "GTK_TOOLBAR_ICONS"; break; case Qt::ToolButtonTextOnly: mConfig.toolButtonStyle = "GTK_TOOLBAR_TEXT"; mConfig.buttonStyle = 0; break; case Qt::ToolButtonTextUnderIcon: mConfig.toolButtonStyle = "GTK_TOOLBAR_BOTH"; break; default: mConfig.toolButtonStyle = "GTK_TOOLBAR_BOTH_HORIZ"; } } } <commit_msg>lxqt-config-appearance: mkpath if settings of GTK doesn't exists.<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * LXQt - a lightweight, Qt based, desktop toolset * https://lxqt.org/ * * Copyright: 2018 LXQt team * * This program or library is free software; you can redistribute it * and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include "configothertoolkits.h" #include <QFile> #include <QTextStream> #include <QStandardPaths> #include <QMetaEnum> #include <QToolBar> #include <QDir> #include <QFileInfo> #include <QFont> #include <QDateTime> #include <QMessageBox> #include <sys/types.h> #include <signal.h> static const char *GTK2_CONFIG = R"GTK2_CONFIG( # Created by lxqt-config-appearance (DO NOT EDIT!) gtk-theme-name = "%1" gtk-icon-theme-name = "%2" gtk-font-name = "%3" gtk-button-images = %4 gtk-menu-images = %4 gtk-toolbar-style = %5 )GTK2_CONFIG"; static const char *GTK3_CONFIG = R"GTK3_CONFIG( # Created by lxqt-config-appearance (DO NOT EDIT!) [Settings] gtk-theme-name = %1 gtk-icon-theme-name = %2 # GTK3 ignores bold or italic attributes. gtk-font-name = %3 gtk-menu-images = %4 gtk-button-images = %4 gtk-toolbar-style = %5 )GTK3_CONFIG"; static const char *XSETTINGS_CONFIG = R"XSETTINGS_CONFIG( # Created by lxqt-config-appearance (DO NOT EDIT!) Net/IconThemeName "%2" Net/ThemeName "%1" Gtk/FontName "%3" Gtk/MenuImages %4 Gtk/ButtonImages %4 Gtk/ToolbarStyle "%5" )XSETTINGS_CONFIG"; ConfigOtherToolKits::ConfigOtherToolKits(LXQt::Settings *settings, LXQt::Settings *configAppearanceSettings, QObject *parent) : QObject(parent) { mSettings = settings; mConfigAppearanceSettings = configAppearanceSettings; if(tempFile.open()) { mXsettingsdProc.setProcessChannelMode(QProcess::ForwardedChannels); mXsettingsdProc.start("xsettingsd", QStringList() << "-c" << tempFile.fileName()); if(!mXsettingsdProc.waitForStarted()) return; tempFile.close(); } } ConfigOtherToolKits::~ConfigOtherToolKits() { mXsettingsdProc.close(); } static QString get_environment_var(const char *envvar, const char *defaultValue) { QString homeDir = QStandardPaths::writableLocation(QStandardPaths::HomeLocation); QString mDirPath = QString::fromLocal8Bit(qgetenv(envvar)); if(mDirPath.isEmpty()) mDirPath = homeDir + defaultValue; else { for(QString path : mDirPath.split(":") ) { mDirPath = path; break; } } return mDirPath; } static QString _get_config_path(QString path) { QString homeDir = QStandardPaths::writableLocation(QStandardPaths::HomeLocation); path.replace("$XDG_CONFIG_HOME", get_environment_var("XDG_CONFIG_HOME", "/.config")); path.replace("$GTK2_RC_FILES", get_environment_var("GTK2_RC_FILES", "/.gtkrc-2.0")); // If $GTK2_RC_FILES is undefined, "~/.gtkrc-2.0" will be used. path.replace("~", homeDir); return path; } QString ConfigOtherToolKits::getGTKConfigPath(QString version) { if(version == "2.0") return _get_config_path("$GTK2_RC_FILES"); return _get_config_path(QString("$XDG_CONFIG_HOME/gtk-%1/settings.ini").arg(version)); } static bool grep(QFile &file, QByteArray text) { if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return false; while (!file.atEnd()) { QByteArray line = file.readLine().trimmed(); if(line.startsWith(text)) { return true; } } file.close(); return false; } bool ConfigOtherToolKits::backupGTKSettings(QString version) { QString gtkrcPath = getGTKConfigPath(version); QFile file(gtkrcPath); if(file.exists() && !grep(file, "# Created by lxqt-config-appearance (DO NOT EDIT!)")) { QString backupPath = gtkrcPath + "-" + QString::number(QDateTime::currentSecsSinceEpoch()) + "~"; file.copy(backupPath); QMessageBox::warning(nullptr, tr("GTK themes"), tr("<p>'%1' has been overwritten.</p><p>You can find a copy of your old settings in '%2'</p>") .arg(getGTKConfigPath(version)) .arg(backupPath) , QMessageBox::Ok); return true; } return false; } void ConfigOtherToolKits::setConfig() { if(!mConfigAppearanceSettings->contains("ControlGTKThemeEnabled")) mConfigAppearanceSettings->setValue("ControlGTKThemeEnabled", false); bool controlGTKThemeEnabled = mConfigAppearanceSettings->value("ControlGTKThemeEnabled").toBool(); if(! controlGTKThemeEnabled) return; updateConfigFromSettings(); mConfig.styleTheme = getGTKThemeFromRCFile("3.0"); setGTKConfig("3.0"); mConfig.styleTheme = getGTKThemeFromRCFile("2.0"); setGTKConfig("2.0"); setXSettingsConfig(); } void ConfigOtherToolKits::setXSettingsConfig() { // setGTKConfig is called before calling setXSettingsConfig, // then updateConfigFromSettings is not required. //updateConfigFromSettings(); //mConfig.styleTheme = getGTKThemeFromRCFile(version); // Reload settings. xsettingsd must be installed. // xsettingsd settings are written to stdin. if(QProcess::Running == mXsettingsdProc.state()) { QFile file(tempFile.fileName()); if(file.open(QIODevice::WriteOnly)) { file.write( getConfig(XSETTINGS_CONFIG).toLocal8Bit() ); file.flush(); file.close(); } int pid = mXsettingsdProc.processId(); kill(pid, SIGHUP); } } void ConfigOtherToolKits::setGTKConfig(QString version, QString theme) { updateConfigFromSettings(); if(!theme.isEmpty()) mConfig.styleTheme = theme; backupGTKSettings(version); QString gtkrcPath = getGTKConfigPath(version); if(version == "2.0") writeConfig(gtkrcPath, GTK2_CONFIG); else writeConfig(gtkrcPath, GTK3_CONFIG); } QString ConfigOtherToolKits::getConfig(const char *configString) { return QString(configString).arg(mConfig.styleTheme, mConfig.iconTheme, mConfig.fontName, mConfig.buttonStyle==0 ? "0":"1", mConfig.toolButtonStyle ); } void ConfigOtherToolKits::writeConfig(QString path, const char *configString) { path = _get_config_path(path); QFile file(path); if(! file.exists()) { QFileInfo fileInfo(file); QDir::home().mkpath(fileInfo.path()); } if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { return; } QTextStream out(&file); out << getConfig(configString); out.flush(); file.close(); } QStringList ConfigOtherToolKits::getGTKThemes(QString version) { QStringList themeList; QString configFile = version=="2.0" ? "gtk-2.0/gtkrc" : QString("gtk-%1/gtk.css").arg(version); QStringList dataPaths = QStandardPaths::standardLocations(QStandardPaths::GenericDataLocation); for(QString dataPath : dataPaths) { QDir themesPath(dataPath + "/themes"); QStringList themes = themesPath.entryList(QDir::Dirs); for(QString theme : themes) { QFileInfo themePath(QString("%1/themes/%2/%3").arg(dataPath, theme, configFile)); if(themePath.exists()) themeList.append(theme); } } return themeList; } QString ConfigOtherToolKits::getGTKThemeFromRCFile(QString version) { if(version == "2.0") { QString gtkrcPath = _get_config_path("$GTK2_RC_FILES"); QFile file(gtkrcPath); if(file.exists()) { if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return QString(); while (!file.atEnd()) { QByteArray line = file.readLine().trimmed(); if(line.startsWith("gtk-theme-name")) { QList<QByteArray> parts = line.split('='); if(parts.size()>=2) { file.close(); return parts[1].replace('"', "").trimmed(); } } } file.close(); } } else { QString gtkrcPath = _get_config_path(QString("$XDG_CONFIG_HOME/gtk-%1/settings.ini").arg(version)); QFile file(gtkrcPath); if(file.exists()) { if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return QString(); bool settingsFound = false; while (!file.atEnd()) { QByteArray line = file.readLine().trimmed(); if(line.startsWith("[Settings]")) settingsFound = true; else if(line.startsWith("[") && line.endsWith("]")) settingsFound = false; else if(settingsFound && line.startsWith("gtk-theme-name")) { QList<QByteArray> parts = line.split('='); if(parts.size()>=2) { file.close(); return parts[1].trimmed(); } } } file.close(); } } return QString(); } void ConfigOtherToolKits::updateConfigFromSettings() { mSettings->beginGroup(QLatin1String("Qt")); QFont font; font.fromString(mSettings->value("font").toString()); // Font name from: https://developer.gnome.org/pango/stable/pango-Fonts.html#pango-font-description-from-string // FAMILY-LIST [SIZE]", where FAMILY-LIST is a comma separated list of families optionally terminated by a comma, // STYLE_OPTIONS is a whitespace separated list of words where each word describes one of style, variant, weight, stretch, or gravity, and // SIZE is a decimal number (size in points) or optionally followed by the unit modifier "px" for absolute size. mConfig.fontName = QString("%1%2%3 %4") .arg(font.family()) //%1 .arg(font.style()==QFont::StyleNormal?"":" Italic") //%2 .arg(font.weight()==QFont::Normal?"":" Bold") //%3 .arg(font.pointSize()); //%4 mSettings->endGroup(); mConfig.iconTheme = mSettings->value("icon_theme").toString(); { // Tool button style QByteArray tb_style = mSettings->value("tool_button_style").toByteArray(); // convert toolbar style name to value QMetaEnum me = QToolBar::staticMetaObject.property(QToolBar::staticMetaObject.indexOfProperty("toolButtonStyle")).enumerator(); int val = me.keyToValue(tb_style.constData()); mConfig.buttonStyle = 1; switch(val) { case Qt::ToolButtonIconOnly: mConfig.toolButtonStyle = "GTK_TOOLBAR_ICONS"; break; case Qt::ToolButtonTextOnly: mConfig.toolButtonStyle = "GTK_TOOLBAR_TEXT"; mConfig.buttonStyle = 0; break; case Qt::ToolButtonTextUnderIcon: mConfig.toolButtonStyle = "GTK_TOOLBAR_BOTH"; break; default: mConfig.toolButtonStyle = "GTK_TOOLBAR_BOTH_HORIZ"; } } } <|endoftext|>
<commit_before>/** @file @brief Implementation @date 2014 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2014 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 "DevicesWithParameters.h" #include "GetSerialPortState.h" #include <osvr/VRPNServer/VRPNDeviceRegistration.h> #include <osvr/USBSerial/USBSerialEnum.h> // Library/third-party includes #include <json/reader.h> #include <json/value.h> #include <vrpn_YEI_3Space.h> // Standard includes #include <vector> #include <memory> #include <string> #include <string.h> namespace { /// @brief Manage an array of dynamically allocated c-strings, terminated with a /// null entry. class CStringArray : boost::noncopyable { public: typedef std::unique_ptr<char[]> UniqueCharArray; void push_back(std::string const &str) { // Remove null terminator from array if (m_arrayHasNullTerminator()) { m_data.pop_back(); } { const size_t stringLength = str.size() + 1; UniqueCharArray copy(new char[stringLength]); memcpy(copy.get(), str.c_str(), stringLength); m_dataOwnership.push_back(std::move(copy)); } m_data.push_back(m_dataOwnership.back().get()); } const char **get_array() { // Ensure null terminator on array if (!m_arrayHasNullTerminator()) { m_data.push_back(nullptr); } return m_data.data(); } private: bool m_arrayHasNullTerminator() const { return !m_data.empty() && nullptr == m_data.back(); } std::vector<const char *> m_data; std::vector<UniqueCharArray> m_dataOwnership; }; } // namespace void createYEI(VRPNMultiserverData &data, OSVR_PluginRegContext ctx, const char *params) { Json::Reader reader; Json::Value root; if (!reader.parse(params, root)) { throw std::runtime_error("Could not parse configuration: " + reader.getFormattedErrorMessages()); } uint16_t vID = 0x9AC; uint16_t pID = 0x3F2; for (auto dev : osvr::usbserial::Enumerator(vID, pID)) { std::string port = normalizeAndVerifySerialPort(dev->getPort()); bool calibrate_gyros_on_setup = root.get("calibrateGyrosOnSetup", false).asBool(); bool tare_on_setup = root.get("tareOnSetup", false).asBool(); double frames_per_second = root.get("framesPerSecond", 250).asFloat(); Json::Value commands = root.get("resetCommands", Json::arrayValue); CStringArray reset_commands; for (Json::ArrayIndex i = 0, e = commands.size(); i < e; ++i) { reset_commands.push_back(commands[i].asString()); } osvr::vrpnserver::VRPNDeviceRegistration reg(ctx); reg.registerDevice(new vrpn_YEI_3Space_Sensor( reg.useDecoratedName(data.getName("YEI_3Space_Sensor")).c_str(), reg.getVRPNConnection(), port.c_str(), 115200, calibrate_gyros_on_setup, tare_on_setup, frames_per_second, 0, 0, 1, 0, reset_commands.get_array())); } } <commit_msg>Make constants const.<commit_after>/** @file @brief Implementation @date 2014 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2014 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 "DevicesWithParameters.h" #include "GetSerialPortState.h" #include <osvr/VRPNServer/VRPNDeviceRegistration.h> #include <osvr/USBSerial/USBSerialEnum.h> // Library/third-party includes #include <json/reader.h> #include <json/value.h> #include <vrpn_YEI_3Space.h> // Standard includes #include <vector> #include <memory> #include <string> #include <string.h> namespace { /// @brief Manage an array of dynamically allocated c-strings, terminated with a /// null entry. class CStringArray : boost::noncopyable { public: typedef std::unique_ptr<char[]> UniqueCharArray; void push_back(std::string const &str) { // Remove null terminator from array if (m_arrayHasNullTerminator()) { m_data.pop_back(); } { const size_t stringLength = str.size() + 1; UniqueCharArray copy(new char[stringLength]); memcpy(copy.get(), str.c_str(), stringLength); m_dataOwnership.push_back(std::move(copy)); } m_data.push_back(m_dataOwnership.back().get()); } const char **get_array() { // Ensure null terminator on array if (!m_arrayHasNullTerminator()) { m_data.push_back(nullptr); } return m_data.data(); } private: bool m_arrayHasNullTerminator() const { return !m_data.empty() && nullptr == m_data.back(); } std::vector<const char *> m_data; std::vector<UniqueCharArray> m_dataOwnership; }; } // namespace void createYEI(VRPNMultiserverData &data, OSVR_PluginRegContext ctx, const char *params) { Json::Reader reader; Json::Value root; if (!reader.parse(params, root)) { throw std::runtime_error("Could not parse configuration: " + reader.getFormattedErrorMessages()); } static const uint16_t vID = 0x9AC; static const uint16_t pID = 0x3F2; for (auto dev : osvr::usbserial::Enumerator(vID, pID)) { std::string port = normalizeAndVerifySerialPort(dev->getPort()); bool calibrate_gyros_on_setup = root.get("calibrateGyrosOnSetup", false).asBool(); bool tare_on_setup = root.get("tareOnSetup", false).asBool(); double frames_per_second = root.get("framesPerSecond", 250).asFloat(); Json::Value commands = root.get("resetCommands", Json::arrayValue); CStringArray reset_commands; for (Json::ArrayIndex i = 0, e = commands.size(); i < e; ++i) { reset_commands.push_back(commands[i].asString()); } osvr::vrpnserver::VRPNDeviceRegistration reg(ctx); reg.registerDevice(new vrpn_YEI_3Space_Sensor( reg.useDecoratedName(data.getName("YEI_3Space_Sensor")).c_str(), reg.getVRPNConnection(), port.c_str(), 115200, calibrate_gyros_on_setup, tare_on_setup, frames_per_second, 0, 0, 1, 0, reset_commands.get_array())); } } <|endoftext|>
<commit_before>//===- IndexBody.cpp - Indexing statements --------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "IndexingContext.h" #include "clang/AST/RecursiveASTVisitor.h" using namespace clang; using namespace clang::index; namespace { class BodyIndexer : public RecursiveASTVisitor<BodyIndexer> { IndexingContext &IndexCtx; const NamedDecl *Parent; const DeclContext *ParentDC; SmallVector<Stmt*, 16> StmtStack; typedef RecursiveASTVisitor<BodyIndexer> base; public: BodyIndexer(IndexingContext &indexCtx, const NamedDecl *Parent, const DeclContext *DC) : IndexCtx(indexCtx), Parent(Parent), ParentDC(DC) { } bool shouldWalkTypesOfTypeLocs() const { return false; } bool dataTraverseStmtPre(Stmt *S) { StmtStack.push_back(S); return true; } bool dataTraverseStmtPost(Stmt *S) { assert(StmtStack.back() == S); StmtStack.pop_back(); return true; } bool TraverseTypeLoc(TypeLoc TL) { IndexCtx.indexTypeLoc(TL, Parent, ParentDC); return true; } bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) { IndexCtx.indexNestedNameSpecifierLoc(NNS, Parent, ParentDC); return true; } SymbolRoleSet getRolesForRef(const Expr *E, SmallVectorImpl<SymbolRelation> &Relations) { SymbolRoleSet Roles{}; assert(!StmtStack.empty() && E == StmtStack.back()); if (StmtStack.size() == 1) return Roles; auto It = StmtStack.end()-2; while (isa<CastExpr>(*It) || isa<ParenExpr>(*It)) { if (auto ICE = dyn_cast<ImplicitCastExpr>(*It)) { if (ICE->getCastKind() == CK_LValueToRValue) Roles |= (unsigned)(unsigned)SymbolRole::Read; } if (It == StmtStack.begin()) break; --It; } const Stmt *Parent = *It; if (auto BO = dyn_cast<BinaryOperator>(Parent)) { if (BO->getOpcode() == BO_Assign && BO->getLHS()->IgnoreParenCasts() == E) Roles |= (unsigned)SymbolRole::Write; } else if (auto UO = dyn_cast<UnaryOperator>(Parent)) { if (UO->isIncrementDecrementOp()) { Roles |= (unsigned)SymbolRole::Read; Roles |= (unsigned)SymbolRole::Write; } else if (UO->getOpcode() == UO_AddrOf) { Roles |= (unsigned)SymbolRole::AddressOf; } } else if (auto CA = dyn_cast<CompoundAssignOperator>(Parent)) { if (CA->getLHS()->IgnoreParenCasts() == E) { Roles |= (unsigned)SymbolRole::Read; Roles |= (unsigned)SymbolRole::Write; } } else if (auto CE = dyn_cast<CallExpr>(Parent)) { if (CE->getCallee()->IgnoreParenCasts() == E) { addCallRole(Roles, Relations); if (auto *ME = dyn_cast<MemberExpr>(E)) { if (auto *CXXMD = dyn_cast_or_null<CXXMethodDecl>(ME->getMemberDecl())) if (CXXMD->isVirtual() && !ME->hasQualifier()) { Roles |= (unsigned)SymbolRole::Dynamic; auto BaseTy = ME->getBase()->IgnoreImpCasts()->getType(); if (!BaseTy.isNull()) if (auto *CXXRD = BaseTy->getPointeeCXXRecordDecl()) Relations.emplace_back((unsigned)SymbolRole::RelationReceivedBy, CXXRD); } } } else if (auto CXXOp = dyn_cast<CXXOperatorCallExpr>(CE)) { if (CXXOp->getNumArgs() > 0 && CXXOp->getArg(0)->IgnoreParenCasts() == E) { OverloadedOperatorKind Op = CXXOp->getOperator(); if (Op == OO_Equal) { Roles |= (unsigned)SymbolRole::Write; } else if ((Op >= OO_PlusEqual && Op <= OO_PipeEqual) || Op == OO_LessLessEqual || Op == OO_GreaterGreaterEqual || Op == OO_PlusPlus || Op == OO_MinusMinus) { Roles |= (unsigned)SymbolRole::Read; Roles |= (unsigned)SymbolRole::Write; } else if (Op == OO_Amp) { Roles |= (unsigned)SymbolRole::AddressOf; } } } } return Roles; } void addCallRole(SymbolRoleSet &Roles, SmallVectorImpl<SymbolRelation> &Relations) { Roles |= (unsigned)SymbolRole::Call; if (auto *FD = dyn_cast<FunctionDecl>(ParentDC)) Relations.emplace_back((unsigned)SymbolRole::RelationCalledBy, FD); else if (auto *MD = dyn_cast<ObjCMethodDecl>(ParentDC)) Relations.emplace_back((unsigned)SymbolRole::RelationCalledBy, MD); } bool VisitDeclRefExpr(DeclRefExpr *E) { SmallVector<SymbolRelation, 4> Relations; SymbolRoleSet Roles = getRolesForRef(E, Relations); return IndexCtx.handleReference(E->getDecl(), E->getLocation(), Parent, ParentDC, Roles, Relations, E); } bool VisitMemberExpr(MemberExpr *E) { SourceLocation Loc = E->getMemberLoc(); if (Loc.isInvalid()) Loc = E->getLocStart(); SmallVector<SymbolRelation, 4> Relations; SymbolRoleSet Roles = getRolesForRef(E, Relations); return IndexCtx.handleReference(E->getMemberDecl(), Loc, Parent, ParentDC, Roles, Relations, E); } bool VisitDesignatedInitExpr(DesignatedInitExpr *E) { for (DesignatedInitExpr::Designator &D : llvm::reverse(E->designators())) { if (D.isFieldDesignator() && D.getField()) return IndexCtx.handleReference(D.getField(), D.getFieldLoc(), Parent, ParentDC, SymbolRoleSet(), {}, E); } return true; } bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { SmallVector<SymbolRelation, 4> Relations; SymbolRoleSet Roles = getRolesForRef(E, Relations); return IndexCtx.handleReference(E->getDecl(), E->getLocation(), Parent, ParentDC, Roles, Relations, E); } bool VisitObjCMessageExpr(ObjCMessageExpr *E) { auto isDynamic = [](const ObjCMessageExpr *MsgE)->bool { if (MsgE->getReceiverKind() != ObjCMessageExpr::Instance) return false; if (auto *RecE = dyn_cast<ObjCMessageExpr>( MsgE->getInstanceReceiver()->IgnoreParenCasts())) { if (RecE->getMethodFamily() == OMF_alloc) return false; } return true; }; if (ObjCMethodDecl *MD = E->getMethodDecl()) { SymbolRoleSet Roles{}; SmallVector<SymbolRelation, 2> Relations; addCallRole(Roles, Relations); if (E->isImplicit()) Roles |= (unsigned)SymbolRole::Implicit; if (isDynamic(E)) { Roles |= (unsigned)SymbolRole::Dynamic; if (auto *RecD = E->getReceiverInterface()) Relations.emplace_back((unsigned)SymbolRole::RelationReceivedBy, RecD); } return IndexCtx.handleReference(MD, E->getSelectorStartLoc(), Parent, ParentDC, Roles, Relations, E); } return true; } bool VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) { if (E->isExplicitProperty()) return IndexCtx.handleReference(E->getExplicitProperty(), E->getLocation(), Parent, ParentDC, SymbolRoleSet(), {}, E); // No need to do a handleReference for the objc method, because there will // be a message expr as part of PseudoObjectExpr. return true; } bool VisitMSPropertyRefExpr(MSPropertyRefExpr *E) { return IndexCtx.handleReference(E->getPropertyDecl(), E->getMemberLoc(), Parent, ParentDC, SymbolRoleSet(), {}, E); } bool VisitObjCProtocolExpr(ObjCProtocolExpr *E) { return IndexCtx.handleReference(E->getProtocol(), E->getProtocolIdLoc(), Parent, ParentDC, SymbolRoleSet(), {}, E); } bool passObjCLiteralMethodCall(const ObjCMethodDecl *MD, const Expr *E) { SymbolRoleSet Roles{}; SmallVector<SymbolRelation, 2> Relations; addCallRole(Roles, Relations); Roles |= (unsigned)SymbolRole::Implicit; return IndexCtx.handleReference(MD, E->getLocStart(), Parent, ParentDC, Roles, Relations, E); } bool VisitObjCBoxedExpr(ObjCBoxedExpr *E) { if (ObjCMethodDecl *MD = E->getBoxingMethod()) { return passObjCLiteralMethodCall(MD, E); } return true; } bool VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) { if (ObjCMethodDecl *MD = E->getDictWithObjectsMethod()) { return passObjCLiteralMethodCall(MD, E); } return true; } bool VisitObjCArrayLiteral(ObjCArrayLiteral *E) { if (ObjCMethodDecl *MD = E->getArrayWithObjectsMethod()) { return passObjCLiteralMethodCall(MD, E); } return true; } bool VisitCXXConstructExpr(CXXConstructExpr *E) { SymbolRoleSet Roles{}; SmallVector<SymbolRelation, 2> Relations; addCallRole(Roles, Relations); return IndexCtx.handleReference(E->getConstructor(), E->getLocation(), Parent, ParentDC, Roles, Relations, E); } bool TraverseCXXOperatorCallExpr(CXXOperatorCallExpr *E, DataRecursionQueue *Q = nullptr) { if (E->getOperatorLoc().isInvalid()) return true; // implicit. return base::TraverseCXXOperatorCallExpr(E, Q); } bool VisitDeclStmt(DeclStmt *S) { if (IndexCtx.shouldIndexFunctionLocalSymbols()) { IndexCtx.indexDeclGroupRef(S->getDeclGroup()); return true; } DeclGroupRef DG = S->getDeclGroup(); for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) { const Decl *D = *I; if (!D) continue; if (!IndexCtx.isFunctionLocalDecl(D)) IndexCtx.indexTopLevelDecl(D); } return true; } bool TraverseLambdaCapture(LambdaExpr *LE, const LambdaCapture *C) { if (C->capturesThis() || C->capturesVLAType()) return true; if (C->capturesVariable() && IndexCtx.shouldIndexFunctionLocalSymbols()) return IndexCtx.handleReference(C->getCapturedVar(), C->getLocation(), Parent, ParentDC, SymbolRoleSet()); // FIXME: Lambda init-captures. return true; } // RecursiveASTVisitor visits both syntactic and semantic forms, duplicating // the things that we visit. Make sure to only visit the semantic form. // Also visit things that are in the syntactic form but not the semantic one, // for example the indices in DesignatedInitExprs. bool TraverseInitListExpr(InitListExpr *S, DataRecursionQueue *Q = nullptr) { class SyntacticFormIndexer : public RecursiveASTVisitor<SyntacticFormIndexer> { IndexingContext &IndexCtx; const NamedDecl *Parent; const DeclContext *ParentDC; bool Visited = false; public: SyntacticFormIndexer(IndexingContext &indexCtx, const NamedDecl *Parent, const DeclContext *DC) : IndexCtx(indexCtx), Parent(Parent), ParentDC(DC) { } bool shouldWalkTypesOfTypeLocs() const { return false; } bool TraverseInitListExpr(InitListExpr *S, DataRecursionQueue *Q = nullptr) { // Don't visit nested InitListExprs, this visitor will be called again // later on for the nested ones. if (Visited) return true; Visited = true; InitListExpr *SyntaxForm = S->isSemanticForm() ? S->getSyntacticForm() : S; if (SyntaxForm) { for (Stmt *SubStmt : SyntaxForm->children()) { if (!TraverseStmt(SubStmt, Q)) return false; } } return true; } bool VisitDesignatedInitExpr(DesignatedInitExpr *E) { for (DesignatedInitExpr::Designator &D : llvm::reverse(E->designators())) { if (D.isFieldDesignator()) return IndexCtx.handleReference(D.getField(), D.getFieldLoc(), Parent, ParentDC, SymbolRoleSet(), {}, E); } return true; } }; auto visitForm = [&](InitListExpr *Form) { for (Stmt *SubStmt : Form->children()) { if (!TraverseStmt(SubStmt, Q)) return false; } return true; }; InitListExpr *SemaForm = S->isSemanticForm() ? S : S->getSemanticForm(); InitListExpr *SyntaxForm = S->isSemanticForm() ? S->getSyntacticForm() : S; if (SemaForm) { // Visit things present in syntactic form but not the semantic form. if (SyntaxForm) { SyntacticFormIndexer(IndexCtx, Parent, ParentDC).TraverseStmt(SyntaxForm); } return visitForm(SemaForm); } // No semantic, try the syntactic. if (SyntaxForm) { return visitForm(SyntaxForm); } return true; } }; } // anonymous namespace void IndexingContext::indexBody(const Stmt *S, const NamedDecl *Parent, const DeclContext *DC) { if (!S) return; if (!DC) DC = Parent->getLexicalDeclContext(); BodyIndexer(*this, Parent, DC).TraverseStmt(const_cast<Stmt*>(S)); } <commit_msg>[index] Avoid using a RecursiveASTVisitor for SyntacticFormIndexer and iterate the DesignatedInitExprs of the InitListExpr directly.<commit_after>//===- IndexBody.cpp - Indexing statements --------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "IndexingContext.h" #include "clang/AST/RecursiveASTVisitor.h" using namespace clang; using namespace clang::index; namespace { class BodyIndexer : public RecursiveASTVisitor<BodyIndexer> { IndexingContext &IndexCtx; const NamedDecl *Parent; const DeclContext *ParentDC; SmallVector<Stmt*, 16> StmtStack; typedef RecursiveASTVisitor<BodyIndexer> base; public: BodyIndexer(IndexingContext &indexCtx, const NamedDecl *Parent, const DeclContext *DC) : IndexCtx(indexCtx), Parent(Parent), ParentDC(DC) { } bool shouldWalkTypesOfTypeLocs() const { return false; } bool dataTraverseStmtPre(Stmt *S) { StmtStack.push_back(S); return true; } bool dataTraverseStmtPost(Stmt *S) { assert(StmtStack.back() == S); StmtStack.pop_back(); return true; } bool TraverseTypeLoc(TypeLoc TL) { IndexCtx.indexTypeLoc(TL, Parent, ParentDC); return true; } bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) { IndexCtx.indexNestedNameSpecifierLoc(NNS, Parent, ParentDC); return true; } SymbolRoleSet getRolesForRef(const Expr *E, SmallVectorImpl<SymbolRelation> &Relations) { SymbolRoleSet Roles{}; assert(!StmtStack.empty() && E == StmtStack.back()); if (StmtStack.size() == 1) return Roles; auto It = StmtStack.end()-2; while (isa<CastExpr>(*It) || isa<ParenExpr>(*It)) { if (auto ICE = dyn_cast<ImplicitCastExpr>(*It)) { if (ICE->getCastKind() == CK_LValueToRValue) Roles |= (unsigned)(unsigned)SymbolRole::Read; } if (It == StmtStack.begin()) break; --It; } const Stmt *Parent = *It; if (auto BO = dyn_cast<BinaryOperator>(Parent)) { if (BO->getOpcode() == BO_Assign && BO->getLHS()->IgnoreParenCasts() == E) Roles |= (unsigned)SymbolRole::Write; } else if (auto UO = dyn_cast<UnaryOperator>(Parent)) { if (UO->isIncrementDecrementOp()) { Roles |= (unsigned)SymbolRole::Read; Roles |= (unsigned)SymbolRole::Write; } else if (UO->getOpcode() == UO_AddrOf) { Roles |= (unsigned)SymbolRole::AddressOf; } } else if (auto CA = dyn_cast<CompoundAssignOperator>(Parent)) { if (CA->getLHS()->IgnoreParenCasts() == E) { Roles |= (unsigned)SymbolRole::Read; Roles |= (unsigned)SymbolRole::Write; } } else if (auto CE = dyn_cast<CallExpr>(Parent)) { if (CE->getCallee()->IgnoreParenCasts() == E) { addCallRole(Roles, Relations); if (auto *ME = dyn_cast<MemberExpr>(E)) { if (auto *CXXMD = dyn_cast_or_null<CXXMethodDecl>(ME->getMemberDecl())) if (CXXMD->isVirtual() && !ME->hasQualifier()) { Roles |= (unsigned)SymbolRole::Dynamic; auto BaseTy = ME->getBase()->IgnoreImpCasts()->getType(); if (!BaseTy.isNull()) if (auto *CXXRD = BaseTy->getPointeeCXXRecordDecl()) Relations.emplace_back((unsigned)SymbolRole::RelationReceivedBy, CXXRD); } } } else if (auto CXXOp = dyn_cast<CXXOperatorCallExpr>(CE)) { if (CXXOp->getNumArgs() > 0 && CXXOp->getArg(0)->IgnoreParenCasts() == E) { OverloadedOperatorKind Op = CXXOp->getOperator(); if (Op == OO_Equal) { Roles |= (unsigned)SymbolRole::Write; } else if ((Op >= OO_PlusEqual && Op <= OO_PipeEqual) || Op == OO_LessLessEqual || Op == OO_GreaterGreaterEqual || Op == OO_PlusPlus || Op == OO_MinusMinus) { Roles |= (unsigned)SymbolRole::Read; Roles |= (unsigned)SymbolRole::Write; } else if (Op == OO_Amp) { Roles |= (unsigned)SymbolRole::AddressOf; } } } } return Roles; } void addCallRole(SymbolRoleSet &Roles, SmallVectorImpl<SymbolRelation> &Relations) { Roles |= (unsigned)SymbolRole::Call; if (auto *FD = dyn_cast<FunctionDecl>(ParentDC)) Relations.emplace_back((unsigned)SymbolRole::RelationCalledBy, FD); else if (auto *MD = dyn_cast<ObjCMethodDecl>(ParentDC)) Relations.emplace_back((unsigned)SymbolRole::RelationCalledBy, MD); } bool VisitDeclRefExpr(DeclRefExpr *E) { SmallVector<SymbolRelation, 4> Relations; SymbolRoleSet Roles = getRolesForRef(E, Relations); return IndexCtx.handleReference(E->getDecl(), E->getLocation(), Parent, ParentDC, Roles, Relations, E); } bool VisitMemberExpr(MemberExpr *E) { SourceLocation Loc = E->getMemberLoc(); if (Loc.isInvalid()) Loc = E->getLocStart(); SmallVector<SymbolRelation, 4> Relations; SymbolRoleSet Roles = getRolesForRef(E, Relations); return IndexCtx.handleReference(E->getMemberDecl(), Loc, Parent, ParentDC, Roles, Relations, E); } bool VisitDesignatedInitExpr(DesignatedInitExpr *E) { for (DesignatedInitExpr::Designator &D : llvm::reverse(E->designators())) { if (D.isFieldDesignator() && D.getField()) return IndexCtx.handleReference(D.getField(), D.getFieldLoc(), Parent, ParentDC, SymbolRoleSet(), {}, E); } return true; } bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { SmallVector<SymbolRelation, 4> Relations; SymbolRoleSet Roles = getRolesForRef(E, Relations); return IndexCtx.handleReference(E->getDecl(), E->getLocation(), Parent, ParentDC, Roles, Relations, E); } bool VisitObjCMessageExpr(ObjCMessageExpr *E) { auto isDynamic = [](const ObjCMessageExpr *MsgE)->bool { if (MsgE->getReceiverKind() != ObjCMessageExpr::Instance) return false; if (auto *RecE = dyn_cast<ObjCMessageExpr>( MsgE->getInstanceReceiver()->IgnoreParenCasts())) { if (RecE->getMethodFamily() == OMF_alloc) return false; } return true; }; if (ObjCMethodDecl *MD = E->getMethodDecl()) { SymbolRoleSet Roles{}; SmallVector<SymbolRelation, 2> Relations; addCallRole(Roles, Relations); if (E->isImplicit()) Roles |= (unsigned)SymbolRole::Implicit; if (isDynamic(E)) { Roles |= (unsigned)SymbolRole::Dynamic; if (auto *RecD = E->getReceiverInterface()) Relations.emplace_back((unsigned)SymbolRole::RelationReceivedBy, RecD); } return IndexCtx.handleReference(MD, E->getSelectorStartLoc(), Parent, ParentDC, Roles, Relations, E); } return true; } bool VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) { if (E->isExplicitProperty()) return IndexCtx.handleReference(E->getExplicitProperty(), E->getLocation(), Parent, ParentDC, SymbolRoleSet(), {}, E); // No need to do a handleReference for the objc method, because there will // be a message expr as part of PseudoObjectExpr. return true; } bool VisitMSPropertyRefExpr(MSPropertyRefExpr *E) { return IndexCtx.handleReference(E->getPropertyDecl(), E->getMemberLoc(), Parent, ParentDC, SymbolRoleSet(), {}, E); } bool VisitObjCProtocolExpr(ObjCProtocolExpr *E) { return IndexCtx.handleReference(E->getProtocol(), E->getProtocolIdLoc(), Parent, ParentDC, SymbolRoleSet(), {}, E); } bool passObjCLiteralMethodCall(const ObjCMethodDecl *MD, const Expr *E) { SymbolRoleSet Roles{}; SmallVector<SymbolRelation, 2> Relations; addCallRole(Roles, Relations); Roles |= (unsigned)SymbolRole::Implicit; return IndexCtx.handleReference(MD, E->getLocStart(), Parent, ParentDC, Roles, Relations, E); } bool VisitObjCBoxedExpr(ObjCBoxedExpr *E) { if (ObjCMethodDecl *MD = E->getBoxingMethod()) { return passObjCLiteralMethodCall(MD, E); } return true; } bool VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) { if (ObjCMethodDecl *MD = E->getDictWithObjectsMethod()) { return passObjCLiteralMethodCall(MD, E); } return true; } bool VisitObjCArrayLiteral(ObjCArrayLiteral *E) { if (ObjCMethodDecl *MD = E->getArrayWithObjectsMethod()) { return passObjCLiteralMethodCall(MD, E); } return true; } bool VisitCXXConstructExpr(CXXConstructExpr *E) { SymbolRoleSet Roles{}; SmallVector<SymbolRelation, 2> Relations; addCallRole(Roles, Relations); return IndexCtx.handleReference(E->getConstructor(), E->getLocation(), Parent, ParentDC, Roles, Relations, E); } bool TraverseCXXOperatorCallExpr(CXXOperatorCallExpr *E, DataRecursionQueue *Q = nullptr) { if (E->getOperatorLoc().isInvalid()) return true; // implicit. return base::TraverseCXXOperatorCallExpr(E, Q); } bool VisitDeclStmt(DeclStmt *S) { if (IndexCtx.shouldIndexFunctionLocalSymbols()) { IndexCtx.indexDeclGroupRef(S->getDeclGroup()); return true; } DeclGroupRef DG = S->getDeclGroup(); for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) { const Decl *D = *I; if (!D) continue; if (!IndexCtx.isFunctionLocalDecl(D)) IndexCtx.indexTopLevelDecl(D); } return true; } bool TraverseLambdaCapture(LambdaExpr *LE, const LambdaCapture *C) { if (C->capturesThis() || C->capturesVLAType()) return true; if (C->capturesVariable() && IndexCtx.shouldIndexFunctionLocalSymbols()) return IndexCtx.handleReference(C->getCapturedVar(), C->getLocation(), Parent, ParentDC, SymbolRoleSet()); // FIXME: Lambda init-captures. return true; } // RecursiveASTVisitor visits both syntactic and semantic forms, duplicating // the things that we visit. Make sure to only visit the semantic form. // Also visit things that are in the syntactic form but not the semantic one, // for example the indices in DesignatedInitExprs. bool TraverseInitListExpr(InitListExpr *S, DataRecursionQueue *Q = nullptr) { auto visitForm = [&](InitListExpr *Form) { for (Stmt *SubStmt : Form->children()) { if (!TraverseStmt(SubStmt, Q)) return false; } return true; }; auto visitSyntacticDesignatedInitExpr = [&](DesignatedInitExpr *E) -> bool { for (DesignatedInitExpr::Designator &D : llvm::reverse(E->designators())) { if (D.isFieldDesignator()) return IndexCtx.handleReference(D.getField(), D.getFieldLoc(), Parent, ParentDC, SymbolRoleSet(), {}, E); } return true; }; InitListExpr *SemaForm = S->isSemanticForm() ? S : S->getSemanticForm(); InitListExpr *SyntaxForm = S->isSemanticForm() ? S->getSyntacticForm() : S; if (SemaForm) { // Visit things present in syntactic form but not the semantic form. if (SyntaxForm) { for (Expr *init : SyntaxForm->inits()) { if (auto *DIE = dyn_cast<DesignatedInitExpr>(init)) visitSyntacticDesignatedInitExpr(DIE); } } return visitForm(SemaForm); } // No semantic, try the syntactic. if (SyntaxForm) { return visitForm(SyntaxForm); } return true; } }; } // anonymous namespace void IndexingContext::indexBody(const Stmt *S, const NamedDecl *Parent, const DeclContext *DC) { if (!S) return; if (!DC) DC = Parent->getLexicalDeclContext(); BodyIndexer(*this, Parent, DC).TraverseStmt(const_cast<Stmt*>(S)); } <|endoftext|>
<commit_before>// This file is a part of the OpenSurgSim project. // Copyright 2013-2015, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "SurgSim/Devices/ReplayPoseDevice/ReplayPoseDevice.h" #include "SurgSim/Devices/ReplayPoseDevice/ReplayPoseScaffold.h" #include "SurgSim/Framework/Assert.h" namespace SurgSim { namespace Devices { SURGSIM_REGISTER(SurgSim::Input::DeviceInterface, SurgSim::Devices::ReplayPoseDevice, ReplayPoseDevice); ReplayPoseDevice::ReplayPoseDevice(const std::string& uniqueName) : SurgSim::Input::CommonDevice(uniqueName, ReplayPoseScaffold::buildDeviceInputData()), m_fileName("ReplayPoseDevice.txt") { } ReplayPoseDevice::~ReplayPoseDevice() { if (isInitialized()) { finalize(); } } const std::string ReplayPoseDevice::getFileName() const { return m_fileName; } void ReplayPoseDevice::setFileName(const std::string& fileName) { SURGSIM_ASSERT(!isInitialized()) << "The filename can only be set before initialization"; m_fileName = fileName; } double ReplayPoseDevice::getRate() const { return m_rate; } void ReplayPoseDevice::setRate(double rate) { SURGSIM_ASSERT(!isInitialized()) << "The rate can only be set before initialization"; m_rate = rate; } bool ReplayPoseDevice::initialize() { SURGSIM_ASSERT(!isInitialized()) << getName() << " already initialized."; std::shared_ptr<ReplayPoseScaffold> scaffold = ReplayPoseScaffold::getOrCreateSharedInstance(); SURGSIM_ASSERT(scaffold); scaffold->setRate(m_rate); if (!scaffold->registerDevice(this)) { return false; } m_scaffold = std::move(scaffold); return true; } bool ReplayPoseDevice::finalize() { SURGSIM_ASSERT(isInitialized()) << getName() << " is not initialized, cannot finalize."; bool ok = m_scaffold->unregisterDevice(); m_scaffold.reset(); return ok; } bool ReplayPoseDevice::isInitialized() const { return (m_scaffold != nullptr); } }; // namespace Devices }; // namespace SurgSim <commit_msg>Make ReplayPoseDevice rate 1KHz by default<commit_after>// This file is a part of the OpenSurgSim project. // Copyright 2013-2015, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "SurgSim/Devices/ReplayPoseDevice/ReplayPoseDevice.h" #include "SurgSim/Devices/ReplayPoseDevice/ReplayPoseScaffold.h" #include "SurgSim/Framework/Assert.h" namespace SurgSim { namespace Devices { SURGSIM_REGISTER(SurgSim::Input::DeviceInterface, SurgSim::Devices::ReplayPoseDevice, ReplayPoseDevice); ReplayPoseDevice::ReplayPoseDevice(const std::string& uniqueName) : SurgSim::Input::CommonDevice(uniqueName, ReplayPoseScaffold::buildDeviceInputData()), m_fileName("ReplayPoseDevice.txt"), m_rate(1000.0) { } ReplayPoseDevice::~ReplayPoseDevice() { if (isInitialized()) { finalize(); } } const std::string ReplayPoseDevice::getFileName() const { return m_fileName; } void ReplayPoseDevice::setFileName(const std::string& fileName) { SURGSIM_ASSERT(!isInitialized()) << "The filename can only be set before initialization"; m_fileName = fileName; } double ReplayPoseDevice::getRate() const { return m_rate; } void ReplayPoseDevice::setRate(double rate) { SURGSIM_ASSERT(!isInitialized()) << "The rate can only be set before initialization"; m_rate = rate; } bool ReplayPoseDevice::initialize() { SURGSIM_ASSERT(!isInitialized()) << getName() << " already initialized."; std::shared_ptr<ReplayPoseScaffold> scaffold = ReplayPoseScaffold::getOrCreateSharedInstance(); SURGSIM_ASSERT(scaffold); scaffold->setRate(m_rate); if (!scaffold->registerDevice(this)) { return false; } m_scaffold = std::move(scaffold); return true; } bool ReplayPoseDevice::finalize() { SURGSIM_ASSERT(isInitialized()) << getName() << " is not initialized, cannot finalize."; bool ok = m_scaffold->unregisterDevice(); m_scaffold.reset(); return ok; } bool ReplayPoseDevice::isInitialized() const { return (m_scaffold != nullptr); } }; // namespace Devices }; // namespace SurgSim <|endoftext|>
<commit_before>// Copyright (C) 1999-2018 // Smithsonian Astrophysical Observatory, Cambridge, MA, USA // For conditions of distribution and use, see copyright notice in "copyright" #include <tk.h> #include "basepolygon.h" #include "fitsimage.h" BasePolygon::BasePolygon(Base* p, const Vector& ctr, const Vector& b) : Marker(p, ctr, 0) { } BasePolygon::BasePolygon(Base* p, const Vector& ctr, const Vector& b, const char* clr, int* dsh, int wth, const char* fnt, const char* txt, unsigned short prop, const char* cmt, const List<Tag>& tg, const List<CallBack>& cb) : Marker(p, ctr, 0, clr, dsh, wth, fnt, txt, prop, cmt, tg, cb) { } BasePolygon::BasePolygon(Base* p, const List<Vertex>& v, const char* clr, int* dsh, int wth, const char* fnt, const char* txt, unsigned short prop, const char* cmt, const List<Tag>& tg, const List<CallBack>& cb) : Marker(p, Vector(0,0), 0, clr, dsh, wth, fnt, txt, prop, cmt, tg, cb) { // Vertex list is in ref coords angle = 0; vertex = v; // find center center = Vector(0,0); vertex.head(); do center += vertex.current()->vector; while (vertex.next()); center /= vertex.count(); // vertices are relative vertex.head(); do vertex.current()->vector *= Translate(-center) * FlipY(); // no rotation while (vertex.next()); updateBBox(); } BasePolygon::BasePolygon(const BasePolygon& a) : Marker(a) { vertex = a.vertex; } void BasePolygon::createVertex(int which, const Vector& v) { // which segment (1 to n) // v is in ref coords Matrix mm = bckMatrix(); int seg = which-1; if (seg>=0 && seg<vertex.count()) { Vertex* n = new Vertex(v * mm); vertex.insert(seg,n); recalcCenter(); updateBBox(); doCallBack(CallBack::EDITCB); doCallBack(CallBack::MOVECB); // center can change } } void BasePolygon::deleteVertex(int h) { if (h>4) { int hh = h-4-1; if (vertex.count() > 3) { Vertex* v = vertex[hh]; if (v) { vertex.extractNext(v); delete v; recalcCenter(); updateBBox(); doCallBack(CallBack::EDITCB); doCallBack(CallBack::MOVECB); // center can change } } } } void BasePolygon::edit(const Vector& v, int h) { if (h < 5) { Vector s1 = v * bckMatrix(); Vector s2 = bckMap(handle[h-1],Coord::CANVAS); if (s1[0] != 0 && s1[1] != 0 && s2[0] != 0 && s2[1] != 0) { double a = fabs(s1[0]/s2[0]); double b = fabs(s1[1]/s2[1]); double s = a > b ? a : b; vertex.head(); do vertex.current()->vector *= Scale(s); while (vertex.next()); } updateBBox(); doCallBack(CallBack::EDITCB); } else { moveVertex(v,h); updateBBox(); doCallBack(CallBack::EDITCB); doCallBack(CallBack::MOVECB); // center can change } } void BasePolygon::moveVertex(const Vector& v, int h) { Matrix mm = bckMatrix(); if (vertex[h-5]) vertex.current()->vector = v * mm; recalcCenter(); } void BasePolygon::recalcCenter() { // recalculate center Vector nc; vertex.head(); do nc += vertex.current()->vector * Rotate(angle) * FlipY(); while (vertex.next()); nc /= vertex.count(); center += nc; // update all vertices vertex.head(); do vertex.current()->vector -= nc * FlipY() * Rotate(-angle); while (vertex.next()); } void BasePolygon::rotate(const Vector& v, int h) { if (h < 5) Marker::rotate(v,h); else { // we need to check this here, because we are really rotating if (canEdit()) { moveVertex(v,h); updateBBox(); doCallBack(CallBack::EDITCB); doCallBack(CallBack::MOVECB); // center can change } } } void BasePolygon::updateHandles() { // generate handles numHandle = 4 + vertex.count(); if (handle) delete [] handle; handle = new Vector[numHandle]; // the first four are our control handles BBox bb; vertex.head(); do bb.bound(vertex.current()->vector); while (vertex.next()); Vector zz = parent->zoom(); float r = 10/zz.length(); bb.expand(r); // give us more room handle[0] = fwdMap(bb.ll,Coord::CANVAS); handle[1] = fwdMap(bb.lr(),Coord::CANVAS); handle[2] = fwdMap(bb.ur,Coord::CANVAS); handle[3] = fwdMap(bb.ul(),Coord::CANVAS); // and the rest are vertices int i=4; vertex.head(); do handle[i++] = fwdMap(vertex.current()->vector,Coord::CANVAS); while (vertex.next()); } void BasePolygon::updateCoords(const Matrix& mx) { Scale s(mx); vertex.head(); do vertex.current()->vector *= s; while (vertex.next()); Marker::updateCoords(mx); } void BasePolygon::listBase(FitsImage* ptr, ostream& str, Coord::CoordSystem sys, Coord::SkyFrame sky, Coord::SkyFormat format) { Matrix mm = fwdMatrix(); switch (sys) { case Coord::IMAGE: case Coord::PHYSICAL: case Coord::DETECTOR: case Coord::AMPLIFIER: { str << type_ << '('; int first=1; vertex.head(); do { if (!first) str << ','; first=0; Vector vv = ptr->mapFromRef(vertex.current()->vector*mm,sys); str << setprecision(parent->precLinear_) << vv; } while (vertex.next()); str << ')'; } break; default: { str << type_ << '('; int first=1; vertex.head(); do { if (!first) str << ','; first=0; listWCS(ptr,vertex.current()->vector*mm,sys,sky,format); str << ra << ',' << dec; } while (vertex.next()); str << ')'; } } } <commit_msg>simplify marker code<commit_after>// Copyright (C) 1999-2018 // Smithsonian Astrophysical Observatory, Cambridge, MA, USA // For conditions of distribution and use, see copyright notice in "copyright" #include <tk.h> #include "basepolygon.h" #include "fitsimage.h" BasePolygon::BasePolygon(Base* p, const Vector& ctr, const Vector& b) : Marker(p, ctr, 0) { } BasePolygon::BasePolygon(Base* p, const Vector& ctr, const Vector& b, const char* clr, int* dsh, int wth, const char* fnt, const char* txt, unsigned short prop, const char* cmt, const List<Tag>& tg, const List<CallBack>& cb) : Marker(p, ctr, 0, clr, dsh, wth, fnt, txt, prop, cmt, tg, cb) { } BasePolygon::BasePolygon(Base* p, const List<Vertex>& v, const char* clr, int* dsh, int wth, const char* fnt, const char* txt, unsigned short prop, const char* cmt, const List<Tag>& tg, const List<CallBack>& cb) : Marker(p, Vector(0,0), 0, clr, dsh, wth, fnt, txt, prop, cmt, tg, cb) { // Vertex list is in ref coords angle = 0; vertex = v; // find center center = Vector(0,0); vertex.head(); do center += vertex.current()->vector; while (vertex.next()); center /= vertex.count(); // vertices are relative vertex.head(); do vertex.current()->vector *= Translate(-center) * FlipY(); // no rotation while (vertex.next()); updateBBox(); } BasePolygon::BasePolygon(const BasePolygon& a) : Marker(a) { vertex = a.vertex; } void BasePolygon::createVertex(int which, const Vector& v) { // which segment (1 to n) // v is in ref coords Matrix mm = bckMatrix(); int seg = which-1; if (seg>=0 && seg<vertex.count()) { Vertex* n = new Vertex(v * mm); vertex.insert(seg,n); recalcCenter(); updateBBox(); doCallBack(CallBack::EDITCB); doCallBack(CallBack::MOVECB); // center can change } } void BasePolygon::deleteVertex(int h) { if (h>4) { int hh = h-4-1; if (vertex.count() > 3) { Vertex* v = vertex[hh]; if (v) { vertex.extractNext(v); delete v; recalcCenter(); updateBBox(); doCallBack(CallBack::EDITCB); doCallBack(CallBack::MOVECB); // center can change } } } } void BasePolygon::edit(const Vector& v, int h) { if (h < 5) { Vector s1 = v * bckMatrix(); Vector s2 = bckMap(handle[h-1],Coord::CANVAS); if (s1[0] != 0 && s1[1] != 0 && s2[0] != 0 && s2[1] != 0) { double a = fabs(s1[0]/s2[0]); double b = fabs(s1[1]/s2[1]); double s = a > b ? a : b; vertex.head(); do vertex.current()->vector *= Scale(s); while (vertex.next()); } updateBBox(); doCallBack(CallBack::EDITCB); } else { moveVertex(v,h); updateBBox(); doCallBack(CallBack::EDITCB); doCallBack(CallBack::MOVECB); // center can change } } void BasePolygon::moveVertex(const Vector& v, int h) { Matrix mm = bckMatrix(); if (vertex[h-5]) vertex.current()->vector = v * mm; recalcCenter(); } void BasePolygon::recalcCenter() { // recalculate center Vector nc; vertex.head(); do nc += vertex.current()->vector * Rotate(angle) * FlipY(); while (vertex.next()); nc /= vertex.count(); center += nc; // update all vertices vertex.head(); do vertex.current()->vector -= nc * FlipY() * Rotate(-angle); while (vertex.next()); } void BasePolygon::rotate(const Vector& v, int h) { if (h < 5) Marker::rotate(v,h); else { // we need to check this here, because we are really rotating if (canEdit()) { moveVertex(v,h); updateBBox(); doCallBack(CallBack::EDITCB); doCallBack(CallBack::MOVECB); // center can change } } } void BasePolygon::updateHandles() { // generate handles numHandle = 4 + vertex.count(); if (handle) delete [] handle; handle = new Vector[numHandle]; // the first four are our control handles BBox bb; vertex.head(); do bb.bound(vertex.current()->vector); while (vertex.next()); Vector zz = parent->zoom(); float r = 10/zz.length(); bb.expand(r); // give us more room handle[0] = fwdMap(bb.ll,Coord::CANVAS); handle[1] = fwdMap(bb.lr(),Coord::CANVAS); handle[2] = fwdMap(bb.ur,Coord::CANVAS); handle[3] = fwdMap(bb.ul(),Coord::CANVAS); // and the rest are vertices int i=4; vertex.head(); do handle[i++] = fwdMap(vertex.current()->vector,Coord::CANVAS); while (vertex.next()); } void BasePolygon::updateCoords(const Matrix& mx) { Scale s(mx); vertex.head(); do vertex.current()->vector *= s; while (vertex.next()); Marker::updateCoords(mx); } void BasePolygon::listBase(FitsImage* ptr, ostream& str, Coord::CoordSystem sys, Coord::SkyFrame sky, Coord::SkyFormat format) { Matrix mm = fwdMatrix(); str << type_ << '('; int first=1; vertex.head(); do { if (!first) str << ','; first=0; Vector vv = vertex.current()->vector*mm; switch (sys) { case Coord::IMAGE: case Coord::PHYSICAL: case Coord::DETECTOR: case Coord::AMPLIFIER: str << setprecision(parent->precLinear_) << ptr->mapFromRef(vv,sys); break; default: listWCS(ptr,vv,sys,sky,format); str << ra << ',' << dec; break; } } while (vertex.next()); str << ')'; } <|endoftext|>
<commit_before>#include "musicsoundkmicrowidget.h" #include "ui_musicsoundkmicrowidget.h" #include "musicsoundkmicrosearchwidget.h" #include "musicfunctionuiobject.h" #include "musiccoremplayer.h" #include "musicsettingmanager.h" #include "musiclrcanalysis.h" #include "musiclrcmanagerforinline.h" #include "musicstringutils.h" #include "musicdownloadsourcethread.h" #include "musicvideouiobject.h" #include "musictinyuiobject.h" #include "musicuiobject.h" #include "musictoolsetsuiobject.h" #include "musicmessagebox.h" #include "musicaudiorecordercore.h" #include "musiccoreutils.h" #include "musicotherdefine.h" #include "musictime.h" #include <QFileDialog> #ifdef Q_CC_GNU #pragma GCC diagnostic ignored "-Wparentheses" #endif MusicSoundKMicroWidget::MusicSoundKMicroWidget(QWidget *parent) : MusicAbstractMoveWidget(parent), m_ui(new Ui::MusicSoundKMicroWidget) { m_ui->setupUi(this); #if defined MUSIC_GREATER_NEW setAttribute(Qt::WA_TranslucentBackground, false); #endif setAttribute(Qt::WA_DeleteOnClose, true); setAttribute(Qt::WA_QuitOnClose, true); m_ui->topTitleCloseButton->setIcon(QIcon(":/functions/btn_close_hover")); m_ui->topTitleCloseButton->setStyleSheet(MusicUIObject::MToolButtonStyle04); m_ui->topTitleCloseButton->setCursor(QCursor(Qt::PointingHandCursor)); m_ui->topTitleCloseButton->setToolTip(tr("Close")); connect(m_ui->topTitleCloseButton, SIGNAL(clicked()), SLOT(close())); m_ui->stackedWidget->setStyleSheet(MusicUIObject::MBackgroundStyle02); m_ui->topWidget->setStyleSheet(MusicUIObject::MBackgroundStyle06); m_ui->controlWidget->setStyleSheet(MusicUIObject::MBackgroundStyle06); m_ui->timeLabel->setStyleSheet(MusicUIObject::MColorStyle03); m_ui->timeSlider->setStyleSheet(MusicUIObject::MSliderStyle01); m_ui->transferButton->setStyleSheet(MusicUIObject::MKGRecordTransfer); m_queryMv = true; m_stateButtonOn = true; m_intervalTime = 0; m_recordCore = nullptr; recordStateChanged(false); setButtonStyle(true); setStateButtonStyle(true); m_ui->gifLabel->setType(MusicGifLabelWidget::Gif_Record_red); // m_ui->gifLabel->start(); m_ui->loadingLabel->setType(MusicGifLabelWidget::Gif_Cicle_Blue); m_ui->loadingLabel->hide(); m_ui->volumeButton->setValue(100); m_ui->volumeButton->setCursor(QCursor(Qt::PointingHandCursor)); m_mediaPlayer = new MusicCoreMPlayer(this); m_searchWidget = new MusicSoundKMicroSearchWidget; m_searchWidget->connectTo(this); m_searchWidget->show(); m_ui->winTipsButton->setStyleSheet(MusicUIObject::MKGTinyBtnWintopOff); m_analysis = new MusicLrcAnalysis(this); m_analysis->setLineMax(5); m_ui->musicPage->connectTo(this); for(int i=0; i<m_analysis->getLineMax(); ++i) { MusicLRCManagerForInline *w = new MusicLRCManagerForInline(this); w->setLrcPerWidth(-10); m_ui->musicPage->addWidget(w); m_musicLrcContainer.append(w); } m_recordCore = new MusicAudioRecorderCore(this); m_ui->transferButton->setAudioCore(m_recordCore); #ifdef Q_OS_UNIX m_ui->stateButton->setFocusPolicy(Qt::NoFocus); m_ui->playButton->setFocusPolicy(Qt::NoFocus); m_ui->winTipsButton->setFocusPolicy(Qt::NoFocus); #endif connect(m_ui->winTipsButton, SIGNAL(clicked()), SLOT(tipsButtonChanged())); connect(m_ui->stateButton, SIGNAL(clicked()), SLOT(stateButtonChanged())); connect(m_ui->playButton, SIGNAL(clicked()), SLOT(playButtonChanged())); connect(m_mediaPlayer, SIGNAL(finished()), SLOT(playFinished())); connect(m_mediaPlayer, SIGNAL(positionChanged(qint64)), SLOT(positionChanged(qint64))); connect(m_mediaPlayer, SIGNAL(durationChanged(qint64)), SLOT(durationChanged(qint64))); connect(m_ui->timeSlider, SIGNAL(sliderReleasedAt(int)), SLOT(setPosition(int))); connect(m_ui->volumeButton, SIGNAL(musicVolumeChanged(int)), SLOT(volumeChanged(int))); connect(m_ui->recordButton, SIGNAL(clicked()), SLOT(recordButtonClicked())); } MusicSoundKMicroWidget::~MusicSoundKMicroWidget() { delete m_ui; } QString MusicSoundKMicroWidget::getClassName() { return staticMetaObject.className(); } void MusicSoundKMicroWidget::setButtonStyle(bool style) const { m_ui->playButton->setStyleSheet(style ? MusicUIObject::MKGVideoBtnPlay : MusicUIObject::MKGVideoBtnPause); } void MusicSoundKMicroWidget::setStateButtonStyle(bool style) const { m_ui->stateButton->setStyleSheet(style ? MusicUIObject::MKGVideoBtnOrigin : MusicUIObject::MKGVideoBtnOriginOff); } void MusicSoundKMicroWidget::startSeachKMicro(const QString &name) { m_searchWidget->startSeachKMicro(name); } void MusicSoundKMicroWidget::volumeChanged(int volume) { m_mediaPlayer->setVolume(volume); } void MusicSoundKMicroWidget::positionChanged(qint64 position) { m_ui->timeSlider->setValue(position*MT_S2MS); m_ui->timeLabel->setText(QString("%1/%2").arg(MusicTime::msecTime2LabelJustified(position*MT_S2MS)) .arg(MusicTime::msecTime2LabelJustified(m_ui->timeSlider->maximum()))); if(!m_queryMv && !m_analysis->isEmpty()) { QString currentLrc, laterLrc; if(m_analysis->findText(m_ui->timeSlider->value(), m_ui->timeSlider->maximum(), currentLrc, laterLrc, m_intervalTime)) { if(currentLrc != m_musicLrcContainer[m_analysis->getMiddle()]->text()) { if(m_analysis->isValid()) { m_ui->musicPage->start(); } } } } } void MusicSoundKMicroWidget::durationChanged(qint64 duration) { m_ui->loadingLabel->stop(); m_ui->loadingLabel->hide(); m_ui->timeSlider->setRange(0, duration*MT_S2MS); m_ui->timeLabel->setText(QString("00:00/%1").arg(MusicTime::msecTime2LabelJustified(duration*MT_S2MS))); multiMediaChanged(); } void MusicSoundKMicroWidget::playFinished() { m_mediaPlayer->stop(); if(m_ui->gifLabel->isRunning()) { MusicMessageBox message; message.setText(tr("Record Finished")); message.exec(); recordStateChanged(false); QString filename = QFileDialog::getSaveFileName( this, tr("choose a filename to save under"), QDir::currentPath(), "Wav(*.wav)"); if(!filename.isEmpty()) { m_recordCore->addWavHeader(MusicUtils::Core::toLocal8Bit(filename)); } } } void MusicSoundKMicroWidget::setPosition(int position) { m_mediaPlayer->setPosition(position/MT_S2MS); m_analysis->setSongSpeedAndSlow(position); } void MusicSoundKMicroWidget::playButtonChanged() { m_mediaPlayer->play(); switch(m_mediaPlayer->state()) { case MusicObject::PS_PlayingState: setButtonStyle(false); break; case MusicObject::PS_PausedState: setButtonStyle(true); break; default: break; } if(!m_queryMv) { if(m_mediaPlayer->state() == MusicObject::PS_PlayingState) { m_musicLrcContainer[m_analysis->getMiddle()]->startLrcMask(m_intervalTime); } else { m_musicLrcContainer[m_analysis->getMiddle()]->stopLrcMask(); m_ui->musicPage->stop(); } } } void MusicSoundKMicroWidget::stateButtonChanged() { m_stateButtonOn = !m_stateButtonOn; setStateButtonStyle(m_stateButtonOn); multiMediaChanged(); } void MusicSoundKMicroWidget::tipsButtonChanged() { if(m_ui->winTipsButton->styleSheet().contains(MusicUIObject::MKGTinyBtnWintopOff)) { m_ui->winTipsButton->setStyleSheet(MusicUIObject::MKGTinyBtnWintopOn); m_searchWidget->hide(); } else { m_ui->winTipsButton->setStyleSheet(MusicUIObject::MKGTinyBtnWintopOff); m_searchWidget->show(); } } void MusicSoundKMicroWidget::mvURLChanged(bool mv, const QString &url, const QString &lrcUrl) { setButtonStyle(false); m_ui->loadingLabel->show(); m_ui->loadingLabel->start(); if(m_queryMv = mv) { m_ui->stackedWidget->setCurrentIndex(SOUND_KMICRO_INDEX_0); m_mediaPlayer->setMedia(MusicCoreMPlayer::VideoCategory, url, (int)m_ui->videoPage->winId()); m_mediaPlayer->play(); } else { m_ui->stackedWidget->setCurrentIndex(SOUND_KMICRO_INDEX_1); m_mediaPlayer->setMedia(MusicCoreMPlayer::MusicCategory, url); m_mediaPlayer->play(); //////////////////////////////////////////////////////////////// MusicDownloadSourceThread *download = new MusicDownloadSourceThread(this); connect(download, SIGNAL(downLoadByteDataChanged(QByteArray)), SLOT(downLoadFinished(QByteArray))); download->startToDownload(lrcUrl); } } void MusicSoundKMicroWidget::downLoadFinished(const QByteArray &data) { m_analysis->setLrcData(data); for(int i=0; i<m_analysis->getLineMax(); ++i) { m_musicLrcContainer[i]->setText( QString() ); } setItemStyleSheet(0, -3, 90); setItemStyleSheet(1, -6, 35); setItemStyleSheet(2, -10, 0); setItemStyleSheet(3, -6, 35); setItemStyleSheet(4, -3, 90); } void MusicSoundKMicroWidget::updateAnimationLrc() { for(int i=0; i<m_analysis->getLineMax(); ++i) { m_musicLrcContainer[i]->setText(m_analysis->getText(i)); } m_analysis->setCurrentIndex(m_analysis->getCurrentIndex() + 1); m_musicLrcContainer[m_analysis->getMiddle()]->startLrcMask(m_intervalTime); } void MusicSoundKMicroWidget::recordButtonClicked() { if(m_ui->gifLabel->isRunning()) { MusicMessageBox message; message.setText(tr("Recording Now, Stop It?")); if(message.exec() == 0) { recordStateChanged(false); } } else { int index = m_ui->transferButton->audioInputIndex(); if(index != -1) { recordStateChanged(true); } else { MusicMessageBox message; message.setText(tr("Input Error")); message.exec(); } } } void MusicSoundKMicroWidget::closeEvent(QCloseEvent *event) { MusicAbstractMoveWidget::closeEvent(event); emit resetFlag(MusicObject::TT_SoundKMicro); qDeleteAll(m_musicLrcContainer); delete m_analysis; delete m_mediaPlayer; delete m_searchWidget; delete m_recordCore; } void MusicSoundKMicroWidget::paintEvent(QPaintEvent *event) { MusicAbstractMoveWidget::paintEvent(event); m_searchWidget->move( geometry().topRight() + QPoint(5, -4) ); } void MusicSoundKMicroWidget::mouseMoveEvent(QMouseEvent *event) { MusicAbstractMoveWidget::mouseMoveEvent(event); m_searchWidget->move( geometry().topRight() + QPoint(5, -4) ); } void MusicSoundKMicroWidget::multiMediaChanged() { if(m_queryMv) { m_mediaPlayer->setMultiVoice(m_stateButtonOn ? 0 : 1); } else { m_stateButtonOn ? m_mediaPlayer->setRightVolume() : m_mediaPlayer->setLeftVolume(); } volumeChanged(m_ui->volumeButton->value()); } void MusicSoundKMicroWidget::setItemStyleSheet(int index, int size, int transparent) { MusicLRCManagerForInline *w = m_musicLrcContainer[index]; w->setCenterOnLrc(false); w->setFontSize(size); int value = 100 - transparent; value = (value < 0) ? 0 : value; value = (value > 100) ? 100 : value; w->setFontTransparent(value); w->setTransparent(value); if(M_SETTING_PTR->value("LrcColorChoiced").toInt() != -1) { MusicLRCColor::LrcColorType index = MStatic_cast(MusicLRCColor::LrcColorType, M_SETTING_PTR->value("LrcColorChoiced").toInt()); MusicLRCColor cl = MusicLRCColor::mapIndexToColor(index); w->setLinearGradientColor(cl); } else { MusicLRCColor cl(MusicUtils::String::readColorConfig(M_SETTING_PTR->value("LrcFgColorChoiced").toString()), MusicUtils::String::readColorConfig(M_SETTING_PTR->value("LrcBgColorChoiced").toString())); w->setLinearGradientColor(cl); } } void MusicSoundKMicroWidget::recordStateChanged(bool state) { if(state && m_mediaPlayer->state() != MusicObject::PS_StoppedState) { m_ui->gifLabel->start(); m_ui->recordButton->setStyleSheet(MusicUIObject::MKGRerecord); if(m_recordCore) { m_recordCore->onRecordStart(); if(m_recordCore->error()) { return; } } } else { m_ui->gifLabel->stop(); m_ui->recordButton->setStyleSheet(MusicUIObject::MKGRecord); if(m_recordCore) { m_recordCore->onRecordStop(); } } } <commit_msg>Fix kmicro deleted twice[548321]<commit_after>#include "musicsoundkmicrowidget.h" #include "ui_musicsoundkmicrowidget.h" #include "musicsoundkmicrosearchwidget.h" #include "musicfunctionuiobject.h" #include "musiccoremplayer.h" #include "musicsettingmanager.h" #include "musiclrcanalysis.h" #include "musiclrcmanagerforinline.h" #include "musicstringutils.h" #include "musicdownloadsourcethread.h" #include "musicvideouiobject.h" #include "musictinyuiobject.h" #include "musicuiobject.h" #include "musictoolsetsuiobject.h" #include "musicmessagebox.h" #include "musicaudiorecordercore.h" #include "musiccoreutils.h" #include "musicotherdefine.h" #include "musictime.h" #include <QFileDialog> #ifdef Q_CC_GNU #pragma GCC diagnostic ignored "-Wparentheses" #endif MusicSoundKMicroWidget::MusicSoundKMicroWidget(QWidget *parent) : MusicAbstractMoveWidget(parent), m_ui(new Ui::MusicSoundKMicroWidget) { m_ui->setupUi(this); #if defined MUSIC_GREATER_NEW setAttribute(Qt::WA_TranslucentBackground, false); #endif // setAttribute(Qt::WA_DeleteOnClose, true); // setAttribute(Qt::WA_QuitOnClose, true); m_ui->topTitleCloseButton->setIcon(QIcon(":/functions/btn_close_hover")); m_ui->topTitleCloseButton->setStyleSheet(MusicUIObject::MToolButtonStyle04); m_ui->topTitleCloseButton->setCursor(QCursor(Qt::PointingHandCursor)); m_ui->topTitleCloseButton->setToolTip(tr("Close")); connect(m_ui->topTitleCloseButton, SIGNAL(clicked()), SLOT(close())); m_ui->stackedWidget->setStyleSheet(MusicUIObject::MBackgroundStyle02); m_ui->topWidget->setStyleSheet(MusicUIObject::MBackgroundStyle06); m_ui->controlWidget->setStyleSheet(MusicUIObject::MBackgroundStyle06); m_ui->timeLabel->setStyleSheet(MusicUIObject::MColorStyle03); m_ui->timeSlider->setStyleSheet(MusicUIObject::MSliderStyle01); m_ui->transferButton->setStyleSheet(MusicUIObject::MKGRecordTransfer); m_queryMv = true; m_stateButtonOn = true; m_intervalTime = 0; m_recordCore = nullptr; recordStateChanged(false); setButtonStyle(true); setStateButtonStyle(true); m_ui->gifLabel->setType(MusicGifLabelWidget::Gif_Record_red); // m_ui->gifLabel->start(); m_ui->loadingLabel->setType(MusicGifLabelWidget::Gif_Cicle_Blue); m_ui->loadingLabel->hide(); m_ui->volumeButton->setValue(100); m_ui->volumeButton->setCursor(QCursor(Qt::PointingHandCursor)); m_mediaPlayer = new MusicCoreMPlayer(this); m_searchWidget = new MusicSoundKMicroSearchWidget; m_searchWidget->connectTo(this); m_searchWidget->show(); m_ui->winTipsButton->setStyleSheet(MusicUIObject::MKGTinyBtnWintopOff); m_analysis = new MusicLrcAnalysis(this); m_analysis->setLineMax(5); m_ui->musicPage->connectTo(this); for(int i=0; i<m_analysis->getLineMax(); ++i) { MusicLRCManagerForInline *w = new MusicLRCManagerForInline(this); w->setLrcPerWidth(-10); m_ui->musicPage->addWidget(w); m_musicLrcContainer.append(w); } m_recordCore = new MusicAudioRecorderCore(this); m_ui->transferButton->setAudioCore(m_recordCore); #ifdef Q_OS_UNIX m_ui->stateButton->setFocusPolicy(Qt::NoFocus); m_ui->playButton->setFocusPolicy(Qt::NoFocus); m_ui->winTipsButton->setFocusPolicy(Qt::NoFocus); #endif connect(m_ui->winTipsButton, SIGNAL(clicked()), SLOT(tipsButtonChanged())); connect(m_ui->stateButton, SIGNAL(clicked()), SLOT(stateButtonChanged())); connect(m_ui->playButton, SIGNAL(clicked()), SLOT(playButtonChanged())); connect(m_mediaPlayer, SIGNAL(finished()), SLOT(playFinished())); connect(m_mediaPlayer, SIGNAL(positionChanged(qint64)), SLOT(positionChanged(qint64))); connect(m_mediaPlayer, SIGNAL(durationChanged(qint64)), SLOT(durationChanged(qint64))); connect(m_ui->timeSlider, SIGNAL(sliderReleasedAt(int)), SLOT(setPosition(int))); connect(m_ui->volumeButton, SIGNAL(musicVolumeChanged(int)), SLOT(volumeChanged(int))); connect(m_ui->recordButton, SIGNAL(clicked()), SLOT(recordButtonClicked())); } MusicSoundKMicroWidget::~MusicSoundKMicroWidget() { delete m_ui; } QString MusicSoundKMicroWidget::getClassName() { return staticMetaObject.className(); } void MusicSoundKMicroWidget::setButtonStyle(bool style) const { m_ui->playButton->setStyleSheet(style ? MusicUIObject::MKGVideoBtnPlay : MusicUIObject::MKGVideoBtnPause); } void MusicSoundKMicroWidget::setStateButtonStyle(bool style) const { m_ui->stateButton->setStyleSheet(style ? MusicUIObject::MKGVideoBtnOrigin : MusicUIObject::MKGVideoBtnOriginOff); } void MusicSoundKMicroWidget::startSeachKMicro(const QString &name) { m_searchWidget->startSeachKMicro(name); } void MusicSoundKMicroWidget::volumeChanged(int volume) { m_mediaPlayer->setVolume(volume); } void MusicSoundKMicroWidget::positionChanged(qint64 position) { m_ui->timeSlider->setValue(position*MT_S2MS); m_ui->timeLabel->setText(QString("%1/%2").arg(MusicTime::msecTime2LabelJustified(position*MT_S2MS)) .arg(MusicTime::msecTime2LabelJustified(m_ui->timeSlider->maximum()))); if(!m_queryMv && !m_analysis->isEmpty()) { QString currentLrc, laterLrc; if(m_analysis->findText(m_ui->timeSlider->value(), m_ui->timeSlider->maximum(), currentLrc, laterLrc, m_intervalTime)) { if(currentLrc != m_musicLrcContainer[m_analysis->getMiddle()]->text()) { if(m_analysis->isValid()) { m_ui->musicPage->start(); } } } } } void MusicSoundKMicroWidget::durationChanged(qint64 duration) { m_ui->loadingLabel->stop(); m_ui->loadingLabel->hide(); m_ui->timeSlider->setRange(0, duration*MT_S2MS); m_ui->timeLabel->setText(QString("00:00/%1").arg(MusicTime::msecTime2LabelJustified(duration*MT_S2MS))); multiMediaChanged(); } void MusicSoundKMicroWidget::playFinished() { m_mediaPlayer->stop(); if(m_ui->gifLabel->isRunning()) { MusicMessageBox message; message.setText(tr("Record Finished")); message.exec(); recordStateChanged(false); QString filename = QFileDialog::getSaveFileName( this, tr("choose a filename to save under"), QDir::currentPath(), "Wav(*.wav)"); if(!filename.isEmpty()) { m_recordCore->addWavHeader(MusicUtils::Core::toLocal8Bit(filename)); } } } void MusicSoundKMicroWidget::setPosition(int position) { m_mediaPlayer->setPosition(position/MT_S2MS); m_analysis->setSongSpeedAndSlow(position); } void MusicSoundKMicroWidget::playButtonChanged() { m_mediaPlayer->play(); switch(m_mediaPlayer->state()) { case MusicObject::PS_PlayingState: setButtonStyle(false); break; case MusicObject::PS_PausedState: setButtonStyle(true); break; default: break; } if(!m_queryMv) { if(m_mediaPlayer->state() == MusicObject::PS_PlayingState) { m_musicLrcContainer[m_analysis->getMiddle()]->startLrcMask(m_intervalTime); } else { m_musicLrcContainer[m_analysis->getMiddle()]->stopLrcMask(); m_ui->musicPage->stop(); } } } void MusicSoundKMicroWidget::stateButtonChanged() { m_stateButtonOn = !m_stateButtonOn; setStateButtonStyle(m_stateButtonOn); multiMediaChanged(); } void MusicSoundKMicroWidget::tipsButtonChanged() { if(m_ui->winTipsButton->styleSheet().contains(MusicUIObject::MKGTinyBtnWintopOff)) { m_ui->winTipsButton->setStyleSheet(MusicUIObject::MKGTinyBtnWintopOn); m_searchWidget->hide(); } else { m_ui->winTipsButton->setStyleSheet(MusicUIObject::MKGTinyBtnWintopOff); m_searchWidget->show(); } } void MusicSoundKMicroWidget::mvURLChanged(bool mv, const QString &url, const QString &lrcUrl) { setButtonStyle(false); m_ui->loadingLabel->show(); m_ui->loadingLabel->start(); if(m_queryMv = mv) { m_ui->stackedWidget->setCurrentIndex(SOUND_KMICRO_INDEX_0); m_mediaPlayer->setMedia(MusicCoreMPlayer::VideoCategory, url, (int)m_ui->videoPage->winId()); m_mediaPlayer->play(); } else { m_ui->stackedWidget->setCurrentIndex(SOUND_KMICRO_INDEX_1); m_mediaPlayer->setMedia(MusicCoreMPlayer::MusicCategory, url); m_mediaPlayer->play(); //////////////////////////////////////////////////////////////// MusicDownloadSourceThread *download = new MusicDownloadSourceThread(this); connect(download, SIGNAL(downLoadByteDataChanged(QByteArray)), SLOT(downLoadFinished(QByteArray))); download->startToDownload(lrcUrl); } } void MusicSoundKMicroWidget::downLoadFinished(const QByteArray &data) { m_analysis->setLrcData(data); for(int i=0; i<m_analysis->getLineMax(); ++i) { m_musicLrcContainer[i]->setText( QString() ); } setItemStyleSheet(0, -3, 90); setItemStyleSheet(1, -6, 35); setItemStyleSheet(2, -10, 0); setItemStyleSheet(3, -6, 35); setItemStyleSheet(4, -3, 90); } void MusicSoundKMicroWidget::updateAnimationLrc() { for(int i=0; i<m_analysis->getLineMax(); ++i) { m_musicLrcContainer[i]->setText(m_analysis->getText(i)); } m_analysis->setCurrentIndex(m_analysis->getCurrentIndex() + 1); m_musicLrcContainer[m_analysis->getMiddle()]->startLrcMask(m_intervalTime); } void MusicSoundKMicroWidget::recordButtonClicked() { if(m_ui->gifLabel->isRunning()) { MusicMessageBox message; message.setText(tr("Recording Now, Stop It?")); if(message.exec() == 0) { recordStateChanged(false); } } else { int index = m_ui->transferButton->audioInputIndex(); if(index != -1) { recordStateChanged(true); } else { MusicMessageBox message; message.setText(tr("Input Error")); message.exec(); } } } void MusicSoundKMicroWidget::closeEvent(QCloseEvent *event) { MusicAbstractMoveWidget::closeEvent(event); emit resetFlag(MusicObject::TT_SoundKMicro); qDeleteAll(m_musicLrcContainer); delete m_analysis; delete m_mediaPlayer; delete m_searchWidget; delete m_recordCore; } void MusicSoundKMicroWidget::paintEvent(QPaintEvent *event) { MusicAbstractMoveWidget::paintEvent(event); m_searchWidget->move( geometry().topRight() + QPoint(5, -4) ); } void MusicSoundKMicroWidget::mouseMoveEvent(QMouseEvent *event) { MusicAbstractMoveWidget::mouseMoveEvent(event); m_searchWidget->move( geometry().topRight() + QPoint(5, -4) ); } void MusicSoundKMicroWidget::multiMediaChanged() { if(m_queryMv) { m_mediaPlayer->setMultiVoice(m_stateButtonOn ? 0 : 1); } else { m_stateButtonOn ? m_mediaPlayer->setRightVolume() : m_mediaPlayer->setLeftVolume(); } volumeChanged(m_ui->volumeButton->value()); } void MusicSoundKMicroWidget::setItemStyleSheet(int index, int size, int transparent) { MusicLRCManagerForInline *w = m_musicLrcContainer[index]; w->setCenterOnLrc(false); w->setFontSize(size); int value = 100 - transparent; value = (value < 0) ? 0 : value; value = (value > 100) ? 100 : value; w->setFontTransparent(value); w->setTransparent(value); if(M_SETTING_PTR->value("LrcColorChoiced").toInt() != -1) { MusicLRCColor::LrcColorType index = MStatic_cast(MusicLRCColor::LrcColorType, M_SETTING_PTR->value("LrcColorChoiced").toInt()); MusicLRCColor cl = MusicLRCColor::mapIndexToColor(index); w->setLinearGradientColor(cl); } else { MusicLRCColor cl(MusicUtils::String::readColorConfig(M_SETTING_PTR->value("LrcFgColorChoiced").toString()), MusicUtils::String::readColorConfig(M_SETTING_PTR->value("LrcBgColorChoiced").toString())); w->setLinearGradientColor(cl); } } void MusicSoundKMicroWidget::recordStateChanged(bool state) { if(state && m_mediaPlayer->state() != MusicObject::PS_StoppedState) { m_ui->gifLabel->start(); m_ui->recordButton->setStyleSheet(MusicUIObject::MKGRerecord); if(m_recordCore) { m_recordCore->onRecordStart(); if(m_recordCore->error()) { return; } } } else { m_ui->gifLabel->stop(); m_ui->recordButton->setStyleSheet(MusicUIObject::MKGRecord); if(m_recordCore) { m_recordCore->onRecordStop(); } } } <|endoftext|>
<commit_before>/** * Copyright 2008 Matthew Graham * 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 "request_parser.h" #include <sstream> void request_parser_c::add_input( const std::string &input ) { m_input.append( input ); } std::string request_parser_c::readline() { if ( m_input.find( "\n" ) == std::string::npos ) { return std::string(); } std::istringstream str( m_input ); std::string line; std::getline( str, line ); m_input = str.str(); return line; } <commit_msg>made some minor mods to the request_parser readline method<commit_after>/** * Copyright 2008 Matthew Graham * 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 "request_parser.h" #include <sstream> #include <iostream> #include <list> void request_parser_c::add_input( const std::string &input ) { m_input.append( input ); } std::string request_parser_c::readline() { if ( m_input.find( "\n" ) == std::string::npos ) { return std::string(); } std::istringstream str( m_input ); std::list< std::string > lines; std::string line; do { std::getline( str, line ); lines.push_back( line ); std::cerr << "line: " << line; } while ( ! str.eof() ); // m_input = remainder; m_input = std::string(); return line; } <|endoftext|>
<commit_before>#include "stel.h" #include "log.h" namespace steg { lua_State* L = NULL; static int cLuaLoadLibs(lua_State* L) { luaL_openlibs(L); return 0; } DBG_Status LuaInit() { DBG_Status status = DBG_OK; ENG_LogInfo("Lua module initializing..."); L = luaL_newstate(); if(L == NULL) { ENG_LogError("Lua module initialization failure! Game cannot run!"); //shut down log module LogQuit(); exit(EXIT_FAILURE); } else { if(lua_cpcall(L, cLuaLoadLibs, NULL)) { //handle error const char* errorStr = lua_tostring(L, -1); ENG_LogErrors("Lua module cannot open libs: ", errorStr); lua_pop(L, 1); //shut down log module LogQuit(); lua_close(L); exit(EXIT_FAILURE); } else { ENG_LogInfo("Lua module initialize successfully!"); } } //load lua interface status |= PLuaDoScript("./scripts/interface.lua"); return status; } void LuaQuit() { ENG_LogInfo("Lua module shutting down..."); lua_close(L); L = NULL; ENG_LogInfo("Lua module shut down successfully!"); } static const char* (luaLoadErrors[3]) = { [0] = "syntax error during pre-compilation", //LUA_ERRSYNTAX [1] = "memory allocation error", //LUA_ERRMEM [2] = "cannot open/read the script file", //LUA_ERRFILE }; static int cLuaDoFile(lua_State* L) { luaL_checktype(L, 1, LUA_TLIGHTUSERDATA); //const char* scriptFile = (char*)lua_topointer(L, 1); //lua_topointer() "Typically this function is used only for debug information." const char* scriptFile = (char*)lua_touserdata(L, 1); int err = luaL_loadfile(L, scriptFile); if(err) { //handle errors const char* errStr = NULL; switch(err) { case LUA_ERRSYNTAX: errStr = luaLoadErrors[0]; break; case LUA_ERRMEM: errStr = luaLoadErrors[1]; break; case LUA_ERRFILE: errStr = luaLoadErrors[2]; break; default: errStr = "Unknown error!"; break; } luaL_error(L, "Cannot load script file: %s", errStr); } else { //do script lua_call(L, 0, 0); } return 0; //return values are discarded in cpcall } DBG_Status PLuaDoScript(const char* scriptFile) { DBG_Status status = DBG_OK; if(scriptFile == NULL) { return DBG_ARG_ERR; } else { if(lua_cpcall(L, cLuaDoFile, (void*)scriptFile)) { //handle error const char* errorStr = lua_tostring(L, -1); LUA_LogErrors("Lua module cannot do script: ", errorStr); lua_pop(L, 1); status |= DBG_LUA_ERR; } } return status; } struct typePtrPair { const char* name; void* ptr; enum luaType { typeInt, typeDouble, typeBool, typeString, typeCFunction, } type; }; static int cLuaGetGlobal(lua_State* L) { luaL_checktype(L, 1, LUA_TLIGHTUSERDATA); typePtrPair* p = (typePtrPair*)lua_touserdata(L, 1); lua_getglobal(L, p->name); if(lua_isnil(L, -1)) { luaL_error(L, "\"%s\" is not defined yet as a global value!", p->name); return 0; } switch(p->type) { case typePtrPair::typeInt: //temp case typePtrPair::typeDouble: //if(lua_type(L, -1) == LUA_TNUMBER) if(lua_isnumber(L, -1)) { double v = lua_tonumber(L, -1); if(p->type == typePtrPair::typeInt) { *((int*)(p->ptr)) = (int)v; } else // double { *((double*)(p->ptr)) = (double)v; } } else { luaL_error(L, "Global \"%s\" is not a number!", p->name); } break; //case typePtrPair::typeDouble: // break; case typePtrPair::typeBool: if(lua_isboolean(L, -1)) { *((bool*)(p->ptr)) = lua_toboolean(L, -1); } else { luaL_error(L, "Global \"%s\" is not a bool!", p->name); } break; case typePtrPair::typeString: if(lua_isstring(L, -1)) { *((std::string*)(p->ptr)) = lua_tostring(L, -1); //The sequence is copied as the new value for the string. //"http://www.cplusplus.com/reference/string/string/operator=/" } else { luaL_error(L, "Global \"%s\" is not a string!", p->name); } break; case typePtrPair::typeCFunction: if(lua_iscfunction(L, -1)) { *((lua_CFunction*)(p->ptr)) = lua_tocfunction(L, -1); } else { luaL_error(L, "Global \"%s\" is not a lua_CFunction!", p->name); } break; default: luaL_error(L, "Wrong type!"); break; } lua_pop(L, 1); return 0; } static DBG_Status _pGetGlobal(const char* name, void* value, typePtrPair::luaType t) { DBG_Status status = DBG_OK; if(value == NULL || name == NULL) return DBG_ARG_ERR | DBG_NULL_PTR; typePtrPair* p = new typePtrPair; if(p) { p->name = name; p->ptr = value; p->type = t; if(lua_cpcall(L, cLuaGetGlobal, (void*)p)) { //handle error const char* errorStr = lua_tostring(L, -1); LUA_LogErrors("Error in lua getglobal: ", errorStr); lua_pop(L, 1); status |= DBG_LUA_ERR; } delete p; } else { LUA_LogError("Cannot alloc new typePtrPair struct!"); status |= DBG_MEM_ERR; } return status; } DBG_Status PLuaGetGlobal(const char* name, double* value) { DBG_Status status = DBG_OK; status |= _pGetGlobal(name, value, typePtrPair::typeDouble); return status; } DBG_Status PLuaGetGlobal(const char* name, float* value) { DBG_Status status = DBG_OK; double tmp; status |= PLuaGetGlobal(name, &tmp); *value = (float)tmp; return status; } DBG_Status PLuaGetGlobal(const char* name, int* value) { DBG_Status status = DBG_OK; status |= _pGetGlobal(name, value, typePtrPair::typeInt); return status; } DBG_Status PLuaGetGlobal(const char* name, bool* value) { DBG_Status status = DBG_OK; status |= _pGetGlobal(name, value, typePtrPair::typeBool); return status; } DBG_Status PLuaGetGlobal(const char* name, std::string* value) { DBG_Status status = DBG_OK; status |= _pGetGlobal(name, value, typePtrPair::typeString); return status; } DBG_Status PLuaGetGlobal(const char* name, lua_CFunction* value) { DBG_Status status = DBG_OK; status |= _pGetGlobal(name, value, typePtrPair::typeCFunction); return status; } } <commit_msg>Update stel.cpp<commit_after>#include "stel.h" #include "log.h" namespace steg { jmp_buf StelJmp; lua_State* L = NULL; static int cLuaLoadLibs(lua_State* L) { luaL_openlibs(L); return 0; } DBG_Status LuaInit() { DBG_Status status = DBG_OK; ENG_LogInfo("Lua module initializing..."); L = luaL_newstate(); if(L == NULL) { ENG_LogError("Lua module initialization failure! Game cannot run!"); //shut down log module LogQuit(); exit(EXIT_FAILURE); } else { if(lua_cpcall(L, cLuaLoadLibs, NULL)) { //handle error const char* errorStr = lua_tostring(L, -1); ENG_LogErrors("Lua module cannot open libs: ", errorStr); lua_pop(L, 1); //shut down log module LogQuit(); lua_close(L); exit(EXIT_FAILURE); } else { ENG_LogInfo("Lua module initialize successfully!"); } } //load lua interface status |= PLuaDoScript("./scripts/interface.lua"); return status; } void LuaQuit() { ENG_LogInfo("Lua module shutting down..."); lua_close(L); L = NULL; ENG_LogInfo("Lua module shut down successfully!"); } static const char* (luaLoadErrors[3]) = { [0] = "syntax error during pre-compilation", //LUA_ERRSYNTAX [1] = "memory allocation error", //LUA_ERRMEM [2] = "cannot open/read the script file", //LUA_ERRFILE }; static int cLuaDoFile(lua_State* L) { luaL_checktype(L, 1, LUA_TLIGHTUSERDATA); //const char* scriptFile = (char*)lua_topointer(L, 1); //lua_topointer() "Typically this function is used only for debug information." const char* scriptFile = (char*)lua_touserdata(L, 1); int err = luaL_loadfile(L, scriptFile); if(err) { //handle errors const char* errStr = NULL; switch(err) { case LUA_ERRSYNTAX: errStr = luaLoadErrors[0]; break; case LUA_ERRMEM: errStr = luaLoadErrors[1]; break; case LUA_ERRFILE: errStr = luaLoadErrors[2]; break; default: errStr = "Unknown error!"; break; } luaL_error(L, "Cannot load script file: %s", errStr); } else { //do script lua_call(L, 0, 0); } return 0; //return values are discarded in cpcall } DBG_Status PLuaDoScript(const char* scriptFile) { DBG_Status status = DBG_OK; if(scriptFile == NULL) { return DBG_ARG_ERR; } else { if(lua_cpcall(L, cLuaDoFile, (void*)scriptFile)) { //handle error const char* errorStr = lua_tostring(L, -1); LUA_LogErrors("Lua module cannot do script: ", errorStr); lua_pop(L, 1); status |= DBG_LUA_ERR; } } return status; } struct typePtrPair { const char* name; void* ptr; enum luaType { typeInt, typeDouble, typeBool, typeString, typeCFunction, } type; }; static int cLuaGetGlobal(lua_State* L) { luaL_checktype(L, 1, LUA_TLIGHTUSERDATA); typePtrPair* p = (typePtrPair*)lua_touserdata(L, 1); lua_getglobal(L, p->name); if(lua_isnil(L, -1)) { luaL_error(L, "\"%s\" is not defined yet as a global value!", p->name); return 0; } switch(p->type) { case typePtrPair::typeInt: //temp case typePtrPair::typeDouble: //if(lua_type(L, -1) == LUA_TNUMBER) if(lua_isnumber(L, -1)) { double v = lua_tonumber(L, -1); if(p->type == typePtrPair::typeInt) { *((int*)(p->ptr)) = (int)v; } else // double { *((double*)(p->ptr)) = (double)v; } } else { luaL_error(L, "Global \"%s\" is not a number!", p->name); } break; //case typePtrPair::typeDouble: // break; case typePtrPair::typeBool: if(lua_isboolean(L, -1)) { *((bool*)(p->ptr)) = lua_toboolean(L, -1); } else { luaL_error(L, "Global \"%s\" is not a bool!", p->name); } break; case typePtrPair::typeString: if(lua_isstring(L, -1)) { *((std::string*)(p->ptr)) = lua_tostring(L, -1); //The sequence is copied as the new value for the string. //"http://www.cplusplus.com/reference/string/string/operator=/" } else { luaL_error(L, "Global \"%s\" is not a string!", p->name); } break; case typePtrPair::typeCFunction: if(lua_iscfunction(L, -1)) { *((lua_CFunction*)(p->ptr)) = lua_tocfunction(L, -1); } else { luaL_error(L, "Global \"%s\" is not a lua_CFunction!", p->name); } break; default: luaL_error(L, "Wrong type!"); break; } lua_pop(L, 1); return 0; } static DBG_Status _pGetGlobal(const char* name, void* value, typePtrPair::luaType t) { DBG_Status status = DBG_OK; if(value == NULL || name == NULL) return DBG_ARG_ERR | DBG_NULL_PTR; typePtrPair* p = new typePtrPair; if(p) { p->name = name; p->ptr = value; p->type = t; if(lua_cpcall(L, cLuaGetGlobal, (void*)p)) { //handle error const char* errorStr = lua_tostring(L, -1); LUA_LogErrors("Error in lua getglobal: ", errorStr); lua_pop(L, 1); status |= DBG_LUA_ERR; } delete p; } else { LUA_LogError("Cannot alloc new typePtrPair struct!"); status |= DBG_MEM_ERR; } return status; } DBG_Status PLuaGetGlobal(const char* name, double* value) { DBG_Status status = DBG_OK; status |= _pGetGlobal(name, value, typePtrPair::typeDouble); return status; } DBG_Status PLuaGetGlobal(const char* name, float* value) { DBG_Status status = DBG_OK; double tmp; status |= PLuaGetGlobal(name, &tmp); *value = (float)tmp; return status; } DBG_Status PLuaGetGlobal(const char* name, int* value) { DBG_Status status = DBG_OK; status |= _pGetGlobal(name, value, typePtrPair::typeInt); return status; } DBG_Status PLuaGetGlobal(const char* name, bool* value) { DBG_Status status = DBG_OK; status |= _pGetGlobal(name, value, typePtrPair::typeBool); return status; } DBG_Status PLuaGetGlobal(const char* name, std::string* value) { DBG_Status status = DBG_OK; status |= _pGetGlobal(name, value, typePtrPair::typeString); return status; } DBG_Status PLuaGetGlobal(const char* name, lua_CFunction* value) { DBG_Status status = DBG_OK; status |= _pGetGlobal(name, value, typePtrPair::typeCFunction); return status; } DBG_Status JLuaCallRegisteredFunction(const char* file, const char* functionPath, const char* argTypes, const char* retTypes, ...) { } } <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2012 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice 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 "OgreStableHeaders.h" #include "OgreDeflate.h" #include "OgreException.h" #include <zlib.h> namespace Ogre { // memory implementations void* OgreZalloc(void* opaque, unsigned int items, unsigned int size) { return OGRE_MALLOC(items * size, MEMCATEGORY_GENERAL); } void OgreZfree(void* opaque, void* address) { OGRE_FREE(address, MEMCATEGORY_GENERAL); } #define OGRE_DEFLATE_TMP_SIZE 16384 //--------------------------------------------------------------------- DeflateStream::DeflateStream(const DataStreamPtr& compressedStream, const String& tmpFileName) : DataStream(compressedStream->getAccessMode()) , mCompressedStream(compressedStream) , mTempFileName(tmpFileName) , mZStream(0) , mCurrentPos(0) , mTmp(0) , mIsCompressedValid(true) { init(); } //--------------------------------------------------------------------- DeflateStream::DeflateStream(const String& name, const DataStreamPtr& compressedStream, const String& tmpFileName) : DataStream(name, compressedStream->getAccessMode()) , mCompressedStream(compressedStream) , mTempFileName(tmpFileName) , mZStream(0) , mCurrentPos(0) , mTmp(0) , mIsCompressedValid(true) { init(); } //--------------------------------------------------------------------- void DeflateStream::init() { mZStream = OGRE_ALLOC_T(z_stream, 1, MEMCATEGORY_GENERAL); mZStream->zalloc = OgreZalloc; mZStream->zfree = OgreZfree; if (getAccessMode() == READ) { mTmp = (unsigned char*)OGRE_MALLOC(OGRE_DEFLATE_TMP_SIZE, MEMCATEGORY_GENERAL); size_t restorePoint = mCompressedStream->tell(); // read early chunk mZStream->next_in = mTmp; mZStream->avail_in = mCompressedStream->read(mTmp, OGRE_DEFLATE_TMP_SIZE); if (inflateInit(mZStream) != Z_OK) { mIsCompressedValid = false; } else mIsCompressedValid = true; if (mIsCompressedValid) { // in fact, inflateInit on some implementations doesn't try to read // anything. We need to at least read something to test Bytef testOut[4]; size_t savedIn = mZStream->avail_in; mZStream->avail_out = 4; mZStream->next_out = testOut; if (inflate(mZStream, Z_SYNC_FLUSH) != Z_OK) mIsCompressedValid = false; // restore for reading mZStream->avail_in = savedIn; mZStream->next_in = mTmp; inflateReset(mZStream); } if (!mIsCompressedValid) { // Not compressed data! // Fail gracefully, fall back on reading the underlying stream direct destroy(); mCompressedStream->seek(restorePoint); } } else { if(mTempFileName.empty()) { // Write to temp file char tmpname[L_tmpnam]; tmpnam(tmpname); mTempFileName = tmpname; } std::fstream *f = OGRE_NEW_T(std::fstream, MEMCATEGORY_GENERAL)(); f->open(mTempFileName.c_str(), std::ios::binary | std::ios::out); mTmpWriteStream = DataStreamPtr(OGRE_NEW FileStreamDataStream(f)); } } //--------------------------------------------------------------------- void DeflateStream::destroy() { if (getAccessMode() == READ) inflateEnd(mZStream); OGRE_FREE(mZStream, MEMCATEGORY_GENERAL); mZStream = 0; OGRE_FREE(mTmp, MEMCATEGORY_GENERAL); mTmp = 0; } //--------------------------------------------------------------------- DeflateStream::~DeflateStream() { close(); destroy(); } //--------------------------------------------------------------------- size_t DeflateStream::read(void* buf, size_t count) { if (!mIsCompressedValid) { return mCompressedStream->read(buf, count); } if (getAccessMode() & WRITE) { return mTmpWriteStream->read(buf, count); } else { size_t restorePoint = mCompressedStream->tell(); // read from cache first size_t cachereads = mReadCache.read(buf, count); size_t newReadUncompressed = 0; if (cachereads < count) { mZStream->avail_out = count - cachereads; mZStream->next_out = (Bytef*)buf + cachereads; while (mZStream->avail_out) { // Pull next chunk of compressed data from the underlying stream if (!mZStream->avail_in && !mCompressedStream->eof()) { mZStream->avail_in = mCompressedStream->read(mTmp, OGRE_DEFLATE_TMP_SIZE); mZStream->next_in = mTmp; } if (mZStream->avail_in) { int availpre = mZStream->avail_out; int status = inflate(mZStream, Z_SYNC_FLUSH); size_t readUncompressed = availpre - mZStream->avail_out; newReadUncompressed += readUncompressed; if (status != Z_OK) { // End of data, or error if (status != Z_STREAM_END) { mCompressedStream->seek(restorePoint); OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Error in compressed stream", "DeflateStrea::read"); } else { // back up the stream so that it can be used from the end onwards long unusedCompressed = mZStream->avail_in; mCompressedStream->skip(-unusedCompressed); } break; } } } } // Cache the last bytes read mReadCache.cacheData((char*)buf + cachereads, newReadUncompressed); mCurrentPos += newReadUncompressed + cachereads; return newReadUncompressed + cachereads; } } //--------------------------------------------------------------------- size_t DeflateStream::write(const void* buf, size_t count) { if ((getAccessMode() & WRITE) == 0) OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Not a writable stream", "DeflateStream::write"); return mTmpWriteStream->write(buf, count); } //--------------------------------------------------------------------- void DeflateStream::compressFinal() { // Close temp stream mTmpWriteStream->close(); // Copy & compress // We do this rather than compress directly because some code seeks // around while writing (e.g. to update size blocks) which is not // possible when compressing on the fly int ret, flush; char in[OGRE_DEFLATE_TMP_SIZE]; char out[OGRE_DEFLATE_TMP_SIZE]; if (deflateInit(mZStream, Z_DEFAULT_COMPRESSION) != Z_OK) { destroy(); OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Error initialising deflate compressed stream!", "DeflateStream::init"); } std::ifstream inFile; inFile.open(mTempFileName.c_str(), std::ios::in | std::ios::binary); do { inFile.read(in, OGRE_DEFLATE_TMP_SIZE); mZStream->avail_in = (uInt)inFile.gcount(); if (inFile.bad()) { deflateEnd(mZStream); OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Error reading temp uncompressed stream!", "DeflateStream::init"); } flush = inFile.eof() ? Z_FINISH : Z_NO_FLUSH; mZStream->next_in = (Bytef*)in; /* run deflate() on input until output buffer not full, finish compression if all of source has been read in */ do { mZStream->avail_out = OGRE_DEFLATE_TMP_SIZE; mZStream->next_out = (Bytef*)out; ret = deflate(mZStream, flush); /* no bad return value */ assert(ret != Z_STREAM_ERROR); /* state not clobbered */ size_t compressed = OGRE_DEFLATE_TMP_SIZE - mZStream->avail_out; mCompressedStream->write(out, compressed); } while (mZStream->avail_out == 0); assert(mZStream->avail_in == 0); /* all input will be used */ /* done when last data in file processed */ } while (flush != Z_FINISH); assert(ret == Z_STREAM_END); /* stream will be complete */ deflateEnd(mZStream); inFile.close(); remove(mTempFileName.c_str()); } //--------------------------------------------------------------------- void DeflateStream::skip(long count) { if (!mIsCompressedValid) { mCompressedStream->skip(count); return; } if (getAccessMode() & WRITE) { mTmpWriteStream->skip(count); } else { if (count > 0) { if (!mReadCache.ff(count)) { OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "You can only skip within the cache range in a deflate stream.", "DeflateStream::skip"); } } else if (count < 0) { if (!mReadCache.rewind((size_t)(-count))) { OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "You can only skip within the cache range in a deflate stream.", "DeflateStream::skip"); } } } mCurrentPos = static_cast<size_t>(static_cast<long>(mCurrentPos) + count); } //--------------------------------------------------------------------- void DeflateStream::seek( size_t pos ) { if (!mIsCompressedValid) { mCompressedStream->seek(pos); return; } if (getAccessMode() & WRITE) { mTmpWriteStream->seek(pos); } else { if (pos == 0) { mCurrentPos = 0; mZStream->next_in = mTmp; mCompressedStream->seek(0); mZStream->avail_in = mCompressedStream->read(mTmp, OGRE_DEFLATE_TMP_SIZE); inflateReset(mZStream); } else { skip(pos - tell()); } } } //--------------------------------------------------------------------- size_t DeflateStream::tell(void) const { if (!mIsCompressedValid) { return mCompressedStream->tell(); } else if(getAccessMode() & WRITE) { return mTmpWriteStream->tell(); } else { return mCurrentPos; } } //--------------------------------------------------------------------- bool DeflateStream::eof(void) const { if (getAccessMode() & WRITE) return mTmpWriteStream->eof(); else { if (!mIsCompressedValid) return mCompressedStream->eof(); else return mCompressedStream->eof() && mZStream->avail_in == 0; } } //--------------------------------------------------------------------- void DeflateStream::close(void) { if (getAccessMode() & WRITE) { compressFinal(); } // don't close underlying compressed stream in case used for something else } //--------------------------------------------------------------------- } <commit_msg>Fix [3538259]: Use _tempnam on Windows to generate temporary file name in OgreDeflate.cpp<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2012 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice 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 "OgreStableHeaders.h" #include "OgreDeflate.h" #include "OgreException.h" #include <zlib.h> namespace Ogre { // memory implementations void* OgreZalloc(void* opaque, unsigned int items, unsigned int size) { return OGRE_MALLOC(items * size, MEMCATEGORY_GENERAL); } void OgreZfree(void* opaque, void* address) { OGRE_FREE(address, MEMCATEGORY_GENERAL); } #define OGRE_DEFLATE_TMP_SIZE 16384 //--------------------------------------------------------------------- DeflateStream::DeflateStream(const DataStreamPtr& compressedStream, const String& tmpFileName) : DataStream(compressedStream->getAccessMode()) , mCompressedStream(compressedStream) , mTempFileName(tmpFileName) , mZStream(0) , mCurrentPos(0) , mTmp(0) , mIsCompressedValid(true) { init(); } //--------------------------------------------------------------------- DeflateStream::DeflateStream(const String& name, const DataStreamPtr& compressedStream, const String& tmpFileName) : DataStream(name, compressedStream->getAccessMode()) , mCompressedStream(compressedStream) , mTempFileName(tmpFileName) , mZStream(0) , mCurrentPos(0) , mTmp(0) , mIsCompressedValid(true) { init(); } //--------------------------------------------------------------------- void DeflateStream::init() { mZStream = OGRE_ALLOC_T(z_stream, 1, MEMCATEGORY_GENERAL); mZStream->zalloc = OgreZalloc; mZStream->zfree = OgreZfree; if (getAccessMode() == READ) { mTmp = (unsigned char*)OGRE_MALLOC(OGRE_DEFLATE_TMP_SIZE, MEMCATEGORY_GENERAL); size_t restorePoint = mCompressedStream->tell(); // read early chunk mZStream->next_in = mTmp; mZStream->avail_in = mCompressedStream->read(mTmp, OGRE_DEFLATE_TMP_SIZE); if (inflateInit(mZStream) != Z_OK) { mIsCompressedValid = false; } else mIsCompressedValid = true; if (mIsCompressedValid) { // in fact, inflateInit on some implementations doesn't try to read // anything. We need to at least read something to test Bytef testOut[4]; size_t savedIn = mZStream->avail_in; mZStream->avail_out = 4; mZStream->next_out = testOut; if (inflate(mZStream, Z_SYNC_FLUSH) != Z_OK) mIsCompressedValid = false; // restore for reading mZStream->avail_in = savedIn; mZStream->next_in = mTmp; inflateReset(mZStream); } if (!mIsCompressedValid) { // Not compressed data! // Fail gracefully, fall back on reading the underlying stream direct destroy(); mCompressedStream->seek(restorePoint); } } else { if(mTempFileName.empty()) { // Write to temp file #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 char* tmpname = _tempnam(".", "ogre"); if (!tmpname) { // Having no file name here will cause various problems later. OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Temporary file name generation failed.", "DeflateStream::init"); } else { mTempFileName = tmpname; free(tmpname); } #else char tmpname[L_tmpnam]; tmpnam(tmpname); mTempFileName = tmpname; #endif } std::fstream *f = OGRE_NEW_T(std::fstream, MEMCATEGORY_GENERAL)(); f->open(mTempFileName.c_str(), std::ios::binary | std::ios::out); mTmpWriteStream = DataStreamPtr(OGRE_NEW FileStreamDataStream(f)); } } //--------------------------------------------------------------------- void DeflateStream::destroy() { if (getAccessMode() == READ) inflateEnd(mZStream); OGRE_FREE(mZStream, MEMCATEGORY_GENERAL); mZStream = 0; OGRE_FREE(mTmp, MEMCATEGORY_GENERAL); mTmp = 0; } //--------------------------------------------------------------------- DeflateStream::~DeflateStream() { close(); destroy(); } //--------------------------------------------------------------------- size_t DeflateStream::read(void* buf, size_t count) { if (!mIsCompressedValid) { return mCompressedStream->read(buf, count); } if (getAccessMode() & WRITE) { return mTmpWriteStream->read(buf, count); } else { size_t restorePoint = mCompressedStream->tell(); // read from cache first size_t cachereads = mReadCache.read(buf, count); size_t newReadUncompressed = 0; if (cachereads < count) { mZStream->avail_out = count - cachereads; mZStream->next_out = (Bytef*)buf + cachereads; while (mZStream->avail_out) { // Pull next chunk of compressed data from the underlying stream if (!mZStream->avail_in && !mCompressedStream->eof()) { mZStream->avail_in = mCompressedStream->read(mTmp, OGRE_DEFLATE_TMP_SIZE); mZStream->next_in = mTmp; } if (mZStream->avail_in) { int availpre = mZStream->avail_out; int status = inflate(mZStream, Z_SYNC_FLUSH); size_t readUncompressed = availpre - mZStream->avail_out; newReadUncompressed += readUncompressed; if (status != Z_OK) { // End of data, or error if (status != Z_STREAM_END) { mCompressedStream->seek(restorePoint); OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Error in compressed stream", "DeflateStrea::read"); } else { // back up the stream so that it can be used from the end onwards long unusedCompressed = mZStream->avail_in; mCompressedStream->skip(-unusedCompressed); } break; } } } } // Cache the last bytes read mReadCache.cacheData((char*)buf + cachereads, newReadUncompressed); mCurrentPos += newReadUncompressed + cachereads; return newReadUncompressed + cachereads; } } //--------------------------------------------------------------------- size_t DeflateStream::write(const void* buf, size_t count) { if ((getAccessMode() & WRITE) == 0) OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Not a writable stream", "DeflateStream::write"); return mTmpWriteStream->write(buf, count); } //--------------------------------------------------------------------- void DeflateStream::compressFinal() { // Close temp stream mTmpWriteStream->close(); // Copy & compress // We do this rather than compress directly because some code seeks // around while writing (e.g. to update size blocks) which is not // possible when compressing on the fly int ret, flush; char in[OGRE_DEFLATE_TMP_SIZE]; char out[OGRE_DEFLATE_TMP_SIZE]; if (deflateInit(mZStream, Z_DEFAULT_COMPRESSION) != Z_OK) { destroy(); OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Error initialising deflate compressed stream!", "DeflateStream::init"); } std::ifstream inFile; inFile.open(mTempFileName.c_str(), std::ios::in | std::ios::binary); do { inFile.read(in, OGRE_DEFLATE_TMP_SIZE); mZStream->avail_in = (uInt)inFile.gcount(); if (inFile.bad()) { deflateEnd(mZStream); OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "Error reading temp uncompressed stream!", "DeflateStream::init"); } flush = inFile.eof() ? Z_FINISH : Z_NO_FLUSH; mZStream->next_in = (Bytef*)in; /* run deflate() on input until output buffer not full, finish compression if all of source has been read in */ do { mZStream->avail_out = OGRE_DEFLATE_TMP_SIZE; mZStream->next_out = (Bytef*)out; ret = deflate(mZStream, flush); /* no bad return value */ assert(ret != Z_STREAM_ERROR); /* state not clobbered */ size_t compressed = OGRE_DEFLATE_TMP_SIZE - mZStream->avail_out; mCompressedStream->write(out, compressed); } while (mZStream->avail_out == 0); assert(mZStream->avail_in == 0); /* all input will be used */ /* done when last data in file processed */ } while (flush != Z_FINISH); assert(ret == Z_STREAM_END); /* stream will be complete */ deflateEnd(mZStream); inFile.close(); remove(mTempFileName.c_str()); } //--------------------------------------------------------------------- void DeflateStream::skip(long count) { if (!mIsCompressedValid) { mCompressedStream->skip(count); return; } if (getAccessMode() & WRITE) { mTmpWriteStream->skip(count); } else { if (count > 0) { if (!mReadCache.ff(count)) { OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "You can only skip within the cache range in a deflate stream.", "DeflateStream::skip"); } } else if (count < 0) { if (!mReadCache.rewind((size_t)(-count))) { OGRE_EXCEPT(Exception::ERR_INVALID_STATE, "You can only skip within the cache range in a deflate stream.", "DeflateStream::skip"); } } } mCurrentPos = static_cast<size_t>(static_cast<long>(mCurrentPos) + count); } //--------------------------------------------------------------------- void DeflateStream::seek( size_t pos ) { if (!mIsCompressedValid) { mCompressedStream->seek(pos); return; } if (getAccessMode() & WRITE) { mTmpWriteStream->seek(pos); } else { if (pos == 0) { mCurrentPos = 0; mZStream->next_in = mTmp; mCompressedStream->seek(0); mZStream->avail_in = mCompressedStream->read(mTmp, OGRE_DEFLATE_TMP_SIZE); inflateReset(mZStream); } else { skip(pos - tell()); } } } //--------------------------------------------------------------------- size_t DeflateStream::tell(void) const { if (!mIsCompressedValid) { return mCompressedStream->tell(); } else if(getAccessMode() & WRITE) { return mTmpWriteStream->tell(); } else { return mCurrentPos; } } //--------------------------------------------------------------------- bool DeflateStream::eof(void) const { if (getAccessMode() & WRITE) return mTmpWriteStream->eof(); else { if (!mIsCompressedValid) return mCompressedStream->eof(); else return mCompressedStream->eof() && mZStream->avail_in == 0; } } //--------------------------------------------------------------------- void DeflateStream::close(void) { if (getAccessMode() & WRITE) { compressFinal(); } // don't close underlying compressed stream in case used for something else } //--------------------------------------------------------------------- } <|endoftext|>
<commit_before>/* Copyright (C) 2013 Martin Klapetek <[email protected]> Copyright (C) 2014 David Edmundson <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "im-persons-data-source.h" #include <TelepathyQt/AccountManager> #include <TelepathyQt/AccountFactory> #include <TelepathyQt/ContactManager> #include <TelepathyQt/PendingOperation> #include <TelepathyQt/PendingReady> #include <TelepathyQt/Presence> #include "KTp/contact-factory.h" #include "KTp/global-contact-manager.h" #include "KTp/types.h" #include "debug.h" #include <KPeopleBackend/AllContactsMonitor> #include <KPluginFactory> #include <KPluginLoader> #include <QSqlDatabase> #include <QSqlQuery> #include <QPixmap> using namespace KPeople; class KTpAllContacts : public AllContactsMonitor { Q_OBJECT public: KTpAllContacts(); ~KTpAllContacts(); virtual QMap<QString, AbstractContact::Ptr> contacts() Q_DECL_OVERRIDE; private Q_SLOTS: void loadCache(); void onAccountManagerReady(Tp::PendingOperation *op); void onContactChanged(); void onContactInvalidated(); void onAllKnownContactsChanged(const Tp::Contacts &contactsAdded, const Tp::Contacts &contactsRemoved); private: QString createUri(const KTp::ContactPtr &contact) const; //presence names indexed by ConnectionPresenceType QHash<QString, KTp::ContactPtr> m_contacts; QMap<QString, AbstractContact::Ptr> m_contactVCards; }; static const QString S_KPEOPLE_PROPERTY_ACCOUNT_PATH = QString::fromLatin1("telepathy-accountPath"); static const QString S_KPEOPLE_PROPERTY_CONTACT_ID = QString::fromLatin1("telepathy-contactId"); static const QString S_KPEOPLE_PROPERTY_PRESENCE = QString::fromLatin1("telepathy-presence"); const QHash<Tp::ConnectionPresenceType, QString> s_presenceStrings = { { Tp::ConnectionPresenceTypeUnset, QString() }, { Tp::ConnectionPresenceTypeOffline, QString::fromLatin1("offline") }, { Tp::ConnectionPresenceTypeAvailable, QString::fromLatin1("available") }, { Tp::ConnectionPresenceTypeAway, QString::fromLatin1("away") }, { Tp::ConnectionPresenceTypeExtendedAway, QString::fromLatin1("xa") }, { Tp::ConnectionPresenceTypeHidden, QString::fromLatin1("hidden") }, //of 'offline' ? { Tp::ConnectionPresenceTypeBusy, QString::fromLatin1("busy") }, { Tp::ConnectionPresenceTypeUnknown, QString() }, { Tp::ConnectionPresenceTypeError, QString() } }; class TelepathyContact : public KPeople::AbstractContact { public: virtual QVariant customProperty(const QString &key) const Q_DECL_OVERRIDE { if (m_contact && m_account) { if (key == AbstractContact::NameProperty) return m_contact->alias(); else if(key == AbstractContact::GroupsProperty) return m_contact->groups(); else if(key == S_KPEOPLE_PROPERTY_CONTACT_ID) return m_contact->id(); else if(key == S_KPEOPLE_PROPERTY_ACCOUNT_PATH) return m_account->objectPath(); else if(key == S_KPEOPLE_PROPERTY_PRESENCE) return s_presenceStrings.value(m_contact->presence().type()); else if (key == AbstractContact::PictureProperty) return m_contact->avatarPixmap(); } return m_properties[key]; } void insertProperty(const QString &key, const QVariant &value) { m_properties[key] = value; } void setContact(const KTp::ContactPtr &contact) { m_contact = contact; } void setAccount(const Tp::AccountPtr &account) { m_account = account; } private: KTp::ContactPtr m_contact; Tp::AccountPtr m_account; QVariantMap m_properties; }; KTpAllContacts::KTpAllContacts() { Tp::registerTypes(); loadCache(); } KTpAllContacts::~KTpAllContacts() { } void KTpAllContacts::loadCache() { QSqlDatabase db = QSqlDatabase::addDatabase(QLatin1String("QSQLITE"), QLatin1String("ktpCache")); QString path = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1String("/ktp"); QDir().mkpath(path); db.setDatabaseName(path+QStringLiteral("/cache.db")); if (!db.open()) { qWarning() << "couldn't open database" << db.databaseName(); } QSqlQuery query(db); query.exec(QLatin1String("SELECT groupName FROM groups ORDER BY groupId;")); QStringList groupsList; while (query.next()) { groupsList.append(query.value(0).toString()); } if (!groupsList.isEmpty()) { query.exec(QLatin1String("SELECT accountId, contactId, alias, avatarFileName, groupsIds FROM contacts;")); } else { query.exec(QLatin1String("SELECT accountId, contactId, alias, avatarFileName FROM contacts;")); } while (query.next()) { QExplicitlySharedDataPointer<TelepathyContact> addressee(new TelepathyContact); const QString accountId = query.value(0).toString(); const QString contactId = query.value(1).toString(); addressee->insertProperty(AbstractContact::NameProperty, query.value(2).toString()); addressee->insertProperty(AbstractContact::PictureProperty, QUrl::fromLocalFile(query.value(3).toString())); if (!groupsList.isEmpty()) { QVariantList contactGroups; Q_FOREACH (const QString &groupIdStr, query.value(4).toString().split(QLatin1String(","))) { bool convSuccess; int groupId = groupIdStr.toInt(&convSuccess); if ((!convSuccess) || (groupId >= groupsList.count())) continue; contactGroups.append(groupsList.at(groupId)); } addressee->insertProperty(QStringLiteral("groups"), contactGroups); } addressee->insertProperty(S_KPEOPLE_PROPERTY_CONTACT_ID, contactId); addressee->insertProperty(S_KPEOPLE_PROPERTY_ACCOUNT_PATH, TP_QT_ACCOUNT_OBJECT_PATH_BASE + QLatin1Char('/') + accountId); addressee->insertProperty(S_KPEOPLE_PROPERTY_PRESENCE, s_presenceStrings[Tp::ConnectionPresenceTypeOffline]); const QString uri = QLatin1String("ktp://") + accountId + QLatin1Char('?') + contactId; m_contactVCards[uri] = addressee; Q_EMIT contactAdded(uri, addressee); } //now start fetching the up-to-date information connect(KTp::accountManager()->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), this, SLOT(onAccountManagerReady(Tp::PendingOperation*))); emitInitialFetchComplete(true); } QString KTpAllContacts::createUri(const KTp::ContactPtr &contact) const { // so real ID will look like // ktp://gabble/jabber/blah/[email protected] // ? is used as it is not a valid character in the dbus path that makes up the account UID return QLatin1String("ktp://") + contact->accountUniqueIdentifier() + QLatin1Char('?') + contact->id(); } void KTpAllContacts::onAccountManagerReady(Tp::PendingOperation *op) { if (op->isError()) { qCWarning(KTP_KPEOPLE) << "Failed to initialize AccountManager:" << op->errorName(); qCWarning(KTP_KPEOPLE) << op->errorMessage(); return; } qCDebug(KTP_KPEOPLE) << "Account manager ready"; connect(KTp::contactManager(), SIGNAL(allKnownContactsChanged(Tp::Contacts,Tp::Contacts)), this, SLOT(onAllKnownContactsChanged(Tp::Contacts,Tp::Contacts))); onAllKnownContactsChanged(KTp::contactManager()->allKnownContacts(), Tp::Contacts()); } void KTpAllContacts::onAllKnownContactsChanged(const Tp::Contacts &contactsAdded, const Tp::Contacts &contactsRemoved) { if (!m_contacts.isEmpty()) { Q_FOREACH (const Tp::ContactPtr &c, contactsRemoved) { const KTp::ContactPtr &contact = KTp::ContactPtr::qObjectCast(c); const QString uri = createUri(contact); m_contacts.remove(uri); m_contactVCards.remove(uri); Q_EMIT contactRemoved(uri); } } Q_FOREACH (const Tp::ContactPtr &contact, contactsAdded) { KTp::ContactPtr ktpContact = KTp::ContactPtr::qObjectCast(contact); const QString uri = createUri(ktpContact); AbstractContact::Ptr vcard = m_contactVCards.value(uri); bool added = false; if (!vcard) { vcard = AbstractContact::Ptr(new TelepathyContact); m_contactVCards[uri] = vcard; added = true; } static_cast<TelepathyContact*>(vcard.data())->setContact(ktpContact); static_cast<TelepathyContact*>(vcard.data())->setAccount(KTp::contactManager()->accountForContact(ktpContact)); m_contacts.insert(uri, ktpContact); if (added) { Q_EMIT contactAdded(uri, vcard); } else { Q_EMIT contactChanged(uri, vcard); } connect(ktpContact.data(), SIGNAL(presenceChanged(Tp::Presence)), this, SLOT(onContactChanged())); connect(ktpContact.data(), SIGNAL(capabilitiesChanged(Tp::ContactCapabilities)), this, SLOT(onContactChanged())); connect(ktpContact.data(), SIGNAL(invalidated()), this, SLOT(onContactInvalidated())); connect(ktpContact.data(), SIGNAL(avatarDataChanged(Tp::AvatarData)), this, SLOT(onContactChanged())); connect(ktpContact.data(), SIGNAL(addedToGroup(QString)), this, SLOT(onContactChanged())); connect(ktpContact.data(), SIGNAL(removedFromGroup(QString)), this, SLOT(onContactChanged())); } } void KTpAllContacts::onContactChanged() { const KTp::ContactPtr contact(qobject_cast<KTp::Contact*>(sender())); const QString uri = createUri(contact); Q_EMIT contactChanged(uri, m_contactVCards.value(uri)); } void KTpAllContacts::onContactInvalidated() { const KTp::ContactPtr contact(qobject_cast<KTp::Contact*>(sender())); const QString uri = createUri(contact); m_contacts.remove(uri); //set to offline and emit changed AbstractContact::Ptr vcard = m_contactVCards[uri]; TelepathyContact *tpContact = static_cast<TelepathyContact*>(vcard.data()); tpContact->insertProperty(S_KPEOPLE_PROPERTY_PRESENCE, QStringLiteral("offline")); Q_EMIT contactChanged(uri, vcard); } QMap<QString, AbstractContact::Ptr> KTpAllContacts::contacts() { return m_contactVCards; } IMPersonsDataSource::IMPersonsDataSource(QObject *parent, const QVariantList &args) : BasePersonsDataSource(parent) { Q_UNUSED(args); } IMPersonsDataSource::~IMPersonsDataSource() { } QString IMPersonsDataSource::sourcePluginId() const { return QStringLiteral("ktp"); } AllContactsMonitor* IMPersonsDataSource::createAllContactsMonitor() { return new KTpAllContacts(); } K_PLUGIN_FACTORY( IMPersonsDataSourceFactory, registerPlugin<IMPersonsDataSource>(); ) K_EXPORT_PLUGIN( IMPersonsDataSourceFactory("im_persons_data_source_plugin") ) #include "im-persons-data-source.moc" <commit_msg>Check for contact actually being valid before using it<commit_after>/* Copyright (C) 2013 Martin Klapetek <[email protected]> Copyright (C) 2014 David Edmundson <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "im-persons-data-source.h" #include <TelepathyQt/AccountManager> #include <TelepathyQt/AccountFactory> #include <TelepathyQt/ContactManager> #include <TelepathyQt/PendingOperation> #include <TelepathyQt/PendingReady> #include <TelepathyQt/Presence> #include "KTp/contact-factory.h" #include "KTp/global-contact-manager.h" #include "KTp/types.h" #include "debug.h" #include <KPeopleBackend/AllContactsMonitor> #include <KPluginFactory> #include <KPluginLoader> #include <QSqlDatabase> #include <QSqlQuery> #include <QPixmap> using namespace KPeople; class KTpAllContacts : public AllContactsMonitor { Q_OBJECT public: KTpAllContacts(); ~KTpAllContacts(); virtual QMap<QString, AbstractContact::Ptr> contacts() Q_DECL_OVERRIDE; private Q_SLOTS: void loadCache(); void onAccountManagerReady(Tp::PendingOperation *op); void onContactChanged(); void onContactInvalidated(); void onAllKnownContactsChanged(const Tp::Contacts &contactsAdded, const Tp::Contacts &contactsRemoved); private: QString createUri(const KTp::ContactPtr &contact) const; //presence names indexed by ConnectionPresenceType QHash<QString, KTp::ContactPtr> m_contacts; QMap<QString, AbstractContact::Ptr> m_contactVCards; }; static const QString S_KPEOPLE_PROPERTY_ACCOUNT_PATH = QString::fromLatin1("telepathy-accountPath"); static const QString S_KPEOPLE_PROPERTY_CONTACT_ID = QString::fromLatin1("telepathy-contactId"); static const QString S_KPEOPLE_PROPERTY_PRESENCE = QString::fromLatin1("telepathy-presence"); const QHash<Tp::ConnectionPresenceType, QString> s_presenceStrings = { { Tp::ConnectionPresenceTypeUnset, QString() }, { Tp::ConnectionPresenceTypeOffline, QString::fromLatin1("offline") }, { Tp::ConnectionPresenceTypeAvailable, QString::fromLatin1("available") }, { Tp::ConnectionPresenceTypeAway, QString::fromLatin1("away") }, { Tp::ConnectionPresenceTypeExtendedAway, QString::fromLatin1("xa") }, { Tp::ConnectionPresenceTypeHidden, QString::fromLatin1("hidden") }, //of 'offline' ? { Tp::ConnectionPresenceTypeBusy, QString::fromLatin1("busy") }, { Tp::ConnectionPresenceTypeUnknown, QString() }, { Tp::ConnectionPresenceTypeError, QString() } }; class TelepathyContact : public KPeople::AbstractContact { public: virtual QVariant customProperty(const QString &key) const Q_DECL_OVERRIDE { // Check if the contact is valid first if (m_contact && m_contact->manager() && m_contact->manager()->connection() && m_account) { if (key == AbstractContact::NameProperty) return m_contact->alias(); else if(key == AbstractContact::GroupsProperty) return m_contact->groups(); else if(key == S_KPEOPLE_PROPERTY_CONTACT_ID) return m_contact->id(); else if(key == S_KPEOPLE_PROPERTY_ACCOUNT_PATH) return m_account->objectPath(); else if(key == S_KPEOPLE_PROPERTY_PRESENCE) return s_presenceStrings.value(m_contact->presence().type()); else if (key == AbstractContact::PictureProperty) return m_contact->avatarPixmap(); } return m_properties[key]; } void insertProperty(const QString &key, const QVariant &value) { m_properties[key] = value; } void setContact(const KTp::ContactPtr &contact) { m_contact = contact; } void setAccount(const Tp::AccountPtr &account) { m_account = account; } private: KTp::ContactPtr m_contact; Tp::AccountPtr m_account; QVariantMap m_properties; }; KTpAllContacts::KTpAllContacts() { Tp::registerTypes(); loadCache(); } KTpAllContacts::~KTpAllContacts() { } void KTpAllContacts::loadCache() { QSqlDatabase db = QSqlDatabase::addDatabase(QLatin1String("QSQLITE"), QLatin1String("ktpCache")); QString path = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1String("/ktp"); QDir().mkpath(path); db.setDatabaseName(path+QStringLiteral("/cache.db")); if (!db.open()) { qWarning() << "couldn't open database" << db.databaseName(); } QSqlQuery query(db); query.exec(QLatin1String("SELECT groupName FROM groups ORDER BY groupId;")); QStringList groupsList; while (query.next()) { groupsList.append(query.value(0).toString()); } if (!groupsList.isEmpty()) { query.exec(QLatin1String("SELECT accountId, contactId, alias, avatarFileName, groupsIds FROM contacts;")); } else { query.exec(QLatin1String("SELECT accountId, contactId, alias, avatarFileName FROM contacts;")); } while (query.next()) { QExplicitlySharedDataPointer<TelepathyContact> addressee(new TelepathyContact); const QString accountId = query.value(0).toString(); const QString contactId = query.value(1).toString(); addressee->insertProperty(AbstractContact::NameProperty, query.value(2).toString()); addressee->insertProperty(AbstractContact::PictureProperty, QUrl::fromLocalFile(query.value(3).toString())); if (!groupsList.isEmpty()) { QVariantList contactGroups; Q_FOREACH (const QString &groupIdStr, query.value(4).toString().split(QLatin1String(","))) { bool convSuccess; int groupId = groupIdStr.toInt(&convSuccess); if ((!convSuccess) || (groupId >= groupsList.count())) continue; contactGroups.append(groupsList.at(groupId)); } addressee->insertProperty(QStringLiteral("groups"), contactGroups); } addressee->insertProperty(S_KPEOPLE_PROPERTY_CONTACT_ID, contactId); addressee->insertProperty(S_KPEOPLE_PROPERTY_ACCOUNT_PATH, TP_QT_ACCOUNT_OBJECT_PATH_BASE + QLatin1Char('/') + accountId); addressee->insertProperty(S_KPEOPLE_PROPERTY_PRESENCE, s_presenceStrings[Tp::ConnectionPresenceTypeOffline]); const QString uri = QLatin1String("ktp://") + accountId + QLatin1Char('?') + contactId; m_contactVCards[uri] = addressee; Q_EMIT contactAdded(uri, addressee); } //now start fetching the up-to-date information connect(KTp::accountManager()->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), this, SLOT(onAccountManagerReady(Tp::PendingOperation*))); emitInitialFetchComplete(true); } QString KTpAllContacts::createUri(const KTp::ContactPtr &contact) const { // so real ID will look like // ktp://gabble/jabber/blah/[email protected] // ? is used as it is not a valid character in the dbus path that makes up the account UID return QLatin1String("ktp://") + contact->accountUniqueIdentifier() + QLatin1Char('?') + contact->id(); } void KTpAllContacts::onAccountManagerReady(Tp::PendingOperation *op) { if (op->isError()) { qCWarning(KTP_KPEOPLE) << "Failed to initialize AccountManager:" << op->errorName(); qCWarning(KTP_KPEOPLE) << op->errorMessage(); return; } qCDebug(KTP_KPEOPLE) << "Account manager ready"; connect(KTp::contactManager(), SIGNAL(allKnownContactsChanged(Tp::Contacts,Tp::Contacts)), this, SLOT(onAllKnownContactsChanged(Tp::Contacts,Tp::Contacts))); onAllKnownContactsChanged(KTp::contactManager()->allKnownContacts(), Tp::Contacts()); } void KTpAllContacts::onAllKnownContactsChanged(const Tp::Contacts &contactsAdded, const Tp::Contacts &contactsRemoved) { if (!m_contacts.isEmpty()) { Q_FOREACH (const Tp::ContactPtr &c, contactsRemoved) { const KTp::ContactPtr &contact = KTp::ContactPtr::qObjectCast(c); const QString uri = createUri(contact); m_contacts.remove(uri); m_contactVCards.remove(uri); Q_EMIT contactRemoved(uri); } } Q_FOREACH (const Tp::ContactPtr &contact, contactsAdded) { KTp::ContactPtr ktpContact = KTp::ContactPtr::qObjectCast(contact); const QString uri = createUri(ktpContact); AbstractContact::Ptr vcard = m_contactVCards.value(uri); bool added = false; if (!vcard) { vcard = AbstractContact::Ptr(new TelepathyContact); m_contactVCards[uri] = vcard; added = true; } static_cast<TelepathyContact*>(vcard.data())->setContact(ktpContact); static_cast<TelepathyContact*>(vcard.data())->setAccount(KTp::contactManager()->accountForContact(ktpContact)); m_contacts.insert(uri, ktpContact); if (added) { Q_EMIT contactAdded(uri, vcard); } else { Q_EMIT contactChanged(uri, vcard); } connect(ktpContact.data(), SIGNAL(presenceChanged(Tp::Presence)), this, SLOT(onContactChanged())); connect(ktpContact.data(), SIGNAL(capabilitiesChanged(Tp::ContactCapabilities)), this, SLOT(onContactChanged())); connect(ktpContact.data(), SIGNAL(invalidated()), this, SLOT(onContactInvalidated())); connect(ktpContact.data(), SIGNAL(avatarDataChanged(Tp::AvatarData)), this, SLOT(onContactChanged())); connect(ktpContact.data(), SIGNAL(addedToGroup(QString)), this, SLOT(onContactChanged())); connect(ktpContact.data(), SIGNAL(removedFromGroup(QString)), this, SLOT(onContactChanged())); } } void KTpAllContacts::onContactChanged() { const KTp::ContactPtr contact(qobject_cast<KTp::Contact*>(sender())); const QString uri = createUri(contact); Q_EMIT contactChanged(uri, m_contactVCards.value(uri)); } void KTpAllContacts::onContactInvalidated() { const KTp::ContactPtr contact(qobject_cast<KTp::Contact*>(sender())); const QString uri = createUri(contact); m_contacts.remove(uri); //set to offline and emit changed AbstractContact::Ptr vcard = m_contactVCards[uri]; TelepathyContact *tpContact = static_cast<TelepathyContact*>(vcard.data()); tpContact->insertProperty(S_KPEOPLE_PROPERTY_PRESENCE, QStringLiteral("offline")); Q_EMIT contactChanged(uri, vcard); } QMap<QString, AbstractContact::Ptr> KTpAllContacts::contacts() { return m_contactVCards; } IMPersonsDataSource::IMPersonsDataSource(QObject *parent, const QVariantList &args) : BasePersonsDataSource(parent) { Q_UNUSED(args); } IMPersonsDataSource::~IMPersonsDataSource() { } QString IMPersonsDataSource::sourcePluginId() const { return QStringLiteral("ktp"); } AllContactsMonitor* IMPersonsDataSource::createAllContactsMonitor() { return new KTpAllContacts(); } K_PLUGIN_FACTORY( IMPersonsDataSourceFactory, registerPlugin<IMPersonsDataSource>(); ) K_EXPORT_PLUGIN( IMPersonsDataSourceFactory("im_persons_data_source_plugin") ) #include "im-persons-data-source.moc" <|endoftext|>
<commit_before>#include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <sys/time.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <iostream> #include <fstream> #include <boost/lexical_cast.hpp> #include "packet.h" #define USAGE "Usage:\r\nc \r\n[tux machine number] \r\n[probability of packet corruption in int form] \r\n[probability of packet loss in int form] \r\n[probability of packet delay] \r\n[length of delay in ms] \r\n" #define PORT 10038 #define PAKSIZE 512 #define ACK 0 #define NAK 1 #define BUFSIZE 505 #define FILENAME "Testfile" #define TIMEOUT 15 //in ms #define WIN_SIZE 16 using namespace std; bool isvpack(unsigned char * p); bool init(int argc, char** argv); bool loadFile(); bool getFile(); bool sendFile(); bool isAck(); void handleAck(); void handleNak(int& x); bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb); Packet createPacket(int index); void loadWindow(); bool sendPacket(); bool getGet(); struct sockaddr_in a; struct sockaddr_in ca; socklen_t calen; int rlen; int s; bool ack; string fstr; char * file; int probCorrupt; int probLoss; int probDelay; int delayT; Packet p; Packet window[16]; int length; bool dropPck; bool delayPck; int toms; unsigned char b[BUFSIZE]; int base; int main(int argc, char** argv) { if(!init(argc, argv)) return -1; if(sendFile()) cout << "GET Testfile complete." << endl; return 0; } bool init(int argc, char** argv){ if(argc != 6) { cout << USAGE << endl; return false; } char * probCorruptStr = argv[2]; probCorrupt = boost::lexical_cast<int>(probCorruptStr); char * probLossStr = argv[3]; probLoss = boost::lexical_cast<int>(probLossStr); char * probDelayStr = argv[4]; probDelay = boost::lexical_cast<int>(probDelayStr); char* delayTStr = argv[5]; delayT = boost::lexical_cast<int>(delayTStr); struct timeval timeout; timeout.tv_usec = TIMEOUT * 1000; toms = TIMEOUT; /* Create our socket. */ if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { cout << "Socket creation failed. (socket s)" << endl; return 0; } setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout)); /* * Bind our socket to an IP (whatever the computer decides) * and a specified port. * */ if (!loadFile()) { cout << "Loading file failed. (filename FILENAME)" << endl; return false; } memset((char *)&a, 0, sizeof(a)); a.sin_family = AF_INET; a.sin_addr.s_addr = htonl(INADDR_ANY); a.sin_port = htons(PORT); if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0) { cout << "Socket binding failed. (socket s, address a)" << endl; return 0; } fstr = string(file); cout << "File: " << endl << fstr << endl; base = 0; dropPck = false; calen = sizeof(ca); getGet(); return true; } bool getGet(){ unsigned char packet[PAKSIZE + 1]; rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen); return (rlen > 0) ? true : false; } bool isvpack(unsigned char * p) { cout << endl << "=== IS VALID PACKET TESTING" << endl; char * sns = new char[2]; memcpy(sns, &p[0], 1); sns[1] = '\0'; char * css = new char[7]; memcpy(css, &p[1], 6); css[6] = '\0'; char * db = new char[121 + 1]; memcpy(db, &p[2], 121); db[121] = '\0'; cout << "Seq. num: " << sns << endl; cout << "Checksum: " << css << endl; cout << "Message: " << db << endl; int sn = boost::lexical_cast<int>(sns); int cs = boost::lexical_cast<int>(css); Packet pk (0, db); pk.setSequenceNum(sn); // change to validate based on checksum and sequence number if(sn == 0) return false; //doesn't matter, only for the old version (netwark) if(cs != pk.generateCheckSum()) return false; return true; } bool getFile(){ /* Loop forever, waiting for messages from a client. */ cout << "Waiting on port " << PORT << "..." << endl; ofstream file("Dumpfile"); for (;;) { unsigned char packet[PAKSIZE + 1]; unsigned char dataPull[PAKSIZE - 7 + 1]; rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen); for(int x = 0; x < PAKSIZE - 7; x++) { dataPull[x] = packet[x + 7]; } dataPull[PAKSIZE - 7] = '\0'; packet[PAKSIZE] = '\0'; if (rlen > 0) { char * css = new char[6]; memcpy(css, &packet[1], 5); css[5] = '\0'; cout << endl << endl << "=== RECEIPT" << endl; cout << "Seq. num: " << packet[0] << endl; cout << "Checksum: " << css << endl; cout << "Received message: " << dataPull << endl; cout << "Sent response: "; if(isvpack(packet)) { ack = ACK; //seqNum = (seqNum) ? false : true; file << dataPull; } else { ack = NAK; } cout << ((ack == ACK) ? "ACK" : "NAK") << endl; Packet p (false, reinterpret_cast<const char *>(dataPull)); p.setCheckSum(boost::lexical_cast<int>(css)); p.setAckNack(ack); if(sendto(s, p.str(), PAKSIZE, 0, (struct sockaddr *)&ca, calen) < 0) { cout << "Acknowledgement failed. (socket s, acknowledgement message ack, client address ca, client address length calen)" << endl; return 0; } delete css; } } file.close(); return true; } bool loadFile() { ifstream is (FILENAME, ifstream::binary); if(is) { is.seekg(0, is.end); length = is.tellg(); is.seekg(0, is.beg); file = new char[length]; cout << "Reading " << length << " characters..." << endl; is.read(file, length); if(!is) { cout << "File reading failed. (filename " << FILENAME << "). Only " << is.gcount() << " could be read."; return false; } is.close(); } return true; } void loadWindow(){ for(int i = base; i < base + WIN_SIZE; i++) { window[i-base] = createPacket(i); if(strlen(window[i-base].getDataBuffer()) < BUFSIZE && window[i-base].chksm()) { cout << "In loadWindow's secret base, index is: " << i-base << endl; for(++i; i < base + WIN_SIZE; i++){ window[i-base].loadDataBuffer("\0"); } } /*cout << "window[i-base] seq. num: " << window[i-base].getSequenceNum() << endl;*/ } /*cout << "packet " << base + 1 << ": " << window[1].str() << endl; cout << "packet " << base + 2 << ": " << window[2].str() << endl;*/ } bool sendFile() { /*Currently causes the program to only send the first 16 packets of file out requires additional code later to sendFile again with updated window*/ fd_set stReadFDS; struct timeval stTimeOut; FD_ZERO(&stReadFDS); stTimeOut.tv_sec = 0; stTimeOut.tv_usec = 1000 * TIMEOUT; FD_SET(s, &stReadFDS); base = 0; int desc_ready; int finale = -1; int max_sd; bool hasRead = false; while(base * BUFSIZE < length) { loadWindow(); if(p.str()[0] == '\0') finale = p.getSequenceNum(); for(int x = 0; x < WIN_SIZE; x++) { p = window[x]; if(!sendPacket()) continue; } for(int x = 0; x < WIN_SIZE; x++) { cout << endl << "beginning of loop " << x << endl; FD_ZERO(&stReadFDS); stTimeOut.tv_sec = 0; stTimeOut.tv_usec = 1000 * TIMEOUT; FD_SET(s, &stReadFDS); max_sd = s; cout << endl << "before select" << endl; int t = select(max_sd + 1, &stReadFDS, NULL, NULL, &stTimeOut); if (t == -1){ perror("select()"); } if (t == 0) { cout << "=== ACK TIMEOUT (select)" << endl; } desc_ready = t; for(int u = 0; u <= max_sd && desc_ready > 0; u++){ if(recvfrom(s, b, BUFSIZE + 7, 0, (struct sockaddr *)&ca, &calen) < 0) { cout << "=== ACK TIMEOUT (recvfrom)" << endl; } else hasRead = true; if(!hasRead) continue; if(isAck()) { handleAck(); } else { handleAck(); //handleNak(x); } } cout << "end of loop " << x << endl; if(finale > 0 && base == finale) {cout << "Finale: " << finale << endl; break;} memset(b, 0, BUFSIZE); } } if(sendto(s, "\0", BUFSIZE, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) { cout << "Final package sending failed. (socket s, server address sa, message m)" << endl; return false; } return true; } Packet createPacket(int index){ string mstr = fstr.substr(index * BUFSIZE, BUFSIZE); if(mstr.length() < BUFSIZE) { cout << "Null terminated mstr." << endl; mstr[length - (index * BUFSIZE)] = '\0'; } cout << "index: " << index << endl; return Packet (index, mstr.c_str()); } bool sendPacket(){ cout << endl; cout << "=== TRANSMISSION START" << endl; cout << "Sequence number before gremlin function: " << p.getSequenceNum() << endl; int pc = probCorrupt; int pl = probLoss; int pd = probDelay; bool* pckStatus = gremlin(&p, pc, pl, pd); dropPck = pckStatus[0]; delayPck = pckStatus[1]; if (dropPck == true) return false; if (delayPck == true) p.setAckNack(1); if(sendto(s, p.str(), BUFSIZE + 8, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) { cout << "Package sending failed. (socket s, server address sa, message m)" << endl; return false; } return true; } bool isAck() { cout << endl << "=== SERVER RESPONSE TEST" << endl; cout << "Data: " << b << endl; if(b[6] == '0') return true; else return false; } void handleAck() { int ack = boost::lexical_cast<int>(b); if(base < ack) base = ack; cout << "Window base: " << base << endl; } void handleNak(int& x) { char * sns = new char[2]; memcpy(sns, &b[0], 1); sns[1] = '\0'; char * css = new char[5]; memcpy(css, &b[1], 5); char * db = new char[BUFSIZE + 1]; memcpy(db, &b[2], BUFSIZE); db[BUFSIZE] = '\0'; cout << "Sequence number: " << sns << endl; cout << "Checksum: " << css << endl; Packet pk (0, db); pk.setSequenceNum(boost::lexical_cast<int>(sns)); pk.setCheckSum(boost::lexical_cast<int>(css)); if(!pk.chksm()) x--; else x = (x - 2 > 0) ? x - 2 : 0; } bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb){ bool* packStatus = new bool[2]; int r = rand() % 100; cout << "Corruption probability: " << corruptProb << endl; cout << "Random number: " << r << endl; packStatus[0] = false; packStatus[1] = false; if(r <= (lossProb)){ packStatus[0] = true; cout << "Dropped!" << endl; } else if(r <= (delayProb)){ packStatus[1] = true; cout << "Delayed!" << endl; } else if(r <= (corruptProb)){ cout << "Corrupted!" << endl; cout << "Seq. num (pre-gremlin): " << pack->getSequenceNum() << endl; pack->loadDataBuffer((char*)"GREMLIN LOL"); } cout << "Seq. num: " << pack->getSequenceNum() << endl; cout << "Checksum: " << pack->getCheckSum() << endl; //cout << "Message: " << pack->getDataBuffer() << endl; return packStatus; }<commit_msg>added test line<commit_after>#include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <sys/time.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <iostream> #include <fstream> #include <boost/lexical_cast.hpp> #include "packet.h" #define USAGE "Usage:\r\nc \r\n[tux machine number] \r\n[probability of packet corruption in int form] \r\n[probability of packet loss in int form] \r\n[probability of packet delay] \r\n[length of delay in ms] \r\n" #define PORT 10038 #define PAKSIZE 512 #define ACK 0 #define NAK 1 #define BUFSIZE 505 #define FILENAME "Testfile" #define TIMEOUT 15 //in ms #define WIN_SIZE 16 using namespace std; bool isvpack(unsigned char * p); bool init(int argc, char** argv); bool loadFile(); bool getFile(); bool sendFile(); bool isAck(); void handleAck(); void handleNak(int& x); bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb); Packet createPacket(int index); void loadWindow(); bool sendPacket(); bool getGet(); struct sockaddr_in a; struct sockaddr_in ca; socklen_t calen; int rlen; int s; bool ack; string fstr; char * file; int probCorrupt; int probLoss; int probDelay; int delayT; Packet p; Packet window[16]; int length; bool dropPck; bool delayPck; int toms; unsigned char b[BUFSIZE]; int base; int main(int argc, char** argv) { if(!init(argc, argv)) return -1; if(sendFile()) cout << "GET Testfile complete." << endl; return 0; } bool init(int argc, char** argv){ if(argc != 6) { cout << USAGE << endl; return false; } char * probCorruptStr = argv[2]; probCorrupt = boost::lexical_cast<int>(probCorruptStr); char * probLossStr = argv[3]; probLoss = boost::lexical_cast<int>(probLossStr); char * probDelayStr = argv[4]; probDelay = boost::lexical_cast<int>(probDelayStr); char* delayTStr = argv[5]; delayT = boost::lexical_cast<int>(delayTStr); struct timeval timeout; timeout.tv_usec = TIMEOUT * 1000; toms = TIMEOUT; /* Create our socket. */ if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { cout << "Socket creation failed. (socket s)" << endl; return 0; } setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout)); /* * Bind our socket to an IP (whatever the computer decides) * and a specified port. * */ if (!loadFile()) { cout << "Loading file failed. (filename FILENAME)" << endl; return false; } memset((char *)&a, 0, sizeof(a)); a.sin_family = AF_INET; a.sin_addr.s_addr = htonl(INADDR_ANY); a.sin_port = htons(PORT); if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0) { cout << "Socket binding failed. (socket s, address a)" << endl; return 0; } fstr = string(file); cout << "File: " << endl << fstr << endl; base = 0; dropPck = false; calen = sizeof(ca); getGet(); return true; } bool getGet(){ unsigned char packet[PAKSIZE + 1]; rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen); return (rlen > 0) ? true : false; } bool isvpack(unsigned char * p) { cout << endl << "=== IS VALID PACKET TESTING" << endl; char * sns = new char[2]; memcpy(sns, &p[0], 1); sns[1] = '\0'; char * css = new char[7]; memcpy(css, &p[1], 6); css[6] = '\0'; char * db = new char[121 + 1]; memcpy(db, &p[2], 121); db[121] = '\0'; cout << "Seq. num: " << sns << endl; cout << "Checksum: " << css << endl; cout << "Message: " << db << endl; int sn = boost::lexical_cast<int>(sns); int cs = boost::lexical_cast<int>(css); Packet pk (0, db); pk.setSequenceNum(sn); // change to validate based on checksum and sequence number if(sn == 0) return false; //doesn't matter, only for the old version (netwark) if(cs != pk.generateCheckSum()) return false; return true; } bool getFile(){ /* Loop forever, waiting for messages from a client. */ cout << "Waiting on port " << PORT << "..." << endl; ofstream file("Dumpfile"); for (;;) { unsigned char packet[PAKSIZE + 1]; unsigned char dataPull[PAKSIZE - 7 + 1]; rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen); for(int x = 0; x < PAKSIZE - 7; x++) { dataPull[x] = packet[x + 7]; } dataPull[PAKSIZE - 7] = '\0'; packet[PAKSIZE] = '\0'; if (rlen > 0) { char * css = new char[6]; memcpy(css, &packet[1], 5); css[5] = '\0'; cout << endl << endl << "=== RECEIPT" << endl; cout << "Seq. num: " << packet[0] << endl; cout << "Checksum: " << css << endl; cout << "Received message: " << dataPull << endl; cout << "Sent response: "; if(isvpack(packet)) { ack = ACK; //seqNum = (seqNum) ? false : true; file << dataPull; } else { ack = NAK; } cout << ((ack == ACK) ? "ACK" : "NAK") << endl; Packet p (false, reinterpret_cast<const char *>(dataPull)); p.setCheckSum(boost::lexical_cast<int>(css)); p.setAckNack(ack); if(sendto(s, p.str(), PAKSIZE, 0, (struct sockaddr *)&ca, calen) < 0) { cout << "Acknowledgement failed. (socket s, acknowledgement message ack, client address ca, client address length calen)" << endl; return 0; } delete css; } } file.close(); return true; } bool loadFile() { ifstream is (FILENAME, ifstream::binary); if(is) { is.seekg(0, is.end); length = is.tellg(); is.seekg(0, is.beg); file = new char[length]; cout << "Reading " << length << " characters..." << endl; is.read(file, length); if(!is) { cout << "File reading failed. (filename " << FILENAME << "). Only " << is.gcount() << " could be read."; return false; } is.close(); } return true; } void loadWindow(){ for(int i = base; i < base + WIN_SIZE; i++) { window[i-base] = createPacket(i); if(strlen(window[i-base].getDataBuffer()) < BUFSIZE && window[i-base].chksm()) { cout << "In loadWindow's secret base, index is: " << i-base << endl; for(++i; i < base + WIN_SIZE; i++){ window[i-base].loadDataBuffer("\0"); } } /*cout << "window[i-base] seq. num: " << window[i-base].getSequenceNum() << endl;*/ } /*cout << "packet " << base + 1 << ": " << window[1].str() << endl; cout << "packet " << base + 2 << ": " << window[2].str() << endl;*/ } bool sendFile() { /*Currently causes the program to only send the first 16 packets of file out requires additional code later to sendFile again with updated window*/ fd_set stReadFDS; struct timeval stTimeOut; FD_ZERO(&stReadFDS); stTimeOut.tv_sec = 0; stTimeOut.tv_usec = 1000 * TIMEOUT; FD_SET(s, &stReadFDS); base = 0; int desc_ready; int finale = -1; int max_sd; bool hasRead = false; while(base * BUFSIZE < length) { loadWindow(); if(p.str()[0] == '\0') finale = p.getSequenceNum(); for(int x = 0; x < WIN_SIZE; x++) { p = window[x]; if(!sendPacket()) continue; } for(int x = 0; x < WIN_SIZE; x++) { cout << endl << "beginning of loop " << x << endl; FD_ZERO(&stReadFDS); stTimeOut.tv_sec = 0; stTimeOut.tv_usec = 1000 * TIMEOUT; FD_SET(s, &stReadFDS); max_sd = s; cout << endl << "before select" << endl; int t = select(max_sd + 1, &stReadFDS, NULL, NULL, &stTimeOut); cout << "after select" << endl; if (t == -1){ perror("select()"); } if (t == 0) { cout << "=== ACK TIMEOUT (select)" << endl; } desc_ready = t; for(int u = 0; u <= max_sd && desc_ready > 0; u++){ if(recvfrom(s, b, BUFSIZE + 7, 0, (struct sockaddr *)&ca, &calen) < 0) { cout << "=== ACK TIMEOUT (recvfrom)" << endl; } else hasRead = true; if(!hasRead) continue; if(isAck()) { handleAck(); } else { handleAck(); //handleNak(x); } } cout << "end of loop " << x << endl; if(finale > 0 && base == finale) {cout << "Finale: " << finale << endl; break;} memset(b, 0, BUFSIZE); } } if(sendto(s, "\0", BUFSIZE, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) { cout << "Final package sending failed. (socket s, server address sa, message m)" << endl; return false; } return true; } Packet createPacket(int index){ string mstr = fstr.substr(index * BUFSIZE, BUFSIZE); if(mstr.length() < BUFSIZE) { cout << "Null terminated mstr." << endl; mstr[length - (index * BUFSIZE)] = '\0'; } cout << "index: " << index << endl; return Packet (index, mstr.c_str()); } bool sendPacket(){ cout << endl; cout << "=== TRANSMISSION START" << endl; cout << "Sequence number before gremlin function: " << p.getSequenceNum() << endl; int pc = probCorrupt; int pl = probLoss; int pd = probDelay; bool* pckStatus = gremlin(&p, pc, pl, pd); dropPck = pckStatus[0]; delayPck = pckStatus[1]; if (dropPck == true) return false; if (delayPck == true) p.setAckNack(1); if(sendto(s, p.str(), BUFSIZE + 8, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) { cout << "Package sending failed. (socket s, server address sa, message m)" << endl; return false; } return true; } bool isAck() { cout << endl << "=== SERVER RESPONSE TEST" << endl; cout << "Data: " << b << endl; if(b[6] == '0') return true; else return false; } void handleAck() { int ack = boost::lexical_cast<int>(b); if(base < ack) base = ack; cout << "Window base: " << base << endl; } void handleNak(int& x) { char * sns = new char[2]; memcpy(sns, &b[0], 1); sns[1] = '\0'; char * css = new char[5]; memcpy(css, &b[1], 5); char * db = new char[BUFSIZE + 1]; memcpy(db, &b[2], BUFSIZE); db[BUFSIZE] = '\0'; cout << "Sequence number: " << sns << endl; cout << "Checksum: " << css << endl; Packet pk (0, db); pk.setSequenceNum(boost::lexical_cast<int>(sns)); pk.setCheckSum(boost::lexical_cast<int>(css)); if(!pk.chksm()) x--; else x = (x - 2 > 0) ? x - 2 : 0; } bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb){ bool* packStatus = new bool[2]; int r = rand() % 100; cout << "Corruption probability: " << corruptProb << endl; cout << "Random number: " << r << endl; packStatus[0] = false; packStatus[1] = false; if(r <= (lossProb)){ packStatus[0] = true; cout << "Dropped!" << endl; } else if(r <= (delayProb)){ packStatus[1] = true; cout << "Delayed!" << endl; } else if(r <= (corruptProb)){ cout << "Corrupted!" << endl; cout << "Seq. num (pre-gremlin): " << pack->getSequenceNum() << endl; pack->loadDataBuffer((char*)"GREMLIN LOL"); } cout << "Seq. num: " << pack->getSequenceNum() << endl; cout << "Checksum: " << pack->getCheckSum() << endl; //cout << "Message: " << pack->getDataBuffer() << endl; return packStatus; }<|endoftext|>
<commit_before>#include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #include <iostream> #include <fstream> #include <boost/lexical_cast.hpp> #include "packet.h" #define USAGE "Usage:\r\nc \r\n[tux machine number] \r\n[probability of packet corruption in int form] \r\n[probability of packet loss in int form] \r\n[probability of packet delay] \r\n[length of delay in ms] \r\n" #define PORT 10038 #define PAKSIZE 128 #define ACK 0 #define NAK 1 #define BUFSIZE 121 #define FILENAME "Testfile" #define TIMEOUT 100 //in ms using namespace std; bool isvpack(unsigned char * p); bool init(int argc, char** argv); bool loadFile(); bool getFile(); bool sendFile(); bool isAck(); void handleAck(); void handleNak(int& x); bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb); Packet createPacket(int index); bool sendPacket(); bool seqNum = true; struct sockaddr_in a; struct sockaddr_in ca; socklen_t calen; int rlen; int s; bool ack; string fstr; char * file; int probCorrupt; int probLoss; int probDelay; int delayT; Packet p; int length; bool dropPck; bool delayPck; unsigned char b[BUFSIZE]; int main(int argc, char** argv) { if(!init(argc, argv)) return -1; calen = sizeof(ca); unsigned char packet[PAKSIZE + 1]; rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen); sendFile(); return 0; } bool init(int argc, char** argv){ if(argc != 6) { cout << USAGE << endl; return false; } char * probCorruptStr = argv[2]; probCorrupt = boost::lexical_cast<int>(probCorruptStr); char * probLossStr = argv[3]; probLoss = boost::lexical_cast<int>(probLossStr); char * probDelayStr = argv[4]; probDelay = boost::lexical_cast<int>(probDelayStr); char* delayTStr = argv[5]; delayT = boost::lexical_cast<int>(delayTStr); static int timeout = TIMEOUT; /* Create our socket. */ if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { cout << "Socket creation failed. (socket s)" << endl; return 0; } setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout)); /* * Bind our socket to an IP (whatever the computer decides) * and a specified port. * */ if (!loadFile()) { cout << "Loading file failed. (filename FILENAME)" << endl; return false; } memset((char *)&a, 0, sizeof(a)); a.sin_family = AF_INET; a.sin_addr.s_addr = htonl(INADDR_ANY); a.sin_port = htons(PORT); if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0) { cout << "Socket binding failed. (socket s, address a)" << endl; return 0; } fstr = string(file); cout << "File: " << endl << fstr << endl; seqNum = true; dropPck = false; return true; } bool isvpack(unsigned char * p) { cout << endl << "=== IS VALID PACKET TESTING" << endl; char * sns = new char[2]; memcpy(sns, &p[0], 1); sns[1] = '\0'; char * css = new char[7]; memcpy(css, &p[1], 6); css[6] = '\0'; char * db = new char[121 + 1]; memcpy(db, &p[2], 121); db[121] = '\0'; cout << "Seq. num: " << sns << endl; cout << "Checksum: " << css << endl; cout << "Message: " << db << endl; int sn = boost::lexical_cast<int>(sns); int cs = boost::lexical_cast<int>(css); Packet pk (0, db); pk.setSequenceNum(sn); // change to validate based on checksum and sequence number if(sn == seqNum) return false; if(cs != pk.generateCheckSum()) return false; return true; } bool getFile(){ /* Loop forever, waiting for messages from a client. */ cout << "Waiting on port " << PORT << "..." << endl; ofstream file("Dumpfile"); bool isSeqNumSet = false; for (;;) { unsigned char packet[PAKSIZE + 1]; unsigned char dataPull[PAKSIZE - 7 + 1]; rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen); if(!isSeqNumSet) { isSeqNumSet = true; char * str = new char[1]; memcpy(str, &packet[0], 1); seqNum = boost::lexical_cast<int>(str); } for(int x = 0; x < PAKSIZE - 7; x++) { dataPull[x] = packet[x + 7]; } dataPull[PAKSIZE - 7] = '\0'; packet[PAKSIZE] = '\0'; if (rlen > 0) { char * css = new char[6]; memcpy(css, &packet[1], 5); css[5] = '\0'; cout << endl << endl << "=== RECEIPT" << endl; cout << "Seq. num: " << packet[0] << endl; cout << "Checksum: " << css << endl; cout << "Received message: " << dataPull << endl; cout << "Sent response: "; if(isvpack(packet)) { ack = ACK; seqNum = (seqNum) ? false : true; file << dataPull; } else { ack = NAK; } cout << ((ack == ACK) ? "ACK" : "NAK") << endl; Packet p ((seqNum) ? false : true, reinterpret_cast<const char *>(dataPull)); p.setCheckSum(boost::lexical_cast<int>(css)); p.setAckNack(ack); if(sendto(s, p.str(), PAKSIZE, 0, (struct sockaddr *)&ca, calen) < 0) { cout << "Acknowledgement failed. (socket s, acknowledgement message ack, client address ca, client address length calen)" << endl; return 0; } delete css; } } file.close(); return true; } bool loadFile() { ifstream is (FILENAME, ifstream::binary); if(is) { is.seekg(0, is.end); length = is.tellg(); is.seekg(0, is.beg); file = new char[length]; cout << "Reading " << length << " characters..." << endl; is.read(file, length); if(!is) { cout << "File reading failed. (filename " << FILENAME << "). Only " << is.gcount() << " could be read."; return false; } is.close(); } return true; } bool sendFile() { for(int x = 0; x <= (length / BUFSIZE) + 1; x++) { p = createPacket(x); if(!sendPacket()) continue; while(recvfrom(s, b, BUFSIZE + 7, 0, (struct sockaddr *)&ca, &calen) < 0) { cout << "Timed out. Resending..." << endl; sendPacket(); } if(isAck()) { handleAck(); } else { handleNak(x); } memset(b, 0, BUFSIZE); } return true; } Packet createPacket(int index){ cout << endl; cout << "=== TRANSMISSION START" << endl; string mstr = fstr.substr(index * BUFSIZE, BUFSIZE); if(mstr.length() < BUFSIZE) { mstr[length - (index * BUFSIZE)] = '\0'; } return Packet (seqNum, mstr.c_str()); } bool sendPacket(){ int pc = probCorrupt; int pl = probLoss; int pd = probDelay; bool* pckStatus = gremlin(&p, pc, pl, pd); dropPck = pckStatus[0]; delayPck = pckStatus[1]; cout << "dropPck: " << dropPck << endl; cout << "delayPck: " << delayPck << endl; if (dropPck == 1) return false; if (delayPck == 1) sleep(delayT); if(sendto(s, p.str(), BUFSIZE + 7, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) { cout << "Package sending failed. (socket s, server address sa, message m)" << endl; return false; } return true; } bool isAck() { cout << endl << "=== SERVER RESPONSE TEST" << endl; cout << "Data: " << b << endl; if(b[6] == '0') return true; else return false; } void handleAck() { } void handleNak(int& x) { char * sns = new char[2]; memcpy(sns, &b[0], 1); sns[1] = '\0'; char * css = new char[5]; memcpy(css, &b[1], 5); char * db = new char[BUFSIZE + 1]; memcpy(db, &b[2], BUFSIZE); db[BUFSIZE] = '\0'; cout << "Sequence number: " << sns << endl; cout << "Checksum: " << css << endl; Packet pk (0, db); pk.setSequenceNum(boost::lexical_cast<int>(sns)); pk.setCheckSum(boost::lexical_cast<int>(css)); if(!pk.chksm()) x--; else x = (x - 2 > 0) ? x - 2 : 0; } bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb){ bool dropPacket = false; bool delayPacket = false; bool* packStatus = new bool[2]; int r = rand() % 100; cout << "Corruption probability: " << corruptProb << endl; cout << "Random number: " << r << endl; if(r <= (lossProb)){ dropPacket = true; packStatus[0] = dropPacket; cout << "Dropped!" << endl; } else if(r <= (delayProb)){ delayPacket = true; packStatus[1] = delayPacket; cout << "Delayed!" << endl; } else if(r <= (corruptProb)){ cout << "Corrupted!" << endl; pack->loadDataBuffer((char*)"GREMLIN LOL"); } else seqNum = (seqNum) ? false : true; cout << "Seq. num: " << pack->getSequenceNum() << endl; cout << "Checksum: " << pack->getCheckSum() << endl; cout << "Message: " << pack->getDataBuffer() << endl; return packStatus; }<commit_msg>Testing for the fix's fix's fix (again)<commit_after>#include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #include <iostream> #include <fstream> #include <boost/lexical_cast.hpp> #include "packet.h" #define USAGE "Usage:\r\nc \r\n[tux machine number] \r\n[probability of packet corruption in int form] \r\n[probability of packet loss in int form] \r\n[probability of packet delay] \r\n[length of delay in ms] \r\n" #define PORT 10038 #define PAKSIZE 128 #define ACK 0 #define NAK 1 #define BUFSIZE 121 #define FILENAME "Testfile" #define TIMEOUT 100 //in ms using namespace std; bool isvpack(unsigned char * p); bool init(int argc, char** argv); bool loadFile(); bool getFile(); bool sendFile(); bool isAck(); void handleAck(); void handleNak(int& x); bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb); Packet createPacket(int index); bool sendPacket(); bool seqNum = true; struct sockaddr_in a; struct sockaddr_in ca; socklen_t calen; int rlen; int s; bool ack; string fstr; char * file; int probCorrupt; int probLoss; int probDelay; int delayT; Packet p; int length; bool dropPck; bool delayPck; unsigned char b[BUFSIZE]; int main(int argc, char** argv) { if(!init(argc, argv)) return -1; calen = sizeof(ca); unsigned char packet[PAKSIZE + 1]; rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen); sendFile(); return 0; } bool init(int argc, char** argv){ if(argc != 6) { cout << USAGE << endl; return false; } char * probCorruptStr = argv[2]; probCorrupt = boost::lexical_cast<int>(probCorruptStr); char * probLossStr = argv[3]; probLoss = boost::lexical_cast<int>(probLossStr); char * probDelayStr = argv[4]; probDelay = boost::lexical_cast<int>(probDelayStr); char* delayTStr = argv[5]; delayT = boost::lexical_cast<int>(delayTStr); static int timeout = TIMEOUT; /* Create our socket. */ if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { cout << "Socket creation failed. (socket s)" << endl; return 0; } setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout)); /* * Bind our socket to an IP (whatever the computer decides) * and a specified port. * */ if (!loadFile()) { cout << "Loading file failed. (filename FILENAME)" << endl; return false; } memset((char *)&a, 0, sizeof(a)); a.sin_family = AF_INET; a.sin_addr.s_addr = htonl(INADDR_ANY); a.sin_port = htons(PORT); if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0) { cout << "Socket binding failed. (socket s, address a)" << endl; return 0; } fstr = string(file); cout << "File: " << endl << fstr << endl; seqNum = true; dropPck = false; return true; } bool isvpack(unsigned char * p) { cout << endl << "=== IS VALID PACKET TESTING" << endl; char * sns = new char[2]; memcpy(sns, &p[0], 1); sns[1] = '\0'; char * css = new char[7]; memcpy(css, &p[1], 6); css[6] = '\0'; char * db = new char[121 + 1]; memcpy(db, &p[2], 121); db[121] = '\0'; cout << "Seq. num: " << sns << endl; cout << "Checksum: " << css << endl; cout << "Message: " << db << endl; int sn = boost::lexical_cast<int>(sns); int cs = boost::lexical_cast<int>(css); Packet pk (0, db); pk.setSequenceNum(sn); // change to validate based on checksum and sequence number if(sn == seqNum) return false; if(cs != pk.generateCheckSum()) return false; return true; } bool getFile(){ /* Loop forever, waiting for messages from a client. */ cout << "Waiting on port " << PORT << "..." << endl; ofstream file("Dumpfile"); bool isSeqNumSet = false; for (;;) { unsigned char packet[PAKSIZE + 1]; unsigned char dataPull[PAKSIZE - 7 + 1]; rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&ca, &calen); if(!isSeqNumSet) { isSeqNumSet = true; char * str = new char[1]; memcpy(str, &packet[0], 1); seqNum = boost::lexical_cast<int>(str); } for(int x = 0; x < PAKSIZE - 7; x++) { dataPull[x] = packet[x + 7]; } dataPull[PAKSIZE - 7] = '\0'; packet[PAKSIZE] = '\0'; if (rlen > 0) { char * css = new char[6]; memcpy(css, &packet[1], 5); css[5] = '\0'; cout << endl << endl << "=== RECEIPT" << endl; cout << "Seq. num: " << packet[0] << endl; cout << "Checksum: " << css << endl; cout << "Received message: " << dataPull << endl; cout << "Sent response: "; if(isvpack(packet)) { ack = ACK; seqNum = (seqNum) ? false : true; file << dataPull; } else { ack = NAK; } cout << ((ack == ACK) ? "ACK" : "NAK") << endl; Packet p ((seqNum) ? false : true, reinterpret_cast<const char *>(dataPull)); p.setCheckSum(boost::lexical_cast<int>(css)); p.setAckNack(ack); if(sendto(s, p.str(), PAKSIZE, 0, (struct sockaddr *)&ca, calen) < 0) { cout << "Acknowledgement failed. (socket s, acknowledgement message ack, client address ca, client address length calen)" << endl; return 0; } delete css; } } file.close(); return true; } bool loadFile() { ifstream is (FILENAME, ifstream::binary); if(is) { is.seekg(0, is.end); length = is.tellg(); is.seekg(0, is.beg); file = new char[length]; cout << "Reading " << length << " characters..." << endl; is.read(file, length); if(!is) { cout << "File reading failed. (filename " << FILENAME << "). Only " << is.gcount() << " could be read."; return false; } is.close(); } return true; } bool sendFile() { for(int x = 0; x <= (length / BUFSIZE) + 1; x++) { p = createPacket(x); if(!sendPacket()) continue; while(recvfrom(s, b, BUFSIZE + 7, 0, (struct sockaddr *)&ca, &calen) < 0) { cout << "Timed out. Resending..." << endl; sendPacket(); } if(isAck()) { handleAck(); } else { handleNak(x); } memset(b, 0, BUFSIZE); } return true; } Packet createPacket(int index){ cout << endl; cout << "=== TRANSMISSION START" << endl; string mstr = fstr.substr(index * BUFSIZE, BUFSIZE); if(mstr.length() < BUFSIZE) { mstr[length - (index * BUFSIZE)] = '\0'; } return Packet (seqNum, mstr.c_str()); } bool sendPacket(){ int pc = probCorrupt; int pl = probLoss; int pd = probDelay; bool* pckStatus = gremlin(&p, pc, pl, pd); dropPck = pckStatus[0]; delayPck = pckStatus[1]; cout << "dropPck: " << dropPck << endl; cout << "delayPck: " << delayPck << endl; if (dropPck == 1) return false; if (delayPck == 1) sleep(delayT); cout << "Made it to sending mode..." << endl; if(sendto(s, p.str(), BUFSIZE + 7, 0, (struct sockaddr *)&ca, sizeof(ca)) < 0) { cout << "Package sending failed. (socket s, server address sa, message m)" << endl; return false; } return true; } bool isAck() { cout << endl << "=== SERVER RESPONSE TEST" << endl; cout << "Data: " << b << endl; if(b[6] == '0') return true; else return false; } void handleAck() { } void handleNak(int& x) { char * sns = new char[2]; memcpy(sns, &b[0], 1); sns[1] = '\0'; char * css = new char[5]; memcpy(css, &b[1], 5); char * db = new char[BUFSIZE + 1]; memcpy(db, &b[2], BUFSIZE); db[BUFSIZE] = '\0'; cout << "Sequence number: " << sns << endl; cout << "Checksum: " << css << endl; Packet pk (0, db); pk.setSequenceNum(boost::lexical_cast<int>(sns)); pk.setCheckSum(boost::lexical_cast<int>(css)); if(!pk.chksm()) x--; else x = (x - 2 > 0) ? x - 2 : 0; } bool* gremlin(Packet * pack, int corruptProb, int lossProb, int delayProb){ bool dropPacket = false; bool delayPacket = false; bool* packStatus = new bool[2]; int r = rand() % 100; cout << "Corruption probability: " << corruptProb << endl; cout << "Random number: " << r << endl; if(r <= (lossProb)){ dropPacket = true; packStatus[0] = dropPacket; cout << "Dropped!" << endl; } else if(r <= (delayProb)){ delayPacket = true; packStatus[1] = delayPacket; cout << "Delayed!" << endl; } else if(r <= (corruptProb)){ cout << "Corrupted!" << endl; pack->loadDataBuffer((char*)"GREMLIN LOL"); } else seqNum = (seqNum) ? false : true; cout << "Seq. num: " << pack->getSequenceNum() << endl; cout << "Checksum: " << pack->getCheckSum() << endl; cout << "Message: " << pack->getDataBuffer() << endl; return packStatus; }<|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Extension port manager takes care of managing the state of // connecting and connected ports. #include "ceee/ie/plugin/bho/extension_port_manager.h" #include "base/logging.h" #include "base/scoped_ptr.h" #include "base/values.h" #include "base/json/json_reader.h" #include "base/json/json_writer.h" #include "ceee/ie/common/chrome_frame_host.h" #include "ceee/ie/plugin/scripting/content_script_native_api.h" #include "chrome/browser/automation/extension_automation_constants.h" namespace ext = extension_automation_constants; ExtensionPortManager::ExtensionPortManager() { } ExtensionPortManager::~ExtensionPortManager() { } void ExtensionPortManager::Initialize(IChromeFrameHost* chrome_frame_host) { chrome_frame_host_ = chrome_frame_host; } void ExtensionPortManager::CloseAll(IContentScriptNativeApi* instance) { DCHECK(instance != NULL); // TODO([email protected]): Deal better with these cases. Connected // ports probably ought to be closed, and connecting ports may // need to hang around until we get the connected message, to be // terminated at that point. ConnectedPortMap::iterator it(connected_ports_.begin()); while (it != connected_ports_.end()) { if (it->second.instance = instance) { connected_ports_.erase(it++); } else { ++it; } } ConnectingPortMap::iterator jt(connecting_ports_.begin()); while (jt != connecting_ports_.end()) { if (jt->second.instance = instance) { connecting_ports_.erase(jt++); } else { ++jt; } } } HRESULT ExtensionPortManager::OpenChannelToExtension( IContentScriptNativeApi* instance, const std::string& extension, const std::string& channel_name, Value* tab, int cookie) { int connection_id = next_connection_id_++; // Prepare the connection request. scoped_ptr<DictionaryValue> dict(new DictionaryValue()); if (dict.get() == NULL) return E_OUTOFMEMORY; dict->SetInteger(ext::kAutomationRequestIdKey, ext::OPEN_CHANNEL); dict->SetInteger(ext::kAutomationConnectionIdKey, connection_id); dict->SetString(ext::kAutomationExtensionIdKey, extension); dict->SetString(ext::kAutomationChannelNameKey, channel_name); dict->Set(ext::kAutomationTabJsonKey, tab); // JSON encode it. std::string request_json; base::JSONWriter::Write(dict.get(), false, &request_json); // And fire it off. HRESULT hr = PostMessageToHost(request_json, ext::kAutomationPortRequestTarget); if (FAILED(hr)) return hr; ConnectingPort connecting_port = { instance, cookie }; connecting_ports_[connection_id] = connecting_port; return S_OK; } HRESULT ExtensionPortManager::PostMessage(int port_id, const std::string& message) { // Wrap the message for sending as a port request. scoped_ptr<DictionaryValue> dict(new DictionaryValue()); if (dict.get() == NULL) return E_OUTOFMEMORY; dict->SetInteger(ext::kAutomationRequestIdKey, ext::POST_MESSAGE); dict->SetInteger(ext::kAutomationPortIdKey, port_id); dict->SetString(ext::kAutomationMessageDataKey, message); // JSON encode it. std::string message_json; base::JSONWriter::Write(dict.get(), false, &message_json); // And fire it off. return PostMessageToHost(message_json, std::string(ext::kAutomationPortRequestTarget)); } void ExtensionPortManager::OnPortMessage(BSTR message) { std::string message_json = CW2A(message); scoped_ptr<Value> value(base::JSONReader::Read(message_json, true)); if (!value.get() || !value->IsType(Value::TYPE_DICTIONARY)) { NOTREACHED(); LOG(ERROR) << "Invalid message"; return; } DictionaryValue* dict = static_cast<DictionaryValue*>(value.get()); int request = -1; if (!dict->GetInteger(ext::kAutomationRequestIdKey, &request)) { NOTREACHED(); LOG(ERROR) << "Request ID missing"; return; } if (request == ext::CHANNEL_OPENED) { int connection_id = -1; if (!dict->GetInteger(ext::kAutomationConnectionIdKey, &connection_id)) { NOTREACHED(); LOG(ERROR) << "Connection ID missing"; return; } int port_id = -1; if (!dict->GetInteger(ext::kAutomationPortIdKey, &port_id)) { NOTREACHED(); LOG(ERROR) << "Port ID missing"; return; } ConnectingPortMap::iterator it(connecting_ports_.find(connection_id)); if (it == connecting_ports_.end()) { // TODO([email protected]): This can happen legitimately on a // race between connect and document unload. We should // probably respond with a close port message here. LOG(ERROR) << "No such connection id " << connection_id; return; } ConnectingPort port = it->second; connecting_ports_.erase(it); // Did it connect successfully? if (port_id != -1) connected_ports_[port_id].instance = port.instance; port.instance->OnChannelOpened(port.cookie, port_id); return; } else if (request == ext::POST_MESSAGE) { int port_id = -1; if (!dict->GetInteger(ext::kAutomationPortIdKey, &port_id)) { NOTREACHED(); LOG(ERROR) << "No port id"; return; } std::string data; if (!dict->GetString(ext::kAutomationMessageDataKey, &data)) { NOTREACHED(); LOG(ERROR) << "No message data"; return; } ConnectedPortMap::iterator it(connected_ports_.find(port_id)); if (it == connected_ports_.end()) { LOG(ERROR) << "No such port " << port_id; return; } it->second.instance->OnPostMessage(port_id, data); return; } else if (request == ext::CHANNEL_CLOSED) { // TODO([email protected]): handle correctly. return; } NOTREACHED(); } HRESULT ExtensionPortManager::PostMessageToHost(const std::string& message, const std::string& target) { // Post our message through the ChromeFrameHost. We allow queueing, // because we don't synchronize to the destination extension loading. return chrome_frame_host_->PostMessage(CComBSTR(message.c_str()), CComBSTR(target.c_str())); } <commit_msg>Small fix to make sure we always start connection ID sequences to the same value.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Extension port manager takes care of managing the state of // connecting and connected ports. #include "ceee/ie/plugin/bho/extension_port_manager.h" #include "base/logging.h" #include "base/scoped_ptr.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "base/json/json_reader.h" #include "base/json/json_writer.h" #include "base/win/scoped_bstr.h" #include "ceee/ie/common/chrome_frame_host.h" #include "ceee/ie/plugin/scripting/content_script_native_api.h" #include "chrome/browser/automation/extension_automation_constants.h" namespace ext = extension_automation_constants; ExtensionPortManager::ExtensionPortManager() : next_connection_id_(0) { } ExtensionPortManager::~ExtensionPortManager() { } void ExtensionPortManager::Initialize(IChromeFrameHost* chrome_frame_host) { chrome_frame_host_ = chrome_frame_host; } void ExtensionPortManager::CloseAll(IContentScriptNativeApi* instance) { DCHECK(instance != NULL); // TODO([email protected]): Deal better with these cases. Connected // ports probably ought to be closed, and connecting ports may // need to hang around until we get the connected message, to be // terminated at that point. ConnectedPortMap::iterator it(connected_ports_.begin()); while (it != connected_ports_.end()) { if (it->second.instance = instance) { connected_ports_.erase(it++); } else { ++it; } } ConnectingPortMap::iterator jt(connecting_ports_.begin()); while (jt != connecting_ports_.end()) { if (jt->second.instance = instance) { connecting_ports_.erase(jt++); } else { ++jt; } } } HRESULT ExtensionPortManager::OpenChannelToExtension( IContentScriptNativeApi* instance, const std::string& extension, const std::string& channel_name, Value* tab, int cookie) { int connection_id = next_connection_id_++; // Prepare the connection request. scoped_ptr<DictionaryValue> dict(new DictionaryValue()); if (dict.get() == NULL) return E_OUTOFMEMORY; dict->SetInteger(ext::kAutomationRequestIdKey, ext::OPEN_CHANNEL); dict->SetInteger(ext::kAutomationConnectionIdKey, connection_id); dict->SetString(ext::kAutomationExtensionIdKey, extension); dict->SetString(ext::kAutomationChannelNameKey, channel_name); dict->Set(ext::kAutomationTabJsonKey, tab); // JSON encode it. std::string request_json; base::JSONWriter::Write(dict.get(), false, &request_json); // And fire it off. HRESULT hr = PostMessageToHost(request_json, ext::kAutomationPortRequestTarget); if (FAILED(hr)) return hr; ConnectingPort connecting_port = { instance, cookie }; connecting_ports_[connection_id] = connecting_port; return S_OK; } HRESULT ExtensionPortManager::PostMessage(int port_id, const std::string& message) { // Wrap the message for sending as a port request. scoped_ptr<DictionaryValue> dict(new DictionaryValue()); if (dict.get() == NULL) return E_OUTOFMEMORY; dict->SetInteger(ext::kAutomationRequestIdKey, ext::POST_MESSAGE); dict->SetInteger(ext::kAutomationPortIdKey, port_id); dict->SetString(ext::kAutomationMessageDataKey, message); // JSON encode it. std::string message_json; base::JSONWriter::Write(dict.get(), false, &message_json); // And fire it off. return PostMessageToHost(message_json, std::string(ext::kAutomationPortRequestTarget)); } void ExtensionPortManager::OnPortMessage(BSTR message) { std::string message_json = CW2A(message); scoped_ptr<Value> value(base::JSONReader::Read(message_json, true)); if (!value.get() || !value->IsType(Value::TYPE_DICTIONARY)) { NOTREACHED(); LOG(ERROR) << "Invalid message"; return; } DictionaryValue* dict = static_cast<DictionaryValue*>(value.get()); int request = -1; if (!dict->GetInteger(ext::kAutomationRequestIdKey, &request)) { NOTREACHED(); LOG(ERROR) << "Request ID missing"; return; } if (request == ext::CHANNEL_OPENED) { int connection_id = -1; if (!dict->GetInteger(ext::kAutomationConnectionIdKey, &connection_id)) { NOTREACHED(); LOG(ERROR) << "Connection ID missing"; return; } int port_id = -1; if (!dict->GetInteger(ext::kAutomationPortIdKey, &port_id)) { NOTREACHED(); LOG(ERROR) << "Port ID missing"; return; } ConnectingPortMap::iterator it(connecting_ports_.find(connection_id)); if (it == connecting_ports_.end()) { // TODO([email protected]): This can happen legitimately on a // race between connect and document unload. We should // probably respond with a close port message here. LOG(ERROR) << "No such connection id " << connection_id; return; } ConnectingPort port = it->second; connecting_ports_.erase(it); // Did it connect successfully? if (port_id != -1) connected_ports_[port_id].instance = port.instance; port.instance->OnChannelOpened(port.cookie, port_id); return; } else if (request == ext::POST_MESSAGE) { int port_id = -1; if (!dict->GetInteger(ext::kAutomationPortIdKey, &port_id)) { NOTREACHED(); LOG(ERROR) << "No port id"; return; } std::string data; if (!dict->GetString(ext::kAutomationMessageDataKey, &data)) { NOTREACHED(); LOG(ERROR) << "No message data"; return; } ConnectedPortMap::iterator it(connected_ports_.find(port_id)); if (it == connected_ports_.end()) { LOG(ERROR) << "No such port " << port_id; return; } it->second.instance->OnPostMessage(port_id, data); return; } else if (request == ext::CHANNEL_CLOSED) { // TODO([email protected]): handle correctly. return; } NOTREACHED(); } HRESULT ExtensionPortManager::PostMessageToHost(const std::string& message, const std::string& target) { // Post our message through the ChromeFrameHost. We allow queueing, // because we don't synchronize to the destination extension loading. return chrome_frame_host_->PostMessage( base::win::ScopedBstr(ASCIIToWide(message).c_str()), base::win::ScopedBstr(ASCIIToWide(target).c_str())); } <|endoftext|>
<commit_before>#include <silicium/tcp_acceptor.hpp> #include <silicium/coroutine.hpp> #include <silicium/total_consumer.hpp> #include <silicium/flatten.hpp> #include <silicium/socket_observable.hpp> #include <silicium/sending_observable.hpp> #include <silicium/received_from_socket_source.hpp> #include <silicium/observable_source.hpp> #include <silicium/optional.hpp> #include <silicium/http/http.hpp> #include <boost/interprocess/sync/null_mutex.hpp> #include <boost/container/string.hpp> #include <boost/unordered_map.hpp> namespace { using response_part = Si::incoming_bytes; boost::iterator_range<char const *> to_range(response_part part) { return boost::make_iterator_range(part.begin, part.end); } using byte = boost::uint8_t; using digest = boost::container::basic_string<byte>; struct content_request { digest requested_file; }; Si::optional<unsigned char> decode_ascii_hex_digit(char digit) { switch (digit) { case '0': return 0; case '1': return 1; case '2': return 2; case '3': return 3; case '4': return 4; case '5': return 5; case '6': return 6; case '7': return 7; case '8': return 8; case '9': return 9; case 'a': case 'A': return 10; case 'b': case 'B': return 11; case 'c': case 'C': return 12; case 'd': case 'D': return 13; case 'e': case 'E': return 14; case 'f': case 'F': return 15; default: return Si::none; } } template <class InputIterator, class OutputIterator> std::pair<InputIterator, OutputIterator> decode_ascii_hex_bytes(InputIterator begin, InputIterator end, OutputIterator bytes) { for (;;) { if (begin == end) { break; } char const first_char = *begin; Si::optional<unsigned char> const first = decode_ascii_hex_digit(first_char); if (!first) { break; } auto const next = begin + 1; if (next == end) { break; } char const second_char = *next; Si::optional<unsigned char> const second = decode_ascii_hex_digit(second_char); if (!second) { break; } begin = next + 1; unsigned char const digit = static_cast<unsigned char>((*first * 16) + *second); *bytes = digit; ++bytes; } return std::make_pair(begin, bytes); } Si::optional<content_request> parse_request_path(std::string const &path) { if (path.empty()) { return Si::none; } auto digest_begin = path.begin(); if (*digest_begin == '/') { ++digest_begin; } content_request request; auto const rest = decode_ascii_hex_bytes(digest_begin, path.end(), std::back_inserter(request.requested_file)); if (rest.first != path.end()) { return Si::none; } return std::move(request); } struct file_system_location { //unique_ptr for noexcept-movability std::unique_ptr<boost::filesystem::path> where; }; using location = Si::fast_variant<file_system_location>; struct file_repository { boost::unordered_map<digest, location> available; location const *find_location(digest const &key) const { auto i = available.find(key); return (i == end(available)) ? nullptr : &i->second; } }; template <class ReceiveObservable, class MakeSender, class Shutdown> void serve_client( Si::yield_context<Si::nothing> &yield, ReceiveObservable &receive, MakeSender const &make_sender, Shutdown const &shutdown, file_repository const &repository) { auto receive_sync = Si::make_observable_source(Si::ref(receive), yield); Si::received_from_socket_source receive_bytes(receive_sync); auto header = Si::http::parse_header(receive_bytes); if (!header) { return; } auto const request = parse_request_path(header->path); if (!request) { //TODO: 404 or sth return; } location const * const found_file = repository.find_location(request->requested_file); if (!found_file) { //TODO: 404 //return; } std::string const body = "Hello at " + header->path; auto const try_send = [&yield, &make_sender](std::string const &data) { auto sender = make_sender(Si::incoming_bytes(data.data(), data.data() + data.size())); auto error = yield.get_one(sender); assert(error); return !*error; }; { Si::http::response_header response; response.http_version = "HTTP/1.0"; response.status_text = "OK"; response.status = 200; response.arguments["Content-Length"] = boost::lexical_cast<std::string>(body.size()); response.arguments["Connection"] = "close"; std::string response_header; auto header_sink = Si::make_container_sink(response_header); Si::http::write_header(header_sink, response); if (!try_send(response_header)) { return; } } if (!try_send(body)) { return; } shutdown(); while (Si::get(receive_bytes)) { } } //TODO: use unique_observable using session_handle = Si::shared_observable<Si::nothing>; } int main() { boost::asio::io_service io; boost::asio::ip::tcp::acceptor acceptor(io, boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4(), 8080)); Si::tcp_acceptor clients(acceptor); file_repository files; auto accept_all = Si::make_coroutine<session_handle>([&clients, &files](Si::yield_context<session_handle> &yield) { for (;;) { auto accepted = yield.get_one(clients); if (!accepted) { return; } Si::visit<void>( *accepted, [&yield, &files](std::shared_ptr<boost::asio::ip::tcp::socket> socket) { auto prepare_socket = [socket, &files](Si::yield_context<Si::nothing> &yield) { std::array<char, 1024> receive_buffer; Si::socket_observable received(*socket, boost::make_iterator_range(receive_buffer.data(), receive_buffer.data() + receive_buffer.size())); auto make_sender = [socket](Si::incoming_bytes sent) { return Si::sending_observable(*socket, to_range(sent)); }; auto shutdown = [socket]() { socket->shutdown(boost::asio::ip::tcp::socket::shutdown_both); }; serve_client(yield, received, make_sender, shutdown, files); }; yield(Si::erase_shared(Si::make_coroutine<Si::nothing>(prepare_socket))); }, [](boost::system::error_code) { throw std::logic_error("to do"); } ); } }); auto all_sessions_finished = Si::flatten<boost::interprocess::null_mutex>(std::move(accept_all)); auto done = Si::make_total_consumer(std::move(all_sessions_finished)); done.start(); io.run(); } <commit_msg>list files recursively<commit_after>#include <silicium/tcp_acceptor.hpp> #include <silicium/coroutine.hpp> #include <silicium/total_consumer.hpp> #include <silicium/flatten.hpp> #include <silicium/socket_observable.hpp> #include <silicium/sending_observable.hpp> #include <silicium/received_from_socket_source.hpp> #include <silicium/observable_source.hpp> #include <silicium/for_each.hpp> #include <silicium/optional.hpp> #include <silicium/http/http.hpp> #include <silicium/thread.hpp> #include <boost/interprocess/sync/null_mutex.hpp> #include <boost/container/string.hpp> #include <boost/unordered_map.hpp> #include <boost/filesystem/operations.hpp> namespace { using response_part = Si::incoming_bytes; boost::iterator_range<char const *> to_range(response_part part) { return boost::make_iterator_range(part.begin, part.end); } using byte = boost::uint8_t; using digest = boost::container::basic_string<byte>; struct content_request { digest requested_file; }; Si::optional<unsigned char> decode_ascii_hex_digit(char digit) { switch (digit) { case '0': return 0; case '1': return 1; case '2': return 2; case '3': return 3; case '4': return 4; case '5': return 5; case '6': return 6; case '7': return 7; case '8': return 8; case '9': return 9; case 'a': case 'A': return 10; case 'b': case 'B': return 11; case 'c': case 'C': return 12; case 'd': case 'D': return 13; case 'e': case 'E': return 14; case 'f': case 'F': return 15; default: return Si::none; } } template <class InputIterator, class OutputIterator> std::pair<InputIterator, OutputIterator> decode_ascii_hex_bytes(InputIterator begin, InputIterator end, OutputIterator bytes) { for (;;) { if (begin == end) { break; } char const first_char = *begin; Si::optional<unsigned char> const first = decode_ascii_hex_digit(first_char); if (!first) { break; } auto const next = begin + 1; if (next == end) { break; } char const second_char = *next; Si::optional<unsigned char> const second = decode_ascii_hex_digit(second_char); if (!second) { break; } begin = next + 1; unsigned char const digit = static_cast<unsigned char>((*first * 16) + *second); *bytes = digit; ++bytes; } return std::make_pair(begin, bytes); } Si::optional<content_request> parse_request_path(std::string const &path) { if (path.empty()) { return Si::none; } auto digest_begin = path.begin(); if (*digest_begin == '/') { ++digest_begin; } content_request request; auto const rest = decode_ascii_hex_bytes(digest_begin, path.end(), std::back_inserter(request.requested_file)); if (rest.first != path.end()) { return Si::none; } return std::move(request); } struct file_system_location { //unique_ptr for noexcept-movability std::unique_ptr<boost::filesystem::path> where; }; using location = Si::fast_variant<file_system_location>; struct file_repository { boost::unordered_map<digest, location> available; location const *find_location(digest const &key) const { auto i = available.find(key); return (i == end(available)) ? nullptr : &i->second; } }; template <class ReceiveObservable, class MakeSender, class Shutdown> void serve_client( Si::yield_context<Si::nothing> &yield, ReceiveObservable &receive, MakeSender const &make_sender, Shutdown const &shutdown, file_repository const &repository) { auto receive_sync = Si::make_observable_source(Si::ref(receive), yield); Si::received_from_socket_source receive_bytes(receive_sync); auto header = Si::http::parse_header(receive_bytes); if (!header) { return; } auto const request = parse_request_path(header->path); if (!request) { //TODO: 404 or sth return; } location const * const found_file = repository.find_location(request->requested_file); if (!found_file) { //TODO: 404 //return; } std::string const body = "Hello at " + header->path; auto const try_send = [&yield, &make_sender](std::string const &data) { auto sender = make_sender(Si::incoming_bytes(data.data(), data.data() + data.size())); auto error = yield.get_one(sender); assert(error); return !*error; }; { Si::http::response_header response; response.http_version = "HTTP/1.0"; response.status_text = "OK"; response.status = 200; response.arguments["Content-Length"] = boost::lexical_cast<std::string>(body.size()); response.arguments["Connection"] = "close"; std::string response_header; auto header_sink = Si::make_container_sink(response_header); Si::http::write_header(header_sink, response); if (!try_send(response_header)) { return; } } if (!try_send(body)) { return; } shutdown(); while (Si::get(receive_bytes)) { } } //TODO: use unique_observable using session_handle = Si::shared_observable<Si::nothing>; namespace detail { void list_files_recursively(Si::yield_context_2<boost::filesystem::path> &yield, boost::filesystem::path const &root) { for (boost::filesystem::directory_iterator i(root); i != boost::filesystem::directory_iterator(); ++i) { switch (i->status().type()) { case boost::filesystem::file_type::regular_file: yield.push_result(i->path()); break; case boost::filesystem::file_type::directory_file: list_files_recursively(yield, i->path()); break; default: //ignore break; } } } } Si::unique_observable<boost::filesystem::path> list_files_recursively(boost::filesystem::path const &root) { return Si::erase_unique(Si::make_thread<boost::filesystem::path, Si::boost_threading>([root](Si::yield_context_2<boost::filesystem::path> &yield) { return detail::list_files_recursively(yield, root); })); } } int main() { boost::asio::io_service io; boost::asio::ip::tcp::acceptor acceptor(io, boost::asio::ip::tcp::endpoint(boost::asio::ip::address_v4(), 8080)); Si::tcp_acceptor clients(acceptor); file_repository files; auto accept_all = Si::make_coroutine<session_handle>([&clients, &files](Si::yield_context<session_handle> &yield) { for (;;) { auto accepted = yield.get_one(clients); if (!accepted) { return; } Si::visit<void>( *accepted, [&yield, &files](std::shared_ptr<boost::asio::ip::tcp::socket> socket) { auto prepare_socket = [socket, &files](Si::yield_context<Si::nothing> &yield) { std::array<char, 1024> receive_buffer; Si::socket_observable received(*socket, boost::make_iterator_range(receive_buffer.data(), receive_buffer.data() + receive_buffer.size())); auto make_sender = [socket](Si::incoming_bytes sent) { return Si::sending_observable(*socket, to_range(sent)); }; auto shutdown = [socket]() { socket->shutdown(boost::asio::ip::tcp::socket::shutdown_both); }; serve_client(yield, received, make_sender, shutdown, files); }; yield(Si::erase_shared(Si::make_coroutine<Si::nothing>(prepare_socket))); }, [](boost::system::error_code) { throw std::logic_error("to do"); } ); } }); auto all_sessions_finished = Si::flatten<boost::interprocess::null_mutex>(std::move(accept_all)); auto done = Si::make_total_consumer(std::move(all_sessions_finished)); done.start(); auto listed = Si::for_each(list_files_recursively(boost::filesystem::current_path()), [](boost::filesystem::path const &file) { std::cerr << file << '\n'; }); listed.start(); io.run(); } <|endoftext|>
<commit_before>#include "stdafx.h" #include "CrashDump.h" #include <atltime.h> #include <dbghelp.h> #pragma comment(lib, "dbghelp.lib") #include "../../Common/Helpers/zip.h" #include "../../Common/Helpers/RapidHelper.hpp" namespace GameServer { namespace Fixes { using UnhandledExceptionFilterPtr_t = LONG(WINAPIV*)(::_EXCEPTION_POINTERS *); using UnhandledExceptionFilterClbk_t = LONG(WINAPIV*)(::_EXCEPTION_POINTERS *, UnhandledExceptionFilterPtr_t); UnhandledExceptionFilterPtr_t UnhandledExceptionFilter_next(nullptr); UnhandledExceptionFilterClbk_t UnhandledExceptionFilter_user(nullptr); inline fs::path GetPathByHandle(HMODULE hModule) { TCHAR szPath[MAX_PATH] = {}; GetModuleFileName(hModule, szPath, _countof(szPath)); return fs::path(szPath); } inline fs::path GetGameServerExePath() { return GetPathByHandle(nullptr); } EXTERN_C IMAGE_DOS_HEADER __ImageBase; inline fs::path GetDllPath() { return GetPathByHandle((HMODULE)&__ImageBase); } void UnhandledExceptionFilter_wrapper(::_EXCEPTION_POINTERS * pExceptionInfo) { UnhandledExceptionFilter_user(pExceptionInfo, UnhandledExceptionFilter_next); }; int CCrashDump::m_nCrash = 0; bool CCrashDump::m_bFullDump = false; const fs::path CCrashDump::m_pathCrashFolder = L".\\YorozuyaGS\\CrashDump\\"; CCrashDump::CCrashDump() { HMODULE hKernel = GetModuleHandleW(L"kernel32.dll"); if (hKernel != nullptr) { m_pSystemUnhandledFilter = GetProcAddress(hKernel, "UnhandledExceptionFilter"); auto& core = ATF::CATFCore::get_instance(); core.reg_wrapper( &CCrashDump::UnhandledExceptionFilter, ATF::_hook_record{ (LPVOID)m_pSystemUnhandledFilter, (LPVOID *)&UnhandledExceptionFilter_user, (LPVOID *)&UnhandledExceptionFilter_next, (LPVOID)ATF::cast_pointer_function(UnhandledExceptionFilter_wrapper), (LPVOID)ATF::cast_pointer_function((void(*)())&CCrashDump::UnhandledExceptionFilter) }); } } void CCrashDump::load() { enable_hook(&ATF::WheatyExceptionReport::GenerateExceptionReport, &CCrashDump::GenerateExceptionReport); enable_hook(&CCrashDump::UnhandledExceptionFilter, &CCrashDump::UnhandledExceptionFilter); fs::create_directories(m_pathCrashFolder); } void CCrashDump::unload() { } Yorozuya::Module::ModuleName_t CCrashDump::get_name() { static const Yorozuya::Module::ModuleName_t name = "system.crash_dump"; return name; } void CCrashDump::configure( const rapidjson::Value & nodeConfig) { m_bFullDump = RapidHelper::GetValueOrDefault(nodeConfig, "full_dump", true); } ::std::wstring CCrashDump::BuildFileNameDump() { ::ATL::CTime tmCurrentTime(::ATL::CTime::GetCurrentTime()); ::std::wstring wsRet(L"Dump " + ::std::to_wstring(m_nCrash++)); return wsRet + tmCurrentTime.Format(L". %d.%m.%Y %H-%M-%S.dmp").GetString(); } void WINAPIV CCrashDump::GenerateExceptionReport( ::_EXCEPTION_POINTERS* pExceptionInfo, ATF::Info::WheatyExceptionReportGenerateExceptionReport10_ptr next) { next((ATF::_EXCEPTION_POINTERS*)pExceptionInfo); fs::path pathFileDump(m_pathCrashFolder / BuildFileNameDump()); HANDLE hFile = CreateFileW( pathFileDump.generic_wstring().c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (hFile == INVALID_HANDLE_VALUE) return; MINIDUMP_EXCEPTION_INFORMATION eInfo; eInfo.ThreadId = GetCurrentThreadId(); eInfo.ExceptionPointers = pExceptionInfo; eInfo.ClientPointers = FALSE; int type; if (CCrashDump::m_bFullDump) { type = MiniDumpWithFullMemory; type |= MiniDumpWithFullMemoryInfo; type |= MiniDumpWithHandleData; type |= MiniDumpWithUnloadedModules; type |= MiniDumpWithThreadInfo; } else { type = MiniDumpNormal; type |= MiniDumpWithDataSegs; type |= MiniDumpFilterModulePaths; } BOOL bWriteDump = MiniDumpWriteDump( GetCurrentProcess(), GetCurrentProcessId(), hFile, static_cast<_MINIDUMP_TYPE>(type), &eInfo, nullptr, nullptr); CloseHandle(hFile); if (bWriteDump != TRUE) return; ::std::vector<fs::path> vecRequiredFiles { pathFileDump, GetGameServerExePath(), GetDllPath(), GetDllPath().replace_extension(L"pdb") }; auto pathZip = fs::path(pathFileDump).replace_extension(L"zip"); do { HZIP hZip = CreateZip(pathZip.generic_wstring().c_str(), 0); if (hZip == nullptr) break; size_t count = 0; ZRESULT hResult = ZR_OK; for (auto& file : vecRequiredFiles) { hResult = ZipAdd( hZip, file.filename().c_str(), file.generic_wstring().c_str()); if (hResult == ZR_OK) { ++count; } } CloseZip(hZip); if (count != vecRequiredFiles.size()) break; fs::remove(pathFileDump); } while (false); } LONG WINAPI CCrashDump::UnhandledExceptionFilter(::_EXCEPTION_POINTERS * ExceptionInfo) { UNREFERENCED_PARAMETER(ExceptionInfo); return EXCEPTION_CONTINUE_SEARCH; } } }<commit_msg>Removed archiving crash dump<commit_after>#include "stdafx.h" #include "CrashDump.h" #include <atltime.h> #include <dbghelp.h> #pragma comment(lib, "dbghelp.lib") #include "../../Common/Helpers/RapidHelper.hpp" namespace GameServer { namespace Fixes { using UnhandledExceptionFilterPtr_t = LONG(WINAPIV*)(::_EXCEPTION_POINTERS *); using UnhandledExceptionFilterClbk_t = LONG(WINAPIV*)(::_EXCEPTION_POINTERS *, UnhandledExceptionFilterPtr_t); UnhandledExceptionFilterPtr_t UnhandledExceptionFilter_next(nullptr); UnhandledExceptionFilterClbk_t UnhandledExceptionFilter_user(nullptr); inline fs::path GetPathByHandle(HMODULE hModule) { TCHAR szPath[MAX_PATH] = {}; GetModuleFileName(hModule, szPath, _countof(szPath)); return fs::path(szPath); } inline fs::path GetGameServerExePath() { return GetPathByHandle(nullptr); } EXTERN_C IMAGE_DOS_HEADER __ImageBase; inline fs::path GetDllPath() { return GetPathByHandle((HMODULE)&__ImageBase); } void UnhandledExceptionFilter_wrapper(::_EXCEPTION_POINTERS * pExceptionInfo) { UnhandledExceptionFilter_user(pExceptionInfo, UnhandledExceptionFilter_next); }; int CCrashDump::m_nCrash = 0; bool CCrashDump::m_bFullDump = false; const fs::path CCrashDump::m_pathCrashFolder = L".\\YorozuyaGS\\CrashDump\\"; CCrashDump::CCrashDump() { HMODULE hKernel = GetModuleHandleW(L"kernel32.dll"); if (hKernel != nullptr) { m_pSystemUnhandledFilter = GetProcAddress(hKernel, "UnhandledExceptionFilter"); auto& core = ATF::CATFCore::get_instance(); core.reg_wrapper( &CCrashDump::UnhandledExceptionFilter, ATF::_hook_record{ (LPVOID)m_pSystemUnhandledFilter, (LPVOID *)&UnhandledExceptionFilter_user, (LPVOID *)&UnhandledExceptionFilter_next, (LPVOID)ATF::cast_pointer_function(UnhandledExceptionFilter_wrapper), (LPVOID)ATF::cast_pointer_function((void(*)())&CCrashDump::UnhandledExceptionFilter) }); } } void CCrashDump::load() { enable_hook(&ATF::WheatyExceptionReport::GenerateExceptionReport, &CCrashDump::GenerateExceptionReport); enable_hook(&CCrashDump::UnhandledExceptionFilter, &CCrashDump::UnhandledExceptionFilter); fs::create_directories(m_pathCrashFolder); } void CCrashDump::unload() { } Yorozuya::Module::ModuleName_t CCrashDump::get_name() { static const Yorozuya::Module::ModuleName_t name = "system.crash_dump"; return name; } void CCrashDump::configure( const rapidjson::Value & nodeConfig) { m_bFullDump = RapidHelper::GetValueOrDefault(nodeConfig, "full_dump", true); } ::std::wstring CCrashDump::BuildFileNameDump() { ::ATL::CTime tmCurrentTime(::ATL::CTime::GetCurrentTime()); ::std::wstring wsRet(L"Dump " + ::std::to_wstring(m_nCrash++)); return wsRet + tmCurrentTime.Format(L". %d.%m.%Y %H-%M-%S.dmp").GetString(); } void WINAPIV CCrashDump::GenerateExceptionReport( ::_EXCEPTION_POINTERS* pExceptionInfo, ATF::Info::WheatyExceptionReportGenerateExceptionReport10_ptr next) { next((ATF::_EXCEPTION_POINTERS*)pExceptionInfo); fs::path pathFileDump(m_pathCrashFolder / BuildFileNameDump()); HANDLE hFile = CreateFileW( pathFileDump.generic_wstring().c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (hFile == INVALID_HANDLE_VALUE) return; MINIDUMP_EXCEPTION_INFORMATION eInfo; eInfo.ThreadId = GetCurrentThreadId(); eInfo.ExceptionPointers = pExceptionInfo; eInfo.ClientPointers = FALSE; int type; if (CCrashDump::m_bFullDump) { type = MiniDumpWithFullMemory; type |= MiniDumpWithFullMemoryInfo; type |= MiniDumpWithHandleData; type |= MiniDumpWithUnloadedModules; type |= MiniDumpWithThreadInfo; } else { type = MiniDumpNormal; type |= MiniDumpWithDataSegs; type |= MiniDumpFilterModulePaths; } BOOL bWriteDump = MiniDumpWriteDump( GetCurrentProcess(), GetCurrentProcessId(), hFile, static_cast<_MINIDUMP_TYPE>(type), &eInfo, nullptr, nullptr); CloseHandle(hFile); if (bWriteDump != TRUE) return; } LONG WINAPI CCrashDump::UnhandledExceptionFilter(::_EXCEPTION_POINTERS * ExceptionInfo) { UNREFERENCED_PARAMETER(ExceptionInfo); return EXCEPTION_CONTINUE_SEARCH; } } }<|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/autofill/autofill_download.h" #include <algorithm> #include <ostream> #include <vector> #include "base/logging.h" #include "base/rand_util.h" #include "base/stl_util.h" #include "base/string_util.h" #include "chrome/browser/autofill/autofill_metrics.h" #include "chrome/browser/autofill/autofill_xml_parser.h" #include "chrome/browser/autofill/form_structure.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/pref_names.h" #include "content/public/common/url_fetcher.h" #include "googleurl/src/gurl.h" #include "net/base/load_flags.h" #include "net/http/http_response_headers.h" #include "third_party/libjingle/source/talk/xmllite/xmlparser.h" namespace { const char kAutofillQueryServerRequestUrl[] = "https://clients1.google.com/tbproxy/af/query?client="; const char kAutofillUploadServerRequestUrl[] = "https://clients1.google.com/tbproxy/af/upload?client="; const char kAutofillQueryServerNameStartInHeader[] = "GFE/"; #if defined(GOOGLE_CHROME_BUILD) const char kClientName[] = "Google Chrome"; #else const char kClientName[] = "Chromium"; #endif // defined(GOOGLE_CHROME_BUILD) const size_t kMaxFormCacheSize = 16; }; struct AutofillDownloadManager::FormRequestData { std::vector<std::string> form_signatures; AutofillRequestType request_type; }; AutofillDownloadManager::AutofillDownloadManager(Profile* profile, Observer* observer) : profile_(profile), observer_(observer), max_form_cache_size_(kMaxFormCacheSize), next_query_request_(base::Time::Now()), next_upload_request_(base::Time::Now()), positive_upload_rate_(0), negative_upload_rate_(0), fetcher_id_for_unittest_(0) { DCHECK(observer_); PrefService* preferences = profile_->GetPrefs(); positive_upload_rate_ = preferences->GetDouble(prefs::kAutofillPositiveUploadRate); negative_upload_rate_ = preferences->GetDouble(prefs::kAutofillNegativeUploadRate); } AutofillDownloadManager::~AutofillDownloadManager() { STLDeleteContainerPairFirstPointers(url_fetchers_.begin(), url_fetchers_.end()); } bool AutofillDownloadManager::StartQueryRequest( const std::vector<FormStructure*>& forms, const AutofillMetrics& metric_logger) { if (next_query_request_ > base::Time::Now()) { // We are in back-off mode: do not do the request. return false; } std::string form_xml; FormRequestData request_data; if (!FormStructure::EncodeQueryRequest(forms, &request_data.form_signatures, &form_xml)) { return false; } request_data.request_type = AutofillDownloadManager::REQUEST_QUERY; metric_logger.LogServerQueryMetric(AutofillMetrics::QUERY_SENT); std::string query_data; if (CheckCacheForQueryRequest(request_data.form_signatures, &query_data)) { DVLOG(1) << "AutofillDownloadManager: query request has been retrieved from" << "the cache"; observer_->OnLoadedServerPredictions(query_data); return true; } return StartRequest(form_xml, request_data); } bool AutofillDownloadManager::StartUploadRequest( const FormStructure& form, bool form_was_autofilled, const FieldTypeSet& available_field_types) { if (next_upload_request_ > base::Time::Now()) { // We are in back-off mode: do not do the request. DVLOG(1) << "AutofillDownloadManager: Upload request is throttled."; return false; } // Flip a coin to see if we should upload this form. double upload_rate = form_was_autofilled ? GetPositiveUploadRate() : GetNegativeUploadRate(); if (form.upload_required() == UPLOAD_NOT_REQUIRED || (form.upload_required() == USE_UPLOAD_RATES && base::RandDouble() > upload_rate)) { DVLOG(1) << "AutofillDownloadManager: Upload request is ignored."; // If we ever need notification that upload was skipped, add it here. return false; } std::string form_xml; if (!form.EncodeUploadRequest(available_field_types, form_was_autofilled, &form_xml)) return false; FormRequestData request_data; request_data.form_signatures.push_back(form.FormSignature()); request_data.request_type = AutofillDownloadManager::REQUEST_UPLOAD; return StartRequest(form_xml, request_data); } double AutofillDownloadManager::GetPositiveUploadRate() const { return positive_upload_rate_; } double AutofillDownloadManager::GetNegativeUploadRate() const { return negative_upload_rate_; } void AutofillDownloadManager::SetPositiveUploadRate(double rate) { if (rate == positive_upload_rate_) return; positive_upload_rate_ = rate; DCHECK_GE(rate, 0.0); DCHECK_LE(rate, 1.0); PrefService* preferences = profile_->GetPrefs(); preferences->SetDouble(prefs::kAutofillPositiveUploadRate, rate); } void AutofillDownloadManager::SetNegativeUploadRate(double rate) { if (rate == negative_upload_rate_) return; negative_upload_rate_ = rate; DCHECK_GE(rate, 0.0); DCHECK_LE(rate, 1.0); PrefService* preferences = profile_->GetPrefs(); preferences->SetDouble(prefs::kAutofillNegativeUploadRate, rate); } bool AutofillDownloadManager::StartRequest( const std::string& form_xml, const FormRequestData& request_data) { net::URLRequestContextGetter* request_context = profile_->GetRequestContext(); DCHECK(request_context); std::string request_url; if (request_data.request_type == AutofillDownloadManager::REQUEST_QUERY) request_url = kAutofillQueryServerRequestUrl; else request_url = kAutofillUploadServerRequestUrl; request_url += kClientName; // Id is ignored for regular chrome, in unit test id's for fake fetcher // factory will be 0, 1, 2, ... content::URLFetcher* fetcher = content::URLFetcher::Create( fetcher_id_for_unittest_++, GURL(request_url), content::URLFetcher::POST, this); url_fetchers_[fetcher] = request_data; fetcher->SetAutomaticallyRetryOn5xx(false); fetcher->SetRequestContext(request_context); fetcher->SetUploadData("text/plain", form_xml); fetcher->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES); fetcher->Start(); return true; } void AutofillDownloadManager::CacheQueryRequest( const std::vector<std::string>& forms_in_query, const std::string& query_data) { std::string signature = GetCombinedSignature(forms_in_query); for (QueryRequestCache::iterator it = cached_forms_.begin(); it != cached_forms_.end(); ++it) { if (it->first == signature) { // We hit the cache, move to the first position and return. std::pair<std::string, std::string> data = *it; cached_forms_.erase(it); cached_forms_.push_front(data); return; } } std::pair<std::string, std::string> data; data.first = signature; data.second = query_data; cached_forms_.push_front(data); while (cached_forms_.size() > max_form_cache_size_) cached_forms_.pop_back(); } bool AutofillDownloadManager::CheckCacheForQueryRequest( const std::vector<std::string>& forms_in_query, std::string* query_data) const { std::string signature = GetCombinedSignature(forms_in_query); for (QueryRequestCache::const_iterator it = cached_forms_.begin(); it != cached_forms_.end(); ++it) { if (it->first == signature) { // We hit the cache, fill the data and return. *query_data = it->second; return true; } } return false; } std::string AutofillDownloadManager::GetCombinedSignature( const std::vector<std::string>& forms_in_query) const { size_t total_size = forms_in_query.size(); for (size_t i = 0; i < forms_in_query.size(); ++i) total_size += forms_in_query[i].length(); std::string signature; signature.reserve(total_size); for (size_t i = 0; i < forms_in_query.size(); ++i) { if (i) signature.append(","); signature.append(forms_in_query[i]); } return signature; } void AutofillDownloadManager::OnURLFetchComplete( const content::URLFetcher* source) { std::map<content::URLFetcher *, FormRequestData>::iterator it = url_fetchers_.find(const_cast<content::URLFetcher*>(source)); if (it == url_fetchers_.end()) { // Looks like crash on Mac is possibly caused with callback entering here // with unknown fetcher when network is refreshed. return; } std::string type_of_request( it->second.request_type == AutofillDownloadManager::REQUEST_QUERY ? "query" : "upload"); const int kHttpResponseOk = 200; const int kHttpInternalServerError = 500; const int kHttpBadGateway = 502; const int kHttpServiceUnavailable = 503; CHECK(it->second.form_signatures.size()); if (source->GetResponseCode() != kHttpResponseOk) { bool back_off = false; std::string server_header; switch (source->GetResponseCode()) { case kHttpBadGateway: if (!source->GetResponseHeaders()->EnumerateHeader(NULL, "server", &server_header) || StartsWithASCII(server_header.c_str(), kAutofillQueryServerNameStartInHeader, false) != 0) break; // Bad gateway was received from Autofill servers. Fall through to back // off. case kHttpInternalServerError: case kHttpServiceUnavailable: back_off = true; break; } if (back_off) { base::Time back_off_time(base::Time::Now() + source->GetBackoffDelay()); if (it->second.request_type == AutofillDownloadManager::REQUEST_QUERY) { next_query_request_ = back_off_time; } else { next_upload_request_ = back_off_time; } } DVLOG(1) << "AutofillDownloadManager: " << type_of_request << " request has failed with response " << source->GetResponseCode(); observer_->OnServerRequestError(it->second.form_signatures[0], it->second.request_type, source->GetResponseCode()); } else { DVLOG(1) << "AutofillDownloadManager: " << type_of_request << " request has succeeded"; std::string response_body; source->GetResponseAsString(&response_body); if (it->second.request_type == AutofillDownloadManager::REQUEST_QUERY) { CacheQueryRequest(it->second.form_signatures, response_body); observer_->OnLoadedServerPredictions(response_body); } else { double new_positive_upload_rate = 0; double new_negative_upload_rate = 0; AutofillUploadXmlParser parse_handler(&new_positive_upload_rate, &new_negative_upload_rate); buzz::XmlParser parser(&parse_handler); parser.Parse(response_body.data(), response_body.length(), true); if (parse_handler.succeeded()) { SetPositiveUploadRate(new_positive_upload_rate); SetNegativeUploadRate(new_negative_upload_rate); } observer_->OnUploadedPossibleFieldTypes(); } } delete it->first; url_fetchers_.erase(it); } <commit_msg>Added net::LOAD_DO_NOT_SEND_COOKIES to autofil_download to fix: 118932: URLFetcher::Create calls in chrome/browser/autofill/autofill_download.cc<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/autofill/autofill_download.h" #include <algorithm> #include <ostream> #include <vector> #include "base/logging.h" #include "base/rand_util.h" #include "base/stl_util.h" #include "base/string_util.h" #include "chrome/browser/autofill/autofill_metrics.h" #include "chrome/browser/autofill/autofill_xml_parser.h" #include "chrome/browser/autofill/form_structure.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/pref_names.h" #include "content/public/common/url_fetcher.h" #include "googleurl/src/gurl.h" #include "net/base/load_flags.h" #include "net/http/http_response_headers.h" #include "third_party/libjingle/source/talk/xmllite/xmlparser.h" namespace { const char kAutofillQueryServerRequestUrl[] = "https://clients1.google.com/tbproxy/af/query?client="; const char kAutofillUploadServerRequestUrl[] = "https://clients1.google.com/tbproxy/af/upload?client="; const char kAutofillQueryServerNameStartInHeader[] = "GFE/"; #if defined(GOOGLE_CHROME_BUILD) const char kClientName[] = "Google Chrome"; #else const char kClientName[] = "Chromium"; #endif // defined(GOOGLE_CHROME_BUILD) const size_t kMaxFormCacheSize = 16; }; struct AutofillDownloadManager::FormRequestData { std::vector<std::string> form_signatures; AutofillRequestType request_type; }; AutofillDownloadManager::AutofillDownloadManager(Profile* profile, Observer* observer) : profile_(profile), observer_(observer), max_form_cache_size_(kMaxFormCacheSize), next_query_request_(base::Time::Now()), next_upload_request_(base::Time::Now()), positive_upload_rate_(0), negative_upload_rate_(0), fetcher_id_for_unittest_(0) { DCHECK(observer_); PrefService* preferences = profile_->GetPrefs(); positive_upload_rate_ = preferences->GetDouble(prefs::kAutofillPositiveUploadRate); negative_upload_rate_ = preferences->GetDouble(prefs::kAutofillNegativeUploadRate); } AutofillDownloadManager::~AutofillDownloadManager() { STLDeleteContainerPairFirstPointers(url_fetchers_.begin(), url_fetchers_.end()); } bool AutofillDownloadManager::StartQueryRequest( const std::vector<FormStructure*>& forms, const AutofillMetrics& metric_logger) { if (next_query_request_ > base::Time::Now()) { // We are in back-off mode: do not do the request. return false; } std::string form_xml; FormRequestData request_data; if (!FormStructure::EncodeQueryRequest(forms, &request_data.form_signatures, &form_xml)) { return false; } request_data.request_type = AutofillDownloadManager::REQUEST_QUERY; metric_logger.LogServerQueryMetric(AutofillMetrics::QUERY_SENT); std::string query_data; if (CheckCacheForQueryRequest(request_data.form_signatures, &query_data)) { DVLOG(1) << "AutofillDownloadManager: query request has been retrieved from" << "the cache"; observer_->OnLoadedServerPredictions(query_data); return true; } return StartRequest(form_xml, request_data); } bool AutofillDownloadManager::StartUploadRequest( const FormStructure& form, bool form_was_autofilled, const FieldTypeSet& available_field_types) { if (next_upload_request_ > base::Time::Now()) { // We are in back-off mode: do not do the request. DVLOG(1) << "AutofillDownloadManager: Upload request is throttled."; return false; } // Flip a coin to see if we should upload this form. double upload_rate = form_was_autofilled ? GetPositiveUploadRate() : GetNegativeUploadRate(); if (form.upload_required() == UPLOAD_NOT_REQUIRED || (form.upload_required() == USE_UPLOAD_RATES && base::RandDouble() > upload_rate)) { DVLOG(1) << "AutofillDownloadManager: Upload request is ignored."; // If we ever need notification that upload was skipped, add it here. return false; } std::string form_xml; if (!form.EncodeUploadRequest(available_field_types, form_was_autofilled, &form_xml)) return false; FormRequestData request_data; request_data.form_signatures.push_back(form.FormSignature()); request_data.request_type = AutofillDownloadManager::REQUEST_UPLOAD; return StartRequest(form_xml, request_data); } double AutofillDownloadManager::GetPositiveUploadRate() const { return positive_upload_rate_; } double AutofillDownloadManager::GetNegativeUploadRate() const { return negative_upload_rate_; } void AutofillDownloadManager::SetPositiveUploadRate(double rate) { if (rate == positive_upload_rate_) return; positive_upload_rate_ = rate; DCHECK_GE(rate, 0.0); DCHECK_LE(rate, 1.0); PrefService* preferences = profile_->GetPrefs(); preferences->SetDouble(prefs::kAutofillPositiveUploadRate, rate); } void AutofillDownloadManager::SetNegativeUploadRate(double rate) { if (rate == negative_upload_rate_) return; negative_upload_rate_ = rate; DCHECK_GE(rate, 0.0); DCHECK_LE(rate, 1.0); PrefService* preferences = profile_->GetPrefs(); preferences->SetDouble(prefs::kAutofillNegativeUploadRate, rate); } bool AutofillDownloadManager::StartRequest( const std::string& form_xml, const FormRequestData& request_data) { net::URLRequestContextGetter* request_context = profile_->GetRequestContext(); DCHECK(request_context); std::string request_url; if (request_data.request_type == AutofillDownloadManager::REQUEST_QUERY) request_url = kAutofillQueryServerRequestUrl; else request_url = kAutofillUploadServerRequestUrl; request_url += kClientName; // Id is ignored for regular chrome, in unit test id's for fake fetcher // factory will be 0, 1, 2, ... content::URLFetcher* fetcher = content::URLFetcher::Create( fetcher_id_for_unittest_++, GURL(request_url), content::URLFetcher::POST, this); url_fetchers_[fetcher] = request_data; fetcher->SetAutomaticallyRetryOn5xx(false); fetcher->SetRequestContext(request_context); fetcher->SetUploadData("text/plain", form_xml); fetcher->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DO_NOT_SEND_COOKIES); fetcher->Start(); return true; } void AutofillDownloadManager::CacheQueryRequest( const std::vector<std::string>& forms_in_query, const std::string& query_data) { std::string signature = GetCombinedSignature(forms_in_query); for (QueryRequestCache::iterator it = cached_forms_.begin(); it != cached_forms_.end(); ++it) { if (it->first == signature) { // We hit the cache, move to the first position and return. std::pair<std::string, std::string> data = *it; cached_forms_.erase(it); cached_forms_.push_front(data); return; } } std::pair<std::string, std::string> data; data.first = signature; data.second = query_data; cached_forms_.push_front(data); while (cached_forms_.size() > max_form_cache_size_) cached_forms_.pop_back(); } bool AutofillDownloadManager::CheckCacheForQueryRequest( const std::vector<std::string>& forms_in_query, std::string* query_data) const { std::string signature = GetCombinedSignature(forms_in_query); for (QueryRequestCache::const_iterator it = cached_forms_.begin(); it != cached_forms_.end(); ++it) { if (it->first == signature) { // We hit the cache, fill the data and return. *query_data = it->second; return true; } } return false; } std::string AutofillDownloadManager::GetCombinedSignature( const std::vector<std::string>& forms_in_query) const { size_t total_size = forms_in_query.size(); for (size_t i = 0; i < forms_in_query.size(); ++i) total_size += forms_in_query[i].length(); std::string signature; signature.reserve(total_size); for (size_t i = 0; i < forms_in_query.size(); ++i) { if (i) signature.append(","); signature.append(forms_in_query[i]); } return signature; } void AutofillDownloadManager::OnURLFetchComplete( const content::URLFetcher* source) { std::map<content::URLFetcher *, FormRequestData>::iterator it = url_fetchers_.find(const_cast<content::URLFetcher*>(source)); if (it == url_fetchers_.end()) { // Looks like crash on Mac is possibly caused with callback entering here // with unknown fetcher when network is refreshed. return; } std::string type_of_request( it->second.request_type == AutofillDownloadManager::REQUEST_QUERY ? "query" : "upload"); const int kHttpResponseOk = 200; const int kHttpInternalServerError = 500; const int kHttpBadGateway = 502; const int kHttpServiceUnavailable = 503; CHECK(it->second.form_signatures.size()); if (source->GetResponseCode() != kHttpResponseOk) { bool back_off = false; std::string server_header; switch (source->GetResponseCode()) { case kHttpBadGateway: if (!source->GetResponseHeaders()->EnumerateHeader(NULL, "server", &server_header) || StartsWithASCII(server_header.c_str(), kAutofillQueryServerNameStartInHeader, false) != 0) break; // Bad gateway was received from Autofill servers. Fall through to back // off. case kHttpInternalServerError: case kHttpServiceUnavailable: back_off = true; break; } if (back_off) { base::Time back_off_time(base::Time::Now() + source->GetBackoffDelay()); if (it->second.request_type == AutofillDownloadManager::REQUEST_QUERY) { next_query_request_ = back_off_time; } else { next_upload_request_ = back_off_time; } } DVLOG(1) << "AutofillDownloadManager: " << type_of_request << " request has failed with response " << source->GetResponseCode(); observer_->OnServerRequestError(it->second.form_signatures[0], it->second.request_type, source->GetResponseCode()); } else { DVLOG(1) << "AutofillDownloadManager: " << type_of_request << " request has succeeded"; std::string response_body; source->GetResponseAsString(&response_body); if (it->second.request_type == AutofillDownloadManager::REQUEST_QUERY) { CacheQueryRequest(it->second.form_signatures, response_body); observer_->OnLoadedServerPredictions(response_body); } else { double new_positive_upload_rate = 0; double new_negative_upload_rate = 0; AutofillUploadXmlParser parse_handler(&new_positive_upload_rate, &new_negative_upload_rate); buzz::XmlParser parser(&parse_handler); parser.Parse(response_body.data(), response_body.length(), true); if (parse_handler.succeeded()) { SetPositiveUploadRate(new_positive_upload_rate); SetNegativeUploadRate(new_negative_upload_rate); } observer_->OnUploadedPossibleFieldTypes(); } } delete it->first; url_fetchers_.erase(it); } <|endoftext|>
<commit_before>// Time: O(nlogn) // Space: O(n) class Solution { public: class BSTreeNode { public: int val, count; BSTreeNode *left, *right; BSTreeNode(int val, int count) { this->val = val; this->count = count; this->left = this->right = nullptr; } }; /** * @param A: An integer array * @return: Count the number of element before this element 'ai' is * smaller than it and return count number array */ vector<int> countOfSmallerNumberII(vector<int> &A) { vector<int> res; BSTreeNode *root = nullptr; // Insert into BST and get left count. for (int i = 0; i < A.size(); ++i) { int count = 0; BSTreeNode *node = new BSTreeNode(A[i], 0); root = insertNode(root, node); count = query(root, A[i]); res.emplace_back(count); } return res; } // Insert node into BST. BSTreeNode* insertNode(BSTreeNode* root, BSTreeNode* node) { if (root == nullptr) { return node; } BSTreeNode* curr = root; while (curr) { // Insert left if smaller. if (node->val < curr->val) { ++curr->count; // Increase the number of left children. if (curr->left != nullptr) { curr = curr->left; } else { curr->left = node; break; } } else { // Insert right if larger or equal. if (curr->right != nullptr) { curr = curr->right; } else { curr->right = node; break; } } } return root; } // Query the smaller count of the value. int query(BSTreeNode* root, int val) { if (root == nullptr) { return 0; } int count = 0; BSTreeNode* curr = root; while (curr) { // Insert left. if (val < curr->val) { curr = curr->left; } else if (val > curr->val) { count += 1 + curr->count; // Count the number of the smaller nodes. curr = curr->right; } else { // Equal. return count + curr->count; } } return 0; } }; <commit_msg>Update count-of-smaller-number-before-itself.cpp<commit_after>// Time: O(nlogn) // Space: O(n) // BIT solution. (281ms) class Solution { public: /** * @param A: An integer array * @return: Count the number of element before this element 'ai' is * smaller than it and return count number array */ vector<int> countOfSmallerNumberII(vector<int> &A) { vector<int> sorted_A(A), orderings(A.size()); sort(sorted_A.begin(), sorted_A.end()); for (int i = 0; i < A.size(); ++i) { orderings[i] = lower_bound(sorted_A.begin(), sorted_A.end(), A[i]) - sorted_A.begin(); } vector<int> bit(A.size() + 1), ans(A.size()); for (int i = 0; i < orderings.size(); ++i) { ans[i] = query(bit, orderings[i]); add(bit, orderings[i] + 1, 1); } return ans; } private: void add(vector<int>& bit, int i, int val) { for (; i < bit.size(); i += lower_bit(i)) { bit[i] += val; } } int query(const vector<int>& bit, int i) { int sum = 0; for (; i > 0; i -= lower_bit(i)) { sum += bit[i]; } return sum; } int lower_bit(int i) { return i & -i; } }; // Time: O(nlogn) // Space: O(n) // BST solution. (743ms) class Solution2 { public: class BSTreeNode { public: int val, count; BSTreeNode *left, *right; BSTreeNode(int val, int count) { this->val = val; this->count = count; this->left = this->right = nullptr; } }; /** * @param A: An integer array * @return: Count the number of element before this element 'ai' is * smaller than it and return count number array */ vector<int> countOfSmallerNumberII(vector<int> &A) { vector<int> res; BSTreeNode *root = nullptr; // Insert into BST and get left count. for (int i = 0; i < A.size(); ++i) { int count = 0; BSTreeNode *node = new BSTreeNode(A[i], 0); root = insertNode(root, node); count = query(root, A[i]); res.emplace_back(count); } return res; } // Insert node into BST. BSTreeNode* insertNode(BSTreeNode* root, BSTreeNode* node) { if (root == nullptr) { return node; } BSTreeNode* curr = root; while (curr) { // Insert left if smaller. if (node->val < curr->val) { ++curr->count; // Increase the number of left children. if (curr->left != nullptr) { curr = curr->left; } else { curr->left = node; break; } } else { // Insert right if larger or equal. if (curr->right != nullptr) { curr = curr->right; } else { curr->right = node; break; } } } return root; } // Query the smaller count of the value. int query(BSTreeNode* root, int val) { if (root == nullptr) { return 0; } int count = 0; BSTreeNode* curr = root; while (curr) { // Insert left. if (val < curr->val) { curr = curr->left; } else if (val > curr->val) { count += 1 + curr->count; // Count the number of the smaller nodes. curr = curr->right; } else { // Equal. return count + curr->count; } } return 0; } }; <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "app/surface/transport_dib.h" #include "base/basictypes.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/ref_counted_memory.h" #include "base/stringprintf.h" #include "chrome/common/render_messages.h" #include "chrome/common/render_messages_params.h" #include "chrome/renderer/render_widget_browsertest.h" #include "gfx/codec/jpeg_codec.h" #include "gfx/size.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/WebKit/WebKit/chromium/public/WebSize.h" #include "third_party/WebKit/WebKit/chromium/public/WebView.h" const int RenderWidgetTest::kNumBytesPerPixel = 4; const int RenderWidgetTest::kLargeWidth = 1024; const int RenderWidgetTest::kLargeHeight = 768; const int RenderWidgetTest::kSmallWidth = 600; const int RenderWidgetTest::kSmallHeight = 450; const int RenderWidgetTest::kTextPositionX = 800; const int RenderWidgetTest::kTextPositionY = 600; const int RenderWidgetTest::kSequenceNum = 1; const uint32 RenderWidgetTest::kRedARGB = 0xFFFF0000; RenderWidgetTest::RenderWidgetTest() {} void RenderWidgetTest::ResizeAndPaint(const gfx::Size& page_size, const gfx::Size& desired_size, SkBitmap* snapshot) { ASSERT_TRUE(snapshot); scoped_ptr<TransportDIB> pixels( TransportDIB::Create( page_size.width() * page_size.height() * kNumBytesPerPixel, kSequenceNum)); view_->OnMsgPaintAtSize(pixels->handle(), kSequenceNum, page_size, desired_size); ProcessPendingMessages(); const IPC::Message* msg = render_thread_.sink().GetUniqueMessageMatching( ViewHostMsg_PaintAtSize_ACK::ID); ASSERT_NE(static_cast<IPC::Message*>(NULL), msg); ViewHostMsg_PaintAtSize_ACK::Param params; ViewHostMsg_PaintAtSize_ACK::Read(msg, &params); render_thread_.sink().ClearMessages(); EXPECT_EQ(kSequenceNum, params.a); gfx::Size size = params.b; EXPECT_EQ(desired_size, size); SkBitmap tmp_bitmap; tmp_bitmap.setConfig(SkBitmap::kARGB_8888_Config, size.width(), size.height()); tmp_bitmap.setPixels(pixels->memory()); // Copy the pixels from the TransportDIB object to the given snapshot. ASSERT_TRUE(tmp_bitmap.copyTo(snapshot, SkBitmap::kARGB_8888_Config)); } void RenderWidgetTest::TestResizeAndPaint() { // Hello World message is only visible if the view size is at least // kTextPositionX x kTextPositionY LoadHTML(StringPrintf( "<html><body><div style='position: absolute; top: %d; left: " "%d; background-color: red;'>Hello World</div></body></html>", kTextPositionY, kTextPositionX).c_str()); WebKit::WebSize old_size = view_->webview()->size(); SkBitmap bitmap; // If we re-size the view to something smaller than where the 'Hello World' // text is displayed we won't see any text in the snapshot. Hence, // the snapshot should not contain any red. gfx::Size size(kSmallWidth, kSmallHeight); ResizeAndPaint(size, size, &bitmap); // Make sure that the view has been re-sized to its old size. EXPECT_EQ(old_size, view_->webview()->size()); EXPECT_EQ(kSmallWidth, bitmap.width()); EXPECT_EQ(kSmallHeight, bitmap.height()); EXPECT_FALSE(ImageContainsColor(bitmap, kRedARGB)); // Since we ask for the view to be re-sized to something larger than where the // 'Hello World' text is written the text should be visible in the snapshot. // Hence, the snapshot should contain some red. size.SetSize(kLargeWidth, kLargeHeight); ResizeAndPaint(size, size, &bitmap); EXPECT_EQ(old_size, view_->webview()->size()); EXPECT_EQ(kLargeWidth, bitmap.width()); EXPECT_EQ(kLargeHeight, bitmap.height()); EXPECT_TRUE(ImageContainsColor(bitmap, kRedARGB)); // Even if the desired size is smaller than where the text is located we // should still see the 'Hello World' message since the view size is // still large enough. ResizeAndPaint(size, gfx::Size(kSmallWidth, kSmallHeight), &bitmap); EXPECT_EQ(old_size, view_->webview()->size()); EXPECT_EQ(kSmallWidth, bitmap.width()); EXPECT_EQ(kSmallHeight, bitmap.height()); EXPECT_TRUE(ImageContainsColor(bitmap, kRedARGB)); } bool RenderWidgetTest::ImageContainsColor(const SkBitmap& bitmap, uint32 argb_color) { SkAutoLockPixels lock(bitmap); bool ready = bitmap.readyToDraw(); EXPECT_TRUE(ready); if (!ready) { return false; } for (int x = 0; x < bitmap.width(); ++x) { for (int y = 0; y < bitmap.height(); ++y) { if (argb_color == *bitmap.getAddr32(x, y)) { return true; } } } return false; } void RenderWidgetTest::OutputBitmapToFile(const SkBitmap& bitmap, const FilePath& file_path) { scoped_refptr<RefCountedBytes> bitmap_data = new RefCountedBytes(); SkAutoLockPixels lock(bitmap); ASSERT_TRUE(gfx::JPEGCodec::Encode( reinterpret_cast<unsigned char*>(bitmap.getAddr32(0, 0)), gfx::JPEGCodec::FORMAT_BGRA, bitmap.width(), bitmap.height(), static_cast<int>(bitmap.rowBytes()), 90 /* quality */, &bitmap_data->data)); ASSERT_LT(0, file_util::WriteFile( file_path, reinterpret_cast<const char*>(bitmap_data->front()), bitmap_data->size())); } TEST_F(RenderWidgetTest, OnMsgPaintAtSize) { TestResizeAndPaint(); } <commit_msg>Mark failing test OnMsgPaintAtSize failing TBR=noelutz BUG=none TEST=none Review URL: http://codereview.chromium.org/3470011<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "app/surface/transport_dib.h" #include "base/basictypes.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/ref_counted_memory.h" #include "base/stringprintf.h" #include "chrome/common/render_messages.h" #include "chrome/common/render_messages_params.h" #include "chrome/renderer/render_widget_browsertest.h" #include "gfx/codec/jpeg_codec.h" #include "gfx/size.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/WebKit/WebKit/chromium/public/WebSize.h" #include "third_party/WebKit/WebKit/chromium/public/WebView.h" const int RenderWidgetTest::kNumBytesPerPixel = 4; const int RenderWidgetTest::kLargeWidth = 1024; const int RenderWidgetTest::kLargeHeight = 768; const int RenderWidgetTest::kSmallWidth = 600; const int RenderWidgetTest::kSmallHeight = 450; const int RenderWidgetTest::kTextPositionX = 800; const int RenderWidgetTest::kTextPositionY = 600; const int RenderWidgetTest::kSequenceNum = 1; const uint32 RenderWidgetTest::kRedARGB = 0xFFFF0000; RenderWidgetTest::RenderWidgetTest() {} void RenderWidgetTest::ResizeAndPaint(const gfx::Size& page_size, const gfx::Size& desired_size, SkBitmap* snapshot) { ASSERT_TRUE(snapshot); scoped_ptr<TransportDIB> pixels( TransportDIB::Create( page_size.width() * page_size.height() * kNumBytesPerPixel, kSequenceNum)); view_->OnMsgPaintAtSize(pixels->handle(), kSequenceNum, page_size, desired_size); ProcessPendingMessages(); const IPC::Message* msg = render_thread_.sink().GetUniqueMessageMatching( ViewHostMsg_PaintAtSize_ACK::ID); ASSERT_NE(static_cast<IPC::Message*>(NULL), msg); ViewHostMsg_PaintAtSize_ACK::Param params; ViewHostMsg_PaintAtSize_ACK::Read(msg, &params); render_thread_.sink().ClearMessages(); EXPECT_EQ(kSequenceNum, params.a); gfx::Size size = params.b; EXPECT_EQ(desired_size, size); SkBitmap tmp_bitmap; tmp_bitmap.setConfig(SkBitmap::kARGB_8888_Config, size.width(), size.height()); tmp_bitmap.setPixels(pixels->memory()); // Copy the pixels from the TransportDIB object to the given snapshot. ASSERT_TRUE(tmp_bitmap.copyTo(snapshot, SkBitmap::kARGB_8888_Config)); } void RenderWidgetTest::TestResizeAndPaint() { // Hello World message is only visible if the view size is at least // kTextPositionX x kTextPositionY LoadHTML(StringPrintf( "<html><body><div style='position: absolute; top: %d; left: " "%d; background-color: red;'>Hello World</div></body></html>", kTextPositionY, kTextPositionX).c_str()); WebKit::WebSize old_size = view_->webview()->size(); SkBitmap bitmap; // If we re-size the view to something smaller than where the 'Hello World' // text is displayed we won't see any text in the snapshot. Hence, // the snapshot should not contain any red. gfx::Size size(kSmallWidth, kSmallHeight); ResizeAndPaint(size, size, &bitmap); // Make sure that the view has been re-sized to its old size. EXPECT_EQ(old_size, view_->webview()->size()); EXPECT_EQ(kSmallWidth, bitmap.width()); EXPECT_EQ(kSmallHeight, bitmap.height()); EXPECT_FALSE(ImageContainsColor(bitmap, kRedARGB)); // Since we ask for the view to be re-sized to something larger than where the // 'Hello World' text is written the text should be visible in the snapshot. // Hence, the snapshot should contain some red. size.SetSize(kLargeWidth, kLargeHeight); ResizeAndPaint(size, size, &bitmap); EXPECT_EQ(old_size, view_->webview()->size()); EXPECT_EQ(kLargeWidth, bitmap.width()); EXPECT_EQ(kLargeHeight, bitmap.height()); EXPECT_TRUE(ImageContainsColor(bitmap, kRedARGB)); // Even if the desired size is smaller than where the text is located we // should still see the 'Hello World' message since the view size is // still large enough. ResizeAndPaint(size, gfx::Size(kSmallWidth, kSmallHeight), &bitmap); EXPECT_EQ(old_size, view_->webview()->size()); EXPECT_EQ(kSmallWidth, bitmap.width()); EXPECT_EQ(kSmallHeight, bitmap.height()); EXPECT_TRUE(ImageContainsColor(bitmap, kRedARGB)); } bool RenderWidgetTest::ImageContainsColor(const SkBitmap& bitmap, uint32 argb_color) { SkAutoLockPixels lock(bitmap); bool ready = bitmap.readyToDraw(); EXPECT_TRUE(ready); if (!ready) { return false; } for (int x = 0; x < bitmap.width(); ++x) { for (int y = 0; y < bitmap.height(); ++y) { if (argb_color == *bitmap.getAddr32(x, y)) { return true; } } } return false; } void RenderWidgetTest::OutputBitmapToFile(const SkBitmap& bitmap, const FilePath& file_path) { scoped_refptr<RefCountedBytes> bitmap_data = new RefCountedBytes(); SkAutoLockPixels lock(bitmap); ASSERT_TRUE(gfx::JPEGCodec::Encode( reinterpret_cast<unsigned char*>(bitmap.getAddr32(0, 0)), gfx::JPEGCodec::FORMAT_BGRA, bitmap.width(), bitmap.height(), static_cast<int>(bitmap.rowBytes()), 90 /* quality */, &bitmap_data->data)); ASSERT_LT(0, file_util::WriteFile( file_path, reinterpret_cast<const char*>(bitmap_data->front()), bitmap_data->size())); } TEST_F(RenderWidgetTest, FAILS_OnMsgPaintAtSize) { TestResizeAndPaint(); } <|endoftext|>
<commit_before><commit_msg>using function pointer for better code readability<commit_after><|endoftext|>
<commit_before>#include <babylon/sprites/sprite_renderer.h> #include <babylon/buffers/buffer.h> #include <babylon/buffers/vertex_buffer.h> #include <babylon/engines/constants.h> #include <babylon/engines/engine.h> #include <babylon/engines/scene.h> #include <babylon/engines/thin_engine.h> #include <babylon/materials/draw_wrapper.h> #include <babylon/materials/effect.h> #include <babylon/materials/ieffect_creation_options.h> #include <babylon/materials/textures/thin_texture.h> #include <babylon/sprites/thin_sprite.h> #include <babylon/states/depth_culling_state.h> namespace BABYLON { SpriteRenderer::SpriteRenderer(ThinEngine* engine, size_t capacity, float epsilon, Scene* scene) : texture{nullptr} , cellWidth{0} , cellHeight{0} , blendMode{Constants::ALPHA_COMBINE} , autoResetAlpha{true} , disableDepthWrite{false} , fogEnabled{true} , capacity{this, &SpriteRenderer::get_capacity} , _engine{nullptr} , _useVAO{false} , _useInstancing{false} , _scene{nullptr} , _buffer{nullptr} , _spriteBuffer{nullptr} , _indexBuffer{nullptr} , _drawWrapperBase{nullptr} , _drawWrapperFog{nullptr} , _vertexArrayObject{nullptr} { _capacity = capacity; _epsilon = epsilon; _engine = engine; _useInstancing = engine->getCaps().instancedArrays; _useVAO = engine->getCaps().vertexArrayObject && !engine->disableVertexArrayObjects; _scene = scene; _drawWrapperBase = std::make_shared<DrawWrapper>(engine); _drawWrapperFog = std::make_shared<DrawWrapper>(engine); if (!_useInstancing) { _buildIndexBuffer(); } // VBO // 18 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, // cellLeft, cellTop, cellWidth, cellHeight, color r, color g, color b, color a) // 16 when using instances _vertexBufferSize = _useInstancing ? 16 : 18; _vertexData = Float32Array(capacity * _vertexBufferSize * (_useInstancing ? 1 : 4), 0.f); _buffer = std::make_unique<Buffer>(engine, _vertexData, true, _vertexBufferSize); auto positions = _buffer->createVertexBuffer(VertexBuffer::PositionKind, 0, 4, _vertexBufferSize, _useInstancing); auto options = _buffer->createVertexBuffer("options", 4, 2, _vertexBufferSize, _useInstancing); auto offset = 6ull; std::unique_ptr<VertexBuffer> offsets = nullptr; if (_useInstancing) { const Float32Array spriteData{0.f, 0.f, 1.f, 0.f, 0.f, 1.f, 1.f, 1.f}; _spriteBuffer = std::make_unique<Buffer>(engine, spriteData, false, 2); offsets = _spriteBuffer->createVertexBuffer("offsets", 0, 2); } else { offsets = _buffer->createVertexBuffer("offsets", offset, 2, _vertexBufferSize, _useInstancing); offset += 2; } auto inverts = _buffer->createVertexBuffer("inverts", offset, 2, _vertexBufferSize, _useInstancing); auto cellInfo = _buffer->createVertexBuffer("cellInfo", offset + 2, 4, _vertexBufferSize, _useInstancing); auto colors = _buffer->createVertexBuffer(VertexBuffer::ColorKind, offset + 6, 4, _vertexBufferSize, _useInstancing); _vertexBuffers[VertexBuffer::PositionKind] = std::move(positions); _vertexBuffers[VertexBuffer::OptionsKind] = std::move(options); _vertexBuffers[VertexBuffer::OffsetsKind] = std::move(offsets); _vertexBuffers[VertexBuffer::InvertsKind] = std::move(inverts); _vertexBuffers[VertexBuffer::CellInfoKind] = std::move(cellInfo); _vertexBuffers[VertexBuffer::ColorKind] = std::move(colors); // Effects { IEffectCreationOptions spriteOptions; spriteOptions.attributes = {VertexBuffer::PositionKind, "options", "offsets", "inverts", "cellInfo", VertexBuffer::ColorKind}; spriteOptions.uniformsNames = {"view", "projection", "textureInfos", "alphaTest"}; spriteOptions.samplers = {"diffuseSampler"}; _drawWrapperBase->effect = _engine->createEffect("sprites", spriteOptions, _scene->getEngine()); } if (_scene) { IEffectCreationOptions spriteOptions; spriteOptions.attributes = {VertexBuffer::PositionKind, "options", "offsets", "inverts", "cellInfo", VertexBuffer::ColorKind}; spriteOptions.uniformsNames = {"view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"}; spriteOptions.samplers = {"diffuseSampler"}; spriteOptions.defines = "#define FOG"; _drawWrapperFog->effect = _scene->getEngine()->createEffect("sprites", spriteOptions, _scene->getEngine()); } } SpriteRenderer::~SpriteRenderer() = default; size_t SpriteRenderer::get_capacity() const { return _capacity; } void SpriteRenderer::render( const std::vector<ThinSpritePtr>& sprites, float deltaTime, const Matrix& viewMatrix, const Matrix& projectionMatrix, const std::function<void(ThinSprite* sprite, const ISize& baseSize)>& customSpriteUpdate) { if (!texture || !texture->isReady() || sprites.empty()) { return; } auto drawWrapper = _drawWrapperBase; auto shouldRenderFog = false; if (fogEnabled && _scene && _scene->fogEnabled() && _scene->fogMode() != 0) { drawWrapper = _drawWrapperFog; shouldRenderFog = true; } const auto& effect = drawWrapper->effect; // Check if (!effect || !effect->isReady()) { return; } auto engine = _scene->getEngine(); const auto useRightHandedSystem = !!(_scene && _scene->useRightHandedSystem()); const auto baseSize = texture->getBaseSize(); // Sprites auto max = std::min(_capacity, sprites.size()); auto offset = 0u; auto noSprite = true; for (size_t index = 0; index < max; index++) { const auto& sprite = sprites[index]; if (!sprite || !sprite->isVisible) { continue; } noSprite = false; sprite->_animate(deltaTime); _appendSpriteVertex(offset++, sprite, 0, 0, baseSize, useRightHandedSystem, customSpriteUpdate); if (!_useInstancing) { _appendSpriteVertex(offset++, sprite, 1, 0, baseSize, useRightHandedSystem, customSpriteUpdate); _appendSpriteVertex(offset++, sprite, 1, 1, baseSize, useRightHandedSystem, customSpriteUpdate); _appendSpriteVertex(offset++, sprite, 0, 1, baseSize, useRightHandedSystem, customSpriteUpdate); } } if (noSprite) { return; } _buffer->update(_vertexData); const auto culling = engine->depthCullingState()->cull().value_or(true); const auto zOffset = engine->depthCullingState()->zOffset(); // Handle Right Handed if (useRightHandedSystem && _scene) { _scene->getEngine()->setState(culling, zOffset, false, false); } // Render engine->enableEffect(drawWrapper); effect->setTexture("diffuseSampler", texture); effect->setMatrix("view", viewMatrix); effect->setMatrix("projection", projectionMatrix); // Scene Info if (shouldRenderFog && _scene) { const auto scene = _scene; // Fog effect->setFloat4("vFogInfos", static_cast<float>(scene->fogMode()), scene->fogStart, scene->fogEnd, scene->fogDensity); effect->setColor3("vFogColor", scene->fogColor); } if (_useVAO) { if (!_vertexArrayObject) { _vertexArrayObject = engine->recordVertexArrayObject(_vertexBuffers, _indexBuffer, effect); } engine->bindVertexArrayObject(_vertexArrayObject, _indexBuffer); } else { // VBOs engine->bindBuffers(_vertexBuffers, _indexBuffer, effect); } // Draw order engine->depthCullingState()->depthFunc = Constants::LEQUAL; if (!disableDepthWrite) { effect->setBool("alphaTest", true); engine->setColorWrite(false); if (_useInstancing) { engine->drawArraysType(Constants::MATERIAL_TriangleStripDrawMode, 0, 4, offset); } else { engine->drawElementsType(Constants::MATERIAL_TriangleFillMode, 0, (offset / 4) * 6); } engine->setColorWrite(true); effect->setBool("alphaTest", false); } engine->setAlphaMode(blendMode); if (_useInstancing) { engine->drawArraysType(Constants::MATERIAL_TriangleStripDrawMode, 0, 4, offset); } else { engine->drawElementsType(Constants::MATERIAL_TriangleFillMode, 0, (offset / 4) * 6); } if (autoResetAlpha) { engine->setAlphaMode(Constants::ALPHA_DISABLE); } // Restore Right Handed if (useRightHandedSystem && _scene) { _scene->getEngine()->setState(culling, zOffset, false, true); } engine->unbindInstanceAttributes(); } void SpriteRenderer::_appendSpriteVertex( size_t index, const ThinSpritePtr& sprite, int offsetX, int offsetY, const ISize& baseSize, bool useRightHandedSystem, const std::function<void(ThinSprite* sprite, const ISize& baseSize)>& customSpriteUpdate) { size_t arrayOffset = index * _vertexBufferSize; auto offsetXVal = static_cast<float>(offsetX); auto offsetYVal = static_cast<float>(offsetY); if (offsetX == 0) { offsetXVal = _epsilon; } else if (offsetX == 1) { offsetXVal = 1.f - _epsilon; } if (offsetY == 0) { offsetYVal = _epsilon; } else if (offsetY == 1) { offsetYVal = 1.f - _epsilon; } if (customSpriteUpdate) { customSpriteUpdate(sprite.get(), baseSize); } else { if (!sprite->cellIndex) { sprite->cellIndex = 0; } const auto rowSize = baseSize.width / cellWidth; const auto offset = (sprite->cellIndex / rowSize) >> 0; sprite->_xOffset = (sprite->cellIndex - offset * rowSize) * cellWidth / baseSize.width; sprite->_yOffset = offset * cellHeight / baseSize.height; sprite->_xSize = cellWidth; sprite->_ySize = cellHeight; } // Positions _vertexData[arrayOffset + 0] = sprite->position.x; _vertexData[arrayOffset + 1] = sprite->position.y; _vertexData[arrayOffset + 2] = sprite->position.z; _vertexData[arrayOffset + 3] = sprite->angle; // Options _vertexData[arrayOffset + 4] = static_cast<float>(sprite->width); _vertexData[arrayOffset + 5] = static_cast<float>(sprite->height); if (!_useInstancing) { _vertexData[arrayOffset + 6] = offsetXVal; _vertexData[arrayOffset + 7] = offsetYVal; } else { arrayOffset -= 2; } // Inverts according to Right Handed if (useRightHandedSystem) { _vertexData[arrayOffset + 8] = sprite->invertU ? 0.f : 1.f; } else { _vertexData[arrayOffset + 8] = sprite->invertU ? 1.f : 0.f; } _vertexData[arrayOffset + 9] = sprite->invertV ? 1.f : 0.f; _vertexData[arrayOffset + 10] = static_cast<float>(sprite->_xOffset); _vertexData[arrayOffset + 11] = static_cast<float>(sprite->_yOffset); _vertexData[arrayOffset + 12] = static_cast<float>(sprite->_xSize) / baseSize.width; _vertexData[arrayOffset + 13] = static_cast<float>(sprite->_ySize) / baseSize.height; // Color _vertexData[arrayOffset + 14] = sprite->color.r; _vertexData[arrayOffset + 15] = sprite->color.g; _vertexData[arrayOffset + 16] = sprite->color.b; _vertexData[arrayOffset + 17] = sprite->color.a; } void SpriteRenderer::_buildIndexBuffer() { IndicesArray indices; auto index = 0; for (unsigned int count = 0; count < capacity; ++count) { indices.emplace_back(index + 0); indices.emplace_back(index + 1); indices.emplace_back(index + 2); indices.emplace_back(index + 0); indices.emplace_back(index + 2); indices.emplace_back(index + 3); index += 4; } _indexBuffer = _engine->createIndexBuffer(indices); } void SpriteRenderer::rebuild() { if (_indexBuffer) { _buildIndexBuffer(); } if (_useVAO) { _vertexArrayObject = nullptr; } _buffer->_rebuild(); for (const auto& [name, vertexBuffer] : _vertexBuffers) { vertexBuffer->_rebuild(); } if (_spriteBuffer) { _spriteBuffer->_rebuild(); } } void SpriteRenderer::dispose() { if (_buffer) { _buffer->dispose(); _buffer = nullptr; } if (_spriteBuffer) { _spriteBuffer->dispose(); _spriteBuffer = nullptr; } if (_indexBuffer) { _engine->_releaseBuffer(_indexBuffer); _indexBuffer = nullptr; } if (_vertexArrayObject) { _engine->releaseVertexArrayObject(_vertexArrayObject); _vertexArrayObject = nullptr; } if (texture) { texture->dispose(); texture = nullptr; } } } // end of namespace BABYLON <commit_msg>Setting depthFunc based on reverse depth buffer flag<commit_after>#include <babylon/sprites/sprite_renderer.h> #include <babylon/buffers/buffer.h> #include <babylon/buffers/vertex_buffer.h> #include <babylon/engines/constants.h> #include <babylon/engines/engine.h> #include <babylon/engines/scene.h> #include <babylon/engines/thin_engine.h> #include <babylon/materials/draw_wrapper.h> #include <babylon/materials/effect.h> #include <babylon/materials/ieffect_creation_options.h> #include <babylon/materials/textures/thin_texture.h> #include <babylon/sprites/thin_sprite.h> #include <babylon/states/depth_culling_state.h> namespace BABYLON { SpriteRenderer::SpriteRenderer(ThinEngine* engine, size_t capacity, float epsilon, Scene* scene) : texture{nullptr} , cellWidth{0} , cellHeight{0} , blendMode{Constants::ALPHA_COMBINE} , autoResetAlpha{true} , disableDepthWrite{false} , fogEnabled{true} , capacity{this, &SpriteRenderer::get_capacity} , _engine{nullptr} , _useVAO{false} , _useInstancing{false} , _scene{nullptr} , _buffer{nullptr} , _spriteBuffer{nullptr} , _indexBuffer{nullptr} , _drawWrapperBase{nullptr} , _drawWrapperFog{nullptr} , _vertexArrayObject{nullptr} { _capacity = capacity; _epsilon = epsilon; _engine = engine; _useInstancing = engine->getCaps().instancedArrays; _useVAO = engine->getCaps().vertexArrayObject && !engine->disableVertexArrayObjects; _scene = scene; _drawWrapperBase = std::make_shared<DrawWrapper>(engine); _drawWrapperFog = std::make_shared<DrawWrapper>(engine); if (!_useInstancing) { _buildIndexBuffer(); } // VBO // 18 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, // cellLeft, cellTop, cellWidth, cellHeight, color r, color g, color b, color a) // 16 when using instances _vertexBufferSize = _useInstancing ? 16 : 18; _vertexData = Float32Array(capacity * _vertexBufferSize * (_useInstancing ? 1 : 4), 0.f); _buffer = std::make_unique<Buffer>(engine, _vertexData, true, _vertexBufferSize); auto positions = _buffer->createVertexBuffer(VertexBuffer::PositionKind, 0, 4, _vertexBufferSize, _useInstancing); auto options = _buffer->createVertexBuffer("options", 4, 2, _vertexBufferSize, _useInstancing); auto offset = 6ull; std::unique_ptr<VertexBuffer> offsets = nullptr; if (_useInstancing) { const Float32Array spriteData{0.f, 0.f, 1.f, 0.f, 0.f, 1.f, 1.f, 1.f}; _spriteBuffer = std::make_unique<Buffer>(engine, spriteData, false, 2); offsets = _spriteBuffer->createVertexBuffer("offsets", 0, 2); } else { offsets = _buffer->createVertexBuffer("offsets", offset, 2, _vertexBufferSize, _useInstancing); offset += 2; } auto inverts = _buffer->createVertexBuffer("inverts", offset, 2, _vertexBufferSize, _useInstancing); auto cellInfo = _buffer->createVertexBuffer("cellInfo", offset + 2, 4, _vertexBufferSize, _useInstancing); auto colors = _buffer->createVertexBuffer(VertexBuffer::ColorKind, offset + 6, 4, _vertexBufferSize, _useInstancing); _vertexBuffers[VertexBuffer::PositionKind] = std::move(positions); _vertexBuffers[VertexBuffer::OptionsKind] = std::move(options); _vertexBuffers[VertexBuffer::OffsetsKind] = std::move(offsets); _vertexBuffers[VertexBuffer::InvertsKind] = std::move(inverts); _vertexBuffers[VertexBuffer::CellInfoKind] = std::move(cellInfo); _vertexBuffers[VertexBuffer::ColorKind] = std::move(colors); // Effects { IEffectCreationOptions spriteOptions; spriteOptions.attributes = {VertexBuffer::PositionKind, "options", "offsets", "inverts", "cellInfo", VertexBuffer::ColorKind}; spriteOptions.uniformsNames = {"view", "projection", "textureInfos", "alphaTest"}; spriteOptions.samplers = {"diffuseSampler"}; _drawWrapperBase->effect = _engine->createEffect("sprites", spriteOptions, _scene->getEngine()); } if (_scene) { IEffectCreationOptions spriteOptions; spriteOptions.attributes = {VertexBuffer::PositionKind, "options", "offsets", "inverts", "cellInfo", VertexBuffer::ColorKind}; spriteOptions.uniformsNames = {"view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"}; spriteOptions.samplers = {"diffuseSampler"}; spriteOptions.defines = "#define FOG"; _drawWrapperFog->effect = _scene->getEngine()->createEffect("sprites", spriteOptions, _scene->getEngine()); } } SpriteRenderer::~SpriteRenderer() = default; size_t SpriteRenderer::get_capacity() const { return _capacity; } void SpriteRenderer::render( const std::vector<ThinSpritePtr>& sprites, float deltaTime, const Matrix& viewMatrix, const Matrix& projectionMatrix, const std::function<void(ThinSprite* sprite, const ISize& baseSize)>& customSpriteUpdate) { if (!texture || !texture->isReady() || sprites.empty()) { return; } auto drawWrapper = _drawWrapperBase; auto shouldRenderFog = false; if (fogEnabled && _scene && _scene->fogEnabled() && _scene->fogMode() != 0) { drawWrapper = _drawWrapperFog; shouldRenderFog = true; } const auto& effect = drawWrapper->effect; // Check if (!effect || !effect->isReady()) { return; } auto engine = _scene->getEngine(); const auto useRightHandedSystem = !!(_scene && _scene->useRightHandedSystem()); const auto baseSize = texture->getBaseSize(); // Sprites auto max = std::min(_capacity, sprites.size()); auto offset = 0u; auto noSprite = true; for (size_t index = 0; index < max; index++) { const auto& sprite = sprites[index]; if (!sprite || !sprite->isVisible) { continue; } noSprite = false; sprite->_animate(deltaTime); _appendSpriteVertex(offset++, sprite, 0, 0, baseSize, useRightHandedSystem, customSpriteUpdate); if (!_useInstancing) { _appendSpriteVertex(offset++, sprite, 1, 0, baseSize, useRightHandedSystem, customSpriteUpdate); _appendSpriteVertex(offset++, sprite, 1, 1, baseSize, useRightHandedSystem, customSpriteUpdate); _appendSpriteVertex(offset++, sprite, 0, 1, baseSize, useRightHandedSystem, customSpriteUpdate); } } if (noSprite) { return; } _buffer->update(_vertexData); const auto culling = engine->depthCullingState()->cull().value_or(true); const auto zOffset = engine->depthCullingState()->zOffset(); engine->setState(culling, zOffset, false, false); // Render engine->enableEffect(drawWrapper); effect->setTexture("diffuseSampler", texture); effect->setMatrix("view", viewMatrix); effect->setMatrix("projection", projectionMatrix); // Scene Info if (shouldRenderFog && _scene) { const auto scene = _scene; // Fog effect->setFloat4("vFogInfos", static_cast<float>(scene->fogMode()), scene->fogStart, scene->fogEnd, scene->fogDensity); effect->setColor3("vFogColor", scene->fogColor); } if (_useVAO) { if (!_vertexArrayObject) { _vertexArrayObject = engine->recordVertexArrayObject(_vertexBuffers, _indexBuffer, effect); } engine->bindVertexArrayObject(_vertexArrayObject, _indexBuffer); } else { // VBOs engine->bindBuffers(_vertexBuffers, _indexBuffer, effect); } // Draw order engine->depthCullingState()->depthFunc = engine->useReverseDepthBuffer ? Constants::GEQUAL : Constants::LEQUAL; if (!disableDepthWrite) { effect->setBool("alphaTest", true); engine->setColorWrite(false); if (_useInstancing) { engine->drawArraysType(Constants::MATERIAL_TriangleStripDrawMode, 0, 4, offset); } else { engine->drawElementsType(Constants::MATERIAL_TriangleFillMode, 0, (offset / 4) * 6); } engine->setColorWrite(true); effect->setBool("alphaTest", false); } engine->setAlphaMode(blendMode); if (_useInstancing) { engine->drawArraysType(Constants::MATERIAL_TriangleStripDrawMode, 0, 4, offset); } else { engine->drawElementsType(Constants::MATERIAL_TriangleFillMode, 0, (offset / 4) * 6); } if (autoResetAlpha) { engine->setAlphaMode(Constants::ALPHA_DISABLE); } // Restore Right Handed if (useRightHandedSystem && _scene) { _scene->getEngine()->setState(culling, zOffset, false, true); } engine->unbindInstanceAttributes(); } void SpriteRenderer::_appendSpriteVertex( size_t index, const ThinSpritePtr& sprite, int offsetX, int offsetY, const ISize& baseSize, bool useRightHandedSystem, const std::function<void(ThinSprite* sprite, const ISize& baseSize)>& customSpriteUpdate) { size_t arrayOffset = index * _vertexBufferSize; auto offsetXVal = static_cast<float>(offsetX); auto offsetYVal = static_cast<float>(offsetY); if (offsetX == 0) { offsetXVal = _epsilon; } else if (offsetX == 1) { offsetXVal = 1.f - _epsilon; } if (offsetY == 0) { offsetYVal = _epsilon; } else if (offsetY == 1) { offsetYVal = 1.f - _epsilon; } if (customSpriteUpdate) { customSpriteUpdate(sprite.get(), baseSize); } else { if (!sprite->cellIndex) { sprite->cellIndex = 0; } const auto rowSize = baseSize.width / cellWidth; const auto offset = (sprite->cellIndex / rowSize) >> 0; sprite->_xOffset = (sprite->cellIndex - offset * rowSize) * cellWidth / baseSize.width; sprite->_yOffset = offset * cellHeight / baseSize.height; sprite->_xSize = cellWidth; sprite->_ySize = cellHeight; } // Positions _vertexData[arrayOffset + 0] = sprite->position.x; _vertexData[arrayOffset + 1] = sprite->position.y; _vertexData[arrayOffset + 2] = sprite->position.z; _vertexData[arrayOffset + 3] = sprite->angle; // Options _vertexData[arrayOffset + 4] = static_cast<float>(sprite->width); _vertexData[arrayOffset + 5] = static_cast<float>(sprite->height); if (!_useInstancing) { _vertexData[arrayOffset + 6] = offsetXVal; _vertexData[arrayOffset + 7] = offsetYVal; } else { arrayOffset -= 2; } // Inverts according to Right Handed if (useRightHandedSystem) { _vertexData[arrayOffset + 8] = sprite->invertU ? 0.f : 1.f; } else { _vertexData[arrayOffset + 8] = sprite->invertU ? 1.f : 0.f; } _vertexData[arrayOffset + 9] = sprite->invertV ? 1.f : 0.f; _vertexData[arrayOffset + 10] = static_cast<float>(sprite->_xOffset); _vertexData[arrayOffset + 11] = static_cast<float>(sprite->_yOffset); _vertexData[arrayOffset + 12] = static_cast<float>(sprite->_xSize) / baseSize.width; _vertexData[arrayOffset + 13] = static_cast<float>(sprite->_ySize) / baseSize.height; // Color _vertexData[arrayOffset + 14] = sprite->color.r; _vertexData[arrayOffset + 15] = sprite->color.g; _vertexData[arrayOffset + 16] = sprite->color.b; _vertexData[arrayOffset + 17] = sprite->color.a; } void SpriteRenderer::_buildIndexBuffer() { IndicesArray indices; auto index = 0; for (unsigned int count = 0; count < capacity; ++count) { indices.emplace_back(index + 0); indices.emplace_back(index + 1); indices.emplace_back(index + 2); indices.emplace_back(index + 0); indices.emplace_back(index + 2); indices.emplace_back(index + 3); index += 4; } _indexBuffer = _engine->createIndexBuffer(indices); } void SpriteRenderer::rebuild() { if (_indexBuffer) { _buildIndexBuffer(); } if (_useVAO) { _vertexArrayObject = nullptr; } _buffer->_rebuild(); for (const auto& [name, vertexBuffer] : _vertexBuffers) { vertexBuffer->_rebuild(); } if (_spriteBuffer) { _spriteBuffer->_rebuild(); } } void SpriteRenderer::dispose() { if (_buffer) { _buffer->dispose(); _buffer = nullptr; } if (_spriteBuffer) { _spriteBuffer->dispose(); _spriteBuffer = nullptr; } if (_indexBuffer) { _engine->_releaseBuffer(_indexBuffer); _indexBuffer = nullptr; } if (_vertexArrayObject) { _engine->releaseVertexArrayObject(_vertexArrayObject); _vertexArrayObject = nullptr; } if (texture) { texture->dispose(); texture = nullptr; } } } // end of namespace BABYLON <|endoftext|>
<commit_before>/*! @file @author Albert Semenov @date 11/2009 @module */ #include "ResourceW32Pointer.h" #include <windows.h> namespace input { ResourceW32Pointer::ResourceW32Pointer() : mHandle(0) { } void ResourceW32Pointer::deserialization(MyGUI::xml::ElementPtr _node, MyGUI::Version _version) { Base::deserialization(_node, _version); MyGUI::xml::ElementEnumerator info = _node->getElementEnumerator(); while (info.next()) { if (info->getName() == "Property") { const std::string& key = info->findAttribute("key"); if (key == "SourceFile") { std::string path = MyGUI::DataManager::getInstance().getDataPath(info->getContent()); mHandle = (size_t)LoadCursorFromFileA(path.c_str()); } else if (key == "SourceSystem") { std::string value = info->getContent(); if (value == "IDC_ARROW") mHandle = (size_t)::LoadCursor(NULL, MAKEINTRESOURCE(IDC_ARROW)); else if (value == "IDC_IBEAM") mHandle = (size_t)::LoadCursor(NULL, MAKEINTRESOURCE(IDC_IBEAM)); else if (value == "IDC_WAIT") mHandle = (size_t)::LoadCursor(NULL, MAKEINTRESOURCE(IDC_WAIT)); else if (value == "IDC_CROSS") mHandle = (size_t)::LoadCursor(NULL, MAKEINTRESOURCE(IDC_CROSS)); else if (value == "IDC_UPARROW") mHandle = (size_t)::LoadCursor(NULL, MAKEINTRESOURCE(IDC_UPARROW)); else if (value == "IDC_SIZE") mHandle = (size_t)::LoadCursor(NULL, MAKEINTRESOURCE(IDC_SIZE)); else if (value == "IDC_ICON") mHandle = (size_t)::LoadCursor(NULL, MAKEINTRESOURCE(IDC_ICON)); else if (value == "IDC_SIZENWSE") mHandle = (size_t)::LoadCursor(NULL, MAKEINTRESOURCE(IDC_SIZENWSE)); else if (value == "IDC_SIZENESW") mHandle = (size_t)::LoadCursor(NULL, MAKEINTRESOURCE(IDC_SIZENESW)); else if (value == "IDC_SIZEWE") mHandle = (size_t)::LoadCursor(NULL, MAKEINTRESOURCE(IDC_SIZEWE)); else if (value == "IDC_SIZENS") mHandle = (size_t)::LoadCursor(NULL, MAKEINTRESOURCE(IDC_SIZENS)); else if (value == "IDC_SIZEALL") mHandle = (size_t)::LoadCursor(NULL, MAKEINTRESOURCE(IDC_SIZEALL)); else if (value == "IDC_NO") mHandle = (size_t)::LoadCursor(NULL, MAKEINTRESOURCE(IDC_NO)); else if (value == "IDC_HAND") mHandle = (size_t)::LoadCursor(NULL, MAKEINTRESOURCE(IDC_HAND)); else if (value == "IDC_APPSTARTING") mHandle = (size_t)::LoadCursor(NULL, MAKEINTRESOURCE(IDC_APPSTARTING)); else if (value == "IDC_HELP") mHandle = (size_t)::LoadCursor(NULL, MAKEINTRESOURCE(IDC_HELP)); } } } } } <commit_msg>fix LoadCursor calls<commit_after>/*! @file @author Albert Semenov @date 11/2009 @module */ #include "ResourceW32Pointer.h" #include <windows.h> namespace input { ResourceW32Pointer::ResourceW32Pointer() : mHandle(0) { } void ResourceW32Pointer::deserialization(MyGUI::xml::ElementPtr _node, MyGUI::Version _version) { Base::deserialization(_node, _version); MyGUI::xml::ElementEnumerator info = _node->getElementEnumerator(); while (info.next()) { if (info->getName() == "Property") { const std::string& key = info->findAttribute("key"); if (key == "SourceFile") { std::string path = MyGUI::DataManager::getInstance().getDataPath(info->getContent()); mHandle = (size_t)LoadCursorFromFileA(path.c_str()); } else if (key == "SourceSystem") { std::string value = info->getContent(); if (value == "IDC_ARROW") mHandle = (size_t)::LoadCursor(NULL, IDC_ARROW); else if (value == "IDC_IBEAM") mHandle = (size_t)::LoadCursor(NULL, IDC_IBEAM); else if (value == "IDC_WAIT") mHandle = (size_t)::LoadCursor(NULL, IDC_WAIT); else if (value == "IDC_CROSS") mHandle = (size_t)::LoadCursor(NULL, IDC_CROSS); else if (value == "IDC_UPARROW") mHandle = (size_t)::LoadCursor(NULL, IDC_UPARROW); else if (value == "IDC_SIZE") mHandle = (size_t)::LoadCursor(NULL, IDC_SIZE); else if (value == "IDC_ICON") mHandle = (size_t)::LoadCursor(NULL, IDC_ICON); else if (value == "IDC_SIZENWSE") mHandle = (size_t)::LoadCursor(NULL, IDC_SIZENWSE); else if (value == "IDC_SIZENESW") mHandle = (size_t)::LoadCursor(NULL, IDC_SIZENESW); else if (value == "IDC_SIZEWE") mHandle = (size_t)::LoadCursor(NULL, IDC_SIZEWE); else if (value == "IDC_SIZENS") mHandle = (size_t)::LoadCursor(NULL, IDC_SIZENS); else if (value == "IDC_SIZEALL") mHandle = (size_t)::LoadCursor(NULL, IDC_SIZEALL); else if (value == "IDC_NO") mHandle = (size_t)::LoadCursor(NULL, IDC_NO); else if (value == "IDC_HAND") mHandle = (size_t)::LoadCursor(NULL, IDC_HAND); else if (value == "IDC_APPSTARTING") mHandle = (size_t)::LoadCursor(NULL, IDC_APPSTARTING); else if (value == "IDC_HELP") mHandle = (size_t)::LoadCursor(NULL, IDC_HELP); } } } } } <|endoftext|>
<commit_before>/** * VariableRegistry.cpp * * History: * David Cox on Tue Dec 10 2002 - Created. * Paul Jankunas on 4/29/05 - Added the experiment package codec to package. * Also added the constant code to codec package. * Paul Jankunas on 5/17/05 - Removed codec code, it now is stored in a * scarab package. * Paul Jankunas on 06/15/05 - Fixed ScarabDatum constructor, added function * addVariable that takes a Variable arg, fixed a bug in getVariable * that was returning empty variables for 0 index. * * Copyright (c) 2005 MIT. All rights reserved. */ #include "VariableRegistry.h" #include "Utilities.h" #include "Experiment.h" #include "EventBuffer.h" #include "EventConstants.h" #include "GenericVariable.h" using namespace mw; VariableRegistry::VariableRegistry(shared_ptr<EventBuffer> _buffer) { event_buffer = _buffer; current_unique_code = N_RESERVED_CODEC_CODES; } void VariableRegistry::reset(){ master_variable_list.clear(); // for faster lookups by tag name master_variable_dictionary = map< string, shared_ptr<Variable> >(); // just the local variables local_variable_list.clear(); // just the global variables global_variable_list.clear(); // just the selection variables selection_variable_list.clear(); //addPlaceholders(); } VariableRegistry::~VariableRegistry() { } void VariableRegistry::updateFromCodecDatum(const Datum &codec) { mprintf(M_SYSTEM_MESSAGE_DOMAIN, "Received new codec, updating variable registry."); if(!codec.isDictionary()) { merror(M_SYSTEM_MESSAGE_DOMAIN, "Invalid codec received. Registry is unchanged."); return; } boost::mutex::scoped_lock s_lock(lock); master_variable_list.clear(); // add the placeholders //addPlaceholders(); ////////////////////////////////////////////////////////////////// // now add what's in the codec ScarabDatum *datum = codec.getScarabDatum(); ScarabDatum ** keys = scarab_dict_keys(datum); int size = datum->data.dict->tablesize; int maxCodecCode = -1; // find the maximum codec value for(int i = 0; i < size; ++i) { if(keys[i]) { long long code = keys[i]->data.integer; maxCodecCode = (maxCodecCode < code) ? code : maxCodecCode; } } // add each variable in order to the registry for(int i = N_RESERVED_CODEC_CODES; i<=maxCodecCode; ++i) { ScarabDatum *key = scarab_new_integer(i); ScarabDatum *serializedVariable = scarab_dict_get(datum, key); scarab_free_datum(key); if(serializedVariable) { if(serializedVariable->type != SCARAB_DICT) { // these must be placeholder datums in the package // that we should ignore. mwarning(M_SYSTEM_MESSAGE_DOMAIN, "Bad variable received from network stream"); shared_ptr<EmptyVariable> empty_var(new EmptyVariable); master_variable_list.push_back(empty_var); continue; } VariableProperties *props = new VariableProperties(serializedVariable); if(props == NULL){ mwarning(M_SYSTEM_MESSAGE_DOMAIN, "Bad variable received from network stream"); shared_ptr<EmptyVariable> empty_var(new EmptyVariable); master_variable_list.push_back(empty_var); continue; } shared_ptr<Variable> newvar(new GlobalVariable(props)); newvar->setCodecCode(i); //necessary? .. Yup master_variable_list.push_back(newvar); std::string tag = newvar->getVariableName(); if(!tag.empty()){ master_variable_dictionary[tag] = newvar; } } } } void VariableRegistry::announceLocalVariables(){ boost::mutex::scoped_lock s_lock(lock); vector< shared_ptr<Variable> >::iterator i; for(i = local_variable_list.begin(); i != local_variable_list.end(); i++){ (*i)->announce(); } } void VariableRegistry::announceGlobalVariables(){ boost::mutex::scoped_lock s_lock(lock); vector< shared_ptr<Variable> >::iterator i; for(i = global_variable_list.begin(); i != global_variable_list.end(); i++){ (*i)->announce(); } } void VariableRegistry::announceSelectionVariables(){ boost::mutex::scoped_lock s_lock(lock); vector< shared_ptr<Variable> >::iterator i; for(i = selection_variable_list.begin(); i != selection_variable_list.end(); i++){ (*i)->announce(); } } void VariableRegistry::announceAll() { boost::mutex::scoped_lock s_lock(lock); vector< shared_ptr<Variable> >::iterator i; for(i = master_variable_list.begin(); i != master_variable_list.end(); i++){ (*i)->announce(); } } // There is potential room for speed up with a hash_map, though this would // require const char * machinations, as hash_map cannot have string keys shared_ptr<Variable> VariableRegistry::getVariable(const std::string& tagname) const{ boost::mutex::scoped_lock s_lock((boost::mutex&)lock); map< string, shared_ptr<Variable> >::const_iterator it; it = master_variable_dictionary.find(tagname); if(it == master_variable_dictionary.end()){ return shared_ptr<Variable>(); } else { return it->second; } // This one line is how it would have been written if the stx parser guy // didn't have a const-correctness stick up his butt //return master_variable_dictionary[tagname]; } shared_ptr<Variable> VariableRegistry::getVariable(int codec_code) { shared_ptr<Variable> var; boost::mutex::scoped_lock s_lock((boost::mutex&)lock); // DDC: removed what was this for? //mExpandableList<Variable> list(master_variable_list); if(codec_code < 0 || codec_code > master_variable_list.size() + N_RESERVED_CODEC_CODES){ merror(M_SYSTEM_MESSAGE_DOMAIN, "Attempt to get an invalid variable (code: %d)", codec_code); var = shared_ptr<Variable>(); } else { // DDC: removed copying. What was that for? //var = list[codec_code]; var = master_variable_list[codec_code - N_RESERVED_CODEC_CODES]; } return var; } std::vector<std::string> VariableRegistry::getVariableTagNames() { boost::mutex::scoped_lock s_lock(lock); std::vector<std::string> tagnames; vector< shared_ptr<Variable> >::iterator i; for(i = master_variable_list.begin(); i != master_variable_list.end(); i++){ shared_ptr<Variable> var = (*i); if(var) { tagnames.push_back(var->getVariableName()); } } return tagnames; } bool VariableRegistry::hasVariable(const char *tagname) const { return (getVariable(tagname) != NULL); } bool VariableRegistry::hasVariable(std::string &tagname) const { return (getVariable(tagname) != NULL); } int VariableRegistry::getNVariables() { return master_variable_list.size(); } shared_ptr<ScopedVariable> VariableRegistry::addScopedVariable(weak_ptr<ScopedVariableEnvironment> env, VariableProperties *props) { // create a new entry and return one instance if(props == NULL) { // TODO warn throw SimpleException("Failed to add scoped variable to registry"); } int variable_context_index = -1; int codec_code = -1; VariableProperties *props_copy = new VariableProperties(*props); shared_ptr<ScopedVariable> new_variable(new ScopedVariable(props_copy)); //GlobalCurrentExperiment->addVariable(new_variable); master_variable_list.push_back(new_variable); codec_code = master_variable_list.size() + N_RESERVED_CODEC_CODES - 1; std::string tag = new_variable->getVariableName(); if(!tag.empty()){ master_variable_dictionary[tag] = new_variable; } local_variable_list.push_back(new_variable); variable_context_index = local_variable_list.size() - 1; new_variable->setContextIndex(variable_context_index); new_variable->setLogging(M_WHEN_CHANGED); new_variable->setCodecCode(codec_code); new_variable->setEventTarget(static_pointer_cast<EventReceiver>(event_buffer)); if(!env.expired()){ shared_ptr<ScopedVariableEnvironment> env_shared(env); env_shared->addVariable(new_variable); } return new_variable; } shared_ptr<GlobalVariable> VariableRegistry::addGlobalVariable(VariableProperties *props){ if(props == NULL){ // TODO: warn throw SimpleException("Failed to add global variable to registry"); } VariableProperties *copy = new VariableProperties(*props); shared_ptr<GlobalVariable> returnref(new GlobalVariable(copy)); master_variable_list.push_back(returnref); int codec_code = master_variable_list.size() + N_RESERVED_CODEC_CODES - 1; std::string tag = returnref->getVariableName(); if(!tag.empty()){ master_variable_dictionary[tag] = returnref; } global_variable_list.push_back(returnref); returnref->setCodecCode(codec_code); returnref->setEventTarget(static_pointer_cast<EventReceiver>(event_buffer)); return returnref; } shared_ptr<ConstantVariable> VariableRegistry::addConstantVariable(Datum value){ shared_ptr<ConstantVariable> returnref(new ConstantVariable(value)); returnref->setCodecCode(-1); returnref->setEventTarget(static_pointer_cast<EventReceiver>(event_buffer)); return returnref; } shared_ptr<Timer> VariableRegistry::createTimer(VariableProperties *props) { VariableProperties *props_copy; if(props != NULL){ props_copy = new VariableProperties(*props); } else { props_copy = NULL; } shared_ptr<Timer> new_timer(new Timer(props_copy)); // int codec_code = master_variable_list.addReference(new_timer); std::string tag = new_timer->getVariableName(); if(!tag.empty()){ master_variable_dictionary[tag] = new_timer; } new_timer->setCodecCode(-1); new_timer->setEventTarget(static_pointer_cast<EventReceiver>(event_buffer)); return new_timer; } //shared_ptr<EmptyVariable> VariableRegistry::addPlaceholderVariable(VariableProperties *props){ // // VariableProperties *props_copy; // // if(props != NULL){ // props_copy = new VariableProperties(*props); // } else { // props_copy = NULL; // } // // // shared_ptr<EmptyVariable> returnref(new EmptyVariable(props_copy)); // // master_variable_list.push_back(returnref); // int codec_code = master_variable_list.size(); // // returnref->setCodecCode(codec_code); // returnref->setEventTarget(static_pointer_cast<EventReceiver>(event_buffer)); // // return returnref; //} shared_ptr<SelectionVariable> VariableRegistry::addSelectionVariable(VariableProperties *props){ VariableProperties *props_copy; if(props != NULL){ props_copy = new VariableProperties(*props); } else { props_copy = NULL; } shared_ptr<SelectionVariable> returnref(new SelectionVariable(props_copy)); master_variable_list.push_back(returnref); int codec_code = master_variable_list.size(); std::string tag = returnref->getVariableName(); if(!tag.empty()){ master_variable_dictionary[tag] = returnref; } selection_variable_list.push_back(returnref); returnref->setCodecCode(codec_code); returnref->setEventTarget(static_pointer_cast<EventReceiver>(event_buffer)); return returnref; } shared_ptr<ScopedVariable> VariableRegistry::createScopedVariable(weak_ptr<ScopedVariableEnvironment> env, VariableProperties *props) { boost::mutex::scoped_lock s_lock(lock); shared_ptr<ScopedVariable> var = addScopedVariable(env, props); return var; } shared_ptr<GlobalVariable> VariableRegistry::createGlobalVariable(VariableProperties *props) { boost::mutex::scoped_lock s_lock(lock); shared_ptr<GlobalVariable> var = addGlobalVariable(props); return var; } shared_ptr<ConstantVariable> VariableRegistry::createConstantVariable(Datum value){ return addConstantVariable(value); } //shared_ptr<EmptyVariable> VariableRegistry::createPlaceholderVariable(VariableProperties *props){ // boost::mutex::scoped_lock s_lock(lock); // // shared_ptr<EmptyVariable> var = addPlaceholderVariable(props); // // return var; //} shared_ptr<SelectionVariable> VariableRegistry::createSelectionVariable(VariableProperties *props){ boost::mutex::scoped_lock s_lock(lock); shared_ptr<SelectionVariable> var = addSelectionVariable(props); return var; } Datum VariableRegistry::generateCodecDatum() { ScarabDatum *codec = NULL; shared_ptr<Variable> var; boost::mutex::scoped_lock s_lock(lock); int dictSize = master_variable_list.size(); codec = scarab_dict_new(dictSize, &scarab_dict_times2); for(int i = 0; i < dictSize; i++) { var = master_variable_list[i]; if(var == NULL) { continue; } int codec_code = var->getCodecCode(); if(codec_code == RESERVED_CODEC_CODE) { continue; } VariableProperties *props = var->getProperties(); if(props == NULL){ continue; } Datum serialized_var(props->operator Datum()); if(serialized_var.isUndefined()) { mdebug("local parameter null value at param (%d)", i); } ScarabDatum *codec_key = scarab_new_integer(codec_code); scarab_dict_put(codec, codec_key, serialized_var.getScarabDatum()); scarab_free_datum(codec_key); } Datum returnCodec(codec); scarab_free_datum(codec); return returnCodec; } /// Return the (constant) value of a variable. stx::AnyScalar VariableRegistry::lookupVariable(const std::string &varname) const{ shared_ptr<Variable> var = getVariable(varname); if(var == NULL){ // TODO: throw better throw SimpleException("Failed to find variable during expression evaluation", varname); } Datum value = *(var); stx::AnyScalar retval = value; return retval; } namespace mw { shared_ptr<VariableRegistry> global_variable_registry; static bool registry_initialized = false; } //void initializeVariableRegistry() { // global_variable_registry = shared_ptr<VariableRegistry>(new VariableRegistry(global_outgoing_event_buffer)); // registry_initialized = true; // //} <commit_msg>Added an additional two lines worth of band-aid for now; a fuller fix has been started in the codec_modernization branch<commit_after>/** * VariableRegistry.cpp * * History: * David Cox on Tue Dec 10 2002 - Created. * Paul Jankunas on 4/29/05 - Added the experiment package codec to package. * Also added the constant code to codec package. * Paul Jankunas on 5/17/05 - Removed codec code, it now is stored in a * scarab package. * Paul Jankunas on 06/15/05 - Fixed ScarabDatum constructor, added function * addVariable that takes a Variable arg, fixed a bug in getVariable * that was returning empty variables for 0 index. * * Copyright (c) 2005 MIT. All rights reserved. */ #include "VariableRegistry.h" #include "Utilities.h" #include "Experiment.h" #include "EventBuffer.h" #include "EventConstants.h" #include "GenericVariable.h" using namespace mw; VariableRegistry::VariableRegistry(shared_ptr<EventBuffer> _buffer) { event_buffer = _buffer; current_unique_code = N_RESERVED_CODEC_CODES; } void VariableRegistry::reset(){ master_variable_list.clear(); // for faster lookups by tag name master_variable_dictionary = map< string, shared_ptr<Variable> >(); // just the local variables local_variable_list.clear(); // just the global variables global_variable_list.clear(); // just the selection variables selection_variable_list.clear(); //addPlaceholders(); } VariableRegistry::~VariableRegistry() { } void VariableRegistry::updateFromCodecDatum(const Datum &codec) { mprintf(M_SYSTEM_MESSAGE_DOMAIN, "Received new codec, updating variable registry."); if(!codec.isDictionary()) { merror(M_SYSTEM_MESSAGE_DOMAIN, "Invalid codec received. Registry is unchanged."); return; } boost::mutex::scoped_lock s_lock(lock); master_variable_list.clear(); // add the placeholders //addPlaceholders(); ////////////////////////////////////////////////////////////////// // now add what's in the codec ScarabDatum *datum = codec.getScarabDatum(); ScarabDatum ** keys = scarab_dict_keys(datum); int size = datum->data.dict->tablesize; int maxCodecCode = -1; // find the maximum codec value for(int i = 0; i < size; ++i) { if(keys[i]) { long long code = keys[i]->data.integer; maxCodecCode = (maxCodecCode < code) ? code : maxCodecCode; } } // add each variable in order to the registry for(int i = N_RESERVED_CODEC_CODES; i<=maxCodecCode; ++i) { ScarabDatum *key = scarab_new_integer(i); ScarabDatum *serializedVariable = scarab_dict_get(datum, key); scarab_free_datum(key); if(!serializedVariable) { shared_ptr<EmptyVariable> empty_var(new EmptyVariable); master_variable_list.push_back(empty_var); continue; } else { if(serializedVariable->type != SCARAB_DICT) { // these must be placeholder datums in the package // that we should ignore. mwarning(M_SYSTEM_MESSAGE_DOMAIN, "Bad variable received from network stream"); shared_ptr<EmptyVariable> empty_var(new EmptyVariable); master_variable_list.push_back(empty_var); continue; } VariableProperties *props = new VariableProperties(serializedVariable); if(props == NULL){ mwarning(M_SYSTEM_MESSAGE_DOMAIN, "Bad variable received from network stream"); shared_ptr<EmptyVariable> empty_var(new EmptyVariable); master_variable_list.push_back(empty_var); continue; } shared_ptr<Variable> newvar(new GlobalVariable(props)); newvar->setCodecCode(i); //necessary? .. Yup master_variable_list.push_back(newvar); std::string tag = newvar->getVariableName(); if(!tag.empty()){ master_variable_dictionary[tag] = newvar; } } } } void VariableRegistry::announceLocalVariables(){ boost::mutex::scoped_lock s_lock(lock); vector< shared_ptr<Variable> >::iterator i; for(i = local_variable_list.begin(); i != local_variable_list.end(); i++){ (*i)->announce(); } } void VariableRegistry::announceGlobalVariables(){ boost::mutex::scoped_lock s_lock(lock); vector< shared_ptr<Variable> >::iterator i; for(i = global_variable_list.begin(); i != global_variable_list.end(); i++){ (*i)->announce(); } } void VariableRegistry::announceSelectionVariables(){ boost::mutex::scoped_lock s_lock(lock); vector< shared_ptr<Variable> >::iterator i; for(i = selection_variable_list.begin(); i != selection_variable_list.end(); i++){ (*i)->announce(); } } void VariableRegistry::announceAll() { boost::mutex::scoped_lock s_lock(lock); vector< shared_ptr<Variable> >::iterator i; for(i = master_variable_list.begin(); i != master_variable_list.end(); i++){ (*i)->announce(); } } // There is potential room for speed up with a hash_map, though this would // require const char * machinations, as hash_map cannot have string keys shared_ptr<Variable> VariableRegistry::getVariable(const std::string& tagname) const{ boost::mutex::scoped_lock s_lock((boost::mutex&)lock); map< string, shared_ptr<Variable> >::const_iterator it; it = master_variable_dictionary.find(tagname); if(it == master_variable_dictionary.end()){ return shared_ptr<Variable>(); } else { return it->second; } // This one line is how it would have been written if the stx parser guy // didn't have a const-correctness stick up his butt //return master_variable_dictionary[tagname]; } shared_ptr<Variable> VariableRegistry::getVariable(int codec_code) { shared_ptr<Variable> var; boost::mutex::scoped_lock s_lock((boost::mutex&)lock); // DDC: removed what was this for? //mExpandableList<Variable> list(master_variable_list); if(codec_code < 0 || codec_code > master_variable_list.size() + N_RESERVED_CODEC_CODES){ merror(M_SYSTEM_MESSAGE_DOMAIN, "Attempt to get an invalid variable (code: %d)", codec_code); var = shared_ptr<Variable>(); } else { // DDC: removed copying. What was that for? //var = list[codec_code]; var = master_variable_list[codec_code - N_RESERVED_CODEC_CODES]; } return var; } std::vector<std::string> VariableRegistry::getVariableTagNames() { boost::mutex::scoped_lock s_lock(lock); std::vector<std::string> tagnames; vector< shared_ptr<Variable> >::iterator i; for(i = master_variable_list.begin(); i != master_variable_list.end(); i++){ shared_ptr<Variable> var = (*i); if(var) { tagnames.push_back(var->getVariableName()); } } return tagnames; } bool VariableRegistry::hasVariable(const char *tagname) const { return (getVariable(tagname) != NULL); } bool VariableRegistry::hasVariable(std::string &tagname) const { return (getVariable(tagname) != NULL); } int VariableRegistry::getNVariables() { return master_variable_list.size(); } shared_ptr<ScopedVariable> VariableRegistry::addScopedVariable(weak_ptr<ScopedVariableEnvironment> env, VariableProperties *props) { // create a new entry and return one instance if(props == NULL) { // TODO warn throw SimpleException("Failed to add scoped variable to registry"); } int variable_context_index = -1; int codec_code = -1; VariableProperties *props_copy = new VariableProperties(*props); shared_ptr<ScopedVariable> new_variable(new ScopedVariable(props_copy)); //GlobalCurrentExperiment->addVariable(new_variable); master_variable_list.push_back(new_variable); codec_code = master_variable_list.size() + N_RESERVED_CODEC_CODES - 1; std::string tag = new_variable->getVariableName(); if(!tag.empty()){ master_variable_dictionary[tag] = new_variable; } local_variable_list.push_back(new_variable); variable_context_index = local_variable_list.size() - 1; new_variable->setContextIndex(variable_context_index); new_variable->setLogging(M_WHEN_CHANGED); new_variable->setCodecCode(codec_code); new_variable->setEventTarget(static_pointer_cast<EventReceiver>(event_buffer)); if(!env.expired()){ shared_ptr<ScopedVariableEnvironment> env_shared(env); env_shared->addVariable(new_variable); } return new_variable; } shared_ptr<GlobalVariable> VariableRegistry::addGlobalVariable(VariableProperties *props){ if(props == NULL){ // TODO: warn throw SimpleException("Failed to add global variable to registry"); } VariableProperties *copy = new VariableProperties(*props); shared_ptr<GlobalVariable> returnref(new GlobalVariable(copy)); master_variable_list.push_back(returnref); int codec_code = master_variable_list.size() + N_RESERVED_CODEC_CODES - 1; std::string tag = returnref->getVariableName(); if(!tag.empty()){ master_variable_dictionary[tag] = returnref; } global_variable_list.push_back(returnref); returnref->setCodecCode(codec_code); returnref->setEventTarget(static_pointer_cast<EventReceiver>(event_buffer)); return returnref; } shared_ptr<ConstantVariable> VariableRegistry::addConstantVariable(Datum value){ shared_ptr<ConstantVariable> returnref(new ConstantVariable(value)); returnref->setCodecCode(-1); returnref->setEventTarget(static_pointer_cast<EventReceiver>(event_buffer)); return returnref; } shared_ptr<Timer> VariableRegistry::createTimer(VariableProperties *props) { VariableProperties *props_copy; if(props != NULL){ props_copy = new VariableProperties(*props); } else { props_copy = NULL; } shared_ptr<Timer> new_timer(new Timer(props_copy)); // int codec_code = master_variable_list.addReference(new_timer); std::string tag = new_timer->getVariableName(); if(!tag.empty()){ master_variable_dictionary[tag] = new_timer; } new_timer->setCodecCode(-1); new_timer->setEventTarget(static_pointer_cast<EventReceiver>(event_buffer)); return new_timer; } //shared_ptr<EmptyVariable> VariableRegistry::addPlaceholderVariable(VariableProperties *props){ // // VariableProperties *props_copy; // // if(props != NULL){ // props_copy = new VariableProperties(*props); // } else { // props_copy = NULL; // } // // // shared_ptr<EmptyVariable> returnref(new EmptyVariable(props_copy)); // // master_variable_list.push_back(returnref); // int codec_code = master_variable_list.size(); // // returnref->setCodecCode(codec_code); // returnref->setEventTarget(static_pointer_cast<EventReceiver>(event_buffer)); // // return returnref; //} shared_ptr<SelectionVariable> VariableRegistry::addSelectionVariable(VariableProperties *props){ VariableProperties *props_copy; if(props != NULL){ props_copy = new VariableProperties(*props); } else { props_copy = NULL; } shared_ptr<SelectionVariable> returnref(new SelectionVariable(props_copy)); master_variable_list.push_back(returnref); int codec_code = master_variable_list.size(); std::string tag = returnref->getVariableName(); if(!tag.empty()){ master_variable_dictionary[tag] = returnref; } selection_variable_list.push_back(returnref); returnref->setCodecCode(codec_code); returnref->setEventTarget(static_pointer_cast<EventReceiver>(event_buffer)); return returnref; } shared_ptr<ScopedVariable> VariableRegistry::createScopedVariable(weak_ptr<ScopedVariableEnvironment> env, VariableProperties *props) { boost::mutex::scoped_lock s_lock(lock); shared_ptr<ScopedVariable> var = addScopedVariable(env, props); return var; } shared_ptr<GlobalVariable> VariableRegistry::createGlobalVariable(VariableProperties *props) { boost::mutex::scoped_lock s_lock(lock); shared_ptr<GlobalVariable> var = addGlobalVariable(props); return var; } shared_ptr<ConstantVariable> VariableRegistry::createConstantVariable(Datum value){ return addConstantVariable(value); } //shared_ptr<EmptyVariable> VariableRegistry::createPlaceholderVariable(VariableProperties *props){ // boost::mutex::scoped_lock s_lock(lock); // // shared_ptr<EmptyVariable> var = addPlaceholderVariable(props); // // return var; //} shared_ptr<SelectionVariable> VariableRegistry::createSelectionVariable(VariableProperties *props){ boost::mutex::scoped_lock s_lock(lock); shared_ptr<SelectionVariable> var = addSelectionVariable(props); return var; } Datum VariableRegistry::generateCodecDatum() { ScarabDatum *codec = NULL; shared_ptr<Variable> var; boost::mutex::scoped_lock s_lock(lock); int dictSize = master_variable_list.size(); codec = scarab_dict_new(dictSize, &scarab_dict_times2); for(int i = 0; i < dictSize; i++) { var = master_variable_list[i]; if(var == NULL) { continue; } int codec_code = var->getCodecCode(); if(codec_code == RESERVED_CODEC_CODE) { continue; } VariableProperties *props = var->getProperties(); if(props == NULL){ continue; } Datum serialized_var(props->operator Datum()); if(serialized_var.isUndefined()) { mdebug("local parameter null value at param (%d)", i); } ScarabDatum *codec_key = scarab_new_integer(codec_code); scarab_dict_put(codec, codec_key, serialized_var.getScarabDatum()); scarab_free_datum(codec_key); } Datum returnCodec(codec); scarab_free_datum(codec); return returnCodec; } /// Return the (constant) value of a variable. stx::AnyScalar VariableRegistry::lookupVariable(const std::string &varname) const{ shared_ptr<Variable> var = getVariable(varname); if(var == NULL){ // TODO: throw better throw SimpleException("Failed to find variable during expression evaluation", varname); } Datum value = *(var); stx::AnyScalar retval = value; return retval; } namespace mw { shared_ptr<VariableRegistry> global_variable_registry; static bool registry_initialized = false; } //void initializeVariableRegistry() { // global_variable_registry = shared_ptr<VariableRegistry>(new VariableRegistry(global_outgoing_event_buffer)); // registry_initialized = true; // //} <|endoftext|>
<commit_before>#include "susi/cluster/ClusterComponent.h" void Susi::ClusterComponent::addToBlacklist(std::string & id){ eventBlacklist.push_front(id); while(eventBlacklist.size() > 64){ eventBlacklist.pop_back(); } } bool Susi::ClusterComponent::checkIfInBlacklist(std::string & id){ for(auto & entry : eventBlacklist){ if(entry == id){ return true; } } return false; } void Susi::ClusterComponent::validateNode(BSON::Value & node){ if(!node.isObject()) throw std::runtime_error{"ClusterComponent: Node config not valid: config is not an object."}; if(!node["id"].isString()) throw std::runtime_error{"ClusterComponent: Node config not valid: the field 'id' is not present or not string."}; if(!node["processors"].isUndefined()){ if(!node["processors"].isArray()) throw std::runtime_error{"ClusterComponent: Node config not valid: the field 'processors' is not an array."}; for(auto & val : node["processors"].getArray()){ if(!val.isString()) throw std::runtime_error{"ClusterComponent: Node config not valid: one entry in 'processors' is not string."}; } } if(!node["consumers"].isUndefined()){ if(!node["consumers"].isArray()) throw std::runtime_error{"ClusterComponent: Node config not valid: the field 'consumers' is not an array."}; for(auto & val : node["consumers"].getArray()){ if(!val.isString()) throw std::runtime_error{"ClusterComponent: Node config not valid: one entry in 'consumers' is not string."}; } } if(!node["forward"].isUndefined()){ if(!node["forward"].isArray()) throw std::runtime_error{"ClusterComponent: Node config not valid: the field 'forward' is not an array."}; for(auto & val : node["forward"].getArray()){ if(!val.isString()) throw std::runtime_error{"ClusterComponent: Node config not valid: one entry in 'forward' is not string."}; } } } void Susi::ClusterComponent::setupNode(BSON::Value & node){ LOG(DEBUG) << "configure cluster node: "<<node.toJSON(); std::string id = node["id"]; auto apiClient = std::make_shared<Susi::Api::ApiClient>(node["addr"].getString()); apiClients[id] = apiClient; apiClient->registerConsumer("connection::connect",[this,id](Susi::Events::SharedEventPtr evt){ LOG(INFO) << "ClusterComponent: node " << id <<" is now online"; auto event = createEvent("cluster::node::open"); event->payload = id; publish(std::move(event)); }); apiClient->registerConsumer("connection::close",[this,id](Susi::Events::SharedEventPtr evt){ LOG(INFO) << "ClusterComponent: node " << id <<" is now offline"; auto event = createEvent("cluster::node::close"); event->payload = id; publish(std::move(event)); }); //forward all events "*@$NODE_ID" to this node. registerForwardingForNode(id,"*@"+id); if(!node["processors"].isUndefined()){ for(std::string & topic : node["processors"].getArray()){ registerProcessorForNode(id,topic); } } if(!node["consumers"].isUndefined()){ for(std::string & topic : node["consumers"].getArray()){ registerConsumerForNode(id,topic); } } if(!node["forward"].isUndefined()){ for(std::string & topic : node["forward"].getArray()){ registerForwardingForNode(id,topic); } } } void Susi::ClusterComponent::registerProcessorForNode(std::string nodeId, std::string topic){ LOG(DEBUG) << "setup processor for "<<nodeId<<": "<<topic; auto & apiClient = apiClients[nodeId]; apiClient->registerProcessor(topic,[this,nodeId](Susi::Events::EventPtr remoteEvent){ if(checkIfInBlacklist(remoteEvent->id)){ return; } addToBlacklist(remoteEvent->id); struct FinishCallback { Susi::Events::EventPtr remoteEvent; FinishCallback(Susi::Events::EventPtr evt) : remoteEvent{std::move(evt)} {} FinishCallback(FinishCallback && other) : remoteEvent{std::move(other.remoteEvent)} {} FinishCallback(FinishCallback & other) : remoteEvent{std::move(other.remoteEvent)} {} void operator()(Susi::Events::SharedEventPtr localEvent){ *remoteEvent = *localEvent; } }; auto localEvent = this->createEvent(remoteEvent->topic); *localEvent = *remoteEvent; FinishCallback finishCallback{std::move(remoteEvent)}; this->publish(std::move(localEvent),std::move(finishCallback)); }); } void Susi::ClusterComponent::registerConsumerForNode(std::string nodeId, std::string topic){ LOG(DEBUG) << "setup consumer for "<<nodeId<<": "<<topic; auto & apiClient = apiClients[nodeId]; apiClient->registerConsumer(topic,[this,nodeId](Susi::Events::SharedEventPtr remoteEvent){ if(checkIfInBlacklist(remoteEvent->id)){ return; } addToBlacklist(remoteEvent->id); auto localEvent = this->createEvent(remoteEvent->topic); *localEvent = *remoteEvent; this->publish(std::move(localEvent)); }); } void Susi::ClusterComponent::registerForwardingForNode(std::string nodeId, std::string topic){ LOG(DEBUG) << "setup forwarding to "<<nodeId<<": "<<topic; this->subscribe(topic,[this,nodeId,topic](Susi::Events::EventPtr localEvent){ if(checkIfInBlacklist(localEvent->id)){ return; } addToBlacklist(localEvent->id); LOG(DEBUG) << "Forwarding to "<<nodeId<<": "<<topic; struct FinishCallback { Susi::Events::EventPtr localEvent; FinishCallback(Susi::Events::EventPtr evt) : localEvent{std::move(evt)} {} FinishCallback(FinishCallback && other) : localEvent{std::move(other.localEvent)} {} FinishCallback(FinishCallback & other) : localEvent{std::move(other.localEvent)} {} void operator()(Susi::Events::SharedEventPtr remoteEvent){ LOG(DEBUG) << "Forwarding finished."; *localEvent = *remoteEvent; } }; auto & apiClient = apiClients[nodeId]; auto remoteEvent = apiClient->createEvent(localEvent->topic); *remoteEvent = *localEvent; FinishCallback finishCallback{std::move(localEvent)}; apiClient->publish(std::move(remoteEvent),std::move(finishCallback)); }); } <commit_msg>[cluster] make code more robust;<commit_after>#include "susi/cluster/ClusterComponent.h" void Susi::ClusterComponent::addToBlacklist(std::string & id){ eventBlacklist.push_front(id); while(eventBlacklist.size() > 64){ eventBlacklist.pop_back(); } } bool Susi::ClusterComponent::checkIfInBlacklist(std::string & id){ for(auto & entry : eventBlacklist){ if(entry == id){ return true; } } return false; } void Susi::ClusterComponent::validateNode(BSON::Value & node){ if(!node.isObject()) throw std::runtime_error{"ClusterComponent: Node config not valid: config is not an object."}; if(!node["id"].isString()) throw std::runtime_error{"ClusterComponent: Node config not valid: the field 'id' is not present or not string."}; if(!node["processors"].isUndefined()){ if(!node["processors"].isArray()) throw std::runtime_error{"ClusterComponent: Node config not valid: the field 'processors' is not an array."}; for(auto & val : node["processors"].getArray()){ if(!val.isString()) throw std::runtime_error{"ClusterComponent: Node config not valid: one entry in 'processors' is not string."}; } } if(!node["consumers"].isUndefined()){ if(!node["consumers"].isArray()) throw std::runtime_error{"ClusterComponent: Node config not valid: the field 'consumers' is not an array."}; for(auto & val : node["consumers"].getArray()){ if(!val.isString()) throw std::runtime_error{"ClusterComponent: Node config not valid: one entry in 'consumers' is not string."}; } } if(!node["forward"].isUndefined()){ if(!node["forward"].isArray()) throw std::runtime_error{"ClusterComponent: Node config not valid: the field 'forward' is not an array."}; for(auto & val : node["forward"].getArray()){ if(!val.isString()) throw std::runtime_error{"ClusterComponent: Node config not valid: one entry in 'forward' is not string."}; } } } void Susi::ClusterComponent::setupNode(BSON::Value & node){ LOG(DEBUG) << "configure cluster node: "<<node.toJSON(); std::string id = node["id"]; auto apiClient = std::make_shared<Susi::Api::ApiClient>(node["addr"].getString()); apiClients[id] = apiClient; apiClient->registerConsumer("connection::connect",[this,id](Susi::Events::SharedEventPtr evt){ LOG(INFO) << "ClusterComponent: node " << id <<" is now online"; auto event = createEvent("cluster::node::open"); event->payload = id; publish(std::move(event)); }); apiClient->registerConsumer("connection::close",[this,id](Susi::Events::SharedEventPtr evt){ LOG(INFO) << "ClusterComponent: node " << id <<" is now offline"; auto event = createEvent("cluster::node::close"); event->payload = id; publish(std::move(event)); }); //forward all events "*@$NODE_ID" to this node. registerForwardingForNode(id,"*@"+id); if(!node["processors"].isUndefined()){ for(std::string & topic : node["processors"].getArray()){ registerProcessorForNode(id,topic); } } if(!node["consumers"].isUndefined()){ for(std::string & topic : node["consumers"].getArray()){ registerConsumerForNode(id,topic); } } if(!node["forward"].isUndefined()){ for(std::string & topic : node["forward"].getArray()){ registerForwardingForNode(id,topic); } } } void Susi::ClusterComponent::registerProcessorForNode(std::string nodeId, std::string topic){ LOG(DEBUG) << "setup processor for "<<nodeId<<": "<<topic; auto & apiClient = apiClients[nodeId]; apiClient->registerProcessor(topic,[this,nodeId](Susi::Events::EventPtr remoteEvent){ if(checkIfInBlacklist(remoteEvent->id)){ return; } addToBlacklist(remoteEvent->id); struct FinishCallback { Susi::Events::EventPtr remoteEvent; FinishCallback(Susi::Events::EventPtr evt) : remoteEvent{std::move(evt)} {} FinishCallback(FinishCallback && other) : remoteEvent{std::move(other.remoteEvent)} {} FinishCallback(FinishCallback & other) : remoteEvent{std::move(other.remoteEvent)} {} void operator()(Susi::Events::SharedEventPtr localEvent){ *remoteEvent = *localEvent; } }; auto localEvent = this->createEvent(remoteEvent->topic); *localEvent = *remoteEvent; FinishCallback finishCallback{std::move(remoteEvent)}; this->publish(std::move(localEvent),std::move(finishCallback)); }); } void Susi::ClusterComponent::registerConsumerForNode(std::string nodeId, std::string topic){ LOG(DEBUG) << "setup consumer for "<<nodeId<<": "<<topic; auto & apiClient = apiClients[nodeId]; apiClient->registerConsumer(topic,[this,nodeId](Susi::Events::SharedEventPtr remoteEvent){ if(checkIfInBlacklist(remoteEvent->id)){ return; } addToBlacklist(remoteEvent->id); auto localEvent = this->createEvent(remoteEvent->topic); *localEvent = *remoteEvent; this->publish(std::move(localEvent)); }); } void Susi::ClusterComponent::registerForwardingForNode(std::string nodeId, std::string topic){ LOG(DEBUG) << "setup forwarding to "<<nodeId<<": "<<topic; this->subscribe(topic,[this,nodeId,topic](Susi::Events::EventPtr localEvent){ if(checkIfInBlacklist(localEvent->id)){ return; } addToBlacklist(localEvent->id); LOG(DEBUG) << "Forwarding to "<<nodeId<<": "<<topic; struct FinishCallback { Susi::Events::EventPtr localEvent; FinishCallback(Susi::Events::EventPtr evt) : localEvent{std::move(evt)} {} FinishCallback(FinishCallback && other) : localEvent{std::move(other.localEvent)} {} FinishCallback(FinishCallback & other) : localEvent{std::move(other.localEvent)} {} void operator()(Susi::Events::SharedEventPtr remoteEvent){ LOG(DEBUG) << "Forwarding finished."; if(localEvent){ *localEvent = *remoteEvent; } } }; auto & apiClient = apiClients[nodeId]; auto remoteEvent = apiClient->createEvent(localEvent->topic); *remoteEvent = *localEvent; FinishCallback finishCallback{std::move(localEvent)}; apiClient->publish(std::move(remoteEvent),std::move(finishCallback)); }); } <|endoftext|>
<commit_before>#include "TailGenerator.h" TailGenerator::TailGenerator(Context* context) : Drawable(context, DRAWABLE_GEOMETRY) { matchNode_ = false; geometry_ = SharedPtr<Geometry>(new Geometry(context)); vertexBuffer_ = SharedPtr<VertexBuffer>(new VertexBuffer(context)); indexBuffer_ = SharedPtr<IndexBuffer>(new IndexBuffer(context)); geometry_->SetVertexBuffer(0, vertexBuffer_); geometry_->SetIndexBuffer(indexBuffer_); indexBuffer_->SetShadowed(false); transforms_[0] = Matrix3x4::IDENTITY; transforms_[1] = Matrix3x4(Vector3::ZERO, Quaternion(0, 0, 0), Vector3::ONE); batches_.Resize(1); batches_[0].geometry_ = geometry_; batches_[0].geometryType_ = GEOM_STATIC; batches_[0].worldTransform_ = &transforms_[0]; batches_[0].numWorldTransforms_ = 2; forceUpdateVertexBuffer_ = false; previousPosition_ = Vector3::ZERO; tailNum_ = 10; // for debug ResourceCache* cache = GetSubsystem<ResourceCache>(); SetMaterial(cache->GetResource<Material>("Materials/TailGenerator.xml")); tailLength_ = 0.25f; scale_ = 1.0f; // default side scale tailTipColor = Color(1.0f, 1.0f, 1.0f, 1.0f); tailHeadColor = Color(1.0f, 1.0f, 1.0f, 1.0f); forceUpdateVertexBuffer_ = false; bbmax = Vector3::ZERO; bbmin = Vector3::ZERO; vertical_ = horizontal_ = true; } TailGenerator::~TailGenerator() { } void TailGenerator::RegisterObject(Context* context) { context->RegisterFactory<TailGenerator>(); URHO3D_COPY_BASE_ATTRIBUTES(Drawable); URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Material", GetMaterialAttr, SetMaterialAttr, ResourceRef, ResourceRef(Material::GetTypeStatic()), AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Segments", GetNumTails, SetNumTails, unsigned int, 10, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Length", GetTailLength, SetTailLength, float, 0.25f, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Width", GetWidthScale, SetWidthScale, float, 1.0f, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Start Color", GetColorForHead, SetColorForHead, Color, Color::WHITE, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("End Color", GetColorForTip, SetColorForTip, Color, Color::WHITE, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Draw Vertical", GetDrawVertical, SetDrawVertical, bool, true, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Draw Horizontal", GetDrawHorizontal, SetDrawHorizontal, bool, true, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Match Node Rotation", GetMatchNodeOrientation, SetMatchNodeOrientation, bool, false, AM_DEFAULT); } void TailGenerator::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results) { // If no billboard-level testing, use the Drawable test if (query.level_ < RAY_TRIANGLE) { Drawable::ProcessRayQuery(query, results); return; } } void TailGenerator::Update(const FrameInfo &frame) { Drawable::Update(frame); } void TailGenerator::UpdateTail() { Vector3 wordPosition = node_->GetWorldPosition(); float path = (previousPosition_ - wordPosition).Length(); if (path > tailLength_) { // новая точка пути Tail newPoint; newPoint.position = wordPosition; Vector3 forwardmotion = matchNode_ ? GetNode()->GetWorldDirection() : (previousPosition_ - wordPosition).Normalized(); Vector3 rightmotion = matchNode_ ? GetNode()->GetWorldRight() : forwardmotion.CrossProduct(Vector3::UP); rightmotion.Normalize(); newPoint.worldRight = rightmotion; newPoint.forward = forwardmotion; //forceBuildMeshInWorkerThread_ = true; forceUpdateVertexBuffer_ = true; previousPosition_ = wordPosition; fullPointPath.Push(newPoint); // Весь путь, все точки за все время работы компонента. //knots.Push(wordPosition); // Для сплайна опорные } } void TailGenerator::DrawDebugGeometry(DebugRenderer *debug, bool depthTest) { Drawable::DrawDebugGeometry(debug, depthTest); debug->AddNode(node_); for (unsigned i = 0; i < tails_.Size()-1; i++) { debug->AddLine(tails_[i].position, tails_[i+1].position, Color(1,1,1).ToUInt(), false); } } void TailGenerator::UpdateBatches(const FrameInfo& frame) { // Update tail's mesh if needed UpdateTail(); // Update information for renderer about this drawable distance_ = frame.camera_->GetDistance(GetWorldBoundingBox().Center()); batches_[0].distance_ = distance_; //batches_[0].numWorldTransforms_ = 2; // TailGenerator positioning //transforms_[0] = Matrix3x4::IDENTITY; // TailGenerator rotation //transforms_[1] = Matrix3x4(Vector3::ZERO, Quaternion(0, 0, 0), Vector3::ONE); } void TailGenerator::UpdateGeometry(const FrameInfo& frame) { if (bufferSizeDirty_ || indexBuffer_->IsDataLost()) UpdateBufferSize(); if (bufferDirty_ || vertexBuffer_->IsDataLost() || forceUpdateVertexBuffer_) UpdateVertexBuffer(frame); } UpdateGeometryType TailGenerator::GetUpdateGeometryType() { if (bufferDirty_ || bufferSizeDirty_ || vertexBuffer_->IsDataLost() || indexBuffer_->IsDataLost()|| forceUpdateVertexBuffer_) return UPDATE_MAIN_THREAD; else return UPDATE_NONE; } void TailGenerator::SetMaterial(Material* material) { batches_[0].material_ = material; MarkNetworkUpdate(); } void TailGenerator::OnNodeSet(Node* node) { Drawable::OnNodeSet(node); } void TailGenerator::OnWorldBoundingBoxUpdate() { //worldBoundingBox_.Define(-M_LARGE_VALUE, M_LARGE_VALUE); worldBoundingBox_.Merge(bbmin); worldBoundingBox_.Merge(bbmax); worldBoundingBox_.Merge(node_->GetWorldPosition()); } /// Resize TailGenerator vertex and index buffers. void TailGenerator::UpdateBufferSize() { unsigned numTails = tailNum_; if (!numTails) return; int vertsPerSegment = (vertical_ && horizontal_ ? 4 : (!vertical_ && !horizontal_ ? 0 : 2)); int degenerateVertCt = 0; if (vertsPerSegment > 2) degenerateVertCt += 2; //requires two degenerate triangles if (vertexBuffer_->GetVertexCount() != (numTails * vertsPerSegment)) { vertexBuffer_->SetSize((numTails * vertsPerSegment), MASK_POSITION | MASK_COLOR | MASK_TEXCOORD1, true); } if (indexBuffer_->GetIndexCount() != (numTails * vertsPerSegment) + degenerateVertCt) { indexBuffer_->SetSize((numTails * vertsPerSegment) + degenerateVertCt, false); } bufferSizeDirty_ = false; bufferDirty_ = true; // Indices do not change for a given tail generator capacity unsigned short* dest = (unsigned short*)indexBuffer_->Lock(0, (numTails * vertsPerSegment) + degenerateVertCt, true); if (!dest) return; unsigned vertexIndex = 0; if (horizontal_) { unsigned stripsLen = numTails; while (stripsLen--) { dest[0] = vertexIndex; dest[1] = vertexIndex + 1; dest += 2; // degenerate triangle vert on horizontal if (vertical_ && stripsLen == 0) { dest[0] = vertexIndex + 1; dest += 1; } vertexIndex += 2; } } if (vertical_) { unsigned stripsLen = numTails; while (stripsLen--) { // degenerate triangle vert on vertical if (horizontal_ && stripsLen == (numTails - 1)) { dest[0] = vertexIndex; dest += 1; } dest[0] = vertexIndex; dest[1] = vertexIndex + 1; dest += 2; vertexIndex += 2; } } indexBuffer_->Unlock(); indexBuffer_->ClearDataLost(); } /// Rewrite TailGenerator vertex buffer. void TailGenerator::UpdateVertexBuffer(const FrameInfo& frame) { unsigned fullPointPathSize = fullPointPath.Size(); unsigned currentVisiblePathSize = tailNum_; // Clear previous mesh data tailMesh.Clear(); // build tail // if tail path is short and nothing to draw, exit if (fullPointPathSize < 2) return; activeTails.Clear(); unsigned min_i = fullPointPathSize < currentVisiblePathSize ? 0 : fullPointPathSize - currentVisiblePathSize; // Step 1 : collect actual point's info for build tail path for (unsigned i = min_i; i < fullPointPathSize - 1; i++) { activeTails.Push(fullPointPath[i]); Vector3 &p = fullPointPath[i].position; // Math BoundingBox based on actual point if (p.x_ < bbmin.x_) bbmin.x_ = p.x_; if (p.y_ < bbmin.y_) bbmin.y_ = p.y_; if (p.z_ < bbmin.z_) bbmin.z_ = p.z_; if (p.x_ > bbmax.x_) bbmax.x_ = p.x_; if (p.y_ > bbmax.y_) bbmax.y_ = p.y_; if (p.z_ > bbmax.z_) bbmax.z_ = p.z_; } if (activeTails.Size() < 2) return; Vector<Tail> &t = activeTails; // generate strips of tris TailVertex v; float mixFactor = 1.0f / activeTails.Size(); // Forward part of tail (strip in xz plane) if (horizontal_) { for (unsigned i = 0; i < activeTails.Size() || i < tailNum_; ++i) { unsigned sub = i < activeTails.Size() ? i : activeTails.Size() - 1; Color c = tailTipColor.Lerp(tailHeadColor, mixFactor * i); v.color_ = c.ToUInt(); v.uv_ = Vector2(1.0f, 0.0f); v.position_ = t[sub].position + t[sub].worldRight * scale_; tailMesh.Push(v); //v.color_ = c.ToUInt(); v.uv_ = Vector2(0.0f, 1.0f); v.position_ = t[sub].position - t[sub].worldRight * scale_; tailMesh.Push(v); } } // Upper part of tail (strip in xy-plane) if (vertical_) { for (unsigned i = 0; i < activeTails.Size() || i < tailNum_; ++i) { unsigned sub = i < activeTails.Size() ? i : activeTails.Size() - 1; Color c = tailTipColor.Lerp(tailHeadColor, mixFactor * i); v.color_ = c.ToUInt(); v.uv_ = Vector2(1.0f, 0.0f); Vector3 up = t[sub].forward.CrossProduct(t[sub].worldRight); up.Normalize(); v.position_ = t[sub].position + up * scale_; tailMesh.Push(v); //v.color_ = c.ToUInt(); v.uv_ = Vector2(0.0f, 1.0f); v.position_ = t[sub].position - up * scale_; tailMesh.Push(v); } } // copy new mesh to vertex buffer unsigned meshVertexCount = tailMesh.Size(); batches_[0].geometry_->SetDrawRange(TRIANGLE_STRIP, 0, meshVertexCount + (horizontal_ && vertical_ ? 2 : 0), false); // get pointer TailVertex* dest = (TailVertex*)vertexBuffer_->Lock(0, meshVertexCount, true); if (!dest) return; // copy to vertex buffer memcpy(dest, &tailMesh[0], tailMesh.Size() * sizeof(TailVertex)); vertexBuffer_->Unlock(); vertexBuffer_->ClearDataLost(); bufferDirty_ = false; // unmark flag forceUpdateVertexBuffer_ = false; } void TailGenerator::SetTailLength(float length) { tailLength_ = length; } void TailGenerator::SetColorForTip(const Color& c) { tailTipColor = Color(c.r_, c.g_, c.b_, 0.0f); } void TailGenerator::SetColorForHead(const Color& c) { tailHeadColor = Color(c.r_, c.g_, c.b_, 1.0f); } void TailGenerator::SetNumTails(unsigned num) { // Prevent negative value being assigned from the editor if (num > M_MAX_INT) num = 0; if (num > MAX_TAILS) num = MAX_TAILS; bufferSizeDirty_ = true; tailNum_ = num; } unsigned TailGenerator::GetNumTails() { return tailNum_; } void TailGenerator::SetDrawVertical(bool value) { vertical_ = value; //SetupBatches(); } void TailGenerator::SetDrawHorizontal(bool value) { horizontal_ = value; //SetupBatches(); } void TailGenerator::SetMatchNodeOrientation(bool value) { matchNode_ = value; } void TailGenerator::MarkPositionsDirty() { Drawable::OnMarkedDirty(node_); bufferDirty_ = true; } void TailGenerator::SetMaterialAttr(const ResourceRef& value) { ResourceCache* cache = GetSubsystem<ResourceCache>(); SetMaterial(cache->GetResource<Material>(value.name_)); } ResourceRef TailGenerator::GetMaterialAttr() const { return GetResourceRef(batches_[0].material_, Material::GetTypeStatic()); } void TailGenerator::SetWidthScale(float scale) { scale_ = scale; }<commit_msg>Fix memory leak https://github.com/MonkeyFirst/urho3d-component-tail-generator/issues/4<commit_after>#include "TailGenerator.h" TailGenerator::TailGenerator(Context* context) : Drawable(context, DRAWABLE_GEOMETRY) { matchNode_ = false; geometry_ = SharedPtr<Geometry>(new Geometry(context)); vertexBuffer_ = SharedPtr<VertexBuffer>(new VertexBuffer(context)); indexBuffer_ = SharedPtr<IndexBuffer>(new IndexBuffer(context)); geometry_->SetVertexBuffer(0, vertexBuffer_); geometry_->SetIndexBuffer(indexBuffer_); indexBuffer_->SetShadowed(false); transforms_[0] = Matrix3x4::IDENTITY; transforms_[1] = Matrix3x4(Vector3::ZERO, Quaternion(0, 0, 0), Vector3::ONE); batches_.Resize(1); batches_[0].geometry_ = geometry_; batches_[0].geometryType_ = GEOM_STATIC; batches_[0].worldTransform_ = &transforms_[0]; batches_[0].numWorldTransforms_ = 2; forceUpdateVertexBuffer_ = false; previousPosition_ = Vector3::ZERO; tailNum_ = 10; // for debug ResourceCache* cache = GetSubsystem<ResourceCache>(); SetMaterial(cache->GetResource<Material>("Materials/TailGenerator.xml")); tailLength_ = 0.25f; scale_ = 1.0f; // default side scale tailTipColor = Color(1.0f, 1.0f, 1.0f, 1.0f); tailHeadColor = Color(1.0f, 1.0f, 1.0f, 1.0f); forceUpdateVertexBuffer_ = false; bbmax = Vector3::ZERO; bbmin = Vector3::ZERO; vertical_ = horizontal_ = true; } TailGenerator::~TailGenerator() { } void TailGenerator::RegisterObject(Context* context) { context->RegisterFactory<TailGenerator>(); URHO3D_COPY_BASE_ATTRIBUTES(Drawable); URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Material", GetMaterialAttr, SetMaterialAttr, ResourceRef, ResourceRef(Material::GetTypeStatic()), AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Segments", GetNumTails, SetNumTails, unsigned int, 10, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Length", GetTailLength, SetTailLength, float, 0.25f, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Width", GetWidthScale, SetWidthScale, float, 1.0f, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Start Color", GetColorForHead, SetColorForHead, Color, Color::WHITE, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("End Color", GetColorForTip, SetColorForTip, Color, Color::WHITE, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Draw Vertical", GetDrawVertical, SetDrawVertical, bool, true, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Draw Horizontal", GetDrawHorizontal, SetDrawHorizontal, bool, true, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Match Node Rotation", GetMatchNodeOrientation, SetMatchNodeOrientation, bool, false, AM_DEFAULT); } void TailGenerator::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results) { // If no billboard-level testing, use the Drawable test if (query.level_ < RAY_TRIANGLE) { Drawable::ProcessRayQuery(query, results); return; } } void TailGenerator::Update(const FrameInfo &frame) { Drawable::Update(frame); } void TailGenerator::UpdateTail() { Vector3 wordPosition = node_->GetWorldPosition(); float path = (previousPosition_ - wordPosition).Length(); if (path > tailLength_) { // новая точка пути Tail newPoint; newPoint.position = wordPosition; Vector3 forwardmotion = matchNode_ ? GetNode()->GetWorldDirection() : (previousPosition_ - wordPosition).Normalized(); Vector3 rightmotion = matchNode_ ? GetNode()->GetWorldRight() : forwardmotion.CrossProduct(Vector3::UP); rightmotion.Normalize(); newPoint.worldRight = rightmotion; newPoint.forward = forwardmotion; //forceBuildMeshInWorkerThread_ = true; forceUpdateVertexBuffer_ = true; previousPosition_ = wordPosition; fullPointPath.Push(newPoint); // Весь путь, все точки за все время работы компонента. //knots.Push(wordPosition); // Для сплайна опорные if (fullPointPath.Size() > tailNum_) fullPointPath.Erase(0, fullPointPath.Size() - tailNum_); } } void TailGenerator::DrawDebugGeometry(DebugRenderer *debug, bool depthTest) { Drawable::DrawDebugGeometry(debug, depthTest); debug->AddNode(node_); for (unsigned i = 0; i < tails_.Size()-1; i++) { debug->AddLine(tails_[i].position, tails_[i+1].position, Color(1,1,1).ToUInt(), false); } } void TailGenerator::UpdateBatches(const FrameInfo& frame) { // Update tail's mesh if needed UpdateTail(); // Update information for renderer about this drawable distance_ = frame.camera_->GetDistance(GetWorldBoundingBox().Center()); batches_[0].distance_ = distance_; //batches_[0].numWorldTransforms_ = 2; // TailGenerator positioning //transforms_[0] = Matrix3x4::IDENTITY; // TailGenerator rotation //transforms_[1] = Matrix3x4(Vector3::ZERO, Quaternion(0, 0, 0), Vector3::ONE); } void TailGenerator::UpdateGeometry(const FrameInfo& frame) { if (bufferSizeDirty_ || indexBuffer_->IsDataLost()) UpdateBufferSize(); if (bufferDirty_ || vertexBuffer_->IsDataLost() || forceUpdateVertexBuffer_) UpdateVertexBuffer(frame); } UpdateGeometryType TailGenerator::GetUpdateGeometryType() { if (bufferDirty_ || bufferSizeDirty_ || vertexBuffer_->IsDataLost() || indexBuffer_->IsDataLost()|| forceUpdateVertexBuffer_) return UPDATE_MAIN_THREAD; else return UPDATE_NONE; } void TailGenerator::SetMaterial(Material* material) { batches_[0].material_ = material; MarkNetworkUpdate(); } void TailGenerator::OnNodeSet(Node* node) { Drawable::OnNodeSet(node); } void TailGenerator::OnWorldBoundingBoxUpdate() { //worldBoundingBox_.Define(-M_LARGE_VALUE, M_LARGE_VALUE); worldBoundingBox_.Merge(bbmin); worldBoundingBox_.Merge(bbmax); worldBoundingBox_.Merge(node_->GetWorldPosition()); } /// Resize TailGenerator vertex and index buffers. void TailGenerator::UpdateBufferSize() { unsigned numTails = tailNum_; if (!numTails) return; int vertsPerSegment = (vertical_ && horizontal_ ? 4 : (!vertical_ && !horizontal_ ? 0 : 2)); int degenerateVertCt = 0; if (vertsPerSegment > 2) degenerateVertCt += 2; //requires two degenerate triangles if (vertexBuffer_->GetVertexCount() != (numTails * vertsPerSegment)) { vertexBuffer_->SetSize((numTails * vertsPerSegment), MASK_POSITION | MASK_COLOR | MASK_TEXCOORD1, true); } if (indexBuffer_->GetIndexCount() != (numTails * vertsPerSegment) + degenerateVertCt) { indexBuffer_->SetSize((numTails * vertsPerSegment) + degenerateVertCt, false); } bufferSizeDirty_ = false; bufferDirty_ = true; // Indices do not change for a given tail generator capacity unsigned short* dest = (unsigned short*)indexBuffer_->Lock(0, (numTails * vertsPerSegment) + degenerateVertCt, true); if (!dest) return; unsigned vertexIndex = 0; if (horizontal_) { unsigned stripsLen = numTails; while (stripsLen--) { dest[0] = vertexIndex; dest[1] = vertexIndex + 1; dest += 2; // degenerate triangle vert on horizontal if (vertical_ && stripsLen == 0) { dest[0] = vertexIndex + 1; dest += 1; } vertexIndex += 2; } } if (vertical_) { unsigned stripsLen = numTails; while (stripsLen--) { // degenerate triangle vert on vertical if (horizontal_ && stripsLen == (numTails - 1)) { dest[0] = vertexIndex; dest += 1; } dest[0] = vertexIndex; dest[1] = vertexIndex + 1; dest += 2; vertexIndex += 2; } } indexBuffer_->Unlock(); indexBuffer_->ClearDataLost(); } /// Rewrite TailGenerator vertex buffer. void TailGenerator::UpdateVertexBuffer(const FrameInfo& frame) { unsigned fullPointPathSize = fullPointPath.Size(); unsigned currentVisiblePathSize = tailNum_; // Clear previous mesh data tailMesh.Clear(); // build tail // if tail path is short and nothing to draw, exit if (fullPointPathSize < 2) return; activeTails.Clear(); unsigned min_i = fullPointPathSize < currentVisiblePathSize ? 0 : fullPointPathSize - currentVisiblePathSize; // Step 1 : collect actual point's info for build tail path for (unsigned i = min_i; i < fullPointPathSize - 1; i++) { activeTails.Push(fullPointPath[i]); Vector3 &p = fullPointPath[i].position; // Math BoundingBox based on actual point if (p.x_ < bbmin.x_) bbmin.x_ = p.x_; if (p.y_ < bbmin.y_) bbmin.y_ = p.y_; if (p.z_ < bbmin.z_) bbmin.z_ = p.z_; if (p.x_ > bbmax.x_) bbmax.x_ = p.x_; if (p.y_ > bbmax.y_) bbmax.y_ = p.y_; if (p.z_ > bbmax.z_) bbmax.z_ = p.z_; } if (activeTails.Size() < 2) return; Vector<Tail> &t = activeTails; // generate strips of tris TailVertex v; float mixFactor = 1.0f / activeTails.Size(); // Forward part of tail (strip in xz plane) if (horizontal_) { for (unsigned i = 0; i < activeTails.Size() || i < tailNum_; ++i) { unsigned sub = i < activeTails.Size() ? i : activeTails.Size() - 1; Color c = tailTipColor.Lerp(tailHeadColor, mixFactor * i); v.color_ = c.ToUInt(); v.uv_ = Vector2(1.0f, 0.0f); v.position_ = t[sub].position + t[sub].worldRight * scale_; tailMesh.Push(v); //v.color_ = c.ToUInt(); v.uv_ = Vector2(0.0f, 1.0f); v.position_ = t[sub].position - t[sub].worldRight * scale_; tailMesh.Push(v); } } // Upper part of tail (strip in xy-plane) if (vertical_) { for (unsigned i = 0; i < activeTails.Size() || i < tailNum_; ++i) { unsigned sub = i < activeTails.Size() ? i : activeTails.Size() - 1; Color c = tailTipColor.Lerp(tailHeadColor, mixFactor * i); v.color_ = c.ToUInt(); v.uv_ = Vector2(1.0f, 0.0f); Vector3 up = t[sub].forward.CrossProduct(t[sub].worldRight); up.Normalize(); v.position_ = t[sub].position + up * scale_; tailMesh.Push(v); //v.color_ = c.ToUInt(); v.uv_ = Vector2(0.0f, 1.0f); v.position_ = t[sub].position - up * scale_; tailMesh.Push(v); } } // copy new mesh to vertex buffer unsigned meshVertexCount = tailMesh.Size(); batches_[0].geometry_->SetDrawRange(TRIANGLE_STRIP, 0, meshVertexCount + (horizontal_ && vertical_ ? 2 : 0), false); // get pointer TailVertex* dest = (TailVertex*)vertexBuffer_->Lock(0, meshVertexCount, true); if (!dest) return; // copy to vertex buffer memcpy(dest, &tailMesh[0], tailMesh.Size() * sizeof(TailVertex)); vertexBuffer_->Unlock(); vertexBuffer_->ClearDataLost(); bufferDirty_ = false; // unmark flag forceUpdateVertexBuffer_ = false; } void TailGenerator::SetTailLength(float length) { tailLength_ = length; } void TailGenerator::SetColorForTip(const Color& c) { tailTipColor = Color(c.r_, c.g_, c.b_, 0.0f); } void TailGenerator::SetColorForHead(const Color& c) { tailHeadColor = Color(c.r_, c.g_, c.b_, 1.0f); } void TailGenerator::SetNumTails(unsigned num) { // Prevent negative value being assigned from the editor if (num > M_MAX_INT) num = 0; if (num > MAX_TAILS) num = MAX_TAILS; bufferSizeDirty_ = true; tailNum_ = num; } unsigned TailGenerator::GetNumTails() { return tailNum_; } void TailGenerator::SetDrawVertical(bool value) { vertical_ = value; //SetupBatches(); } void TailGenerator::SetDrawHorizontal(bool value) { horizontal_ = value; //SetupBatches(); } void TailGenerator::SetMatchNodeOrientation(bool value) { matchNode_ = value; } void TailGenerator::MarkPositionsDirty() { Drawable::OnMarkedDirty(node_); bufferDirty_ = true; } void TailGenerator::SetMaterialAttr(const ResourceRef& value) { ResourceCache* cache = GetSubsystem<ResourceCache>(); SetMaterial(cache->GetResource<Material>(value.name_)); } ResourceRef TailGenerator::GetMaterialAttr() const { return GetResourceRef(batches_[0].material_, Material::GetTypeStatic()); } void TailGenerator::SetWidthScale(float scale) { scale_ = scale; }<|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved */ // TEST Foundation::Containers::Mapping // STATUS Alpha-Late #include "Stroika/Foundation/StroikaPreComp.h" #include <iostream> #include <sstream> #include "Stroika/Foundation/Containers/Collection.h" #include "Stroika/Foundation/Containers/Concrete/Mapping_Array.h" #include "Stroika/Foundation/Containers/Concrete/Mapping_LinkedList.h" #include "Stroika/Foundation/Containers/Concrete/Mapping_stdmap.h" #include "Stroika/Foundation/Containers/Concrete/SortedMapping_stdmap.h" #include "Stroika/Foundation/Containers/Mapping.h" #include "Stroika/Foundation/Debug/Assertions.h" #include "Stroika/Foundation/Debug/Trace.h" #include "../TestCommon/CommonTests_Mapping.h" #include "../TestHarness/SimpleClass.h" #include "../TestHarness/TestHarness.h" using namespace Stroika; using namespace Stroika::Foundation; using namespace Stroika::Foundation::Containers; using Concrete::Mapping_Array; using Concrete::Mapping_LinkedList; using Concrete::Mapping_stdmap; namespace { template <typename CONCRETE_CONTAINER> void DoTestForConcreteContainer_ () { using namespace CommonTests::MappingTests; SimpleMappingTest_All_ (DEFAULT_TESTING_SCHEMA<CONCRETE_CONTAINER>{}); SimpleMappingTest_WithDefaultEqCompaerer_ (DEFAULT_TESTING_SCHEMA<CONCRETE_CONTAINER>{}); } template <typename CONCRETE_CONTAINER, typename FACTORY, typename VALUE_EQUALS_COMPARER_TYPE> void DoTestForConcreteContainer_ (FACTORY factory, VALUE_EQUALS_COMPARER_TYPE valueEqualsComparer) { using namespace CommonTests::MappingTests; auto testschema = DEFAULT_TESTING_SCHEMA<CONCRETE_CONTAINER, FACTORY, VALUE_EQUALS_COMPARER_TYPE>{factory, valueEqualsComparer}; SimpleMappingTest_All_ (testschema); } } namespace { void Test2_SimpleBaseClassConversionTraitsConfusion_ () { Debug::TraceContextBumper ctx{L"{}::Test2_SimpleBaseClassConversionTraitsConfusion_"}; SortedMapping<int, float> xxxyy = Concrete::SortedMapping_stdmap<int, float> (); Mapping<int, float> xxxyy1 = Concrete::Mapping_stdmap<int, float> (); } } namespace { namespace Test4_MappingCTOROverloads_ { namespace xPrivate_ { struct A; struct B; struct A { A () = default; A (const A&) = default; A (const B&) {} }; struct B { B () = default; B (const A&) {} B (const B&) = default; }; using Common::KeyValuePair; using KEY_TYPE = int; using VALUE_TYPE = B; using CONTAINER_OF_PAIR_KEY_T = Mapping<int, A>; using T = KeyValuePair<KEY_TYPE, VALUE_TYPE>; } void DoIt () { Debug::TraceContextBumper ctx{L"{}::Test4_MappingCTOROverloads_"}; using namespace xPrivate_; Mapping<int, A> from; static_assert (Configuration::IsIterableOfT_v<Mapping<int, A>, KeyValuePair<int, A>>); static_assert (Configuration::IsIterableOfT_v<Mapping<int, B>, KeyValuePair<int, B>>); Mapping<int, B> to1; for (auto i : from) { to1.Add (i); } Mapping<int, B> to2{from}; } } } namespace { namespace ExampleCTORS_Test_5_ { void DoTest () { Debug::TraceContextBumper ctx{L"{}::ExampleCTORS_Test_5_"}; // From Mapping<> CTOR docs Collection<pair<int, int>> c; std::map<int, int> m; Mapping<int, int> m1 = {pair<int, int>{1, 1}, pair<int, int>{2, 2}, pair<int, int>{3, 2}}; Mapping<int, int> m2 = m1; Mapping<int, int> m3{m1}; Mapping<int, int> m4{m1.begin (), m1.end ()}; Mapping<int, int> m5{c}; Mapping<int, int> m6{m}; Mapping<int, int> m7{m.begin (), m.end ()}; Mapping<int, int> m8{move (m1)}; Mapping<int, int> m9{Common::DeclareEqualsComparer ([] (int l, int r) { return l == r; })}; } } } namespace { namespace Where_Test_6_ { void DoAll () { Mapping<int, int> m{KeyValuePair<int, int>{1, 3}, KeyValuePair<int, int>{2, 4}, KeyValuePair<int, int>{3, 5}, KeyValuePair<int, int>{4, 5}, KeyValuePair<int, int>{5, 7}}; VerifyTestResult ((m.Where ([] (const KeyValuePair<int, int>& value) { return Math::IsPrime (value.fKey); }) == Mapping<int, int>{KeyValuePair<int, int>{2, 4}, KeyValuePair<int, int>{3, 5}, KeyValuePair<int, int>{5, 7}})); VerifyTestResult ((m.Where ([] (int key) { return Math::IsPrime (key); }) == Mapping<int, int>{KeyValuePair<int, int>{2, 4}, KeyValuePair<int, int>{3, 5}, KeyValuePair<int, int>{5, 7}})); } } } namespace { namespace WithKeys_Test_7_ { void DoAll () { Mapping<int, int> m{KeyValuePair<int, int>{1, 3}, KeyValuePair<int, int>{2, 4}, KeyValuePair<int, int>{3, 5}, KeyValuePair<int, int>{4, 5}, KeyValuePair<int, int>{5, 7}}; VerifyTestResult ((m.WithKeys (initializer_list<int>{2, 5}) == Mapping<int, int>{KeyValuePair<int, int>{2, 4}, KeyValuePair<int, int>{5, 7}})); } } } namespace { namespace ClearBug_Test_8_ { void DoAll () { // https://stroika.atlassian.net/browse/STK-541 Mapping<int, int> m{KeyValuePair<int, int>{1, 3}, KeyValuePair<int, int>{2, 4}, KeyValuePair<int, int>{3, 5}, KeyValuePair<int, int>{4, 5}, KeyValuePair<int, int>{5, 7}}; Mapping<int, int> mm{move (m)}; m.clear (); } } } namespace { void DoRegressionTests_ () { struct MySimpleClassWithoutComparisonOperators_ComparerWithEquals_ : Common::ComparisonRelationDeclaration<Common::ComparisonRelationType::eEquals> { using value_type = SimpleClassWithoutComparisonOperators; bool operator() (const value_type& v1, const value_type& v2) const { return v1.GetValue () == v2.GetValue (); } }; DoTestForConcreteContainer_<Mapping<size_t, size_t>> (); DoTestForConcreteContainer_<Mapping<SimpleClass, SimpleClass>> (); DoTestForConcreteContainer_<Mapping<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators>> ( [] () { return Mapping<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators> (MySimpleClassWithoutComparisonOperators_ComparerWithEquals_{}); }, MySimpleClassWithoutComparisonOperators_ComparerWithEquals_{}); DoTestForConcreteContainer_<Mapping_Array<size_t, size_t>> (); DoTestForConcreteContainer_<Mapping_Array<SimpleClass, SimpleClass>> (); DoTestForConcreteContainer_<Mapping_Array<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators>> ( [] () { return Mapping_Array<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators> (MySimpleClassWithoutComparisonOperators_ComparerWithEquals_{}); }, MySimpleClassWithoutComparisonOperators_ComparerWithEquals_{}); DoTestForConcreteContainer_<Mapping_LinkedList<size_t, size_t>> (); DoTestForConcreteContainer_<Mapping_LinkedList<SimpleClass, SimpleClass>> (); // DoTestForConcreteContainer_AllTestsWhichDontRequireComparer_For_Type_<Mapping_LinkedList<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators_MappingTRAITS>> (); DoTestForConcreteContainer_<Mapping_LinkedList<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators>> ( [] () { return Mapping_LinkedList<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators> (MySimpleClassWithoutComparisonOperators_ComparerWithEquals_{}); }, MySimpleClassWithoutComparisonOperators_ComparerWithEquals_{}); DoTestForConcreteContainer_<Mapping_stdmap<size_t, size_t>> (); DoTestForConcreteContainer_<Mapping_stdmap<SimpleClass, SimpleClass>> (); { struct MySimpleClassWithoutComparisonOperators_ComparerWithLess_ : Common::ComparisonRelationDeclaration<Common::ComparisonRelationType::eStrictInOrder> { using value_type = SimpleClassWithoutComparisonOperators; bool operator() (const value_type& v1, const value_type& v2) const { return v1.GetValue () < v2.GetValue (); } }; DoTestForConcreteContainer_<Mapping_stdmap<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators>> ( [] () { return Mapping_stdmap<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators> (MySimpleClassWithoutComparisonOperators_ComparerWithLess_{}); }, //Common::mkEqualsComparerAdapter (MySimpleClassWithoutComparisonOperators_ComparerWithLess_{}) MySimpleClassWithoutComparisonOperators_ComparerWithEquals_{}); } Test2_SimpleBaseClassConversionTraitsConfusion_ (); //Test3_SimpleMappingTest_WhichRequiresExplcitValueComparer (); Test4_MappingCTOROverloads_::DoIt (); ExampleCTORS_Test_5_::DoTest (); Where_Test_6_::DoAll (); WithKeys_Test_7_::DoAll (); ClearBug_Test_8_::DoAll (); } } int main ([[maybe_unused]] int argc, [[maybe_unused]] const char* argv[]) { Stroika::TestHarness::Setup (); return Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_); } <commit_msg>Added mapping AddVsAddIf_Test_9 test<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved */ // TEST Foundation::Containers::Mapping // STATUS Alpha-Late #include "Stroika/Foundation/StroikaPreComp.h" #include <iostream> #include <sstream> #include "Stroika/Foundation/Containers/Collection.h" #include "Stroika/Foundation/Containers/Concrete/Mapping_Array.h" #include "Stroika/Foundation/Containers/Concrete/Mapping_LinkedList.h" #include "Stroika/Foundation/Containers/Concrete/Mapping_stdmap.h" #include "Stroika/Foundation/Containers/Concrete/SortedMapping_stdmap.h" #include "Stroika/Foundation/Containers/Mapping.h" #include "Stroika/Foundation/Debug/Assertions.h" #include "Stroika/Foundation/Debug/Trace.h" #include "../TestCommon/CommonTests_Mapping.h" #include "../TestHarness/SimpleClass.h" #include "../TestHarness/TestHarness.h" using namespace Stroika; using namespace Stroika::Foundation; using namespace Stroika::Foundation::Containers; using Concrete::Mapping_Array; using Concrete::Mapping_LinkedList; using Concrete::Mapping_stdmap; namespace { template <typename CONCRETE_CONTAINER> void DoTestForConcreteContainer_ () { using namespace CommonTests::MappingTests; SimpleMappingTest_All_ (DEFAULT_TESTING_SCHEMA<CONCRETE_CONTAINER>{}); SimpleMappingTest_WithDefaultEqCompaerer_ (DEFAULT_TESTING_SCHEMA<CONCRETE_CONTAINER>{}); } template <typename CONCRETE_CONTAINER, typename FACTORY, typename VALUE_EQUALS_COMPARER_TYPE> void DoTestForConcreteContainer_ (FACTORY factory, VALUE_EQUALS_COMPARER_TYPE valueEqualsComparer) { using namespace CommonTests::MappingTests; auto testschema = DEFAULT_TESTING_SCHEMA<CONCRETE_CONTAINER, FACTORY, VALUE_EQUALS_COMPARER_TYPE>{factory, valueEqualsComparer}; SimpleMappingTest_All_ (testschema); } } namespace { void Test2_SimpleBaseClassConversionTraitsConfusion_ () { Debug::TraceContextBumper ctx{L"{}::Test2_SimpleBaseClassConversionTraitsConfusion_"}; SortedMapping<int, float> xxxyy = Concrete::SortedMapping_stdmap<int, float> (); Mapping<int, float> xxxyy1 = Concrete::Mapping_stdmap<int, float> (); } } namespace { namespace Test4_MappingCTOROverloads_ { namespace xPrivate_ { struct A; struct B; struct A { A () = default; A (const A&) = default; A (const B&) {} }; struct B { B () = default; B (const A&) {} B (const B&) = default; }; using Common::KeyValuePair; using KEY_TYPE = int; using VALUE_TYPE = B; using CONTAINER_OF_PAIR_KEY_T = Mapping<int, A>; using T = KeyValuePair<KEY_TYPE, VALUE_TYPE>; } void DoIt () { Debug::TraceContextBumper ctx{L"{}::Test4_MappingCTOROverloads_"}; using namespace xPrivate_; Mapping<int, A> from; static_assert (Configuration::IsIterableOfT_v<Mapping<int, A>, KeyValuePair<int, A>>); static_assert (Configuration::IsIterableOfT_v<Mapping<int, B>, KeyValuePair<int, B>>); Mapping<int, B> to1; for (auto i : from) { to1.Add (i); } Mapping<int, B> to2{from}; } } } namespace { namespace ExampleCTORS_Test_5_ { void DoTest () { Debug::TraceContextBumper ctx{L"{}::ExampleCTORS_Test_5_"}; // From Mapping<> CTOR docs Collection<pair<int, int>> c; std::map<int, int> m; Mapping<int, int> m1 = {pair<int, int>{1, 1}, pair<int, int>{2, 2}, pair<int, int>{3, 2}}; Mapping<int, int> m2 = m1; Mapping<int, int> m3{m1}; Mapping<int, int> m4{m1.begin (), m1.end ()}; Mapping<int, int> m5{c}; Mapping<int, int> m6{m}; Mapping<int, int> m7{m.begin (), m.end ()}; Mapping<int, int> m8{move (m1)}; Mapping<int, int> m9{Common::DeclareEqualsComparer ([] (int l, int r) { return l == r; })}; } } } namespace { namespace Where_Test_6_ { void DoAll () { Mapping<int, int> m{KeyValuePair<int, int>{1, 3}, KeyValuePair<int, int>{2, 4}, KeyValuePair<int, int>{3, 5}, KeyValuePair<int, int>{4, 5}, KeyValuePair<int, int>{5, 7}}; VerifyTestResult ((m.Where ([] (const KeyValuePair<int, int>& value) { return Math::IsPrime (value.fKey); }) == Mapping<int, int>{KeyValuePair<int, int>{2, 4}, KeyValuePair<int, int>{3, 5}, KeyValuePair<int, int>{5, 7}})); VerifyTestResult ((m.Where ([] (int key) { return Math::IsPrime (key); }) == Mapping<int, int>{KeyValuePair<int, int>{2, 4}, KeyValuePair<int, int>{3, 5}, KeyValuePair<int, int>{5, 7}})); } } } namespace { namespace WithKeys_Test_7_ { void DoAll () { Mapping<int, int> m{KeyValuePair<int, int>{1, 3}, KeyValuePair<int, int>{2, 4}, KeyValuePair<int, int>{3, 5}, KeyValuePair<int, int>{4, 5}, KeyValuePair<int, int>{5, 7}}; VerifyTestResult ((m.WithKeys (initializer_list<int>{2, 5}) == Mapping<int, int>{KeyValuePair<int, int>{2, 4}, KeyValuePair<int, int>{5, 7}})); } } } namespace { namespace ClearBug_Test_8_ { void DoAll () { // https://stroika.atlassian.net/browse/STK-541 Mapping<int, int> m{KeyValuePair<int, int>{1, 3}, KeyValuePair<int, int>{2, 4}, KeyValuePair<int, int>{3, 5}, KeyValuePair<int, int>{4, 5}, KeyValuePair<int, int>{5, 7}}; Mapping<int, int> mm{move (m)}; m.clear (); } } } namespace { namespace AddVsAddIf_Test_9_ { void DoAll () { { Mapping<int, int> m; m.Add (1,2); VerifyTestResult (m[1] == 2); m.Add (1,3); VerifyTestResult (m[1] == 3); VerifyTestResult (not m.AddIf (1,4)); VerifyTestResult (m[1] == 3); VerifyTestResult (m.AddIf (2,3)); VerifyTestResult (m[2] == 3); } } } } namespace { void DoRegressionTests_ () { struct MySimpleClassWithoutComparisonOperators_ComparerWithEquals_ : Common::ComparisonRelationDeclaration<Common::ComparisonRelationType::eEquals> { using value_type = SimpleClassWithoutComparisonOperators; bool operator() (const value_type& v1, const value_type& v2) const { return v1.GetValue () == v2.GetValue (); } }; DoTestForConcreteContainer_<Mapping<size_t, size_t>> (); DoTestForConcreteContainer_<Mapping<SimpleClass, SimpleClass>> (); DoTestForConcreteContainer_<Mapping<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators>> ( [] () { return Mapping<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators> (MySimpleClassWithoutComparisonOperators_ComparerWithEquals_{}); }, MySimpleClassWithoutComparisonOperators_ComparerWithEquals_{}); DoTestForConcreteContainer_<Mapping_Array<size_t, size_t>> (); DoTestForConcreteContainer_<Mapping_Array<SimpleClass, SimpleClass>> (); DoTestForConcreteContainer_<Mapping_Array<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators>> ( [] () { return Mapping_Array<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators> (MySimpleClassWithoutComparisonOperators_ComparerWithEquals_{}); }, MySimpleClassWithoutComparisonOperators_ComparerWithEquals_{}); DoTestForConcreteContainer_<Mapping_LinkedList<size_t, size_t>> (); DoTestForConcreteContainer_<Mapping_LinkedList<SimpleClass, SimpleClass>> (); // DoTestForConcreteContainer_AllTestsWhichDontRequireComparer_For_Type_<Mapping_LinkedList<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators_MappingTRAITS>> (); DoTestForConcreteContainer_<Mapping_LinkedList<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators>> ( [] () { return Mapping_LinkedList<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators> (MySimpleClassWithoutComparisonOperators_ComparerWithEquals_{}); }, MySimpleClassWithoutComparisonOperators_ComparerWithEquals_{}); DoTestForConcreteContainer_<Mapping_stdmap<size_t, size_t>> (); DoTestForConcreteContainer_<Mapping_stdmap<SimpleClass, SimpleClass>> (); { struct MySimpleClassWithoutComparisonOperators_ComparerWithLess_ : Common::ComparisonRelationDeclaration<Common::ComparisonRelationType::eStrictInOrder> { using value_type = SimpleClassWithoutComparisonOperators; bool operator() (const value_type& v1, const value_type& v2) const { return v1.GetValue () < v2.GetValue (); } }; DoTestForConcreteContainer_<Mapping_stdmap<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators>> ( [] () { return Mapping_stdmap<SimpleClassWithoutComparisonOperators, SimpleClassWithoutComparisonOperators> (MySimpleClassWithoutComparisonOperators_ComparerWithLess_{}); }, //Common::mkEqualsComparerAdapter (MySimpleClassWithoutComparisonOperators_ComparerWithLess_{}) MySimpleClassWithoutComparisonOperators_ComparerWithEquals_{}); } Test2_SimpleBaseClassConversionTraitsConfusion_ (); //Test3_SimpleMappingTest_WhichRequiresExplcitValueComparer (); Test4_MappingCTOROverloads_::DoIt (); ExampleCTORS_Test_5_::DoTest (); Where_Test_6_::DoAll (); WithKeys_Test_7_::DoAll (); ClearBug_Test_8_::DoAll (); AddVsAddIf_Test_9_::DoAll (); } } int main ([[maybe_unused]] int argc, [[maybe_unused]] const char* argv[]) { Stroika::TestHarness::Setup (); return Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_); } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved */ // TEST Foundation::Execution::Exceptions #include "Stroika/Foundation/StroikaPreComp.h" #include <iostream> #include <sstream> #if qPlatform_Windows #include <Windows.h> #include <winerror.h> #include <wininet.h> // for error codes #endif #include "Stroika/Foundation/Characters/ToString.h" #include "Stroika/Foundation/Debug/BackTrace.h" #include "Stroika/Foundation/Debug/Trace.h" #include "Stroika/Foundation/Execution/Exceptions.h" #include "Stroika/Foundation/Execution/TimeOutException.h" #if qPlatform_Windows #include "Stroika/Foundation/Execution/Platform/Windows/Exception.h" #endif #include "../TestHarness/TestHarness.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Execution; namespace { void Test2_ThrowCatchStringException_ () { Debug::TraceContextBumper ctx{L"Test2_ThrowCatchStringException_"}; { try { Throw (Exception (L"HiMom")); VerifyTestResult (false); } catch (const Exception<>& e) { VerifyTestResult (e.As<wstring> () == L"HiMom"); } } { try { Throw (Exception (L"HiMom")); VerifyTestResult (false); } catch (const std::exception& e) { VerifyTestResult (strcmp (e.what (), "HiMom") == 0); } } } } namespace { namespace Test3_SystemErrorException_ { namespace Private_ { void T1_system_error_ () { static const int kErr2TestFor_ = make_error_code (errc::bad_address).value (); // any value from errc would do static const Characters::String kErr2TestForExpectedMsg_ = L"bad address {errno: 14}"sv; // maybe not always right due to locales? try { ThrowPOSIXErrNo (kErr2TestFor_); } catch (const std::system_error& e) { VerifyTestResult (e.code ().value () == kErr2TestFor_); VerifyTestResult (e.code ().category () == system_category () or e.code ().category () == generic_category ()); VerifyTestResult (Characters::ToString (e).Contains (kErr2TestForExpectedMsg_, Characters::CompareOptions::eCaseInsensitive)); } catch (...) { DbgTrace (L"err=%s", Characters::ToString (current_exception ()).c_str ()); VerifyTestResult (false); //oops } // and test throwing fancy unicode string const Characters::String kMsgWithUnicode_ = L"zß水𝄋"; // this works even if using a code page / locale which doesn't support UNICODE/Chinese try { Execution::Throw (SystemErrorException (kErr2TestFor_, generic_category (), kMsgWithUnicode_)); } catch (const std::system_error& e) { VerifyTestResult (e.code ().value () == kErr2TestFor_); VerifyTestResult (e.code ().category () == generic_category ()); VerifyTestResult (Characters::ToString (e).Contains (kMsgWithUnicode_, Characters::CompareOptions::eCaseInsensitive)); } catch (...) { DbgTrace (L"err=%s", Characters::ToString (current_exception ()).c_str ()); VerifyTestResult (false); //oops } } void T2_TestTimeout_ () { try { Execution::Throw (Execution::TimeOutException{}); } catch (const system_error& e) { VerifyTestResult (e.code () == errc::timed_out); VerifyTestResult (e.code () != errc::already_connected); } catch (...) { DbgTrace (L"err=%s", Characters::ToString (current_exception ()).c_str ()); VerifyTestResult (false); //oops } try { Execution::Throw (Execution::TimeOutException{}); } catch (const Execution::TimeOutException& e) { VerifyTestResult (e.code () == errc::timed_out); VerifyTestResult (e.code () != errc::already_connected); } catch (...) { DbgTrace (L"err=%s", Characters::ToString (current_exception ()).c_str ()); VerifyTestResult (false); //oops } const Characters::String kMsg1_ = L"to abcd 123 zß水𝄋"; try { Execution::Throw (Execution::TimeOutException{kMsg1_}); } catch (const system_error& e) { VerifyTestResult (e.code () == errc::timed_out); VerifyTestResult (e.code () != errc::already_connected); VerifyTestResult (Characters::ToString (e).Contains (kMsg1_)); } catch (...) { DbgTrace (L"err=%s", Characters::ToString (current_exception ()).c_str ()); VerifyTestResult (false); //oops } } } void TestAll_ () { Debug::TraceContextBumper ctx{L"Test3_SystemErrorException_"}; Private_::T1_system_error_ (); Private_::T2_TestTimeout_ (); } } } namespace { namespace Test4_Activities_ { namespace Private { void T1_Basics_ () { using Characters::String; String argument; [[maybe_unused]] static constexpr Activity kBuildingThingy_{L"Building thingy"sv}; // constexpr only works if we lose the virtual in ~AsStringObj_ () static constexpr const auto kA1_{Activity<wstring_view>{L"a1"sv}}; static const auto kOtherActivity = Activity<String>{L"kOtherActivity"}; // automatic variable activity OK as long as it's lifetime longer than reference in DeclareActivity auto otherActivity = Activity<String>{L"otherActivity" + argument}; // activities can be stack based, but these cost more to define auto lazyEvalActivity = LazyEvalActivity ([&] () -> String { return argument.Repeat (5) + L"xxx"; }); DeclareActivity active1{&kA1_}; DeclareActivity active2{&kOtherActivity}; DeclareActivity active3{&otherActivity}; DeclareActivity active4{&lazyEvalActivity}; try { // something that will throw Execution::Throw (Exception<> (L"testing 123")); } catch (...) { String msg = Characters::ToString (current_exception ()); VerifyTestResult (msg.Contains (L"testing 123")); VerifyTestResult (msg.Contains (L"a1")); VerifyTestResult (msg.Contains (L"kOtherActivity")); VerifyTestResult (msg.Contains (L"otherActivity")); VerifyTestResult (msg.Contains (L"xxx")); } } } void TestAll_ () { Debug::TraceContextBumper ctx{L"Test4_Activities_"}; Private::T1_Basics_ (); } } } namespace { namespace Test5_error_code_condition_compares_ { namespace Private { void Bug1_ () { try { throw std::system_error (ENOENT, std::system_category ()); } catch (std::system_error const& e) { VerifyTestResult (e.code ().value() == static_cast<int> (std::errc::no_such_file_or_directory)); // workaround? #if !qCompilerAndStdLib_error_code_compare_condition_Buggy VerifyTestResult (e.code () == std::errc::no_such_file_or_directory); // <- FAILS!? #endif } catch (...) { VerifyTestResult (false); } } #if qPlatform_Windows void Bug2_Windows_Errors_Mapped_To_Conditions_ () { VerifyTestResult ((error_code{ERROR_NOT_ENOUGH_MEMORY, system_category ()} == errc::not_enough_memory)); VerifyTestResult ((error_code{ERROR_OUTOFMEMORY, system_category ()} == errc::not_enough_memory)); #if qCompilerAndStdLib_Winerror_map_doesnt_map_timeout_Buggy if ((error_code{WAIT_TIMEOUT, system_category ()} == errc::timed_out)) { DbgTrace (L"FIXED - qCompilerAndStdLib_Winerror_map_doesnt_map_timeout_Buggy"); } if ((error_code{ERROR_INTERNET_TIMEOUT, system_category ()} == errc::timed_out)) { DbgTrace (L"FIXED"); } #else VerifyTestResult ((error_code{WAIT_TIMEOUT, system_category ()} == errc::timed_out)); VerifyTestResult ((error_code{ERROR_INTERNET_TIMEOUT, system_category ()} == errc::timed_out)); #endif try { ThrowSystemErrNo (ERROR_NOT_ENOUGH_MEMORY); } catch (const bad_alloc&) { // Good } catch (...) { VerifyTestResult (false); } try { ThrowSystemErrNo (ERROR_OUTOFMEMORY); } catch (const bad_alloc&) { // Good } catch (...) { VerifyTestResult (false); } try { ThrowSystemErrNo (WAIT_TIMEOUT); } catch (const TimeOutException&) { // Good } catch (...) { VerifyTestResult (false); } try { ThrowSystemErrNo (ERROR_INTERNET_TIMEOUT); } catch (const TimeOutException&) { // Good } catch (...) { VerifyTestResult (false); } } #endif } void TestAll_ () { Debug::TraceContextBumper ctx{L"Test5_error_code_condition_compares_"}; Private::Bug1_ (); #if qPlatform_Windows Private::Bug2_Windows_Errors_Mapped_To_Conditions_ (); #endif } } } namespace { namespace Test6_Throw_Logging_with_and_without_srclines_in_stack_backtrace_ { namespace Private { void ThrowCatchStringException_ () { Debug::TraceContextBumper ctx{L"ThrowCatchStringException_"}; { try { Throw (Exception (L"HiMom")); VerifyTestResult (false); } catch (const Exception<>& e) { VerifyTestResult (e.As<wstring> () == L"HiMom"); } } { try { Throw (Exception (L"HiMom")); VerifyTestResult (false); } catch (const std::exception& e) { VerifyTestResult (strcmp (e.what (), "HiMom") == 0); } } } } void TestAll_ () { Debug::TraceContextBumper ctx{L"Test6_Throw_Logging_with_and_without_srclines_in_stack_backtrace_"}; auto prevValue = Debug::BackTrace::Options::sDefault_IncludeSourceLines; DbgTrace ("sDefault_IncludeSourceLines = true"); Debug::BackTrace::Options::sDefault_IncludeSourceLines = true; Private::ThrowCatchStringException_ (); DbgTrace ("sDefault_IncludeSourceLines = false"); Debug::BackTrace::Options::sDefault_IncludeSourceLines = false; Private::ThrowCatchStringException_ (); DbgTrace ("sDefault_IncludeSourceLines = <<default>>"); Debug::BackTrace::Options::sDefault_IncludeSourceLines = prevValue; Private::ThrowCatchStringException_ (); } } } namespace { void DoRegressionTests_ () { Debug::TraceContextBumper ctx{L"DoRegressionTests_"}; Test2_ThrowCatchStringException_ (); Test3_SystemErrorException_::TestAll_ (); Test4_Activities_::TestAll_ (); Test5_error_code_condition_compares_::TestAll_ (); Test6_Throw_Logging_with_and_without_srclines_in_stack_backtrace_::TestAll_ (); } } int main ([[maybe_unused]] int argc, [[maybe_unused]] const char* argv[]) { Stroika::TestHarness::Setup (); return Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_); } <commit_msg>added regtest<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved */ // TEST Foundation::Execution::Exceptions #include "Stroika/Foundation/StroikaPreComp.h" #include <iostream> #include <sstream> #if qPlatform_Windows #include <Windows.h> #include <winerror.h> #include <wininet.h> // for error codes #endif #include "Stroika/Foundation/Characters/ToString.h" #include "Stroika/Foundation/Debug/BackTrace.h" #include "Stroika/Foundation/Debug/Trace.h" #include "Stroika/Foundation/Execution/Exceptions.h" #include "Stroika/Foundation/Execution/TimeOutException.h" #if qPlatform_Windows #include "Stroika/Foundation/Execution/Platform/Windows/Exception.h" #endif #include "../TestHarness/TestHarness.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Execution; namespace { void Test2_ThrowCatchStringException_ () { Debug::TraceContextBumper ctx{L"Test2_ThrowCatchStringException_"}; { try { Throw (Exception (L"HiMom")); VerifyTestResult (false); } catch (const Exception<>& e) { VerifyTestResult (e.As<wstring> () == L"HiMom"); } } { try { Throw (Exception (L"HiMom")); VerifyTestResult (false); } catch (const std::exception& e) { VerifyTestResult (strcmp (e.what (), "HiMom") == 0); } } } } namespace { namespace Test3_SystemErrorException_ { namespace Private_ { void T1_system_error_ () { static const int kErr2TestFor_ = make_error_code (errc::bad_address).value (); // any value from errc would do static const Characters::String kErr2TestForExpectedMsg_ = L"bad address {errno: 14}"sv; // maybe not always right due to locales? try { ThrowPOSIXErrNo (kErr2TestFor_); } catch (const std::system_error& e) { VerifyTestResult (e.code ().value () == kErr2TestFor_); VerifyTestResult (e.code ().category () == system_category () or e.code ().category () == generic_category ()); VerifyTestResult (Characters::ToString (e).Contains (kErr2TestForExpectedMsg_, Characters::CompareOptions::eCaseInsensitive)); } catch (...) { DbgTrace (L"err=%s", Characters::ToString (current_exception ()).c_str ()); VerifyTestResult (false); //oops } // and test throwing fancy unicode string const Characters::String kMsgWithUnicode_ = L"zß水𝄋"; // this works even if using a code page / locale which doesn't support UNICODE/Chinese try { Execution::Throw (SystemErrorException (kErr2TestFor_, generic_category (), kMsgWithUnicode_)); } catch (const std::system_error& e) { VerifyTestResult (e.code ().value () == kErr2TestFor_); VerifyTestResult (e.code ().category () == generic_category ()); VerifyTestResult (Characters::ToString (e).Contains (kMsgWithUnicode_, Characters::CompareOptions::eCaseInsensitive)); } catch (...) { DbgTrace (L"err=%s", Characters::ToString (current_exception ()).c_str ()); VerifyTestResult (false); //oops } } void T2_TestTimeout_ () { try { Execution::Throw (Execution::TimeOutException{}); } catch (const system_error& e) { VerifyTestResult (e.code () == errc::timed_out); VerifyTestResult (e.code () != errc::already_connected); } catch (...) { DbgTrace (L"err=%s", Characters::ToString (current_exception ()).c_str ()); VerifyTestResult (false); //oops } try { Execution::Throw (Execution::TimeOutException{}); } catch (const Execution::TimeOutException& e) { VerifyTestResult (e.code () == errc::timed_out); VerifyTestResult (e.code () != errc::already_connected); } catch (...) { DbgTrace (L"err=%s", Characters::ToString (current_exception ()).c_str ()); VerifyTestResult (false); //oops } const Characters::String kMsg1_ = L"to abcd 123 zß水𝄋"; try { Execution::Throw (Execution::TimeOutException{kMsg1_}); } catch (const system_error& e) { VerifyTestResult (e.code () == errc::timed_out); VerifyTestResult (e.code () != errc::already_connected); VerifyTestResult (Characters::ToString (e).Contains (kMsg1_)); } catch (...) { DbgTrace (L"err=%s", Characters::ToString (current_exception ()).c_str ()); VerifyTestResult (false); //oops } } } void TestAll_ () { Debug::TraceContextBumper ctx{L"Test3_SystemErrorException_"}; Private_::T1_system_error_ (); Private_::T2_TestTimeout_ (); } } } namespace { namespace Test4_Activities_ { namespace Private { void T1_Basics_ () { using Characters::String; String argument; [[maybe_unused]] static constexpr Activity kBuildingThingy_{L"Building thingy"sv}; // constexpr only works if we lose the virtual in ~AsStringObj_ () static constexpr const auto kA1_{Activity<wstring_view>{L"a1"sv}}; static const auto kOtherActivity = Activity<String>{L"kOtherActivity"}; // automatic variable activity OK as long as it's lifetime longer than reference in DeclareActivity auto otherActivity = Activity<String>{L"otherActivity" + argument}; // activities can be stack based, but these cost more to define auto lazyEvalActivity = LazyEvalActivity ([&] () -> String { return argument.Repeat (5) + L"xxx"; }); DeclareActivity active1{&kA1_}; DeclareActivity active2{&kOtherActivity}; DeclareActivity active3{&otherActivity}; DeclareActivity active4{&lazyEvalActivity}; try { // something that will throw Execution::Throw (Exception<> (L"testing 123")); } catch (...) { String msg = Characters::ToString (current_exception ()); VerifyTestResult (msg.Contains (L"testing 123")); VerifyTestResult (msg.Contains (L"a1")); VerifyTestResult (msg.Contains (L"kOtherActivity")); VerifyTestResult (msg.Contains (L"otherActivity")); VerifyTestResult (msg.Contains (L"xxx")); } } } void TestAll_ () { Debug::TraceContextBumper ctx{L"Test4_Activities_"}; Private::T1_Basics_ (); } } } namespace { namespace Test5_error_code_condition_compares_ { namespace Private { void Bug1_ () { try { throw std::system_error (ENOENT, std::system_category ()); } catch (std::system_error const& e) { VerifyTestResult (e.code ().value () == static_cast<int> (std::errc::no_such_file_or_directory)); // workaround? #if !qCompilerAndStdLib_error_code_compare_condition_Buggy VerifyTestResult (e.code () == std::errc::no_such_file_or_directory); // <- FAILS!? #endif } catch (...) { VerifyTestResult (false); } } #if qPlatform_Windows void Bug2_Windows_Errors_Mapped_To_Conditions_ () { VerifyTestResult ((error_code{ERROR_NOT_ENOUGH_MEMORY, system_category ()} == errc::not_enough_memory)); VerifyTestResult ((error_code{ERROR_OUTOFMEMORY, system_category ()} == errc::not_enough_memory)); #if qCompilerAndStdLib_Winerror_map_doesnt_map_timeout_Buggy if ((error_code{WAIT_TIMEOUT, system_category ()} == errc::timed_out)) { DbgTrace (L"FIXED - qCompilerAndStdLib_Winerror_map_doesnt_map_timeout_Buggy"); } if ((error_code{ERROR_INTERNET_TIMEOUT, system_category ()} == errc::timed_out)) { DbgTrace (L"FIXED"); } #else VerifyTestResult ((error_code{WAIT_TIMEOUT, system_category ()} == errc::timed_out)); VerifyTestResult ((error_code{ERROR_INTERNET_TIMEOUT, system_category ()} == errc::timed_out)); #endif try { ThrowSystemErrNo (ERROR_NOT_ENOUGH_MEMORY); } catch (const bad_alloc&) { // Good } catch (...) { VerifyTestResult (false); } try { ThrowSystemErrNo (ERROR_OUTOFMEMORY); } catch (const bad_alloc&) { // Good } catch (...) { VerifyTestResult (false); } try { ThrowSystemErrNo (WAIT_TIMEOUT); } catch (const TimeOutException&) { // Good } catch (...) { VerifyTestResult (false); } try { ThrowSystemErrNo (ERROR_INTERNET_TIMEOUT); } catch (const TimeOutException&) { // Good } catch (...) { VerifyTestResult (false); } } #endif } void TestAll_ () { Debug::TraceContextBumper ctx{L"Test5_error_code_condition_compares_"}; Private::Bug1_ (); #if qPlatform_Windows Private::Bug2_Windows_Errors_Mapped_To_Conditions_ (); #endif } } } namespace { namespace Test6_Throw_Logging_with_and_without_srclines_in_stack_backtrace_ { namespace Private { void ThrowCatchStringException_ () { Debug::TraceContextBumper ctx{L"ThrowCatchStringException_"}; { try { Throw (Exception (L"HiMom")); VerifyTestResult (false); } catch (const Exception<>& e) { VerifyTestResult (e.As<wstring> () == L"HiMom"); } } { try { Throw (Exception (L"HiMom")); VerifyTestResult (false); } catch (const std::exception& e) { VerifyTestResult (strcmp (e.what (), "HiMom") == 0); } } } } void TestAll_ () { Debug::TraceContextBumper ctx{L"Test6_Throw_Logging_with_and_without_srclines_in_stack_backtrace_"}; auto prevValue = Debug::BackTrace::Options::sDefault_IncludeSourceLines; DbgTrace ("sDefault_IncludeSourceLines = true"); Debug::BackTrace::Options::sDefault_IncludeSourceLines = true; Private::ThrowCatchStringException_ (); DbgTrace ("sDefault_IncludeSourceLines = false"); Debug::BackTrace::Options::sDefault_IncludeSourceLines = false; Private::ThrowCatchStringException_ (); DbgTrace ("sDefault_IncludeSourceLines = <<default>>"); Debug::BackTrace::Options::sDefault_IncludeSourceLines = prevValue; Private::ThrowCatchStringException_ (); } } } namespace { void DoRegressionTests_ () { Debug::TraceContextBumper ctx{L"DoRegressionTests_"}; Test2_ThrowCatchStringException_ (); Test3_SystemErrorException_::TestAll_ (); Test4_Activities_::TestAll_ (); Test5_error_code_condition_compares_::TestAll_ (); Test6_Throw_Logging_with_and_without_srclines_in_stack_backtrace_::TestAll_ (); } } int main ([[maybe_unused]] int argc, [[maybe_unused]] const char* argv[]) { Stroika::TestHarness::Setup (); return Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_); } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved */ // TEST Foundation::Execution::Exceptions #include "Stroika/Foundation/StroikaPreComp.h" #include <iostream> #include <sstream> #if qPlatform_Windows #include <Windows.h> #include <winerror.h> #include <wininet.h> // for error codes #endif #include "Stroika/Foundation/Characters/ToString.h" #include "Stroika/Foundation/Execution/Exceptions.h" #include "Stroika/Foundation/Execution/TimeOutException.h" #if qPlatform_Windows #include "Stroika/Foundation/Execution/Platform/Windows/Exception.h" #endif #include "../TestHarness/TestHarness.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Execution; namespace { void RegressionTest1_ () { #if qPlatform_Windows VerifyTestResult (Platform::Windows::Exception::kERROR_INTERNET_TIMEOUT == ERROR_INTERNET_TIMEOUT); VerifyTestResult (Platform::Windows::Exception::kERROR_INTERNET_INVALID_URL == ERROR_INTERNET_INVALID_URL); VerifyTestResult (Platform::Windows::Exception::kERROR_INTERNET_UNRECOGNIZED_SCHEME == ERROR_INTERNET_UNRECOGNIZED_SCHEME); VerifyTestResult (Platform::Windows::Exception::kERROR_INTERNET_NAME_NOT_RESOLVED == ERROR_INTERNET_NAME_NOT_RESOLVED); VerifyTestResult (Platform::Windows::Exception::kERROR_INTERNET_PROTOCOL_NOT_FOUND == ERROR_INTERNET_PROTOCOL_NOT_FOUND); VerifyTestResult (Platform::Windows::Exception::kERROR_INTERNET_CANNOT_CONNECT == ERROR_INTERNET_CANNOT_CONNECT); #endif } } namespace { void Test2_ThrowCatchStringException_ () { { try { Throw (Exception (L"HiMom")); VerifyTestResult (false); } catch (const Exception<>& e) { VerifyTestResult (e.As<wstring> () == L"HiMom"); } } { try { Throw (Exception (L"HiMom")); VerifyTestResult (false); } catch (const std::exception& e) { VerifyTestResult (strcmp (e.what (), "HiMom") == 0); } } } } namespace { namespace Test3_SystemException_ { namespace Private_ { void T1_system_error_ () { static const int kErr2TestFor_ = make_error_code (errc::bad_address).value (); // any value from errc would do Characters::String msg1; static const Characters::String kErr2TestForExpectedMsg_ = L"bad address {errno: 14}"sv; // maybe not always right due to locales? // One way try { SystemException::ThrowPOSIXErrNo (kErr2TestFor_); } catch (const Execution::SystemException& e) { VerifyTestResult (e.code ().value () == kErr2TestFor_); VerifyTestResult (e.code ().category () == system_category () or e.code ().category () == generic_category ()); msg1 = Characters::ToString (e); VerifyTestResult (msg1 == kErr2TestForExpectedMsg_); } catch (...) { DbgTrace (L"err=%s", Characters::ToString (current_exception ()).c_str ()); VerifyTestResult (false); //oops } // But this works too try { SystemException::ThrowPOSIXErrNo (kErr2TestFor_); } catch (const std::system_error& e) { VerifyTestResult (e.code ().value () == kErr2TestFor_); VerifyTestResult (e.code ().category () == system_category () or e.code ().category () == generic_category ()); VerifyTestResult (msg1 == Characters::ToString (e)); } catch (...) { DbgTrace (L"err=%s", Characters::ToString (current_exception ()).c_str ()); VerifyTestResult (false); //oops } // and test throwing fancy unicode string const Characters::String kMsgWithUnicode_ = L"zß水𝄋"; // this works even if using a code page / locale which doesn't support UNICODE/Chinese try { Execution::Throw (SystemException (kErr2TestFor_, generic_category (), kMsgWithUnicode_)); } catch (const std::system_error& e) { VerifyTestResult (e.code ().value () == kErr2TestFor_); VerifyTestResult (e.code ().category () == generic_category ()); VerifyTestResult (Characters::ToString (e).Contains (kMsgWithUnicode_)); } catch (...) { DbgTrace (L"err=%s", Characters::ToString (current_exception ()).c_str ()); VerifyTestResult (false); //oops } } void T2_TestTimeout_ () { try { Execution::Throw (Execution::TimeOutException{}); } catch (const system_error& e) { VerifyTestResult (e.code () == errc::timed_out); VerifyTestResult (e.code () != errc::already_connected); } catch (...) { DbgTrace (L"err=%s", Characters::ToString (current_exception ()).c_str ()); VerifyTestResult (false); //oops } try { Execution::Throw (Execution::TimeOutException{}); } catch (const Execution::TimeOutException& e) { VerifyTestResult (e.code () == errc::timed_out); VerifyTestResult (e.code () != errc::already_connected); } catch (...) { DbgTrace (L"err=%s", Characters::ToString (current_exception ()).c_str ()); VerifyTestResult (false); //oops } const Characters::String kMsg1_ = L"to abcd 123 zß水𝄋"; try { Execution::Throw (Execution::TimeOutException{kMsg1_}); } catch (const system_error& e) { VerifyTestResult (e.code () == errc::timed_out); VerifyTestResult (e.code () != errc::already_connected); VerifyTestResult (Characters::ToString (e).Contains (kMsg1_)); } catch (...) { DbgTrace (L"err=%s", Characters::ToString (current_exception ()).c_str ()); VerifyTestResult (false); //oops } } } void TestAll_ () { Private_::T1_system_error_ (); Private_::T2_TestTimeout_ (); } } } namespace { void DoRegressionTests_ () { RegressionTest1_ (); Test2_ThrowCatchStringException_ (); Test3_SystemException_::TestAll_ (); } } int main ([[maybe_unused]] int argc, [[maybe_unused]] const char* argv[]) { Stroika::TestHarness::Setup (); return Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_); } <commit_msg>fixed typo<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved */ // TEST Foundation::Execution::Exceptions #include "Stroika/Foundation/StroikaPreComp.h" #include <iostream> #include <sstream> #if qPlatform_Windows #include <Windows.h> #include <winerror.h> #include <wininet.h> // for error codes #endif #include "Stroika/Foundation/Characters/ToString.h" #include "Stroika/Foundation/Execution/Exceptions.h" #include "Stroika/Foundation/Execution/TimeOutException.h" #if qPlatform_Windows #include "Stroika/Foundation/Execution/Platform/Windows/Exception.h" #endif #include "../TestHarness/TestHarness.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Execution; namespace { void RegressionTest1_ () { #if qPlatform_Windows VerifyTestResult (Platform::Windows::Exception::kERROR_INTERNET_TIMEOUT == ERROR_INTERNET_TIMEOUT); VerifyTestResult (Platform::Windows::Exception::kERROR_INTERNET_INVALID_URL == ERROR_INTERNET_INVALID_URL); VerifyTestResult (Platform::Windows::Exception::kERROR_INTERNET_UNRECOGNIZED_SCHEME == ERROR_INTERNET_UNRECOGNIZED_SCHEME); VerifyTestResult (Platform::Windows::Exception::kERROR_INTERNET_NAME_NOT_RESOLVED == ERROR_INTERNET_NAME_NOT_RESOLVED); VerifyTestResult (Platform::Windows::Exception::kERROR_INTERNET_PROTOCOL_NOT_FOUND == ERROR_INTERNET_PROTOCOL_NOT_FOUND); VerifyTestResult (Platform::Windows::Exception::kERROR_INTERNET_CANNOT_CONNECT == ERROR_INTERNET_CANNOT_CONNECT); #endif } } namespace { void Test2_ThrowCatchStringException_ () { { try { Throw (Exception (L"HiMom")); VerifyTestResult (false); } catch (const Exception<>& e) { VerifyTestResult (e.As<wstring> () == L"HiMom"); } } { try { Throw (Exception (L"HiMom")); VerifyTestResult (false); } catch (const std::exception& e) { VerifyTestResult (strcmp (e.what (), "HiMom") == 0); } } } } namespace { namespace Test3_SystemErrorException_ { namespace Private_ { void T1_system_error_ () { static const int kErr2TestFor_ = make_error_code (errc::bad_address).value (); // any value from errc would do Characters::String msg1; static const Characters::String kErr2TestForExpectedMsg_ = L"bad address {errno: 14}"sv; // maybe not always right due to locales? // One way try { SystemErrorException::ThrowPOSIXErrNo (kErr2TestFor_); } catch (const Execution::SystemErrorException& e) { VerifyTestResult (e.code ().value () == kErr2TestFor_); VerifyTestResult (e.code ().category () == system_category () or e.code ().category () == generic_category ()); msg1 = Characters::ToString (e); VerifyTestResult (msg1 == kErr2TestForExpectedMsg_); } catch (...) { DbgTrace (L"err=%s", Characters::ToString (current_exception ()).c_str ()); VerifyTestResult (false); //oops } // But this works too try { SystemErrorException::ThrowPOSIXErrNo (kErr2TestFor_); } catch (const std::system_error& e) { VerifyTestResult (e.code ().value () == kErr2TestFor_); VerifyTestResult (e.code ().category () == system_category () or e.code ().category () == generic_category ()); VerifyTestResult (msg1 == Characters::ToString (e)); } catch (...) { DbgTrace (L"err=%s", Characters::ToString (current_exception ()).c_str ()); VerifyTestResult (false); //oops } // and test throwing fancy unicode string const Characters::String kMsgWithUnicode_ = L"zß水𝄋"; // this works even if using a code page / locale which doesn't support UNICODE/Chinese try { Execution::Throw (SystemErrorException (kErr2TestFor_, generic_category (), kMsgWithUnicode_)); } catch (const std::system_error& e) { VerifyTestResult (e.code ().value () == kErr2TestFor_); VerifyTestResult (e.code ().category () == generic_category ()); VerifyTestResult (Characters::ToString (e).Contains (kMsgWithUnicode_)); } catch (...) { DbgTrace (L"err=%s", Characters::ToString (current_exception ()).c_str ()); VerifyTestResult (false); //oops } } void T2_TestTimeout_ () { try { Execution::Throw (Execution::TimeOutException{}); } catch (const system_error& e) { VerifyTestResult (e.code () == errc::timed_out); VerifyTestResult (e.code () != errc::already_connected); } catch (...) { DbgTrace (L"err=%s", Characters::ToString (current_exception ()).c_str ()); VerifyTestResult (false); //oops } try { Execution::Throw (Execution::TimeOutException{}); } catch (const Execution::TimeOutException& e) { VerifyTestResult (e.code () == errc::timed_out); VerifyTestResult (e.code () != errc::already_connected); } catch (...) { DbgTrace (L"err=%s", Characters::ToString (current_exception ()).c_str ()); VerifyTestResult (false); //oops } const Characters::String kMsg1_ = L"to abcd 123 zß水𝄋"; try { Execution::Throw (Execution::TimeOutException{kMsg1_}); } catch (const system_error& e) { VerifyTestResult (e.code () == errc::timed_out); VerifyTestResult (e.code () != errc::already_connected); VerifyTestResult (Characters::ToString (e).Contains (kMsg1_)); } catch (...) { DbgTrace (L"err=%s", Characters::ToString (current_exception ()).c_str ()); VerifyTestResult (false); //oops } } } void TestAll_ () { Private_::T1_system_error_ (); Private_::T2_TestTimeout_ (); } } } namespace { void DoRegressionTests_ () { RegressionTest1_ (); Test2_ThrowCatchStringException_ (); Test3_SystemErrorException_::TestAll_ (); } } int main ([[maybe_unused]] int argc, [[maybe_unused]] const char* argv[]) { Stroika::TestHarness::Setup (); return Stroika::TestHarness::PrintPassOrFail (DoRegressionTests_); } <|endoftext|>
<commit_before>#include "Payment.h" #include <string.h> void PrintUsage(char *name) { cout << name << " <rate> <nper> <pmt> [pv] [type]" << endl; } int main(int argc, char *argv[]) { if (argc >= 4) { double rate = atof(argv[1]); int nper = atoi(argv[2]); double pv = atof(argv[3]); double fv = 0; int type = DueAtEnd; if (argc >= 5) fv = atof(argv[4]); if (argc >= 6) type = atoi(argv[5]); cout << fixed; cout.precision(2); cout << Payment(rate, nper, pv, fv, type) << endl; return 0; } else { PrintUsage(argv[0]); return 1; } } <commit_msg>Modify the PMT usage<commit_after>#include "Payment.h" #include <string.h> void PrintUsage(char *name) { cout << name << " <rate> <nper> <pv> [fv] [type]" << endl; } int main(int argc, char *argv[]) { if (argc >= 4) { double rate = atof(argv[1]); int nper = atoi(argv[2]); double pv = atof(argv[3]); double fv = 0; int type = DueAtEnd; if (argc >= 5) fv = atof(argv[4]); if (argc >= 6) type = atoi(argv[5]); cout << fixed; cout.precision(2); cout << Payment(rate, nper, pv, fv, type) << endl; return 0; } else { PrintUsage(argv[0]); return 1; } } <|endoftext|>
<commit_before>#include "clunk_ex.h" #include <errno.h> #include <stdio.h> #include <string.h> void clunk::Exception::add_message(const char *file, int line) { char buf[1024]; snprintf(buf, sizeof(buf), "[%s:%d] ", file, line); message += buf; } void clunk::Exception::add_message(const std::string &msg) { message += msg; message += ' '; } void clunk::IOException::add_custom_message() { char buf[1024]; memset(buf, 0, sizeof(buf)); #ifdef _WINDOWS strncpy(buf, _strerror(NULL), sizeof(buf)); #else strncpy(buf, strerror(errno), sizeof(buf)); // if (strerror_r(errno, buf, sizeof(buf)-1) != 0) perror("strerror"); #endif add_message(buf); } <commit_msg>defined snprinf for windows<commit_after>#include "clunk_ex.h" #include <errno.h> #include <stdio.h> #include <string.h> #if defined _WINDOWS # ifndef snprintf # define snprintf _snprintf # endif #endif void clunk::Exception::add_message(const char *file, int line) { char buf[1024]; snprintf(buf, sizeof(buf), "[%s:%d] ", file, line); message += buf; } void clunk::Exception::add_message(const std::string &msg) { message += msg; message += ' '; } void clunk::IOException::add_custom_message() { char buf[1024]; memset(buf, 0, sizeof(buf)); #ifdef _WINDOWS strncpy(buf, _strerror(NULL), sizeof(buf)); #else strncpy(buf, strerror(errno), sizeof(buf)); // if (strerror_r(errno, buf, sizeof(buf)-1) != 0) perror("strerror"); #endif add_message(buf); } <|endoftext|>
<commit_before>#include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/io/pcd_io.h> #include <pcl/visualization/pcl_visualizer.h> #include <pcl/surface/on_nurbs/fitting_surface_tdm.h> #include <pcl/surface/on_nurbs/fitting_curve_2d_asdm.h> #include <pcl/surface/on_nurbs/triangulation.h> typedef pcl::PointXYZ Point; void PointCloud2Vector3d (pcl::PointCloud<Point>::Ptr cloud, pcl::on_nurbs::vector_vec3d &data) { for (unsigned i = 0; i < cloud->size (); i++) { Point &p = cloud->at (i); if (!pcl_isnan (p.x) && !pcl_isnan (p.y) && !pcl_isnan (p.z)) data.push_back (Eigen::Vector3d (p.x, p.y, p.z)); } } void visualizeCurve (ON_NurbsCurve &curve, ON_NurbsSurface &surface, pcl::visualization::PCLVisualizer &viewer) { pcl::PointCloud<pcl::PointXYZRGB>::Ptr curve_cloud (new pcl::PointCloud<pcl::PointXYZRGB>); pcl::on_nurbs::Triangulation::convertCurve2PointCloud (curve, surface, curve_cloud, 4); for (std::size_t i = 0; i < curve_cloud->size () - 1; i++) { pcl::PointXYZRGB &p1 = curve_cloud->at (i); pcl::PointXYZRGB &p2 = curve_cloud->at (i + 1); std::ostringstream os; os << "line" << i; viewer.removeShape (os.str ()); viewer.addLine<pcl::PointXYZRGB> (p1, p2, 1.0, 0.0, 0.0, os.str ()); } pcl::PointCloud<pcl::PointXYZRGB>::Ptr curve_cps (new pcl::PointCloud<pcl::PointXYZRGB>); for (int i = 0; i < curve.CVCount (); i++) { ON_3dPoint p1; curve.GetCV (i, p1); double pnt[3]; surface.Evaluate (p1.x, p1.y, 0, 3, pnt); pcl::PointXYZRGB p2; p2.x = float (pnt[0]); p2.y = float (pnt[1]); p2.z = float (pnt[2]); p2.r = 255; p2.g = 0; p2.b = 0; curve_cps->push_back (p2); } viewer.removePointCloud ("cloud_cps"); viewer.addPointCloud (curve_cps, "cloud_cps"); } int main (int argc, char *argv[]) { std::string pcd_file; if (argc < 2) { printf ("\nUsage: pcl_example_nurbs_fitting_surface pcd<PointXYZ>-file\n\n"); exit (0); } pcd_file = argv[1]; unsigned order (3); unsigned refinement (6); unsigned iterations (10); unsigned mesh_resolution (256); pcl::visualization::PCLVisualizer viewer ("Test: NURBS surface fitting"); viewer.setSize (800, 600); // ############################################################################ // load point cloud printf (" loading %s\n", pcd_file.c_str ()); pcl::PointCloud<Point>::Ptr cloud (new pcl::PointCloud<Point>); pcl::PCLPointCloud2 cloud2; pcl::on_nurbs::NurbsDataSurface data; if (pcl::io::loadPCDFile (pcd_file, cloud2) == -1) throw std::runtime_error (" PCD file not found."); fromPCLPointCloud2 (cloud2, *cloud); PointCloud2Vector3d (cloud, data.interior); pcl::visualization::PointCloudColorHandlerCustom<Point> handler (cloud, 0, 255, 0); viewer.addPointCloud<Point> (cloud, handler, "cloud_cylinder"); printf (" %zu points in data set\n", cloud->size ()); // ############################################################################ // fit NURBS surface printf (" surface fitting ...\n"); ON_NurbsSurface nurbs = pcl::on_nurbs::FittingSurface::initNurbsPCABoundingBox (order, &data); pcl::on_nurbs::FittingSurface fit (&data, nurbs); // fit.setQuiet (false); pcl::PolygonMesh mesh; pcl::PointCloud<pcl::PointXYZ>::Ptr mesh_cloud (new pcl::PointCloud<pcl::PointXYZ>); std::vector<pcl::Vertices> mesh_vertices; std::string mesh_id = "mesh_nurbs"; pcl::on_nurbs::Triangulation::convertSurface2PolygonMesh (fit.m_nurbs, mesh, mesh_resolution); viewer.addPolygonMesh (mesh, mesh_id); pcl::on_nurbs::FittingSurface::Parameter params; params.interior_smoothness = 0.15; params.interior_weight = 1.0; params.boundary_smoothness = 0.15; params.boundary_weight = 0.0; // NURBS refinement for (unsigned i = 0; i < refinement; i++) { fit.refine (0); fit.refine (1); fit.assemble (params); fit.solve (); pcl::on_nurbs::Triangulation::convertSurface2Vertices (fit.m_nurbs, mesh_cloud, mesh_vertices, mesh_resolution); viewer.updatePolygonMesh<pcl::PointXYZ> (mesh_cloud, mesh_vertices, mesh_id); viewer.spinOnce (); } // fitting iterations for (unsigned i = 0; i < iterations; i++) { fit.assemble (params); fit.solve (); pcl::on_nurbs::Triangulation::convertSurface2Vertices (fit.m_nurbs, mesh_cloud, mesh_vertices, mesh_resolution); viewer.updatePolygonMesh<pcl::PointXYZ> (mesh_cloud, mesh_vertices, mesh_id); viewer.spinOnce (); } // ############################################################################ // fit NURBS curve pcl::on_nurbs::FittingCurve2dAPDM::FitParameter curve_params; curve_params.addCPsAccuracy = 3e-2; curve_params.addCPsIteration = 3; curve_params.maxCPs = 200; curve_params.accuracy = 1e-3; curve_params.iterations = 10000; curve_params.param.closest_point_resolution = 0; curve_params.param.closest_point_weight = 1.0; curve_params.param.closest_point_sigma2 = 0.1; curve_params.param.interior_sigma2 = 0.0001; curve_params.param.smooth_concavity = 1.0; curve_params.param.smoothness = 1.0; pcl::on_nurbs::NurbsDataCurve2d curve_data; curve_data.interior = data.interior_param; curve_data.interior_weight_function.push_back (true); ON_NurbsCurve curve_nurbs = pcl::on_nurbs::FittingCurve2dAPDM::initNurbsCurve2D (order, curve_data.interior); pcl::on_nurbs::FittingCurve2dASDM curve_fit (&curve_data, curve_nurbs); // curve_fit.setQuiet (false); // ############################### FITTING ############################### curve_fit.fitting (curve_params); visualizeCurve (curve_fit.m_nurbs, fit.m_nurbs, viewer); // ############################################################################ // triangulation of trimmed surface printf (" triangulate trimmed surface ...\n"); viewer.removePolygonMesh (mesh_id); pcl::on_nurbs::Triangulation::convertTrimmedSurface2PolygonMesh (fit.m_nurbs, curve_fit.m_nurbs, mesh, mesh_resolution); viewer.addPolygonMesh (mesh, mesh_id); printf (" ... done.\n"); viewer.spin (); return 0; } <commit_msg>NURBS fitting: fixed trimming curve for surface fitting (parameter was wrong)<commit_after>#include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/io/pcd_io.h> #include <pcl/visualization/pcl_visualizer.h> #include <pcl/surface/on_nurbs/fitting_surface_tdm.h> #include <pcl/surface/on_nurbs/fitting_curve_2d_asdm.h> #include <pcl/surface/on_nurbs/triangulation.h> typedef pcl::PointXYZ Point; void PointCloud2Vector3d (pcl::PointCloud<Point>::Ptr cloud, pcl::on_nurbs::vector_vec3d &data) { for (unsigned i = 0; i < cloud->size (); i++) { Point &p = cloud->at (i); if (!pcl_isnan (p.x) && !pcl_isnan (p.y) && !pcl_isnan (p.z)) data.push_back (Eigen::Vector3d (p.x, p.y, p.z)); } } void visualizeCurve (ON_NurbsCurve &curve, ON_NurbsSurface &surface, pcl::visualization::PCLVisualizer &viewer) { pcl::PointCloud<pcl::PointXYZRGB>::Ptr curve_cloud (new pcl::PointCloud<pcl::PointXYZRGB>); pcl::on_nurbs::Triangulation::convertCurve2PointCloud (curve, surface, curve_cloud, 4); for (std::size_t i = 0; i < curve_cloud->size () - 1; i++) { pcl::PointXYZRGB &p1 = curve_cloud->at (i); pcl::PointXYZRGB &p2 = curve_cloud->at (i + 1); std::ostringstream os; os << "line" << i; viewer.removeShape (os.str ()); viewer.addLine<pcl::PointXYZRGB> (p1, p2, 1.0, 0.0, 0.0, os.str ()); } pcl::PointCloud<pcl::PointXYZRGB>::Ptr curve_cps (new pcl::PointCloud<pcl::PointXYZRGB>); for (int i = 0; i < curve.CVCount (); i++) { ON_3dPoint p1; curve.GetCV (i, p1); double pnt[3]; surface.Evaluate (p1.x, p1.y, 0, 3, pnt); pcl::PointXYZRGB p2; p2.x = float (pnt[0]); p2.y = float (pnt[1]); p2.z = float (pnt[2]); p2.r = 255; p2.g = 0; p2.b = 0; curve_cps->push_back (p2); } viewer.removePointCloud ("cloud_cps"); viewer.addPointCloud (curve_cps, "cloud_cps"); } int main (int argc, char *argv[]) { std::string pcd_file; if (argc < 2) { printf ("\nUsage: pcl_example_nurbs_fitting_surface pcd<PointXYZ>-file\n\n"); exit (0); } pcd_file = argv[1]; unsigned order (3); unsigned refinement (5); unsigned iterations (10); unsigned mesh_resolution (256); pcl::visualization::PCLVisualizer viewer ("Test: NURBS surface fitting"); viewer.setSize (800, 600); // ############################################################################ // load point cloud printf (" loading %s\n", pcd_file.c_str ()); pcl::PointCloud<Point>::Ptr cloud (new pcl::PointCloud<Point>); pcl::PCLPointCloud2 cloud2; pcl::on_nurbs::NurbsDataSurface data; if (pcl::io::loadPCDFile (pcd_file, cloud2) == -1) throw std::runtime_error (" PCD file not found."); fromPCLPointCloud2 (cloud2, *cloud); PointCloud2Vector3d (cloud, data.interior); pcl::visualization::PointCloudColorHandlerCustom<Point> handler (cloud, 0, 255, 0); viewer.addPointCloud<Point> (cloud, handler, "cloud_cylinder"); printf (" %zu points in data set\n", cloud->size ()); // ############################################################################ // fit NURBS surface printf (" surface fitting ...\n"); ON_NurbsSurface nurbs = pcl::on_nurbs::FittingSurface::initNurbsPCABoundingBox (order, &data); pcl::on_nurbs::FittingSurface fit (&data, nurbs); // fit.setQuiet (false); pcl::PolygonMesh mesh; pcl::PointCloud<pcl::PointXYZ>::Ptr mesh_cloud (new pcl::PointCloud<pcl::PointXYZ>); std::vector<pcl::Vertices> mesh_vertices; std::string mesh_id = "mesh_nurbs"; pcl::on_nurbs::Triangulation::convertSurface2PolygonMesh (fit.m_nurbs, mesh, mesh_resolution); viewer.addPolygonMesh (mesh, mesh_id); pcl::on_nurbs::FittingSurface::Parameter params; params.interior_smoothness = 0.15; params.interior_weight = 1.0; params.boundary_smoothness = 0.15; params.boundary_weight = 0.0; // NURBS refinement for (unsigned i = 0; i < refinement; i++) { fit.refine (0); fit.refine (1); fit.assemble (params); fit.solve (); pcl::on_nurbs::Triangulation::convertSurface2Vertices (fit.m_nurbs, mesh_cloud, mesh_vertices, mesh_resolution); viewer.updatePolygonMesh<pcl::PointXYZ> (mesh_cloud, mesh_vertices, mesh_id); viewer.spinOnce (); } // fitting iterations for (unsigned i = 0; i < iterations; i++) { fit.assemble (params); fit.solve (); pcl::on_nurbs::Triangulation::convertSurface2Vertices (fit.m_nurbs, mesh_cloud, mesh_vertices, mesh_resolution); viewer.updatePolygonMesh<pcl::PointXYZ> (mesh_cloud, mesh_vertices, mesh_id); viewer.spinOnce (); } // ############################################################################ // fit NURBS curve pcl::on_nurbs::FittingCurve2dAPDM::FitParameter curve_params; curve_params.addCPsAccuracy = 5e-2; curve_params.addCPsIteration = 3; curve_params.maxCPs = 200; curve_params.accuracy = 1e-3; curve_params.iterations = 100; curve_params.param.closest_point_resolution = 0; curve_params.param.closest_point_weight = 1.0; curve_params.param.closest_point_sigma2 = 0.1; curve_params.param.interior_sigma2 = 0.0001; curve_params.param.smooth_concavity = 1.0; curve_params.param.smoothness = 1.0; pcl::on_nurbs::NurbsDataCurve2d curve_data; curve_data.interior = data.interior_param; curve_data.interior_weight_function.push_back (true); ON_NurbsCurve curve_nurbs = pcl::on_nurbs::FittingCurve2dAPDM::initNurbsCurve2D (order, curve_data.interior); pcl::on_nurbs::FittingCurve2dASDM curve_fit (&curve_data, curve_nurbs); // curve_fit.setQuiet (false); // ############################### FITTING ############################### curve_fit.fitting (curve_params); visualizeCurve (curve_fit.m_nurbs, fit.m_nurbs, viewer); // ############################################################################ // triangulation of trimmed surface printf (" triangulate trimmed surface ...\n"); viewer.removePolygonMesh (mesh_id); pcl::on_nurbs::Triangulation::convertTrimmedSurface2PolygonMesh (fit.m_nurbs, curve_fit.m_nurbs, mesh, mesh_resolution); viewer.addPolygonMesh (mesh, mesh_id); printf (" ... done.\n"); viewer.spin (); return 0; } <|endoftext|>
<commit_before>/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * _______ _ * * ( ____ \ ( \ |\ /| * * | ( \/ | ( ( \ / ) * * | (__ | | \ (_) / * * | __) | | \ / * * | ( | | ) ( * * | ) | (____/\ | | * * |/ (_______/ \_/ * * * * * * fly is an awesome c++11 network library. * * * * @author: lichuan * * @qq: 308831759 * * @email: [email protected] * * @github: https://github.com/lichuan/fly * * @date: 2015-06-24 20:43:56 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include <sys/epoll.h> #include <sys/eventfd.h> #include <unistd.h> #include "fly/base/logger.hpp" #include "fly/net/poller_task.hpp" namespace fly { namespace net { template<typename T> Poller_Task<T>::Poller_Task(uint64 seq) : Loop_Task(seq) { m_fd = epoll_create1(0); if(m_fd < 0) { LOG_FATAL("epoll_create1 failed in Poller_Task::Poller_Task %s", strerror(errno)); return; } m_close_event_fd = eventfd(0, 0); if(m_close_event_fd < 0) { LOG_FATAL("close event eventfd failed in Poller_Task::Poller_Task"); return; } m_write_event_fd = eventfd(0, 0); if(m_write_event_fd < 0) { LOG_FATAL("write event eventfd failed in Poller_Task::Poller_Task"); return; } m_stop_event_fd = eventfd(0, 0); if(m_stop_event_fd < 0) { LOG_FATAL("stop event eventfd failed in Poller_Task::Poller_Task"); return; } struct epoll_event event; m_close_udata.reset(new Connection<T>(m_close_event_fd, Addr("close_event", 0))); event.data.ptr = m_close_udata.get(); event.events = EPOLLIN; int32 ret = epoll_ctl(m_fd, EPOLL_CTL_ADD, m_close_event_fd, &event); if(ret < 0) { LOG_FATAL("close event epoll_ctl failed in Poller_Task::Poller_Task"); return; } m_write_udata.reset(new Connection<T>(m_write_event_fd, Addr("write_event", 0))); event.data.ptr = m_write_udata.get(); ret = epoll_ctl(m_fd, EPOLL_CTL_ADD, m_write_event_fd, &event); if(ret < 0) { LOG_FATAL("write event epoll_ctl failed in Poller_Task::Poller_Task"); return; } m_stop_udata.reset(new Connection<T>(m_stop_event_fd, Addr("stop_event", 0))); event.data.ptr = m_stop_udata.get(); ret = epoll_ctl(m_fd, EPOLL_CTL_ADD, m_stop_event_fd, &event); if(ret < 0) { LOG_FATAL("stop event epoll_ctl failed in Poller_Task::Poller_Task"); } } template<typename T> bool Poller_Task<T>::register_connection(std::shared_ptr<Connection<T>> connection) { struct epoll_event event; event.data.ptr = connection.get(); event.events = EPOLLIN | EPOLLOUT | EPOLLRDHUP | EPOLLET; connection->m_poller_task = this; connection->m_self = connection; connection->m_init_cb(connection); int32 ret = epoll_ctl(m_fd, EPOLL_CTL_ADD, connection->m_fd, &event); if(ret < 0) { LOG_FATAL("epoll_ctl failed in Poller_Task::register_connection: %s", strerror(errno)); close(connection->m_fd); connection->m_closed.store(true, std::memory_order_relaxed); connection->m_be_closed_cb(connection->shared_from_this()); connection->m_self.reset(); return false; } return true; } template<typename T> void Poller_Task<T>::close_connection(std::shared_ptr<Connection<T>> connection) { m_close_queue.push(connection); uint64 data = 1; int32 num = write(m_close_event_fd, &data, sizeof(uint64)); if(num != sizeof(uint64)) { LOG_FATAL("write m_close_event_fd failed in Poller_Task::close_connection"); } } template<typename T> void Poller_Task<T>::stop() { uint64 data = 1; int32 num = write(m_stop_event_fd, &data, sizeof(uint64)); if(num != sizeof(uint64)) { LOG_FATAL("write m_stop_event_fd failed in Poller_Task::stop"); } } template<typename T> void Poller_Task<T>::write_connection(std::shared_ptr<Connection<T>> connection) { m_write_queue.push(connection); uint64 data = 1; int32 num = write(m_write_event_fd, &data, sizeof(uint64)); if(num != sizeof(uint64)) { LOG_FATAL("write m_write_event_fd failed in Poller_Task::write_connection"); } } template<typename T> void Poller_Task<T>::do_write(std::shared_ptr<Connection<T>> connection) { int32 fd = connection->m_fd; Message_Chunk_Queue &send_queue = connection->m_send_msg_queue; while(Message_Chunk *message_chunk = send_queue.pop()) { int32 message_length = message_chunk->length(); int32 num = write(fd, message_chunk->read_ptr(), message_length); if(num < 0) { if(errno == EAGAIN || errno == EWOULDBLOCK) { send_queue.push_front(message_chunk); break; } } if(num == 0) { LOG_FATAL("write return 0, it's impossible, in Poller_Task::do_write(arg)"); } if(num <= 0) { epoll_ctl(m_fd, EPOLL_CTL_DEL, fd, NULL); close(fd); connection->m_self.reset(); connection->m_closed.store(true, std::memory_order_relaxed); connection->m_be_closed_cb(connection); break; } if(num < message_length) { message_chunk->read_ptr(num); send_queue.push_front(message_chunk); break; } else { delete message_chunk; } } } template<typename T> void Poller_Task<T>::do_write() { uint64 data = 0; int32 num = read(m_write_event_fd, &data, sizeof(uint64)); if(num != sizeof(uint64)) { LOG_FATAL("read m_write_event_fd failed in Poller_Task::do_write"); return; } std::list<std::shared_ptr<Connection<T>>> write_queue; if(m_write_queue.pop(write_queue)) { for(auto &connection : write_queue) { if(!connection->m_closed.load(std::memory_order_relaxed)) { do_write(connection); } } } } template<typename T> void Poller_Task<T>::do_close() { uint64 data = 0; int32 num = read(m_close_event_fd, &data, sizeof(uint64)); if(num != sizeof(uint64)) { LOG_FATAL("read m_close_event_fd failed in Poller_Task::do_close"); return; } std::list<std::shared_ptr<Connection<T>>> close_queue; if(m_close_queue.pop(close_queue)) { for(auto &connection : close_queue) { if(!connection->m_closed.load(std::memory_order_relaxed)) { int32 fd = connection->m_fd; int ret = epoll_ctl(m_fd, EPOLL_CTL_DEL, fd, NULL); if(ret < 0) { LOG_FATAL("epoll_ctl EPOLL_CTL_DEL failed in Poller_Task::do_close: %s", strerror(errno)); } close(fd); connection->m_self.reset(); connection->m_closed.store(true, std::memory_order_relaxed); connection->m_close_cb(connection); } } } } template<typename T> void Poller_Task<T>::run_in_loop() { struct epoll_event events[2048]; int32 fd_num = epoll_wait(m_fd, events, 2048, -1); if(fd_num < 0) { LOG_FATAL("epoll_wait failed in Poller_Task::run_in_loop %s", strerror(errno)); return; } for(auto i = 0; i < fd_num; ++i) { Connection<T> *connection = static_cast<Connection<T>*>(events[i].data.ptr); int32 fd = connection->m_fd; uint32 event = events[i].events; if(event & (EPOLLERR | EPOLLHUP | EPOLLRDHUP)) { if(connection->m_closed.load(std::memory_order_relaxed)) { continue; } int ret = epoll_ctl(m_fd, EPOLL_CTL_DEL, fd, NULL); if(ret < 0) { LOG_FATAL("epoll_ctl EPOLL_CTL_DEL failed in Poller_Task::run_in_loop: %s", strerror(errno)); } close(fd); connection->m_closed.store(true, std::memory_order_relaxed); connection->m_be_closed_cb(connection->shared_from_this()); connection->m_self.reset(); } else if(event & EPOLLIN) { if(fd == m_close_event_fd) { do_close(); } else if(fd == m_write_event_fd) { do_write(); } else if(fd == m_stop_event_fd) { Loop_Task::stop(); close(m_fd); break; } else { if(connection->m_closed.load(std::memory_order_relaxed)) { continue; } while(true) { const uint32 REQ_SIZE = 100 * 1024; Message_Chunk_Queue &recv_queue = connection->m_recv_msg_queue; std::unique_ptr<Message_Chunk> message_chunk(new Message_Chunk(REQ_SIZE)); int32 num = read(fd, message_chunk->read_ptr(), REQ_SIZE); if(num < 0) { if(errno == EAGAIN || errno == EWOULDBLOCK) { break; } } if(num <= 0) { epoll_ctl(m_fd, EPOLL_CTL_DEL, fd, NULL); close(fd); connection->m_closed.store(true, std::memory_order_relaxed); connection->m_be_closed_cb(connection->shared_from_this()); connection->m_self.reset(); break; } message_chunk->write_ptr(num); recv_queue.push(message_chunk.release()); connection->parse(); if(num < REQ_SIZE) { break; } } } } if(event & EPOLLOUT) { if(connection->m_closed.load(std::memory_order_relaxed)) { continue; } do_write(connection->shared_from_this()); } } } template class Poller_Task<Json>; template class Poller_Task<Wsock>; template class Poller_Task<Proto>; } } <commit_msg>change req size to 2M<commit_after>/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * _______ _ * * ( ____ \ ( \ |\ /| * * | ( \/ | ( ( \ / ) * * | (__ | | \ (_) / * * | __) | | \ / * * | ( | | ) ( * * | ) | (____/\ | | * * |/ (_______/ \_/ * * * * * * fly is an awesome c++11 network library. * * * * @author: lichuan * * @qq: 308831759 * * @email: [email protected] * * @github: https://github.com/lichuan/fly * * @date: 2015-06-24 20:43:56 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include <sys/epoll.h> #include <sys/eventfd.h> #include <unistd.h> #include "fly/base/logger.hpp" #include "fly/net/poller_task.hpp" namespace fly { namespace net { template<typename T> Poller_Task<T>::Poller_Task(uint64 seq) : Loop_Task(seq) { m_fd = epoll_create1(0); if(m_fd < 0) { LOG_FATAL("epoll_create1 failed in Poller_Task::Poller_Task %s", strerror(errno)); return; } m_close_event_fd = eventfd(0, 0); if(m_close_event_fd < 0) { LOG_FATAL("close event eventfd failed in Poller_Task::Poller_Task"); return; } m_write_event_fd = eventfd(0, 0); if(m_write_event_fd < 0) { LOG_FATAL("write event eventfd failed in Poller_Task::Poller_Task"); return; } m_stop_event_fd = eventfd(0, 0); if(m_stop_event_fd < 0) { LOG_FATAL("stop event eventfd failed in Poller_Task::Poller_Task"); return; } struct epoll_event event; m_close_udata.reset(new Connection<T>(m_close_event_fd, Addr("close_event", 0))); event.data.ptr = m_close_udata.get(); event.events = EPOLLIN; int32 ret = epoll_ctl(m_fd, EPOLL_CTL_ADD, m_close_event_fd, &event); if(ret < 0) { LOG_FATAL("close event epoll_ctl failed in Poller_Task::Poller_Task"); return; } m_write_udata.reset(new Connection<T>(m_write_event_fd, Addr("write_event", 0))); event.data.ptr = m_write_udata.get(); ret = epoll_ctl(m_fd, EPOLL_CTL_ADD, m_write_event_fd, &event); if(ret < 0) { LOG_FATAL("write event epoll_ctl failed in Poller_Task::Poller_Task"); return; } m_stop_udata.reset(new Connection<T>(m_stop_event_fd, Addr("stop_event", 0))); event.data.ptr = m_stop_udata.get(); ret = epoll_ctl(m_fd, EPOLL_CTL_ADD, m_stop_event_fd, &event); if(ret < 0) { LOG_FATAL("stop event epoll_ctl failed in Poller_Task::Poller_Task"); } } template<typename T> bool Poller_Task<T>::register_connection(std::shared_ptr<Connection<T>> connection) { struct epoll_event event; event.data.ptr = connection.get(); event.events = EPOLLIN | EPOLLOUT | EPOLLRDHUP | EPOLLET; connection->m_poller_task = this; connection->m_self = connection; connection->m_init_cb(connection); int32 ret = epoll_ctl(m_fd, EPOLL_CTL_ADD, connection->m_fd, &event); if(ret < 0) { LOG_FATAL("epoll_ctl failed in Poller_Task::register_connection: %s", strerror(errno)); close(connection->m_fd); connection->m_closed.store(true, std::memory_order_relaxed); connection->m_be_closed_cb(connection->shared_from_this()); connection->m_self.reset(); return false; } return true; } template<typename T> void Poller_Task<T>::close_connection(std::shared_ptr<Connection<T>> connection) { m_close_queue.push(connection); uint64 data = 1; int32 num = write(m_close_event_fd, &data, sizeof(uint64)); if(num != sizeof(uint64)) { LOG_FATAL("write m_close_event_fd failed in Poller_Task::close_connection"); } } template<typename T> void Poller_Task<T>::stop() { uint64 data = 1; int32 num = write(m_stop_event_fd, &data, sizeof(uint64)); if(num != sizeof(uint64)) { LOG_FATAL("write m_stop_event_fd failed in Poller_Task::stop"); } } template<typename T> void Poller_Task<T>::write_connection(std::shared_ptr<Connection<T>> connection) { m_write_queue.push(connection); uint64 data = 1; int32 num = write(m_write_event_fd, &data, sizeof(uint64)); if(num != sizeof(uint64)) { LOG_FATAL("write m_write_event_fd failed in Poller_Task::write_connection"); } } template<typename T> void Poller_Task<T>::do_write(std::shared_ptr<Connection<T>> connection) { int32 fd = connection->m_fd; Message_Chunk_Queue &send_queue = connection->m_send_msg_queue; while(Message_Chunk *message_chunk = send_queue.pop()) { int32 message_length = message_chunk->length(); int32 num = write(fd, message_chunk->read_ptr(), message_length); if(num < 0) { if(errno == EAGAIN || errno == EWOULDBLOCK) { send_queue.push_front(message_chunk); break; } } if(num == 0) { LOG_FATAL("write return 0, it's impossible, in Poller_Task::do_write(arg)"); } if(num <= 0) { epoll_ctl(m_fd, EPOLL_CTL_DEL, fd, NULL); close(fd); connection->m_self.reset(); connection->m_closed.store(true, std::memory_order_relaxed); connection->m_be_closed_cb(connection); break; } if(num < message_length) { message_chunk->read_ptr(num); send_queue.push_front(message_chunk); break; } else { delete message_chunk; } } } template<typename T> void Poller_Task<T>::do_write() { uint64 data = 0; int32 num = read(m_write_event_fd, &data, sizeof(uint64)); if(num != sizeof(uint64)) { LOG_FATAL("read m_write_event_fd failed in Poller_Task::do_write"); return; } std::list<std::shared_ptr<Connection<T>>> write_queue; if(m_write_queue.pop(write_queue)) { for(auto &connection : write_queue) { if(!connection->m_closed.load(std::memory_order_relaxed)) { do_write(connection); } } } } template<typename T> void Poller_Task<T>::do_close() { uint64 data = 0; int32 num = read(m_close_event_fd, &data, sizeof(uint64)); if(num != sizeof(uint64)) { LOG_FATAL("read m_close_event_fd failed in Poller_Task::do_close"); return; } std::list<std::shared_ptr<Connection<T>>> close_queue; if(m_close_queue.pop(close_queue)) { for(auto &connection : close_queue) { if(!connection->m_closed.load(std::memory_order_relaxed)) { int32 fd = connection->m_fd; int ret = epoll_ctl(m_fd, EPOLL_CTL_DEL, fd, NULL); if(ret < 0) { LOG_FATAL("epoll_ctl EPOLL_CTL_DEL failed in Poller_Task::do_close: %s", strerror(errno)); } close(fd); connection->m_self.reset(); connection->m_closed.store(true, std::memory_order_relaxed); connection->m_close_cb(connection); } } } } template<typename T> void Poller_Task<T>::run_in_loop() { struct epoll_event events[2048]; int32 fd_num = epoll_wait(m_fd, events, 2048, -1); if(fd_num < 0) { LOG_FATAL("epoll_wait failed in Poller_Task::run_in_loop %s", strerror(errno)); return; } for(auto i = 0; i < fd_num; ++i) { Connection<T> *connection = static_cast<Connection<T>*>(events[i].data.ptr); int32 fd = connection->m_fd; uint32 event = events[i].events; if(event & (EPOLLERR | EPOLLHUP | EPOLLRDHUP)) { if(connection->m_closed.load(std::memory_order_relaxed)) { continue; } int ret = epoll_ctl(m_fd, EPOLL_CTL_DEL, fd, NULL); if(ret < 0) { LOG_FATAL("epoll_ctl EPOLL_CTL_DEL failed in Poller_Task::run_in_loop: %s", strerror(errno)); } close(fd); connection->m_closed.store(true, std::memory_order_relaxed); connection->m_be_closed_cb(connection->shared_from_this()); connection->m_self.reset(); } else if(event & EPOLLIN) { if(fd == m_close_event_fd) { do_close(); } else if(fd == m_write_event_fd) { do_write(); } else if(fd == m_stop_event_fd) { Loop_Task::stop(); close(m_fd); break; } else { if(connection->m_closed.load(std::memory_order_relaxed)) { continue; } while(true) { const uint32 REQ_SIZE = 2 * 1024 * 1024; Message_Chunk_Queue &recv_queue = connection->m_recv_msg_queue; std::unique_ptr<Message_Chunk> message_chunk(new Message_Chunk(REQ_SIZE)); int32 num = read(fd, message_chunk->read_ptr(), REQ_SIZE); if(num < 0) { if(errno == EAGAIN || errno == EWOULDBLOCK) { break; } } if(num <= 0) { epoll_ctl(m_fd, EPOLL_CTL_DEL, fd, NULL); close(fd); connection->m_closed.store(true, std::memory_order_relaxed); connection->m_be_closed_cb(connection->shared_from_this()); connection->m_self.reset(); break; } message_chunk->write_ptr(num); recv_queue.push(message_chunk.release()); connection->parse(); if(num < REQ_SIZE) { break; } } } } if(event & EPOLLOUT) { if(connection->m_closed.load(std::memory_order_relaxed)) { continue; } do_write(connection->shared_from_this()); } } } template class Poller_Task<Json>; template class Poller_Task<Wsock>; template class Poller_Task<Proto>; } } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// @brief batch request handler /// /// @file /// /// DISCLAIMER /// /// Copyright 2004-2012 triagens GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is triAGENS GmbH, Cologne, Germany /// /// @author Jan Steemann /// @author Copyright 2012, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "RestBatchHandler.h" #include "Basics/StringUtils.h" #include "Basics/MutexLocker.h" #include "Rest/HttpRequest.h" #include "Rest/HttpResponse.h" #include "VocBase/vocbase.h" #include "GeneralServer/GeneralCommTask.h" #include "GeneralServer/GeneralServerJob.h" #include "HttpServer/HttpHandler.h" #include "HttpServer/HttpServer.h" #include "ProtocolBuffers/HttpRequestProtobuf.h" using namespace std; using namespace triagens::basics; using namespace triagens::rest; using namespace triagens::arango; // ----------------------------------------------------------------------------- // --SECTION-- constructors and destructors // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup ArangoDB /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief constructor //////////////////////////////////////////////////////////////////////////////// RestBatchHandler::RestBatchHandler (HttpRequest* request, TRI_vocbase_t* vocbase) : RestVocbaseBaseHandler(request, vocbase), _missingResponses(0), _reallyDone(0), _outputMessages(new PB_ArangoMessage) { } //////////////////////////////////////////////////////////////////////////////// /// @brief destructor //////////////////////////////////////////////////////////////////////////////// RestBatchHandler::~RestBatchHandler () { // delete protobuf message delete _outputMessages; // clear all handlers that still exist for (size_t i = 0; i < _handlers.size(); ++i) { HttpHandler* handler = _handlers[i]; if (handler != 0) { _task->getServer()->destroyHandler(handler); _handlers[i] = 0; } } } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- Handler methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup ArangoDB /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// bool RestBatchHandler::isDirect () { return false; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// string const& RestBatchHandler::queue () { static string const client = "STANDARD"; return client; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// HttpHandler::status_e RestBatchHandler::execute () { // extract the request type HttpRequest::HttpRequestType type = request->requestType(); string contentType = StringUtils::tolower(StringUtils::trim(request->header("content-type"))); if (type != HttpRequest::HTTP_REQUEST_POST || contentType != getContentType()) { generateNotImplemented("ILLEGAL " + BATCH_PATH); return HANDLER_DONE; } /* FILE* fp = fopen("got","w"); fwrite(request->body(), request->bodySize(), 1, fp); fclose(fp); */ PB_ArangoMessage inputMessages; bool result = inputMessages.ParseFromArray(request->body(), request->bodySize()); if (!result) { generateError(HttpResponse::BAD, TRI_ERROR_ARANGO_COLLECTION_PARAMETER_MISSING, // TODO FIXME "invalid protobuf message"); return HANDLER_DONE; } bool failed = false; bool hasAsync = false; // loop over the input messages once to set up the output structures without concurrency for (int i = 0; i < inputMessages.messages_size(); ++i) { _outputMessages->add_messages(); // create a handler for each input part const PB_ArangoBatchMessage inputMessage = inputMessages.messages(i); HttpRequestProtobuf* request = new HttpRequestProtobuf(inputMessage); HttpHandler* handler = _task->getServer()->createHandler(request); if (!handler) { failed = true; break; } else { _handlers.push_back(handler); if (!handler->isDirect()) { // async handler ++_missingResponses; hasAsync = true; } } } if (failed) { // TODO: handle error! std::cout << "SOMETHING FAILED--------------------------------------------------------------------------\n"; return Handler::HANDLER_DONE; } try { // now loop again with all output structures set up for (int i = 0; i < inputMessages.messages_size(); ++i) { const PB_ArangoBatchMessage inputMessage = inputMessages.messages(i); HttpHandler* handler = _handlers[i]; assert(handler); if (handler->isDirect()) { // execute handler directly Handler::status_e status = Handler::HANDLER_FAILED; try { status = handler->execute(); } catch (...) { // TODO } if (status != Handler::HANDLER_REQUEUE) { addResponse(handler); } } else { // execute handler via dispatcher HttpServer* server = dynamic_cast<HttpServer*>(_task->getServer()); Scheduler* scheduler = server->getScheduler(); Dispatcher* dispatcher = server->getDispatcher(); Job* job = handler->createJob(scheduler, dispatcher, _task); GeneralServerJob<HttpServer, HttpHandlerFactory::GeneralHandler>* generalJob = dynamic_cast<GeneralServerJob<HttpServer, HttpHandlerFactory::GeneralHandler> * >(job); generalJob->attachObserver(this); dispatcher->addJob(job); } } } catch (...) { std::cout << "SOMETHING WENT WRONG - EXCEPTION\n"; } if (!hasAsync) { _reallyDone = 1; return Handler::HANDLER_DONE; } // we have async jobs return Handler::HANDLER_DETACH; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// bool RestBatchHandler::handleAsync () { if (_reallyDone) { assembleResponse(); toServerJob(_job)->setDone(); return HttpHandler::handleAsync(); } return true; } //////////////////////////////////////////////////////////////////////////////// /// notification routine called by async sub jobs //////////////////////////////////////////////////////////////////////////////// void RestBatchHandler::notify (Job* job, const Job::notification_e type) { if (type != Job::JOB_CLEANUP) { return; } assert(_reallyDone == 0); HttpHandler* handler = toServerJob(job)->getHandler(); addResponse(handler); if (--_missingResponses == 0) { _reallyDone = 1; // signal to the task that we are done GeneralAsyncCommTask<HttpServer, HttpHandlerFactory, HttpCommTask>* atask = dynamic_cast<GeneralAsyncCommTask<HttpServer, HttpHandlerFactory, HttpCommTask>*>(_task); atask->signal(); } } //////////////////////////////////////////////////////////////////////////////// /// @brief add a single handler response to the output array //////////////////////////////////////////////////////////////////////////////// void RestBatchHandler::addResponse (HttpHandler* handler) { for (size_t i = 0; i < _handlers.size(); ++i) { if (_handlers[i] == handler) { // avoid concurrent modifications to the structure MUTEX_LOCKER(_handlerLock); PB_ArangoBatchMessage* batch = _outputMessages->mutable_messages(i); handler->getResponse()->write(batch); // delete the handler _task->getServer()->destroyHandler(handler); _handlers[i] = 0; return; } } // handler not found LOGGER_WARNING << "handler not found. this should not happen."; } //////////////////////////////////////////////////////////////////////////////// /// @brief create an overall protobuf response from the array of responses //////////////////////////////////////////////////////////////////////////////// void RestBatchHandler::assembleResponse () { assert(_missingResponses == 0); response = new HttpResponse(HttpResponse::OK); response->setContentType(getContentType()); string data; if (!_outputMessages->SerializeToString(&data)) { // TODO } response->body().appendText(data); } //////////////////////////////////////////////////////////////////////////////// /// @brief convert a Job* to a GeneralServerJob* //////////////////////////////////////////////////////////////////////////////// GeneralServerJob<HttpServer, HttpHandlerFactory::GeneralHandler>* RestBatchHandler::toServerJob(Job* job) { return dynamic_cast<GeneralServerJob<HttpServer, HttpHandlerFactory::GeneralHandler> * >(job); } //////////////////////////////////////////////////////////////////////////////// /// @brief return the required content type string //////////////////////////////////////////////////////////////////////////////// string const& RestBatchHandler::getContentType () { static string const contentType = "application/x-protobuf"; return contentType; } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // Local Variables: // mode: outline-minor // outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|// --SECTION--\\|/// @\\}\\)" // End: <commit_msg>some cleanup<commit_after>//////////////////////////////////////////////////////////////////////////////// /// @brief batch request handler /// /// @file /// /// DISCLAIMER /// /// Copyright 2004-2012 triagens GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is triAGENS GmbH, Cologne, Germany /// /// @author Jan Steemann /// @author Copyright 2012, triAGENS GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "RestBatchHandler.h" #include "Basics/StringUtils.h" #include "Basics/MutexLocker.h" #include "Rest/HttpRequest.h" #include "Rest/HttpResponse.h" #include "VocBase/vocbase.h" #include "GeneralServer/GeneralCommTask.h" #include "GeneralServer/GeneralServerJob.h" #include "HttpServer/HttpHandler.h" #include "HttpServer/HttpServer.h" #include "ProtocolBuffers/HttpRequestProtobuf.h" using namespace std; using namespace triagens::basics; using namespace triagens::rest; using namespace triagens::arango; // ----------------------------------------------------------------------------- // --SECTION-- constructors and destructors // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup ArangoDB /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// @brief constructor //////////////////////////////////////////////////////////////////////////////// RestBatchHandler::RestBatchHandler (HttpRequest* request, TRI_vocbase_t* vocbase) : RestVocbaseBaseHandler(request, vocbase), _missingResponses(0), _reallyDone(0), _outputMessages(new PB_ArangoMessage) { } //////////////////////////////////////////////////////////////////////////////// /// @brief destructor //////////////////////////////////////////////////////////////////////////////// RestBatchHandler::~RestBatchHandler () { // delete protobuf message delete _outputMessages; // clear all handlers that still exist for (size_t i = 0; i < _handlers.size(); ++i) { HttpHandler* handler = _handlers[i]; if (handler != 0) { _task->getServer()->destroyHandler(handler); _handlers[i] = 0; } } } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // ----------------------------------------------------------------------------- // --SECTION-- Handler methods // ----------------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// /// @addtogroup ArangoDB /// @{ //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// bool RestBatchHandler::isDirect () { return false; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// string const& RestBatchHandler::queue () { static string const client = "STANDARD"; return client; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// HttpHandler::status_e RestBatchHandler::execute () { // extract the request type HttpRequest::HttpRequestType type = request->requestType(); string contentType = StringUtils::tolower(StringUtils::trim(request->header("content-type"))); if (type != HttpRequest::HTTP_REQUEST_POST || contentType != getContentType()) { generateNotImplemented("ILLEGAL " + BATCH_PATH); return HANDLER_DONE; } PB_ArangoMessage inputMessages; bool result = inputMessages.ParseFromArray(request->body(), request->bodySize()); if (!result) { generateError(HttpResponse::BAD, TRI_ERROR_HTTP_BAD_PARAMETER, "invalid protobuf message"); return HANDLER_DONE; } assert(_task); HttpServer* server = dynamic_cast<HttpServer*>(_task->getServer()); assert(server); bool failed = false; bool hasAsync = false; // loop over the input messages once to set up the output structures without concurrency for (int i = 0; i < inputMessages.messages_size(); ++i) { _outputMessages->add_messages(); // create a handler for each input part const PB_ArangoBatchMessage inputMessage = inputMessages.messages(i); HttpRequestProtobuf* request = new HttpRequestProtobuf(inputMessage); HttpHandler* handler = server->createHandler(request); if (!handler) { failed = true; break; } else { _handlers.push_back(handler); if (!handler->isDirect()) { // async handler ++_missingResponses; hasAsync = true; } } } if (failed) { // TODO: handle error! std::cout << "SOMETHING FAILED--------------------------------------------------------------------------\n"; return Handler::HANDLER_DONE; } try { // now loop again with all output structures set up for (int i = 0; i < inputMessages.messages_size(); ++i) { const PB_ArangoBatchMessage inputMessage = inputMessages.messages(i); HttpHandler* handler = _handlers[i]; assert(handler); if (handler->isDirect()) { // execute handler directly Handler::status_e status = Handler::HANDLER_FAILED; try { status = handler->execute(); } catch (...) { // TODO } if (status != Handler::HANDLER_REQUEUE) { addResponse(handler); } } else { // execute handler via dispatcher Scheduler* scheduler = server->getScheduler(); Dispatcher* dispatcher = server->getDispatcher(); Job* job = handler->createJob(scheduler, dispatcher, _task); GeneralServerJob<HttpServer, HttpHandlerFactory::GeneralHandler>* generalJob = dynamic_cast<GeneralServerJob<HttpServer, HttpHandlerFactory::GeneralHandler> * >(job); generalJob->attachObserver(this); dispatcher->addJob(job); } } } catch (...) { std::cout << "SOMETHING WENT WRONG - EXCEPTION\n"; } if (!hasAsync) { _reallyDone = 1; return Handler::HANDLER_DONE; } // we have async jobs return Handler::HANDLER_DETACH; } //////////////////////////////////////////////////////////////////////////////// /// {@inheritDoc} //////////////////////////////////////////////////////////////////////////////// bool RestBatchHandler::handleAsync () { if (_reallyDone) { assembleResponse(); toServerJob(_job)->setDone(); return HttpHandler::handleAsync(); } return true; } //////////////////////////////////////////////////////////////////////////////// /// notification routine called by async sub jobs //////////////////////////////////////////////////////////////////////////////// void RestBatchHandler::notify (Job* job, const Job::notification_e type) { if (type != Job::JOB_CLEANUP) { return; } assert(_reallyDone == 0); HttpHandler* handler = toServerJob(job)->getHandler(); addResponse(handler); if (--_missingResponses == 0) { _reallyDone = 1; // signal to the task that we are done GeneralAsyncCommTask<HttpServer, HttpHandlerFactory, HttpCommTask>* atask = dynamic_cast<GeneralAsyncCommTask<HttpServer, HttpHandlerFactory, HttpCommTask>*>(_task); atask->signal(); } } //////////////////////////////////////////////////////////////////////////////// /// @brief add a single handler response to the output array //////////////////////////////////////////////////////////////////////////////// void RestBatchHandler::addResponse (HttpHandler* handler) { for (size_t i = 0; i < _handlers.size(); ++i) { if (_handlers[i] == handler) { // avoid concurrent modifications to the structure MUTEX_LOCKER(_handlerLock); PB_ArangoBatchMessage* batch = _outputMessages->mutable_messages(i); handler->getResponse()->write(batch); // delete the handler _task->getServer()->destroyHandler(handler); _handlers[i] = 0; return; } } // handler not found LOGGER_WARNING << "handler not found. this should not happen."; } //////////////////////////////////////////////////////////////////////////////// /// @brief create an overall protobuf response from the array of responses //////////////////////////////////////////////////////////////////////////////// void RestBatchHandler::assembleResponse () { assert(_missingResponses == 0); response = new HttpResponse(HttpResponse::OK); response->setContentType(getContentType()); string data; if (!_outputMessages->SerializeToString(&data)) { // TODO } response->body().appendText(data); } //////////////////////////////////////////////////////////////////////////////// /// @brief convert a Job* to a GeneralServerJob* //////////////////////////////////////////////////////////////////////////////// GeneralServerJob<HttpServer, HttpHandlerFactory::GeneralHandler>* RestBatchHandler::toServerJob(Job* job) { return dynamic_cast<GeneralServerJob<HttpServer, HttpHandlerFactory::GeneralHandler> * >(job); } //////////////////////////////////////////////////////////////////////////////// /// @brief return the required content type string //////////////////////////////////////////////////////////////////////////////// string const& RestBatchHandler::getContentType () { static string const contentType = "application/x-protobuf"; return contentType; } //////////////////////////////////////////////////////////////////////////////// /// @} //////////////////////////////////////////////////////////////////////////////// // Local Variables: // mode: outline-minor // outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|// --SECTION--\\|/// @\\}\\)" // End: <|endoftext|>
<commit_before>// Filename: decompressor.cxx // Created by: mike (09Jan97) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) 2001, Disney Enterprises, Inc. All rights reserved // // All use of this software is subject to the terms of the Panda 3d // Software license. You should have received a copy of this license // along with this source code; you will also find a current copy of // the license at http://www.panda3d.org/license.txt . // // To contact the maintainers of this program write to // [email protected] . // //////////////////////////////////////////////////////////////////// // This file is compiled only if we have zlib installed. #include "config_downloader.h" #include "error_utils.h" #include "filename.h" #include "buffer.h" #include "zStream.h" #include "decompressor.h" #include <stdio.h> #include <errno.h> //////////////////////////////////////////////////////////////////// // Function: Decompressor::Constructor // Access: Public // Description: //////////////////////////////////////////////////////////////////// Decompressor:: Decompressor() { _source = NULL; _decompress = NULL; _dest = NULL; } //////////////////////////////////////////////////////////////////// // Function: Decompressor::Destructor // Access: Public // Description: //////////////////////////////////////////////////////////////////// Decompressor:: ~Decompressor() { cleanup(); } //////////////////////////////////////////////////////////////////// // Function: Decompressor::initiate // Access: Public // Description: Begins a background decompression of the named file // (whose filename must end in ".pz") to a new file // without the .pz extension. The source file is // removed after successful completion. //////////////////////////////////////////////////////////////////// int Decompressor:: initiate(const Filename &source_file) { string extension = source_file.get_extension(); if (extension == "pz") { Filename dest_file = source_file; dest_file = source_file.get_fullpath_wo_extension(); return initiate(source_file, dest_file); } if (downloader_cat.is_debug()) { downloader_cat.debug() << "Unknown file extension for decompressor: ." << extension << endl; } return EU_error_abort; } //////////////////////////////////////////////////////////////////// // Function: Decompressor::initiate // Access: Public // Description: Begins a background decompression from the named // source file to the named destination file. The // source file is removed after successful completion. //////////////////////////////////////////////////////////////////// int Decompressor:: initiate(const Filename &source_file, const Filename &dest_file) { cleanup(); // Open source file _source_filename = Filename(source_file); _source_filename.set_binary(); ifstream *source_fstream = new ifstream; _source = source_fstream; if (!_source_filename.open_read(*source_fstream)) { downloader_cat.error() << "Unable to read " << _source_filename << "\n"; return get_write_error(); } // Determine source file length source_fstream->seekg(0, ios::end); _source_length = source_fstream->tellg(); if (_source_length == 0) { downloader_cat.warning() << "Zero length file: " << source_file << "\n"; return EU_error_file_empty; } source_fstream->seekg(0, ios::beg); // Open destination file Filename dest_filename(dest_file); dest_filename.set_binary(); ofstream *dest_fstream = new ofstream; _dest = dest_fstream; if (dest_filename.exists()) { downloader_cat.info() << dest_filename << " already exists, removing.\n"; if (!dest_filename.unlink()) { downloader_cat.error() << "Unable to remove old " << dest_filename << "\n"; return get_write_error(); } } else { if (downloader_cat.is_debug()) { downloader_cat.debug() << dest_filename << " does not already exist.\n"; } } if (!dest_filename.open_write(*dest_fstream)) { downloader_cat.error() << "Unable to write to " << dest_filename << "\n"; return get_write_error(); } // Now create the decompressor stream. _decompress = new IDecompressStream(_source, false); return EU_success; } //////////////////////////////////////////////////////////////////// // Function: Decompressor::run // Access: Public // Description: Called each frame to do the next bit of work in the // background task. Returns EU_ok if a chunk is // completed but there is more to go, or EU_success when // we're all done. Any other return value indicates an // error. //////////////////////////////////////////////////////////////////// int Decompressor:: run() { if (_decompress == (istream *)NULL) { // Hmm, we were already done. return EU_success; } // Read a bunch of characters from the decompress stream, but no // more than decompressor_buffer_size. int count = 0; int ch = _decompress->get(); while (!_decompress->eof() && !_decompress->fail()) { _dest->put(ch); if (++count >= decompressor_buffer_size) { // That's enough for now. return EU_ok; } ch = _decompress->get(); } // All done! cleanup(); _source_filename.unlink(); return EU_success; } //////////////////////////////////////////////////////////////////// // Function: Decompressor::decompress // Access: Public // Description: Performs a foreground decompression of the named // file; does not return until the decompression is // complete. //////////////////////////////////////////////////////////////////// bool Decompressor:: decompress(const Filename &source_file) { int ret = initiate(source_file); if (ret < 0) return false; int ch = _decompress->get(); while (!_decompress->eof() && !_decompress->fail()) { _dest->put(ch); ch = _decompress->get(); } cleanup(); _source_filename.unlink(); return true; } //////////////////////////////////////////////////////////////////// // Function: Decompressor::decompress // Access: Public // Description: Does an in-memory decompression of the indicated // Ramfile. The decompressed contents are written back // into the same Ramfile on completion. //////////////////////////////////////////////////////////////////// bool Decompressor:: decompress(Ramfile &source_and_dest_file) { istringstream source(source_and_dest_file._data); ostringstream dest; IDecompressStream decompress(&source, false); int ch = decompress.get(); while (!decompress.eof() && !decompress.fail()) { dest.put(ch); ch = decompress.get(); } source_and_dest_file._pos = 0; source_and_dest_file._data = dest.str(); return true; } //////////////////////////////////////////////////////////////////// // Function: Decompressor::get_progress // Access: Public // Description: Returns the ratio through the decompression step // in the background. //////////////////////////////////////////////////////////////////// float Decompressor:: get_progress() const { if (_decompress == (istream *)NULL) { // Hmm, we were already done. return 1.0f; } nassertr(_source_length > 0, 0.0); size_t source_pos = _source->tellg(); // We stop the scale at 0.99 because there may be a little bit more // to do even after the decompressor has read all of the source. return (0.99f * (float)source_pos / (float)_source_length); } //////////////////////////////////////////////////////////////////// // Function: Decompressor::cleanup // Access: Private // Description: Called to reset a previous decompressor state and // clean up properly. //////////////////////////////////////////////////////////////////// void Decompressor:: cleanup() { if (_source != (istream *)NULL) { delete _source; _source = NULL; } if (_dest != (ostream *)NULL) { delete _dest; _dest = NULL; } if (_decompress != (istream *)NULL) { delete _decompress; _decompress = NULL; } } <commit_msg>keep_temporary_files<commit_after>// Filename: decompressor.cxx // Created by: mike (09Jan97) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) 2001, Disney Enterprises, Inc. All rights reserved // // All use of this software is subject to the terms of the Panda 3d // Software license. You should have received a copy of this license // along with this source code; you will also find a current copy of // the license at http://www.panda3d.org/license.txt . // // To contact the maintainers of this program write to // [email protected] . // //////////////////////////////////////////////////////////////////// // This file is compiled only if we have zlib installed. #include "config_downloader.h" #include "error_utils.h" #include "filename.h" #include "buffer.h" #include "zStream.h" #include "config_express.h" #include "decompressor.h" #include <stdio.h> #include <errno.h> //////////////////////////////////////////////////////////////////// // Function: Decompressor::Constructor // Access: Public // Description: //////////////////////////////////////////////////////////////////// Decompressor:: Decompressor() { _source = NULL; _decompress = NULL; _dest = NULL; } //////////////////////////////////////////////////////////////////// // Function: Decompressor::Destructor // Access: Public // Description: //////////////////////////////////////////////////////////////////// Decompressor:: ~Decompressor() { cleanup(); } //////////////////////////////////////////////////////////////////// // Function: Decompressor::initiate // Access: Public // Description: Begins a background decompression of the named file // (whose filename must end in ".pz") to a new file // without the .pz extension. The source file is // removed after successful completion. //////////////////////////////////////////////////////////////////// int Decompressor:: initiate(const Filename &source_file) { string extension = source_file.get_extension(); if (extension == "pz") { Filename dest_file = source_file; dest_file = source_file.get_fullpath_wo_extension(); return initiate(source_file, dest_file); } if (downloader_cat.is_debug()) { downloader_cat.debug() << "Unknown file extension for decompressor: ." << extension << endl; } return EU_error_abort; } //////////////////////////////////////////////////////////////////// // Function: Decompressor::initiate // Access: Public // Description: Begins a background decompression from the named // source file to the named destination file. The // source file is removed after successful completion. //////////////////////////////////////////////////////////////////// int Decompressor:: initiate(const Filename &source_file, const Filename &dest_file) { cleanup(); // Open source file _source_filename = Filename(source_file); _source_filename.set_binary(); ifstream *source_fstream = new ifstream; _source = source_fstream; if (!_source_filename.open_read(*source_fstream)) { downloader_cat.error() << "Unable to read " << _source_filename << "\n"; return get_write_error(); } // Determine source file length source_fstream->seekg(0, ios::end); _source_length = source_fstream->tellg(); if (_source_length == 0) { downloader_cat.warning() << "Zero length file: " << source_file << "\n"; return EU_error_file_empty; } source_fstream->seekg(0, ios::beg); // Open destination file Filename dest_filename(dest_file); dest_filename.set_binary(); ofstream *dest_fstream = new ofstream; _dest = dest_fstream; if (dest_filename.exists()) { downloader_cat.info() << dest_filename << " already exists, removing.\n"; if (!dest_filename.unlink()) { downloader_cat.error() << "Unable to remove old " << dest_filename << "\n"; return get_write_error(); } } else { if (downloader_cat.is_debug()) { downloader_cat.debug() << dest_filename << " does not already exist.\n"; } } if (!dest_filename.open_write(*dest_fstream)) { downloader_cat.error() << "Unable to write to " << dest_filename << "\n"; return get_write_error(); } // Now create the decompressor stream. _decompress = new IDecompressStream(_source, false); return EU_success; } //////////////////////////////////////////////////////////////////// // Function: Decompressor::run // Access: Public // Description: Called each frame to do the next bit of work in the // background task. Returns EU_ok if a chunk is // completed but there is more to go, or EU_success when // we're all done. Any other return value indicates an // error. //////////////////////////////////////////////////////////////////// int Decompressor:: run() { if (_decompress == (istream *)NULL) { // Hmm, we were already done. return EU_success; } // Read a bunch of characters from the decompress stream, but no // more than decompressor_buffer_size. int count = 0; int ch = _decompress->get(); while (!_decompress->eof() && !_decompress->fail()) { _dest->put(ch); if (++count >= decompressor_buffer_size) { // That's enough for now. return EU_ok; } ch = _decompress->get(); } // All done! cleanup(); if (!keep_temporary_files) { _source_filename.unlink(); } return EU_success; } //////////////////////////////////////////////////////////////////// // Function: Decompressor::decompress // Access: Public // Description: Performs a foreground decompression of the named // file; does not return until the decompression is // complete. //////////////////////////////////////////////////////////////////// bool Decompressor:: decompress(const Filename &source_file) { int ret = initiate(source_file); if (ret < 0) return false; int ch = _decompress->get(); while (!_decompress->eof() && !_decompress->fail()) { _dest->put(ch); ch = _decompress->get(); } cleanup(); if (!keep_temporary_files) { _source_filename.unlink(); } return true; } //////////////////////////////////////////////////////////////////// // Function: Decompressor::decompress // Access: Public // Description: Does an in-memory decompression of the indicated // Ramfile. The decompressed contents are written back // into the same Ramfile on completion. //////////////////////////////////////////////////////////////////// bool Decompressor:: decompress(Ramfile &source_and_dest_file) { istringstream source(source_and_dest_file._data); ostringstream dest; IDecompressStream decompress(&source, false); int ch = decompress.get(); while (!decompress.eof() && !decompress.fail()) { dest.put(ch); ch = decompress.get(); } source_and_dest_file._pos = 0; source_and_dest_file._data = dest.str(); return true; } //////////////////////////////////////////////////////////////////// // Function: Decompressor::get_progress // Access: Public // Description: Returns the ratio through the decompression step // in the background. //////////////////////////////////////////////////////////////////// float Decompressor:: get_progress() const { if (_decompress == (istream *)NULL) { // Hmm, we were already done. return 1.0f; } nassertr(_source_length > 0, 0.0); size_t source_pos = _source->tellg(); // We stop the scale at 0.99 because there may be a little bit more // to do even after the decompressor has read all of the source. return (0.99f * (float)source_pos / (float)_source_length); } //////////////////////////////////////////////////////////////////// // Function: Decompressor::cleanup // Access: Private // Description: Called to reset a previous decompressor state and // clean up properly. //////////////////////////////////////////////////////////////////// void Decompressor:: cleanup() { if (_source != (istream *)NULL) { delete _source; _source = NULL; } if (_dest != (ostream *)NULL) { delete _dest; _dest = NULL; } if (_decompress != (istream *)NULL) { delete _decompress; _decompress = NULL; } } <|endoftext|>
<commit_before>/* * Copyright (c) 2015, Nagoya University * 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 Autoware nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <opencv/cv.h> #include <opencv/highgui.h> #include <opencv2/opencv.hpp> #include <cv_bridge/cv_bridge.h> #include "ros/ros.h" #include <sensor_msgs/image_encodings.h> #include <sensor_msgs/CompressedImage.h> #include "cv_tracker/image_obj_ranged.h" #include <math.h> #include <float.h> #define NO_DATA 0 static char window_name[] = "image_d_viewer"; //for imageCallback static cv_bridge::CvImagePtr cv_image; static IplImage temp; static IplImage *image; static double ratio = 1; //resize ratio static cv_tracker::image_obj_ranged car_fused_objects; static cv_tracker::image_obj_ranged pedestrian_fused_objects; static const int OBJ_RECT_THICKNESS = 3; static void showImage(); /* check whether floating value x is nearly 0 or not */ static inline bool isNearlyNODATA(float x) { float abs_x = (float)fabs(x); const int rangeScale = 100; return(abs_x < FLT_MIN*rangeScale); } void showRects(IplImage *Image, std::vector<cv_tracker::image_rect_ranged> objects, double ratio, CvScalar col) { unsigned int object_num = objects.size(); for(unsigned int i = 0; i < object_num; i++) { if (!isNearlyNODATA(objects.at(i).range)) { CvPoint p1=cvPoint(objects.at(i).rect.x, objects.at(i).rect.y); CvPoint p2=cvPoint(objects.at(i).rect.x + objects.at(i).rect.width, objects.at(i).rect.y + objects.at(i).rect.height); cvRectangle(Image,p1,p2,col,OBJ_RECT_THICKNESS); } } } static void obj_carCallback(const cv_tracker::image_obj_ranged& fused_objects) { if(image == NULL){ return; } car_fused_objects = fused_objects; showImage(); } static void obj_personCallback(const cv_tracker::image_obj_ranged& fused_objects) { if(image == NULL){ return; } pedestrian_fused_objects = fused_objects; showImage(); } static void imageCallback(const sensor_msgs::Image& image_source) { cv_image = cv_bridge::toCvCopy(image_source, sensor_msgs::image_encodings::BGR8); temp = cv_image->image; image = &temp; showImage(); } static void showImage() { IplImage* image_clone = cvCloneImage(image); char distance_string[32]; CvFont dfont; float hscale = 0.7f; float vscale = 0.7f; float italicscale = 0.0f; int thickness = 1; std::string objectLabel; CvFont dfont_label; float hscale_label = 0.5f; float vscale_label = 0.5f; CvSize text_size; int baseline = 0; cvInitFont(&dfont_label, CV_FONT_HERSHEY_COMPLEX, hscale_label, vscale_label, italicscale, thickness, CV_AA); objectLabel = car_fused_objects.type; cvGetTextSize(objectLabel.data(), &dfont_label, &text_size, &baseline); /* * Plot obstacle frame */ showRects(image_clone, car_fused_objects.obj, ratio, cvScalar(255.0,255.0,0.0)); showRects(image_clone, pedestrian_fused_objects.obj, ratio, cvScalar(0.0,255.0,0.0)); /* * Plot car distance data on image */ for (unsigned int i = 0; i < car_fused_objects.obj.size(); i++) { if(!isNearlyNODATA(car_fused_objects.obj.at(i).range)) { int rect_x = car_fused_objects.obj.at(i).rect.x; int rect_y = car_fused_objects.obj.at(i).rect.y; int rect_width = car_fused_objects.obj.at(i).rect.width; int rect_height = car_fused_objects.obj.at(i).rect.height; float range = car_fused_objects.obj.at(i).range; /* put label */ CvPoint labelOrg = cvPoint(rect_x - OBJ_RECT_THICKNESS, rect_y - baseline - OBJ_RECT_THICKNESS); cvRectangle(image_clone, cvPoint(labelOrg.x + 0, labelOrg.y + baseline), cvPoint(labelOrg.x + text_size.width, labelOrg.y - text_size.height), CV_RGB(0, 0, 0), // label background color is black -1, 8, 0 ); cvPutText(image_clone, objectLabel.data(), labelOrg, &dfont_label, CV_RGB(255, 255, 255) // label text color is white ); /* put distance data */ cvRectangle(image_clone, cv::Point(rect_x + (rect_width/2) - (((int)log10(range/100)+1) * 5 + 45), rect_y + rect_height + 5), cv::Point(rect_x + (rect_width/2) + (((int)log10(range/100)+1) * 8 + 38), rect_y + rect_height + 30), cv::Scalar(255,255,255), -1); cvInitFont (&dfont, CV_FONT_HERSHEY_COMPLEX , hscale, vscale, italicscale, thickness, CV_AA); sprintf(distance_string, "%.2f m", range / 100); //unit of length is meter cvPutText(image_clone, distance_string, cvPoint(rect_x + (rect_width/2) - (((int)log10(range/100)+1) * 5 + 40), rect_y + rect_height + 25), &dfont, CV_RGB(255, 0, 0)); } } objectLabel = pedestrian_fused_objects.type; cvGetTextSize(objectLabel.data(), &dfont_label, &text_size, &baseline); /* * Plot pedestrian distance data on image */ for (unsigned int i = 0; i < pedestrian_fused_objects.obj.size(); i++) { if(!isNearlyNODATA(pedestrian_fused_objects.obj.at(i).range)) { int rect_x = pedestrian_fused_objects.obj.at(i).rect.x; int rect_y = pedestrian_fused_objects.obj.at(i).rect.y; int rect_width = pedestrian_fused_objects.obj.at(i).rect.width; int rect_height = pedestrian_fused_objects.obj.at(i).rect.height; float range = pedestrian_fused_objects.obj.at(i).range; /* put label */ CvPoint labelOrg = cvPoint(rect_x - OBJ_RECT_THICKNESS, rect_y - baseline - OBJ_RECT_THICKNESS); cvRectangle(image_clone, cvPoint(labelOrg.x + 0, labelOrg.y + baseline), cvPoint(labelOrg.x + text_size.width, labelOrg.y - text_size.height), CV_RGB(0, 0, 0), // label background color is black -1, 8, 0 ); cvPutText(image_clone, objectLabel.data(), labelOrg, &dfont_label, CV_RGB(255, 255, 255) // label text color is white ); /* put distance data */ cvRectangle(image_clone, cv::Point(rect_x + (rect_width/2) - (((int)log10(range/100)+1) * 5 + 45), rect_y + rect_height + 5), cv::Point(rect_x + (rect_width/2) + (((int)log10(range/100)+1) * 8 + 38), rect_y + rect_height + 30), cv::Scalar(255,255,255), -1); cvInitFont (&dfont, CV_FONT_HERSHEY_COMPLEX , hscale, vscale, italicscale, thickness, CV_AA); sprintf(distance_string, "%.2f m", range / 100); //unit of length is meter cvPutText(image_clone, distance_string, cvPoint(rect_x + (rect_width/2) - (((int)log10(range/100)+1) * 5 + 40), rect_y + rect_height + 25), &dfont, CV_RGB(255, 0, 0)); } } /* * Show image */ if (cvGetWindowHandle(window_name) != NULL) // Guard not to write destroyed window by using close button on the window { cvShowImage(window_name, image_clone); cvWaitKey(2); } cvReleaseImage(&image_clone); } int main(int argc, char **argv) { /** * The ros::init() function needs to see argc and argv so that it can perform * any ROS arguments and name remapping that were provided at the command line. For programmatic * remappings you can use a different version of init() which takes remappings * directly, but for most command-line programs, passing argc and argv is the easiest * way to do it. The third argument to init() is the name of the node. * * You must call one of the versions of ros::init() before using any other * part of the ROS system. */ cvNamedWindow(window_name, 2); cvStartWindowThread(); image = NULL; car_fused_objects.obj.clear(); pedestrian_fused_objects.obj.clear(); ros::init(argc, argv, "image_d_viewer"); /** * NodeHandle is the main access point to communications with the ROS system. * The first NodeHandle constructed will fully initialize this node, and the last * NodeHandle destructed will close down the node. */ ros::NodeHandle n; /** * The subscribe() call is how you tell ROS that you want to receive messages * on a given topic. This invokes a call to the ROS * master node, which keeps a registry of who is publishing and who * is subscribing. Messages are passed to a callback function, here * called Callback. subscribe() returns a Subscriber object that you * must hold on to until you want to unsubscribe. When all copies of the Subscriber * object go out of scope, this callback will automatically be unsubscribed from * this topic. * * The second parameter to the subscribe() function is the size of the message * queue. If messages are arriving faster than they are being processed, this * is the number of messages that will be buffered up before beginning to throw * away the oldest ones. */ ros::Subscriber image_sub = n.subscribe("/image_raw", 1, imageCallback); ros::Subscriber obj_car_sub = n.subscribe("/obj_car/image_obj_ranged", 1, obj_carCallback); ros::Subscriber obj_person_sub = n.subscribe("/obj_car/image_obj_ranged", 1, obj_personCallback); /** * ros::spin() will enter a loop, pumping callbacks. With this version, all * callbacks will be called from within this thread (the main one). ros::spin() * will exit when Ctrl-C is pressed, or the node is shutdown by the master. */ ros::spin(); cvDestroyWindow(window_name); return 0; } <commit_msg>Modified image_d_viewe to make subscribed topic name being selectable<commit_after>/* * Copyright (c) 2015, Nagoya University * 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 Autoware nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <opencv/cv.h> #include <opencv/highgui.h> #include <opencv2/opencv.hpp> #include <cv_bridge/cv_bridge.h> #include "ros/ros.h" #include <sensor_msgs/image_encodings.h> #include <sensor_msgs/CompressedImage.h> #include "cv_tracker/image_obj_ranged.h" #include <math.h> #include <float.h> #define NO_DATA 0 static char window_name_base[] = "image_d_viewer"; static std::string window_name; //for imageCallback static cv_bridge::CvImagePtr cv_image; static IplImage temp; static IplImage *image; static double ratio = 1; //resize ratio static cv_tracker::image_obj_ranged car_fused_objects; static cv_tracker::image_obj_ranged pedestrian_fused_objects; static const int OBJ_RECT_THICKNESS = 3; static void showImage(); /* check whether floating value x is nearly 0 or not */ static inline bool isNearlyNODATA(float x) { float abs_x = (float)fabs(x); const int rangeScale = 100; return(abs_x < FLT_MIN*rangeScale); } void showRects(IplImage *Image, std::vector<cv_tracker::image_rect_ranged> objects, double ratio, CvScalar col) { unsigned int object_num = objects.size(); for(unsigned int i = 0; i < object_num; i++) { if (!isNearlyNODATA(objects.at(i).range)) { CvPoint p1=cvPoint(objects.at(i).rect.x, objects.at(i).rect.y); CvPoint p2=cvPoint(objects.at(i).rect.x + objects.at(i).rect.width, objects.at(i).rect.y + objects.at(i).rect.height); cvRectangle(Image,p1,p2,col,OBJ_RECT_THICKNESS); } } } static void obj_carCallback(const cv_tracker::image_obj_ranged& fused_objects) { if(image == NULL){ return; } car_fused_objects = fused_objects; showImage(); } static void obj_personCallback(const cv_tracker::image_obj_ranged& fused_objects) { if(image == NULL){ return; } pedestrian_fused_objects = fused_objects; showImage(); } static void imageCallback(const sensor_msgs::Image& image_source) { cv_image = cv_bridge::toCvCopy(image_source, sensor_msgs::image_encodings::BGR8); temp = cv_image->image; image = &temp; showImage(); } static void showImage() { IplImage* image_clone = cvCloneImage(image); char distance_string[32]; CvFont dfont; float hscale = 0.7f; float vscale = 0.7f; float italicscale = 0.0f; int thickness = 1; std::string objectLabel; CvFont dfont_label; float hscale_label = 0.5f; float vscale_label = 0.5f; CvSize text_size; int baseline = 0; cvInitFont(&dfont_label, CV_FONT_HERSHEY_COMPLEX, hscale_label, vscale_label, italicscale, thickness, CV_AA); objectLabel = car_fused_objects.type; cvGetTextSize(objectLabel.data(), &dfont_label, &text_size, &baseline); /* * Plot obstacle frame */ showRects(image_clone, car_fused_objects.obj, ratio, cvScalar(255.0,255.0,0.0)); showRects(image_clone, pedestrian_fused_objects.obj, ratio, cvScalar(0.0,255.0,0.0)); /* * Plot car distance data on image */ for (unsigned int i = 0; i < car_fused_objects.obj.size(); i++) { if(!isNearlyNODATA(car_fused_objects.obj.at(i).range)) { int rect_x = car_fused_objects.obj.at(i).rect.x; int rect_y = car_fused_objects.obj.at(i).rect.y; int rect_width = car_fused_objects.obj.at(i).rect.width; int rect_height = car_fused_objects.obj.at(i).rect.height; float range = car_fused_objects.obj.at(i).range; /* put label */ CvPoint labelOrg = cvPoint(rect_x - OBJ_RECT_THICKNESS, rect_y - baseline - OBJ_RECT_THICKNESS); cvRectangle(image_clone, cvPoint(labelOrg.x + 0, labelOrg.y + baseline), cvPoint(labelOrg.x + text_size.width, labelOrg.y - text_size.height), CV_RGB(0, 0, 0), // label background color is black -1, 8, 0 ); cvPutText(image_clone, objectLabel.data(), labelOrg, &dfont_label, CV_RGB(255, 255, 255) // label text color is white ); /* put distance data */ cvRectangle(image_clone, cv::Point(rect_x + (rect_width/2) - (((int)log10(range/100)+1) * 5 + 45), rect_y + rect_height + 5), cv::Point(rect_x + (rect_width/2) + (((int)log10(range/100)+1) * 8 + 38), rect_y + rect_height + 30), cv::Scalar(255,255,255), -1); cvInitFont (&dfont, CV_FONT_HERSHEY_COMPLEX , hscale, vscale, italicscale, thickness, CV_AA); sprintf(distance_string, "%.2f m", range / 100); //unit of length is meter cvPutText(image_clone, distance_string, cvPoint(rect_x + (rect_width/2) - (((int)log10(range/100)+1) * 5 + 40), rect_y + rect_height + 25), &dfont, CV_RGB(255, 0, 0)); } } objectLabel = pedestrian_fused_objects.type; cvGetTextSize(objectLabel.data(), &dfont_label, &text_size, &baseline); /* * Plot pedestrian distance data on image */ for (unsigned int i = 0; i < pedestrian_fused_objects.obj.size(); i++) { if(!isNearlyNODATA(pedestrian_fused_objects.obj.at(i).range)) { int rect_x = pedestrian_fused_objects.obj.at(i).rect.x; int rect_y = pedestrian_fused_objects.obj.at(i).rect.y; int rect_width = pedestrian_fused_objects.obj.at(i).rect.width; int rect_height = pedestrian_fused_objects.obj.at(i).rect.height; float range = pedestrian_fused_objects.obj.at(i).range; /* put label */ CvPoint labelOrg = cvPoint(rect_x - OBJ_RECT_THICKNESS, rect_y - baseline - OBJ_RECT_THICKNESS); cvRectangle(image_clone, cvPoint(labelOrg.x + 0, labelOrg.y + baseline), cvPoint(labelOrg.x + text_size.width, labelOrg.y - text_size.height), CV_RGB(0, 0, 0), // label background color is black -1, 8, 0 ); cvPutText(image_clone, objectLabel.data(), labelOrg, &dfont_label, CV_RGB(255, 255, 255) // label text color is white ); /* put distance data */ cvRectangle(image_clone, cv::Point(rect_x + (rect_width/2) - (((int)log10(range/100)+1) * 5 + 45), rect_y + rect_height + 5), cv::Point(rect_x + (rect_width/2) + (((int)log10(range/100)+1) * 8 + 38), rect_y + rect_height + 30), cv::Scalar(255,255,255), -1); cvInitFont (&dfont, CV_FONT_HERSHEY_COMPLEX , hscale, vscale, italicscale, thickness, CV_AA); sprintf(distance_string, "%.2f m", range / 100); //unit of length is meter cvPutText(image_clone, distance_string, cvPoint(rect_x + (rect_width/2) - (((int)log10(range/100)+1) * 5 + 40), rect_y + rect_height + 25), &dfont, CV_RGB(255, 0, 0)); } } /* * Show image */ if (cvGetWindowHandle(window_name.c_str()) != NULL) // Guard not to write destroyed window by using close button on the window { cvShowImage(window_name.c_str(), image_clone); cvWaitKey(2); } cvReleaseImage(&image_clone); } int main(int argc, char **argv) { /** * The ros::init() function needs to see argc and argv so that it can perform * any ROS arguments and name remapping that were provided at the command line. For programmatic * remappings you can use a different version of init() which takes remappings * directly, but for most command-line programs, passing argc and argv is the easiest * way to do it. The third argument to init() is the name of the node. * * You must call one of the versions of ros::init() before using any other * part of the ROS system. */ ros::init(argc, argv, "image_d_viewer"); /** * NodeHandle is the main access point to communications with the ROS system. * The first NodeHandle constructed will fully initialize this node, and the last * NodeHandle destructed will close down the node. */ ros::NodeHandle n; ros::NodeHandle private_nh("~"); /** * The subscribe() call is how you tell ROS that you want to receive messages * on a given topic. This invokes a call to the ROS * master node, which keeps a registry of who is publishing and who * is subscribing. Messages are passed to a callback function, here * called Callback. subscribe() returns a Subscriber object that you * must hold on to until you want to unsubscribe. When all copies of the Subscriber * object go out of scope, this callback will automatically be unsubscribed from * this topic. * * The second parameter to the subscribe() function is the size of the message * queue. If messages are arriving faster than they are being processed, this * is the number of messages that will be buffered up before beginning to throw * away the oldest ones. */ std::string image_topic; std::string car_topic; std::string person_topic; if (!private_nh.getParam("image_topic", image_topic)) { image_topic = "/image_raw"; } if (!private_nh.getParam("car_topic", car_topic)) { car_topic = "/obj_car/image_obj_ranged"; } if (!private_nh.getParam("person_topic", person_topic)) { person_topic = "/obj_person/image_obj_ranged"; } std::string name_space_str = ros::this_node::getNamespace(); if (name_space_str != "/") { window_name = std::string(window_name_base) + " (" + ros::this_node::getNamespace() + ")"; } else { window_name = std::string(window_name_base); } cvNamedWindow(window_name.c_str(), 2); cvStartWindowThread(); image = NULL; car_fused_objects.obj.clear(); pedestrian_fused_objects.obj.clear(); ros::Subscriber image_sub = n.subscribe(image_topic, 1, imageCallback); ros::Subscriber obj_car_sub = n.subscribe(car_topic, 1, obj_carCallback); ros::Subscriber obj_person_sub = n.subscribe(person_topic, 1, obj_personCallback); /** * ros::spin() will enter a loop, pumping callbacks. With this version, all * callbacks will be called from within this thread (the main one). ros::spin() * will exit when Ctrl-C is pressed, or the node is shutdown by the master. */ ros::spin(); cvDestroyWindow(window_name.c_str()); return 0; } <|endoftext|>
<commit_before>#pragma once #include "stdafx.h" #include "cJSON/cJSON.h" CLANG_DIAGNOSTIC_PUSH; CLANG_DIAGNOSTIC_IGNORE("-Wunused-macros"); // I dont think namespace matters for macros but whatever namespace asdf { #define CJSON_OBJ(node_name, obj_name) cJSON_GetObjectItem(node_name, #obj_name) #define CJSON_INT(node_name, int_name) CJSON_OBJ(node_name, int_name)->valueint #define CJSON_FLOAT(node_name, float_name) static_cast<float>(CJSON_OBJ(node_name, float_name)->valuedouble) #define CJSON_DOUBLE(node_name, double_name) CJSON_OBJ(node_name, double_name)->valuedouble #define CJSON_STR(node_name, str_name) CJSON_OBJ(node_name, str_name)->valuestring #define CJSON_ENUM(node_name, int_name, enum_type) static_cast<enum_type>(CJSON_INT(node_name, int_name)) #define CJSON_VALUE_ARRAY(container_node, container, valuetype, resize_container) \ { \ size_t len = cJSON_GetArraySize(container_node); \ \ if(resize_container) \ { \ container.clear(); \ container.resize(len); \ } \ else \ { \ ASSERT(container.size() == len, ""); \ } \ \ for(size_t i = 0; i < len; ++i) \ { \ cJSON* json = cJSON_GetArrayItem(container_node, i); \ container[i] = json->valuetype; \ } \ } //--- #define CJSON_GET_INT(int_name) int_name = CJSON_INT(root, int_name) #define CJSON_GET_FLOAT(float_name) float_name = CJSON_FLOAT(root, float_name) #define CJSON_GET_DOUBLE(double_name) int_name = CJSON_DOUBLE(root, double_name) #define CJSON_GET_STR(str_name) str_name = CJSON_STR(root, str_name) #define CJSON_GET_ITEM(obj_name) obj_name.from_JSON(cJSON_GetObjectItem(root, #obj_name)); #define CJSON_GET_ENUM_INT(int_name, enum_type) int_name = CJSON_ENUM(int_name, enum_type); #define CJSON_GET_VALUE_ARRAY(container, valuetype, resize_container) \ { \ cJSON* container_json = cJSON_GetObjectItem(root, #container); \ CJSON_VALUE_ARRAY(container_json, container, valuetype, resize_container) \ } //--- #define CJSON_GET_INT_ARRAY(container) CJSON_GET_VALUE_ARRAY(container, valueint, false); #define CJSON_GET_DOUBLE_ARRAY(container) CJSON_GET_VALUE_ARRAY(container, valuedouble, false); #define CJSON_GET_STR_ARRAY(container) CJSON_GET_VALUE_ARRAY(container, valuestring, false); #define CJSON_GET_INT_VECTOR(container) CJSON_GET_VALUE_ARRAY(container, valueint, true); #define CJSON_GET_DOUBLE_VECTOR(container) CJSON_GET_VALUE_ARRAY(container, valuedouble, true); #define CJSON_GET_STR_VECTOR(container) CJSON_GET_VALUE_ARRAY(container, valuestring, true); #define CJSON_GET_ITEM_ARRAY(container) \ { \ cJSON* container##_json = cJSON_GetObjectItem(root, #container); \ size_t len = cJSON_GetArraySize(container##_json); \ for(size_t i = 0; i < len; ++i) \ { \ container[i].from_JSON(cJSON_GetArrayItem(container##_json, i)); \ } \ } //--- #define CJSON_GET_ITEM_VECTOR(container) \ { \ cJSON* container##_json = cJSON_GetObjectItem(root, #container); \ size_t len = cJSON_GetArraySize(container##_json); \ \ container.clear(); \ container.resize(len); \ \ for(size_t i = 0; i < len; ++i) \ { \ container[i].from_JSON(cJSON_GetArrayItem(container##_json, i)); \ } \ } //--- /* */ #define CJSON_CREATE_ROOT() cJSON* root = cJSON_CreateObject() #define CJSON_ADD_BLANK_ITEM(root, child) \ cJSON* child##_json = cJSON_CreateObject(); \ cJSON_AddItemToObject(root, #child, child##_json); //--- #define CJSON_ADD_ITEM(obj) cJSON_AddItemToObject(root, #obj, obj.to_JSON()); #define CJSON_ADD_NUMBER(num_name) cJSON_AddNumberToObject(root, #num_name, num_name); #define CJSON_ADD_INT(num_name) CJSON_ADD_NUMBER(num_name) #define CJSON_ADD_STR(str_name) cJSON_AddStringToObject(root, #str_name, (str_name##.c_str() == nullptr) ? "" : str_name##.c_str()); #define CJSON_ADD_CSTR(str_name) cJSON_AddStringToObject(root, #str_name, str_name); #define CJSON_ITEM_ARRAY(container_name) \ cJSON* container_name##_json = cJSON_CreateArray(); \ for(auto const& thing : container_name) \ { cJSON_AddItemToArray(container_name##_json, thing.to_JSON()); } //--- #define CJSON_ADD_INT_ARRAY(container) cJSON_AddItemToObject(root, #container, cJSON_CreateIntArray(container.data(), container.size())); #define CJSON_ADD_ITEM_ARRAY(container_name) \ CJSON_ITEM_ARRAY(container_name); \ cJSON_AddItemToObject(root, #container_name, container_name##_json); //--- } CLANG_DIAGNOSTIC_POP<commit_msg>removed the asdf namespace from cjson_utils added a constexpr cstring array of json type strings for debugging and error messages<commit_after>#pragma once #include "stdafx.h" #include "cJSON/cJSON.h" #include <array> CLANG_DIAGNOSTIC_PUSH; CLANG_DIAGNOSTIC_IGNORE("-Wunused-macros"); constexpr std::array<char const*, cJSON_Object+1> cJSON_type_strings = { "cJSON_False" , "cJSON_True" , "cJSON_NULL" , "cJSON_Number" , "cJSON_String" , "cJSON_Array" , "cJSON_Object" }; #define CJSON_OBJ(node_name, obj_name) cJSON_GetObjectItem(node_name, #obj_name) #define CJSON_INT(node_name, int_name) CJSON_OBJ(node_name, int_name)->valueint #define CJSON_FLOAT(node_name, float_name) static_cast<float>(CJSON_OBJ(node_name, float_name)->valuedouble) #define CJSON_DOUBLE(node_name, double_name) CJSON_OBJ(node_name, double_name)->valuedouble #define CJSON_STR(node_name, str_name) CJSON_OBJ(node_name, str_name)->valuestring #define CJSON_ENUM(node_name, int_name, enum_type) static_cast<enum_type>(CJSON_INT(node_name, int_name)) #define CJSON_VALUE_ARRAY(container_node, container, valuetype, resize_container) \ { \ size_t len = cJSON_GetArraySize(container_node); \ \ if(resize_container) \ { \ container.clear(); \ container.resize(len); \ } \ else \ { \ ASSERT(container.size() == len, ""); \ } \ \ for(size_t i = 0; i < len; ++i) \ { \ cJSON* json = cJSON_GetArrayItem(container_node, i); \ container[i] = json->valuetype; \ } \ } //--- #define CJSON_GET_INT(int_name) int_name = CJSON_INT(root, int_name) #define CJSON_GET_FLOAT(float_name) float_name = CJSON_FLOAT(root, float_name) #define CJSON_GET_DOUBLE(double_name) int_name = CJSON_DOUBLE(root, double_name) #define CJSON_GET_STR(str_name) str_name = CJSON_STR(root, str_name) #define CJSON_GET_ITEM(obj_name) obj_name.from_JSON(cJSON_GetObjectItem(root, #obj_name)); #define CJSON_GET_ENUM_INT(int_name, enum_type) int_name = CJSON_ENUM(int_name, enum_type); #define CJSON_GET_VALUE_ARRAY(container, valuetype, resize_container) \ { \ cJSON* container_json = cJSON_GetObjectItem(root, #container); \ CJSON_VALUE_ARRAY(container_json, container, valuetype, resize_container) \ } //--- #define CJSON_GET_INT_ARRAY(container) CJSON_GET_VALUE_ARRAY(container, valueint, false); #define CJSON_GET_DOUBLE_ARRAY(container) CJSON_GET_VALUE_ARRAY(container, valuedouble, false); #define CJSON_GET_STR_ARRAY(container) CJSON_GET_VALUE_ARRAY(container, valuestring, false); #define CJSON_GET_INT_VECTOR(container) CJSON_GET_VALUE_ARRAY(container, valueint, true); #define CJSON_GET_DOUBLE_VECTOR(container) CJSON_GET_VALUE_ARRAY(container, valuedouble, true); #define CJSON_GET_STR_VECTOR(container) CJSON_GET_VALUE_ARRAY(container, valuestring, true); #define CJSON_GET_ITEM_ARRAY(container) \ { \ cJSON* container##_json = cJSON_GetObjectItem(root, #container); \ size_t len = cJSON_GetArraySize(container##_json); \ for(size_t i = 0; i < len; ++i) \ { \ container[i].from_JSON(cJSON_GetArrayItem(container##_json, i)); \ } \ } //--- #define CJSON_GET_ITEM_VECTOR(container) \ { \ cJSON* container##_json = cJSON_GetObjectItem(root, #container); \ size_t len = cJSON_GetArraySize(container##_json); \ \ container.clear(); \ container.resize(len); \ \ for(size_t i = 0; i < len; ++i) \ { \ container[i].from_JSON(cJSON_GetArrayItem(container##_json, i)); \ } \ } //--- /* */ #define CJSON_CREATE_ROOT() cJSON* root = cJSON_CreateObject() #define CJSON_ADD_BLANK_ITEM(root, child) \ cJSON* child##_json = cJSON_CreateObject(); \ cJSON_AddItemToObject(root, #child, child##_json); //--- #define CJSON_ADD_ITEM(obj) cJSON_AddItemToObject(root, #obj, obj.to_JSON()); #define CJSON_ADD_NUMBER(num_name) cJSON_AddNumberToObject(root, #num_name, num_name); #define CJSON_ADD_INT(num_name) CJSON_ADD_NUMBER(num_name) #define CJSON_ADD_STR(str_name) cJSON_AddStringToObject(root, #str_name, (str_name##.c_str() == nullptr) ? "" : str_name##.c_str()); #define CJSON_ADD_CSTR(str_name) cJSON_AddStringToObject(root, #str_name, str_name); #define CJSON_ITEM_ARRAY(container_name) \ cJSON* container_name##_json = cJSON_CreateArray(); \ for(auto const& thing : container_name) \ { cJSON_AddItemToArray(container_name##_json, thing.to_JSON()); } //--- #define CJSON_ADD_INT_ARRAY(container) cJSON_AddItemToObject(root, #container, cJSON_CreateIntArray(container.data(), container.size())); #define CJSON_ADD_ITEM_ARRAY(container_name) \ CJSON_ITEM_ARRAY(container_name); \ cJSON_AddItemToObject(root, #container_name, container_name##_json); //--- CLANG_DIAGNOSTIC_POP<|endoftext|>
<commit_before>/*========================================================================= Library: CTK Copyright (c) 2010 Kitware 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.commontk.org/LICENSE Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ // QT includes #include <QDebug> #include <QHBoxLayout> // CTK includes #include "ctkDoubleSlider.h" // STD includes #include <limits> //----------------------------------------------------------------------------- class ctkDoubleSliderPrivate: public ctkPrivate<ctkDoubleSlider> { public: ctkDoubleSliderPrivate(); int toInt(double _value)const; double fromInt(int _value)const; void init(); void updateOffset(double value); QSlider* Slider; double Minimum; double Maximum; // we should have a Offset and SliderPositionOffset (and MinimumOffset?) double Offset; double SingleStep; double Value; }; // -------------------------------------------------------------------------- ctkDoubleSliderPrivate::ctkDoubleSliderPrivate() { this->Slider = 0; this->Minimum = 0.; this->Maximum = 100.; this->Offset = 0.; this->SingleStep = 1.; this->Value = 0.; } // -------------------------------------------------------------------------- void ctkDoubleSliderPrivate::init() { CTK_P(ctkDoubleSlider); this->Slider = new QSlider(p); QHBoxLayout* l = new QHBoxLayout(p); l->addWidget(this->Slider); l->setContentsMargins(0,0,0,0); this->Minimum = this->Slider->minimum(); this->Maximum = this->Slider->maximum(); this->SingleStep = this->Slider->singleStep(); this->Value = this->Slider->value(); p->connect(this->Slider, SIGNAL(valueChanged(int)), p, SLOT(onValueChanged(int))); p->connect(this->Slider, SIGNAL(sliderMoved(int)), p, SLOT(onSliderMoved(int))); p->connect(this->Slider, SIGNAL(sliderPressed()), p, SIGNAL(sliderPressed())); p->connect(this->Slider, SIGNAL(sliderReleased()), p, SIGNAL(sliderReleased())); } // -------------------------------------------------------------------------- int ctkDoubleSliderPrivate::toInt(double doubleValue)const { double tmp = doubleValue / this->SingleStep; static const double minInt = std::numeric_limits<int>::min(); static const double maxInt = std::numeric_limits<int>::max(); #ifndef QT_NO_DEBUG if (tmp < minInt || tmp > maxInt) { qWarning("ctkDoubleSliderPrivate::toInt value out of bounds !"); } #endif tmp = qBound(minInt, tmp, maxInt); int intValue = qRound(tmp); //qDebug() << __FUNCTION__ << doubleValue << tmp << intValue; return intValue; } // -------------------------------------------------------------------------- double ctkDoubleSliderPrivate::fromInt(int intValue)const { double doubleValue = this->SingleStep * (this->Offset + intValue) ; //qDebug() << __FUNCTION__ << intValue << doubleValue; return doubleValue; } // -------------------------------------------------------------------------- void ctkDoubleSliderPrivate::updateOffset(double value) { this->Offset = (value / this->SingleStep) - this->toInt(value); } // -------------------------------------------------------------------------- ctkDoubleSlider::ctkDoubleSlider(QWidget* _parent) : Superclass(_parent) { CTK_INIT_PRIVATE(ctkDoubleSlider); ctk_d()->init(); } // -------------------------------------------------------------------------- ctkDoubleSlider::ctkDoubleSlider(Qt::Orientation _orientation, QWidget* _parent) : Superclass(_parent) { CTK_INIT_PRIVATE(ctkDoubleSlider); ctk_d()->init(); this->setOrientation(_orientation); } // -------------------------------------------------------------------------- ctkDoubleSlider::~ctkDoubleSlider() { } // -------------------------------------------------------------------------- void ctkDoubleSlider::setMinimum(double min) { CTK_D(ctkDoubleSlider); d->Minimum = min; if (d->Minimum >= d->Value) { d->updateOffset(d->Minimum); } d->Slider->setMinimum(d->toInt(min)); } // -------------------------------------------------------------------------- void ctkDoubleSlider::setMaximum(double max) { CTK_D(ctkDoubleSlider); d->Maximum = max; if (d->Maximum <= d->Value) { d->updateOffset(d->Maximum); } d->Slider->setMaximum(d->toInt(max)); } // -------------------------------------------------------------------------- void ctkDoubleSlider::setRange(double min, double max) { CTK_D(ctkDoubleSlider); d->Minimum = min; d->Maximum = max; if (d->Minimum >= d->Value) { d->updateOffset(d->Minimum); } if (d->Maximum <= d->Value) { d->updateOffset(d->Maximum); } d->Slider->setRange(d->toInt(min), d->toInt(max)); } // -------------------------------------------------------------------------- double ctkDoubleSlider::minimum()const { CTK_D(const ctkDoubleSlider); return d->Minimum; } // -------------------------------------------------------------------------- double ctkDoubleSlider::maximum()const { CTK_D(const ctkDoubleSlider); return d->Maximum; } // -------------------------------------------------------------------------- double ctkDoubleSlider::sliderPosition()const { CTK_D(const ctkDoubleSlider); return d->fromInt(d->Slider->sliderPosition()); } // -------------------------------------------------------------------------- void ctkDoubleSlider::setSliderPosition(double newSliderPosition) { CTK_D(ctkDoubleSlider); d->Slider->setSliderPosition(d->toInt(newSliderPosition)); } // -------------------------------------------------------------------------- double ctkDoubleSlider::value()const { CTK_D(const ctkDoubleSlider); return d->Value; } // -------------------------------------------------------------------------- void ctkDoubleSlider::setValue(double newValue) { CTK_D(ctkDoubleSlider); newValue = qBound(d->Minimum, newValue, d->Maximum); d->updateOffset(newValue); int newIntValue = d->toInt(newValue); if (newIntValue != d->Slider->value()) { // d->Slider will emit a valueChanged signal that is connected to // ctkDoubleSlider::onValueChanged d->Slider->setValue(newIntValue); } else { double oldValue = d->Value; d->Value = newValue; // don't emit a valuechanged signal if the new value is quite // similar to the old value. if (qAbs(newValue - oldValue) > (d->SingleStep * 0.000000001)) { emit this->valueChanged(newValue); } } } // -------------------------------------------------------------------------- double ctkDoubleSlider::singleStep()const { CTK_D(const ctkDoubleSlider); return d->SingleStep; } // -------------------------------------------------------------------------- void ctkDoubleSlider::setSingleStep(double newStep) { CTK_D(ctkDoubleSlider); d->SingleStep = newStep; // update the new values of the QSlider double _value = d->Value; d->updateOffset(_value); bool oldBlockSignals = this->blockSignals(true); this->setRange(d->Minimum, d->Maximum); d->Slider->setValue(d->toInt(_value)); d->Value = _value; this->blockSignals(oldBlockSignals); } // -------------------------------------------------------------------------- double ctkDoubleSlider::tickInterval()const { CTK_D(const ctkDoubleSlider); return d->fromInt(d->Slider->tickInterval()); } // -------------------------------------------------------------------------- void ctkDoubleSlider::setTickInterval(double newTickInterval) { CTK_D(ctkDoubleSlider); d->Slider->setTickInterval(d->toInt(newTickInterval)); } // -------------------------------------------------------------------------- bool ctkDoubleSlider::hasTracking()const { CTK_D(const ctkDoubleSlider); return d->Slider->hasTracking(); } // -------------------------------------------------------------------------- void ctkDoubleSlider::setTracking(bool enable) { CTK_D(ctkDoubleSlider); d->Slider->setTracking(enable); } // -------------------------------------------------------------------------- void ctkDoubleSlider::triggerAction( QAbstractSlider::SliderAction action) { CTK_D(ctkDoubleSlider); d->Slider->triggerAction(action); } // -------------------------------------------------------------------------- Qt::Orientation ctkDoubleSlider::orientation()const { CTK_D(const ctkDoubleSlider); return d->Slider->orientation(); } // -------------------------------------------------------------------------- void ctkDoubleSlider::setOrientation(Qt::Orientation newOrientation) { CTK_D(ctkDoubleSlider); d->Slider->setOrientation(newOrientation); } // -------------------------------------------------------------------------- void ctkDoubleSlider::onValueChanged(int newValue) { CTK_D(ctkDoubleSlider); double doubleNewValue = d->fromInt(newValue); /* qDebug() << "onValueChanged: " << newValue << "->"<< d->fromInt(newValue+d->Offset) << " old: " << d->Value << "->" << d->toInt(d->Value) << "offset:" << d->Offset << doubleNewValue; */ if (d->Value == doubleNewValue) { return; } d->Value = doubleNewValue; emit this->valueChanged(d->Value); } // -------------------------------------------------------------------------- void ctkDoubleSlider::onSliderMoved(int newPosition) { CTK_D(const ctkDoubleSlider); emit this->sliderMoved(d->fromInt(newPosition)); } <commit_msg>ENH: ctkDoubleSlider now uses the same size policies than QSlider<commit_after>/*========================================================================= Library: CTK Copyright (c) 2010 Kitware 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.commontk.org/LICENSE Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ // QT includes #include <QDebug> #include <QHBoxLayout> // CTK includes #include "ctkDoubleSlider.h" // STD includes #include <limits> //----------------------------------------------------------------------------- class ctkDoubleSliderPrivate: public ctkPrivate<ctkDoubleSlider> { public: ctkDoubleSliderPrivate(); int toInt(double _value)const; double fromInt(int _value)const; void init(); void updateOffset(double value); QSlider* Slider; double Minimum; double Maximum; // we should have a Offset and SliderPositionOffset (and MinimumOffset?) double Offset; double SingleStep; double Value; }; // -------------------------------------------------------------------------- ctkDoubleSliderPrivate::ctkDoubleSliderPrivate() { this->Slider = 0; this->Minimum = 0.; this->Maximum = 100.; this->Offset = 0.; this->SingleStep = 1.; this->Value = 0.; } // -------------------------------------------------------------------------- void ctkDoubleSliderPrivate::init() { CTK_P(ctkDoubleSlider); this->Slider = new QSlider(p); QHBoxLayout* l = new QHBoxLayout(p); l->addWidget(this->Slider); l->setContentsMargins(0,0,0,0); this->Minimum = this->Slider->minimum(); this->Maximum = this->Slider->maximum(); this->SingleStep = this->Slider->singleStep(); this->Value = this->Slider->value(); p->connect(this->Slider, SIGNAL(valueChanged(int)), p, SLOT(onValueChanged(int))); p->connect(this->Slider, SIGNAL(sliderMoved(int)), p, SLOT(onSliderMoved(int))); p->connect(this->Slider, SIGNAL(sliderPressed()), p, SIGNAL(sliderPressed())); p->connect(this->Slider, SIGNAL(sliderReleased()), p, SIGNAL(sliderReleased())); p->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed, QSizePolicy::Slider)); } // -------------------------------------------------------------------------- int ctkDoubleSliderPrivate::toInt(double doubleValue)const { double tmp = doubleValue / this->SingleStep; static const double minInt = std::numeric_limits<int>::min(); static const double maxInt = std::numeric_limits<int>::max(); #ifndef QT_NO_DEBUG if (tmp < minInt || tmp > maxInt) { qWarning("ctkDoubleSliderPrivate::toInt value out of bounds !"); } #endif tmp = qBound(minInt, tmp, maxInt); int intValue = qRound(tmp); //qDebug() << __FUNCTION__ << doubleValue << tmp << intValue; return intValue; } // -------------------------------------------------------------------------- double ctkDoubleSliderPrivate::fromInt(int intValue)const { double doubleValue = this->SingleStep * (this->Offset + intValue) ; //qDebug() << __FUNCTION__ << intValue << doubleValue; return doubleValue; } // -------------------------------------------------------------------------- void ctkDoubleSliderPrivate::updateOffset(double value) { this->Offset = (value / this->SingleStep) - this->toInt(value); } // -------------------------------------------------------------------------- ctkDoubleSlider::ctkDoubleSlider(QWidget* _parent) : Superclass(_parent) { CTK_INIT_PRIVATE(ctkDoubleSlider); ctk_d()->init(); } // -------------------------------------------------------------------------- ctkDoubleSlider::ctkDoubleSlider(Qt::Orientation _orientation, QWidget* _parent) : Superclass(_parent) { CTK_INIT_PRIVATE(ctkDoubleSlider); ctk_d()->init(); this->setOrientation(_orientation); } // -------------------------------------------------------------------------- ctkDoubleSlider::~ctkDoubleSlider() { } // -------------------------------------------------------------------------- void ctkDoubleSlider::setMinimum(double min) { CTK_D(ctkDoubleSlider); d->Minimum = min; if (d->Minimum >= d->Value) { d->updateOffset(d->Minimum); } d->Slider->setMinimum(d->toInt(min)); } // -------------------------------------------------------------------------- void ctkDoubleSlider::setMaximum(double max) { CTK_D(ctkDoubleSlider); d->Maximum = max; if (d->Maximum <= d->Value) { d->updateOffset(d->Maximum); } d->Slider->setMaximum(d->toInt(max)); } // -------------------------------------------------------------------------- void ctkDoubleSlider::setRange(double min, double max) { CTK_D(ctkDoubleSlider); d->Minimum = min; d->Maximum = max; if (d->Minimum >= d->Value) { d->updateOffset(d->Minimum); } if (d->Maximum <= d->Value) { d->updateOffset(d->Maximum); } d->Slider->setRange(d->toInt(min), d->toInt(max)); } // -------------------------------------------------------------------------- double ctkDoubleSlider::minimum()const { CTK_D(const ctkDoubleSlider); return d->Minimum; } // -------------------------------------------------------------------------- double ctkDoubleSlider::maximum()const { CTK_D(const ctkDoubleSlider); return d->Maximum; } // -------------------------------------------------------------------------- double ctkDoubleSlider::sliderPosition()const { CTK_D(const ctkDoubleSlider); return d->fromInt(d->Slider->sliderPosition()); } // -------------------------------------------------------------------------- void ctkDoubleSlider::setSliderPosition(double newSliderPosition) { CTK_D(ctkDoubleSlider); d->Slider->setSliderPosition(d->toInt(newSliderPosition)); } // -------------------------------------------------------------------------- double ctkDoubleSlider::value()const { CTK_D(const ctkDoubleSlider); return d->Value; } // -------------------------------------------------------------------------- void ctkDoubleSlider::setValue(double newValue) { CTK_D(ctkDoubleSlider); newValue = qBound(d->Minimum, newValue, d->Maximum); d->updateOffset(newValue); int newIntValue = d->toInt(newValue); if (newIntValue != d->Slider->value()) { // d->Slider will emit a valueChanged signal that is connected to // ctkDoubleSlider::onValueChanged d->Slider->setValue(newIntValue); } else { double oldValue = d->Value; d->Value = newValue; // don't emit a valuechanged signal if the new value is quite // similar to the old value. if (qAbs(newValue - oldValue) > (d->SingleStep * 0.000000001)) { emit this->valueChanged(newValue); } } } // -------------------------------------------------------------------------- double ctkDoubleSlider::singleStep()const { CTK_D(const ctkDoubleSlider); return d->SingleStep; } // -------------------------------------------------------------------------- void ctkDoubleSlider::setSingleStep(double newStep) { CTK_D(ctkDoubleSlider); d->SingleStep = newStep; // update the new values of the QSlider double _value = d->Value; d->updateOffset(_value); bool oldBlockSignals = this->blockSignals(true); this->setRange(d->Minimum, d->Maximum); d->Slider->setValue(d->toInt(_value)); d->Value = _value; this->blockSignals(oldBlockSignals); } // -------------------------------------------------------------------------- double ctkDoubleSlider::tickInterval()const { CTK_D(const ctkDoubleSlider); return d->fromInt(d->Slider->tickInterval()); } // -------------------------------------------------------------------------- void ctkDoubleSlider::setTickInterval(double newTickInterval) { CTK_D(ctkDoubleSlider); d->Slider->setTickInterval(d->toInt(newTickInterval)); } // -------------------------------------------------------------------------- bool ctkDoubleSlider::hasTracking()const { CTK_D(const ctkDoubleSlider); return d->Slider->hasTracking(); } // -------------------------------------------------------------------------- void ctkDoubleSlider::setTracking(bool enable) { CTK_D(ctkDoubleSlider); d->Slider->setTracking(enable); } // -------------------------------------------------------------------------- void ctkDoubleSlider::triggerAction( QAbstractSlider::SliderAction action) { CTK_D(ctkDoubleSlider); d->Slider->triggerAction(action); } // -------------------------------------------------------------------------- Qt::Orientation ctkDoubleSlider::orientation()const { CTK_D(const ctkDoubleSlider); return d->Slider->orientation(); } // -------------------------------------------------------------------------- void ctkDoubleSlider::setOrientation(Qt::Orientation newOrientation) { CTK_D(ctkDoubleSlider); d->Slider->setOrientation(newOrientation); } // -------------------------------------------------------------------------- void ctkDoubleSlider::onValueChanged(int newValue) { CTK_D(ctkDoubleSlider); double doubleNewValue = d->fromInt(newValue); /* qDebug() << "onValueChanged: " << newValue << "->"<< d->fromInt(newValue+d->Offset) << " old: " << d->Value << "->" << d->toInt(d->Value) << "offset:" << d->Offset << doubleNewValue; */ if (d->Value == doubleNewValue) { return; } d->Value = doubleNewValue; emit this->valueChanged(d->Value); } // -------------------------------------------------------------------------- void ctkDoubleSlider::onSliderMoved(int newPosition) { CTK_D(const ctkDoubleSlider); emit this->sliderMoved(d->fromInt(newPosition)); } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "views/touchui/touch_factory.h" #include <gtk/gtk.h> #include <gdk/gdkx.h> #include <X11/cursorfont.h> #include <X11/extensions/XInput.h> #include <X11/extensions/XInput2.h> #include <X11/extensions/XIproto.h> #include "base/basictypes.h" #include "base/compiler_specific.h" #include "base/logging.h" #include "ui/base/x/x11_util.h" namespace { // The X cursor is hidden if it is idle for kCursorIdleSeconds seconds. int kCursorIdleSeconds = 5; // Given the TouchParam, return the correspoding valuator index using // the X device information through Atom name matching. char FindTPValuator(Display* display, XIDeviceInfo* info, views::TouchFactory::TouchParam touch_param) { // Lookup table for mapping TouchParam to Atom string used in X. // A full set of Atom strings can be found at xserver-properties.h. static struct { views::TouchFactory::TouchParam tp; const char* atom; } kTouchParamAtom[] = { { views::TouchFactory::TP_TOUCH_MAJOR, "Abs MT Touch Major" }, { views::TouchFactory::TP_TOUCH_MINOR, "Abs MT Touch Minor" }, { views::TouchFactory::TP_ORIENTATION, "Abs MT Orientation" }, { views::TouchFactory::TP_LAST_ENTRY, NULL }, }; const char* atom_tp = NULL; for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTouchParamAtom); i++) { if (touch_param == kTouchParamAtom[i].tp) { atom_tp = kTouchParamAtom[i].atom; break; } } if (!atom_tp) return -1; for (int i = 0; i < info->num_classes; i++) { if (info->classes[i]->type != XIValuatorClass) continue; XIValuatorClassInfo* v = reinterpret_cast<XIValuatorClassInfo*>(info->classes[i]); const char* atom = XGetAtomName(display, v->label); if (atom && strcmp(atom, atom_tp) == 0) return v->number; } return -1; } // Setup XInput2 select for the GtkWidget. gboolean GtkWidgetRealizeCallback(GSignalInvocationHint* hint, guint nparams, const GValue* pvalues, gpointer data) { GtkWidget* widget = GTK_WIDGET(g_value_get_object(pvalues)); GdkWindow* window = widget->window; views::TouchFactory* factory = static_cast<views::TouchFactory*>(data); if (GDK_WINDOW_TYPE(window) != GDK_WINDOW_TOPLEVEL && GDK_WINDOW_TYPE(window) != GDK_WINDOW_CHILD && GDK_WINDOW_TYPE(window) != GDK_WINDOW_DIALOG) return true; factory->SetupXI2ForXWindow(GDK_WINDOW_XID(window)); return true; } // We need to capture all the GDK windows that get created, and start // listening for XInput2 events. So we setup a callback to the 'realize' // signal for GTK+ widgets, so that whenever the signal triggers for any // GtkWidget, which means the GtkWidget should now have a GdkWindow, we can // setup XInput2 events for the GdkWindow. guint realize_signal_id = 0; guint realize_hook_id = 0; void SetupGtkWidgetRealizeNotifier(views::TouchFactory* factory) { gpointer klass = g_type_class_ref(GTK_TYPE_WIDGET); g_signal_parse_name("realize", GTK_TYPE_WIDGET, &realize_signal_id, NULL, FALSE); realize_hook_id = g_signal_add_emission_hook(realize_signal_id, 0, GtkWidgetRealizeCallback, static_cast<gpointer>(factory), NULL); g_type_class_unref(klass); } void RemoveGtkWidgetRealizeNotifier() { if (realize_signal_id != 0) g_signal_remove_emission_hook(realize_signal_id, realize_hook_id); realize_signal_id = 0; realize_hook_id = 0; } } // namespace namespace views { // static TouchFactory* TouchFactory::GetInstance() { return Singleton<TouchFactory>::get(); } TouchFactory::TouchFactory() : is_cursor_visible_(true), cursor_timer_(), pointer_device_lookup_(), touch_device_list_() { char nodata[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; XColor black; black.red = black.green = black.blue = 0; Display* display = ui::GetXDisplay(); Pixmap blank = XCreateBitmapFromData(display, ui::GetX11RootWindow(), nodata, 8, 8); invisible_cursor_ = XCreatePixmapCursor(display, blank, blank, &black, &black, 0, 0); arrow_cursor_ = XCreateFontCursor(display, XC_arrow); SetCursorVisible(false, false); UpdateDeviceList(display); // TODO(sad): Here, we only setup so that the X windows created by GTK+ are // setup for XInput2 events. We need a way to listen for XInput2 events for X // windows created by other means (e.g. for context menus). SetupGtkWidgetRealizeNotifier(this); // Make sure the list of devices is kept up-to-date by listening for // XI_HierarchyChanged event on the root window. unsigned char mask[XIMaskLen(XI_LASTEVENT)]; memset(mask, 0, sizeof(mask)); XISetMask(mask, XI_HierarchyChanged); XIEventMask evmask; evmask.deviceid = XIAllDevices; evmask.mask_len = sizeof(mask); evmask.mask = mask; XISelectEvents(display, ui::GetX11RootWindow(), &evmask, 1); } TouchFactory::~TouchFactory() { SetCursorVisible(true, false); Display* display = ui::GetXDisplay(); XFreeCursor(display, invisible_cursor_); XFreeCursor(display, arrow_cursor_); RemoveGtkWidgetRealizeNotifier(); } void TouchFactory::UpdateDeviceList(Display* display) { // Detect touch devices. // NOTE: The new API for retrieving the list of devices (XIQueryDevice) does // not provide enough information to detect a touch device. As a result, the // old version of query function (XListInputDevices) is used instead. // If XInput2 is not supported, this will return null (with count of -1) so // we assume there cannot be any touch devices. int count = 0; touch_device_lookup_.reset(); touch_device_list_.clear(); XDeviceInfo* devlist = XListInputDevices(display, &count); for (int i = 0; i < count; i++) { const char* devtype = XGetAtomName(display, devlist[i].type); if (devtype && !strcmp(devtype, XI_TOUCHSCREEN)) { touch_device_lookup_[devlist[i].id] = true; touch_device_list_.push_back(devlist[i].id); } } if (devlist) XFreeDeviceList(devlist); // Instead of asking X for the list of devices all the time, let's maintain a // list of pointer devices we care about. // It is not necessary to select for slave devices. XInput2 provides enough // information to the event callback to decide which slave device triggered // the event, thus decide whether the 'pointer event' is a 'mouse event' or a // 'touch event'. // If the touch device has 'GrabDevice' set and 'SendCoreEvents' unset (which // is possible), then the device is detected as a floating device, and a // floating device is not connected to a master device. So it is necessary to // also select on the floating devices. pointer_device_lookup_.reset(); XIDeviceInfo* devices = XIQueryDevice(display, XIAllDevices, &count); for (int i = 0; i < count; i++) { XIDeviceInfo* devinfo = devices + i; if (devinfo->use == XIFloatingSlave || devinfo->use == XIMasterPointer) { pointer_device_lookup_[devinfo->deviceid] = true; } } XIFreeDeviceInfo(devices); SetupValuator(); } bool TouchFactory::ShouldProcessXI2Event(XEvent* xev) { DCHECK_EQ(GenericEvent, xev->type); XGenericEventCookie* cookie = &xev->xcookie; if (cookie->evtype != XI_ButtonPress && cookie->evtype != XI_ButtonRelease && cookie->evtype != XI_Motion) return true; XIDeviceEvent* xiev = static_cast<XIDeviceEvent*>(cookie->data); return pointer_device_lookup_[xiev->sourceid]; } void TouchFactory::SetupXI2ForXWindow(Window window) { // Setup mask for mouse events. It is possible that a device is loaded/plugged // in after we have setup XInput2 on a window. In such cases, we need to // either resetup XInput2 for the window, so that we get events from the new // device, or we need to listen to events from all devices, and then filter // the events from uninteresting devices. We do the latter because that's // simpler. Display* display = ui::GetXDisplay(); unsigned char mask[XIMaskLen(XI_LASTEVENT)]; memset(mask, 0, sizeof(mask)); XISetMask(mask, XI_ButtonPress); XISetMask(mask, XI_ButtonRelease); XISetMask(mask, XI_Motion); XIEventMask evmask; evmask.deviceid = XIAllDevices; evmask.mask_len = sizeof(mask); evmask.mask = mask; XISelectEvents(display, window, &evmask, 1); XFlush(display); } void TouchFactory::SetTouchDeviceList( const std::vector<unsigned int>& devices) { touch_device_lookup_.reset(); touch_device_list_.clear(); for (std::vector<unsigned int>::const_iterator iter = devices.begin(); iter != devices.end(); ++iter) { DCHECK(*iter < touch_device_lookup_.size()); touch_device_lookup_[*iter] = true; touch_device_list_.push_back(*iter); } SetupValuator(); } bool TouchFactory::IsTouchDevice(unsigned deviceid) const { return deviceid < touch_device_lookup_.size() ? touch_device_lookup_[deviceid] : false; } bool TouchFactory::GrabTouchDevices(Display* display, ::Window window) { if (touch_device_list_.empty()) return true; unsigned char mask[XIMaskLen(XI_LASTEVENT)]; bool success = true; memset(mask, 0, sizeof(mask)); XISetMask(mask, XI_ButtonPress); XISetMask(mask, XI_ButtonRelease); XISetMask(mask, XI_Motion); XIEventMask evmask; evmask.mask_len = sizeof(mask); evmask.mask = mask; for (std::vector<int>::const_iterator iter = touch_device_list_.begin(); iter != touch_device_list_.end(); ++iter) { evmask.deviceid = *iter; Status status = XIGrabDevice(display, *iter, window, CurrentTime, None, GrabModeAsync, GrabModeAsync, False, &evmask); success = success && status == GrabSuccess; } return success; } bool TouchFactory::UngrabTouchDevices(Display* display) { bool success = true; for (std::vector<int>::const_iterator iter = touch_device_list_.begin(); iter != touch_device_list_.end(); ++iter) { Status status = XIUngrabDevice(display, *iter, CurrentTime); success = success && status == GrabSuccess; } return success; } void TouchFactory::SetCursorVisible(bool show, bool start_timer) { // The cursor is going to be shown. Reset the timer for hiding it. if (show && start_timer) { cursor_timer_.Stop(); cursor_timer_.Start(base::TimeDelta::FromSeconds(kCursorIdleSeconds), this, &TouchFactory::HideCursorForInactivity); } else { cursor_timer_.Stop(); } if (show == is_cursor_visible_) return; is_cursor_visible_ = show; Display* display = ui::GetXDisplay(); Window window = DefaultRootWindow(display); if (is_cursor_visible_) { XDefineCursor(display, window, arrow_cursor_); } else { XDefineCursor(display, window, invisible_cursor_); } } void TouchFactory::SetupValuator() { memset(valuator_lookup_, -1, sizeof(valuator_lookup_)); Display* display = ui::GetXDisplay(); int ndevice; XIDeviceInfo* info_list = XIQueryDevice(display, XIAllDevices, &ndevice); for (int i = 0; i < ndevice; i++) { XIDeviceInfo* info = info_list + i; if (!IsTouchDevice(info->deviceid)) continue; for (int i = 0; i < TP_LAST_ENTRY; i++) { TouchParam tp = static_cast<TouchParam>(i); valuator_lookup_[info->deviceid][i] = FindTPValuator(display, info, tp); } } if (info_list) XIFreeDeviceInfo(info_list); } bool TouchFactory::ExtractTouchParam(const XEvent& xev, TouchParam tp, float* value) { XIDeviceEvent* xiev = static_cast<XIDeviceEvent*>(xev.xcookie.data); if (xiev->sourceid >= kMaxDeviceNum) return false; int v = valuator_lookup_[xiev->sourceid][tp]; if (v >= 0 && XIMaskIsSet(xiev->valuators.mask, v)) { *value = xiev->valuators.values[v]; return true; } return false; } } // namespace views <commit_msg>Select on slave pointers instead of master pointers.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "views/touchui/touch_factory.h" #include <gtk/gtk.h> #include <gdk/gdkx.h> #include <X11/cursorfont.h> #include <X11/extensions/XInput.h> #include <X11/extensions/XInput2.h> #include <X11/extensions/XIproto.h> #include "base/basictypes.h" #include "base/compiler_specific.h" #include "base/logging.h" #include "ui/base/x/x11_util.h" namespace { // The X cursor is hidden if it is idle for kCursorIdleSeconds seconds. int kCursorIdleSeconds = 5; // Given the TouchParam, return the correspoding valuator index using // the X device information through Atom name matching. char FindTPValuator(Display* display, XIDeviceInfo* info, views::TouchFactory::TouchParam touch_param) { // Lookup table for mapping TouchParam to Atom string used in X. // A full set of Atom strings can be found at xserver-properties.h. static struct { views::TouchFactory::TouchParam tp; const char* atom; } kTouchParamAtom[] = { { views::TouchFactory::TP_TOUCH_MAJOR, "Abs MT Touch Major" }, { views::TouchFactory::TP_TOUCH_MINOR, "Abs MT Touch Minor" }, { views::TouchFactory::TP_ORIENTATION, "Abs MT Orientation" }, { views::TouchFactory::TP_LAST_ENTRY, NULL }, }; const char* atom_tp = NULL; for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTouchParamAtom); i++) { if (touch_param == kTouchParamAtom[i].tp) { atom_tp = kTouchParamAtom[i].atom; break; } } if (!atom_tp) return -1; for (int i = 0; i < info->num_classes; i++) { if (info->classes[i]->type != XIValuatorClass) continue; XIValuatorClassInfo* v = reinterpret_cast<XIValuatorClassInfo*>(info->classes[i]); const char* atom = XGetAtomName(display, v->label); if (atom && strcmp(atom, atom_tp) == 0) return v->number; } return -1; } // Setup XInput2 select for the GtkWidget. gboolean GtkWidgetRealizeCallback(GSignalInvocationHint* hint, guint nparams, const GValue* pvalues, gpointer data) { GtkWidget* widget = GTK_WIDGET(g_value_get_object(pvalues)); GdkWindow* window = widget->window; views::TouchFactory* factory = static_cast<views::TouchFactory*>(data); if (GDK_WINDOW_TYPE(window) != GDK_WINDOW_TOPLEVEL && GDK_WINDOW_TYPE(window) != GDK_WINDOW_CHILD && GDK_WINDOW_TYPE(window) != GDK_WINDOW_DIALOG) return true; factory->SetupXI2ForXWindow(GDK_WINDOW_XID(window)); return true; } // We need to capture all the GDK windows that get created, and start // listening for XInput2 events. So we setup a callback to the 'realize' // signal for GTK+ widgets, so that whenever the signal triggers for any // GtkWidget, which means the GtkWidget should now have a GdkWindow, we can // setup XInput2 events for the GdkWindow. guint realize_signal_id = 0; guint realize_hook_id = 0; void SetupGtkWidgetRealizeNotifier(views::TouchFactory* factory) { gpointer klass = g_type_class_ref(GTK_TYPE_WIDGET); g_signal_parse_name("realize", GTK_TYPE_WIDGET, &realize_signal_id, NULL, FALSE); realize_hook_id = g_signal_add_emission_hook(realize_signal_id, 0, GtkWidgetRealizeCallback, static_cast<gpointer>(factory), NULL); g_type_class_unref(klass); } void RemoveGtkWidgetRealizeNotifier() { if (realize_signal_id != 0) g_signal_remove_emission_hook(realize_signal_id, realize_hook_id); realize_signal_id = 0; realize_hook_id = 0; } } // namespace namespace views { // static TouchFactory* TouchFactory::GetInstance() { return Singleton<TouchFactory>::get(); } TouchFactory::TouchFactory() : is_cursor_visible_(true), cursor_timer_(), pointer_device_lookup_(), touch_device_list_() { char nodata[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; XColor black; black.red = black.green = black.blue = 0; Display* display = ui::GetXDisplay(); Pixmap blank = XCreateBitmapFromData(display, ui::GetX11RootWindow(), nodata, 8, 8); invisible_cursor_ = XCreatePixmapCursor(display, blank, blank, &black, &black, 0, 0); arrow_cursor_ = XCreateFontCursor(display, XC_arrow); SetCursorVisible(false, false); UpdateDeviceList(display); // TODO(sad): Here, we only setup so that the X windows created by GTK+ are // setup for XInput2 events. We need a way to listen for XInput2 events for X // windows created by other means (e.g. for context menus). SetupGtkWidgetRealizeNotifier(this); // Make sure the list of devices is kept up-to-date by listening for // XI_HierarchyChanged event on the root window. unsigned char mask[XIMaskLen(XI_LASTEVENT)]; memset(mask, 0, sizeof(mask)); XISetMask(mask, XI_HierarchyChanged); XIEventMask evmask; evmask.deviceid = XIAllDevices; evmask.mask_len = sizeof(mask); evmask.mask = mask; XISelectEvents(display, ui::GetX11RootWindow(), &evmask, 1); } TouchFactory::~TouchFactory() { SetCursorVisible(true, false); Display* display = ui::GetXDisplay(); XFreeCursor(display, invisible_cursor_); XFreeCursor(display, arrow_cursor_); RemoveGtkWidgetRealizeNotifier(); } void TouchFactory::UpdateDeviceList(Display* display) { // Detect touch devices. // NOTE: The new API for retrieving the list of devices (XIQueryDevice) does // not provide enough information to detect a touch device. As a result, the // old version of query function (XListInputDevices) is used instead. // If XInput2 is not supported, this will return null (with count of -1) so // we assume there cannot be any touch devices. int count = 0; touch_device_lookup_.reset(); touch_device_list_.clear(); XDeviceInfo* devlist = XListInputDevices(display, &count); for (int i = 0; i < count; i++) { const char* devtype = XGetAtomName(display, devlist[i].type); if (devtype && !strcmp(devtype, XI_TOUCHSCREEN)) { touch_device_lookup_[devlist[i].id] = true; touch_device_list_.push_back(devlist[i].id); } } if (devlist) XFreeDeviceList(devlist); // Instead of asking X for the list of devices all the time, let's maintain a // list of pointer devices we care about. // It should not be necessary to select for slave devices. XInput2 provides // enough information to the event callback to decide which slave device // triggered the event, thus decide whether the 'pointer event' is a // 'mouse event' or a 'touch event'. // However, on some desktops, some events from a master pointer are // not delivered to the client. So we select for slave devices instead. // If the touch device has 'GrabDevice' set and 'SendCoreEvents' unset (which // is possible), then the device is detected as a floating device, and a // floating device is not connected to a master device. So it is necessary to // also select on the floating devices. pointer_device_lookup_.reset(); XIDeviceInfo* devices = XIQueryDevice(display, XIAllDevices, &count); for (int i = 0; i < count; i++) { XIDeviceInfo* devinfo = devices + i; if (devinfo->use == XIFloatingSlave || devinfo->use == XISlavePointer) { pointer_device_lookup_[devinfo->deviceid] = true; } } XIFreeDeviceInfo(devices); SetupValuator(); } bool TouchFactory::ShouldProcessXI2Event(XEvent* xev) { DCHECK_EQ(GenericEvent, xev->type); XGenericEventCookie* cookie = &xev->xcookie; if (cookie->evtype != XI_ButtonPress && cookie->evtype != XI_ButtonRelease && cookie->evtype != XI_Motion) return true; XIDeviceEvent* xiev = static_cast<XIDeviceEvent*>(cookie->data); return pointer_device_lookup_[xiev->sourceid]; } void TouchFactory::SetupXI2ForXWindow(Window window) { // Setup mask for mouse events. It is possible that a device is loaded/plugged // in after we have setup XInput2 on a window. In such cases, we need to // either resetup XInput2 for the window, so that we get events from the new // device, or we need to listen to events from all devices, and then filter // the events from uninteresting devices. We do the latter because that's // simpler. Display* display = ui::GetXDisplay(); unsigned char mask[XIMaskLen(XI_LASTEVENT)]; memset(mask, 0, sizeof(mask)); XISetMask(mask, XI_ButtonPress); XISetMask(mask, XI_ButtonRelease); XISetMask(mask, XI_Motion); XIEventMask evmask; evmask.deviceid = XIAllDevices; evmask.mask_len = sizeof(mask); evmask.mask = mask; XISelectEvents(display, window, &evmask, 1); XFlush(display); } void TouchFactory::SetTouchDeviceList( const std::vector<unsigned int>& devices) { touch_device_lookup_.reset(); touch_device_list_.clear(); for (std::vector<unsigned int>::const_iterator iter = devices.begin(); iter != devices.end(); ++iter) { DCHECK(*iter < touch_device_lookup_.size()); touch_device_lookup_[*iter] = true; touch_device_list_.push_back(*iter); } SetupValuator(); } bool TouchFactory::IsTouchDevice(unsigned deviceid) const { return deviceid < touch_device_lookup_.size() ? touch_device_lookup_[deviceid] : false; } bool TouchFactory::GrabTouchDevices(Display* display, ::Window window) { if (touch_device_list_.empty()) return true; unsigned char mask[XIMaskLen(XI_LASTEVENT)]; bool success = true; memset(mask, 0, sizeof(mask)); XISetMask(mask, XI_ButtonPress); XISetMask(mask, XI_ButtonRelease); XISetMask(mask, XI_Motion); XIEventMask evmask; evmask.mask_len = sizeof(mask); evmask.mask = mask; for (std::vector<int>::const_iterator iter = touch_device_list_.begin(); iter != touch_device_list_.end(); ++iter) { evmask.deviceid = *iter; Status status = XIGrabDevice(display, *iter, window, CurrentTime, None, GrabModeAsync, GrabModeAsync, False, &evmask); success = success && status == GrabSuccess; } return success; } bool TouchFactory::UngrabTouchDevices(Display* display) { bool success = true; for (std::vector<int>::const_iterator iter = touch_device_list_.begin(); iter != touch_device_list_.end(); ++iter) { Status status = XIUngrabDevice(display, *iter, CurrentTime); success = success && status == GrabSuccess; } return success; } void TouchFactory::SetCursorVisible(bool show, bool start_timer) { // The cursor is going to be shown. Reset the timer for hiding it. if (show && start_timer) { cursor_timer_.Stop(); cursor_timer_.Start(base::TimeDelta::FromSeconds(kCursorIdleSeconds), this, &TouchFactory::HideCursorForInactivity); } else { cursor_timer_.Stop(); } if (show == is_cursor_visible_) return; is_cursor_visible_ = show; Display* display = ui::GetXDisplay(); Window window = DefaultRootWindow(display); if (is_cursor_visible_) { XDefineCursor(display, window, arrow_cursor_); } else { XDefineCursor(display, window, invisible_cursor_); } } void TouchFactory::SetupValuator() { memset(valuator_lookup_, -1, sizeof(valuator_lookup_)); Display* display = ui::GetXDisplay(); int ndevice; XIDeviceInfo* info_list = XIQueryDevice(display, XIAllDevices, &ndevice); for (int i = 0; i < ndevice; i++) { XIDeviceInfo* info = info_list + i; if (!IsTouchDevice(info->deviceid)) continue; for (int i = 0; i < TP_LAST_ENTRY; i++) { TouchParam tp = static_cast<TouchParam>(i); valuator_lookup_[info->deviceid][i] = FindTPValuator(display, info, tp); } } if (info_list) XIFreeDeviceInfo(info_list); } bool TouchFactory::ExtractTouchParam(const XEvent& xev, TouchParam tp, float* value) { XIDeviceEvent* xiev = static_cast<XIDeviceEvent*>(xev.xcookie.data); if (xiev->sourceid >= kMaxDeviceNum) return false; int v = valuator_lookup_[xiev->sourceid][tp]; if (v >= 0 && XIMaskIsSet(xiev->valuators.mask, v)) { *value = xiev->valuators.values[v]; return true; } return false; } } // namespace views <|endoftext|>
<commit_before><commit_msg>[booking] android build fix<commit_after><|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Copyright (c) 2009, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder(s) 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. * * $Id: extract_indices.hpp 1897 2011-07-26 20:35:49Z rusu $ * */ #ifndef PCL_FILTERS_IMPL_RANDOM_SAMPLE_H_ #define PCL_FILTERS_IMPL_RANDOM_SAMPLE_H_ #include <pcl/filters/random_sample.h> #include <pcl/common/io.h> #include <pcl/point_traits.h> /////////////////////////////////////////////////////////////////////////////// template<typename PointT> void pcl::RandomSample<PointT>::applyFilter (PointCloud &output) { std::vector<int> indices; if (keep_organized_) { bool temp = extract_removed_indices_; extract_removed_indices_ = true; applyFilter (indices); extract_removed_indices_ = temp; copyPointCloud (*input_, output); // Get X, Y, Z fields std::vector<pcl::PCLPointField> fields; pcl::getFields (*input_, fields); std::vector<size_t> offsets; for (size_t i = 0; i < fields.size (); ++i) { if (fields[i].name == "x" || fields[i].name == "y" || fields[i].name == "z") offsets.push_back (fields[i].offset); } // For every "removed" point, set the x,y,z fields to user_filter_value_ const static float user_filter_value = user_filter_value_; for (size_t rii = 0; rii < removed_indices_->size (); ++rii) { uint8_t* pt_data = reinterpret_cast<uint8_t*> (&output[(*removed_indices_)[rii]]); for (size_t i = 0; i < offsets.size (); ++i) { memcpy (pt_data + offsets[i], &user_filter_value, sizeof (float)); } if (!pcl_isfinite (user_filter_value_)) output.is_dense = false; } } else { output.is_dense = true; applyFilter (indices); copyPointCloud (*input_, indices, output); } } /////////////////////////////////////////////////////////////////////////////// template<typename PointT> void pcl::RandomSample<PointT>::applyFilter (std::vector<int> &indices) { unsigned N = static_cast<unsigned> (indices_->size ()); unsigned int sample_size = negative_ ? N - sample_ : sample_; // If sample size is 0 or if the sample size is greater then input cloud size // then return all indices if (sample_size >= N) { indices = *indices_; removed_indices_->clear (); } else { // Resize output indices to sample size indices.resize (static_cast<size_t> (sample_size)); if (extract_removed_indices_) removed_indices_->resize (static_cast<size_t> (N - sample_size)); // Set random seed so derived indices are the same each time the filter runs std::srand (seed_); // Algorithm A unsigned top = N - sample_size; unsigned i = 0; unsigned index = 0; std::vector<bool> added; if (extract_removed_indices_) added.resize (indices_->size (), false); for (size_t n = sample_size; n >= 2; n--) { float V = unifRand (); unsigned S = 0; float quot = static_cast<float> (top) / static_cast<float> (N); while (quot > V) { S++; top--; N--; quot = quot * static_cast<float> (top) / static_cast<float> (N); } index += S; if (extract_removed_indices_) added[index] = true; indices[i++] = (*indices_)[index++]; N--; } index += N * static_cast<unsigned> (unifRand ()); if (extract_removed_indices_) added[index] = true; indices[i++] = (*indices_)[index++]; // Now populate removed_indices_ appropriately if (extract_removed_indices_) { unsigned ri = 0; for (size_t i = 0; i < added.size (); i++) { if (!added[i]) { (*removed_indices_)[ri++] = (*indices_)[i]; } } } } } #define PCL_INSTANTIATE_RandomSample(T) template class PCL_EXPORTS pcl::RandomSample<T>; #endif // PCL_FILTERS_IMPL_RANDOM_SAMPLE_H_ <commit_msg>Avoid huge index jumps in pcl::RandomSample<commit_after>/* * Software License Agreement (BSD License) * * Copyright (c) 2009, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder(s) 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. * * $Id: extract_indices.hpp 1897 2011-07-26 20:35:49Z rusu $ * */ #ifndef PCL_FILTERS_IMPL_RANDOM_SAMPLE_H_ #define PCL_FILTERS_IMPL_RANDOM_SAMPLE_H_ #include <pcl/filters/random_sample.h> #include <pcl/common/io.h> #include <pcl/point_traits.h> /////////////////////////////////////////////////////////////////////////////// template<typename PointT> void pcl::RandomSample<PointT>::applyFilter (PointCloud &output) { std::vector<int> indices; if (keep_organized_) { bool temp = extract_removed_indices_; extract_removed_indices_ = true; applyFilter (indices); extract_removed_indices_ = temp; copyPointCloud (*input_, output); // Get X, Y, Z fields std::vector<pcl::PCLPointField> fields; pcl::getFields (*input_, fields); std::vector<size_t> offsets; for (size_t i = 0; i < fields.size (); ++i) { if (fields[i].name == "x" || fields[i].name == "y" || fields[i].name == "z") offsets.push_back (fields[i].offset); } // For every "removed" point, set the x,y,z fields to user_filter_value_ const static float user_filter_value = user_filter_value_; for (size_t rii = 0; rii < removed_indices_->size (); ++rii) { uint8_t* pt_data = reinterpret_cast<uint8_t*> (&output[(*removed_indices_)[rii]]); for (size_t i = 0; i < offsets.size (); ++i) { memcpy (pt_data + offsets[i], &user_filter_value, sizeof (float)); } if (!pcl_isfinite (user_filter_value_)) output.is_dense = false; } } else { output.is_dense = true; applyFilter (indices); copyPointCloud (*input_, indices, output); } } /////////////////////////////////////////////////////////////////////////////// template<typename PointT> void pcl::RandomSample<PointT>::applyFilter (std::vector<int> &indices) { size_t N = indices_->size (); size_t sample_size = negative_ ? N - sample_ : sample_; // If sample size is 0 or if the sample size is greater then input cloud size // then return all indices if (sample_size >= N) { indices = *indices_; removed_indices_->clear (); } else { // Resize output indices to sample size indices.resize (sample_size); if (extract_removed_indices_) removed_indices_->resize (N - sample_size); // Set random seed so derived indices are the same each time the filter runs std::srand (seed_); // Algorithm S size_t i = 0; size_t index = 0; std::vector<bool> added; if (extract_removed_indices_) added.resize (indices_->size (), false); size_t n = sample_size; while (n > 0) { // Step 1: [Generate U.] Generate a random variate U that is uniformly distributed between 0 and 1. const float U = unifRand (); // Step 2: [Test.] If N * U > n, go to Step 4. if ((N * U) <= n) { // Step 3: [Select.] Select the next record in the file for the sample, and set n : = n - 1. if (extract_removed_indices_) added[index] = true; indices[i++] = (*indices_)[index]; --n; } // Step 4: [Don't select.] Skip over the next record (do not include it in the sample). // Set N : = N - 1. --N; ++index; // If n > 0, then return to Step 1; otherwise, the sample is complete and the algorithm terminates. } // Now populate removed_indices_ appropriately if (extract_removed_indices_) { size_t ri = 0; for (size_t i = 0; i < added.size (); i++) { if (!added[i]) { (*removed_indices_)[ri++] = (*indices_)[i]; } } } } } #define PCL_INSTANTIATE_RandomSample(T) template class PCL_EXPORTS pcl::RandomSample<T>; #endif // PCL_FILTERS_IMPL_RANDOM_SAMPLE_H_ <|endoftext|>
<commit_before> // todo: // -Ir // -Iz // -zr // -zt // -f #include "i2_options.h" #include "posix_fe.h" #include <netdb.h> class i2_program { i2_options opts; bool _ok; pxfe_tcp_stream_socket * net_fd; uint64_t bytes_sent; uint64_t bytes_received; pxfe_timeval start_time; pxfe_string buffer; pxfe_ticker ticker; public: i2_program(int argc, char ** argv) : opts(argc, argv), _ok(false) { _ok = opts.ok; net_fd = NULL; bytes_received = 0; bytes_sent = 0; } ~i2_program(void) { // opts destructor will close the input & output fds. if (net_fd) delete net_fd; } bool ok(void) const { return _ok; } int main(void) { uint32_t addr; pxfe_errno e; if (opts.outbound && pxfe_iputils::hostname_to_ipaddr(opts.hostname.c_str(), &addr) == false) return 1; if (opts.outbound) { net_fd = new pxfe_tcp_stream_socket; if (net_fd->init(&e) == false) { std::cerr << e.Format() << std::endl; return 1; } if (opts.verbose) fprintf(stderr, "connecting..."); if (net_fd->connect(addr, opts.port_number, &e) == false) { std::cerr << e.Format() << std::endl; return 1; } if (opts.verbose) fprintf(stderr, "success\n"); } else { pxfe_tcp_stream_socket listen; if (listen.init(opts.port_number,true,&e) == false) { std::cerr << e.Format() << std::endl; return 1; } listen.listen(); if (opts.verbose) fprintf(stderr, "listening..."); do { net_fd = listen.accept(&e); if (e.e != 0) std::cerr << e.Format() << std::endl; } while (net_fd == NULL); if (opts.verbose) { uint32_t addr = net_fd->get_peer_addr(); std::cerr << "accepted from " << (int) ((addr >> 24) & 0xFF) << "." << (int) ((addr >> 16) & 0xFF) << "." << (int) ((addr >> 8) & 0xFF) << "." << (int) ((addr >> 0) & 0xFF) << std::endl; } // listen socket closed here, because we // no longer need it. } start_time.getNow(); ticker.start(0, 500000); pxfe_poll p; p.set(net_fd->getFd(), POLLIN); p.set(ticker.fd(), POLLIN); while (1) { if (opts.input_set) p.set(opts.input_fd, POLLIN); else p.set(opts.input_fd, 0); p.poll(1000); if (p.rget(net_fd->getFd()) & POLLIN) if (!handle_net_fd()) break; if (opts.input_set && p.rget(opts.input_fd) & POLLIN) if (!handle_input_fd()) break; if (p.rget(ticker.fd()) & POLLIN) handle_tick(); } ticker.pause(); if (opts.verbose || opts.stats_at_end) print_stats(true); return 0; } private: bool handle_net_fd(void) { pxfe_errno e; if (net_fd->recv(buffer, &e) == false) { std::cerr << e.Format() << std::endl; return false; } if (buffer.length() == 0) return false; bytes_received += buffer.length(); if (opts.output_set) { int cc = -1; do { cc = buffer.write(opts.output_fd); if (cc == buffer.length()) break; if (cc < 0) { int e = errno; char * err = strerror(e); fprintf(stderr, "write failed: %d: %s\n", e, err); return false; } else if (cc == 0) { fprintf(stderr, "write returned zero\n"); return false; } else // remove the bytes already written // and go around again to get the rest. buffer.erase(0,cc); } while (true); } return true; } bool handle_input_fd(void) { pxfe_errno e; int cc = buffer.read(opts.input_fd, pxfe_tcp_stream_socket::MAX_MSG_LEN, &e); if (cc < 0) { std::cerr << e.Format() << std::endl; return false; } else if (cc == 0) return false; else { if (net_fd->send(buffer, &e) == false) { std::cerr << e.Format() << std::endl; return false; } bytes_sent += buffer.length(); } return true; } void handle_tick(void) { ticker.doread(); if (opts.verbose) print_stats(/*final*/false); } void print_stats(bool final) { pxfe_timeval now, diff; uint64_t total = bytes_sent + bytes_received; now.getNow(); diff = now - start_time; float t = diff.usecs() / 1000000.0; if (t == 0.0) t = 99999.0; float bytes_per_sec = (float) total / t; float bits_per_sec = bytes_per_sec * 8.0; fprintf(stderr, "\r%" PRIu64 " in %u.%06u s " "(%.0f Bps %.0f bps)", total, (unsigned int) diff.tv_sec, (unsigned int) diff.tv_usec, bytes_per_sec, bits_per_sec); if (final) fprintf(stderr, "\n"); } }; extern "C" int i2_main(int argc, char ** argv) { i2_program i2(argc, argv); if (i2.ok() == false) return 1; return i2.main(); } <commit_msg>FINALLY figured out that i2 lockup -- poll's got some quirks!<commit_after> // todo: // -Ir // -Iz // -zr // -zt // -f #include "i2_options.h" #include "posix_fe.h" #include <netdb.h> class i2_program { i2_options opts; bool _ok; pxfe_tcp_stream_socket * net_fd; uint64_t bytes_sent; uint64_t bytes_received; pxfe_timeval start_time; pxfe_string buffer; pxfe_ticker ticker; public: i2_program(int argc, char ** argv) : opts(argc, argv), _ok(false) { _ok = opts.ok; net_fd = NULL; bytes_received = 0; bytes_sent = 0; } ~i2_program(void) { // opts destructor will close the input & output fds. if (net_fd) delete net_fd; } bool ok(void) const { return _ok; } int main(void) { uint32_t addr; pxfe_errno e; if (opts.outbound && pxfe_iputils::hostname_to_ipaddr(opts.hostname.c_str(), &addr) == false) return 1; if (opts.outbound) { net_fd = new pxfe_tcp_stream_socket; if (net_fd->init(&e) == false) { std::cerr << e.Format() << std::endl; return 1; } if (opts.verbose) fprintf(stderr, "connecting..."); if (net_fd->connect(addr, opts.port_number, &e) == false) { std::cerr << e.Format() << std::endl; return 1; } if (opts.verbose) fprintf(stderr, "success\n"); } else { pxfe_tcp_stream_socket listen; if (listen.init(opts.port_number,true,&e) == false) { std::cerr << e.Format() << std::endl; return 1; } listen.listen(); if (opts.verbose) fprintf(stderr, "listening..."); do { net_fd = listen.accept(&e); if (e.e != 0) std::cerr << e.Format() << std::endl; } while (net_fd == NULL); if (opts.verbose) { uint32_t addr = net_fd->get_peer_addr(); std::cerr << "accepted from " << (int) ((addr >> 24) & 0xFF) << "." << (int) ((addr >> 16) & 0xFF) << "." << (int) ((addr >> 8) & 0xFF) << "." << (int) ((addr >> 0) & 0xFF) << std::endl; } // listen socket closed here, because we // no longer need it. } start_time.getNow(); ticker.start(0, 500000); pxfe_poll p; p.set(net_fd->getFd(), POLLIN); p.set(ticker.fd(), POLLIN); #define POLLERRS (POLLERR | POLLHUP | POLLNVAL) while (1) { int evt; if (opts.input_set) p.set(opts.input_fd, POLLIN); else p.set(opts.input_fd, 0); p.poll(1000); evt = p.rget(net_fd->getFd()); if (evt & POLLIN) { if (!handle_net_fd()) break; } else if (evt & POLLERRS) break; if (opts.input_set) { evt = p.rget(opts.input_fd); if (evt & POLLIN) { if (!handle_input_fd()) break; } else if (evt & POLLERRS) break; } if (p.rget(ticker.fd()) & POLLIN) handle_tick(); } ticker.pause(); if (opts.verbose || opts.stats_at_end) print_stats(true); return 0; } private: bool handle_net_fd(void) { pxfe_errno e; if (net_fd->recv(buffer, &e) == false) { std::cerr << e.Format() << std::endl; return false; } if (buffer.length() == 0) return false; bytes_received += buffer.length(); if (opts.output_set) { int cc = -1; do { cc = buffer.write(opts.output_fd); if (cc == buffer.length()) break; if (cc < 0) { int e = errno; char * err = strerror(e); fprintf(stderr, "write failed: %d: %s\n", e, err); return false; } else if (cc == 0) { fprintf(stderr, "write returned zero\n"); return false; } else // remove the bytes already written // and go around again to get the rest. buffer.erase(0,cc); } while (true); } return true; } bool handle_input_fd(void) { pxfe_errno e; int cc = buffer.read(opts.input_fd, pxfe_tcp_stream_socket::MAX_MSG_LEN, &e); if (cc < 0) { std::cerr << e.Format() << std::endl; return false; } else if (cc == 0) return false; else { if (net_fd->send(buffer, &e) == false) { std::cerr << e.Format() << std::endl; return false; } bytes_sent += buffer.length(); } return true; } void handle_tick(void) { ticker.doread(); if (opts.verbose) print_stats(/*final*/false); } void print_stats(bool final) { pxfe_timeval now, diff; uint64_t total = bytes_sent + bytes_received; now.getNow(); diff = now - start_time; float t = diff.usecs() / 1000000.0; if (t == 0.0) t = 99999.0; float bytes_per_sec = (float) total / t; float bits_per_sec = bytes_per_sec * 8.0; fprintf(stderr, "\r%" PRIu64 " in %u.%06u s " "(%.0f Bps %.0f bps)", total, (unsigned int) diff.tv_sec, (unsigned int) diff.tv_usec, bytes_per_sec, bits_per_sec); if (final) fprintf(stderr, "\n"); } }; extern "C" int i2_main(int argc, char ** argv) { i2_program i2(argc, argv); if (i2.ok() == false) return 1; return i2.main(); } <|endoftext|>
<commit_before>/*----------------------------------------------------------------------------- This source file is a part of Hopsan Copyright (c) 2009 to present year, Hopsan Group This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. For license details and information about the Hopsan Group see the files GPLv3 and HOPSANGROUP in the Hopsan source code root directory For author and contributor information see the AUTHORS file -----------------------------------------------------------------------------*/ //! //! @file FirstOrderTransferFunction.cc //! @author Björn Eriksson <[email protected]> //! @date 2010-01-23 //! //! @brief Contains the Core First Order Transfer Function class //! //$Id$ //#include <iostream> #include <algorithm> #include "ComponentUtilities/FirstOrderTransferFunction.h" using namespace hopsan; //! @class hopsan::FirstOrderTransferFunction //! @ingroup ComponentUtilityClasses //! @brief The FirstOrderTransferFunction class implements a first order time discrete transfer function using bilinear transform //! //! To declare a filter like \f[G=\frac{a_1 s + a_0}{b_1 s + b_0}\f] //! the syntax is filter.setNumDen(num, den) //! where \f$num[0]=a_0\f$, \f$num[1]=a_1\f$ //! and \f$den[0]=b_0\f$, \f$den[1]=b_1\f$ //! void FirstOrderTransferFunction::initialize(double timestep, double num[2], double den[2], double u0, double y0, double min, double max) { mIsSaturated = false; mMin = min; mMax = max; mValue = y0; mDelayedU = u0; mDelayedY = std::max(std::min(y0, mMax), mMin); mTimeStep = timestep; setNumDen(num, den); setBackupLength(1); } void FirstOrderTransferFunction::setMinMax(double min, double max) { mMin = min; mMax = max; } void FirstOrderTransferFunction::setNum(double num[2]) { mCoeffU[0] = num[0]*mTimeStep-2.0*num[1]; mCoeffU[1] = num[0]*mTimeStep+2.0*num[1]; //std::cout << "DiscNum: " << mCoeffU[1] << " " << mCoeffU[0] << std::endl; } void FirstOrderTransferFunction::setDen(double den[2]) { mCoeffY[0] = den[0]*mTimeStep-2.0*den[1]; mCoeffY[1] = den[0]*mTimeStep+2.0*den[1]; //std::cout << "DiscDen: " << mCoeffY[1] << " " << mCoeffY[0] << std::endl; } void FirstOrderTransferFunction::setNumDen(double num[2], double den[2]) { mCoeffU[0] = num[0]*mTimeStep-2.0*num[1]; mCoeffU[1] = num[0]*mTimeStep+2.0*num[1]; mCoeffY[0] = den[0]*mTimeStep-2.0*den[1]; mCoeffY[1] = den[0]*mTimeStep+2.0*den[1]; } //! @brief Restore the backup at teh given step //! @param[in] nSteps The number of steps backwards in time to restore (1=last step) must be >=1 //! @note The function assumes that the backup buffer has been allocated //! @see setBackupLength void FirstOrderTransferFunction::restoreBackup(size_t nSteps) { if (nSteps > 0) { nSteps -= 1; } mDelayedU = mBackupU.getIdx(nSteps); mDelayedY = mBackupY.getIdx(nSteps); } //! @brief Pushes a backup of transfere function states into the backup buffer //! @note Only the delayed states are backed up, not the current value or the coefficients //! @todo Maybe we should backup more things like coefficients, saturated flag, current value, but that will take time at every timestep void FirstOrderTransferFunction::backup() { mBackupU.update(mDelayedU); mBackupY.update(mDelayedY); } void FirstOrderTransferFunction::initializeValues(double u0, double y0) { mDelayedU = u0; mDelayedY = y0; mValue = y0; } //! @brief Setup the number of backup steps to remember (size of the backup buffer) //! @param[in] nSteps The number of steps to remember void FirstOrderTransferFunction::setBackupLength(size_t nStep) { mBackupU.initialize(nStep, mDelayedU); mBackupY.initialize(nStep, mDelayedY); } //! @brief Updates the transfere function //! @param[in] u The new input value //! @returns The current transfere function ouput value after update double FirstOrderTransferFunction::update(double u) { //Filter equation //Bilinear transform is used mValue = 1.0/mCoeffY[1]*(mCoeffU[1]*u + mCoeffU[0]*mDelayedU - mCoeffY[0]*mDelayedY); // if (mValue >= mMax) // { // mDelayY = mMax; // mDelayU = mMax; // mValue = mMax; // mIsSaturated = true; // } // else if (mValue <= mMin) // { // mDelayY = mMin; // mDelayU = mMin; // mValue = mMin; // mIsSaturated = true; // } // else // { // mDelayY = mValue; // mDelayU = u; // mIsSaturated = false; // } if (mValue >= mMax) { mValue = mMax; mIsSaturated = true; } else if (mValue <= mMin) { mValue = mMin; mIsSaturated = true; } else { mIsSaturated = false; } mDelayedY = mValue; mDelayedU = u; return mValue; } //! @brief Make a backup of states and then calls update //! @param[in] u The new input value //! @returns The current transfere function ouput value after update double FirstOrderTransferFunction::updateWithBackup(double u) { backup(); return update(u); } //! @brief Read current transfere function output value //! @return The filtered actual value. double FirstOrderTransferFunction::value() const { return mValue; } double FirstOrderTransferFunction::delayedU() const { return mDelayedU; } double FirstOrderTransferFunction::delayedY() const { return mDelayedY; } //! @brief Check if the transfer function is saturated (has reached the set limits) //! @returns true or false bool FirstOrderTransferFunction::isSaturated() const { return mIsSaturated; } void FirstOrderTransferFunctionVariable::initialize(double *pTimestep, double num[2], double den[2], double u0, double y0, double min, double max) { mMin = min; mMax = max; mValue = y0; mDelayU = u0; mDelayY = std::max(std::min(y0, mMax), mMin); mpTimeStep = pTimestep; mPrevTimeStep = *pTimestep; mNum[0] = num[0]; mNum[1] = num[1]; mDen[0] = den[0]; mDen[1] = den[1]; recalculateCoefficients(); } void FirstOrderTransferFunctionVariable::setMinMax(double min, double max) { mMin = min; mMax = max; } void FirstOrderTransferFunctionVariable::setNum(double num[2]) { mNum[0] = num[0]; mNum[1] = num[1]; recalculateCoefficients(); } void FirstOrderTransferFunctionVariable::setDen(double den[2]) { mDen[0] = den[0]; mDen[1] = den[1]; recalculateCoefficients(); } void FirstOrderTransferFunctionVariable::setNumDen(double num[2], double den[2]) { mNum[0] = num[0]; mNum[1] = num[1]; mDen[0] = den[0]; mDen[1] = den[1]; recalculateCoefficients(); } void FirstOrderTransferFunctionVariable::recalculateCoefficients() { mCoeffU[0] = mNum[0]*(*mpTimeStep)-2.0*mNum[1]; mCoeffU[1] = mNum[0]*(*mpTimeStep)+2.0*mNum[1]; mCoeffY[0] = mDen[0]*(*mpTimeStep)-2.0*mDen[1]; mCoeffY[1] = mDen[0]*(*mpTimeStep)+2.0*mDen[1]; } void FirstOrderTransferFunctionVariable::initializeValues(double u0, double y0) { mDelayU = u0; mDelayY = y0; mValue = y0; } double FirstOrderTransferFunctionVariable::update(double u) { //Filter equation //Bilinear transform is used if((*mpTimeStep) != mPrevTimeStep) { mPrevTimeStep = (*mpTimeStep); recalculateCoefficients(); } mValue = 1.0/mCoeffY[1]*(mCoeffU[1]*u + mCoeffU[0]*mDelayU - mCoeffY[0]*mDelayY); if (mValue > mMax) { mDelayY = mMax; mDelayU = mMax; mValue = mMax; } else if (mValue < mMin) { mDelayY = mMin; mDelayU = mMin; mValue = mMin; } else { mDelayY = mValue; mDelayU = u; } return mValue; } //! Read current filter output value //! @return The filtered actual value. double FirstOrderTransferFunctionVariable::value() { return mValue; } <commit_msg>Fixed spelling mistakes<commit_after>/*----------------------------------------------------------------------------- This source file is a part of Hopsan Copyright (c) 2009 to present year, Hopsan Group This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. For license details and information about the Hopsan Group see the files GPLv3 and HOPSANGROUP in the Hopsan source code root directory For author and contributor information see the AUTHORS file -----------------------------------------------------------------------------*/ //! //! @file FirstOrderTransferFunction.cc //! @author Björn Eriksson <[email protected]> //! @date 2010-01-23 //! //! @brief Contains the Core First Order Transfer Function class //! //$Id$ //#include <iostream> #include <algorithm> #include "ComponentUtilities/FirstOrderTransferFunction.h" using namespace hopsan; //! @class hopsan::FirstOrderTransferFunction //! @ingroup ComponentUtilityClasses //! @brief The FirstOrderTransferFunction class implements a first order time discrete transfer function using bilinear transform //! //! To declare a filter like \f[G=\frac{a_1 s + a_0}{b_1 s + b_0}\f] //! the syntax is filter.setNumDen(num, den) //! where \f$num[0]=a_0\f$, \f$num[1]=a_1\f$ //! and \f$den[0]=b_0\f$, \f$den[1]=b_1\f$ //! void FirstOrderTransferFunction::initialize(double timestep, double num[2], double den[2], double u0, double y0, double min, double max) { mIsSaturated = false; mMin = min; mMax = max; mValue = y0; mDelayedU = u0; mDelayedY = std::max(std::min(y0, mMax), mMin); mTimeStep = timestep; setNumDen(num, den); setBackupLength(1); } void FirstOrderTransferFunction::setMinMax(double min, double max) { mMin = min; mMax = max; } void FirstOrderTransferFunction::setNum(double num[2]) { mCoeffU[0] = num[0]*mTimeStep-2.0*num[1]; mCoeffU[1] = num[0]*mTimeStep+2.0*num[1]; //std::cout << "DiscNum: " << mCoeffU[1] << " " << mCoeffU[0] << std::endl; } void FirstOrderTransferFunction::setDen(double den[2]) { mCoeffY[0] = den[0]*mTimeStep-2.0*den[1]; mCoeffY[1] = den[0]*mTimeStep+2.0*den[1]; //std::cout << "DiscDen: " << mCoeffY[1] << " " << mCoeffY[0] << std::endl; } void FirstOrderTransferFunction::setNumDen(double num[2], double den[2]) { mCoeffU[0] = num[0]*mTimeStep-2.0*num[1]; mCoeffU[1] = num[0]*mTimeStep+2.0*num[1]; mCoeffY[0] = den[0]*mTimeStep-2.0*den[1]; mCoeffY[1] = den[0]*mTimeStep+2.0*den[1]; } //! @brief Restore the backup at the given step //! @param[in] nSteps The number of steps backwards in time to restore (1=last step) must be >=1 //! @note The function assumes that the backup buffer has been allocated //! @see setBackupLength void FirstOrderTransferFunction::restoreBackup(size_t nSteps) { if (nSteps > 0) { nSteps -= 1; } mDelayedU = mBackupU.getIdx(nSteps); mDelayedY = mBackupY.getIdx(nSteps); } //! @brief Pushes a backup of transfer function states into the backup buffer //! @note Only the delayed states are backed up, not the current value or the coefficients //! @todo Maybe we should backup more things like coefficients, saturated flag, current value, but that will take time at every timestep void FirstOrderTransferFunction::backup() { mBackupU.update(mDelayedU); mBackupY.update(mDelayedY); } void FirstOrderTransferFunction::initializeValues(double u0, double y0) { mDelayedU = u0; mDelayedY = y0; mValue = y0; } //! @brief Setup the number of backup steps to remember (size of the backup buffer) //! @param[in] nSteps The number of steps to remember void FirstOrderTransferFunction::setBackupLength(size_t nStep) { mBackupU.initialize(nStep, mDelayedU); mBackupY.initialize(nStep, mDelayedY); } //! @brief Updates the transfer function //! @param[in] u The new input value //! @returns The current transfer function output value after update double FirstOrderTransferFunction::update(double u) { //Filter equation //Bilinear transform is used mValue = 1.0/mCoeffY[1]*(mCoeffU[1]*u + mCoeffU[0]*mDelayedU - mCoeffY[0]*mDelayedY); // if (mValue >= mMax) // { // mDelayY = mMax; // mDelayU = mMax; // mValue = mMax; // mIsSaturated = true; // } // else if (mValue <= mMin) // { // mDelayY = mMin; // mDelayU = mMin; // mValue = mMin; // mIsSaturated = true; // } // else // { // mDelayY = mValue; // mDelayU = u; // mIsSaturated = false; // } if (mValue >= mMax) { mValue = mMax; mIsSaturated = true; } else if (mValue <= mMin) { mValue = mMin; mIsSaturated = true; } else { mIsSaturated = false; } mDelayedY = mValue; mDelayedU = u; return mValue; } //! @brief Make a backup of states and then calls update //! @param[in] u The new input value //! @returns The current transfer function output value after update double FirstOrderTransferFunction::updateWithBackup(double u) { backup(); return update(u); } //! @brief Read current transfer function output value //! @return The filtered actual value. double FirstOrderTransferFunction::value() const { return mValue; } double FirstOrderTransferFunction::delayedU() const { return mDelayedU; } double FirstOrderTransferFunction::delayedY() const { return mDelayedY; } //! @brief Check if the transfer function is saturated (has reached the set limits) //! @returns true or false bool FirstOrderTransferFunction::isSaturated() const { return mIsSaturated; } void FirstOrderTransferFunctionVariable::initialize(double *pTimestep, double num[2], double den[2], double u0, double y0, double min, double max) { mMin = min; mMax = max; mValue = y0; mDelayU = u0; mDelayY = std::max(std::min(y0, mMax), mMin); mpTimeStep = pTimestep; mPrevTimeStep = *pTimestep; mNum[0] = num[0]; mNum[1] = num[1]; mDen[0] = den[0]; mDen[1] = den[1]; recalculateCoefficients(); } void FirstOrderTransferFunctionVariable::setMinMax(double min, double max) { mMin = min; mMax = max; } void FirstOrderTransferFunctionVariable::setNum(double num[2]) { mNum[0] = num[0]; mNum[1] = num[1]; recalculateCoefficients(); } void FirstOrderTransferFunctionVariable::setDen(double den[2]) { mDen[0] = den[0]; mDen[1] = den[1]; recalculateCoefficients(); } void FirstOrderTransferFunctionVariable::setNumDen(double num[2], double den[2]) { mNum[0] = num[0]; mNum[1] = num[1]; mDen[0] = den[0]; mDen[1] = den[1]; recalculateCoefficients(); } void FirstOrderTransferFunctionVariable::recalculateCoefficients() { mCoeffU[0] = mNum[0]*(*mpTimeStep)-2.0*mNum[1]; mCoeffU[1] = mNum[0]*(*mpTimeStep)+2.0*mNum[1]; mCoeffY[0] = mDen[0]*(*mpTimeStep)-2.0*mDen[1]; mCoeffY[1] = mDen[0]*(*mpTimeStep)+2.0*mDen[1]; } void FirstOrderTransferFunctionVariable::initializeValues(double u0, double y0) { mDelayU = u0; mDelayY = y0; mValue = y0; } double FirstOrderTransferFunctionVariable::update(double u) { //Filter equation //Bilinear transform is used if((*mpTimeStep) != mPrevTimeStep) { mPrevTimeStep = (*mpTimeStep); recalculateCoefficients(); } mValue = 1.0/mCoeffY[1]*(mCoeffU[1]*u + mCoeffU[0]*mDelayU - mCoeffY[0]*mDelayY); if (mValue > mMax) { mDelayY = mMax; mDelayU = mMax; mValue = mMax; } else if (mValue < mMin) { mDelayY = mMin; mDelayU = mMin; mValue = mMin; } else { mDelayY = mValue; mDelayU = u; } return mValue; } //! Read current filter output value //! @return The filtered actual value. double FirstOrderTransferFunctionVariable::value() { return mValue; } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved */ #ifndef _Stroika_Foundation_DataExchange_OptionsFile_inl_ #define _Stroika_Foundation_DataExchange_OptionsFile_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "../Characters/Format.h" #include "../Streams/BasicBinaryOutputStream.h" namespace Stroika { namespace Foundation { namespace DataExchange { /* ******************************************************************************** ************************** DataExchange::OptionsFile *************************** ******************************************************************************** */ template <typename T> Optional<T> OptionsFile::Read () { Optional<VariantValue> tmp = Read<VariantValue> (); if (tmp.IsMissing ()) { return Optional<T> (); } try { return fMapper_.ToObject<T> (*tmp); } catch (const BadFormatException& bf) { fLogger_ (Execution::Logger::Priority::eCriticalError, Characters::Format (L"Error analyzing configuration file (bad format) '%s' - using defaults.", GetReadFilePath_ ().c_str ())); return Optional<T> (); } catch (...) { // if this fails, its probably because somehow the data in the config file was bad. // So at least log that, and continue without reading anything (as if empty file) fLogger_ (Execution::Logger::Priority::eCriticalError, Characters::Format (L"Error analyzing configuration file '%s' - using defaults.", GetReadFilePath_ ().c_str ())); return Optional<T> (); } } template <typename T> T OptionsFile::Read (const T& defaultObj, ReadFlags readFlags) { Optional<T> eltRead = Read<T> (); Optional<T> elt2Write; // only if needed String msgAugment; if (eltRead.IsMissing ()) { if (readFlags == ReadFlags::eWriteIfChanged) { elt2Write = defaultObj; msgAugment = L"default"; } } else { if (readFlags == ReadFlags::eWriteIfChanged) { try { // See if re-persisting the item would change it. // This is useful if your data model adds or removes fields. It updates the file contents written to the // upgraded/latest form Memory::BLOB oldData = ReadRaw (); // @todo could have saved from previous Read<T> Memory::BLOB newData; { Streams::BasicBinaryOutputStream outStream; fWriter_.Write (fMapper_.FromObject (*eltRead), outStream); // not sure needed? outStream.Flush(); newData = outStream.As<Memory::BLOB> (); } if (oldData != newData) { elt2Write = eltRead; msgAugment = L"(because something changed)"; } } catch (...) { fLogger_ (Execution::Logger::Priority::eError, Characters::Format (L"Failed to compare configuration file: %s", GetReadFilePath_ ().c_str ())); } } } if (elt2Write.IsPresent ()) { fLogger_ (Execution::Logger::Priority::eInfo, Characters::Format (L"Writing %s '%s' configuration file.", msgAugment.c_str (), GetWriteFilePath_ ().c_str ())); try { Write (*elt2Write); } catch (...) { fLogger_ (Execution::Logger::Priority::eError, Characters::Format (L"Failed to write default values to file: %s", GetWriteFilePath_ ().c_str ())); } return *elt2Write; } else if (eltRead.IsPresent ()) { return *eltRead; } else { return defaultObj; } } template <typename T> void OptionsFile::Write (const T& optionsObject) { Write<VariantValue> (fMapper_.FromObject<T> (optionsObject)); } } } } #endif /*_Stroika_Foundation_DataExchange_OptionsFile_inl_*/ <commit_msg>OptionsFile - cleanup to Read (and automatic write if changes) code<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved */ #ifndef _Stroika_Foundation_DataExchange_OptionsFile_inl_ #define _Stroika_Foundation_DataExchange_OptionsFile_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "../Characters/Format.h" #include "../Streams/BasicBinaryOutputStream.h" namespace Stroika { namespace Foundation { namespace DataExchange { /* ******************************************************************************** ************************** DataExchange::OptionsFile *************************** ******************************************************************************** */ template <typename T> Optional<T> OptionsFile::Read () { Optional<VariantValue> tmp = Read<VariantValue> (); if (tmp.IsMissing ()) { return Optional<T> (); } try { return fMapper_.ToObject<T> (*tmp); } catch (const BadFormatException& bf) { fLogger_ (Execution::Logger::Priority::eCriticalError, Characters::Format (L"Error analyzing configuration file (bad format) '%s' - using defaults.", GetReadFilePath_ ().c_str ())); return Optional<T> (); } catch (...) { // if this fails, its probably because somehow the data in the config file was bad. // So at least log that, and continue without reading anything (as if empty file) fLogger_ (Execution::Logger::Priority::eCriticalError, Characters::Format (L"Error analyzing configuration file '%s' - using defaults.", GetReadFilePath_ ().c_str ())); return Optional<T> (); } } template <typename T> T OptionsFile::Read (const T& defaultObj, ReadFlags readFlags) { Optional<T> eltRead = Read<T> (); Optional<T> elt2Write; // only if needed String msgAugment; if (eltRead.IsMissing ()) { if (readFlags == ReadFlags::eWriteIfChanged) { elt2Write = defaultObj; msgAugment = L" so defaults are more easily editable"; } } else { if (readFlags == ReadFlags::eWriteIfChanged) { if (elt2Write.IsMissing ()) { // if filename differs - upgrading if (GetReadFilePath_ () != GetWriteFilePath_ ()) { elt2Write = eltRead; msgAugment = L" in a new directory because upgrading the software has been upgraded"; } } if (elt2Write.IsMissing ()) { try { // See if re-persisting the item would change it. // This is useful if your data model adds or removes fields. It updates the file contents written to the // upgraded/latest form. Memory::BLOB oldData = ReadRaw (); // @todo could have saved from previous Read<T> Memory::BLOB newData; { Streams::BasicBinaryOutputStream outStream; fWriter_.Write (fMapper_.FromObject (*eltRead), outStream); // not sure needed? outStream.Flush(); newData = outStream.As<Memory::BLOB> (); } if (oldData != newData) { elt2Write = eltRead; msgAugment = L" because something changed (e.g. a default, or field added/removed)."; } } catch (...) { fLogger_ (Execution::Logger::Priority::eError, Characters::Format (L"Failed to compare configuration file: %s", GetReadFilePath_ ().c_str ())); } } } } if (elt2Write.IsPresent ()) { fLogger_ (Execution::Logger::Priority::eInfo, Characters::Format (L"Writing configuration file '%s'%s.", GetWriteFilePath_ ().c_str (), msgAugment.c_str ())); try { Write (*elt2Write); } catch (...) { fLogger_ (Execution::Logger::Priority::eError, Characters::Format (L"Failed to write default values to file: %s", GetWriteFilePath_ ().c_str ())); } return *elt2Write; } else if (eltRead.IsPresent ()) { return *eltRead; } else { return defaultObj; } } template <typename T> void OptionsFile::Write (const T& optionsObject) { Write<VariantValue> (fMapper_.FromObject<T> (optionsObject)); } } } } #endif /*_Stroika_Foundation_DataExchange_OptionsFile_inl_*/ <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/phy/adr32s.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file adr32s.C /// @brief Subroutines for the PHY ADR32S registers /// // *HWP HWP Owner: Stephen Glancy <[email protected]> // *HWP HWP Backup: Andre Marin <[email protected]> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <lib/phy/adr32s.H> #include <lib/phy/dcd.H> #include <lib/workarounds/adr32s_workarounds.H> #include <generic/memory/lib/utils/find.H> #include <lib/mss_attribute_accessors_manual.H> using fapi2::TARGET_TYPE_MCA; using fapi2::TARGET_TYPE_SYSTEM; using fapi2::FAPI2_RC_SUCCESS; namespace mss { // Definition of the ADR32S DLL Config registers const std::vector<uint64_t> adr32sTraits<fapi2::TARGET_TYPE_MCA>::DLL_CNFG_REG = { MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0, MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S1 }; // Definition of the ADR32S output driver registers const std::vector<uint64_t> adr32sTraits<fapi2::TARGET_TYPE_MCA>::OUTPUT_DRIVER_REG = { MCA_DDRPHY_ADR_OUTPUT_FORCE_ATEST_CNTL_P0_ADR32S0, MCA_DDRPHY_ADR_OUTPUT_FORCE_ATEST_CNTL_P0_ADR32S1, }; // Definition of the ADR32S duty cycle distortion registers const std::vector<uint64_t> adr32sTraits<fapi2::TARGET_TYPE_MCA>::DUTY_CYCLE_DISTORTION_REG = { MCA_DDRPHY_ADR_DCD_CONTROL_P0_ADR32S0, MCA_DDRPHY_ADR_DCD_CONTROL_P0_ADR32S1, }; // Definition of the ADR32S write clock static offset registers const std::vector<uint64_t> adr32sTraits<fapi2::TARGET_TYPE_MCA>::PR_STATIC_OFFSET_REG = { MCA_DDRPHY_ADR_MCCLK_WRCLK_PR_STATIC_OFFSET_P0_ADR32S0, MCA_DDRPHY_ADR_MCCLK_WRCLK_PR_STATIC_OFFSET_P0_ADR32S1, }; namespace adr32s { /// /// @brief Perform ADR DCD calibration - Nimbus Only /// @param[in] i_target the MCBIST (controler) to perform calibration on /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode duty_cycle_distortion_calibration( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target ) { const auto l_mca = mss::find_targets<TARGET_TYPE_MCA>(i_target); uint8_t l_sim = 0; FAPI_TRY( mss::is_simulation( l_sim) ); // Nothing works here in cycle sim ... if (l_sim) { return FAPI2_RC_SUCCESS; } if (l_mca.size() == 0) { FAPI_INF("No MCA, skipping duty cycle distortion calibration"); return FAPI2_RC_SUCCESS; } // If we're supposed to skip DCD, just return success if (!mss::run_dcd_calibration(i_target)) { FAPI_INF("%s Skipping DCD calibration algorithm per ATTR set", mss::c_str(i_target)); return FAPI2_RC_SUCCESS; } // Runs the proper DCD calibration for Nimbus DD1 vs DD2 if(mss::chip_ec_nimbus_lt_2_0(i_target)) { // Runs the DD1 calibration FAPI_TRY(mss::workarounds::adr32s::duty_cycle_distortion_calibration(i_target)); } else { // Runs the DD2 calibration algorithm FAPI_TRY(mss::dcd::execute_hw_calibration(i_target)); } fapi_try_exit: return fapi2::current_err; } } // close namespace adrs32 } // close namespace mss <commit_msg>L3 support for ddr_phy_reset, termination_control<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/phy/adr32s.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file adr32s.C /// @brief Subroutines for the PHY ADR32S registers /// // *HWP HWP Owner: Stephen Glancy <[email protected]> // *HWP HWP Backup: Andre Marin <[email protected]> // *HWP Team: Memory // *HWP Level: 3 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <lib/phy/adr32s.H> #include <lib/phy/dcd.H> #include <lib/workarounds/adr32s_workarounds.H> #include <generic/memory/lib/utils/find.H> #include <lib/mss_attribute_accessors_manual.H> using fapi2::TARGET_TYPE_MCA; using fapi2::TARGET_TYPE_SYSTEM; using fapi2::FAPI2_RC_SUCCESS; namespace mss { // Definition of the ADR32S DLL Config registers const std::vector<uint64_t> adr32sTraits<fapi2::TARGET_TYPE_MCA>::DLL_CNFG_REG = { MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0, MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S1 }; // Definition of the ADR32S output driver registers const std::vector<uint64_t> adr32sTraits<fapi2::TARGET_TYPE_MCA>::OUTPUT_DRIVER_REG = { MCA_DDRPHY_ADR_OUTPUT_FORCE_ATEST_CNTL_P0_ADR32S0, MCA_DDRPHY_ADR_OUTPUT_FORCE_ATEST_CNTL_P0_ADR32S1, }; // Definition of the ADR32S duty cycle distortion registers const std::vector<uint64_t> adr32sTraits<fapi2::TARGET_TYPE_MCA>::DUTY_CYCLE_DISTORTION_REG = { MCA_DDRPHY_ADR_DCD_CONTROL_P0_ADR32S0, MCA_DDRPHY_ADR_DCD_CONTROL_P0_ADR32S1, }; // Definition of the ADR32S write clock static offset registers const std::vector<uint64_t> adr32sTraits<fapi2::TARGET_TYPE_MCA>::PR_STATIC_OFFSET_REG = { MCA_DDRPHY_ADR_MCCLK_WRCLK_PR_STATIC_OFFSET_P0_ADR32S0, MCA_DDRPHY_ADR_MCCLK_WRCLK_PR_STATIC_OFFSET_P0_ADR32S1, }; namespace adr32s { /// /// @brief Perform ADR DCD calibration - Nimbus Only /// @param[in] i_target the MCBIST (controler) to perform calibration on /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode duty_cycle_distortion_calibration( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target ) { const auto l_mca = mss::find_targets<TARGET_TYPE_MCA>(i_target); uint8_t l_sim = 0; FAPI_TRY( mss::is_simulation( l_sim) ); // Nothing works here in cycle sim ... if (l_sim) { return FAPI2_RC_SUCCESS; } if (l_mca.size() == 0) { FAPI_INF("%s No MCA, skipping duty cycle distortion calibration", mss::c_str(i_target) ); return FAPI2_RC_SUCCESS; } // If we're supposed to skip DCD, just return success if (!mss::run_dcd_calibration(i_target)) { FAPI_INF("%s Skipping DCD calibration algorithm per ATTR set", mss::c_str(i_target)); return FAPI2_RC_SUCCESS; } // Runs the proper DCD calibration for Nimbus DD1 vs DD2 if(mss::chip_ec_nimbus_lt_2_0(i_target)) { // Runs the DD1 calibration FAPI_TRY(mss::workarounds::adr32s::duty_cycle_distortion_calibration(i_target), "%s Failed dcd calibration", mss::c_str(i_target) ); } else { // Runs the DD2 calibration algorithm FAPI_TRY(mss::dcd::execute_hw_calibration(i_target), "%s Failed dcd execute hw calibration", mss::c_str(i_target) ); } fapi_try_exit: return fapi2::current_err; } } // close namespace adrs32 } // close namespace mss <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_memdiag.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_mss_memdiag.C /// @brief Mainstore pattern testing /// // *HWP HWP Owner: Brian Silver <[email protected]> // *HWP HWP Backup: Andre Marin <[email protected]> // *HWP Team: Memory // *HWP Level: 1 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <p9_mss_memdiag.H> #include <lib/utils/poll.H> #include <lib/mcbist/address.H> #include <lib/mcbist/memdiags.H> #include <lib/mcbist/mcbist.H> #include <lib/fir/memdiags_fir.H> using fapi2::TARGET_TYPE_MCBIST; extern "C" { /// /// @brief Pattern test the DRAM /// @param[in] i_target the McBIST of the ports of the dram you're training /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode p9_mss_memdiag( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target ) { FAPI_INF("Start memdiag"); // Unmask the memdiags FIR FAPI_TRY( mss::unmask_memdiags_errors(i_target) ); FAPI_TRY( memdiags::sf_init(i_target, mss::mcbist::PATTERN_0) ); // TODO RTC:153951 // Remove the polling when the attention bits are hooked up { // Poll for the fir bit. We expect this to be set ... fapi2::buffer<uint64_t> l_status; // A small vector of addresses to poll during the polling loop static const std::vector<mss::poll_probe<fapi2::TARGET_TYPE_MCBIST>> l_probes = { {i_target, "mcbist current address", MCBIST_MCBMCATQ}, }; mss::poll_parameters l_poll_parameters; bool l_poll_results = mss::poll(i_target, MCBIST_MCBISTFIRQ, l_poll_parameters, [&l_status](const size_t poll_remaining, const fapi2::buffer<uint64_t>& stat_reg) -> bool { FAPI_DBG("mcbist firq 0x%llx, remaining: %d", stat_reg, poll_remaining); l_status = stat_reg; return l_status.getBit<MCBIST_MCBISTFIRQ_MCBIST_PROGRAM_COMPLETE>() == true; }, l_probes); FAPI_ASSERT( l_poll_results == true, fapi2::MSS_MEMDIAGS_SUPERFAST_INIT_FAILED_TO_INIT().set_TARGET(i_target), "p9_mss_memdiags timedout %s", mss::c_str(i_target) ); } fapi_try_exit: FAPI_INF("End memdiag"); return fapi2::current_err; } } <commit_msg>Change memdiags/mcbist stop conditions to incorporate end, thresholds<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_memdiag.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_mss_memdiag.C /// @brief Mainstore pattern testing /// // *HWP HWP Owner: Brian Silver <[email protected]> // *HWP HWP Backup: Andre Marin <[email protected]> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <p9_mss_memdiag.H> #include <lib/utils/poll.H> #include <lib/mcbist/address.H> #include <lib/mcbist/memdiags.H> #include <lib/mcbist/mcbist.H> #include <lib/fir/memdiags_fir.H> using fapi2::TARGET_TYPE_MCBIST; extern "C" { /// /// @brief Pattern test the DRAM /// @param[in] i_target the McBIST of the ports of the dram you're training /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode p9_mss_memdiag( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target ) { FAPI_INF("Start memdiag"); // Unmask the memdiags FIR FAPI_TRY( mss::unmask_memdiags_errors(i_target) ); FAPI_TRY( memdiags::sf_init(i_target, mss::mcbist::PATTERN_0) ); // TODO RTC:153951 // Remove the polling when the attention bits are hooked up { // Poll for the fir bit. We expect this to be set ... fapi2::buffer<uint64_t> l_status; // A small vector of addresses to poll during the polling loop static const std::vector<mss::poll_probe<fapi2::TARGET_TYPE_MCBIST>> l_probes = { {i_target, "mcbist current address", MCBIST_MCBMCATQ}, }; mss::poll_parameters l_poll_parameters; bool l_poll_results = mss::poll(i_target, MCBIST_MCBISTFIRQ, l_poll_parameters, [&l_status](const size_t poll_remaining, const fapi2::buffer<uint64_t>& stat_reg) -> bool { FAPI_DBG("mcbist firq 0x%llx, remaining: %d", stat_reg, poll_remaining); l_status = stat_reg; return l_status.getBit<MCBIST_MCBISTFIRQ_MCBIST_PROGRAM_COMPLETE>() == true; }, l_probes); FAPI_ASSERT( l_poll_results == true, fapi2::MSS_MEMDIAGS_SUPERFAST_INIT_FAILED_TO_INIT().set_TARGET(i_target), "p9_mss_memdiags timedout %s", mss::c_str(i_target) ); } fapi_try_exit: FAPI_INF("End memdiag"); return fapi2::current_err; } } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/utils/imageProcs/p9_infrastruct_help.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _P9_INFRASTRUCT_HELP_H_ #define _P9_INFRASTRUCT_HELP_H_ #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <string.h> //memcpy() #include <errno.h> // // Various image/ring buffer sizes. Must be used by all users (VBU, FSP, HB, HBI, Cronus) // const uint32_t MAX_REF_IMAGE_SIZE = 1024 * 1024; // Max reference image size. const uint32_t FIXED_RING_BUF_SIZE = 60000; // Fixed ring buf size for _fixed. #define CHIPLET_ID_MIN (uint8_t)0x00 #define CHIPLET_ID_MAX (uint8_t)0x37 #define MY_INF(_fmt_, _args_...) printf(_fmt_, ##_args_) #define MY_ERR(_fmt_, _args_...) printf(_fmt_, ##_args_) #define MY_DBG(_fmt_, _args_...) printf(_fmt_, ##_args_) // N-byte align an address, offset or size (aos) inline uint64_t myByteAlign( const uint8_t nBytes, const uint64_t aos) { return ((aos + nBytes - 1) / nBytes) * nBytes; } #endif //_P9_INFRASTRUCT_HELP_H_ <commit_msg>Replace usage of printf() with FAPI_INF() in p9_tor<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/utils/imageProcs/p9_infrastruct_help.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef _P9_INFRASTRUCT_HELP_H_ #define _P9_INFRASTRUCT_HELP_H_ #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <string.h> //memcpy() #include <errno.h> // // Various image/ring buffer sizes. Must be used by all users (VBU, FSP, HB, HBI, Cronus) // const uint32_t MAX_REF_IMAGE_SIZE = 1024 * 1024; // Max reference image size. const uint32_t FIXED_RING_BUF_SIZE = 60000; // Fixed ring buf size for _fixed. #define CHIPLET_ID_MIN (uint8_t)0x00 #define CHIPLET_ID_MAX (uint8_t)0x37 #if defined(__FAPI) #define MY_INF(_fmt_, _args_...) FAPI_INF(_fmt_, ##_args_) #define MY_ERR(_fmt_, _args_...) FAPI_INF(_fmt_, ##_args_) #define MY_DBG(_fmt_, _args_...) FAPI_DBG(_fmt_, ##_args_) #else #define MY_INF(_fmt_, _args_...) printf(_fmt_, ##_args_) #define MY_ERR(_fmt_, _args_...) printf(_fmt_, ##_args_) #define MY_DBG(_fmt_, _args_...) printf(_fmt_, ##_args_) #endif // N-byte align an address, offset or size (aos) inline uint64_t myByteAlign( const uint8_t nBytes, const uint64_t aos) { return ((aos + nBytes - 1) / nBytes) * nBytes; } #endif //_P9_INFRASTRUCT_HELP_H_ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: adc_cmds.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: vg $ $Date: 2007-09-18 14:05:27 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <precomp.h> #include "adc_cmds.hxx" // NOT FULLY DEFINED SERVICES #include <ary/ary.hxx> #include <autodoc/displaying.hxx> #include <autodoc/dsp_html_std.hxx> #include <display/corframe.hxx> #include <display/uidldisp.hxx> namespace autodoc { namespace command { extern const String C_opt_Include("-I:"); extern const String C_opt_Verbose("-v"); extern const String C_opt_Parse("-parse"); extern const String C_opt_Name("-name"); extern const String C_opt_LangAll("-lg"); extern const String C_opt_ExtensionsAll("-extg"); extern const String C_opt_DevmanFile("-dvgfile"); extern const String C_opt_SinceFile("-sincefile"); extern const String C_arg_Cplusplus("c++"); extern const String C_arg_Idl("idl"); extern const String C_arg_Java("java"); extern const String C_opt_Project("-p"); //extern const String C_opt_Lang; //extern const String C_opt_Extensions; extern const String C_opt_SourceDir("-d"); extern const String C_opt_SourceTree("-t"); extern const String C_opt_SourceFile("-f"); extern const String C_opt_CreateHtml("-html"); extern const String C_opt_DevmanRoot("-dvgroot"); //extern const String C_opt_CreateXml("-xml"); //extern const String C_opt_Load("-load"); //extern const String C_opt_Save("-save"); extern const String C_opt_ExternNamespace("-extnsp"); extern const String C_opt_ExternRoot("-extroot"); //************************** CreateHTML ***********************// CreateHtml::CreateHtml() : sOutputRootDirectory(), sDevelopersManual_HtmlRoot() { } CreateHtml::~CreateHtml() { } void CreateHtml::do_Init( opt_iter & it, opt_iter itEnd ) { ++it; CHECKOPT( it != itEnd && (*it).char_at(0) != '-', "output directory", C_opt_CreateHtml ); sOutputRootDirectory = *it; for ( ++it; it != itEnd AND (*it == C_opt_DevmanRoot); ++it ) { if (*it == C_opt_DevmanRoot) { ++it; CHECKOPT( it != itEnd AND (*it).char_at(0) != '-', "HTML root directory of Developers Guide", C_opt_DevmanRoot ); sDevelopersManual_HtmlRoot = *it; } } // end for } bool CreateHtml::do_Run() const { if ( ::ary::n22::Repository::The_().HasIdl() ) run_Idl(); if ( ::ary::n22::Repository::The_().HasCpp() ) run_Cpp(); return true; } int CreateHtml::inq_RunningRank() const { return static_cast<int>(rank_CreateHtml); } void CreateHtml::run_Idl() const { const ary::idl::Gate & rGate = ary::n22::Repository::The_().Gate_Idl(); Cout() << "Creating HTML-output into the directory " << sOutputRootDirectory << "." << Endl(); const DisplayToolsFactory_Ifc & rToolsFactory = DisplayToolsFactory_Ifc::GetIt_(); Dyn<autodoc::HtmlDisplay_Idl_Ifc> pDisplay( rToolsFactory.Create_HtmlDisplay_Idl() ); DYN display::CorporateFrame & // KORR: Remove the need for const_cast in future. drFrame = const_cast< display::CorporateFrame& >(rToolsFactory.Create_StdFrame()); if (NOT DevelopersManual_HtmlRoot().empty()) drFrame.Set_DevelopersGuideHtmlRoot( DevelopersManual_HtmlRoot() ); pDisplay->Run( sOutputRootDirectory, rGate, drFrame ); } void CreateHtml::run_Cpp() const { const ary::n22::Repository & rReposy = ary::n22::Repository::The_(); const ary::cpp::DisplayGate & rGate = rReposy.Gate_Cpp(); const DisplayToolsFactory_Ifc & rToolsFactory = DisplayToolsFactory_Ifc::GetIt_(); Dyn< autodoc::HtmlDisplay_UdkStd > pDisplay( rToolsFactory.Create_HtmlDisplay_UdkStd() ); pDisplay->Run( sOutputRootDirectory, rGate, rToolsFactory.Create_StdFrame() ); } } // namespace command } // namespace autodoc <commit_msg>INTEGRATION: CWS adc18 (1.8.2); FILE MERGED 2007/10/19 10:37:29 np 1.8.2.2: #i81775# 2007/10/18 15:23:15 np 1.8.2.1: #i81775#<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: adc_cmds.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: hr $ $Date: 2007-11-02 16:43:34 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <precomp.h> #include "adc_cmds.hxx" // NOT FULLY DEFINED SERVICES #include <ary/ary.hxx> #include <autodoc/displaying.hxx> #include <autodoc/dsp_html_std.hxx> #include <display/corframe.hxx> #include <adc_cl.hxx> namespace autodoc { namespace command { extern const String C_opt_Include("-I:"); extern const String C_opt_Verbose("-v"); extern const String C_opt_Parse("-parse"); extern const String C_opt_Name("-name"); extern const String C_opt_LangAll("-lg"); extern const String C_opt_ExtensionsAll("-extg"); extern const String C_opt_DevmanFile("-dvgfile"); extern const String C_opt_SinceFile("-sincefile"); extern const String C_arg_Cplusplus("c++"); extern const String C_arg_Idl("idl"); extern const String C_arg_Java("java"); extern const String C_opt_Project("-p"); //extern const String C_opt_Lang; //extern const String C_opt_Extensions; extern const String C_opt_SourceDir("-d"); extern const String C_opt_SourceTree("-t"); extern const String C_opt_SourceFile("-f"); extern const String C_opt_CreateHtml("-html"); extern const String C_opt_DevmanRoot("-dvgroot"); //extern const String C_opt_CreateXml("-xml"); //extern const String C_opt_Load("-load"); //extern const String C_opt_Save("-save"); extern const String C_opt_ExternNamespace("-extnsp"); extern const String C_opt_ExternRoot("-extroot"); //************************** CreateHTML ***********************// CreateHtml::CreateHtml() : sOutputRootDirectory(), sDevelopersManual_HtmlRoot() { } CreateHtml::~CreateHtml() { } void CreateHtml::do_Init( opt_iter & it, opt_iter itEnd ) { ++it; CHECKOPT( it != itEnd && (*it).char_at(0) != '-', "output directory", C_opt_CreateHtml ); sOutputRootDirectory = *it; for ( ++it; it != itEnd AND (*it == C_opt_DevmanRoot); ++it ) { if (*it == C_opt_DevmanRoot) { ++it; CHECKOPT( it != itEnd AND (*it).char_at(0) != '-', "HTML root directory of Developers Guide", C_opt_DevmanRoot ); sDevelopersManual_HtmlRoot = *it; } } // end for } bool CreateHtml::do_Run() const { if ( CommandLine::Get_().IdlUsed() ) run_Idl(); if ( CommandLine::Get_().CppUsed() ) run_Cpp(); return true; } int CreateHtml::inq_RunningRank() const { return static_cast<int>(rank_CreateHtml); } void CreateHtml::run_Idl() const { const ary::idl::Gate & rGate = CommandLine::Get_().TheRepository().Gate_Idl(); Cout() << "Creating HTML-output into the directory " << sOutputRootDirectory << "." << Endl(); const DisplayToolsFactory_Ifc & rToolsFactory = DisplayToolsFactory_Ifc::GetIt_(); Dyn<autodoc::HtmlDisplay_Idl_Ifc> pDisplay( rToolsFactory.Create_HtmlDisplay_Idl() ); DYN display::CorporateFrame & // KORR_FUTURE: Remove the need for const_cast drFrame = const_cast< display::CorporateFrame& >(rToolsFactory.Create_StdFrame()); if (NOT DevelopersManual_HtmlRoot().empty()) drFrame.Set_DevelopersGuideHtmlRoot( DevelopersManual_HtmlRoot() ); pDisplay->Run( sOutputRootDirectory, rGate, drFrame ); } void CreateHtml::run_Cpp() const { const ary::Repository & rReposy = CommandLine::Get_().TheRepository(); const ary::cpp::Gate & rGate = rReposy.Gate_Cpp(); const DisplayToolsFactory_Ifc & rToolsFactory = DisplayToolsFactory_Ifc::GetIt_(); Dyn< autodoc::HtmlDisplay_UdkStd > pDisplay( rToolsFactory.Create_HtmlDisplay_UdkStd() ); pDisplay->Run( sOutputRootDirectory, rGate, rToolsFactory.Create_StdFrame() ); } } // namespace command } // namespace autodoc <|endoftext|>
<commit_before>// __BEGIN_LICENSE__ // Copyright (C) 2006-2010 United States Government as represented by // the Administrator of the National Aeronautics and Space Administration. // All Rights Reserved. // __END_LICENSE__ #include <gtest/gtest.h> #include <test/Helpers.h> #include <vw/Core/Settings.h> #include <boost/filesystem/operations.hpp> namespace fs = boost::filesystem; #if VW_HAVE_FENV_H #include <fenv.h> #endif int main(int argc, char **argv) { // Disable the user's config file vw::vw_settings().set_rc_filename(""); ::testing::InitGoogleTest(&argc, argv); // Default to the "threadsafe" style because we can't delete our singletons // yet; this style of test launches a new process, so the singletons are // fresh. ::testing::FLAGS_gtest_death_test_style = "threadsafe"; #if VW_HAVE_FEENABLEEXCEPT if (getenv("VW_CATCH_FP_ERRORS")) feenableexcept(FE_DIVBYZERO|FE_INVALID|FE_OVERFLOW|FE_UNDERFLOW); #endif if (getenv("VW_DEBUG")) { vw::vw_log().console_log().rule_set().add_rule(vw::VerboseDebugMessage, "*"); } // TODO: Make it so the seed is settable so we can reproduce failures in // probabilistic algorithms. This uses clock() instead of time() because // clock() (being measured in "processor ticks" instead of seconds) is likely // to exhibit more variation when tests are run many times in a short time // span. std::srand(boost::numeric_cast<unsigned int>((clock()))); return RUN_ALL_TESTS(); } namespace vw { namespace test { UnlinkName::UnlinkName(const std::string& base, const std::string& directory) : std::string(directory + "/" + base) { VW_ASSERT(!directory.empty(), ArgumentErr() << "An empty directory path is dangerous"); fs::remove_all(this->c_str()); } UnlinkName::UnlinkName(const char *base, const std::string& directory) : std::string(directory + "/" + base) { VW_ASSERT(!directory.empty(), ArgumentErr() << "An empty directory path is dangerous"); fs::remove_all(this->c_str()); } UnlinkName::~UnlinkName() { if (!this->empty()) fs::remove_all(this->c_str()); } }} // namespace vw::test <commit_msg>test to make sure nothing changes the working directory<commit_after>// __BEGIN_LICENSE__ // Copyright (C) 2006-2010 United States Government as represented by // the Administrator of the National Aeronautics and Space Administration. // All Rights Reserved. // __END_LICENSE__ #include <gtest/gtest.h> #include <test/Helpers.h> #include <vw/Core/Settings.h> #include <boost/filesystem/operations.hpp> namespace fs = boost::filesystem; #if VW_HAVE_FENV_H #include <fenv.h> #endif int main(int argc, char **argv) { // Disable the user's config file vw::vw_settings().set_rc_filename(""); ::testing::InitGoogleTest(&argc, argv); // Default to the "threadsafe" style because we can't delete our singletons // yet; this style of test launches a new process, so the singletons are // fresh. ::testing::FLAGS_gtest_death_test_style = "threadsafe"; #if VW_HAVE_FEENABLEEXCEPT if (getenv("VW_CATCH_FP_ERRORS")) feenableexcept(FE_DIVBYZERO|FE_INVALID|FE_OVERFLOW|FE_UNDERFLOW); #endif if (getenv("VW_DEBUG")) { vw::vw_log().console_log().rule_set().add_rule(vw::VerboseDebugMessage, "*"); } // TODO: Make it so the seed is settable so we can reproduce failures in // probabilistic algorithms. This uses clock() instead of time() because // clock() (being measured in "processor ticks" instead of seconds) is likely // to exhibit more variation when tests are run many times in a short time // span. std::srand(boost::numeric_cast<unsigned int>((clock()))); fs::current_path(TEST_SRCDIR); int ret = RUN_ALL_TESTS(); VW_ASSERT( fs::path(TEST_SRCDIR) == fs::current_path(), vw::LogicErr() << "Something changed the working directory"); return ret; } namespace vw { namespace test { UnlinkName::UnlinkName(const std::string& base, const std::string& directory) : std::string(directory + "/" + base) { VW_ASSERT(!directory.empty(), ArgumentErr() << "An empty directory path is dangerous"); fs::remove_all(this->c_str()); } UnlinkName::UnlinkName(const char *base, const std::string& directory) : std::string(directory + "/" + base) { VW_ASSERT(!directory.empty(), ArgumentErr() << "An empty directory path is dangerous"); fs::remove_all(this->c_str()); } UnlinkName::~UnlinkName() { if (!this->empty()) fs::remove_all(this->c_str()); } }} // namespace vw::test <|endoftext|>
<commit_before>#include "c24/communication/stream.h" #include <chrono> #include <string> #include <thread> #include <glog/logging.h> namespace c24 { namespace communication { Stream::Stream(std::unique_ptr<StreamBackendInterface> stream_backend) : stream_backend_(std::move(stream_backend)) {} bool Stream::Connected() { status_ = Status(); if (stream_backend_ == nullptr) { return false; } return stream_backend_->Connected(); } bool Stream::MessageAvailable() { CheckConnectionAndReconnect(); status_ = Status(); CHECK_NE(stream_backend_, nullptr); return stream_backend_->MessageAvailable(); } std::string Stream::GetMessage() { CheckConnectionAndReconnect(); status_ = Status(); CHECK_NE(stream_backend_, nullptr); std::string msg = stream_backend_->GetMessage(); LOG(INFO) << "Received: \"" << msg << "\""; return msg; } bool Stream::SendMessage(const std::string& msg, bool newline) { CheckConnectionAndReconnect(); status_ = Status(); CHECK_NE(stream_backend_, nullptr); // Put two spaces after Sending so it is lined up with messages after // Received. LOG(INFO) << "Sending: \"" << msg << "\""; const std::string& msg_to_send = newline ? msg + '\n' : msg; return stream_backend_->SendMessage(msg_to_send); } Status Stream::LastStatus() const { if (!status_.Ok()) return status_; CHECK_NE(stream_backend_, nullptr); return stream_backend_->LastStatus(); } bool Stream::GetMessageWithCheck(const char* expected) { std::string msg_ok = GetMessage(); if (msg_ok != expected) { status_ = stream_backend_->LastStatus(); if (msg_ok.length() >= 11 && msg_ok.substr(0, 5) == "ERROR") { int error_code = std::atoi(msg_ok.substr(6, 3).c_str()); status_.SetServerError(error_code, msg_ok.substr(11)); } LOG(ERROR) << "Expected \"" << expected << "\" but received \"" << msg_ok << "\""; return false; } return true; } bool Stream::SendMessageWithCheck(const std::string& msg, bool newline, const char* expected) { status_ = Status(); bool success = SendMessage(msg, newline); if (success) { success = GetMessageWithCheck(expected); } return success; } void Stream::CheckConnectionAndReconnect() { if (Connected()) return; stream_backend_->Reconnect(); while (!Connected()) { std::this_thread::sleep_for( std::chrono::milliseconds(TIME_BETWEEN_RECONNECT_TRIES_MILLISECONDS)); stream_backend_->Reconnect(); } } } // namespace communication } // namespace c24 <commit_msg>Change CHECK_NE to CHECK to fix the compilation.<commit_after>#include "c24/communication/stream.h" #include <chrono> #include <string> #include <thread> #include <glog/logging.h> namespace c24 { namespace communication { Stream::Stream(std::unique_ptr<StreamBackendInterface> stream_backend) : stream_backend_(std::move(stream_backend)) {} bool Stream::Connected() { status_ = Status(); if (stream_backend_ == nullptr) { return false; } return stream_backend_->Connected(); } bool Stream::MessageAvailable() { CheckConnectionAndReconnect(); status_ = Status(); CHECK(stream_backend_ != nullptr); return stream_backend_->MessageAvailable(); } std::string Stream::GetMessage() { CheckConnectionAndReconnect(); status_ = Status(); CHECK(stream_backend_ != nullptr); std::string msg = stream_backend_->GetMessage(); LOG(INFO) << "Received: \"" << msg << "\""; return msg; } bool Stream::SendMessage(const std::string& msg, bool newline) { CheckConnectionAndReconnect(); status_ = Status(); CHECK(stream_backend_ != nullptr); // Put two spaces after Sending so it is lined up with messages after // Received. LOG(INFO) << "Sending: \"" << msg << "\""; const std::string& msg_to_send = newline ? msg + '\n' : msg; return stream_backend_->SendMessage(msg_to_send); } Status Stream::LastStatus() const { if (!status_.Ok()) return status_; CHECK(stream_backend_ != nullptr); return stream_backend_->LastStatus(); } bool Stream::GetMessageWithCheck(const char* expected) { std::string msg_ok = GetMessage(); if (msg_ok != expected) { status_ = stream_backend_->LastStatus(); if (msg_ok.length() >= 11 && msg_ok.substr(0, 5) == "ERROR") { int error_code = std::atoi(msg_ok.substr(6, 3).c_str()); status_.SetServerError(error_code, msg_ok.substr(11)); } LOG(ERROR) << "Expected \"" << expected << "\" but received \"" << msg_ok << "\""; return false; } return true; } bool Stream::SendMessageWithCheck(const std::string& msg, bool newline, const char* expected) { status_ = Status(); bool success = SendMessage(msg, newline); if (success) { success = GetMessageWithCheck(expected); } return success; } void Stream::CheckConnectionAndReconnect() { if (Connected()) return; stream_backend_->Reconnect(); while (!Connected()) { std::this_thread::sleep_for( std::chrono::milliseconds(TIME_BETWEEN_RECONNECT_TRIES_MILLISECONDS)); stream_backend_->Reconnect(); } } } // namespace communication } // namespace c24 <|endoftext|>
<commit_before>#include "stdafx.h" #include "texturebutton.h" #include <QPushButton> #include <QImage> #include <QFileDialog> #include <QSettings> #include <QStandardPaths> #include <QPainter> #include <QFileInfo> #include <QMessageBox> #include "OgreTexture.h" #include "OgreImage.h" #include "OgreHlmsPbsDatablock.h" TextureButton::TextureButton(QPushButton* button, Ogre::PbsTextureTypes texType) : QObject(button) { Q_ASSERT(button); mButton = button; //mButton->setStyleSheet("Text-align:left"); mTextureType = texType; connect(button, &QPushButton::clicked, this, &TextureButton::buttonClicked); } void TextureButton::updateTexImage(Ogre::HlmsPbsDatablock* datablock, Ogre::PbsTextureTypes textureType) { mDatablock = datablock; Ogre::HlmsTextureManager::TextureLocation texLocation; texLocation.texture = datablock->getTexture(textureType); texLocation.xIdx = datablock->_getTextureIdx(textureType); texLocation.yIdx = 0; texLocation.divisor = 1; if (texLocation.texture.isNull()) { clear(); return; } //qDebug() << "Type:" << (int)textureType // << ", X index:" << texLocation.xIdx // << ", Pointer:" << texLocation.texture; Ogre::Image img; texLocation.texture->convertToImage(img, false, 0, texLocation.xIdx, 1); int originalWidth = img.getWidth(); int originalHeight = img.getHeight(); //img.resize(64, 64); QString textureName; const Ogre::String* aliasName = getHlmsTexManager()->findAliasName(texLocation); if (aliasName) { textureName = QString::fromStdString(*aliasName); } setInfoText(textureName, originalWidth, originalHeight); QImage qtImg = toQtImage(img); if (!qtImg.isNull()) { QPixmap pixmap = QPixmap::fromImage(qtImg); mButton->setIconSize(QSize(64, 64)); mButton->setIcon(QIcon(pixmap)); } else { // TODO: show unknown format mButton->setIcon(QIcon()); mButton->setIconSize(QSize(1, 1)); } } void TextureButton::buttonClicked() { QSettings settings("OgreV2ModelViewer", "OgreV2ModelViewer"); QString myDocument = QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation)[0]; QString defaultFolder = settings.value("textureLocation", myDocument).toString(); QString fileName = QFileDialog::getOpenFileName(mButton, "Load textures", defaultFolder, "Images (*.png *.jpg *.dds *.bmp *.tga *.hdr)"); if (fileName.isEmpty()) { return; } if (mDatablock) { Ogre::HlmsTextureManager::TextureLocation loc; bool ok = LoadImage(fileName, loc); if (ok) { mDatablock->setTexture(mTextureType, loc.xIdx, loc.texture); updateTexImage(mDatablock, mTextureType); settings.setValue("textureLocation", QFileInfo(fileName).absolutePath()); } else { QMessageBox::information(mButton, "Error", "Ogre3D cannot load this texture"); } } } void TextureButton::setInfoText(const QString& texName, int width, int height) { QString texInfo = QString("%1\n%2x%3") .arg(texName) .arg(width) .arg(height); mButton->setText(texInfo); } Ogre::HlmsTextureManager* TextureButton::getHlmsTexManager() { if (mHlmsTexManager == nullptr) mHlmsTexManager = Ogre::Root::getSingleton().getHlmsManager()->getTextureManager(); return mHlmsTexManager; } void TextureButton::clear() { mButton->setIcon(QIcon()); mButton->setIconSize(QSize(1, 1)); mButton->setText("No Texture"); } QImage::Format TextureButton::toQtImageFormat(Ogre::PixelFormat ogreFormat) { switch (ogreFormat) { case Ogre::PF_A8R8G8B8: return QImage::Format_ARGB32; case Ogre::PF_A8: return QImage::Format_Alpha8; case Ogre::PF_L8: return QImage::Format_Grayscale8; //case Ogre::PF_A8B8G8R8: return QImage::Format_Invalid; default: qDebug() << "Unknown tex format:" << ogreFormat; break; } return QImage::Format_Invalid; } QImage TextureButton::toQtImage(const Ogre::Image& img) { QImage::Format qtFormat = toQtImageFormat(img.getFormat()); if (qtFormat != QImage::Format_Invalid) { QImage qImg(img.getData(), img.getWidth(), img.getHeight(), qtFormat); return qImg; } switch(img.getFormat()) { case Ogre::PF_R8G8_SNORM: { QImage qtImg(img.getWidth(), img.getHeight(), QImage::Format_RGBA8888_Premultiplied); char* src = (char*)img.getData(); for (size_t x = 0; x < img.getWidth(); ++x) { for (size_t y = 0; y < img.getHeight(); ++y) { size_t src_byte_offset = x * y * 2; int r = src[src_byte_offset + 0] + 128; int g = src[src_byte_offset + 1] + 128; qtImg.setPixel((int)x, (int)y, qRgb(r, g, 255)); } } //qtImg.save("C:/Temp/normal.png"); return qtImg; break; } case Ogre::PF_A8B8G8R8: { QImage qtImg(img.getWidth(), img.getHeight(), QImage::Format_RGBA8888_Premultiplied); break; } default: break; } static QImage emptyImg(64, 64, QImage::Format_RGBA8888_Premultiplied); QPainter painter(&emptyImg); painter.fillRect(QRect(0, 0, 64, 64), Qt::white); painter.drawText(13, 30, "Preview"); painter.drawText(6, 42, "Unavailable"); return emptyImg; } bool TextureButton::LoadImage(const QString& texturePath, Ogre::HlmsTextureManager::TextureLocation& loc) { bool ok = false; std::ifstream ifs(texturePath.toStdWString(), std::ios::binary | std::ios::in); ON_SCOPE_EXIT(ifs.close()); if (!ifs.is_open()) { return false; } QString fileExt = QFileInfo(texturePath).suffix(); if (fileExt.isEmpty()) { return false; } std::string texName = texturePath.toStdString(); Ogre::DataStreamPtr dataStream(new Ogre::FileStreamDataStream(texName, &ifs, false)); try { Ogre::Image img; img.load(dataStream, fileExt.toStdString()); if (img.getWidth() == 0) { return false; } Ogre::HlmsTextureManager::TextureMapType mapType; switch (mTextureType) { case Ogre::PBSM_DIFFUSE: case Ogre::PBSM_EMISSIVE: mapType = Ogre::HlmsTextureManager::TEXTURE_TYPE_DIFFUSE; break; case Ogre::PBSM_METALLIC: case Ogre::PBSM_ROUGHNESS: mapType = Ogre::HlmsTextureManager::TEXTURE_TYPE_MONOCHROME; break; case Ogre::PBSM_NORMAL: mapType = Ogre::HlmsTextureManager::TEXTURE_TYPE_NORMALS; break; case Ogre::PBSM_REFLECTION: mapType = Ogre::HlmsTextureManager::TEXTURE_TYPE_ENV_MAP; break; default: Ogre::HlmsTextureManager::TEXTURE_TYPE_DETAIL; Ogre::HlmsTextureManager::TEXTURE_TYPE_DETAIL_NORMAL_MAP; Ogre::HlmsTextureManager::TEXTURE_TYPE_NON_COLOR_DATA; break; } loc = mHlmsTexManager->createOrRetrieveTexture(texName, texName, mapType, 0, &img); ok = true; } catch(Ogre::Exception& e) { qDebug() << e.what(); ok = false; } return ok; }<commit_msg>Fix a crash on loading textures<commit_after>#include "stdafx.h" #include "texturebutton.h" #include <QPushButton> #include <QImage> #include <QFileDialog> #include <QSettings> #include <QStandardPaths> #include <QPainter> #include <QFileInfo> #include <QMessageBox> #include "OgreTexture.h" #include "OgreImage.h" #include "OgreHlmsPbsDatablock.h" TextureButton::TextureButton(QPushButton* button, Ogre::PbsTextureTypes texType) : QObject(button) { Q_ASSERT(button); mButton = button; //mButton->setStyleSheet("Text-align:left"); mTextureType = texType; connect(button, &QPushButton::clicked, this, &TextureButton::buttonClicked); } void TextureButton::updateTexImage(Ogre::HlmsPbsDatablock* datablock, Ogre::PbsTextureTypes textureType) { mDatablock = datablock; Ogre::HlmsTextureManager::TextureLocation texLocation; texLocation.texture = datablock->getTexture(textureType); texLocation.xIdx = datablock->_getTextureIdx(textureType); texLocation.yIdx = 0; texLocation.divisor = 1; if (texLocation.texture.isNull()) { clear(); return; } //qDebug() << "Type:" << (int)textureType // << ", X index:" << texLocation.xIdx // << ", Pointer:" << texLocation.texture; Ogre::Image img; texLocation.texture->convertToImage(img, false, 0, texLocation.xIdx, 1); int originalWidth = img.getWidth(); int originalHeight = img.getHeight(); //img.resize(64, 64); QString textureName; const Ogre::String* aliasName = getHlmsTexManager()->findAliasName(texLocation); if (aliasName) { textureName = QString::fromStdString(*aliasName); } setInfoText(textureName, originalWidth, originalHeight); QImage qtImg = toQtImage(img); if (!qtImg.isNull()) { QPixmap pixmap = QPixmap::fromImage(qtImg); mButton->setIconSize(QSize(64, 64)); mButton->setIcon(QIcon(pixmap)); } else { // TODO: show unknown format mButton->setIcon(QIcon()); mButton->setIconSize(QSize(1, 1)); } } void TextureButton::buttonClicked() { QSettings settings("OgreV2ModelViewer", "OgreV2ModelViewer"); QString myDocument = QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation)[0]; QString defaultFolder = settings.value("textureLocation", myDocument).toString(); QString fileName = QFileDialog::getOpenFileName(mButton, "Load textures", defaultFolder, "Images (*.png *.jpg *.dds *.bmp *.tga *.hdr)"); if (fileName.isEmpty()) { return; } if (mDatablock) { Ogre::HlmsTextureManager::TextureLocation loc; bool ok = LoadImage(fileName, loc); if (ok) { mDatablock->setTexture(mTextureType, loc.xIdx, loc.texture); updateTexImage(mDatablock, mTextureType); settings.setValue("textureLocation", QFileInfo(fileName).absolutePath()); } else { QMessageBox::information(mButton, "Error", "Ogre3D cannot load this texture"); } } } void TextureButton::setInfoText(const QString& texName, int width, int height) { QString texInfo = QString("%1\n%2x%3") .arg(texName) .arg(width) .arg(height); mButton->setText(texInfo); } Ogre::HlmsTextureManager* TextureButton::getHlmsTexManager() { if (mHlmsTexManager == nullptr) mHlmsTexManager = Ogre::Root::getSingleton().getHlmsManager()->getTextureManager(); return mHlmsTexManager; } void TextureButton::clear() { mButton->setIcon(QIcon()); mButton->setIconSize(QSize(1, 1)); mButton->setText("No Texture"); } QImage::Format TextureButton::toQtImageFormat(Ogre::PixelFormat ogreFormat) { switch (ogreFormat) { case Ogre::PF_A8R8G8B8: return QImage::Format_ARGB32; case Ogre::PF_A8: return QImage::Format_Alpha8; case Ogre::PF_L8: return QImage::Format_Grayscale8; //case Ogre::PF_A8B8G8R8: return QImage::Format_Invalid; default: qDebug() << "Unknown tex format:" << ogreFormat; break; } return QImage::Format_Invalid; } QImage TextureButton::toQtImage(const Ogre::Image& img) { QImage::Format qtFormat = toQtImageFormat(img.getFormat()); if (qtFormat != QImage::Format_Invalid) { QImage qImg(img.getData(), img.getWidth(), img.getHeight(), qtFormat); return qImg; } switch(img.getFormat()) { case Ogre::PF_R8G8_SNORM: { QImage qtImg(img.getWidth(), img.getHeight(), QImage::Format_RGBA8888_Premultiplied); char* src = (char*)img.getData(); for (size_t x = 0; x < img.getWidth(); ++x) { for (size_t y = 0; y < img.getHeight(); ++y) { size_t src_byte_offset = x * y * 2; int r = src[src_byte_offset + 0] + 128; int g = src[src_byte_offset + 1] + 128; qtImg.setPixel((int)x, (int)y, qRgb(r, g, 255)); } } //qtImg.save("C:/Temp/normal.png"); return qtImg; break; } case Ogre::PF_A8B8G8R8: { QImage qtImg(img.getWidth(), img.getHeight(), QImage::Format_RGBA8888_Premultiplied); break; } default: break; } static QImage emptyImg(64, 64, QImage::Format_RGBA8888_Premultiplied); QPainter painter(&emptyImg); painter.fillRect(QRect(0, 0, 64, 64), Qt::white); painter.drawText(13, 30, "Preview"); painter.drawText(6, 42, "Unavailable"); return emptyImg; } bool TextureButton::LoadImage(const QString& texturePath, Ogre::HlmsTextureManager::TextureLocation& loc) { bool ok = false; std::ifstream ifs(texturePath.toStdWString(), std::ios::binary | std::ios::in); ON_SCOPE_EXIT(ifs.close()); if (!ifs.is_open()) { return false; } QString fileExt = QFileInfo(texturePath).suffix(); if (fileExt.isEmpty()) { return false; } std::string texName = texturePath.toStdString(); Ogre::DataStreamPtr dataStream(new Ogre::FileStreamDataStream(texName, &ifs, false)); try { Ogre::Image img; img.load(dataStream, fileExt.toStdString()); if (img.getWidth() == 0) { return false; } Ogre::HlmsTextureManager::TextureMapType mapType; switch (mTextureType) { case Ogre::PBSM_DIFFUSE: case Ogre::PBSM_EMISSIVE: mapType = Ogre::HlmsTextureManager::TEXTURE_TYPE_DIFFUSE; break; case Ogre::PBSM_METALLIC: case Ogre::PBSM_ROUGHNESS: mapType = Ogre::HlmsTextureManager::TEXTURE_TYPE_MONOCHROME; break; case Ogre::PBSM_NORMAL: mapType = Ogre::HlmsTextureManager::TEXTURE_TYPE_NORMALS; break; case Ogre::PBSM_REFLECTION: mapType = Ogre::HlmsTextureManager::TEXTURE_TYPE_ENV_MAP; break; default: Ogre::HlmsTextureManager::TEXTURE_TYPE_DETAIL; Ogre::HlmsTextureManager::TEXTURE_TYPE_DETAIL_NORMAL_MAP; Ogre::HlmsTextureManager::TEXTURE_TYPE_NON_COLOR_DATA; break; } loc = getHlmsTexManager()->createOrRetrieveTexture(texName, texName, mapType, 0, &img); ok = true; } catch(Ogre::Exception& e) { qDebug() << e.what(); ok = false; } return ok; }<|endoftext|>
<commit_before>// Copyright (c) 2016 Mirants Lu. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "voyager/core/tcp_connection.h" #include <unistd.h> #include <errno.h> #include "voyager/core/dispatch.h" #include "voyager/core/eventloop.h" #include "voyager/util/logging.h" #include "voyager/util/slice.h" namespace voyager { TcpConnection::TcpConnection(const std::string& name, EventLoop* ev, int fd) : name_(name), eventloop_(CHECK_NOTNULL(ev)), socket_(fd), state_(kConnecting), dispatch_(new Dispatch(ev, fd)), high_water_mark_(64 * 1024 * 1024) { dispatch_->SetReadCallback( std::bind(&TcpConnection::HandleRead, this)); dispatch_->SetWriteCallback( std::bind(&TcpConnection::HandleWrite, this)); dispatch_->SetCloseCallback( std::bind(&TcpConnection::HandleClose, this)); dispatch_->SetErrorCallback( std::bind(&TcpConnection::HandleError, this)); socket_.SetNonBlockAndCloseOnExec(true); socket_.SetKeepAlive(true); socket_.SetTcpNoDelay(true); VOYAGER_LOG(DEBUG) << "TcpConnection::TcpConnection [" << name_ << "] at " << this << " fd=" << fd; } TcpConnection::~TcpConnection() { VOYAGER_LOG(DEBUG) << "TcpConnection::~TcpConnection [" << name_ << "] at " << this << " fd=" << dispatch_->Fd() << " ConnectState=" << StateToString(); } void TcpConnection::StartWorking() { eventloop_->AssertInMyLoop(); assert(state_ == kConnecting); state_ = kConnected; TcpConnectionPtr ptr(shared_from_this()); dispatch_->Tie(ptr); dispatch_->EnableRead(); eventloop_->AddConnection(ptr); if (connection_cb_) { connection_cb_(ptr); } } void TcpConnection::StartRead() { TcpConnectionPtr ptr(shared_from_this()); eventloop_->RunInLoop([ptr]() { if (!ptr->dispatch_->IsReading()) { ptr->dispatch_->EnableRead(); } }); } void TcpConnection::StopRead() { TcpConnectionPtr ptr(shared_from_this()); eventloop_->RunInLoop([ptr]() { if (ptr->dispatch_->IsReading()) { ptr->dispatch_->DisableRead(); } }); } void TcpConnection::ShutDown() { ConnectState expected = kConnected; if (state_.compare_exchange_weak(expected, kDisconnecting)) { TcpConnectionPtr ptr(shared_from_this()); eventloop_->RunInLoop([ptr]() { if (!ptr->dispatch_->IsWriting()) { ptr->socket_.ShutDownWrite(); } }); } } void TcpConnection::ForceClose() { ConnectState expected = kConnected; if (state_.compare_exchange_weak(expected, kDisconnecting) || state_ == kDisconnecting) { TcpConnectionPtr ptr(shared_from_this()); eventloop_->QueueInLoop([ptr]() { if (ptr->state_ == kConnected || ptr->state_ == kDisconnecting) { ptr->HandleClose(); } }); } } void TcpConnection::HandleRead() { eventloop_->AssertInMyLoop(); ssize_t n = readbuf_.ReadV(dispatch_->Fd()); if (n > 0) { if (message_cb_) { message_cb_(shared_from_this(), &readbuf_); } } else if (n == 0) { HandleClose(); } else { if (errno == EPIPE || errno == ECONNRESET) { HandleClose(); } if (errno != EWOULDBLOCK && errno != EAGAIN) { VOYAGER_LOG(ERROR) << "TcpConnection::HandleRead [" << name_ <<"] - readv: " << strerror(errno); } } } void TcpConnection::HandleWrite() { eventloop_->AssertInMyLoop(); if (dispatch_->IsWriting()) { ssize_t n = ::write(dispatch_->Fd(), writebuf_.Peek(), writebuf_.ReadableSize()); if (n >= 0) { writebuf_.Retrieve(static_cast<size_t>(n)); if (writebuf_.ReadableSize() == 0) { dispatch_->DisableWrite(); if (writecomplete_cb_) { writecomplete_cb_(shared_from_this()); } if (state_ == kDisconnecting) { HandleClose(); } } } else { if (errno == EPIPE || errno == ECONNRESET) { HandleClose(); } if (errno != EWOULDBLOCK && errno != EAGAIN) { VOYAGER_LOG(ERROR) << "TcpConnection::HandleWrite [" << name_ << "] - write: " << strerror(errno); } } } else { VOYAGER_LOG(INFO) << "TcpConnection::HandleWrite [" << name_ << "] - fd=" << dispatch_->Fd() << " is down, no more writing"; } } void TcpConnection::HandleClose() { eventloop_->AssertInMyLoop(); assert(state_ == kConnected || state_ == kDisconnecting); state_ = kDisconnected; dispatch_->DisableAll(); dispatch_->RemoveEvents(); eventloop_->RemoveCnnection(shared_from_this()); if (close_cb_) { close_cb_(shared_from_this()); } } void TcpConnection::HandleError() { Status st = socket_.CheckSocketError(); if (!st.ok()) { VOYAGER_LOG(ERROR) << "TcpConnection::HandleError [" << name_ << "] - " << st; } } void TcpConnection::SendMessage(std::string&& message) { if (state_ == kConnected) { if (eventloop_->IsInMyLoop()) { SendInLoop(message.data(), message.size()); } else { eventloop_->RunInLoop( std::bind(&TcpConnection::Send, shared_from_this(), std::move(message))); } } } void TcpConnection::SendMessage(const Slice& message) { if (state_ == kConnected) { if (eventloop_->IsInMyLoop()) { SendInLoop(message.data(), message.size()); } else { eventloop_->RunInLoop( std::bind(&TcpConnection::Send, shared_from_this(), message.ToString())); } } } void TcpConnection::SendMessage(Buffer* message) { CHECK_NOTNULL(message); if (state_ == kConnected) { if (eventloop_->IsInMyLoop()) { SendInLoop(message->Peek(), message->ReadableSize()); message->RetrieveAll(); } else { std::shared_ptr<std::string> s( new std::string(message->Peek(), message->ReadableSize())); message->RetrieveAll(); eventloop_->RunInLoop( std::bind(&TcpConnection::Send, shared_from_this(), message->RetrieveAllAsString())); } } } void TcpConnection::Send(const std::string& s) { SendInLoop(s.data(), s.size()); } void TcpConnection::SendInLoop(const void* data, size_t size) { eventloop_->AssertInMyLoop(); if (state_ == kDisconnected) { VOYAGER_LOG(WARN) << "TcpConnection::SendInLoop[" << name_ << "]" << "has disconnected, give up writing."; return; } ssize_t nwrote = 0; size_t remaining = size; bool fault = false; if (!dispatch_->IsWriting() && writebuf_.ReadableSize() == 0) { nwrote = ::write(dispatch_->Fd(), data, size); if (nwrote >= 0) { remaining = size - static_cast<size_t>(nwrote); if (remaining == 0 && writecomplete_cb_) { writecomplete_cb_(shared_from_this()); } } else { nwrote = 0; if (errno == EPIPE || errno == ECONNRESET) { HandleClose(); fault = true; } if (errno != EWOULDBLOCK && errno != EAGAIN) { VOYAGER_LOG(ERROR) << "TcpConnection::SendInLoop [" << name_ << "] - write: " << strerror(errno); } } } assert(remaining <= size); if (!fault && remaining > 0) { size_t old = writebuf_.ReadableSize(); if (high_water_mark_cb_ && old < high_water_mark_ && (old + remaining) >= high_water_mark_) { eventloop_->QueueInLoop( std::bind(high_water_mark_cb_, shared_from_this(), old + remaining)); } writebuf_.Append(static_cast<const char*>(data)+nwrote, remaining); if (!dispatch_->IsWriting()) { dispatch_->EnableWrite(); } } } std::string TcpConnection::StateToString() const { const char *type; switch (state_.load(std::memory_order_relaxed)) { case kDisconnected: type = "Disconnected"; break; case kDisconnecting: type = "Disconnecting"; break; case kConnected: type = "Connected"; break; case kConnecting: type = "Connecting"; break; default: type = "Unknown State"; break; } std::string result(type); return result; } } // namespace voyager <commit_msg>fix sendmessage bug<commit_after>// Copyright (c) 2016 Mirants Lu. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "voyager/core/tcp_connection.h" #include <unistd.h> #include <errno.h> #include "voyager/core/dispatch.h" #include "voyager/core/eventloop.h" #include "voyager/util/logging.h" #include "voyager/util/slice.h" namespace voyager { TcpConnection::TcpConnection(const std::string& name, EventLoop* ev, int fd) : name_(name), eventloop_(CHECK_NOTNULL(ev)), socket_(fd), state_(kConnecting), dispatch_(new Dispatch(ev, fd)), high_water_mark_(64 * 1024 * 1024) { dispatch_->SetReadCallback( std::bind(&TcpConnection::HandleRead, this)); dispatch_->SetWriteCallback( std::bind(&TcpConnection::HandleWrite, this)); dispatch_->SetCloseCallback( std::bind(&TcpConnection::HandleClose, this)); dispatch_->SetErrorCallback( std::bind(&TcpConnection::HandleError, this)); socket_.SetNonBlockAndCloseOnExec(true); socket_.SetKeepAlive(true); socket_.SetTcpNoDelay(true); VOYAGER_LOG(DEBUG) << "TcpConnection::TcpConnection [" << name_ << "] at " << this << " fd=" << fd; } TcpConnection::~TcpConnection() { VOYAGER_LOG(DEBUG) << "TcpConnection::~TcpConnection [" << name_ << "] at " << this << " fd=" << dispatch_->Fd() << " ConnectState=" << StateToString(); } void TcpConnection::StartWorking() { eventloop_->AssertInMyLoop(); assert(state_ == kConnecting); state_ = kConnected; TcpConnectionPtr ptr(shared_from_this()); dispatch_->Tie(ptr); dispatch_->EnableRead(); eventloop_->AddConnection(ptr); if (connection_cb_) { connection_cb_(ptr); } } void TcpConnection::StartRead() { TcpConnectionPtr ptr(shared_from_this()); eventloop_->RunInLoop([ptr]() { if (!ptr->dispatch_->IsReading()) { ptr->dispatch_->EnableRead(); } }); } void TcpConnection::StopRead() { TcpConnectionPtr ptr(shared_from_this()); eventloop_->RunInLoop([ptr]() { if (ptr->dispatch_->IsReading()) { ptr->dispatch_->DisableRead(); } }); } void TcpConnection::ShutDown() { ConnectState expected = kConnected; if (state_.compare_exchange_weak(expected, kDisconnecting)) { TcpConnectionPtr ptr(shared_from_this()); eventloop_->RunInLoop([ptr]() { if (!ptr->dispatch_->IsWriting()) { ptr->socket_.ShutDownWrite(); } }); } } void TcpConnection::ForceClose() { ConnectState expected = kConnected; if (state_.compare_exchange_weak(expected, kDisconnecting) || state_ == kDisconnecting) { TcpConnectionPtr ptr(shared_from_this()); eventloop_->QueueInLoop([ptr]() { if (ptr->state_ == kConnected || ptr->state_ == kDisconnecting) { ptr->HandleClose(); } }); } } void TcpConnection::HandleRead() { eventloop_->AssertInMyLoop(); ssize_t n = readbuf_.ReadV(dispatch_->Fd()); if (n > 0) { if (message_cb_) { message_cb_(shared_from_this(), &readbuf_); } } else if (n == 0) { HandleClose(); } else { if (errno == EPIPE || errno == ECONNRESET) { HandleClose(); } if (errno != EWOULDBLOCK && errno != EAGAIN) { VOYAGER_LOG(ERROR) << "TcpConnection::HandleRead [" << name_ <<"] - readv: " << strerror(errno); } } } void TcpConnection::HandleWrite() { eventloop_->AssertInMyLoop(); if (dispatch_->IsWriting()) { ssize_t n = ::write(dispatch_->Fd(), writebuf_.Peek(), writebuf_.ReadableSize()); if (n >= 0) { writebuf_.Retrieve(static_cast<size_t>(n)); if (writebuf_.ReadableSize() == 0) { dispatch_->DisableWrite(); if (writecomplete_cb_) { writecomplete_cb_(shared_from_this()); } if (state_ == kDisconnecting) { HandleClose(); } } } else { if (errno == EPIPE || errno == ECONNRESET) { HandleClose(); } if (errno != EWOULDBLOCK && errno != EAGAIN) { VOYAGER_LOG(ERROR) << "TcpConnection::HandleWrite [" << name_ << "] - write: " << strerror(errno); } } } else { VOYAGER_LOG(INFO) << "TcpConnection::HandleWrite [" << name_ << "] - fd=" << dispatch_->Fd() << " is down, no more writing"; } } void TcpConnection::HandleClose() { eventloop_->AssertInMyLoop(); assert(state_ == kConnected || state_ == kDisconnecting); state_ = kDisconnected; dispatch_->DisableAll(); dispatch_->RemoveEvents(); eventloop_->RemoveCnnection(shared_from_this()); if (close_cb_) { close_cb_(shared_from_this()); } } void TcpConnection::HandleError() { Status st = socket_.CheckSocketError(); if (!st.ok()) { VOYAGER_LOG(ERROR) << "TcpConnection::HandleError [" << name_ << "] - " << st; } } void TcpConnection::SendMessage(std::string&& message) { if (state_ == kConnected) { if (eventloop_->IsInMyLoop()) { SendInLoop(message.data(), message.size()); } else { eventloop_->RunInLoop( std::bind(&TcpConnection::Send, shared_from_this(), std::move(message))); } } } void TcpConnection::SendMessage(const Slice& message) { if (state_ == kConnected) { if (eventloop_->IsInMyLoop()) { SendInLoop(message.data(), message.size()); } else { eventloop_->RunInLoop( std::bind(&TcpConnection::Send, shared_from_this(), message.ToString())); } } } void TcpConnection::SendMessage(Buffer* message) { CHECK_NOTNULL(message); if (state_ == kConnected) { if (eventloop_->IsInMyLoop()) { SendInLoop(message->Peek(), message->ReadableSize()); message->RetrieveAll(); } else { eventloop_->RunInLoop( std::bind(&TcpConnection::Send, shared_from_this(), message->RetrieveAllAsString())); } } } void TcpConnection::Send(const std::string& s) { SendInLoop(s.data(), s.size()); } void TcpConnection::SendInLoop(const void* data, size_t size) { eventloop_->AssertInMyLoop(); if (state_ == kDisconnected) { VOYAGER_LOG(WARN) << "TcpConnection::SendInLoop[" << name_ << "]" << "has disconnected, give up writing."; return; } ssize_t nwrote = 0; size_t remaining = size; bool fault = false; if (!dispatch_->IsWriting() && writebuf_.ReadableSize() == 0) { nwrote = ::write(dispatch_->Fd(), data, size); if (nwrote >= 0) { remaining = size - static_cast<size_t>(nwrote); if (remaining == 0 && writecomplete_cb_) { writecomplete_cb_(shared_from_this()); } } else { nwrote = 0; if (errno == EPIPE || errno == ECONNRESET) { HandleClose(); fault = true; } if (errno != EWOULDBLOCK && errno != EAGAIN) { VOYAGER_LOG(ERROR) << "TcpConnection::SendInLoop [" << name_ << "] - write: " << strerror(errno); } } } assert(remaining <= size); if (!fault && remaining > 0) { size_t old = writebuf_.ReadableSize(); if (high_water_mark_cb_ && old < high_water_mark_ && (old + remaining) >= high_water_mark_) { eventloop_->QueueInLoop( std::bind(high_water_mark_cb_, shared_from_this(), old + remaining)); } writebuf_.Append(static_cast<const char*>(data)+nwrote, remaining); if (!dispatch_->IsWriting()) { dispatch_->EnableWrite(); } } } std::string TcpConnection::StateToString() const { const char *type; switch (state_.load(std::memory_order_relaxed)) { case kDisconnected: type = "Disconnected"; break; case kDisconnecting: type = "Disconnecting"; break; case kConnected: type = "Connected"; break; case kConnecting: type = "Connecting"; break; default: type = "Unknown State"; break; } std::string result(type); return result; } } // namespace voyager <|endoftext|>
<commit_before>#include <string> using std::string; class Sales_data{ public: Sales_data() = default; ~Sales_data() = default; Sales_data(int i):a(i){} Sales_data(const Sales_data &rhs):a(rhs.a){} Sales_data& operator=(const Sales_data&rhs){ a = rhs.a; return *this; } private: int a = 0; }; class Token{ public: Token():tok(INT),ival(0){} Token(const Token&t): tok(t.tok){copyUnion(t);} ~Token(){ if(tok == STR) sval.~string(); if(tok == SAL) item.~Sales_data(); } Token& operator=(Token &&); Token(Token&&); Token& operator=(const Token&); Token& operator=(const string&); Token& operator=(const int&); Token& operator=(const char&); Token& operator=(const Sales_data&); private: enum { INT, CHAR, STR, SAL} tok; union{ char cval; int ival; std::string sval; Sales_data item; }; void copyUnion(const Token&); //move edition void copyUnion(Token&&); }; void Token::copyUnion(Token&& t){ switch (t.tok) { case INT : ival = t.ival; break; case CHAR : cval = t.cval; break; case STR : std::move(t.sval);break; case SAL : std::move(t.item); break; } } void Token::copyUnion(const Token &t){ switch (t.tok) { case INT : ival = t.ival; break; case CHAR : cval = t.cval; break; case STR : new(&sval) string(t.sval);break; case SAL : new(&item) Sales_data(t.item); break; } } Token& Token::operator=(const Token&t){ if(tok == STR && t.tok != STR) sval.~string(); if(tok == SAL && t.tok != SAL) item.~Sales_data(); if(tok == STR && t.tok == STR) sval = t.sval; if(tok == SAL && t.tok == SAL) item = t.item; else copyUnion(t); tok = t.tok; return *this; } //move constructor Token& Token::operator=(Token&& t){ if(this != &t){ this->~Token(); copyUnion(t); tok = std::move(t.tok); } return *this; } Token::Token(Token &&t){ copyUnion(t); tok = std::move(t.tok); } Token& Token::operator=(const Sales_data& rhs){ if(tok == STR) sval.~string(); if(tok == SAL) item = rhs; else new(&item) Sales_data(rhs); tok = SAL; return *this; } Token& Token::operator=(const int& i){ if(tok == STR) sval.~string(); if(tok == SAL) item.~Sales_data(); ival = i; tok = INT; return *this; } int main(int argc, char const *argv[]) { Token s; Sales_data sal(5); s = sal; return 0; } <commit_msg>Add i<commit_after>#include <iostream> #include <string> using std::string; class Sales_data{ public: Sales_data() = default; ~Sales_data() = default; Sales_data(int i):a(i){} Sales_data(const Sales_data &rhs):a(rhs.a){} Sales_data& operator=(const Sales_data&rhs){ a = rhs.a; return *this; } private: int a = 0; }; class Token{ public: Token():tok(INT),ival(0){} Token(const Token&t): tok(t.tok){copyUnion(t);} ~Token(){ if(tok == STR) sval.~string(); if(tok == SAL) item.~Sales_data(); } Token& operator=(Token &&); Token(Token&&); Token& operator=(const Token&); Token& operator=(const string&); Token& operator=(const int&); Token& operator=(const char&); Token& operator=(const Sales_data&); private: enum { INT, CHAR, STR, SAL} tok; union{ char cval; int ival; std::string sval; Sales_data item; }; void copyUnion(const Token&); //move edition void copyUnion(Token&&); }; void Token::copyUnion(Token&& t){ switch (t.tok) { case INT : ival = t.ival; break; case CHAR : cval = t.cval; break; case STR : std::move(t.sval);break; case SAL : std::move(t.item); break; } } void Token::copyUnion(const Token &t){ switch (t.tok) { case INT : ival = t.ival; break; case CHAR : cval = t.cval; break; case STR : new(&sval) string(t.sval);break; case SAL : new(&item) Sales_data(t.item); break; } } Token& Token::operator=(const Token&t){ if(tok == STR && t.tok != STR) sval.~string(); if(tok == SAL && t.tok != SAL) item.~Sales_data(); if(tok == STR && t.tok == STR) sval = t.sval; if(tok == SAL && t.tok == SAL) item = t.item; else copyUnion(t); tok = t.tok; return *this; } //move constructor Token& Token::operator=(Token&& t){ if(this != &t){ this->~Token(); copyUnion(t); tok = std::move(t.tok); } return *this; } Token::Token(Token &&t){ copyUnion(t); tok = std::move(t.tok); } Token& Token::operator=(const Sales_data& rhs){ if(tok == STR) sval.~string(); if(tok == SAL) item = rhs; else new(&item) Sales_data(rhs); tok = SAL; return *this; } Token& Token::operator=(const int& i){ if(tok == STR) sval.~string(); if(tok == SAL) item.~Sales_data(); ival = i; tok = INT; return *this; } int main(int argc, char const *argv[]) { Token s; Sales_data sal(5); s = sal; int i = 5; std::cout << i << std::endl; return 0; } <|endoftext|>
<commit_before>/* * #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * 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. * #L% */ #include "libjoynrclustercontroller/mqtt/MosquittoConnection.h" #include "joynr/ClusterControllerSettings.h" #include "joynr/MessagingSettings.h" #include "joynr/exceptions/JoynrException.h" namespace joynr { MosquittoConnection::MosquittoConnection(const MessagingSettings& messagingSettings, const ClusterControllerSettings& ccSettings, const std::string& clientId) : mosquittopp(clientId.c_str(), false), messagingSettings(messagingSettings), host(messagingSettings.getBrokerUrl().getBrokerChannelsBaseUrl().getHost()), port(messagingSettings.getBrokerUrl().getBrokerChannelsBaseUrl().getPort()), channelId(), subscribeChannelMid(), topic(), additionalTopics(), additionalTopicsMutex(), isConnected(false), isRunning(false), isChannelIdRegistered(false), subscribedToChannelTopic(false), readyToSend(false), onMessageReceived(), onReadyToSendChangedMutex(), onReadyToSendChanged() { JOYNR_LOG_INFO(logger(), "Init mosquitto connection using MQTT client ID: {}", clientId); mosqpp::lib_init(); if (ccSettings.isMqttTlsEnabled()) { const std::string mqttCertificateAuthorityPemFilename = ccSettings.getMqttCertificateAuthorityPemFilename(); const std::string mqttCertificateAuthorityCertificateFolderPath = ccSettings.getMqttCertificateAuthorityCertificateFolderPath(); const char* mqttCertificateAuthorityPemFilename_cstr = nullptr; if (!mqttCertificateAuthorityPemFilename.empty()) { mqttCertificateAuthorityPemFilename_cstr = mqttCertificateAuthorityPemFilename.c_str(); } const char* mqttCertificateAuthorityCertificateFolderPath_cstr = nullptr; if (!mqttCertificateAuthorityCertificateFolderPath.empty()) { mqttCertificateAuthorityCertificateFolderPath_cstr = mqttCertificateAuthorityCertificateFolderPath.c_str(); } int rc = tls_set(mqttCertificateAuthorityPemFilename_cstr, mqttCertificateAuthorityCertificateFolderPath_cstr, ccSettings.getMqttCertificatePemFilename().c_str(), ccSettings.getMqttPrivateKeyPemFilename().c_str()); if (rc != MOSQ_ERR_SUCCESS) { const std::string errorString(getErrorString(rc)); mosqpp::lib_cleanup(); JOYNR_LOG_FATAL( logger(), "fatal failure to initialize TLS connection - {}", errorString); } } else { JOYNR_LOG_DEBUG(logger(), "MQTT connection not encrypted"); } } MosquittoConnection::~MosquittoConnection() { stop(); stopLoop(true); mosqpp::lib_cleanup(); } std::string MosquittoConnection::getErrorString(int rc) { // Do not use mosq::strerror() in case of MOSQ_ERR_ERRNO // since it calls the MT-unsafe API strerror() if (rc != MOSQ_ERR_ERRNO) { return std::string(mosqpp::strerror(rc)); } // MT-safe workaround char buf[256]; buf[0] = '\0'; int storedErrno = errno; // POSIX compliant check for conversion errors, // see 'man strerror_r' errno = 0; strerror_r(storedErrno, buf, sizeof(buf)); if (errno) { return "failed to convert errno"; } return std::string(buf); } void MosquittoConnection::on_disconnect(int rc) { const std::string errorString(getErrorString(rc)); setReadyToSend(false); if (!isConnected) { // In case we didn't connect yet JOYNR_LOG_ERROR( logger(), "Not yet connected to tcp://{}:{}, error: {}", host, port, errorString); return; } // There was indeed a disconnect...set connect to false isConnected = false; if (rc == MOSQ_ERR_SUCCESS) { JOYNR_LOG_INFO(logger(), "Disconnected from tcp://{}:{}", host, port); stopLoop(); } else { JOYNR_LOG_ERROR(logger(), "Unexpectedly disconnected from tcp://{}:{}, error: {}", host, port, errorString); reconnect(); } } void MosquittoConnection::on_log(int level, const char* str) { if (level == MOSQ_LOG_ERR) { JOYNR_LOG_ERROR(logger(), "Mosquitto Log: {}", str); } else if (level == MOSQ_LOG_WARNING) { JOYNR_LOG_WARN(logger(), "Mosquitto Log: {}", str); } else if (level == MOSQ_LOG_INFO) { JOYNR_LOG_INFO(logger(), "Mosquitto Log: {}", str); } else { // MOSQ_LOG_NOTICE || MOSQ_LOG_DEBUG || any other log level JOYNR_LOG_DEBUG(logger(), "Mosquitto Log: {}", str); } } std::uint16_t MosquittoConnection::getMqttQos() const { return mqttQos; } std::string MosquittoConnection::getMqttPrio() const { static const std::string value("low"); return value; } bool MosquittoConnection::isMqttRetain() const { return mqttRetain; } void MosquittoConnection::start() { JOYNR_LOG_TRACE( logger(), "Start called with isRunning: {}, isConnected: {}", isRunning, isConnected); JOYNR_LOG_INFO(logger(), "Try to connect to tcp://{}:{}", host, port); connect_async(host.c_str(), port, messagingSettings.getMqttKeepAliveTimeSeconds().count()); reconnect_delay_set(messagingSettings.getMqttReconnectDelayTimeSeconds().count(), messagingSettings.getMqttReconnectMaxDelayTimeSeconds().count(), messagingSettings.getMqttExponentialBackoffEnabled()); startLoop(); } void MosquittoConnection::startLoop() { int rc = loop_start(); if (rc == MOSQ_ERR_SUCCESS) { JOYNR_LOG_INFO(logger(), "Mosquitto loop started"); isRunning = true; } else { const std::string errorString(getErrorString(rc)); JOYNR_LOG_ERROR(logger(), "Mosquitto loop start failed: error: {} ({})", std::to_string(rc), errorString); } } void MosquittoConnection::stop() { if (isConnected) { int rc = disconnect(); if (rc == MOSQ_ERR_SUCCESS) { JOYNR_LOG_INFO(logger(), "Mosquitto Connection disconnected"); } else { const std::string errorString(getErrorString(rc)); JOYNR_LOG_ERROR(logger(), "Mosquitto disconnect failed: error: {} ({})", std::to_string(rc), errorString); stopLoop(true); } } else if (isRunning) { stopLoop(true); } setReadyToSend(false); } void MosquittoConnection::stopLoop(bool force) { int rc = loop_stop(force); if (rc == MOSQ_ERR_SUCCESS) { isRunning = false; JOYNR_LOG_INFO(logger(), "Mosquitto loop stopped"); } else { const std::string errorString(getErrorString(rc)); JOYNR_LOG_ERROR(logger(), "Mosquitto loop stop failed: error: {} ({})", std::to_string(rc), errorString); } } void MosquittoConnection::on_connect(int rc) { if (rc == MOSQ_ERR_SUCCESS) { JOYNR_LOG_INFO(logger(), "Mosquitto Connection established"); isConnected = true; createSubscriptions(); } else { const std::string errorString(getErrorString(rc)); JOYNR_LOG_ERROR( logger(), "Mosquitto Connection Error: {} ({})", std::to_string(rc), errorString); } } void MosquittoConnection::createSubscriptions() { while (!isChannelIdRegistered && isRunning) { std::this_thread::sleep_for(std::chrono::milliseconds(25)); } try { subscribeToTopicInternal(topic, true); std::lock_guard<std::recursive_mutex> lock(additionalTopicsMutex); for (const std::string& additionalTopic : additionalTopics) { subscribeToTopicInternal(additionalTopic); } } catch (const exceptions::JoynrRuntimeException& error) { JOYNR_LOG_ERROR(logger(), "Error subscribing to Mqtt topic, error: ", error.getMessage()); } } void MosquittoConnection::subscribeToTopicInternal(const std::string& topic, const bool isChannelTopic) { int* mid = nullptr; if (isChannelTopic) { mid = &subscribeChannelMid; } int rc = subscribe(mid, topic.c_str(), getMqttQos()); switch (rc) { case (MOSQ_ERR_SUCCESS): JOYNR_LOG_INFO(logger(), "Subscribed to {}", topic); break; case (MOSQ_ERR_NO_CONN): { const std::string errorString(getErrorString(rc)); JOYNR_LOG_DEBUG(logger(), "Subscription to {} failed: error: {} ({}). " "Subscription will be restored on connect.", topic, std::to_string(rc), errorString); break; } default: { // MOSQ_ERR_INVAL, MOSQ_ERR_NOMEM const std::string errorString(getErrorString(rc)); std::string errorMsg = "Subscription to " + topic + " failed: error: " + std::to_string(rc) + " (" + errorString + ")"; throw exceptions::JoynrRuntimeException(errorMsg); } } } void MosquittoConnection::subscribeToTopic(const std::string& topic) { if (!isChannelIdRegistered) { std::string errorMsg = "No channelId registered, cannot subscribe to topic " + topic; throw exceptions::JoynrRuntimeException(errorMsg); } { std::lock_guard<std::recursive_mutex> lock(additionalTopicsMutex); if (additionalTopics.find(topic) != additionalTopics.end()) { JOYNR_LOG_DEBUG(logger(), "Already subscribed to topic {}", topic); return; } subscribeToTopicInternal(topic); additionalTopics.insert(topic); } } void MosquittoConnection::unsubscribeFromTopic(const std::string& topic) { if (isChannelIdRegistered) { std::lock_guard<std::recursive_mutex> lock(additionalTopicsMutex); if (additionalTopics.find(topic) == additionalTopics.end()) { JOYNR_LOG_DEBUG(logger(), "Unsubscribe called for non existing topic {}", topic); return; } additionalTopics.erase(topic); if (isConnected && isRunning) { int rc = unsubscribe(nullptr, topic.c_str()); if (rc == MOSQ_ERR_SUCCESS) { JOYNR_LOG_INFO(logger(), "Unsubscribed from {}", topic); } else { // MOSQ_ERR_INVAL || MOSQ_ERR_NOMEM || MOSQ_ERR_NO_CONN const std::string errorString(getErrorString(rc)); JOYNR_LOG_ERROR(logger(), "Unsubscribe from {} failed: error: {} ({})", topic, std::to_string(rc), errorString); } } } } void MosquittoConnection::publishMessage( const std::string& topic, const int qosLevel, const std::function<void(const exceptions::JoynrRuntimeException&)>& onFailure, uint32_t payloadlen = 0, const void* payload = nullptr) { JOYNR_LOG_DEBUG(logger(), "Publish message of length {} to {}", payloadlen, topic); int mid; int rc = publish(&mid, topic.c_str(), payloadlen, payload, qosLevel, isMqttRetain()); if (!(rc == MOSQ_ERR_SUCCESS)) { const std::string errorString(getErrorString(rc)); if (rc == MOSQ_ERR_INVAL || rc == MOSQ_ERR_PAYLOAD_SIZE) { onFailure(exceptions::JoynrMessageNotSentException( "message could not be sent: mid (mqtt message id): " + std::to_string(mid) + ", error: " + std::to_string(rc) + " (" + errorString + ")")); return; } // MOSQ_ERR_NOMEM || MOSQ_ERR_NO_CONN || MOSQ_ERR_PROTOCOL ||| unexpected errors onFailure(exceptions::JoynrDelayMessageException( "error sending message: mid (mqtt message id): " + std::to_string(mid) + ", error: " + std::to_string(rc) + " (" + errorString + ")")); return; } JOYNR_LOG_TRACE(logger(), "published message with mqtt message id {}", std::to_string(mid)); } void MosquittoConnection::registerChannelId(const std::string& channelId) { this->channelId = channelId; topic = channelId + "/" + getMqttPrio() + "/" + "#"; isChannelIdRegistered = true; } void MosquittoConnection::registerReceiveCallback( std::function<void(smrf::ByteVector&&)> onMessageReceived) { this->onMessageReceived = onMessageReceived; } void MosquittoConnection::registerReadyToSendChangedCallback( std::function<void(bool)> onReadyToSendChanged) { std::lock_guard<std::mutex> lock(onReadyToSendChangedMutex); this->onReadyToSendChanged = std::move(onReadyToSendChanged); } bool MosquittoConnection::isSubscribedToChannelTopic() const { return subscribedToChannelTopic; } bool MosquittoConnection::isReadyToSend() const { return readyToSend; } void MosquittoConnection::on_subscribe(int mid, int qos_count, const int* granted_qos) { JOYNR_LOG_DEBUG(logger(), "Subscribed (mid: {} with granted QOS {}", mid, granted_qos[0]); for (int i = 1; i < qos_count; i++) { JOYNR_LOG_DEBUG(logger(), "QOS: {} granted {}", i, granted_qos[i]); } if (mid == subscribeChannelMid) { subscribedToChannelTopic = true; setReadyToSend(isConnected); } } void MosquittoConnection::on_message(const mosquitto_message* message) { if (!onMessageReceived) { JOYNR_LOG_ERROR(logger(), "Discarding received message, since onMessageReceived callback is empty."); return; } if (!message || message->payloadlen <= 0) { JOYNR_LOG_ERROR( logger(), "Discarding received message: invalid message or non-positive payload's length."); return; } std::uint8_t* data = static_cast<std::uint8_t*>(message->payload); // convert address of data into integral type std::uintptr_t integralAddress = reinterpret_cast<std::uintptr_t>(data); const bool overflow = joynr::util::isAdditionOnPointerSafe(integralAddress, message->payloadlen); if (overflow) { JOYNR_LOG_ERROR(logger(), "Discarding received message, since there is an overflow."); return; } smrf::ByteVector rawMessage(data, data + message->payloadlen); onMessageReceived(std::move(rawMessage)); } void MosquittoConnection::on_publish(int mid) { JOYNR_LOG_TRACE(logger(), "published message with mid {}", std::to_string(mid)); } void MosquittoConnection::setReadyToSend(bool readyToSend) { if (this->readyToSend != readyToSend) { this->readyToSend = readyToSend; std::lock_guard<std::mutex> lock(onReadyToSendChangedMutex); if (onReadyToSendChanged) { onReadyToSendChanged(readyToSend); } } } } // namespace joynr <commit_msg>[C++] MosquittoConnection::getErrorString() uses joynr::util::getErrorString()<commit_after>/* * #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * 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. * #L% */ #include "libjoynrclustercontroller/mqtt/MosquittoConnection.h" #include "joynr/ClusterControllerSettings.h" #include "joynr/MessagingSettings.h" #include "joynr/Util.h" #include "joynr/exceptions/JoynrException.h" namespace joynr { MosquittoConnection::MosquittoConnection(const MessagingSettings& messagingSettings, const ClusterControllerSettings& ccSettings, const std::string& clientId) : mosquittopp(clientId.c_str(), false), messagingSettings(messagingSettings), host(messagingSettings.getBrokerUrl().getBrokerChannelsBaseUrl().getHost()), port(messagingSettings.getBrokerUrl().getBrokerChannelsBaseUrl().getPort()), channelId(), subscribeChannelMid(), topic(), additionalTopics(), additionalTopicsMutex(), isConnected(false), isRunning(false), isChannelIdRegistered(false), subscribedToChannelTopic(false), readyToSend(false), onMessageReceived(), onReadyToSendChangedMutex(), onReadyToSendChanged() { JOYNR_LOG_INFO(logger(), "Init mosquitto connection using MQTT client ID: {}", clientId); mosqpp::lib_init(); if (ccSettings.isMqttTlsEnabled()) { const std::string mqttCertificateAuthorityPemFilename = ccSettings.getMqttCertificateAuthorityPemFilename(); const std::string mqttCertificateAuthorityCertificateFolderPath = ccSettings.getMqttCertificateAuthorityCertificateFolderPath(); const char* mqttCertificateAuthorityPemFilename_cstr = nullptr; if (!mqttCertificateAuthorityPemFilename.empty()) { mqttCertificateAuthorityPemFilename_cstr = mqttCertificateAuthorityPemFilename.c_str(); } const char* mqttCertificateAuthorityCertificateFolderPath_cstr = nullptr; if (!mqttCertificateAuthorityCertificateFolderPath.empty()) { mqttCertificateAuthorityCertificateFolderPath_cstr = mqttCertificateAuthorityCertificateFolderPath.c_str(); } int rc = tls_set(mqttCertificateAuthorityPemFilename_cstr, mqttCertificateAuthorityCertificateFolderPath_cstr, ccSettings.getMqttCertificatePemFilename().c_str(), ccSettings.getMqttPrivateKeyPemFilename().c_str()); if (rc != MOSQ_ERR_SUCCESS) { const std::string errorString(getErrorString(rc)); mosqpp::lib_cleanup(); JOYNR_LOG_FATAL( logger(), "fatal failure to initialize TLS connection - {}", errorString); } } else { JOYNR_LOG_DEBUG(logger(), "MQTT connection not encrypted"); } } MosquittoConnection::~MosquittoConnection() { stop(); stopLoop(true); mosqpp::lib_cleanup(); } std::string MosquittoConnection::getErrorString(int rc) { // Do not use mosq::strerror() in case of MOSQ_ERR_ERRNO // since it calls the MT-unsafe API strerror() if (rc != MOSQ_ERR_ERRNO) { return std::string(mosqpp::strerror(rc)); } const int storedErrno = errno; return joynr::util::getErrorString(storedErrno); } void MosquittoConnection::on_disconnect(int rc) { const std::string errorString(getErrorString(rc)); setReadyToSend(false); if (!isConnected) { // In case we didn't connect yet JOYNR_LOG_ERROR( logger(), "Not yet connected to tcp://{}:{}, error: {}", host, port, errorString); return; } // There was indeed a disconnect...set connect to false isConnected = false; if (rc == MOSQ_ERR_SUCCESS) { JOYNR_LOG_INFO(logger(), "Disconnected from tcp://{}:{}", host, port); stopLoop(); } else { JOYNR_LOG_ERROR(logger(), "Unexpectedly disconnected from tcp://{}:{}, error: {}", host, port, errorString); reconnect(); } } void MosquittoConnection::on_log(int level, const char* str) { if (level == MOSQ_LOG_ERR) { JOYNR_LOG_ERROR(logger(), "Mosquitto Log: {}", str); } else if (level == MOSQ_LOG_WARNING) { JOYNR_LOG_WARN(logger(), "Mosquitto Log: {}", str); } else if (level == MOSQ_LOG_INFO) { JOYNR_LOG_INFO(logger(), "Mosquitto Log: {}", str); } else { // MOSQ_LOG_NOTICE || MOSQ_LOG_DEBUG || any other log level JOYNR_LOG_DEBUG(logger(), "Mosquitto Log: {}", str); } } std::uint16_t MosquittoConnection::getMqttQos() const { return mqttQos; } std::string MosquittoConnection::getMqttPrio() const { static const std::string value("low"); return value; } bool MosquittoConnection::isMqttRetain() const { return mqttRetain; } void MosquittoConnection::start() { JOYNR_LOG_TRACE( logger(), "Start called with isRunning: {}, isConnected: {}", isRunning, isConnected); JOYNR_LOG_INFO(logger(), "Try to connect to tcp://{}:{}", host, port); connect_async(host.c_str(), port, messagingSettings.getMqttKeepAliveTimeSeconds().count()); reconnect_delay_set(messagingSettings.getMqttReconnectDelayTimeSeconds().count(), messagingSettings.getMqttReconnectMaxDelayTimeSeconds().count(), messagingSettings.getMqttExponentialBackoffEnabled()); startLoop(); } void MosquittoConnection::startLoop() { int rc = loop_start(); if (rc == MOSQ_ERR_SUCCESS) { JOYNR_LOG_INFO(logger(), "Mosquitto loop started"); isRunning = true; } else { const std::string errorString(getErrorString(rc)); JOYNR_LOG_ERROR(logger(), "Mosquitto loop start failed: error: {} ({})", std::to_string(rc), errorString); } } void MosquittoConnection::stop() { if (isConnected) { int rc = disconnect(); if (rc == MOSQ_ERR_SUCCESS) { JOYNR_LOG_INFO(logger(), "Mosquitto Connection disconnected"); } else { const std::string errorString(getErrorString(rc)); JOYNR_LOG_ERROR(logger(), "Mosquitto disconnect failed: error: {} ({})", std::to_string(rc), errorString); stopLoop(true); } } else if (isRunning) { stopLoop(true); } setReadyToSend(false); } void MosquittoConnection::stopLoop(bool force) { int rc = loop_stop(force); if (rc == MOSQ_ERR_SUCCESS) { isRunning = false; JOYNR_LOG_INFO(logger(), "Mosquitto loop stopped"); } else { const std::string errorString(getErrorString(rc)); JOYNR_LOG_ERROR(logger(), "Mosquitto loop stop failed: error: {} ({})", std::to_string(rc), errorString); } } void MosquittoConnection::on_connect(int rc) { if (rc == MOSQ_ERR_SUCCESS) { JOYNR_LOG_INFO(logger(), "Mosquitto Connection established"); isConnected = true; createSubscriptions(); } else { const std::string errorString(getErrorString(rc)); JOYNR_LOG_ERROR( logger(), "Mosquitto Connection Error: {} ({})", std::to_string(rc), errorString); } } void MosquittoConnection::createSubscriptions() { while (!isChannelIdRegistered && isRunning) { std::this_thread::sleep_for(std::chrono::milliseconds(25)); } try { subscribeToTopicInternal(topic, true); std::lock_guard<std::recursive_mutex> lock(additionalTopicsMutex); for (const std::string& additionalTopic : additionalTopics) { subscribeToTopicInternal(additionalTopic); } } catch (const exceptions::JoynrRuntimeException& error) { JOYNR_LOG_ERROR(logger(), "Error subscribing to Mqtt topic, error: ", error.getMessage()); } } void MosquittoConnection::subscribeToTopicInternal(const std::string& topic, const bool isChannelTopic) { int* mid = nullptr; if (isChannelTopic) { mid = &subscribeChannelMid; } int rc = subscribe(mid, topic.c_str(), getMqttQos()); switch (rc) { case (MOSQ_ERR_SUCCESS): JOYNR_LOG_INFO(logger(), "Subscribed to {}", topic); break; case (MOSQ_ERR_NO_CONN): { const std::string errorString(getErrorString(rc)); JOYNR_LOG_DEBUG(logger(), "Subscription to {} failed: error: {} ({}). " "Subscription will be restored on connect.", topic, std::to_string(rc), errorString); break; } default: { // MOSQ_ERR_INVAL, MOSQ_ERR_NOMEM const std::string errorString(getErrorString(rc)); std::string errorMsg = "Subscription to " + topic + " failed: error: " + std::to_string(rc) + " (" + errorString + ")"; throw exceptions::JoynrRuntimeException(errorMsg); } } } void MosquittoConnection::subscribeToTopic(const std::string& topic) { if (!isChannelIdRegistered) { std::string errorMsg = "No channelId registered, cannot subscribe to topic " + topic; throw exceptions::JoynrRuntimeException(errorMsg); } { std::lock_guard<std::recursive_mutex> lock(additionalTopicsMutex); if (additionalTopics.find(topic) != additionalTopics.end()) { JOYNR_LOG_DEBUG(logger(), "Already subscribed to topic {}", topic); return; } subscribeToTopicInternal(topic); additionalTopics.insert(topic); } } void MosquittoConnection::unsubscribeFromTopic(const std::string& topic) { if (isChannelIdRegistered) { std::lock_guard<std::recursive_mutex> lock(additionalTopicsMutex); if (additionalTopics.find(topic) == additionalTopics.end()) { JOYNR_LOG_DEBUG(logger(), "Unsubscribe called for non existing topic {}", topic); return; } additionalTopics.erase(topic); if (isConnected && isRunning) { int rc = unsubscribe(nullptr, topic.c_str()); if (rc == MOSQ_ERR_SUCCESS) { JOYNR_LOG_INFO(logger(), "Unsubscribed from {}", topic); } else { // MOSQ_ERR_INVAL || MOSQ_ERR_NOMEM || MOSQ_ERR_NO_CONN const std::string errorString(getErrorString(rc)); JOYNR_LOG_ERROR(logger(), "Unsubscribe from {} failed: error: {} ({})", topic, std::to_string(rc), errorString); } } } } void MosquittoConnection::publishMessage( const std::string& topic, const int qosLevel, const std::function<void(const exceptions::JoynrRuntimeException&)>& onFailure, uint32_t payloadlen = 0, const void* payload = nullptr) { JOYNR_LOG_DEBUG(logger(), "Publish message of length {} to {}", payloadlen, topic); int mid; int rc = publish(&mid, topic.c_str(), payloadlen, payload, qosLevel, isMqttRetain()); if (!(rc == MOSQ_ERR_SUCCESS)) { const std::string errorString(getErrorString(rc)); if (rc == MOSQ_ERR_INVAL || rc == MOSQ_ERR_PAYLOAD_SIZE) { onFailure(exceptions::JoynrMessageNotSentException( "message could not be sent: mid (mqtt message id): " + std::to_string(mid) + ", error: " + std::to_string(rc) + " (" + errorString + ")")); return; } // MOSQ_ERR_NOMEM || MOSQ_ERR_NO_CONN || MOSQ_ERR_PROTOCOL ||| unexpected errors onFailure(exceptions::JoynrDelayMessageException( "error sending message: mid (mqtt message id): " + std::to_string(mid) + ", error: " + std::to_string(rc) + " (" + errorString + ")")); return; } JOYNR_LOG_TRACE(logger(), "published message with mqtt message id {}", std::to_string(mid)); } void MosquittoConnection::registerChannelId(const std::string& channelId) { this->channelId = channelId; topic = channelId + "/" + getMqttPrio() + "/" + "#"; isChannelIdRegistered = true; } void MosquittoConnection::registerReceiveCallback( std::function<void(smrf::ByteVector&&)> onMessageReceived) { this->onMessageReceived = onMessageReceived; } void MosquittoConnection::registerReadyToSendChangedCallback( std::function<void(bool)> onReadyToSendChanged) { std::lock_guard<std::mutex> lock(onReadyToSendChangedMutex); this->onReadyToSendChanged = std::move(onReadyToSendChanged); } bool MosquittoConnection::isSubscribedToChannelTopic() const { return subscribedToChannelTopic; } bool MosquittoConnection::isReadyToSend() const { return readyToSend; } void MosquittoConnection::on_subscribe(int mid, int qos_count, const int* granted_qos) { JOYNR_LOG_DEBUG(logger(), "Subscribed (mid: {} with granted QOS {}", mid, granted_qos[0]); for (int i = 1; i < qos_count; i++) { JOYNR_LOG_DEBUG(logger(), "QOS: {} granted {}", i, granted_qos[i]); } if (mid == subscribeChannelMid) { subscribedToChannelTopic = true; setReadyToSend(isConnected); } } void MosquittoConnection::on_message(const mosquitto_message* message) { if (!onMessageReceived) { JOYNR_LOG_ERROR(logger(), "Discarding received message, since onMessageReceived callback is empty."); return; } if (!message || message->payloadlen <= 0) { JOYNR_LOG_ERROR( logger(), "Discarding received message: invalid message or non-positive payload's length."); return; } std::uint8_t* data = static_cast<std::uint8_t*>(message->payload); // convert address of data into integral type std::uintptr_t integralAddress = reinterpret_cast<std::uintptr_t>(data); const bool overflow = joynr::util::isAdditionOnPointerSafe(integralAddress, message->payloadlen); if (overflow) { JOYNR_LOG_ERROR(logger(), "Discarding received message, since there is an overflow."); return; } smrf::ByteVector rawMessage(data, data + message->payloadlen); onMessageReceived(std::move(rawMessage)); } void MosquittoConnection::on_publish(int mid) { JOYNR_LOG_TRACE(logger(), "published message with mid {}", std::to_string(mid)); } void MosquittoConnection::setReadyToSend(bool readyToSend) { if (this->readyToSend != readyToSend) { this->readyToSend = readyToSend; std::lock_guard<std::mutex> lock(onReadyToSendChangedMutex); if (onReadyToSendChanged) { onReadyToSendChanged(readyToSend); } } } } // namespace joynr <|endoftext|>
<commit_before> // INCLUDES #include <unistd.h> #include <string.h> #include <netdb.h> #include <fcntl.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/param.h> #include <sys/select.h> #include "atTCPNetworkInterface.h++" atTCPNetworkInterface::atTCPNetworkInterface(char * address, short port) { char hostname[MAXHOSTNAMELEN]; struct hostent * host; // Open the socket if ( (socket_value = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) notify(AT_ERROR, "Unable to open socket for communication.\n"); // Get information about this host and initialize the read name field gethostname(hostname, sizeof(hostname)); host = gethostbyname(hostname); read_name.sin_family = AF_INET; memcpy(&read_name.sin_addr.s_addr, host->h_addr_list[0], host->h_length); read_name.sin_port = htons(port); // Get information about remote host and initialize the write name field host = gethostbyname(address); write_name.sin_family = AF_INET; memcpy(&write_name.sin_addr.s_addr, host->h_addr_list[0], host->h_length); write_name.sin_port = htons(port); // Initialize remaining instance variables num_client_sockets = 0; } atTCPNetworkInterface::atTCPNetworkInterface(short port) { char hostname[MAXHOSTNAMELEN]; struct hostent * host; // Open the socket if ( (socket_value = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) notify(AT_ERROR, "Unable to open socket for communication.\n"); // Get information about this host and initialize the read name field gethostname(hostname, sizeof(hostname)); host = gethostbyname(hostname); read_name.sin_family = AF_INET; memcpy(&read_name.sin_addr.s_addr, host->h_addr_list[0], host->h_length); read_name.sin_port = htons(port); // Get information about remote host and initialize the write name field write_name.sin_family = AF_INET; memcpy(&write_name.sin_addr.s_addr, host->h_addr_list[0], host->h_length); write_name.sin_port = htons(port); // Initialize remaining instance variables num_client_sockets = 0; } atTCPNetworkInterface::~atTCPNetworkInterface() { // Close the socket close(socket_value); } void atTCPNetworkInterface::allowConnections(int backlog) { // Bind to the port if (bind(socket_value, (struct sockaddr *) &read_name, sizeof(read_name)) < 0) { notify(AT_ERROR, "Unable to bind to the port.\n"); } // Notify our willingness to accept connections and give a backlog limit listen(socket_value, backlog); } int atTCPNetworkInterface::acceptConnection() { int newSocket; struct sockaddr_in connectingName; socklen_t connectingNameLength; char * address; // Try to accept a connection connectingNameLength = sizeof(connectingName); newSocket = accept(socket_value, (struct sockaddr *) &connectingName, &connectingNameLength); // If we had an error and it wasn't that we would block on a non-blocking // socket (a blocking socket shouldn't generate an EWOULDBLOCK error), then // notify the user; otherwise, store the socket and return an ID to the user if (newSocket == -1) { if (errno != EWOULDBLOCK) notify(AT_ERROR, "Could not accept a connection.\n"); return -1; } else { client_sockets[num_client_sockets] = newSocket; address = (char *) connectingName.sin_addr.s_addr; sprintf(client_addrs[num_client_sockets].address, "%d.%d.%d.%d", address[0], address[1], address[2], address[3]); client_addrs[num_client_sockets].port = connectingName.sin_port; num_client_sockets++; return num_client_sockets - 1; } } void atTCPNetworkInterface::enableBlockingOnClient(int clientID) { int statusFlags; // Get the current flags on the socket (return an error if we fail) if ( (statusFlags = fcntl(client_sockets[clientID], F_GETFL)) < 0 ) notify(AT_ERROR, "Unable to get status of socket.\n"); else { // Now set the flags back while removing the non-blocking bit if (fcntl(client_sockets[clientID], F_SETFL, statusFlags & (~FNONBLOCK)) < 0) { // Report an error if we fail notify(AT_ERROR, "Unable to disable blocking on socket.\n"); } } } void atTCPNetworkInterface::disableBlockingOnClient(int clientID) { int statusFlags; // Get the current flags on the socket (return an error if we fail) if ( (statusFlags = fcntl(client_sockets[clientID], F_GETFL)) < 0 ) notify(AT_ERROR, "Unable to get status of socket.\n"); else { // Now set the flags back while adding the non-blocking bit (report any // errors we get if we fail) if (fcntl(client_sockets[clientID], F_SETFL, statusFlags | FNONBLOCK) < 0) notify(AT_ERROR, "Unable to disable blocking on socket.\n"); } } ClientAddr atTCPNetworkInterface::getClientInfo(int clientID) { // Return the information for this client ID return client_addrs[clientID]; } int atTCPNetworkInterface::makeConnection() { int statusFlags; int keepTrying; struct sockaddr_in connectingName; fd_set readFds; fd_set writeFds; struct timeval timeout; // Get flags on our current socket (so we can put them on new sockets if // needed) if ( (statusFlags = fcntl(socket_value, F_GETFL)) < 0 ) notify(AT_ERROR, "Unable to get status of socket.\n"); keepTrying = 1; while (keepTrying == 1) { // Try to connect connectingName = write_name; if (connect(socket_value, (struct sockaddr *) &connectingName, sizeof(connectingName)) != -1) { // We connected so signal the loop to end keepTrying = 0; } else { // If we are not in blocking mode, tell the loop to stop (we give up); // Otherwise, tell the user the info that we failed this time and // re-open the socket if ( (fcntl(socket_value, F_GETFL) & FNONBLOCK) != 0 ) { // We are non-blocking so we could be failing to connect // or we could just need more time (EINPROGRESS) so // use select() to give it some time and then check again if (errno == EINPROGRESS) { notify(AT_INFO, "Waiting for connection.\n"); FD_ZERO(&readFds); FD_SET(socket_value, &readFds); FD_ZERO(&writeFds); FD_SET(socket_value, &writeFds); timeout.tv_sec = 1; timeout.tv_usec = 0; if (select(socket_value+1, &readFds, &writeFds, NULL, &timeout) < 1) { // We didn't connect so close the socket keepTrying = 0; close(socket_value); socket_value = -1; } else { // We actually did connect! keepTrying = 0; } } else { // Just give up notify(AT_INFO, "Failed to connect to server. Giving up.\n"); keepTrying = 0; close(socket_value); socket_value = -1; } } else { // We didn't connect so close the socket close(socket_value); socket_value = -1; notify(AT_INFO, "Failed to connect to server. Trying again.\n"); // Re-open the socket if ( (socket_value = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) notify(AT_ERROR, "Unable to open socket for communication.\n"); // Put flags from previous socket on this new socket if (fcntl(socket_value, F_SETFL, statusFlags) < 0) notify(AT_ERROR, "Unable to disable blocking on socket.\n"); } } } // Tell the user whether or not we succeeded to connect if (socket_value == -1) return -1; else return 0; } int atTCPNetworkInterface::read(u_char * buffer, u_long len) { struct sockaddr_in fromAddress; socklen_t fromAddressLength; int packetLength; // Get a packet fromAddressLength = sizeof(fromAddress); packetLength = recvfrom(socket_value, buffer, len, MSG_WAITALL, (struct sockaddr *) &fromAddress, &fromAddressLength); // Tell user how many bytes we read (-1 means an error) return packetLength; } int atTCPNetworkInterface::read(int clientID, u_char * buffer, u_long len) { struct sockaddr_in fromAddress; socklen_t fromAddressLength; int packetLength; // Get a packet fromAddressLength = sizeof(fromAddress); packetLength = recvfrom(client_sockets[clientID], buffer, len, MSG_WAITALL, (struct sockaddr *) &fromAddress, &fromAddressLength); // Tell user how many bytes we read (-1 means an error) return packetLength; } int atTCPNetworkInterface::write(u_char * buffer, u_long len) { int lengthWritten; // Write the packet lengthWritten = sendto(socket_value, buffer, len, 0, (struct sockaddr *) &write_name, write_name_length); // Tell user how many bytes we wrote (-1 if error) return lengthWritten; } int atTCPNetworkInterface::write(int clientID, u_char * buffer, u_long len) { int lengthWritten; // Write the packet lengthWritten = sendto(client_sockets[clientID], buffer, len, 0, (struct sockaddr *) &write_name, write_name_length); // Tell user how many bytes we wrote (-1 if error) return lengthWritten; } <commit_msg><commit_after> // INCLUDES #include <unistd.h> #include <string.h> #include <netdb.h> #include <fcntl.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/param.h> #include <sys/select.h> #include "atTCPNetworkInterface.h++" atTCPNetworkInterface::atTCPNetworkInterface(char * address, short port) { char hostname[MAXHOSTNAMELEN]; struct hostent * host; // Open the socket if ( (socket_value = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) notify(AT_ERROR, "Unable to open socket for communication.\n"); // Get information about this host and initialize the read name field gethostname(hostname, sizeof(hostname)); host = gethostbyname(hostname); read_name.sin_family = AF_INET; memcpy(&read_name.sin_addr.s_addr, host->h_addr_list[0], host->h_length); read_name.sin_port = htons(port); // Get information about remote host and initialize the write name field host = gethostbyname(address); write_name.sin_family = AF_INET; memcpy(&write_name.sin_addr.s_addr, host->h_addr_list[0], host->h_length); write_name.sin_port = htons(port); // Initialize remaining instance variables num_client_sockets = 0; } atTCPNetworkInterface::atTCPNetworkInterface(short port) { char hostname[MAXHOSTNAMELEN]; struct hostent * host; // Open the socket if ( (socket_value = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) notify(AT_ERROR, "Unable to open socket for communication.\n"); // Get information about this host and initialize the read name field gethostname(hostname, sizeof(hostname)); host = gethostbyname(hostname); read_name.sin_family = AF_INET; memcpy(&read_name.sin_addr.s_addr, host->h_addr_list[0], host->h_length); read_name.sin_port = htons(port); // Get information about remote host and initialize the write name field write_name.sin_family = AF_INET; memcpy(&write_name.sin_addr.s_addr, host->h_addr_list[0], host->h_length); write_name.sin_port = htons(port); // Initialize remaining instance variables num_client_sockets = 0; } atTCPNetworkInterface::~atTCPNetworkInterface() { // Close the socket if (socket_value != -1) close(socket_value); } void atTCPNetworkInterface::allowConnections(int backlog) { // Bind to the port if (bind(socket_value, (struct sockaddr *) &read_name, sizeof(read_name)) < 0) { notify(AT_ERROR, "Unable to bind to the port.\n"); } // Notify our willingness to accept connections and give a backlog limit listen(socket_value, backlog); } int atTCPNetworkInterface::acceptConnection() { int newSocket; struct sockaddr_in connectingName; socklen_t connectingNameLength; char * address; // Try to accept a connection connectingNameLength = sizeof(connectingName); newSocket = accept(socket_value, (struct sockaddr *) &connectingName, &connectingNameLength); // If we had an error and it wasn't that we would block on a non-blocking // socket (a blocking socket shouldn't generate an EWOULDBLOCK error), then // notify the user; otherwise, store the socket and return an ID to the user if (newSocket == -1) { if (errno != EWOULDBLOCK) notify(AT_ERROR, "Could not accept a connection.\n"); return -1; } else { client_sockets[num_client_sockets] = newSocket; address = (char *) &connectingName.sin_addr.s_addr; sprintf(client_addrs[num_client_sockets].address, "%hhu.%hhu.%hhu.%hhu", address[0], address[1], address[2], address[3]); client_addrs[num_client_sockets].port = connectingName.sin_port; num_client_sockets++; return num_client_sockets - 1; } } void atTCPNetworkInterface::enableBlockingOnClient(int clientID) { int statusFlags; // Get the current flags on the socket (return an error if we fail) if ( (statusFlags = fcntl(client_sockets[clientID], F_GETFL)) < 0 ) notify(AT_ERROR, "Unable to get status of socket.\n"); else { // Now set the flags back while removing the non-blocking bit if (fcntl(client_sockets[clientID], F_SETFL, statusFlags & (~FNONBLOCK)) < 0) { // Report an error if we fail notify(AT_ERROR, "Unable to disable blocking on socket.\n"); } } } void atTCPNetworkInterface::disableBlockingOnClient(int clientID) { int statusFlags; // Get the current flags on the socket (return an error if we fail) if ( (statusFlags = fcntl(client_sockets[clientID], F_GETFL)) < 0 ) notify(AT_ERROR, "Unable to get status of socket.\n"); else { // Now set the flags back while adding the non-blocking bit (report any // errors we get if we fail) if (fcntl(client_sockets[clientID], F_SETFL, statusFlags | FNONBLOCK) < 0) notify(AT_ERROR, "Unable to disable blocking on socket.\n"); } } ClientAddr atTCPNetworkInterface::getClientInfo(int clientID) { // Return the information for this client ID return client_addrs[clientID]; } int atTCPNetworkInterface::makeConnection() { int statusFlags; int keepTrying; struct sockaddr_in connectingName; fd_set readFds; fd_set writeFds; struct timeval timeout; int errorCode; socklen_t errorLength; // Get flags on our current socket (so we can put them on new sockets if // needed) if ( (statusFlags = fcntl(socket_value, F_GETFL)) < 0 ) notify(AT_ERROR, "Unable to get status of socket.\n"); keepTrying = 1; while (keepTrying == 1) { // Try to connect connectingName = write_name; if (connect(socket_value, (struct sockaddr *) &connectingName, sizeof(connectingName)) != -1) { // We connected so signal the loop to end keepTrying = 0; } else { // If we are not in blocking mode, tell the loop to stop (we give up); // Otherwise, tell the user the info that we failed this time and // re-open the socket if ( (fcntl(socket_value, F_GETFL) & FNONBLOCK) != 0 ) { // We are non-blocking so we could be failing to connect // or we could just need more time (EINPROGRESS) so // use select() to give it some time and then check again if (errno == EINPROGRESS) { notify(AT_INFO, "Waiting for connection.\n"); FD_ZERO(&readFds); FD_SET(socket_value, &readFds); FD_ZERO(&writeFds); FD_SET(socket_value, &writeFds); timeout.tv_sec = 1; timeout.tv_usec = 0; if (select(socket_value+1, &readFds, &writeFds, NULL, &timeout) < 1) { // We didn't connect so close the socket notify(AT_INFO, "Failed to connect to server. Giving up.\n"); keepTrying = 0; close(socket_value); socket_value = -1; } else { // Check for error on the socket to see if we connected // successfully or not errorLength = sizeof(int); getsockopt(socket_value, SOL_SOCKET, SO_ERROR, &errorCode, &errorLength); // Check the error status if (errorCode == 0) { // We actually did connect! notify(AT_INFO, "Connected!\n"); keepTrying = 0; } else { // Failed to connect, so give up notify(AT_INFO, "Failed to connect to server. Giving up.\n"); keepTrying = 0; close(socket_value); socket_value = -1; } } } else { // Just give up notify(AT_INFO, "Failed to connect to server. Giving up.\n"); keepTrying = 0; close(socket_value); socket_value = -1; } } else { // We didn't connect so close the socket close(socket_value); socket_value = -1; notify(AT_INFO, "Failed to connect to server. Trying again.\n"); // Re-open the socket if ( (socket_value = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) notify(AT_ERROR, "Unable to open socket for communication.\n"); // Put flags from previous socket on this new socket if (fcntl(socket_value, F_SETFL, statusFlags) < 0) notify(AT_ERROR, "Unable to disable blocking on socket.\n"); } } } // Tell the user whether or not we succeeded to connect if (socket_value == -1) return -1; else return 0; } int atTCPNetworkInterface::read(u_char * buffer, u_long len) { struct sockaddr_in fromAddress; socklen_t fromAddressLength; int packetLength; // Get a packet fromAddressLength = sizeof(fromAddress); packetLength = recvfrom(socket_value, buffer, len, MSG_WAITALL, (struct sockaddr *) &fromAddress, &fromAddressLength); // Tell user how many bytes we read (-1 means an error) return packetLength; } int atTCPNetworkInterface::read(int clientID, u_char * buffer, u_long len) { struct sockaddr_in fromAddress; socklen_t fromAddressLength; int packetLength; // Get a packet fromAddressLength = sizeof(fromAddress); packetLength = recvfrom(client_sockets[clientID], buffer, len, MSG_WAITALL, (struct sockaddr *) &fromAddress, &fromAddressLength); // Tell user how many bytes we read (-1 means an error) return packetLength; } int atTCPNetworkInterface::write(u_char * buffer, u_long len) { int lengthWritten; // Write the packet lengthWritten = sendto(socket_value, buffer, len, 0, (struct sockaddr *) &write_name, write_name_length); // Tell user how many bytes we wrote (-1 if error) return lengthWritten; } int atTCPNetworkInterface::write(int clientID, u_char * buffer, u_long len) { int lengthWritten; // Write the packet lengthWritten = sendto(client_sockets[clientID], buffer, len, 0, (struct sockaddr *) &write_name, write_name_length); // Tell user how many bytes we wrote (-1 if error) return lengthWritten; } <|endoftext|>