text
stringlengths
54
60.6k
<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/delegates/gpu/cl/selectors/special_selector.h" #include "absl/types/any.h" #include "tensorflow/lite/delegates/gpu/cl/cl_device.h" #include "tensorflow/lite/delegates/gpu/cl/kernels/special/depthwise_conv_plus_1x1_conv.h" #include "tensorflow/lite/delegates/gpu/cl/kernels/special/fc_fc_add.h" #include "tensorflow/lite/delegates/gpu/common/data_type.h" #include "tensorflow/lite/delegates/gpu/common/operations.h" #include "tensorflow/lite/delegates/gpu/common/shape.h" #include "tensorflow/lite/delegates/gpu/common/status.h" #include "tensorflow/lite/delegates/gpu/common/task/tensor_desc.h" #include "tensorflow/lite/delegates/gpu/common/tensor.h" namespace tflite { namespace gpu { namespace cl { namespace { absl::Status TryDepthwiseConvPlus1x1Conv( CalculationsPrecision precision, const GraphFloat32& graph, NodeId first_node_id, const std::map<ValueId, TensorDescriptor>& tensor_descriptors, std::set<NodeId>* consumed_nodes, GPUOperationsSubgraph* gpu_subgraph) { auto* dw_node = graph.GetNode(first_node_id); if (OperationTypeFromString(dw_node->operation.type) != OperationType::DEPTHWISE_CONVOLUTION) { return absl::NotFoundError("DepthwiseConvPlus1x1Conv not suitable."); } auto dw_inputs = graph.FindInputs(dw_node->id); if (dw_inputs.size() != 1) { return absl::NotFoundError("DepthwiseConvPlus1x1Conv not suitable."); } auto dw_outputs = graph.FindOutputs(dw_node->id); auto consumers = graph.FindConsumers(dw_outputs[0]->id); if (consumers.size() != 1) { return absl::NotFoundError("DepthwiseConvPlus1x1Conv not suitable."); } auto* conv_node = consumers[0]; if (consumed_nodes->find(conv_node->id) != consumed_nodes->end()) { return absl::NotFoundError("DepthwiseConvPlus1x1Conv not suitable."); } if (OperationTypeFromString(conv_node->operation.type) != OperationType::CONVOLUTION_2D) { return absl::NotFoundError("DepthwiseConvPlus1x1Conv not suitable."); } if (graph.FindInputs(conv_node->id).size() != 1) { return absl::NotFoundError("DepthwiseConvPlus1x1Conv not suitable."); } auto dw_attr = absl::any_cast<DepthwiseConvolution2DAttributes>( dw_node->operation.attributes); auto conv_attr = absl::any_cast<Convolution2DAttributes>(conv_node->operation.attributes); auto conv_outputs = graph.FindOutputs(conv_node->id); OperationDef op_def; op_def.precision = precision; auto it = tensor_descriptors.find(dw_inputs[0]->id); if (it != tensor_descriptors.end()) { op_def.src_tensors.push_back(it->second); } it = tensor_descriptors.find(conv_outputs[0]->id); if (it != tensor_descriptors.end()) { op_def.dst_tensors.push_back(it->second); } if (!IsDepthwiseConvPlus1x1ConvSupported(op_def, dw_attr, conv_attr)) { return absl::NotFoundError("DepthwiseConvPlus1x1Conv not suitable."); } std::unique_ptr<GPUOperation>* gpu_op = InitSingleOpSubgraph(dw_inputs, conv_outputs, gpu_subgraph); auto operation = CreateDepthwiseConvPlus1x1Conv(op_def, dw_attr, conv_attr); *gpu_op = absl::make_unique<GPUOperation>(std::move(operation)); consumed_nodes->insert(dw_node->id); consumed_nodes->insert(conv_node->id); return absl::OkStatus(); } // fully connected + fully connected + add absl::Status TryFCFCAdd( const GpuInfo& gpu_info, CalculationsPrecision precision, const GraphFloat32& graph, NodeId first_node_id, const std::map<ValueId, TensorDescriptor>& tensor_descriptors, std::set<NodeId>* consumed_nodes, GPUOperationsSubgraph* gpu_subgraph) { auto* fc0_node = graph.GetNode(first_node_id); if (OperationTypeFromString(fc0_node->operation.type) != OperationType::FULLY_CONNECTED) { return absl::NotFoundError("FCFCAdd not suitable."); } auto fc0_inputs = graph.FindInputs(fc0_node->id); if (fc0_inputs.size() != 1) { return absl::NotFoundError("FCFCAdd not suitable."); } auto fc0_output_id = graph.FindOutputs(fc0_node->id)[0]->id; auto consumers = graph.FindConsumers(fc0_output_id); if (consumers.size() != 1) { return absl::NotFoundError("FCFCAdd not suitable."); } auto* add_node = consumers[0]; if (consumed_nodes->find(add_node->id) != consumed_nodes->end()) { return absl::NotFoundError("FCFCAdd not suitable."); } if (OperationTypeFromString(add_node->operation.type) != OperationType::ADD) { return absl::NotFoundError("FCFCAdd not suitable."); } auto add_inputs = graph.FindInputs(add_node->id); if (add_inputs.size() != 2) { return absl::NotFoundError("FCFCAdd not suitable."); } auto fc1_output_id = add_inputs[0]->id + add_inputs[1]->id - fc0_output_id; auto* fc1_node = graph.FindProducer(fc1_output_id); if (OperationTypeFromString(fc1_node->operation.type) != OperationType::FULLY_CONNECTED) { return absl::NotFoundError("FCFCAdd not suitable."); } if (consumed_nodes->find(fc1_node->id) != consumed_nodes->end()) { return absl::NotFoundError("FCFCAdd not suitable."); } auto fc1_inputs = graph.FindInputs(fc1_node->id); if (fc1_inputs.size() != 1) { return absl::NotFoundError("FCFCAdd not suitable."); } auto fc0_attr = absl::any_cast<FullyConnectedAttributes>(fc0_node->operation.attributes); auto fc1_attr = absl::any_cast<FullyConnectedAttributes>(fc1_node->operation.attributes); if (fc0_attr.weights.shape.o != fc1_attr.weights.shape.o) { return absl::NotFoundError("FCFCAdd not suitable."); } auto add_outputs = graph.FindOutputs(add_node->id); OperationDef op_def; op_def.precision = precision; auto it = tensor_descriptors.find(fc0_inputs[0]->id); if (it != tensor_descriptors.end()) { op_def.src_tensors.push_back(it->second); } it = tensor_descriptors.find(fc1_inputs[0]->id); if (it != tensor_descriptors.end()) { op_def.src_tensors.push_back(it->second); } it = tensor_descriptors.find(add_outputs[0]->id); if (it != tensor_descriptors.end()) { op_def.dst_tensors.push_back(it->second); } for (int i = 0; i < fc1_inputs.size(); ++i) { fc0_inputs.push_back(fc1_inputs[i]); } std::unique_ptr<GPUOperation>* gpu_op = InitSingleOpSubgraph(fc0_inputs, add_outputs, gpu_subgraph); FCFCAdd fc = CreateFCFCAdd(gpu_info, op_def, fc0_attr, fc1_attr); *gpu_op = absl::make_unique<FCFCAdd>(std::move(fc)); consumed_nodes->insert(fc0_node->id); consumed_nodes->insert(fc1_node->id); consumed_nodes->insert(add_node->id); return absl::OkStatus(); } } // namespace absl::Status GPUSubgraphFromGraph( const GpuInfo& gpu_info, CalculationsPrecision precision, const GraphFloat32& graph, NodeId first_node_id, const std::map<ValueId, TensorDescriptor>& tensor_descriptors, std::set<NodeId>* consumed_nodes, GPUOperationsSubgraph* gpu_subgraph, std::string* name) { if ((gpu_info.IsAdreno() || gpu_info.IsNvidia()) && TryDepthwiseConvPlus1x1Conv(precision, graph, first_node_id, tensor_descriptors, consumed_nodes, gpu_subgraph) .ok()) { *name = "depthwise_conv_plus_1x1_conv"; return absl::OkStatus(); } if ((gpu_info.IsIntel() || gpu_info.IsNvidia()) && TryFCFCAdd(gpu_info, precision, graph, first_node_id, tensor_descriptors, consumed_nodes, gpu_subgraph) .ok()) { *name = "fully_connected_x2_and_add"; return absl::OkStatus(); } return absl::NotFoundError("No special combination."); } } // namespace cl } // namespace gpu } // namespace tflite <commit_msg>Fix potential nullptr dereferences.<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/delegates/gpu/cl/selectors/special_selector.h" #include "absl/types/any.h" #include "tensorflow/lite/delegates/gpu/cl/cl_device.h" #include "tensorflow/lite/delegates/gpu/cl/kernels/special/depthwise_conv_plus_1x1_conv.h" #include "tensorflow/lite/delegates/gpu/cl/kernels/special/fc_fc_add.h" #include "tensorflow/lite/delegates/gpu/common/data_type.h" #include "tensorflow/lite/delegates/gpu/common/operations.h" #include "tensorflow/lite/delegates/gpu/common/shape.h" #include "tensorflow/lite/delegates/gpu/common/status.h" #include "tensorflow/lite/delegates/gpu/common/task/tensor_desc.h" #include "tensorflow/lite/delegates/gpu/common/tensor.h" namespace tflite { namespace gpu { namespace cl { namespace { absl::Status TryDepthwiseConvPlus1x1Conv( CalculationsPrecision precision, const GraphFloat32& graph, NodeId first_node_id, const std::map<ValueId, TensorDescriptor>& tensor_descriptors, std::set<NodeId>* consumed_nodes, GPUOperationsSubgraph* gpu_subgraph) { auto* dw_node = graph.GetNode(first_node_id); if (dw_node == nullptr) { return absl::NotFoundError("DepthwiseConvPlus1x1Conv not suitable."); } if (OperationTypeFromString(dw_node->operation.type) != OperationType::DEPTHWISE_CONVOLUTION) { return absl::NotFoundError("DepthwiseConvPlus1x1Conv not suitable."); } auto dw_inputs = graph.FindInputs(dw_node->id); if (dw_inputs.size() != 1) { return absl::NotFoundError("DepthwiseConvPlus1x1Conv not suitable."); } auto dw_outputs = graph.FindOutputs(dw_node->id); auto consumers = graph.FindConsumers(dw_outputs[0]->id); if (consumers.size() != 1) { return absl::NotFoundError("DepthwiseConvPlus1x1Conv not suitable."); } auto* conv_node = consumers[0]; if (conv_node == nullptr) { return absl::NotFoundError("DepthwiseConvPlus1x1Conv not suitable."); } if (consumed_nodes->find(conv_node->id) != consumed_nodes->end()) { return absl::NotFoundError("DepthwiseConvPlus1x1Conv not suitable."); } if (OperationTypeFromString(conv_node->operation.type) != OperationType::CONVOLUTION_2D) { return absl::NotFoundError("DepthwiseConvPlus1x1Conv not suitable."); } if (graph.FindInputs(conv_node->id).size() != 1) { return absl::NotFoundError("DepthwiseConvPlus1x1Conv not suitable."); } auto dw_attr = absl::any_cast<DepthwiseConvolution2DAttributes>( dw_node->operation.attributes); auto conv_attr = absl::any_cast<Convolution2DAttributes>(conv_node->operation.attributes); auto conv_outputs = graph.FindOutputs(conv_node->id); OperationDef op_def; op_def.precision = precision; auto it = tensor_descriptors.find(dw_inputs[0]->id); if (it != tensor_descriptors.end()) { op_def.src_tensors.push_back(it->second); } it = tensor_descriptors.find(conv_outputs[0]->id); if (it != tensor_descriptors.end()) { op_def.dst_tensors.push_back(it->second); } if (!IsDepthwiseConvPlus1x1ConvSupported(op_def, dw_attr, conv_attr)) { return absl::NotFoundError("DepthwiseConvPlus1x1Conv not suitable."); } std::unique_ptr<GPUOperation>* gpu_op = InitSingleOpSubgraph(dw_inputs, conv_outputs, gpu_subgraph); auto operation = CreateDepthwiseConvPlus1x1Conv(op_def, dw_attr, conv_attr); *gpu_op = absl::make_unique<GPUOperation>(std::move(operation)); consumed_nodes->insert(dw_node->id); consumed_nodes->insert(conv_node->id); return absl::OkStatus(); } // fully connected + fully connected + add absl::Status TryFCFCAdd( const GpuInfo& gpu_info, CalculationsPrecision precision, const GraphFloat32& graph, NodeId first_node_id, const std::map<ValueId, TensorDescriptor>& tensor_descriptors, std::set<NodeId>* consumed_nodes, GPUOperationsSubgraph* gpu_subgraph) { auto* fc0_node = graph.GetNode(first_node_id); if (fc0_node == nullptr) { return absl::NotFoundError("FCFCAdd not suitable."); } if (OperationTypeFromString(fc0_node->operation.type) != OperationType::FULLY_CONNECTED) { return absl::NotFoundError("FCFCAdd not suitable."); } auto fc0_inputs = graph.FindInputs(fc0_node->id); if (fc0_inputs.size() != 1) { return absl::NotFoundError("FCFCAdd not suitable."); } auto fc0_output_id = graph.FindOutputs(fc0_node->id)[0]->id; auto consumers = graph.FindConsumers(fc0_output_id); if (consumers.size() != 1) { return absl::NotFoundError("FCFCAdd not suitable."); } auto* add_node = consumers[0]; if (add_node == nullptr) { return absl::NotFoundError("FCFCAdd not suitable."); } if (consumed_nodes->find(add_node->id) != consumed_nodes->end()) { return absl::NotFoundError("FCFCAdd not suitable."); } if (OperationTypeFromString(add_node->operation.type) != OperationType::ADD) { return absl::NotFoundError("FCFCAdd not suitable."); } auto add_inputs = graph.FindInputs(add_node->id); if (add_inputs.size() != 2) { return absl::NotFoundError("FCFCAdd not suitable."); } auto fc1_output_id = add_inputs[0]->id + add_inputs[1]->id - fc0_output_id; auto* fc1_node = graph.FindProducer(fc1_output_id); if (fc1_node == nullptr) { return absl::NotFoundError("FCFCAdd not suitable."); } if (OperationTypeFromString(fc1_node->operation.type) != OperationType::FULLY_CONNECTED) { return absl::NotFoundError("FCFCAdd not suitable."); } if (consumed_nodes->find(fc1_node->id) != consumed_nodes->end()) { return absl::NotFoundError("FCFCAdd not suitable."); } auto fc1_inputs = graph.FindInputs(fc1_node->id); if (fc1_inputs.size() != 1) { return absl::NotFoundError("FCFCAdd not suitable."); } auto fc0_attr = absl::any_cast<FullyConnectedAttributes>(fc0_node->operation.attributes); auto fc1_attr = absl::any_cast<FullyConnectedAttributes>(fc1_node->operation.attributes); if (fc0_attr.weights.shape.o != fc1_attr.weights.shape.o) { return absl::NotFoundError("FCFCAdd not suitable."); } auto add_outputs = graph.FindOutputs(add_node->id); OperationDef op_def; op_def.precision = precision; auto it = tensor_descriptors.find(fc0_inputs[0]->id); if (it != tensor_descriptors.end()) { op_def.src_tensors.push_back(it->second); } it = tensor_descriptors.find(fc1_inputs[0]->id); if (it != tensor_descriptors.end()) { op_def.src_tensors.push_back(it->second); } it = tensor_descriptors.find(add_outputs[0]->id); if (it != tensor_descriptors.end()) { op_def.dst_tensors.push_back(it->second); } for (int i = 0; i < fc1_inputs.size(); ++i) { fc0_inputs.push_back(fc1_inputs[i]); } std::unique_ptr<GPUOperation>* gpu_op = InitSingleOpSubgraph(fc0_inputs, add_outputs, gpu_subgraph); FCFCAdd fc = CreateFCFCAdd(gpu_info, op_def, fc0_attr, fc1_attr); *gpu_op = absl::make_unique<FCFCAdd>(std::move(fc)); consumed_nodes->insert(fc0_node->id); consumed_nodes->insert(fc1_node->id); consumed_nodes->insert(add_node->id); return absl::OkStatus(); } } // namespace absl::Status GPUSubgraphFromGraph( const GpuInfo& gpu_info, CalculationsPrecision precision, const GraphFloat32& graph, NodeId first_node_id, const std::map<ValueId, TensorDescriptor>& tensor_descriptors, std::set<NodeId>* consumed_nodes, GPUOperationsSubgraph* gpu_subgraph, std::string* name) { if ((gpu_info.IsAdreno() || gpu_info.IsNvidia()) && TryDepthwiseConvPlus1x1Conv(precision, graph, first_node_id, tensor_descriptors, consumed_nodes, gpu_subgraph) .ok()) { *name = "depthwise_conv_plus_1x1_conv"; return absl::OkStatus(); } if ((gpu_info.IsIntel() || gpu_info.IsNvidia()) && TryFCFCAdd(gpu_info, precision, graph, first_node_id, tensor_descriptors, consumed_nodes, gpu_subgraph) .ok()) { *name = "fully_connected_x2_and_add"; return absl::OkStatus(); } return absl::NotFoundError("No special combination."); } } // namespace cl } // namespace gpu } // namespace tflite <|endoftext|>
<commit_before>/** * @file device_properties.hxx * @author Muhammad Osama ([email protected]) * @brief * @version 0.1 * @date 2020-10-05 * * @copyright Copyright (c) 2020 * */ #pragma once #include <iostream> #include <gunrock/cuda/device.hxx> namespace gunrock { namespace cuda { typedef cudaDeviceProp device_properties_t; typedef int architecture_t; /** * @namespace properties * C++ based CUDA device properties. */ namespace properties { void print(device_properties_t& prop) { device_id_t ordinal; cudaGetDevice(&ordinal); size_t freeMem, totalMem; error::error_t status = cudaMemGetInfo(&freeMem, &totalMem); error::throw_if_exception(status); double memBandwidth = (prop.memoryClockRate * 1000.0) * (prop.memoryBusWidth / 8 * 2) / 1.0e9; std::cout << prop.name << " : " << prop.clockRate / 1000.0 << " Mhz " << "(Ordinal " << ordinal << ")" << std::endl; std::cout << "FreeMem: " << (int)(freeMem / (1 << 20)) << " MB " << "TotalMem: " << (int)(totalMem / (1 << 20)) << " MB " << ((int)8 * sizeof(int*)) << "-bit pointers." << std::endl; std::cout << prop.multiProcessorCount << " SMs enabled, Compute Capability sm_" << prop.major << prop.minor << std::endl; std::cout << "Mem Clock: " << prop.memoryClockRate / 1000.0 << " Mhz x " << prop.memoryBusWidth << " bits (" << memBandwidth << " GB/s)" << std::endl; std::cout << "ECC " << (prop.ECCEnabled ? "Enabled" : "Disabled") << std::endl; } inline constexpr unsigned shared_memory_banks() { return 1 << 5; // 32 memory banks per SM } inline constexpr unsigned shared_memory_bank_stride() { return 1 << 2; // 4 byte words } inline constexpr unsigned maximum_threads_per_warp() { return 1 << 5; // 32 threads per warp } } // namespace properties } // namespace cuda } // namespace gunrock<commit_msg>Include error.hxx for print()<commit_after>/** * @file device_properties.hxx * @author Muhammad Osama ([email protected]) * @brief * @version 0.1 * @date 2020-10-05 * * @copyright Copyright (c) 2020 * */ #pragma once #include <iostream> #include <gunrock/cuda/device.hxx> #include <gunrock/error.hxx> namespace gunrock { namespace cuda { typedef cudaDeviceProp device_properties_t; typedef int architecture_t; /** * @namespace properties * C++ based CUDA device properties. */ namespace properties { void print(device_properties_t& prop) { device_id_t ordinal; cudaGetDevice(&ordinal); size_t freeMem, totalMem; error::error_t status = cudaMemGetInfo(&freeMem, &totalMem); error::throw_if_exception(status); double memBandwidth = (prop.memoryClockRate * 1000.0) * (prop.memoryBusWidth / 8 * 2) / 1.0e9; std::cout << prop.name << " : " << prop.clockRate / 1000.0 << " Mhz " << "(Ordinal " << ordinal << ")" << std::endl; std::cout << "FreeMem: " << (int)(freeMem / (1 << 20)) << " MB " << "TotalMem: " << (int)(totalMem / (1 << 20)) << " MB " << ((int)8 * sizeof(int*)) << "-bit pointers." << std::endl; std::cout << prop.multiProcessorCount << " SMs enabled, Compute Capability sm_" << prop.major << prop.minor << std::endl; std::cout << "Mem Clock: " << prop.memoryClockRate / 1000.0 << " Mhz x " << prop.memoryBusWidth << " bits (" << memBandwidth << " GB/s)" << std::endl; std::cout << "ECC " << (prop.ECCEnabled ? "Enabled" : "Disabled") << std::endl; } inline constexpr unsigned shared_memory_banks() { return 1 << 5; // 32 memory banks per SM } inline constexpr unsigned shared_memory_bank_stride() { return 1 << 2; // 4 byte words } inline constexpr unsigned maximum_threads_per_warp() { return 1 << 5; // 32 threads per warp } } // namespace properties } // namespace cuda } // namespace gunrock<|endoftext|>
<commit_before>#include "material/ggx.h" namespace AT_NAME { // NOTE // http://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf // https://agraphicsguy.wordpress.com/2015/11/01/sampling-microfacet-brdf/ // NOTE // http://qiita.com/_Pheema_/items/f1ffb2e38cc766e6e668 AT_DEVICE_MTRL_API real MicrofacetGGX::pdf( const aten::MaterialParameter* param, const aten::vec3& normal, const aten::vec3& wi, const aten::vec3& wo, real u, real v) { auto roughness = material::sampleTexture( param->roughnessMap, u, v, param->roughness); auto ret = pdf(roughness.r, normal, wi, wo); return ret; } AT_DEVICE_MTRL_API real MicrofacetGGX::pdf( const aten::vec3& normal, const aten::vec3& wi, const aten::vec3& wo, real u, real v) const { return pdf(&m_param, normal, wi, wo, u, v); } AT_DEVICE_MTRL_API aten::vec3 MicrofacetGGX::sampleDirection( const aten::MaterialParameter* param, const aten::vec3& normal, const aten::vec3& wi, real u, real v, aten::sampler* sampler) { auto roughness = material::sampleTexture( param->roughnessMap, u, v, param->roughness); aten::vec3 dir = sampleDirection(roughness.r, normal, wi, sampler); return std::move(dir); } AT_DEVICE_MTRL_API aten::vec3 MicrofacetGGX::sampleDirection( const aten::ray& ray, const aten::vec3& normal, real u, real v, aten::sampler* sampler) const { return std::move(sampleDirection(&m_param, normal, ray.dir, u, v, sampler)); } AT_DEVICE_MTRL_API aten::vec3 MicrofacetGGX::bsdf( const aten::MaterialParameter* param, const aten::vec3& normal, const aten::vec3& wi, const aten::vec3& wo, real u, real v) { auto roughness = material::sampleTexture( param->roughnessMap, u, v, param->roughness); auto albedo = param->baseColor; albedo *= material::sampleTexture(param->albedoMap, u, v, real(1)); real fresnel = 1; real ior = param->ior; aten::vec3 ret = bsdf(albedo, roughness.r, ior, fresnel, normal, wi, wo, u, v); return std::move(ret); } AT_DEVICE_MTRL_API aten::vec3 MicrofacetGGX::bsdf( const aten::MaterialParameter* param, const aten::vec3& normal, const aten::vec3& wi, const aten::vec3& wo, real u, real v, const aten::vec3& externalAlbedo) { auto roughness = material::sampleTexture( param->roughnessMap, u, v, param->roughness); auto albedo = param->baseColor; albedo *= externalAlbedo; real fresnel = 1; real ior = param->ior; aten::vec3 ret = bsdf(albedo, roughness.r, ior, fresnel, normal, wi, wo, u, v); return std::move(ret); } AT_DEVICE_MTRL_API aten::vec3 MicrofacetGGX::bsdf( const aten::vec3& normal, const aten::vec3& wi, const aten::vec3& wo, real u, real v) const { return std::move(bsdf(&m_param, normal, wi, wo, u, v)); } static AT_DEVICE_MTRL_API real sampleGGX_D( const aten::vec3& wh, // half const aten::vec3& n, // normal real roughness) { // NOTE // https://agraphicsguy.wordpress.com/2015/11/01/sampling-microfacet-brdf/ // NOTE // ((a^2 - 1) * cos^2 + 1)^2 // (-> a^2 = a2, cos^2 = cos2) // ((a2 - 1) * cos2 + 1)^2 // = (a2cos2 + 1 - cos2)^2 = (a2cos2 + sin2)^2 // (-> sin = sqrt(1 - cos2), sin2 = 1 - cos2) // = a4 * cos4 + 2 * a2 * cos2 * sin2 + sin4 // = cos4 * (a4 + 2 * a2 * (sin2 / cos2) + (sin4 / cos4)) // = cos4 * (a4 + 2 * a2 * tan2 + tan4) // = cos4 * (a2 + tan2) ^ 2 real a = roughness; auto a2 = a * a; auto costheta = aten::abs(dot(wh, n)); auto cos2 = costheta * costheta; auto denom = aten::pow((a2 - 1) * cos2 + 1, 2); auto D = denom > 0 ? a2 / (AT_MATH_PI * denom) : 0; return D; } AT_DEVICE_MTRL_API real MicrofacetGGX::computeGGXSmithG1(real roughness, const aten::vec3& v, const aten::vec3& n) { // NOTE // http://computergraphics.stackexchange.com/questions/2489/correct-form-of-the-ggx-geometry-term // http://gregory-igehy.hatenadiary.com/entry/2015/02/26/154142 real a = roughness; real costheta = aten::abs(dot(v, n)); real sintheta = aten::sqrt(1 - aten::clamp<real>(costheta * costheta, 0, 1)); real tan = costheta > 0 ? sintheta / costheta : 0; real denom = aten::sqrt(1 + a * a * tan * tan); real ret = 2 / (1 + denom); return ret; } AT_DEVICE_MTRL_API real MicrofacetGGX::pdf( real roughness, const aten::vec3& normal, const aten::vec3& wi, const aten::vec3& wo) { // NOTE // https://agraphicsguy.wordpress.com/2015/11/01/sampling-microfacet-brdf/ auto wh = normalize(-wi + wo); auto costheta = aten::abs(dot(wh, normal)); auto D = sampleGGX_D(wh, normal, roughness); auto denom = 4 * aten::abs(dot(wo, wh)); auto pdf = denom > 0 ? (D * costheta) / denom : 0; return pdf; } AT_DEVICE_MTRL_API aten::vec3 MicrofacetGGX::sampleDirection( real roughness, const aten::vec3& in, const aten::vec3& normal, aten::sampler* sampler) { auto r1 = sampler->nextSample(); auto r2 = sampler->nextSample(); auto a = roughness; auto theta = aten::atan(a * aten::sqrt(r1 / (1 - r1))); theta = ((theta >= 0) ? theta : (theta + 2 * AT_MATH_PI)); auto phi = 2 * AT_MATH_PI * r2; auto costheta = aten::cos(theta); auto sintheta = aten::sqrt(1 - costheta * costheta); auto cosphi = aten::cos(phi); auto sinphi = aten::sqrt(1 - cosphi * cosphi); // Ortho normal base. auto n = normal; auto t = aten::getOrthoVector(normal); auto b = normalize(cross(n, t)); auto w = t * sintheta * cosphi + b * sintheta * sinphi + n * costheta; w = normalize(w); auto dir = in - 2 * dot(in, w) * w; return std::move(dir); } AT_DEVICE_MTRL_API aten::vec3 MicrofacetGGX::bsdf( const aten::vec3& albedo, const real roughness, const real ior, real& fresnel, const aten::vec3& normal, const aten::vec3& wi, const aten::vec3& wo, real u, real v) { // C˂Ă鑤̂̋̕ܗ. real ni = real(1); // ^ real nt = ior; // ̓̋ܗ. aten::vec3 V = -wi; aten::vec3 L = wo; aten::vec3 N = normal; aten::vec3 H = normalize(L + V); // TODO // DesneyabsĂȂAAMD̂͂Ă.... auto NdotH = aten::abs(dot(N, H)); auto VdotH = aten::abs(dot(V, H)); auto NdotL = aten::abs(dot(N, L)); auto NdotV = aten::abs(dot(N, V)); // Compute D. real D = sampleGGX_D(H, N, roughness); // Compute G. real G(1); { auto G1_lh = computeGGXSmithG1(roughness, L, N); auto G1_vh = computeGGXSmithG1(roughness, V, N); G = G1_lh * G1_vh; } real F(1); { // http://d.hatena.ne.jp/hanecci/20130525/p3 // NOTE // Fschlick(v,h) R0 + (1 - R0)(1 - cos)^5 // R0 = ((n1 - n2) / (n1 + n2))^2 auto r0 = (ni - nt) / (ni + nt); r0 = r0 * r0; auto LdotH = aten::abs(dot(L, H)); F = r0 + (1 - r0) * aten::pow((1 - LdotH), 5); } auto denom = 4 * NdotL * NdotV; auto bsdf = denom > AT_MATH_EPSILON ? albedo * F * G * D / denom : aten::vec3(0); fresnel = F; return std::move(bsdf); } AT_DEVICE_MTRL_API void MicrofacetGGX::sample( MaterialSampling* result, const aten::MaterialParameter* param, const aten::vec3& normal, const aten::vec3& wi, const aten::vec3& orgnormal, aten::sampler* sampler, real u, real v, bool isLightPath/*= false*/) { auto roughness = material::sampleTexture( param->roughnessMap, u, v, param->roughness); result->dir = sampleDirection(roughness.r, wi, normal, sampler); result->pdf = pdf(roughness.r, normal, wi, result->dir); auto albedo = param->baseColor; albedo *= material::sampleTexture(param->albedoMap, u, v, real(1)); real fresnel = 1; real ior = param->ior; result->bsdf = bsdf(albedo, roughness.r, ior, fresnel, normal, wi, result->dir, u, v); result->fresnel = fresnel; } AT_DEVICE_MTRL_API void MicrofacetGGX::sample( MaterialSampling* result, const aten::MaterialParameter* param, const aten::vec3& normal, const aten::vec3& wi, const aten::vec3& orgnormal, aten::sampler* sampler, real u, real v, const aten::vec3& externalAlbedo, bool isLightPath/*= false*/) { auto roughness = material::sampleTexture( param->roughnessMap, u, v, param->roughness); result->dir = sampleDirection(roughness.r, wi, normal, sampler); result->pdf = pdf(roughness.r, normal, wi, result->dir); auto albedo = param->baseColor; albedo *= externalAlbedo; real fresnel = 1; real ior = param->ior; result->bsdf = bsdf(albedo, roughness.r, ior, fresnel, normal, wi, result->dir, u, v); result->fresnel = fresnel; } AT_DEVICE_MTRL_API MaterialSampling MicrofacetGGX::sample( const aten::ray& ray, const aten::vec3& normal, const aten::vec3& orgnormal, aten::sampler* sampler, real u, real v, bool isLightPath/*= false*/) const { MaterialSampling ret; sample( &ret, &m_param, normal, ray.dir, orgnormal, sampler, u, v, isLightPath); return std::move(ret); } bool MicrofacetGGX::edit(aten::IMaterialParamEditor* editor) { auto b0 = AT_EDIT_MATERIAL_PARAM(editor, m_param, roughness); auto b1 = AT_EDIT_MATERIAL_PARAM_RANGE(editor, m_param, ior, real(0.01), real(10)); auto b2 = AT_EDIT_MATERIAL_PARAM(editor, m_param, baseColor); AT_EDIT_MATERIAL_PARAM_TEXTURE(editor, m_param, albedoMap); AT_EDIT_MATERIAL_PARAM_TEXTURE(editor, m_param, normalMap); AT_EDIT_MATERIAL_PARAM_TEXTURE(editor, m_param, roughnessMap); return b0 || b1 || b2; } } <commit_msg>Add comments.<commit_after>#include "material/ggx.h" namespace AT_NAME { // NOTE // http://www.cs.cornell.edu/~srm/publications/EGSR07-btdf.pdf // https://agraphicsguy.wordpress.com/2015/11/01/sampling-microfacet-brdf/ // NOTE // http://qiita.com/_Pheema_/items/f1ffb2e38cc766e6e668 AT_DEVICE_MTRL_API real MicrofacetGGX::pdf( const aten::MaterialParameter* param, const aten::vec3& normal, const aten::vec3& wi, const aten::vec3& wo, real u, real v) { auto roughness = material::sampleTexture( param->roughnessMap, u, v, param->roughness); auto ret = pdf(roughness.r, normal, wi, wo); return ret; } AT_DEVICE_MTRL_API real MicrofacetGGX::pdf( const aten::vec3& normal, const aten::vec3& wi, const aten::vec3& wo, real u, real v) const { return pdf(&m_param, normal, wi, wo, u, v); } AT_DEVICE_MTRL_API aten::vec3 MicrofacetGGX::sampleDirection( const aten::MaterialParameter* param, const aten::vec3& normal, const aten::vec3& wi, real u, real v, aten::sampler* sampler) { auto roughness = material::sampleTexture( param->roughnessMap, u, v, param->roughness); aten::vec3 dir = sampleDirection(roughness.r, normal, wi, sampler); return std::move(dir); } AT_DEVICE_MTRL_API aten::vec3 MicrofacetGGX::sampleDirection( const aten::ray& ray, const aten::vec3& normal, real u, real v, aten::sampler* sampler) const { return std::move(sampleDirection(&m_param, normal, ray.dir, u, v, sampler)); } AT_DEVICE_MTRL_API aten::vec3 MicrofacetGGX::bsdf( const aten::MaterialParameter* param, const aten::vec3& normal, const aten::vec3& wi, const aten::vec3& wo, real u, real v) { auto roughness = material::sampleTexture( param->roughnessMap, u, v, param->roughness); auto albedo = param->baseColor; albedo *= material::sampleTexture(param->albedoMap, u, v, real(1)); real fresnel = 1; real ior = param->ior; aten::vec3 ret = bsdf(albedo, roughness.r, ior, fresnel, normal, wi, wo, u, v); return std::move(ret); } AT_DEVICE_MTRL_API aten::vec3 MicrofacetGGX::bsdf( const aten::MaterialParameter* param, const aten::vec3& normal, const aten::vec3& wi, const aten::vec3& wo, real u, real v, const aten::vec3& externalAlbedo) { auto roughness = material::sampleTexture( param->roughnessMap, u, v, param->roughness); auto albedo = param->baseColor; albedo *= externalAlbedo; real fresnel = 1; real ior = param->ior; aten::vec3 ret = bsdf(albedo, roughness.r, ior, fresnel, normal, wi, wo, u, v); return std::move(ret); } AT_DEVICE_MTRL_API aten::vec3 MicrofacetGGX::bsdf( const aten::vec3& normal, const aten::vec3& wi, const aten::vec3& wo, real u, real v) const { return std::move(bsdf(&m_param, normal, wi, wo, u, v)); } static AT_DEVICE_MTRL_API real sampleGGX_D( const aten::vec3& wh, // half const aten::vec3& n, // normal real roughness) { // NOTE // https://agraphicsguy.wordpress.com/2015/11/01/sampling-microfacet-brdf/ // NOTE // ((a^2 - 1) * cos^2 + 1)^2 // (-> a^2 = a2, cos^2 = cos2) // ((a2 - 1) * cos2 + 1)^2 // = (a2cos2 + 1 - cos2)^2 = (a2cos2 + sin2)^2 // (-> sin = sqrt(1 - cos2), sin2 = 1 - cos2) // = a4 * cos4 + 2 * a2 * cos2 * sin2 + sin4 // = cos4 * (a4 + 2 * a2 * (sin2 / cos2) + (sin4 / cos4)) // = cos4 * (a4 + 2 * a2 * tan2 + tan4) // = cos4 * (a2 + tan2)^2 // = (cos2 * (a2 + tan2))^2 // (tan = sin / cos -> tan2 = sin2 / cos2) // = (a2 * cos2 + sin2)^2 // = (a2 * cos2 + (1 - cos2))^2 // = ((a2 - 1) * cos2 + 1)^2 real a = roughness; auto a2 = a * a; auto costheta = aten::abs(dot(wh, n)); auto cos2 = costheta * costheta; auto denom = aten::pow((a2 - 1) * cos2 + 1, 2); auto D = denom > 0 ? a2 / (AT_MATH_PI * denom) : 0; return D; } AT_DEVICE_MTRL_API real MicrofacetGGX::computeGGXSmithG1(real roughness, const aten::vec3& v, const aten::vec3& n) { // NOTE // http://computergraphics.stackexchange.com/questions/2489/correct-form-of-the-ggx-geometry-term // http://gregory-igehy.hatenadiary.com/entry/2015/02/26/154142 real a = roughness; real costheta = aten::abs(dot(v, n)); real sintheta = aten::sqrt(1 - aten::clamp<real>(costheta * costheta, 0, 1)); real tan = costheta > 0 ? sintheta / costheta : 0; real denom = aten::sqrt(1 + a * a * tan * tan); real ret = 2 / (1 + denom); return ret; } AT_DEVICE_MTRL_API real MicrofacetGGX::pdf( real roughness, const aten::vec3& normal, const aten::vec3& wi, const aten::vec3& wo) { // NOTE // https://agraphicsguy.wordpress.com/2015/11/01/sampling-microfacet-brdf/ auto wh = normalize(-wi + wo); auto costheta = aten::abs(dot(wh, normal)); auto D = sampleGGX_D(wh, normal, roughness); auto denom = 4 * aten::abs(dot(wo, wh)); auto pdf = denom > 0 ? (D * costheta) / denom : 0; return pdf; } AT_DEVICE_MTRL_API aten::vec3 MicrofacetGGX::sampleDirection( real roughness, const aten::vec3& in, const aten::vec3& normal, aten::sampler* sampler) { auto r1 = sampler->nextSample(); auto r2 = sampler->nextSample(); auto a = roughness; auto theta = aten::atan(a * aten::sqrt(r1 / (1 - r1))); theta = ((theta >= 0) ? theta : (theta + 2 * AT_MATH_PI)); auto phi = 2 * AT_MATH_PI * r2; auto costheta = aten::cos(theta); auto sintheta = aten::sqrt(1 - costheta * costheta); auto cosphi = aten::cos(phi); auto sinphi = aten::sqrt(1 - cosphi * cosphi); // Ortho normal base. auto n = normal; auto t = aten::getOrthoVector(normal); auto b = normalize(cross(n, t)); auto w = t * sintheta * cosphi + b * sintheta * sinphi + n * costheta; w = normalize(w); auto dir = in - 2 * dot(in, w) * w; return std::move(dir); } AT_DEVICE_MTRL_API aten::vec3 MicrofacetGGX::bsdf( const aten::vec3& albedo, const real roughness, const real ior, real& fresnel, const aten::vec3& normal, const aten::vec3& wi, const aten::vec3& wo, real u, real v) { // C˂Ă鑤̂̋̕ܗ. real ni = real(1); // ^ real nt = ior; // ̓̋ܗ. aten::vec3 V = -wi; aten::vec3 L = wo; aten::vec3 N = normal; aten::vec3 H = normalize(L + V); // TODO // DesneyabsĂȂAAMD̂͂Ă.... auto NdotH = aten::abs(dot(N, H)); auto VdotH = aten::abs(dot(V, H)); auto NdotL = aten::abs(dot(N, L)); auto NdotV = aten::abs(dot(N, V)); // Compute D. real D = sampleGGX_D(H, N, roughness); // Compute G. real G(1); { auto G1_lh = computeGGXSmithG1(roughness, L, N); auto G1_vh = computeGGXSmithG1(roughness, V, N); G = G1_lh * G1_vh; } real F(1); { // http://d.hatena.ne.jp/hanecci/20130525/p3 // NOTE // Fschlick(v,h) R0 + (1 - R0)(1 - cos)^5 // R0 = ((n1 - n2) / (n1 + n2))^2 auto r0 = (ni - nt) / (ni + nt); r0 = r0 * r0; auto LdotH = aten::abs(dot(L, H)); F = r0 + (1 - r0) * aten::pow((1 - LdotH), 5); } auto denom = 4 * NdotL * NdotV; auto bsdf = denom > AT_MATH_EPSILON ? albedo * F * G * D / denom : aten::vec3(0); fresnel = F; return std::move(bsdf); } AT_DEVICE_MTRL_API void MicrofacetGGX::sample( MaterialSampling* result, const aten::MaterialParameter* param, const aten::vec3& normal, const aten::vec3& wi, const aten::vec3& orgnormal, aten::sampler* sampler, real u, real v, bool isLightPath/*= false*/) { auto roughness = material::sampleTexture( param->roughnessMap, u, v, param->roughness); result->dir = sampleDirection(roughness.r, wi, normal, sampler); result->pdf = pdf(roughness.r, normal, wi, result->dir); auto albedo = param->baseColor; albedo *= material::sampleTexture(param->albedoMap, u, v, real(1)); real fresnel = 1; real ior = param->ior; result->bsdf = bsdf(albedo, roughness.r, ior, fresnel, normal, wi, result->dir, u, v); result->fresnel = fresnel; } AT_DEVICE_MTRL_API void MicrofacetGGX::sample( MaterialSampling* result, const aten::MaterialParameter* param, const aten::vec3& normal, const aten::vec3& wi, const aten::vec3& orgnormal, aten::sampler* sampler, real u, real v, const aten::vec3& externalAlbedo, bool isLightPath/*= false*/) { auto roughness = material::sampleTexture( param->roughnessMap, u, v, param->roughness); result->dir = sampleDirection(roughness.r, wi, normal, sampler); result->pdf = pdf(roughness.r, normal, wi, result->dir); auto albedo = param->baseColor; albedo *= externalAlbedo; real fresnel = 1; real ior = param->ior; result->bsdf = bsdf(albedo, roughness.r, ior, fresnel, normal, wi, result->dir, u, v); result->fresnel = fresnel; } AT_DEVICE_MTRL_API MaterialSampling MicrofacetGGX::sample( const aten::ray& ray, const aten::vec3& normal, const aten::vec3& orgnormal, aten::sampler* sampler, real u, real v, bool isLightPath/*= false*/) const { MaterialSampling ret; sample( &ret, &m_param, normal, ray.dir, orgnormal, sampler, u, v, isLightPath); return std::move(ret); } bool MicrofacetGGX::edit(aten::IMaterialParamEditor* editor) { auto b0 = AT_EDIT_MATERIAL_PARAM(editor, m_param, roughness); auto b1 = AT_EDIT_MATERIAL_PARAM_RANGE(editor, m_param, ior, real(0.01), real(10)); auto b2 = AT_EDIT_MATERIAL_PARAM(editor, m_param, baseColor); AT_EDIT_MATERIAL_PARAM_TEXTURE(editor, m_param, albedoMap); AT_EDIT_MATERIAL_PARAM_TEXTURE(editor, m_param, normalMap); AT_EDIT_MATERIAL_PARAM_TEXTURE(editor, m_param, roughnessMap); return b0 || b1 || b2; } } <|endoftext|>
<commit_before>#include "../test.h" extern "C" { #include "udp-json-parser/json.h" #include "udp-json-builder/json-builder.h" } // extern "C" static void GenStat(Stat* s, const json_value* v) { switch (v->type) { case json_object: for (size_t i = 0; i < v->u.object.length; i++) { const json_object_entry* e = v->u.object.values + i; GenStat(s, e->value); s->stringLength += e->name_length; } s->stringCount += v->u.object.length; s->memberCount += v->u.object.length; s->objectCount++; break; case json_array: for (size_t i = 0; i < v->u.array.length; i++) GenStat(s, v->u.array.values[i]); s->arrayCount++; s->elementCount += v->u.array.length; break; case json_string: s->stringCount++; s->stringLength += v->u.string.length; break; case json_integer: case json_double: s->numberCount++; break; case json_boolean: if (v->u.boolean) s->trueCount++; else s->falseCount++; break; case json_null: s->nullCount++; break; default: break; } } class UdpjsonParseResult : public ParseResultBase { public: UdpjsonParseResult() : root() {} ~UdpjsonParseResult() { json_value_free(root); } json_value *root; }; class UdpjsonStringResult : public StringResultBase { public: UdpjsonStringResult() : s() {} ~UdpjsonStringResult() { free(s); } virtual const char* c_str() const { return s; } char* s; }; class UdpjsonTest : public TestBase { public: #if TEST_INFO virtual const char* GetName() const { return "udp/json-parser (C)"; } virtual const char* GetFilename() const { return __FILE__; } #endif #if TEST_PARSE virtual ParseResultBase* Parse(const char* json, size_t length) const { UdpjsonParseResult* pr = new UdpjsonParseResult; json_settings settings = json_settings(); settings.value_extra = json_builder_extra; /* space for json-builder state */ char error[128]; pr->root = json_parse_ex(&settings, json, length, error); if (!pr->root) { delete pr; return 0; } return pr; } #endif // Very slow in the current version. #if TEST_STRINGIFY virtual StringResultBase* Stringify(const ParseResultBase* parseResult) const { const UdpjsonParseResult* pr = static_cast<const UdpjsonParseResult*>(parseResult); UdpjsonStringResult* sr = new UdpjsonStringResult; json_serialize_opts opts = { json_serialize_mode_packed, 0, 0 }; sr->s = (char*)malloc(json_measure_ex(pr->root, opts)); json_serialize_ex(sr->s, pr->root, opts); return sr; } #endif #if TEST_PRETTIFY virtual StringResultBase* Prettify(const ParseResultBase* parseResult) const { const UdpjsonParseResult* pr = static_cast<const UdpjsonParseResult*>(parseResult); UdpjsonStringResult* sr = new UdpjsonStringResult; json_serialize_opts opts = { json_serialize_mode_multiline, 0, 4 }; sr->s = (char*)malloc(json_measure_ex(pr->root, opts)); json_serialize_ex(sr->s, pr->root, opts); return sr; } #endif #if TEST_STATISTICS virtual bool Statistics(const ParseResultBase* parseResult, Stat* stat) const { const UdpjsonParseResult* pr = static_cast<const UdpjsonParseResult*>(parseResult); memset(stat, 0, sizeof(Stat)); GenStat(stat, pr->root); return true; } #endif #if TEST_CONFORMANCE virtual bool ParseDouble(const char* json, double* d) const { UdpjsonParseResult pr; json_settings settings = json_settings(); settings.value_extra = json_builder_extra; /* space for json-builder state */ char error[128]; pr.root = json_parse_ex(&settings, json, strlen(json), error); if (pr.root && pr.root->type == json_array && pr.root->u.array.length == 1 && pr.root->u.array.values[0]->type == json_double) { *d = pr.root->u.array.values[0]->u.dbl; return true; } return false; } virtual bool ParseString(const char* json, std::string& s) const { UdpjsonParseResult pr; json_settings settings = json_settings(); settings.value_extra = json_builder_extra; /* space for json-builder state */ char error[128]; pr.root = json_parse_ex(&settings, json, strlen(json), error); if (pr.root && pr.root->type == json_array && pr.root->u.array.length == 1 && pr.root->u.array.values[0]->type == json_string) { s = std::string( pr.root->u.array.values[0]->u.string.ptr, pr.root->u.array.values[0]->u.string.length); return true; } return false; } #endif }; REGISTER_TEST(UdpjsonTest); <commit_msg>Temp disable udpjson on gcc<commit_after>#include "../test.h" #if !defined(__GNUC__) || defined(__clang__) // gcc crash in Travis https://github.com/udp/json-builder/issues/7 extern "C" { #include "udp-json-parser/json.h" #include "udp-json-builder/json-builder.h" } // extern "C" static void GenStat(Stat* s, const json_value* v) { switch (v->type) { case json_object: for (size_t i = 0; i < v->u.object.length; i++) { const json_object_entry* e = v->u.object.values + i; GenStat(s, e->value); s->stringLength += e->name_length; } s->stringCount += v->u.object.length; s->memberCount += v->u.object.length; s->objectCount++; break; case json_array: for (size_t i = 0; i < v->u.array.length; i++) GenStat(s, v->u.array.values[i]); s->arrayCount++; s->elementCount += v->u.array.length; break; case json_string: s->stringCount++; s->stringLength += v->u.string.length; break; case json_integer: case json_double: s->numberCount++; break; case json_boolean: if (v->u.boolean) s->trueCount++; else s->falseCount++; break; case json_null: s->nullCount++; break; default: break; } } class UdpjsonParseResult : public ParseResultBase { public: UdpjsonParseResult() : root() {} ~UdpjsonParseResult() { json_value_free(root); } json_value *root; }; class UdpjsonStringResult : public StringResultBase { public: UdpjsonStringResult() : s() {} ~UdpjsonStringResult() { free(s); } virtual const char* c_str() const { return s; } char* s; }; class UdpjsonTest : public TestBase { public: #if TEST_INFO virtual const char* GetName() const { return "udp/json-parser (C)"; } virtual const char* GetFilename() const { return __FILE__; } #endif #if TEST_PARSE virtual ParseResultBase* Parse(const char* json, size_t length) const { UdpjsonParseResult* pr = new UdpjsonParseResult; json_settings settings = json_settings(); settings.value_extra = json_builder_extra; /* space for json-builder state */ char error[128]; pr->root = json_parse_ex(&settings, json, length, error); if (!pr->root) { delete pr; return 0; } return pr; } #endif // Very slow in the current version. #if TEST_STRINGIFY virtual StringResultBase* Stringify(const ParseResultBase* parseResult) const { const UdpjsonParseResult* pr = static_cast<const UdpjsonParseResult*>(parseResult); UdpjsonStringResult* sr = new UdpjsonStringResult; json_serialize_opts opts = { json_serialize_mode_packed, 0, 0 }; sr->s = (char*)malloc(json_measure_ex(pr->root, opts)); json_serialize_ex(sr->s, pr->root, opts); return sr; } #endif #if TEST_PRETTIFY virtual StringResultBase* Prettify(const ParseResultBase* parseResult) const { const UdpjsonParseResult* pr = static_cast<const UdpjsonParseResult*>(parseResult); UdpjsonStringResult* sr = new UdpjsonStringResult; json_serialize_opts opts = { json_serialize_mode_multiline, 0, 4 }; sr->s = (char*)malloc(json_measure_ex(pr->root, opts)); json_serialize_ex(sr->s, pr->root, opts); return sr; } #endif #if TEST_STATISTICS virtual bool Statistics(const ParseResultBase* parseResult, Stat* stat) const { const UdpjsonParseResult* pr = static_cast<const UdpjsonParseResult*>(parseResult); memset(stat, 0, sizeof(Stat)); GenStat(stat, pr->root); return true; } #endif #if TEST_CONFORMANCE virtual bool ParseDouble(const char* json, double* d) const { UdpjsonParseResult pr; json_settings settings = json_settings(); settings.value_extra = json_builder_extra; /* space for json-builder state */ char error[128]; pr.root = json_parse_ex(&settings, json, strlen(json), error); if (pr.root && pr.root->type == json_array && pr.root->u.array.length == 1 && pr.root->u.array.values[0]->type == json_double) { *d = pr.root->u.array.values[0]->u.dbl; return true; } return false; } virtual bool ParseString(const char* json, std::string& s) const { UdpjsonParseResult pr; json_settings settings = json_settings(); settings.value_extra = json_builder_extra; /* space for json-builder state */ char error[128]; pr.root = json_parse_ex(&settings, json, strlen(json), error); if (pr.root && pr.root->type == json_array && pr.root->u.array.length == 1 && pr.root->u.array.values[0]->type == json_string) { s = std::string( pr.root->u.array.values[0]->u.string.ptr, pr.root->u.array.values[0]->u.string.length); return true; } return false; } #endif }; REGISTER_TEST(UdpjsonTest); #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: rtl_OUStringBuffer2.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2006-09-17 08:58:39 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sal.hxx" #include <cppunit/simpleheader.hxx> #include "stringhelper.hxx" #include <rtl/ustrbuf.hxx> #include <rtl/uri.hxx> namespace rtl_OUStringBuffer { class insertUtf32 : public CppUnit::TestFixture { public: // initialise your test code values here. void setUp() { } void tearDown() { } void insertUtf32_001() { ::rtl::OUStringBuffer aUStrBuf(4); aUStrBuf.insertUtf32(0,0x10ffff); rtl::OUString suStr = aUStrBuf.makeStringAndClear(); rtl::OUString suStr2 = rtl::Uri::encode(suStr, rtl_UriCharClassUnoParamValue, rtl_UriEncodeKeepEscapes, RTL_TEXTENCODING_UTF8); rtl::OString sStr; sStr <<= suStr2; t_print("%s\n", sStr.getStr()); CPPUNIT_ASSERT_MESSAGE("Strings must be '%F4%8F%BF%BF'", sStr.equals(rtl::OString("%F4%8F%BF%BF")) == sal_True); } void insertUtf32_002() { ::rtl::OUStringBuffer aUStrBuf(4); aUStrBuf.insertUtf32(0,0x41); aUStrBuf.insertUtf32(1,0x42); aUStrBuf.insertUtf32(2,0x43); rtl::OUString suStr = aUStrBuf.makeStringAndClear(); rtl::OUString suStr2 = rtl::Uri::encode(suStr, rtl_UriCharClassUnoParamValue, rtl_UriEncodeKeepEscapes, RTL_TEXTENCODING_UTF8); rtl::OString sStr; sStr <<= suStr2; t_print("%s\n", sStr.getStr()); CPPUNIT_ASSERT_MESSAGE("Strings must be 'ABC'", sStr.equals(rtl::OString("ABC")) == sal_True); } CPPUNIT_TEST_SUITE(insertUtf32); CPPUNIT_TEST(insertUtf32_001); CPPUNIT_TEST(insertUtf32_002); CPPUNIT_TEST_SUITE_END(); }; // class getToken // ----------------------------------------------------------------------------- CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(rtl_OUStringBuffer::insertUtf32, "rtl_OUStringBuffer"); } // namespace rtl_OUStringBuffer // ----------------------------------------------------------------------------- // this macro creates an empty function, which will called by the RegisterAllFunctions() // to let the user the possibility to also register some functions by hand. NOADDITIONAL; <commit_msg>INTEGRATION: CWS changefileheader (1.3.234); FILE MERGED 2008/03/31 13:23:56 rt 1.3.234.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: rtl_OUStringBuffer2.cxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sal.hxx" #include <cppunit/simpleheader.hxx> #include "stringhelper.hxx" #include <rtl/ustrbuf.hxx> #include <rtl/uri.hxx> namespace rtl_OUStringBuffer { class insertUtf32 : public CppUnit::TestFixture { public: // initialise your test code values here. void setUp() { } void tearDown() { } void insertUtf32_001() { ::rtl::OUStringBuffer aUStrBuf(4); aUStrBuf.insertUtf32(0,0x10ffff); rtl::OUString suStr = aUStrBuf.makeStringAndClear(); rtl::OUString suStr2 = rtl::Uri::encode(suStr, rtl_UriCharClassUnoParamValue, rtl_UriEncodeKeepEscapes, RTL_TEXTENCODING_UTF8); rtl::OString sStr; sStr <<= suStr2; t_print("%s\n", sStr.getStr()); CPPUNIT_ASSERT_MESSAGE("Strings must be '%F4%8F%BF%BF'", sStr.equals(rtl::OString("%F4%8F%BF%BF")) == sal_True); } void insertUtf32_002() { ::rtl::OUStringBuffer aUStrBuf(4); aUStrBuf.insertUtf32(0,0x41); aUStrBuf.insertUtf32(1,0x42); aUStrBuf.insertUtf32(2,0x43); rtl::OUString suStr = aUStrBuf.makeStringAndClear(); rtl::OUString suStr2 = rtl::Uri::encode(suStr, rtl_UriCharClassUnoParamValue, rtl_UriEncodeKeepEscapes, RTL_TEXTENCODING_UTF8); rtl::OString sStr; sStr <<= suStr2; t_print("%s\n", sStr.getStr()); CPPUNIT_ASSERT_MESSAGE("Strings must be 'ABC'", sStr.equals(rtl::OString("ABC")) == sal_True); } CPPUNIT_TEST_SUITE(insertUtf32); CPPUNIT_TEST(insertUtf32_001); CPPUNIT_TEST(insertUtf32_002); CPPUNIT_TEST_SUITE_END(); }; // class getToken // ----------------------------------------------------------------------------- CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(rtl_OUStringBuffer::insertUtf32, "rtl_OUStringBuffer"); } // namespace rtl_OUStringBuffer // ----------------------------------------------------------------------------- // this macro creates an empty function, which will called by the RegisterAllFunctions() // to let the user the possibility to also register some functions by hand. NOADDITIONAL; <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ // mapnik #include <mapnik/json/geometry_generator_grammar.hpp> #include <mapnik/util/spirit_transform_attribute.hpp> // boost #include <boost/spirit/include/karma.hpp> #include <boost/spirit/include/phoenix.hpp> #include <boost/spirit/include/phoenix_core.hpp> #include <boost/spirit/include/phoenix_fusion.hpp> #include <boost/fusion/include/at.hpp> namespace mapnik { namespace json { namespace karma = boost::spirit::karma; namespace phoenix = boost::phoenix; template <typename OutputIterator, typename Geometry> geometry_generator_grammar<OutputIterator, Geometry>::geometry_generator_grammar() : geometry_generator_grammar::base_type(geometry) { boost::spirit::karma::_val_type _val; boost::spirit::karma::_1_type _1; boost::spirit::karma::_a_type _a; boost::spirit::karma::lit_type lit; boost::spirit::karma::uint_type uint_; boost::spirit::karma::eps_type eps; geometry = geometry_dispatch.alias() ; geometry_dispatch = eps[_a = geometry_type(_val)] << (&uint_(new_geometry::geometry_types::Point)[_1 = _a] << (point | lit("null"))) | (&uint_(new_geometry::geometry_types::LineString)[_1 = _a] << (linestring | lit("null"))) | (&uint_(new_geometry::geometry_types::Polygon)[_1 = _a] << (polygon | lit("null"))) | (&uint_(new_geometry::geometry_types::MultiPoint)[_1 = _a] << (multi_point | lit("null"))) | (&uint_(new_geometry::geometry_types::MultiLineString)[_1 = _a] << (multi_linestring | lit("null"))) | (&uint_(new_geometry::geometry_types::MultiPolygon)[_1 = _a] << (multi_polygon | lit("null"))) | (&uint_(new_geometry::geometry_types::GeometryCollection)[_1 = _a] << (geometry_collection | lit("null"))) ; point = lit("{\"type\":\"Point\",\"coordinates\":") << point_coord << lit("}") ; linestring = lit("{\"type\":\"LineString\",\"coordinates\":[") << linestring_coord << lit("]}") ; polygon = lit("{\"type\":\"Polygon\",\"coordinates\":[") << polygon_coord << lit("]}") ; multi_point = lit("{\"type\":\"MultiPoint\",\"coordinates\":[") << multi_point_coord << lit("]}") ; multi_linestring = lit("{\"type\":\"MultiLineString\",\"coordinates\":[") << multi_linestring_coord << lit("]}") ; multi_polygon = lit("{\"type\":\"MultiPolygon\",\"coordinates\":[") << multi_polygon_coord << lit("]}") ; geometry_collection = lit("{\"type\":\"GeometryCollection\",\"geometries\":[") << geometries << lit("]}") ; point_coord = lit('[') << coordinate << lit(',') << coordinate << lit(']') ; linestring_coord = point_coord % lit(',') ; polygon_coord = lit('[') << exterior_ring_coord << lit(']') << interior_ring_coord ; exterior_ring_coord = linestring_coord.alias() ; interior_ring_coord = *(lit(",[") << exterior_ring_coord << lit(']')) ; multi_point_coord = linestring_coord.alias() ; multi_linestring_coord = (lit('[') << linestring_coord << lit(']')) % lit(',') ; multi_polygon_coord = (lit('[') << polygon_coord << lit(']')) % lit(',') ; geometries = geometry % lit(',') ; } }} <commit_msg>json geometry generator - output "null" for uninitialised geometry<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ // mapnik #include <mapnik/json/geometry_generator_grammar.hpp> #include <mapnik/util/spirit_transform_attribute.hpp> // boost #include <boost/spirit/include/karma.hpp> #include <boost/spirit/include/phoenix.hpp> #include <boost/spirit/include/phoenix_core.hpp> #include <boost/spirit/include/phoenix_fusion.hpp> #include <boost/fusion/include/at.hpp> namespace mapnik { namespace json { namespace karma = boost::spirit::karma; namespace phoenix = boost::phoenix; template <typename OutputIterator, typename Geometry> geometry_generator_grammar<OutputIterator, Geometry>::geometry_generator_grammar() : geometry_generator_grammar::base_type(geometry) { boost::spirit::karma::_val_type _val; boost::spirit::karma::_1_type _1; boost::spirit::karma::_a_type _a; boost::spirit::karma::lit_type lit; boost::spirit::karma::uint_type uint_; boost::spirit::karma::eps_type eps; geometry = geometry_dispatch.alias() ; geometry_dispatch = eps[_a = geometry_type(_val)] << (&uint_(new_geometry::geometry_types::Point)[_1 = _a] << (point | lit("null"))) | (&uint_(new_geometry::geometry_types::LineString)[_1 = _a] << (linestring | lit("null"))) | (&uint_(new_geometry::geometry_types::Polygon)[_1 = _a] << (polygon | lit("null"))) | (&uint_(new_geometry::geometry_types::MultiPoint)[_1 = _a] << (multi_point | lit("null"))) | (&uint_(new_geometry::geometry_types::MultiLineString)[_1 = _a] << (multi_linestring | lit("null"))) | (&uint_(new_geometry::geometry_types::MultiPolygon)[_1 = _a] << (multi_polygon | lit("null"))) | (&uint_(new_geometry::geometry_types::GeometryCollection)[_1 = _a] << (geometry_collection | lit("null"))) | lit("null") ; point = lit("{\"type\":\"Point\",\"coordinates\":") << point_coord << lit("}") ; linestring = lit("{\"type\":\"LineString\",\"coordinates\":[") << linestring_coord << lit("]}") ; polygon = lit("{\"type\":\"Polygon\",\"coordinates\":[") << polygon_coord << lit("]}") ; multi_point = lit("{\"type\":\"MultiPoint\",\"coordinates\":[") << multi_point_coord << lit("]}") ; multi_linestring = lit("{\"type\":\"MultiLineString\",\"coordinates\":[") << multi_linestring_coord << lit("]}") ; multi_polygon = lit("{\"type\":\"MultiPolygon\",\"coordinates\":[") << multi_polygon_coord << lit("]}") ; geometry_collection = lit("{\"type\":\"GeometryCollection\",\"geometries\":[") << geometries << lit("]}") ; point_coord = lit('[') << coordinate << lit(',') << coordinate << lit(']') ; linestring_coord = point_coord % lit(',') ; polygon_coord = lit('[') << exterior_ring_coord << lit(']') << interior_ring_coord ; exterior_ring_coord = linestring_coord.alias() ; interior_ring_coord = *(lit(",[") << exterior_ring_coord << lit(']')) ; multi_point_coord = linestring_coord.alias() ; multi_linestring_coord = (lit('[') << linestring_coord << lit(']')) % lit(',') ; multi_polygon_coord = (lit('[') << polygon_coord << lit(']')) % lit(',') ; geometries = geometry % lit(',') ; } }} <|endoftext|>
<commit_before>/* * @file TopKItemEstimation.hpp * @author Kuilong Liu * @date 2013.04.24 * @ TopKItem by count min sketch */ #ifndef IZENELIB_UTIL_TOPKITEM_ESTIMATION_H_ #define IZENELIB_UTIL_TOPKITEM_ESTIMATION_H_ #include <list> #include <iterator> #include <iostream> #include <boost/unordered_map.hpp> #include <boost/shared_ptr.hpp> namespace izenelib { namespace util { template<typename ElemType, typename CountType> class Bucket; template<typename ElemType, typename CountType> class Item { public: typedef Bucket<ElemType, CountType> BucketT; typedef Item<ElemType, CountType> ItemT; Item(ElemType e, BucketT* b, ItemT* p, ItemT* n) :elem_(e), b_(b), prev_(p), next_(n) { } ~Item() { b_ = NULL; if(next_)delete next_; } ElemType elem_; BucketT* b_; ItemT* prev_; ItemT* next_; }; template<typename ElemType, typename CountType> class Bucket { public: typedef Item<ElemType, CountType> ItemT; typedef Bucket<ElemType, CountType> BucketT; Bucket(CountType c, BucketT* p, BucketT* n) :size_(0), c_(c), head_(NULL), end_(NULL), prev_(p), next_(n) { } ~Bucket() { if(head_)delete head_; if(next_)delete next_; } bool insert(ItemT* i) { if(size_==0) { head_=end_=i; i->prev_=NULL; } else { end_->next_=i; i->prev_=end_; end_=i; } i->b_=this; i->next_=NULL; size_++; return true; } bool erase(ItemT* i) { if(size_==1) { head_=end_=NULL; } else if(i->next_==NULL) { end_=end_->prev_; end_->next_=NULL; } else if(i->prev_==NULL) { head_=i->next_; head_->prev_=NULL; } else { i->prev_->next_=i->next_; i->next_->prev_=i->prev_; } size_--; i->prev_=i->next_=NULL; i->b_=NULL; return true; } CountType size_; CountType c_; ItemT* head_; ItemT* end_; BucketT* prev_; BucketT* next_; }; template<typename ElemType, typename CountType> class TopKEstimation { public: typedef Bucket<ElemType, CountType> BucketT; typedef Item<ElemType, CountType> ItemT; TopKEstimation(CountType m) :MAXSIZE_(m), size_(0), th_(0) { bs_ = new BucketT(0, NULL, NULL); } ~TopKEstimation() { if(bs_)delete bs_; gps_.clear(); } bool reset() { if(bs_->next_) delete bs_->next_; gps_.clear(); size_=th_=0; return true; } bool insert(ElemType elem, CountType count) { if(gps_.find(elem) != gps_.end()) { return update(elem, count); } else if(size_ >= MAXSIZE_ && count <= th_) return true; else if(size_ >= MAXSIZE_) { return replace(elem, count); } else { return additem(elem, count); } } bool get(std::list<ElemType>& elem, std::list<CountType>& count) { BucketT* bp = bs_->next_; while(bp) { ItemT* i=bp->head_; while(i) { elem.push_back(i->elem_); count.push_back(i->b_->c_); i=i->next_; } bp=bp->next_; } return true; } bool get(std::list<std::pair<ElemType, CountType> >& topk) { BucketT* bp = bs_->next_; while(bp) { ItemT* i=bp->head_; while(i) { topk.push_back(make_pair(i->elem_, i->b_->c_)); i=i->next_; } bp=bp->next_; } return true; } private: bool update(ElemType elem, CountType count) { ItemT* i = gps_[elem]; BucketT* bp = i->b_; count = bp->c_+1; if(bp->size_==1 && (!(bp->next_) || bp->next_->c_ > count)) { bp->c_++; th_ = bs_->next_->c_; return true; } bp->erase(i); if(!(bp->next_)) bp->next_=new BucketT(count, bp, NULL); else if(bp->next_->c_ > count) { BucketT* tp=new BucketT(count, bp, bp->next_); bp->next_=tp; tp->next_->prev_=tp; } bp->next_->insert(i); if(bp->size_==0) { bp->prev_->next_=bp->next_; bp->next_->prev_=bp->prev_; bp->next_=bp->prev_=NULL; delete bp; } return true; } bool replace(ElemType elem, CountType count) { count = bs_->next_->c_+1; ItemT* i = bs_->next_->end_; gps_.erase(gps_.find(i->elem_)); gps_[elem] = i; i->elem_=elem; return update(elem,count); } bool additem(ElemType elem, CountType count) { count=1; if(bs_->next_==NULL) { bs_->next_=new BucketT(count, bs_, NULL); } BucketT* bp=bs_->next_; ItemT* i=new ItemT(elem, bp, NULL, NULL); if(bp->c_ == count) { bp->insert(i); } else { BucketT* nbp = new BucketT(count, bs_, bs_->next_); bs_->next_ = nbp; nbp->next_->prev_=nbp; nbp->insert(i); } size_++; gps_[elem]=i; th_=bs_->next_->c_; return true; } CountType MAXSIZE_; //current size CountType size_; //threshold CountType th_; BucketT* bs_; boost::unordered_map<ElemType, ItemT* > gps_; }; } //end of namespace util } //end of namespace izenelib #endif <commit_msg>reverse the topk list, so it can be read more conveniently<commit_after>/* * @file TopKItemEstimation.hpp * @author Kuilong Liu * @date 2013.04.24 * @ TopKItem by count min sketch */ #ifndef IZENELIB_UTIL_TOPKITEM_ESTIMATION_H_ #define IZENELIB_UTIL_TOPKITEM_ESTIMATION_H_ #include <list> #include <iterator> #include <iostream> #include <boost/unordered_map.hpp> #include <boost/shared_ptr.hpp> namespace izenelib { namespace util { template<typename ElemType, typename CountType> class Bucket; template<typename ElemType, typename CountType> class Item { public: typedef Bucket<ElemType, CountType> BucketT; typedef Item<ElemType, CountType> ItemT; Item(ElemType e, BucketT* b, ItemT* p, ItemT* n) :elem_(e), b_(b), prev_(p), next_(n) { } ~Item() { b_ = NULL; if(next_)delete next_; } ElemType elem_; BucketT* b_; ItemT* prev_; ItemT* next_; }; template<typename ElemType, typename CountType> class Bucket { public: typedef Item<ElemType, CountType> ItemT; typedef Bucket<ElemType, CountType> BucketT; Bucket(CountType c, BucketT* p, BucketT* n) :size_(0), c_(c), head_(NULL), end_(NULL), prev_(p), next_(n) { } ~Bucket() { if(head_)delete head_; if(next_)delete next_; } bool insert(ItemT* i) { if(size_==0) { head_=end_=i; i->prev_=NULL; } else { end_->next_=i; i->prev_=end_; end_=i; } i->b_=this; i->next_=NULL; size_++; return true; } bool erase(ItemT* i) { if(size_==1) { head_=end_=NULL; } else if(i->next_==NULL) { end_=end_->prev_; end_->next_=NULL; } else if(i->prev_==NULL) { head_=i->next_; head_->prev_=NULL; } else { i->prev_->next_=i->next_; i->next_->prev_=i->prev_; } size_--; i->prev_=i->next_=NULL; i->b_=NULL; return true; } CountType size_; CountType c_; ItemT* head_; ItemT* end_; BucketT* prev_; BucketT* next_; }; template<typename ElemType, typename CountType> class TopKEstimation { public: typedef Bucket<ElemType, CountType> BucketT; typedef Item<ElemType, CountType> ItemT; TopKEstimation(CountType m) :MAXSIZE_(m), size_(0), th_(0) { bs_ = new BucketT(0, NULL, NULL); } ~TopKEstimation() { if(bs_)delete bs_; gps_.clear(); } bool reset() { if(bs_->next_) delete bs_->next_; gps_.clear(); size_=th_=0; return true; } bool insert(ElemType elem, CountType count) { if(gps_.find(elem) != gps_.end()) { return update(elem, count); } else if(size_ >= MAXSIZE_ && count <= th_) return true; else if(size_ >= MAXSIZE_) { return replace(elem, count); } else { return additem(elem, count); } } bool get(std::list<ElemType>& elem, std::list<CountType>& count) { BucketT* bp = bs_->next_; while(bp) { ItemT* i=bp->head_; while(i) { elem.push_front(i->elem_); count.push_front(i->b_->c_); i=i->next_; } bp=bp->next_; } return true; } bool get(std::list<std::pair<ElemType, CountType> >& topk) { BucketT* bp = bs_->next_; while(bp) { ItemT* i=bp->head_; while(i) { topk.push_front(make_pair(i->elem_, i->b_->c_)); i=i->next_; } bp=bp->next_; } return true; } private: bool update(ElemType elem, CountType count) { ItemT* i = gps_[elem]; BucketT* bp = i->b_; count = bp->c_+1; if(bp->size_==1 && (!(bp->next_) || bp->next_->c_ > count)) { bp->c_++; th_ = bs_->next_->c_; return true; } bp->erase(i); if(!(bp->next_)) bp->next_=new BucketT(count, bp, NULL); else if(bp->next_->c_ > count) { BucketT* tp=new BucketT(count, bp, bp->next_); bp->next_=tp; tp->next_->prev_=tp; } bp->next_->insert(i); if(bp->size_==0) { bp->prev_->next_=bp->next_; bp->next_->prev_=bp->prev_; bp->next_=bp->prev_=NULL; delete bp; } return true; } bool replace(ElemType elem, CountType count) { count = bs_->next_->c_+1; ItemT* i = bs_->next_->end_; gps_.erase(gps_.find(i->elem_)); gps_[elem] = i; i->elem_=elem; return update(elem,count); } bool additem(ElemType elem, CountType count) { count=1; if(bs_->next_==NULL) { bs_->next_=new BucketT(count, bs_, NULL); } BucketT* bp=bs_->next_; ItemT* i=new ItemT(elem, bp, NULL, NULL); if(bp->c_ == count) { bp->insert(i); } else { BucketT* nbp = new BucketT(count, bs_, bs_->next_); bs_->next_ = nbp; nbp->next_->prev_=nbp; nbp->insert(i); } size_++; gps_[elem]=i; th_=bs_->next_->c_; return true; } CountType MAXSIZE_; //current size CountType size_; //threshold CountType th_; BucketT* bs_; boost::unordered_map<ElemType, ItemT* > gps_; }; } //end of namespace util } //end of namespace izenelib #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2013, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford 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 "oskar_global.h" #include "widgets/oskar_About.h" #include <QtGui/QApplication> #include <QtGui/QDialogButtonBox> #include <QtGui/QFont> #include <QtGui/QGroupBox> #include <QtGui/QHBoxLayout> #include <QtGui/QLabel> #include <QtGui/QTextBrowser> #include <QtGui/QTextDocument> #include <QtGui/QSizePolicy> #include <QtGui/QVBoxLayout> oskar_About::oskar_About(QWidget *parent) : QDialog(parent) { // Set up the GUI. QVBoxLayout* vLayoutMain = new QVBoxLayout(this); QVBoxLayout* vLayout1 = new QVBoxLayout; QHBoxLayout* hLayout1 = new QHBoxLayout; QHBoxLayout* hLayout2 = new QHBoxLayout; // Create icon. QLabel* icon = new QLabel(this); QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(icon->sizePolicy().hasHeightForWidth()); icon->setSizePolicy(sizePolicy); icon->setPixmap(QPixmap(QString::fromUtf8(":/icons/oskar-32x32.png"))); icon->setAlignment(Qt::AlignCenter); icon->setMargin(10); hLayout1->addWidget(icon); // Create title. setWindowTitle("About OSKAR"); QLabel* title = new QLabel("OSKAR 2", this); title->setFont(QFont("Arial", 28)); hLayout1->addWidget(title); // Add title block to vertical layout. hLayout1->setContentsMargins(0, 0, 80, 0); vLayout1->addLayout(hLayout1); // Create version label. QLabel* version = new QLabel(QString("OSKAR Version %1") .arg(OSKAR_VERSION_STR), this); vLayout1->addWidget(version); // Create compilation date label. QLabel* date = new QLabel(QString("Build Date: %1, %2"). arg(__DATE__).arg(__TIME__), this); vLayout1->addWidget(date); // Add vertical spacer. vLayout1->addStretch(); // Create logos. QLabel* oerc = new QLabel(this); oerc->setSizePolicy(sizePolicy); oerc->setPixmap(QPixmap(QString(":/icons/oerc-128x128.png"))); oerc->setAlignment(Qt::AlignCenter); oerc->setMargin(4); QLabel* oxford = new QLabel(this); oxford->setSizePolicy(sizePolicy); oxford->setPixmap(QPixmap(QString(":/icons/oxford-128x128.png"))); oxford->setAlignment(Qt::AlignCenter); oxford->setMargin(4); hLayout2->addLayout(vLayout1); hLayout2->addWidget(oerc); hLayout2->addWidget(oxford); // Add top banner to main vertical layout. vLayoutMain->addLayout(hLayout2); // Create license group. QGroupBox* grpLic = new QGroupBox("License", this); sizePolicy = grpLic->sizePolicy(); sizePolicy.setVerticalStretch(10); grpLic->setSizePolicy(sizePolicy); QVBoxLayout* vLayoutLic = new QVBoxLayout(grpLic); // Create license text. QTextDocument* licenseText = new QTextDocument(this); { QTextBlockFormat paragraph; paragraph.setBottomMargin(10); QTextCursor cursor(licenseText); cursor.setBlockFormat(paragraph); cursor.insertText("Copyright (c) 2011-2013, The University of Oxford. " "\nAll rights reserved."); cursor.insertList(QTextListFormat::ListDecimal); cursor.insertText("Redistributions of source code must retain the " "above copyright notice, this list of conditions and the " "following disclaimer."); cursor.insertBlock(); cursor.insertText("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."); cursor.insertBlock(); cursor.insertText("Neither the name of the University of Oxford nor " "the names of its contributors may be used to endorse or " "promote products derived from this software without specific " "prior written permission."); cursor.insertBlock(); cursor.setBlockFormat(paragraph); cursor.insertText("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."); } // Create license display. QTextBrowser* license = new QTextBrowser(this); license->setDocument(licenseText); license->setReadOnly(true); vLayoutLic->addWidget(license); // Add license group. vLayoutMain->addWidget(grpLic); // Create attribution group. QGroupBox* grpAtt = new QGroupBox("Attribution && Acknowledgements", this); sizePolicy = grpAtt->sizePolicy(); sizePolicy.setVerticalStretch(10); grpAtt->setSizePolicy(sizePolicy); QVBoxLayout* vLayoutAtt = new QVBoxLayout(grpAtt); // Create attribution document. QString html; html.append("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" " "\"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head></head><body>\n"); html.append("<p>OSKAR 2 has been developed using hardware " "donated by NVIDIA UK.</p>"); html.append("<p>OSKAR 2 directly links against or uses the following " "software libraries:</p>"); html.append("<ul>"); html.append("<li>NVIDIA CUDA " "(<a href=\"http://www.nvidia.com/object/cuda_home.html\">" "http://www.nvidia.com/object/cuda_home.html</a>)</li>"); #ifndef OSKAR_NO_LAPACK html.append("<li>LAPACK " "(<a href=\"http://www.netlib.org/lapack/\">" "http://www.netlib.org/lapack/</a>)</li>"); #endif #ifndef OSKAR_NO_CBLAS html.append("<li>CBLAS " "(<a href=\"http://www.netlib.org/blas/\">" "http://www.netlib.org/blas/</a>)</li>"); #endif html.append("<li>DIERCKX for surface fitting using splines " "(<a href=\"http://netlib.org/dierckx/\">" "http://netlib.org/dierckx/</a>)</li>"); html.append("<li>The Qt cross-platform application framework " "(<a href=\"http://qt.nokia.com/\">" "http://qt.nokia.com/</a>)</li>"); #ifndef OSKAR_NO_MS html.append("<li>casacore for Measurement Set export " "(<a href=\"http://code.google.com/p/casacore/\">" "http://code.google.com/p/casacore/</a>)</li>"); #endif #ifndef OSKAR_NO_FITS html.append("<li>CFITSIO for FITS file export " "(<a href=\"http://heasarc.gsfc.nasa.gov/fitsio/\">" "http://heasarc.gsfc.nasa.gov/fitsio/</a>)</li>"); #endif html.append("<li>ezOptionParser " "(<a href=\"http://sourceforge.net/projects/ezoptionparser/\">" "http://sourceforge.net/projects/ezoptionparser/</a>)</li>"); html.append("</ul>"); html.append("<p>The following tools have been used during the development " "of OSKAR 2:</p>"); html.append("<ul>"); html.append("<li>The CMake cross-platform build system " "(<a href=\"http://www.cmake.org/\">" "http://www.cmake.org/</a>)</li>"); html.append("<li>The Google Test unit-testing framework " "(<a href=\"http://code.google.com/p/googletest/\">" "http://code.google.com/p/googletest/</a>)</li>"); html.append("<li>The Eclipse source-code IDE " "(<a href=\"http://www.eclipse.org/\">" "http://www.eclipse.org/</a>)</li>"); html.append("<li>The Valgrind memory checker " "(<a href=\"http://valgrind.org/\">" "http://valgrind.org/</a>)</li>"); html.append("<li>The GCC toolchain " "(<a href=\"http://gcc.gnu.org/\">" "http://gcc.gnu.org/</a>)</li>"); html.append("<li>MATLAB " "(<a href=\"http://www.mathworks.co.uk/products/matlab/\">" "http://www.mathworks.co.uk/products/matlab/</a>)</li>"); html.append("</ul>"); html.append("<p>This research has made use of SAOImage DS9, developed " "by Smithsonian Astrophysical Observatory.</p>"); html.append("</body></html>"); // Create attribution document display. QTextBrowser* libs = new QTextBrowser(this); libs->setOpenExternalLinks(true); libs->setHtml(html); libs->setReadOnly(true); vLayoutAtt->addWidget(libs); // Create acknowledgement labels. QLabel* ack1 = new QLabel("If OSKAR has been helpful in your research, " "please give the following acknowledgement:", this); vLayoutAtt->addWidget(ack1); QLabel* ack2 = new QLabel("<blockquote><i>\"This research has made use of OSKAR, " "developed at the University of Oxford.\"</i></blockquote>", this); ack2->setTextFormat(Qt::RichText); vLayoutAtt->addWidget(ack2); QLabel* ack3 = new QLabel("and/or reference the following publication:", this); vLayoutAtt->addWidget(ack3); QLabel* ack4 = new QLabel("<blockquote>Dulwich, F., Mort, B.J., Salvini, S., " "\"<i>Using OSKAR to simulate data from radio interferometers\"</i>,<br>" "MNRAS 2013 in preparation.</blockquote>", this); ack4->setTextFormat(Qt::RichText); vLayoutAtt->addWidget(ack4); // Add attribution group. vLayoutMain->addWidget(grpAtt); // Create close button. QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Ok, Qt::Horizontal, this); connect(buttons, SIGNAL(accepted()), this, SLOT(accept())); vLayoutMain->addWidget(buttons); } <commit_msg>Updated reference title.<commit_after>/* * Copyright (c) 2012-2014, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford 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 <oskar_global.h> #include <widgets/oskar_About.h> #include <QtGui/QApplication> #include <QtGui/QDialogButtonBox> #include <QtGui/QFont> #include <QtGui/QGroupBox> #include <QtGui/QHBoxLayout> #include <QtGui/QLabel> #include <QtGui/QTextBrowser> #include <QtGui/QTextDocument> #include <QtGui/QSizePolicy> #include <QtGui/QVBoxLayout> oskar_About::oskar_About(QWidget *parent) : QDialog(parent) { // Set up the GUI. QVBoxLayout* vLayoutMain = new QVBoxLayout(this); QVBoxLayout* vLayout1 = new QVBoxLayout; QHBoxLayout* hLayout1 = new QHBoxLayout; QHBoxLayout* hLayout2 = new QHBoxLayout; // Create icon. QLabel* icon = new QLabel(this); QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(icon->sizePolicy().hasHeightForWidth()); icon->setSizePolicy(sizePolicy); icon->setPixmap(QPixmap(QString::fromUtf8(":/icons/oskar-32x32.png"))); icon->setAlignment(Qt::AlignCenter); icon->setMargin(10); hLayout1->addWidget(icon); // Create title. setWindowTitle("About OSKAR"); QLabel* title = new QLabel("OSKAR 2", this); title->setFont(QFont("Arial", 28)); hLayout1->addWidget(title); // Add title block to vertical layout. hLayout1->setContentsMargins(0, 0, 80, 0); vLayout1->addLayout(hLayout1); // Create version label. QLabel* version = new QLabel(QString("OSKAR Version %1") .arg(OSKAR_VERSION_STR), this); vLayout1->addWidget(version); // Create compilation date label. QLabel* date = new QLabel(QString("Build Date: %1, %2"). arg(__DATE__).arg(__TIME__), this); vLayout1->addWidget(date); // Add vertical spacer. vLayout1->addStretch(); // Create logos. QLabel* oerc = new QLabel(this); oerc->setSizePolicy(sizePolicy); oerc->setPixmap(QPixmap(QString(":/icons/oerc-128x128.png"))); oerc->setAlignment(Qt::AlignCenter); oerc->setMargin(4); QLabel* oxford = new QLabel(this); oxford->setSizePolicy(sizePolicy); oxford->setPixmap(QPixmap(QString(":/icons/oxford-128x128.png"))); oxford->setAlignment(Qt::AlignCenter); oxford->setMargin(4); hLayout2->addLayout(vLayout1); hLayout2->addWidget(oerc); hLayout2->addWidget(oxford); // Add top banner to main vertical layout. vLayoutMain->addLayout(hLayout2); // Create license group. QGroupBox* grpLic = new QGroupBox("License", this); sizePolicy = grpLic->sizePolicy(); sizePolicy.setVerticalStretch(10); grpLic->setSizePolicy(sizePolicy); QVBoxLayout* vLayoutLic = new QVBoxLayout(grpLic); // Create license text. QTextDocument* licenseText = new QTextDocument(this); { QTextBlockFormat paragraph; paragraph.setBottomMargin(10); QTextCursor cursor(licenseText); cursor.setBlockFormat(paragraph); cursor.insertText("Copyright (c) 2011-2014, The University of Oxford. " "\nAll rights reserved."); cursor.insertList(QTextListFormat::ListDecimal); cursor.insertText("Redistributions of source code must retain the " "above copyright notice, this list of conditions and the " "following disclaimer."); cursor.insertBlock(); cursor.insertText("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."); cursor.insertBlock(); cursor.insertText("Neither the name of the University of Oxford nor " "the names of its contributors may be used to endorse or " "promote products derived from this software without specific " "prior written permission."); cursor.insertBlock(); cursor.setBlockFormat(paragraph); cursor.insertText("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."); } // Create license display. QTextBrowser* license = new QTextBrowser(this); license->setDocument(licenseText); license->setReadOnly(true); vLayoutLic->addWidget(license); // Add license group. vLayoutMain->addWidget(grpLic); // Create attribution group. QGroupBox* grpAtt = new QGroupBox("Attribution && Acknowledgements", this); sizePolicy = grpAtt->sizePolicy(); sizePolicy.setVerticalStretch(10); grpAtt->setSizePolicy(sizePolicy); QVBoxLayout* vLayoutAtt = new QVBoxLayout(grpAtt); // Create attribution document. QString html; html.append("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" " "\"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head></head><body>\n"); html.append("<p>OSKAR 2 has been developed using hardware " "donated by NVIDIA UK.</p>"); html.append("<p>OSKAR 2 directly links against or uses the following " "software libraries:</p>"); html.append("<ul>"); html.append("<li>NVIDIA CUDA " "(<a href=\"http://www.nvidia.com/object/cuda_home.html\">" "http://www.nvidia.com/object/cuda_home.html</a>)</li>"); #ifndef OSKAR_NO_LAPACK html.append("<li>LAPACK " "(<a href=\"http://www.netlib.org/lapack/\">" "http://www.netlib.org/lapack/</a>)</li>"); #endif #ifndef OSKAR_NO_CBLAS html.append("<li>CBLAS " "(<a href=\"http://www.netlib.org/blas/\">" "http://www.netlib.org/blas/</a>)</li>"); #endif html.append("<li>DIERCKX for surface fitting using splines " "(<a href=\"http://netlib.org/dierckx/\">" "http://netlib.org/dierckx/</a>)</li>"); html.append("<li>The Qt cross-platform application framework " "(<a href=\"http://qt.digia.com/\">" "http://qt.digia.com/</a>)</li>"); #ifndef OSKAR_NO_MS html.append("<li>casacore for Measurement Set export " "(<a href=\"http://code.google.com/p/casacore/\">" "http://code.google.com/p/casacore/</a>)</li>"); #endif #ifndef OSKAR_NO_FITS html.append("<li>CFITSIO for FITS file export " "(<a href=\"http://heasarc.gsfc.nasa.gov/fitsio/\">" "http://heasarc.gsfc.nasa.gov/fitsio/</a>)</li>"); #endif html.append("<li>ezOptionParser " "(<a href=\"http://sourceforge.net/projects/ezoptionparser/\">" "http://sourceforge.net/projects/ezoptionparser/</a>)</li>"); html.append("</ul>"); html.append("<p>The following tools have been used during the development " "of OSKAR 2:</p>"); html.append("<ul>"); html.append("<li>The CMake cross-platform build system " "(<a href=\"http://www.cmake.org/\">" "http://www.cmake.org/</a>)</li>"); html.append("<li>The Google Test unit-testing framework " "(<a href=\"http://code.google.com/p/googletest/\">" "http://code.google.com/p/googletest/</a>)</li>"); html.append("<li>The Eclipse source-code IDE " "(<a href=\"http://www.eclipse.org/\">" "http://www.eclipse.org/</a>)</li>"); html.append("<li>The Valgrind memory checker " "(<a href=\"http://valgrind.org/\">" "http://valgrind.org/</a>)</li>"); html.append("<li>The GCC toolchain " "(<a href=\"http://gcc.gnu.org/\">" "http://gcc.gnu.org/</a>)</li>"); html.append("<li>MATLAB " "(<a href=\"http://www.mathworks.co.uk/products/matlab/\">" "http://www.mathworks.co.uk/products/matlab/</a>)</li>"); html.append("</ul>"); html.append("<p>This research has made use of SAOImage DS9, developed " "by Smithsonian Astrophysical Observatory.</p>"); html.append("</body></html>"); // Create attribution document display. QTextBrowser* libs = new QTextBrowser(this); libs->setOpenExternalLinks(true); libs->setHtml(html); libs->setReadOnly(true); vLayoutAtt->addWidget(libs); // Create acknowledgement labels. QLabel* ack1 = new QLabel("If OSKAR has been helpful in your research, " "please give the following acknowledgement:", this); vLayoutAtt->addWidget(ack1); QLabel* ack2 = new QLabel("<blockquote><i>\"This research has made use of OSKAR, " "developed at the University of Oxford.\"</i></blockquote>", this); ack2->setTextFormat(Qt::RichText); vLayoutAtt->addWidget(ack2); QLabel* ack3 = new QLabel("and/or reference the following publication:", this); vLayoutAtt->addWidget(ack3); QLabel* ack4 = new QLabel("<blockquote>Dulwich, F., Mort, B. J., Salvini, S., " "\"<i>OSKAR: A software package to simulate data from radio " "interferometers\"</i>,<br>" "MNRAS 2014, in preparation.</blockquote>", this); ack4->setTextFormat(Qt::RichText); vLayoutAtt->addWidget(ack4); // Add attribution group. vLayoutMain->addWidget(grpAtt); // Create close button. QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Ok, Qt::Horizontal, this); connect(buttons, SIGNAL(accepted()), this, SLOT(accept())); vLayoutMain->addWidget(buttons); } <|endoftext|>
<commit_before>/* Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include <string> #include "util/sstream.h" #include "kernel/find_fn.h" #include "kernel/replace_fn.h" #include "kernel/instantiate.h" #include "library/scoped_ext.h" #include "library/expr_lt.h" #include "library/util.h" #include "library/normalize.h" namespace lean { typedef pair<name, bool> abbrev_entry; struct abbrev_state { name_map<bool> m_abbrevs; rb_map<expr, name, expr_cmp_no_level_params> m_inv_map; // for pretty printer void add(environment const & env, name const & n, bool parsing_only) { declaration const & d = env.get(n); if (!d.is_definition()) throw exception(sstream() << "invalid abbreviation '" << n << "', it is not a definition"); m_abbrevs.insert(n, parsing_only); if (!parsing_only) { expr v = try_eta(d.get_value()); m_inv_map.insert(v, n); } } bool is_abbreviation(name const & n) const { return m_abbrevs.contains(n); } bool is_parsing_only_abbreviation(name const & n) const { if (auto it = m_abbrevs.find(n)) return *it; else return false; } optional<name> is_abbreviated(expr const & e) const { if (auto it = m_inv_map.find(e)) return optional<name>(*it); else return optional<name>(); } }; static name * g_class_name = nullptr; static std::string * g_key = nullptr; struct abbrev_config { typedef abbrev_state state; typedef abbrev_entry entry; static void add_entry(environment const & env, io_state const &, state & s, entry const & e) { s.add(env, e.first, e.second); } static name const & get_class_name() { return *g_class_name; } static std::string const & get_serialization_key() { return *g_key; } static void write_entry(serializer & s, entry const & e) { s << e.first << e.second; } static entry read_entry(deserializer & d) { entry e; d >> e.first >> e.second; return e; } static optional<unsigned> get_fingerprint(entry const & e) { return some(e.first.hash()); } }; template class scoped_ext<abbrev_config>; typedef scoped_ext<abbrev_config> abbrev_ext; environment add_abbreviation(environment const & env, name const & n, bool parsing_only, bool persistent) { return abbrev_ext::add_entry(env, get_dummy_ios(), abbrev_entry(n, parsing_only), persistent); } bool is_abbreviation(environment const & env, name const & n) { abbrev_state const & s = abbrev_ext::get_state(env); return s.is_abbreviation(n); } bool is_parsing_only_abbreviation(environment const & env, name const & n) { abbrev_state const & s = abbrev_ext::get_state(env); return s.is_parsing_only_abbreviation(n); } optional<name> is_abbreviated(environment const & env, expr const & e) { abbrev_state const & s = abbrev_ext::get_state(env); return s.is_abbreviated(e); } bool contains_abbreviations(environment const & env, expr const & e) { abbrev_state const & s = abbrev_ext::get_state(env); return static_cast<bool>(find(e, [&](expr const & e, unsigned) { return is_constant(e) && s.is_abbreviation(const_name(e)); })); } expr expand_abbreviations(environment const & env, expr const & e) { if (!contains_abbreviations(env, e)) return e; abbrev_state const & s = abbrev_ext::get_state(env); return replace(e, [&](expr const & e, unsigned) { if (is_constant(e) && s.is_abbreviation(const_name(e))) return some_expr(instantiate_value_univ_params(env.get(const_name(e)), const_levels(e))); else return none_expr(); }); } void initialize_abbreviation() { g_class_name = new name("abbreviations"); g_key = new std::string("abbrev"); abbrev_ext::initialize(); } void finalize_abbreviation() { abbrev_ext::finalize(); delete g_key; delete g_class_name; } } <commit_msg>feat(library/abbreviation): apply eta-reduction when expanding abbreviations<commit_after>/* Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include <string> #include "util/sstream.h" #include "kernel/find_fn.h" #include "kernel/replace_fn.h" #include "kernel/instantiate.h" #include "library/scoped_ext.h" #include "library/expr_lt.h" #include "library/util.h" #include "library/normalize.h" namespace lean { typedef pair<name, bool> abbrev_entry; struct abbrev_state { name_map<bool> m_abbrevs; rb_map<expr, name, expr_cmp_no_level_params> m_inv_map; // for pretty printer void add(environment const & env, name const & n, bool parsing_only) { declaration const & d = env.get(n); if (!d.is_definition()) throw exception(sstream() << "invalid abbreviation '" << n << "', it is not a definition"); m_abbrevs.insert(n, parsing_only); if (!parsing_only) { expr v = try_eta(d.get_value()); m_inv_map.insert(v, n); } } bool is_abbreviation(name const & n) const { return m_abbrevs.contains(n); } bool is_parsing_only_abbreviation(name const & n) const { if (auto it = m_abbrevs.find(n)) return *it; else return false; } optional<name> is_abbreviated(expr const & e) const { if (auto it = m_inv_map.find(e)) return optional<name>(*it); else return optional<name>(); } }; static name * g_class_name = nullptr; static std::string * g_key = nullptr; struct abbrev_config { typedef abbrev_state state; typedef abbrev_entry entry; static void add_entry(environment const & env, io_state const &, state & s, entry const & e) { s.add(env, e.first, e.second); } static name const & get_class_name() { return *g_class_name; } static std::string const & get_serialization_key() { return *g_key; } static void write_entry(serializer & s, entry const & e) { s << e.first << e.second; } static entry read_entry(deserializer & d) { entry e; d >> e.first >> e.second; return e; } static optional<unsigned> get_fingerprint(entry const & e) { return some(e.first.hash()); } }; template class scoped_ext<abbrev_config>; typedef scoped_ext<abbrev_config> abbrev_ext; environment add_abbreviation(environment const & env, name const & n, bool parsing_only, bool persistent) { return abbrev_ext::add_entry(env, get_dummy_ios(), abbrev_entry(n, parsing_only), persistent); } bool is_abbreviation(environment const & env, name const & n) { abbrev_state const & s = abbrev_ext::get_state(env); return s.is_abbreviation(n); } bool is_parsing_only_abbreviation(environment const & env, name const & n) { abbrev_state const & s = abbrev_ext::get_state(env); return s.is_parsing_only_abbreviation(n); } optional<name> is_abbreviated(environment const & env, expr const & e) { abbrev_state const & s = abbrev_ext::get_state(env); return s.is_abbreviated(e); } bool contains_abbreviations(environment const & env, expr const & e) { abbrev_state const & s = abbrev_ext::get_state(env); return static_cast<bool>(find(e, [&](expr const & e, unsigned) { return is_constant(e) && s.is_abbreviation(const_name(e)); })); } expr expand_abbreviations(environment const & env, expr const & e) { if (!contains_abbreviations(env, e)) return e; abbrev_state const & s = abbrev_ext::get_state(env); return replace(e, [&](expr const & e, unsigned) { if (is_constant(e) && s.is_abbreviation(const_name(e))) return some_expr(try_eta(instantiate_value_univ_params(env.get(const_name(e)), const_levels(e)))); else return none_expr(); }); } void initialize_abbreviation() { g_class_name = new name("abbreviations"); g_key = new std::string("abbrev"); abbrev_ext::initialize(); } void finalize_abbreviation() { abbrev_ext::finalize(); delete g_key; delete g_class_name; } } <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // SneezyMUD - All rights reserved, SneezyMUD Coding Team // // $Log: task_trance_of_blades.cc,v $ // Revision 1.1 2000/12/22 07:12:03 dash // Initial revision // // Revision 5.1.1.1 1999/10/16 04:32:20 batopr // new branch // // Revision 5.1 1999/10/16 04:31:17 batopr // new branch // // Revision 1.1 1999/09/12 17:24:04 sneezy // Initial revision // // ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // // SneezyMUD 4.0 - All rights reserved, SneezyMUD Coding Team // "task.cc" - All functions related to tasks that keep mobs/PCs busy // ////////////////////////////////////////////////////////////////////////// #include "stdsneezy.h" void stop_trance_of_blades(TBeing *ch) { if (ch->getPosition() >= POSITION_RESTING) { act("You suddenly snap out of your trance.", FALSE, ch, 0, 0, TO_CHAR); act("$n suddenly snaps out of $s trance.", FALSE, ch, 0, 0, TO_ROOM); } ch->stopTask(); } void TBaseWeapon::tranceOfBladesPulse(TBeing *ch, TThing *) { stop_trance_of_blades(ch); return; } int task_trance_of_blades(TBeing *ch, cmdTypeT cmd, const char *, int pulse, TRoom *, TObj *) { TThing *o = NULL; // sanity check if (ch->isLinkdead() || (ch->in_room != ch->task->wasInRoom) || (ch->getPosition() < POSITION_RESTING) || !(o = ch->heldInPrimHand())) { stop_trance_of_blades(ch); return FALSE; // returning FALSE lets command be interpreted } if (ch->utilityTaskCommand(cmd) || ch->nobrainerTaskCommand(cmd)) return FALSE; switch (cmd) { case CMD_TASK_CONTINUE: ch->task->calcNextUpdate(pulse, 2 * PULSE_MOBACT); //w->sharpenPulse(ch, o); return FALSE; case CMD_ABORT: case CMD_STOP: act("You slowly come out of the trance.", FALSE, ch, o, 0, TO_CHAR); act("$n slowly comes out of $s trance.", FALSE, ch, o, 0, TO_ROOM); ch->stopTask(); break; case CMD_TASK_FIGHTING: act("Your $o becomes a blur as you concentrate on your defensive trance.", FALSE, ch, o, 0, TO_CHAR); act("$n's $o becomes a blur as $e concentrates on $s defensive trance.", FALSE, ch, o, 0, TO_ROOM); break; default: if (cmd < MAX_CMD_LIST) warn_busy(ch); break; // eat the command } return TRUE; } <commit_msg>added code for 'defensive trance' warrior skill<commit_after>////////////////////////////////////////////////////////////////////////// // // SneezyMUD - All rights reserved, SneezyMUD Coding Team // // $Log: task_trance_of_blades.cc,v $ // Revision 1.2 2000/12/27 08:27:35 dash // added code for 'defensive trance' warrior skill // // Revision 1.1 2000/12/22 07:12:03 dash // Initial revision // // ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // // SneezyMUD 4.0 - All rights reserved, SneezyMUD Coding Team // "task.cc" - All functions related to tasks that keep mobs/PCs busy // ////////////////////////////////////////////////////////////////////////// #include "stdsneezy.h" void stop_trance_of_blades(TBeing *ch) { if (ch->getPosition() >= POSITION_RESTING) { act("You suddenly snap out of your trance.", FALSE, ch, 0, 0, TO_CHAR, ANSI_RED); act("$n suddenly snaps out of $s trance.", FALSE, ch, 0, 0, TO_ROOM); } ch->stopTask(); } //void TBaseWeapon::tranceOfBladesPulse(TBeing *ch, TThing *) // { // stop_trance_of_blades(ch); // return; // } int task_trance_of_blades(TBeing *ch, cmdTypeT cmd, const char *, int pulse, TRoom *, TObj *) { TThing *o = NULL; int chance = 0; // sanity check if (ch->isLinkdead() || (ch->in_room != ch->task->wasInRoom) || (ch->getPosition() < POSITION_RESTING)) { stop_trance_of_blades(ch); return FALSE; // returning FALSE lets command be interpreted } if (ch->utilityTaskCommand(cmd) || ch->nobrainerTaskCommand(cmd)) return FALSE; switch (cmd) { case CMD_TASK_CONTINUE: ch->task->calcNextUpdate(pulse, PULSE_MOBACT); if (!(o = ch->heldInPrimHand())) { act("Loss of your weapon causes you to snap out of your trance.", FALSE, ch, 0, 0, TO_CHAR, ANSI_RED); act("Loss of $s weapon causes $n to snap out of $s trance.", FALSE, ch, 0, 0, TO_ROOM); ch->stopTask(); ch->addToWait(combatRound(2)); ch->cantHit += ch->loseRound(1); return FALSE; } if (ch->getCombatMode() == ATTACK_BERSERK) { act("Berserking causes you to snap out of your trance.", FALSE, ch, 0, 0, TO_CHAR, ANSI_RED); act("Berserking causes $n to snap out of $s trance.", FALSE, ch, 0, 0, TO_ROOM); ch->stopTask(); ch->addToWait(combatRound(2)); ch->cantHit += ch->loseRound(1); return FALSE; } if (ch->isSwimming()) { act("Sudden immersion causes you to snap out of your trance.", FALSE, ch, 0, 0, TO_CHAR, ANSI_RED); act("Sudden immersion causes $n to snap out of $s trance.", FALSE, ch, 0, 0, TO_ROOM); ch->stopTask(); ch->addToWait(combatRound(2)); ch->cantHit += ch->loseRound(1); return FALSE; } if (!ch->canUseArm(HAND_PRIMARY)) { act("Your injured arm causes you to snap out of your trance.", FALSE, ch, 0, 0, TO_CHAR), ANSI_RED; act("$n's injured arm causes $m to snap out of $s trance.", FALSE, ch, 0, 0, TO_ROOM); ch->stopTask(); ch->addToWait(combatRound(2)); ch->cantHit += ch->loseRound(1); return FALSE; } if (ch->getMove() < 30) { act("Your fatigue causes you to snap out of your trance.", FALSE, ch, 0, 0, TO_CHAR, ANSI_RED); act("$n's fatigue causes $m to snap out of $s trance.", FALSE, ch, 0, 0, TO_ROOM); ch->stopTask(); ch->addToWait(combatRound(2)); ch->cantHit += ch->loseRound(1); return FALSE; } ch->addToMove(-10); chance = 150 - ch->getSkillValue(SKILL_TRANCE_OF_BLADES); if (!(ch->attackers)) chance *= 2; chance = (int)((float) chance * ch->plotStat(STAT_CURRENT, STAT_FOC, 1.25, 0.80, 1.00)); if (chance > ::number(0,999)) { act("Your concentraion has been lost, and you snap out of your defensive trance.", FALSE, ch, 0, 0, TO_CHAR, ANSI_YELLOW); act("$n loses $s concentration and snaps out of $s defensive trance.", FALSE, ch, 0, 0, TO_ROOM, ANSI_YELLOW); ch->stopTask(); ch->addToWait(combatRound(2)); ch->cantHit += ch->loseRound(1); return FALSE; } if (!(::number(0,2)) || (ch->attackers)) act("Your focus is good and you are able to maintain your defensive trance.", FALSE, ch, 0, 0, TO_CHAR); return FALSE; case CMD_ABORT: case CMD_STOP: act("You slowly come out of your trance.", FALSE, ch, o, 0, TO_CHAR); act("$n slowly comes out of $s trance.", FALSE, ch, o, 0, TO_ROOM); ch->stopTask(); ch->addToWait(combatRound(2)); ch->cantHit += ch->loseRound(1); break; case CMD_TASK_FIGHTING: // act("Your $o becomes a blur as you concentrate on your defensive trance.", FALSE, ch, o, 0, TO_CHAR); // act("$n's $o becomes a blur as $e concentrates on $s defensive trance.", FALSE, ch, o, 0, TO_ROOM); break; default: if (cmd < MAX_CMD_LIST) warn_busy(ch); break; // eat the command } return TRUE; } <|endoftext|>
<commit_before>/******************************************************************************* * ALMA - Atacama Large Millimiter Array * (c) European Southern Observatory, 2011 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * "@(#) $Id: bulkDataNTGenReceiver.cpp,v 1.7 2012/07/16 22:34:32 bjeram Exp $" * * who when what * -------- -------- ---------------------------------------------- * bjeram 2011-04-19 created */ #include "bulkDataNTReceiverStream.h" #include "bulkDataNTCallback.h" #include <iostream> #include <ace/Get_Opt.h> #include <ace/Tokenizer_T.h> using namespace std; class TestCB: public BulkDataNTCallback { public: TestCB() { totalRcvData=0; } virtual ~TestCB() { std::cout << "Total received data for: " << getStreamName() << "#" << getFlowName() << " : " << totalRcvData << std::endl; } int cbStart(unsigned char* userParam_p, unsigned int size) { // we cannot initialize flow name and flow stream in ctor, because they are after CB object is created fn = getFlowName(); sn = getStreamName(); std::cout << "cbStart[ " << sn << "#" << fn << " ]: got a parameter: "; for(unsigned int i=0; i<size; i++) { std::cout << *(char*)(userParam_p+i); } std::cout << " of size: " << size << std::endl; return 0; } int cbReceive(unsigned char* data, unsigned int size) { std::cout << "cbReceive[ " << sn << "#" << fn << " ]: got data of size: " << size << " :"; /* for(unsigned int i=0; i<frame_p->length(); i++) { std::cout << *(char*)(frame_p->base()+i); } */ std::cout << std::endl; if (cbDealy>0) usleep(cbDealy); totalRcvData+=size; return 0; } int cbStop() { std::cout << "cbStop[ " << sn << "#" << fn << " ]" << std::endl; return 0; } static unsigned long cbDealy; private: std::string fn; ///flow Name std::string sn; ///stream name unsigned int totalRcvData; ///total size of all received data }; unsigned long TestCB::cbDealy = 0; void print_usage(char *argv[]) { cout << "Usage: " << argv[0] << " [-s streamName] -f flow1Name[,flow2Name,flow3Name...] [-d cbReceive delay(sleep) in msec] [-u unicast mode] [-m multicast address]" << endl; exit(1); } int main(int argc, char *argv[]) { char c; ReceiverFlowConfiguration flowCfg; char *streamName = "DefaultStream"; /*char unicastPortQoS[250]; unsigned int unicastPort=24000; */ list<char *> flows; // Parse the args ACE_Get_Opt get_opts (argc, argv, "s:f:d:m:u"); while(( c = get_opts()) != -1 ) { switch(c) { case 'm': { flowCfg.setMulticastAddress(get_opts.opt_arg()); break; } case 'u': { flowCfg.setEnableMulticast(false); break; } case 's': { streamName = get_opts.opt_arg(); break; } case 'f': { ACE_Tokenizer tok(get_opts.opt_arg()); tok.delimiter_replace(',', 0); for(char *p = tok.next(); p; p = tok.next()) flows.push_back(p); break; } case 'd': { TestCB::cbDealy = atoi(get_opts.opt_arg()); break; } }//case }//while if( flows.size() == 0 ) print_usage(argv); LoggingProxy m_logger(0, 0, 31, 0); LoggingProxy::init (&m_logger); ACS_CHECK_LOGGER; AcsBulkdata::BulkDataNTReceiverStream<TestCB> receiverStream(streamName); list<char *>::iterator it; for(it = flows.begin(); it != flows.end(); it++) { /* sprintf(unicastPortQoS, "<datareader_qos><unicast><value><element><receive_port>%ud</receive_port></element></value></unicast></datareader_qos>", unicastPort++); flowCfg.setDDSReceiverFlowQoS((*it), unicastPortQoS); */ BulkDataNTReceiverFlow *flow = receiverStream.createFlow((*it), flowCfg); flow->getCallback<TestCB>(); std::vector<string> flowNames = receiverStream.getFlowNames(); std::cout << "Waiting on the following " << receiverStream.getFlowNumber() << " flow(s):[ "; for(unsigned int i=0;i<flowNames.size(); i++) std::cout << flowNames[i] << " "; std::cout << "] of stream: " << streamName << std::endl; } std::cout << "Press a key to exit.." << std::endl; getchar(); } <commit_msg>added option: -n suppers printing in cbReceive<commit_after>/******************************************************************************* * ALMA - Atacama Large Millimiter Array * (c) European Southern Observatory, 2011 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * "@(#) $Id: bulkDataNTGenReceiver.cpp,v 1.8 2012/07/21 01:08:17 bjeram Exp $" * * who when what * -------- -------- ---------------------------------------------- * bjeram 2011-04-19 created */ #include "bulkDataNTReceiverStream.h" #include "bulkDataNTCallback.h" #include <iostream> #include <ace/Get_Opt.h> #include <ace/Tokenizer_T.h> using namespace std; class TestCB: public BulkDataNTCallback { public: TestCB() { totalRcvData=0; } virtual ~TestCB() { std::cout << "Total received data for: " << getStreamName() << "#" << getFlowName() << " : " << totalRcvData << std::endl; } int cbStart(unsigned char* userParam_p, unsigned int size) { // we cannot initialize flow name and flow stream in ctor, because they are after CB object is created fn = getFlowName(); sn = getStreamName(); std::cout << "cbStart[ " << sn << "#" << fn << " ]: got a parameter: "; for(unsigned int i=0; i<size; i++) { std::cout << *(char*)(userParam_p+i); } std::cout << " of size: " << size << std::endl; return 0; } int cbReceive(unsigned char* data, unsigned int size) { if (cbReceivePrint) { std::cout << "cbReceive[ " << sn << "#" << fn << " ]: got data of size: " << size << " :"; /* for(unsigned int i=0; i<frame_p->length(); i++) { std::cout << *(char*)(frame_p->base()+i); } */ std::cout << std::endl; } if (cbDealy>0) usleep(cbDealy); totalRcvData+=size; return 0; } int cbStop() { std::cout << "cbStop[ " << sn << "#" << fn << " ]" << std::endl; return 0; } static unsigned long cbDealy; static bool cbReceivePrint; private: std::string fn; ///flow Name std::string sn; ///stream name unsigned int totalRcvData; ///total size of all received data }; unsigned long TestCB::cbDealy = 0; bool TestCB::cbReceivePrint=true; void print_usage(char *argv[]) { cout << "Usage: " << argv[0] << " [-s streamName] -f flow1Name[,flow2Name,flow3Name...] [-d cbReceive delay(sleep) in msec] [-u unicast mode] [-m multicast address] [-n suppers printing in cbReceive]" << endl; exit(1); } int main(int argc, char *argv[]) { char c; ReceiverFlowConfiguration flowCfg; char *streamName = "DefaultStream"; /*char unicastPortQoS[250]; unsigned int unicastPort=24000; */ list<char *> flows; // Parse the args ACE_Get_Opt get_opts (argc, argv, "s:f:d:m:un"); while(( c = get_opts()) != -1 ) { switch(c) { case 'n': { TestCB::cbReceivePrint=false; break; } case 'm': { flowCfg.setMulticastAddress(get_opts.opt_arg()); break; } case 'u': { flowCfg.setEnableMulticast(false); break; } case 's': { streamName = get_opts.opt_arg(); break; } case 'f': { ACE_Tokenizer tok(get_opts.opt_arg()); tok.delimiter_replace(',', 0); for(char *p = tok.next(); p; p = tok.next()) flows.push_back(p); break; } case 'd': { TestCB::cbDealy = atoi(get_opts.opt_arg()); break; } }//case }//while if( flows.size() == 0 ) print_usage(argv); LoggingProxy m_logger(0, 0, 31, 0); LoggingProxy::init (&m_logger); ACS_CHECK_LOGGER; AcsBulkdata::BulkDataNTReceiverStream<TestCB> receiverStream(streamName); list<char *>::iterator it; for(it = flows.begin(); it != flows.end(); it++) { /* sprintf(unicastPortQoS, "<datareader_qos><unicast><value><element><receive_port>%ud</receive_port></element></value></unicast></datareader_qos>", unicastPort++); flowCfg.setDDSReceiverFlowQoS((*it), unicastPortQoS); */ BulkDataNTReceiverFlow *flow = receiverStream.createFlow((*it), flowCfg); flow->getCallback<TestCB>(); std::vector<string> flowNames = receiverStream.getFlowNames(); std::cout << "Waiting on the following " << receiverStream.getFlowNumber() << " flow(s):[ "; for(unsigned int i=0;i<flowNames.size(); i++) std::cout << flowNames[i] << " "; std::cout << "] of stream: " << streamName << std::endl; } std::cout << "Press a key to exit.." << std::endl; getchar(); } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * 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 _SVX_OPTINET_HXX #define _SVX_OPTINET_HXX #include <com/sun/star/lang/XMultiServiceFactory.hpp> #include <vcl/lstbox.hxx> #include <vcl/group.hxx> #include <vcl/field.hxx> #include <svtools/stdctrl.hxx> #include <svtools/svtabbx.hxx> #include <sfx2/tabdlg.hxx> #include <unotools/configitem.hxx> #ifdef _SVX_OPTINET2_CXX #include <svtools/headbar.hxx> #else class HeaderBar; #endif #include <readonlyimage.hxx> class SfxFilter; namespace svx { class SecurityOptionsDialog; } namespace lang = ::com::sun::star::lang; namespace uno = ::com::sun::star::uno; // class SvxNoSpaceEdit -------------------------------------------------- class SvxNoSpaceEdit : public Edit { private: sal_Bool bOnlyNumeric; public: SvxNoSpaceEdit(Window* pParent, ResId rResId, sal_Bool bNum = sal_False ) : Edit( pParent, rResId ), bOnlyNumeric( bNum ) {} virtual void KeyInput( const KeyEvent& rKEvent ); virtual void Modify(); }; typedef std::vector<SfxFilter*> SfxFilterPtrArr; // class SvxProxyTabPage ------------------------------------------------- class SvxProxyTabPage : public SfxTabPage { private: FixedLine aOptionGB; FixedText aProxyModeFT; ListBox aProxyModeLB; FixedText aHttpProxyFT; SvxNoSpaceEdit aHttpProxyED; FixedText aHttpPortFT; SvxNoSpaceEdit aHttpPortED; FixedText aHttpsProxyFT; SvxNoSpaceEdit aHttpsProxyED; FixedText aHttpsPortFT; SvxNoSpaceEdit aHttpsPortED; FixedText aFtpProxyFT; SvxNoSpaceEdit aFtpProxyED; FixedText aFtpPortFT; SvxNoSpaceEdit aFtpPortED; FixedText aNoProxyForFT; Edit aNoProxyForED; FixedText aNoProxyDescFT; String sFromBrowser; const rtl::OUString aProxyModePN; const rtl::OUString aHttpProxyPN; const rtl::OUString aHttpPortPN; const rtl::OUString aHttpsProxyPN; const rtl::OUString aHttpsPortPN; const rtl::OUString aFtpProxyPN; const rtl::OUString aFtpPortPN; const rtl::OUString aNoProxyDescPN; uno::Reference< uno::XInterface > m_xConfigurationUpdateAccess; #ifdef _SVX_OPTINET2_CXX void ArrangeControls_Impl(); void EnableControls_Impl(sal_Bool bEnable); void ReadConfigData_Impl(); void ReadConfigDefaults_Impl(); void RestoreConfigDefaults_Impl(); DECL_LINK( ProxyHdl_Impl, ListBox * ); DECL_LINK( LoseFocusHdl_Impl, Edit * ); #endif SvxProxyTabPage( Window* pParent, const SfxItemSet& rSet ); virtual ~SvxProxyTabPage(); public: static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet ); virtual sal_Bool FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); }; // #98647# class SvxScriptExecListBox ------------------------------------ class SvxScriptExecListBox : public ListBox { // for adding tooltips to ListBox public: SvxScriptExecListBox( Window* pParent, WinBits nStyle = WB_BORDER ) :ListBox(pParent, nStyle) {} SvxScriptExecListBox( Window* pParent, const ResId& rResId ) :ListBox(pParent, rResId) {} protected: virtual void RequestHelp( const HelpEvent& rHEvt ); }; // class SvxSecurityTabPage --------------------------------------------- class SvtSecurityOptions; class CertPathDialog; class SvxSecurityTabPage : public SfxTabPage { using TabPage::ActivatePage; using TabPage::DeactivatePage; private: FixedLine maSecurityOptionsFL; FixedInfo maSecurityOptionsFI; PushButton maSecurityOptionsPB; FixedLine maPasswordsFL; CheckBox maSavePasswordsCB; PushButton maShowConnectionsPB; CheckBox maMasterPasswordCB; FixedInfo maMasterPasswordFI; PushButton maMasterPasswordPB; FixedLine maMacroSecFL; FixedInfo maMacroSecFI; PushButton maMacroSecPB; FixedLine m_aCertPathFL; FixedInfo m_aCertPathFI; PushButton m_aCertPathPB; SvtSecurityOptions* mpSecOptions; svx::SecurityOptionsDialog* mpSecOptDlg; CertPathDialog* mpCertPathDlg; String msPasswordStoringDeactivateStr; DECL_LINK(SecurityOptionsHdl, void *); DECL_LINK(SavePasswordHdl, void* ); DECL_LINK(MasterPasswordHdl, void *); DECL_LINK(MasterPasswordCBHdl, void* ); DECL_LINK(ShowPasswordsHdl, void *); DECL_LINK(MacroSecPBHdl, void* ); DECL_LINK(CertPathPBHdl, void* ); void InitControls(); SvxSecurityTabPage( Window* pParent, const SfxItemSet& rSet ); virtual ~SvxSecurityTabPage(); protected: virtual void ActivatePage( const SfxItemSet& rSet ); virtual int DeactivatePage( SfxItemSet* pSet = 0 ); public: static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet ); virtual sal_Bool FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); }; class MozPluginTabPage : public SfxTabPage { FixedLine aMSWordGB; CheckBox aWBasicCodeCB; sal_Bool isInstalled(void); sal_Bool installPlugin(void); sal_Bool uninstallPlugin(void); MozPluginTabPage( Window* pParent, const SfxItemSet& rSet ); virtual ~MozPluginTabPage(); public: static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet ); virtual sal_Bool FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); }; struct SvxEMailTabPage_Impl; class SvxEMailTabPage : public SfxTabPage { FixedLine aMailFL; ReadOnlyImage aMailerURLFI; FixedText aMailerURLFT; Edit aMailerURLED; PushButton aMailerURLPB; String m_sDefaultFilterName; SvxEMailTabPage_Impl* pImpl; DECL_LINK( FileDialogHdl_Impl, PushButton* ) ; public: SvxEMailTabPage( Window* pParent, const SfxItemSet& rSet ); ~SvxEMailTabPage(); static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet ); virtual sal_Bool FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); }; #endif // #ifndef _SVX_OPTINET_HXX /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>remove unused SfxFilterPtrArr<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * 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 _SVX_OPTINET_HXX #define _SVX_OPTINET_HXX #include <com/sun/star/lang/XMultiServiceFactory.hpp> #include <vcl/lstbox.hxx> #include <vcl/group.hxx> #include <vcl/field.hxx> #include <svtools/stdctrl.hxx> #include <svtools/svtabbx.hxx> #include <sfx2/tabdlg.hxx> #include <unotools/configitem.hxx> #ifdef _SVX_OPTINET2_CXX #include <svtools/headbar.hxx> #else class HeaderBar; #endif #include <readonlyimage.hxx> class SfxFilter; namespace svx { class SecurityOptionsDialog; } namespace lang = ::com::sun::star::lang; namespace uno = ::com::sun::star::uno; // class SvxNoSpaceEdit -------------------------------------------------- class SvxNoSpaceEdit : public Edit { private: sal_Bool bOnlyNumeric; public: SvxNoSpaceEdit(Window* pParent, ResId rResId, sal_Bool bNum = sal_False ) : Edit( pParent, rResId ), bOnlyNumeric( bNum ) {} virtual void KeyInput( const KeyEvent& rKEvent ); virtual void Modify(); }; // class SvxProxyTabPage ------------------------------------------------- class SvxProxyTabPage : public SfxTabPage { private: FixedLine aOptionGB; FixedText aProxyModeFT; ListBox aProxyModeLB; FixedText aHttpProxyFT; SvxNoSpaceEdit aHttpProxyED; FixedText aHttpPortFT; SvxNoSpaceEdit aHttpPortED; FixedText aHttpsProxyFT; SvxNoSpaceEdit aHttpsProxyED; FixedText aHttpsPortFT; SvxNoSpaceEdit aHttpsPortED; FixedText aFtpProxyFT; SvxNoSpaceEdit aFtpProxyED; FixedText aFtpPortFT; SvxNoSpaceEdit aFtpPortED; FixedText aNoProxyForFT; Edit aNoProxyForED; FixedText aNoProxyDescFT; String sFromBrowser; const rtl::OUString aProxyModePN; const rtl::OUString aHttpProxyPN; const rtl::OUString aHttpPortPN; const rtl::OUString aHttpsProxyPN; const rtl::OUString aHttpsPortPN; const rtl::OUString aFtpProxyPN; const rtl::OUString aFtpPortPN; const rtl::OUString aNoProxyDescPN; uno::Reference< uno::XInterface > m_xConfigurationUpdateAccess; #ifdef _SVX_OPTINET2_CXX void ArrangeControls_Impl(); void EnableControls_Impl(sal_Bool bEnable); void ReadConfigData_Impl(); void ReadConfigDefaults_Impl(); void RestoreConfigDefaults_Impl(); DECL_LINK( ProxyHdl_Impl, ListBox * ); DECL_LINK( LoseFocusHdl_Impl, Edit * ); #endif SvxProxyTabPage( Window* pParent, const SfxItemSet& rSet ); virtual ~SvxProxyTabPage(); public: static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet ); virtual sal_Bool FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); }; // #98647# class SvxScriptExecListBox ------------------------------------ class SvxScriptExecListBox : public ListBox { // for adding tooltips to ListBox public: SvxScriptExecListBox( Window* pParent, WinBits nStyle = WB_BORDER ) :ListBox(pParent, nStyle) {} SvxScriptExecListBox( Window* pParent, const ResId& rResId ) :ListBox(pParent, rResId) {} protected: virtual void RequestHelp( const HelpEvent& rHEvt ); }; // class SvxSecurityTabPage --------------------------------------------- class SvtSecurityOptions; class CertPathDialog; class SvxSecurityTabPage : public SfxTabPage { using TabPage::ActivatePage; using TabPage::DeactivatePage; private: FixedLine maSecurityOptionsFL; FixedInfo maSecurityOptionsFI; PushButton maSecurityOptionsPB; FixedLine maPasswordsFL; CheckBox maSavePasswordsCB; PushButton maShowConnectionsPB; CheckBox maMasterPasswordCB; FixedInfo maMasterPasswordFI; PushButton maMasterPasswordPB; FixedLine maMacroSecFL; FixedInfo maMacroSecFI; PushButton maMacroSecPB; FixedLine m_aCertPathFL; FixedInfo m_aCertPathFI; PushButton m_aCertPathPB; SvtSecurityOptions* mpSecOptions; svx::SecurityOptionsDialog* mpSecOptDlg; CertPathDialog* mpCertPathDlg; String msPasswordStoringDeactivateStr; DECL_LINK(SecurityOptionsHdl, void *); DECL_LINK(SavePasswordHdl, void* ); DECL_LINK(MasterPasswordHdl, void *); DECL_LINK(MasterPasswordCBHdl, void* ); DECL_LINK(ShowPasswordsHdl, void *); DECL_LINK(MacroSecPBHdl, void* ); DECL_LINK(CertPathPBHdl, void* ); void InitControls(); SvxSecurityTabPage( Window* pParent, const SfxItemSet& rSet ); virtual ~SvxSecurityTabPage(); protected: virtual void ActivatePage( const SfxItemSet& rSet ); virtual int DeactivatePage( SfxItemSet* pSet = 0 ); public: static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet ); virtual sal_Bool FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); }; class MozPluginTabPage : public SfxTabPage { FixedLine aMSWordGB; CheckBox aWBasicCodeCB; sal_Bool isInstalled(void); sal_Bool installPlugin(void); sal_Bool uninstallPlugin(void); MozPluginTabPage( Window* pParent, const SfxItemSet& rSet ); virtual ~MozPluginTabPage(); public: static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet ); virtual sal_Bool FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); }; struct SvxEMailTabPage_Impl; class SvxEMailTabPage : public SfxTabPage { FixedLine aMailFL; ReadOnlyImage aMailerURLFI; FixedText aMailerURLFT; Edit aMailerURLED; PushButton aMailerURLPB; String m_sDefaultFilterName; SvxEMailTabPage_Impl* pImpl; DECL_LINK( FileDialogHdl_Impl, PushButton* ) ; public: SvxEMailTabPage( Window* pParent, const SfxItemSet& rSet ); ~SvxEMailTabPage(); static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet ); virtual sal_Bool FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); }; #endif // #ifndef _SVX_OPTINET_HXX /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" //#include "otbWrapperTypes.h" #include "itkVariableLengthVector.h" #include "otbChangeLabelImageFilter.h" #include "otbStandardWriterWatcher.h" #include "otbStatisticsXMLFileReader.h" #include "otbShiftScaleVectorImageFilter.h" #include "otbSVMImageClassificationFilter.h" #include "otbMultiToMonoChannelExtractROI.h" #include "otbImageToVectorImageCastFilter.h" namespace otb { namespace Wrapper { class ImageSVMClassifier : public Application { public: /** Standard class typedefs. */ typedef ImageSVMClassifier Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(ImageSVMClassifier, otb::Application); /** Filters typedef */ // Statistic XML file Reader typedef itk::VariableLengthVector<FloatVectorImageType::InternalPixelType> MeasurementType; typedef otb::StatisticsXMLFileReader<MeasurementType> StatisticsReader; typedef otb::ShiftScaleVectorImageFilter<FloatVectorImageType, FloatVectorImageType> RescalerType; /// Classification typedefs typedef otb::SVMImageClassificationFilter<FloatVectorImageType, UInt8ImageType> ClassificationFilterType; typedef ClassificationFilterType::Pointer ClassificationFilterPointerType; typedef ClassificationFilterType::ModelType ModelType; typedef ModelType::Pointer ModelPointerType; // Cast filter // TODO: supress that !! typedef MultiToMonoChannelExtractROI<FloatVectorImageType::InternalPixelType, UInt8ImageType::PixelType> ExtractImageFilterType; typedef ImageToVectorImageCastFilter<UInt8ImageType, FloatVectorImageType> CastImageFilterType; private: ImageSVMClassifier() { SetName("ImageSVMClassifier"); SetDescription("Perform SVM classification based a previous computed SVM model"); } virtual ~ImageSVMClassifier() { } void DoCreateParameters() { AddParameter(ParameterType_InputImage, "in", "Input Image to classify"); SetParameterDescription( "in", "Input Image to classify"); AddParameter(ParameterType_InputImage, "mask", "Input Mask to classify"); SetParameterDescription( "mask", "A mask associated with the new image to classify"); MandatoryOff("mask"); AddParameter(ParameterType_Filename, "imstat", "Image statistics file."); SetParameterDescription("imstat", "a XML file containing mean and standard deviation of input images used to train svm model."); MandatoryOff("imstat"); AddParameter(ParameterType_Filename, "svm", "SVM Model."); SetParameterDescription("svm", "An estimated SVM model previously computed"); AddParameter(ParameterType_OutputImage, "out", "Output Image"); SetParameterDescription( "out", "Output labeled image"); SetParameterOutputImagePixelType( "out", ImagePixelType_uint8); } void DoUpdateParameters() { // Nothing to do here : all parameters are independent } void DoExecute() { // Load input image FloatVectorImageType::Pointer inImage = GetParameterImage("in"); inImage->UpdateOutputInformation(); // Load svm model otbAppLogINFO("Loading SVM model"); m_ModelSVM = ModelType::New(); m_ModelSVM->LoadModel(GetParameterString("svm").c_str()); otbAppLogINFO("SVM model loaded"); // Normalize input image (optional) StatisticsReader::Pointer statisticsReader = StatisticsReader::New(); MeasurementType meanMeasurementVector; MeasurementType stddevMeasurementVector; m_Rescaler = RescalerType::New(); // Classify m_ClassificationFilter = ClassificationFilterType::New(); m_ClassificationFilter->SetModel(m_ModelSVM); // Normalize input image if asked if( HasValue("imstat") ) { otbAppLogINFO("Input image normalization activated."); // Load input image statistics statisticsReader->SetFileName(GetParameterString("imstat")); meanMeasurementVector = statisticsReader->GetStatisticVectorByName("mean"); stddevMeasurementVector = statisticsReader->GetStatisticVectorByName("stddev"); otbAppLogINFO( "mean used: " << meanMeasurementVector ); otbAppLogINFO( "standard deviation used: " << stddevMeasurementVector ); // Rescale vector image m_Rescaler->SetScale(stddevMeasurementVector); m_Rescaler->SetShift(meanMeasurementVector); m_Rescaler->SetInput(inImage); m_ClassificationFilter->SetInput(m_Rescaler->GetOutput()); } else { otbAppLogINFO("Input image normalization deactivated."); m_ClassificationFilter->SetInput(inImage); } if( HasValue("mask") ) { otbAppLogINFO("Using input mask"); // Load mask image and cast into LabeledImageType FloatVectorImageType::Pointer inMask = GetParameterImage("mask"); m_Extract = ExtractImageFilterType::New(); m_Extract->SetInput( inMask ); m_Extract->SetChannel(0); m_Extract->UpdateOutputInformation(); m_ClassificationFilter->SetInputMask(m_Extract->GetOutput()); } SetParameterOutputImage<UInt8ImageType>("out", m_ClassificationFilter->GetOutput()); } ClassificationFilterType::Pointer m_ClassificationFilter; ModelPointerType m_ModelSVM; RescalerType::Pointer m_Rescaler; ExtractImageFilterType::Pointer m_Extract; }; } } OTB_APPLICATION_EXPORT(otb::Wrapper::ImageSVMClassifier) <commit_msg>BUG: first channel of ROIextractor is 1.<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" //#include "otbWrapperTypes.h" #include "itkVariableLengthVector.h" #include "otbChangeLabelImageFilter.h" #include "otbStandardWriterWatcher.h" #include "otbStatisticsXMLFileReader.h" #include "otbShiftScaleVectorImageFilter.h" #include "otbSVMImageClassificationFilter.h" #include "otbMultiToMonoChannelExtractROI.h" #include "otbImageToVectorImageCastFilter.h" namespace otb { namespace Wrapper { class ImageSVMClassifier : public Application { public: /** Standard class typedefs. */ typedef ImageSVMClassifier Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(ImageSVMClassifier, otb::Application); /** Filters typedef */ // Statistic XML file Reader typedef itk::VariableLengthVector<FloatVectorImageType::InternalPixelType> MeasurementType; typedef otb::StatisticsXMLFileReader<MeasurementType> StatisticsReader; typedef otb::ShiftScaleVectorImageFilter<FloatVectorImageType, FloatVectorImageType> RescalerType; /// Classification typedefs typedef otb::SVMImageClassificationFilter<FloatVectorImageType, UInt8ImageType> ClassificationFilterType; typedef ClassificationFilterType::Pointer ClassificationFilterPointerType; typedef ClassificationFilterType::ModelType ModelType; typedef ModelType::Pointer ModelPointerType; // Cast filter // TODO: supress that !! typedef MultiToMonoChannelExtractROI<FloatVectorImageType::InternalPixelType, UInt8ImageType::PixelType> ExtractImageFilterType; typedef ImageToVectorImageCastFilter<UInt8ImageType, FloatVectorImageType> CastImageFilterType; private: ImageSVMClassifier() { SetName("ImageSVMClassifier"); SetDescription("Perform SVM classification based a previous computed SVM model"); } virtual ~ImageSVMClassifier() { } void DoCreateParameters() { AddParameter(ParameterType_InputImage, "in", "Input Image to classify"); SetParameterDescription( "in", "Input Image to classify"); AddParameter(ParameterType_InputImage, "mask", "Input Mask to classify"); SetParameterDescription( "mask", "A mask associated with the new image to classify"); MandatoryOff("mask"); AddParameter(ParameterType_Filename, "imstat", "Image statistics file."); SetParameterDescription("imstat", "a XML file containing mean and standard deviation of input images used to train svm model."); MandatoryOff("imstat"); AddParameter(ParameterType_Filename, "svm", "SVM Model."); SetParameterDescription("svm", "An estimated SVM model previously computed"); AddParameter(ParameterType_OutputImage, "out", "Output Image"); SetParameterDescription( "out", "Output labeled image"); SetParameterOutputImagePixelType( "out", ImagePixelType_uint8); } void DoUpdateParameters() { // Nothing to do here : all parameters are independent } void DoExecute() { // Load input image FloatVectorImageType::Pointer inImage = GetParameterImage("in"); inImage->UpdateOutputInformation(); // Load svm model otbAppLogINFO("Loading SVM model"); m_ModelSVM = ModelType::New(); m_ModelSVM->LoadModel(GetParameterString("svm").c_str()); otbAppLogINFO("SVM model loaded"); // Normalize input image (optional) StatisticsReader::Pointer statisticsReader = StatisticsReader::New(); MeasurementType meanMeasurementVector; MeasurementType stddevMeasurementVector; m_Rescaler = RescalerType::New(); // Classify m_ClassificationFilter = ClassificationFilterType::New(); m_ClassificationFilter->SetModel(m_ModelSVM); // Normalize input image if asked if( HasValue("imstat") ) { otbAppLogINFO("Input image normalization activated."); // Load input image statistics statisticsReader->SetFileName(GetParameterString("imstat")); meanMeasurementVector = statisticsReader->GetStatisticVectorByName("mean"); stddevMeasurementVector = statisticsReader->GetStatisticVectorByName("stddev"); otbAppLogINFO( "mean used: " << meanMeasurementVector ); otbAppLogINFO( "standard deviation used: " << stddevMeasurementVector ); // Rescale vector image m_Rescaler->SetScale(stddevMeasurementVector); m_Rescaler->SetShift(meanMeasurementVector); m_Rescaler->SetInput(inImage); m_ClassificationFilter->SetInput(m_Rescaler->GetOutput()); } else { otbAppLogINFO("Input image normalization deactivated."); m_ClassificationFilter->SetInput(inImage); } if( HasValue("mask") ) { otbAppLogINFO("Using input mask"); // Load mask image and cast into LabeledImageType FloatVectorImageType::Pointer inMask = GetParameterImage("mask"); m_Extract = ExtractImageFilterType::New(); m_Extract->SetInput( inMask ); m_Extract->SetChannel(1); m_Extract->UpdateOutputInformation(); m_ClassificationFilter->SetInputMask(m_Extract->GetOutput()); } SetParameterOutputImage<UInt8ImageType>("out", m_ClassificationFilter->GetOutput()); } ClassificationFilterType::Pointer m_ClassificationFilter; ModelPointerType m_ModelSVM; RescalerType::Pointer m_Rescaler; ExtractImageFilterType::Pointer m_Extract; }; } } OTB_APPLICATION_EXPORT(otb::Wrapper::ImageSVMClassifier) <|endoftext|>
<commit_before><commit_msg>[cling] Only add NullPtrChk if enabled.<commit_after><|endoftext|>
<commit_before>// Copyright 2016, Kay Hayen, mailto:[email protected] // // Part of "Nuitka", an optimizing Python compiler that is compatible and // integrates with CPython, but also works on its own. // // 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 "nuitka/prelude.h" #include "nuitka/compiled_method.h" #include "structmember.h" static PyObject *Nuitka_Method_get__doc__( struct Nuitka_MethodObject *method, void *closure ) { return INCREASE_REFCOUNT( method->m_function->m_doc ); } static PyGetSetDef Nuitka_Method_getsets[] = { { (char *)"__doc__", (getter)Nuitka_Method_get__doc__, NULL, NULL }, { NULL } }; #define OFF( x ) offsetof( struct Nuitka_MethodObject, x ) static PyMemberDef Nuitka_Method_members[] = { { (char *)"im_class", T_OBJECT, OFF( m_class ), READONLY | RESTRICTED, (char *)"the class associated with a method"}, { (char *)"im_func", T_OBJECT, OFF( m_function ), READONLY | RESTRICTED, (char *)"the function (or other callable) implementing a method" }, { (char *)"__func__", T_OBJECT, OFF( m_function ), READONLY | RESTRICTED, (char *)"the function (or other callable) implementing a method" }, { (char *)"im_self", T_OBJECT, OFF( m_object ), READONLY | RESTRICTED, (char *)"the instance to which a method is bound; None for unbound method" }, { (char *)"__self__", T_OBJECT, OFF( m_object ), READONLY | RESTRICTED, (char *)"the instance to which a method is bound; None for unbound method" }, { NULL } }; static PyObject *Nuitka_Method_reduce( struct Nuitka_MethodObject *method ) { PyErr_Format( PyExc_TypeError, "Can't pickle instancemethod objects" ); return NULL; } static PyObject *Nuitka_Method_reduce_ex( struct Nuitka_MethodObject *method, PyObject *args ) { int proto; if ( !PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto) ) { return NULL; } PyErr_Format( PyExc_TypeError, "Can't pickle instancemethod objects" ); return NULL; } static PyObject *Nuitka_Method_deepcopy( struct Nuitka_MethodObject *method, PyObject *memo ) { assert( Nuitka_Method_Check( (PyObject *)method )); static PyObject *module_copy = NULL; static PyObject *deepcopy_function = NULL; if ( module_copy == NULL ) { module_copy = PyImport_ImportModule( "copy" ); CHECK_OBJECT( module_copy ); deepcopy_function = PyObject_GetAttrString( module_copy, "deepcopy" ); CHECK_OBJECT( deepcopy_function ); } PyObject *object = PyObject_CallFunctionObjArgs( deepcopy_function, method->m_object, memo, NULL ); if (unlikely( object == NULL )) { return NULL; } return Nuitka_Method_New( method->m_function, object, method->m_class ); } static PyMethodDef Nuitka_Method_methods[] = { { "__reduce__", (PyCFunction)Nuitka_Method_reduce, METH_NOARGS, NULL }, { "__reduce_ex__", (PyCFunction)Nuitka_Method_reduce_ex, METH_VARARGS, NULL }, { "__deepcopy__", (PyCFunction)Nuitka_Method_deepcopy, METH_O, NULL }, { NULL } }; extern PyObject *const_str_plain___name__; static char const *GET_CLASS_NAME( PyObject *klass ) { if ( klass == NULL ) { return "?"; } else { #if PYTHON_VERSION < 300 if ( PyClass_Check( klass ) ) { return Nuitka_String_AsString( ((PyClassObject *)klass)->cl_name ); } #endif if ( !PyType_Check( klass ) ) { klass = (PyObject *)Py_TYPE( klass ); } return ((PyTypeObject *)klass)->tp_name; } } static char const *GET_INSTANCE_CLASS_NAME( PyObject *instance ) { // TODO: We have a constant for that already. PyObject *klass = PyObject_GetAttrString( instance, "__class__" ); // Fallback to type as this cannot fail. if ( klass == NULL ) { CLEAR_ERROR_OCCURRED(); klass = INCREASE_REFCOUNT( (PyObject *)Py_TYPE( instance ) ); } char const *result = GET_CLASS_NAME( klass ); Py_DECREF( klass ); return result; } static char const *GET_CALLABLE_DESC( PyObject *object ) { if ( Nuitka_Function_Check( object ) || Nuitka_Generator_Check( object ) || PyMethod_Check( object ) || PyFunction_Check( object ) || PyCFunction_Check( object ) ) { return "()"; } #if PYTHON_VERSION < 300 else if ( PyClass_Check( object ) ) { return " constructor"; } else if ( PyInstance_Check( object )) { return " instance"; } #endif else { return " object"; } } static char const *GET_CALLABLE_NAME( PyObject *object ) { if ( Nuitka_Function_Check( object ) ) { return Nuitka_String_AsString( Nuitka_Function_GetName( object ) ); } else if ( Nuitka_Generator_Check( object ) ) { return Nuitka_String_AsString( Nuitka_Generator_GetName( object ) ); } else if ( PyMethod_Check( object ) ) { return PyEval_GetFuncName( PyMethod_GET_FUNCTION( object ) ); } else if ( PyFunction_Check( object ) ) { return Nuitka_String_AsString( ((PyFunctionObject*)object)->func_name ); } #if PYTHON_VERSION < 300 else if ( PyInstance_Check( object ) ) { return Nuitka_String_AsString( ((PyInstanceObject*)object)->in_class->cl_name ); } else if ( PyClass_Check( object ) ) { return Nuitka_String_AsString( ((PyClassObject*)object)->cl_name ); } #endif else if ( PyCFunction_Check( object ) ) { return ((PyCFunctionObject*)object)->m_ml->ml_name; } else { return Py_TYPE( object )->tp_name; } } static PyObject *Nuitka_Method_tp_call( struct Nuitka_MethodObject *method, PyObject *args, PyObject *kw ) { Py_ssize_t arg_count = PyTuple_Size( args ); if ( method->m_object == NULL ) { if (unlikely( arg_count < 1 )) { PyErr_Format( PyExc_TypeError, "unbound compiled_method %s%s must be called with %s instance as first argument (got nothing instead)", GET_CALLABLE_NAME( (PyObject *)method->m_function ), GET_CALLABLE_DESC( (PyObject *)method->m_function ), GET_CLASS_NAME( method->m_class ) ); return NULL; } else { PyObject *self = PyTuple_GET_ITEM( args, 0 ); CHECK_OBJECT( self ); int result = PyObject_IsInstance( self, method->m_class ); if (unlikely( result < 0 )) { return NULL; } else if (unlikely( result == 0 )) { PyErr_Format( PyExc_TypeError, "unbound compiled_method %s%s must be called with %s instance as first argument (got %s instance instead)", GET_CALLABLE_NAME( (PyObject *)method->m_function ), GET_CALLABLE_DESC( (PyObject *)method->m_function ), GET_CLASS_NAME( method->m_class ), GET_INSTANCE_CLASS_NAME( (PyObject *)self ) ); return NULL; } } return Py_TYPE( method->m_function )->tp_call( (PyObject *)method->m_function, args, kw ); } else { return Nuitka_CallMethodFunctionPosArgsKwArgs( method->m_function, method->m_object, &PyTuple_GET_ITEM( args, 0 ), arg_count, kw ); } } static PyObject *Nuitka_Method_tp_descr_get( struct Nuitka_MethodObject *method, PyObject *object, PyObject *klass ) { // Don't rebind already bound methods. if ( method->m_object != NULL ) { return INCREASE_REFCOUNT( (PyObject *)method ); } if ( method->m_class != NULL && klass != NULL ) { // Quick subclass test, bound methods remain the same if the class is a sub class int result = PyObject_IsSubclass( klass, method->m_class ); if (unlikely( result < 0 )) { return NULL; } else if ( result == 0 ) { return INCREASE_REFCOUNT( (PyObject *)method ); } } return Nuitka_Method_New( method->m_function, object, klass ); } static PyObject *Nuitka_Method_tp_getattro( struct Nuitka_MethodObject *method, PyObject *name ) { PyObject *descr = _PyType_Lookup( &Nuitka_Method_Type, name ); if ( descr != NULL ) { if ( #if PYTHON_VERSION < 300 PyType_HasFeature( Py_TYPE( descr ), Py_TPFLAGS_HAVE_CLASS ) && #endif ( Py_TYPE( descr )->tp_descr_get != NULL ) ) { return Py_TYPE( descr )->tp_descr_get( descr, (PyObject *)method, (PyObject *)Py_TYPE( method ) ); } else { return INCREASE_REFCOUNT( descr ); } } return PyObject_GetAttr( (PyObject *)method->m_function, name ); } static long Nuitka_Method_tp_traverse( struct Nuitka_MethodObject *method, visitproc visit, void *arg ) { Py_VISIT( method->m_function ); Py_VISIT( method->m_object ); Py_VISIT( method->m_class ); return 0; } // tp_repr slot, decide how a function shall be output static PyObject *Nuitka_Method_tp_repr( struct Nuitka_MethodObject *method ) { if ( method->m_object == NULL ) { #if PYTHON_VERSION < 300 return PyString_FromFormat( "<unbound compiled_method %s.%s>", GET_CLASS_NAME( method->m_class ), Nuitka_String_AsString( method->m_function->m_name ) ); #else return PyUnicode_FromFormat( "<compiled_function %s at %p>", Nuitka_String_AsString( method->m_function->m_name ), method->m_function ); #endif } else { // Note: CPython uses repr ob the object, although a comment despises // it, we do it for compatibility. PyObject *object_repr = PyObject_Repr( method->m_object ); if ( object_repr == NULL ) { return NULL; } #if PYTHON_VERSION < 300 else if ( !PyString_Check( object_repr ) ) { Py_DECREF( object_repr ); return NULL; } #else else if ( !PyUnicode_Check( object_repr ) ) { Py_DECREF( object_repr ); return NULL; } #endif #if PYTHON_VERSION < 300 PyObject *result = PyString_FromFormat( "<bound compiled_method %s.%s of %s>", GET_CLASS_NAME( method->m_class ), Nuitka_String_AsString( method->m_function->m_name ), Nuitka_String_AsString_Unchecked( object_repr ) ); #elif PYTHON_VERSION < 350 PyObject *result = PyUnicode_FromFormat( "<bound compiled_method %s.%s of %s>", GET_CLASS_NAME( method->m_class ), Nuitka_String_AsString( method->m_function->m_name ), Nuitka_String_AsString_Unchecked( object_repr ) ); #else PyObject *result = PyUnicode_FromFormat( "<bound compiled_method %s of %s>", Nuitka_String_AsString( method->m_function->m_qualname ), Nuitka_String_AsString_Unchecked( object_repr ) ); #endif Py_DECREF( object_repr ); return result; } } #if PYTHON_VERSION < 300 static int Nuitka_Method_tp_compare( struct Nuitka_MethodObject *a, struct Nuitka_MethodObject *b ) { if ( a->m_function->m_counter < b->m_function->m_counter ) { return -1; } else if ( a->m_function->m_counter > b->m_function->m_counter ) { return 1; } else if ( a->m_object == b->m_object ) { return 0; } else if ( a->m_object == NULL ) { return -1; } else if ( b->m_object == NULL ) { return 1; } else { return PyObject_Compare( a->m_object, b->m_object ); } } #endif static PyObject *Nuitka_Method_tp_richcompare( struct Nuitka_MethodObject *a, struct Nuitka_MethodObject *b, int op ) { if ( op != Py_EQ && op != Py_NE ) { return INCREASE_REFCOUNT( Py_NotImplemented ); } if ( Nuitka_Method_Check( (PyObject *)a ) == false || Nuitka_Method_Check( (PyObject *)b ) == false ) { return INCREASE_REFCOUNT( Py_NotImplemented ); } bool result = a->m_function->m_counter == b->m_function->m_counter; // If the underlying function objects are the same, check the objects, which // may be NULL in case of unbound methods, which would be the same again. if ( result ) { if ( a->m_object == NULL ) { result = b->m_object == NULL; } else if ( b->m_object == NULL ) { result = 0; } else { int res = PyObject_RichCompareBool( a->m_object, b->m_object, Py_EQ ); result = res != 0; } } if ( op == Py_EQ ) { return INCREASE_REFCOUNT( BOOL_FROM( result ) ); } else { return INCREASE_REFCOUNT( BOOL_FROM( !result ) ); } } static long Nuitka_Method_tp_hash( struct Nuitka_MethodObject *method ) { // Just give the hash of the method function, that ought to be good enough. return method->m_function->m_counter; } // Cache for method object, try to avoid malloc overhead. static struct Nuitka_MethodObject *method_cache_head = NULL; static int method_cache_size = 0; static const int max_method_cache_size = 4096; static void Nuitka_Method_tp_dealloc( struct Nuitka_MethodObject *method ) { #ifndef __NUITKA_NO_ASSERT__ // Save the current exception, if any, we must to not corrupt it. PyObject *save_exception_type, *save_exception_value; PyTracebackObject *save_exception_tb; FETCH_ERROR_OCCURRED( &save_exception_type, &save_exception_value, &save_exception_tb ); RESTORE_ERROR_OCCURRED( save_exception_type, save_exception_value, save_exception_tb ); #endif Nuitka_GC_UnTrack( method ); if ( method->m_weakrefs != NULL ) { PyObject_ClearWeakRefs( (PyObject *)method ); } Py_XDECREF( method->m_object ); Py_XDECREF( method->m_class ); Py_DECREF( (PyObject *)method->m_function ); if (likely( method_cache_size < max_method_cache_size )) { method->m_object = (PyObject *)method_cache_head; method_cache_head = method; method_cache_size += 1; } else { PyObject_GC_Del( method ); } #ifndef __NUITKA_NO_ASSERT__ PyThreadState *tstate = PyThreadState_GET(); assert( tstate->curexc_type == save_exception_type ); assert( tstate->curexc_value == save_exception_value ); assert( (PyTracebackObject *)tstate->curexc_traceback == save_exception_tb ); #endif } static PyObject *Nuitka_Method_tp_new( PyTypeObject* type, PyObject* args, PyObject *kw ) { PyObject *func; PyObject *self; PyObject *klass = NULL; if ( !_PyArg_NoKeywords( "instancemethod", kw ) ) { return NULL; } else if ( !PyArg_UnpackTuple( args, "compiled_method", 2, 3, &func, &self, &klass ) ) { return NULL; } else if ( !PyCallable_Check( func ) ) { PyErr_Format( PyExc_TypeError, "first argument must be callable" ); return NULL; } else { if ( self == Py_None ) { self = NULL; } if ( self == NULL && klass == NULL ) { PyErr_Format( PyExc_TypeError, "unbound methods must have non-NULL im_class" ); return NULL; } } assert( Nuitka_Function_Check( func ) ); return Nuitka_Method_New( (struct Nuitka_FunctionObject *)func, self, klass ); } PyTypeObject Nuitka_Method_Type = { PyVarObject_HEAD_INIT(NULL, 0) "compiled_method", sizeof(struct Nuitka_MethodObject), 0, (destructor)Nuitka_Method_tp_dealloc, // tp_dealloc 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ #if PYTHON_VERSION < 300 (cmpfunc)Nuitka_Method_tp_compare, /* tp_compare */ #else 0, #endif (reprfunc)Nuitka_Method_tp_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ (hashfunc)Nuitka_Method_tp_hash, /* tp_hash */ (ternaryfunc)Nuitka_Method_tp_call, /* tp_call */ 0, /* tp_str */ (getattrofunc)Nuitka_Method_tp_getattro, /* tp_getattro */ PyObject_GenericSetAttr, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | #if PYTHON_VERSION < 300 Py_TPFLAGS_HAVE_WEAKREFS | #endif Py_TPFLAGS_HAVE_GC, /* tp_flags */ 0, /* tp_doc */ (traverseproc)Nuitka_Method_tp_traverse, /* tp_traverse */ 0, /* tp_clear */ (richcmpfunc)Nuitka_Method_tp_richcompare, /* tp_richcompare */ offsetof(struct Nuitka_MethodObject, m_weakrefs), /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ Nuitka_Method_methods, /* tp_methods */ Nuitka_Method_members, /* tp_members */ Nuitka_Method_getsets, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ (descrgetfunc)Nuitka_Method_tp_descr_get, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ Nuitka_Method_tp_new, /* tp_new */ 0, /* tp_free */ 0, /* tp_is_gc */ 0, /* tp_bases */ 0, /* tp_mro */ 0, /* tp_cache */ 0, /* tp_subclasses */ 0, /* tp_weaklist */ 0, /* tp_del */ 0 /* tp_version_tag */ #if PYTHON_VERSION >= 340 ,0 /* tp_finalizer */ #endif }; void _initCompiledMethodType( void ) { PyType_Ready( &Nuitka_Method_Type ); } PyObject *Nuitka_Method_New( struct Nuitka_FunctionObject *function, PyObject *object, PyObject *klass ) { struct Nuitka_MethodObject *result = method_cache_head; if ( result != NULL ) { method_cache_head = (struct Nuitka_MethodObject *)method_cache_head->m_object; method_cache_size -= 1; Py_TYPE( result ) = &Nuitka_Method_Type; _Py_NewReference( (PyObject *)result ); } else { result = PyObject_GC_New(struct Nuitka_MethodObject, &Nuitka_Method_Type); } if (unlikely( result == NULL )) { PyErr_Format( PyExc_RuntimeError, "cannot create method %s", Nuitka_String_AsString( function->m_name ) ); return NULL; } result->m_function = (struct Nuitka_FunctionObject *)INCREASE_REFCOUNT( (PyObject *)function ); result->m_object = object; Py_XINCREF( object ); result->m_class = klass; Py_XINCREF( klass ); result->m_weakrefs = NULL; Nuitka_GC_Track( result ); return (PyObject *)result; } <commit_msg>Delete CompiledMethodType.cpp<commit_after><|endoftext|>
<commit_before>/****************************************************************** * * Copyright 2014 Samsung Electronics All Rights Reserved. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************/ #include "QueryEngine.h" #include "DataReader.h" SSMRESULT CQueryEngine::finalConstruct() { SSMRESULT res = SSM_E_FAIL; m_cqid = 0; m_pQueryEngineEvent = NULL; SSM_CLEANUP_ASSERT(CreateInstance(OID_ITasker, (IBase **)&m_pTasker)); SSM_CLEANUP_ASSERT(CreateGlobalInstance(OID_IPropagationEngine, (IBase **)&m_pPropagationEngine)); CLEANUP: return res; } void CQueryEngine::finalRelease() { m_pQueryEngineEvent = NULL; m_mtxQueries.lock(); for (std::map<int, IConditionedQuery *>::iterator itor = m_conditionedQueries.begin(); itor != m_conditionedQueries.end(); ++itor) { itor->second->deactivateTriggers(); SAFE_RELEASE(itor->second); } for (std::map<int, CContextQuery *>::iterator itor = m_contextQueries.begin(); itor != m_contextQueries.end(); ++itor) { //Token *root = itor->second->getRoot(); //SAFE_DELETE(root); SAFE_DELETE(itor->second); } m_mtxQueries.unlock(); } SSMRESULT CQueryEngine::processQueryResult(int userTriggerId, std::vector<result_model> *result) { SSMRESULT res = SSM_E_FAIL; ModelPropertyVec modelData; std::vector<result_model> result_model_data_id; IntVec modelID; std::vector<std::string> contextName; IContextModel *temp_contextmodel = NULL; IContextModel *temp_contextmodel2 = NULL; intptr_t *pData = NULL; CDataReader *pDataReader = NULL; m_mtxQueries.lock(); if (m_contextQueries.find(userTriggerId) == m_contextQueries.end()) { SSM_CLEANUP_ASSERT(SSM_E_FAIL); } m_contextQueries[userTriggerId]->check_result_model(); m_contextQueries[userTriggerId]->return_contextName(&contextName); m_contextQueries[userTriggerId]->return_modelID(&modelID); for (unsigned int i = 0; i < modelID.size(); i++) { SSM_CLEANUP_ASSERT(m_pPropagationEngine->getContextModel(contextName.at(i), &temp_contextmodel2)); for (unsigned int j = 0 ; j < result->size() ; j++) { int data; if (result->at(j).dataId.size() <= 0) { continue; } int modelid = modelID.at(i); std::vector<int> dataid; for (unsigned int k = 0 ; k < result->at(j).dataId.size() ; k++) { SSM_CLEANUP_ASSERT(m_pPropagationEngine->getContextModel(result->at(j).modelName, &temp_contextmodel)); data = result->at(j).dataId.at(k); if (modelID.at(i) < result->at(j).modelID ) { SSM_CLEANUP_ASSERT(temp_contextmodel->getParentDataId(data, temp_contextmodel2, &data)); dataid.push_back(data); } else if (modelID.at(i) > result->at(j).modelID ) { SSM_CLEANUP_ASSERT(temp_contextmodel->getChildDataId(data, temp_contextmodel2, &dataid)); } else { dataid.push_back(data); } SAFE_RELEASE(temp_contextmodel); } m_contextQueries[userTriggerId]->integrate_result(&result_model_data_id, modelid, &dataid, temp_contextmodel2->getModelName()); } SAFE_RELEASE(temp_contextmodel2); } pDataReader = new CDataReader(); for (unsigned int i = 0; i < result_model_data_id.size(); i++) { std::vector<CModelData *> modelDataSet; for (unsigned int j = 0; j < (result_model_data_id)[i].dataId.size(); j++) { CModelData *pModelData = new CModelData(); IContextModel *pCM = NULL; ModelPropertyVec modelPropertyVec; SSM_CLEANUP_ASSERT(m_pPropagationEngine->getContextModel((result_model_data_id)[i].modelName, &pCM)); SSM_CLEANUP_ASSERT(pCM->getModelData((result_model_data_id)[i].dataId[j], &modelPropertyVec)); pModelData->setDataId((result_model_data_id)[i].dataId[j]); for (ModelPropertyVec::iterator itor = modelPropertyVec.begin(); itor != modelPropertyVec.end(); ++itor) { pModelData->addModelData(itor->propertyName, itor->propertyValue); } modelDataSet.push_back(pModelData); SAFE_RELEASE(pCM); } SSM_CLEANUP_ASSERT(pDataReader->addModelData((result_model_data_id)[i].modelName, &modelDataSet)); } pData = new intptr_t [3]; pData[0] = EVENT_TYPE_OUTER; pData[1] = userTriggerId; pData[2] = reinterpret_cast<intptr_t>(pDataReader); m_pTasker->addTask(this, (void *)pData); res = SSM_S_OK; CLEANUP: m_mtxQueries.unlock(); SAFE_RELEASE(temp_contextmodel); SAFE_RELEASE(temp_contextmodel2); return res; } SSMRESULT CQueryEngine::validateQueryResult(IConditionedQueryResult *pConditionedQueryResult, std::vector<result_model> *resultData) { SSMRESULT res = SSM_E_FAIL; IContextModel *pContextModel = NULL; IConditionedModel *pConditionedModel = NULL; for (unsigned int i = 0 ; i < pConditionedQueryResult->getConditionedModelCount() ; i++) { std::vector<int> temp_dataID; result_model temp_result; SSM_CLEANUP_ASSERT(pConditionedQueryResult->getConditionedContextModel(i, &pConditionedModel)); SSM_CLEANUP_ASSERT(pConditionedModel->getAffectedData(&temp_dataID)); if (temp_dataID.size() == 0) { break; } SSM_CLEANUP_ASSERT(pConditionedModel->getBaseContextModel(&pContextModel)); temp_result.modelID = pContextModel->getModelId(); temp_result.dataId = temp_dataID; temp_result.modelName = pContextModel->getModelName(); resultData->push_back(temp_result); SAFE_RELEASE(pConditionedModel); SAFE_RELEASE(pContextModel); } if (resultData->size() == pConditionedQueryResult->getConditionedModelCount()) { res = SSM_S_OK; } else { res = SSM_S_FALSE; } CLEANUP: SAFE_RELEASE(pConditionedModel); SAFE_RELEASE(pContextModel); return res; } SSMRESULT CQueryEngine::onConditionedQueryEvent(int userTriggerId, IConditionedQueryResult *pConditionedQueryResult) { SSMRESULT res = SSM_E_FAIL; std::vector<result_model> result; SSM_CLEANUP_ASSERT(validateQueryResult(pConditionedQueryResult, &result)); SSM_CLEANUP_ASSERT(processQueryResult(userTriggerId, &result)); CLEANUP: return res; } void CQueryEngine::onExecute(void *pArg) { intptr_t *pData = (intptr_t *)pArg; switch (pData[0]) { case EVENT_TYPE_INNER: processQueryResult(pData[1], (std::vector<result_model> *)pData[2]); break; case EVENT_TYPE_OUTER: if (m_pQueryEngineEvent != NULL) { m_pQueryEngineEvent->onQueryEngineEvent(pData[1], (IDataReader *)pData[2]); } break; default: break; } } void CQueryEngine::onTerminate(void *pArg) { intptr_t *pData = (intptr_t *)pArg; std::vector<result_model> *pResult = NULL; CDataReader *pDataReader = NULL; switch (pData[0]) { case EVENT_TYPE_INNER: pResult = (std::vector<result_model> *)pData[2]; SAFE_DELETE(pResult); break; case EVENT_TYPE_OUTER: pDataReader = (CDataReader *)pData[2]; SAFE_DELETE(pDataReader); break; default: break; } SAFE_ARRAY_DELETE(pData); } SSMRESULT CQueryEngine::executeContextQuery(std::string contextQuery, int *cqid) { SSMRESULT res = SSM_E_FAIL; IConditionedQuery *pConditionedQuery = NULL; IConditionedQueryResult *pConditionedQueryResult = NULL; QueryCondition queryConditions; CContextQuery *clsContextQuery = NULL; Token token; CCQLParser cqlParser; IContextModel::ActivationType queryCommandType; if (!cqlParser.parse(contextQuery, &token)) { SSM_CLEANUP_ASSERT(SSM_E_FAIL); } if (!cqlParser.check_grammer(&token)) { SSM_CLEANUP_ASSERT(SSM_E_FAIL); } clsContextQuery = new CContextQuery(); SSM_CLEANUP_NULL_ASSERT(clsContextQuery); SSM_CLEANUP_ASSERT(clsContextQuery->initialize(token)); clsContextQuery->make_QueryCondition(&queryConditions); if (CCQLParser::tolower(token.child_token[0].name) == "subscribe") { queryCommandType = IContextModel::ACTIVATION_TYPE_SUBSCRIBE; } else { queryCommandType = IContextModel::ACTIVATION_TYPE_GET; } SSM_CLEANUP_ASSERT(m_pPropagationEngine->createConditionedQuery(queryCommandType, &queryConditions, this, &pConditionedQuery)); m_mtxQueries.lock(); pConditionedQuery->addRef(); m_conditionedQueries[m_cqid] = pConditionedQuery; m_contextQueries[m_cqid] = clsContextQuery; m_mtxQueries.unlock(); if (pConditionedQuery->hasAllConditionedModels() == true) { std::vector<result_model> *pResult = NULL; SSM_CLEANUP_ASSERT(pConditionedQuery->getConditionedQueryResult(&pConditionedQueryResult)); pResult = new std::vector<result_model>(); if (validateQueryResult(pConditionedQueryResult, pResult) == SSM_S_OK) { //We have valid data, let's deliver to application. intptr_t *pData = new intptr_t [3]; pData[0] = EVENT_TYPE_INNER; pData[1] = m_cqid; pData[2] = reinterpret_cast<intptr_t>(pResult); m_pTasker->addTask(this, (void *)pData); } else { SAFE_DELETE(pResult); if (queryCommandType == IContextModel::ACTIVATION_TYPE_GET) { //There is no valid data. let's request new one SSM_CLEANUP_ASSERT(pConditionedQuery->activateTriggers(m_cqid)); } } } else { if (queryCommandType == IContextModel::ACTIVATION_TYPE_GET) { //There is no models such name SSM_CLEANUP_ASSERT(SSM_E_FAIL); } } //Every subscribe command must request new data to models if (queryCommandType == IContextModel::ACTIVATION_TYPE_SUBSCRIBE) { SSM_CLEANUP_ASSERT(pConditionedQuery->activateTriggers(m_cqid)); } *cqid = m_cqid++; CLEANUP: SAFE_RELEASE(pConditionedQuery); SAFE_RELEASE(pConditionedQueryResult); return res; } //TODO: Registration with multiple instance support SSMRESULT CQueryEngine::registerQueryEvent(IQueryEngineEvent *pQueryEngineEvent) { m_pQueryEngineEvent = pQueryEngineEvent; return SSM_S_OK; } SSMRESULT CQueryEngine::unregisterQueryEvent(IQueryEngineEvent *pQueryEngineEvent) { if (m_pQueryEngineEvent == pQueryEngineEvent) { m_pQueryEngineEvent = NULL; return SSM_S_OK; } return SSM_E_FAIL; } SSMRESULT CQueryEngine::killContextQuery(int cqid) { SSMRESULT res = SSM_E_FAIL; std::map<int, IConditionedQuery *>::iterator itorConditionedQueries; std::map<int, CContextQuery *>::iterator itorContextQuries; m_mtxQueries.lock(); itorConditionedQueries = m_conditionedQueries.find(cqid); itorContextQuries = m_contextQueries.find(cqid); if (itorConditionedQueries != m_conditionedQueries.end()) { SSM_CLEANUP_ASSERT(itorConditionedQueries->second->deactivateTriggers()); itorConditionedQueries->second->release(); m_conditionedQueries.erase(itorConditionedQueries); } if (itorContextQuries != m_contextQueries.end()) { SAFE_DELETE(itorContextQuries->second); m_contextQueries.erase(itorContextQuries); } CLEANUP: m_mtxQueries.unlock(); return res; } <commit_msg>Fix memory leak in SSM QueryEngine<commit_after>/****************************************************************** * * Copyright 2014 Samsung Electronics All Rights Reserved. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************/ #include "QueryEngine.h" #include "DataReader.h" SSMRESULT CQueryEngine::finalConstruct() { SSMRESULT res = SSM_E_FAIL; m_cqid = 0; m_pQueryEngineEvent = NULL; SSM_CLEANUP_ASSERT(CreateInstance(OID_ITasker, (IBase **)&m_pTasker)); SSM_CLEANUP_ASSERT(CreateGlobalInstance(OID_IPropagationEngine, (IBase **)&m_pPropagationEngine)); CLEANUP: return res; } void CQueryEngine::finalRelease() { m_pQueryEngineEvent = NULL; m_mtxQueries.lock(); for (std::map<int, IConditionedQuery *>::iterator itor = m_conditionedQueries.begin(); itor != m_conditionedQueries.end(); ++itor) { itor->second->deactivateTriggers(); SAFE_RELEASE(itor->second); } for (std::map<int, CContextQuery *>::iterator itor = m_contextQueries.begin(); itor != m_contextQueries.end(); ++itor) { //Token *root = itor->second->getRoot(); //SAFE_DELETE(root); SAFE_DELETE(itor->second); } m_mtxQueries.unlock(); } SSMRESULT CQueryEngine::processQueryResult(int userTriggerId, std::vector<result_model> *result) { SSMRESULT res = SSM_E_FAIL; ModelPropertyVec modelData; std::vector<result_model> result_model_data_id; IntVec modelID; std::vector<std::string> contextName; IContextModel *temp_contextmodel = NULL; IContextModel *temp_contextmodel2 = NULL; intptr_t *pData = NULL; CDataReader *pDataReader = NULL; m_mtxQueries.lock(); if (m_contextQueries.find(userTriggerId) == m_contextQueries.end()) { SSM_CLEANUP_ASSERT(SSM_E_FAIL); } m_contextQueries[userTriggerId]->check_result_model(); m_contextQueries[userTriggerId]->return_contextName(&contextName); m_contextQueries[userTriggerId]->return_modelID(&modelID); for (unsigned int i = 0; i < modelID.size(); i++) { SSM_CLEANUP_ASSERT(m_pPropagationEngine->getContextModel(contextName.at(i), &temp_contextmodel2)); for (unsigned int j = 0 ; j < result->size() ; j++) { int data; if (result->at(j).dataId.size() <= 0) { continue; } int modelid = modelID.at(i); std::vector<int> dataid; for (unsigned int k = 0 ; k < result->at(j).dataId.size() ; k++) { SSM_CLEANUP_ASSERT(m_pPropagationEngine->getContextModel(result->at(j).modelName, &temp_contextmodel)); data = result->at(j).dataId.at(k); if (modelID.at(i) < result->at(j).modelID ) { SSM_CLEANUP_ASSERT(temp_contextmodel->getParentDataId(data, temp_contextmodel2, &data)); dataid.push_back(data); } else if (modelID.at(i) > result->at(j).modelID ) { SSM_CLEANUP_ASSERT(temp_contextmodel->getChildDataId(data, temp_contextmodel2, &dataid)); } else { dataid.push_back(data); } SAFE_RELEASE(temp_contextmodel); } m_contextQueries[userTriggerId]->integrate_result(&result_model_data_id, modelid, &dataid, temp_contextmodel2->getModelName()); } SAFE_RELEASE(temp_contextmodel2); } pDataReader = new CDataReader(); for (unsigned int i = 0; i < result_model_data_id.size(); i++) { std::vector<CModelData *> modelDataSet; for (unsigned int j = 0; j < (result_model_data_id)[i].dataId.size(); j++) { CModelData *pModelData = NULL; IContextModel *pCM = NULL; ModelPropertyVec modelPropertyVec; SSM_CLEANUP_ASSERT(m_pPropagationEngine->getContextModel((result_model_data_id)[i].modelName, &pCM)); SSM_CLEANUP_ASSERT(pCM->getModelData((result_model_data_id)[i].dataId[j], &modelPropertyVec)); pModelData = new CModelData(); pModelData->setDataId((result_model_data_id)[i].dataId[j]); for (ModelPropertyVec::iterator itor = modelPropertyVec.begin(); itor != modelPropertyVec.end(); ++itor) { pModelData->addModelData(itor->propertyName, itor->propertyValue); } modelDataSet.push_back(pModelData); SAFE_RELEASE(pCM); } SSM_CLEANUP_ASSERT(pDataReader->addModelData((result_model_data_id)[i].modelName, &modelDataSet)); } pData = new intptr_t [3]; pData[0] = EVENT_TYPE_OUTER; pData[1] = userTriggerId; pData[2] = reinterpret_cast<intptr_t>(pDataReader); m_pTasker->addTask(this, (void *)pData); res = SSM_S_OK; CLEANUP: m_mtxQueries.unlock(); SAFE_RELEASE(temp_contextmodel); SAFE_RELEASE(temp_contextmodel2); return res; } SSMRESULT CQueryEngine::validateQueryResult(IConditionedQueryResult *pConditionedQueryResult, std::vector<result_model> *resultData) { SSMRESULT res = SSM_E_FAIL; IContextModel *pContextModel = NULL; IConditionedModel *pConditionedModel = NULL; for (unsigned int i = 0 ; i < pConditionedQueryResult->getConditionedModelCount() ; i++) { std::vector<int> temp_dataID; result_model temp_result; SSM_CLEANUP_ASSERT(pConditionedQueryResult->getConditionedContextModel(i, &pConditionedModel)); SSM_CLEANUP_ASSERT(pConditionedModel->getAffectedData(&temp_dataID)); if (temp_dataID.size() == 0) { break; } SSM_CLEANUP_ASSERT(pConditionedModel->getBaseContextModel(&pContextModel)); temp_result.modelID = pContextModel->getModelId(); temp_result.dataId = temp_dataID; temp_result.modelName = pContextModel->getModelName(); resultData->push_back(temp_result); SAFE_RELEASE(pConditionedModel); SAFE_RELEASE(pContextModel); } if (resultData->size() == pConditionedQueryResult->getConditionedModelCount()) { res = SSM_S_OK; } else { res = SSM_S_FALSE; } CLEANUP: SAFE_RELEASE(pConditionedModel); SAFE_RELEASE(pContextModel); return res; } SSMRESULT CQueryEngine::onConditionedQueryEvent(int userTriggerId, IConditionedQueryResult *pConditionedQueryResult) { SSMRESULT res = SSM_E_FAIL; std::vector<result_model> result; SSM_CLEANUP_ASSERT(validateQueryResult(pConditionedQueryResult, &result)); SSM_CLEANUP_ASSERT(processQueryResult(userTriggerId, &result)); CLEANUP: return res; } void CQueryEngine::onExecute(void *pArg) { intptr_t *pData = (intptr_t *)pArg; switch (pData[0]) { case EVENT_TYPE_INNER: processQueryResult(pData[1], (std::vector<result_model> *)pData[2]); break; case EVENT_TYPE_OUTER: if (m_pQueryEngineEvent != NULL) { m_pQueryEngineEvent->onQueryEngineEvent(pData[1], (IDataReader *)pData[2]); } break; default: break; } } void CQueryEngine::onTerminate(void *pArg) { intptr_t *pData = (intptr_t *)pArg; std::vector<result_model> *pResult = NULL; CDataReader *pDataReader = NULL; switch (pData[0]) { case EVENT_TYPE_INNER: pResult = (std::vector<result_model> *)pData[2]; SAFE_DELETE(pResult); break; case EVENT_TYPE_OUTER: pDataReader = (CDataReader *)pData[2]; SAFE_DELETE(pDataReader); break; default: break; } SAFE_ARRAY_DELETE(pData); } SSMRESULT CQueryEngine::executeContextQuery(std::string contextQuery, int *cqid) { SSMRESULT res = SSM_E_FAIL; IConditionedQuery *pConditionedQuery = NULL; IConditionedQueryResult *pConditionedQueryResult = NULL; QueryCondition queryConditions; CContextQuery *clsContextQuery = NULL; Token token; CCQLParser cqlParser; IContextModel::ActivationType queryCommandType; if (!cqlParser.parse(contextQuery, &token)) { SSM_CLEANUP_ASSERT(SSM_E_FAIL); } if (!cqlParser.check_grammer(&token)) { SSM_CLEANUP_ASSERT(SSM_E_FAIL); } clsContextQuery = new CContextQuery(); SSM_CLEANUP_NULL_ASSERT(clsContextQuery); SSM_CLEANUP_ASSERT(clsContextQuery->initialize(token)); clsContextQuery->make_QueryCondition(&queryConditions); if (CCQLParser::tolower(token.child_token[0].name) == "subscribe") { queryCommandType = IContextModel::ACTIVATION_TYPE_SUBSCRIBE; } else { queryCommandType = IContextModel::ACTIVATION_TYPE_GET; } SSM_CLEANUP_ASSERT(m_pPropagationEngine->createConditionedQuery(queryCommandType, &queryConditions, this, &pConditionedQuery)); m_mtxQueries.lock(); pConditionedQuery->addRef(); m_conditionedQueries[m_cqid] = pConditionedQuery; m_contextQueries[m_cqid] = clsContextQuery; m_mtxQueries.unlock(); if (pConditionedQuery->hasAllConditionedModels() == true) { std::vector<result_model> *pResult = NULL; SSM_CLEANUP_ASSERT(pConditionedQuery->getConditionedQueryResult(&pConditionedQueryResult)); pResult = new std::vector<result_model>(); if (validateQueryResult(pConditionedQueryResult, pResult) == SSM_S_OK) { //We have valid data, let's deliver to application. intptr_t *pData = new intptr_t [3]; pData[0] = EVENT_TYPE_INNER; pData[1] = m_cqid; pData[2] = reinterpret_cast<intptr_t>(pResult); m_pTasker->addTask(this, (void *)pData); } else { SAFE_DELETE(pResult); if (queryCommandType == IContextModel::ACTIVATION_TYPE_GET) { //There is no valid data. let's request new one SSM_CLEANUP_ASSERT(pConditionedQuery->activateTriggers(m_cqid)); } } } else { if (queryCommandType == IContextModel::ACTIVATION_TYPE_GET) { //There is no models such name SSM_CLEANUP_ASSERT(SSM_E_FAIL); } } //Every subscribe command must request new data to models if (queryCommandType == IContextModel::ACTIVATION_TYPE_SUBSCRIBE) { SSM_CLEANUP_ASSERT(pConditionedQuery->activateTriggers(m_cqid)); } *cqid = m_cqid++; CLEANUP: SAFE_RELEASE(pConditionedQuery); SAFE_RELEASE(pConditionedQueryResult); return res; } //TODO: Registration with multiple instance support SSMRESULT CQueryEngine::registerQueryEvent(IQueryEngineEvent *pQueryEngineEvent) { m_pQueryEngineEvent = pQueryEngineEvent; return SSM_S_OK; } SSMRESULT CQueryEngine::unregisterQueryEvent(IQueryEngineEvent *pQueryEngineEvent) { if (m_pQueryEngineEvent == pQueryEngineEvent) { m_pQueryEngineEvent = NULL; return SSM_S_OK; } return SSM_E_FAIL; } SSMRESULT CQueryEngine::killContextQuery(int cqid) { SSMRESULT res = SSM_E_FAIL; std::map<int, IConditionedQuery *>::iterator itorConditionedQueries; std::map<int, CContextQuery *>::iterator itorContextQuries; m_mtxQueries.lock(); itorConditionedQueries = m_conditionedQueries.find(cqid); itorContextQuries = m_contextQueries.find(cqid); if (itorConditionedQueries != m_conditionedQueries.end()) { SSM_CLEANUP_ASSERT(itorConditionedQueries->second->deactivateTriggers()); itorConditionedQueries->second->release(); m_conditionedQueries.erase(itorConditionedQueries); } if (itorContextQuries != m_contextQueries.end()) { SAFE_DELETE(itorContextQuries->second); m_contextQueries.erase(itorContextQuries); } CLEANUP: m_mtxQueries.unlock(); return res; } <|endoftext|>
<commit_before>// tinygettext - A gettext replacement that works directly on .po files // Copyright (C) 2009 Ingo Ruhnke <[email protected]> // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. extern "C" { #include "../../engine/qcommon/q_shared.h" #include "../../engine/qcommon/qcommon.h" } #include <iostream> #include "log.hpp" namespace tinygettext { Log::log_callback_t Log::log_info_callback = &Log::default_log_callback; Log::log_callback_t Log::log_warning_callback = &Log::default_log_callback; Log::log_callback_t Log::log_error_callback = &Log::default_log_callback; void Log::default_log_callback(const std::string& str) { if( Cvar_VariableIntegerValue( "language_debug" ) ) { std::cerr << "tinygettext: " << str; } } void Log::set_log_info_callback(log_callback_t callback) { log_info_callback = callback; } void Log::set_log_warning_callback(log_callback_t callback) { log_warning_callback = callback; } void Log::set_log_error_callback(log_callback_t callback) { log_error_callback = callback; } Log::Log(log_callback_t callback_) : callback(callback_), out() { } Log::~Log() { callback(out.str()); } std::ostream& Log::get() { return out; } } // namespace tinygettext /* EOF */ <commit_msg>Remove qshared and qcommon from log.cpp includes<commit_after>// tinygettext - A gettext replacement that works directly on .po files // Copyright (C) 2009 Ingo Ruhnke <[email protected]> // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. extern "C" { extern int Cvar_VariableIntegerValue( const char* str ); } #include <iostream> #include "log.hpp" namespace tinygettext { Log::log_callback_t Log::log_info_callback = &Log::default_log_callback; Log::log_callback_t Log::log_warning_callback = &Log::default_log_callback; Log::log_callback_t Log::log_error_callback = &Log::default_log_callback; void Log::default_log_callback(const std::string& str) { if( Cvar_VariableIntegerValue( "language_debug" ) ) { std::cerr << "tinygettext: " << str; } } void Log::set_log_info_callback(log_callback_t callback) { log_info_callback = callback; } void Log::set_log_warning_callback(log_callback_t callback) { log_warning_callback = callback; } void Log::set_log_error_callback(log_callback_t callback) { log_error_callback = callback; } Log::Log(log_callback_t callback_) : callback(callback_), out() { } Log::~Log() { callback(out.str()); } std::ostream& Log::get() { return out; } } // namespace tinygettext /* EOF */ <|endoftext|>
<commit_before>#include "Thread/Win/MutexImpl.hh" #include "Thread/ThreadException.hh" namespace LilWrapper { MutexImpl::MutexImpl() { InitializeCriticalSection(&this->_mutex); } MutexImpl::~MutexImpl() { DeleteCriticalSection(&this->_mutex); } void MutexImpl::lock() { EnterCriticalSection(&this->_mutex); } void MutexImpl::unlock() { LeaveCriticalSection(&this->_mutex); } bool MutexImpl::trylock() { } } <commit_msg>Add trylock in Windows implementation of mutex.<commit_after>#include "Thread/Win/MutexImpl.hh" #include "Thread/ThreadException.hh" namespace LilWrapper { MutexImpl::MutexImpl() { InitializeCriticalSection(&this->_mutex); } MutexImpl::~MutexImpl() { DeleteCriticalSection(&this->_mutex); } void MutexImpl::lock() { EnterCriticalSection(&this->_mutex); } void MutexImpl::unlock() { LeaveCriticalSection(&this->_mutex); } bool MutexImpl::trylock() { return (TryEnterCriticalSection(&this->_mutex) != 0); } } <|endoftext|>
<commit_before> /*! \file \brief Compound file. \author Igor Mironchik (igor.mironchik at gmail dot com). Copyright (c) 2011-2017 Igor Mironchik 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. */ #ifndef COMPOUNDFILE__COMPOUNDFILE_HPP__INCLUDED #define COMPOUNDFILE__COMPOUNDFILE_HPP__INCLUDED // CompoundFile include. #include "compoundfile_stream_and_dir.hpp" #include "header.hpp" #include "sat.hpp" #include "msat.hpp" #include "utils.hpp" #include "compoundfile_exceptions.hpp" // Excel include. #include "../stream.hpp" // C++ include. #include <string> #include <vector> #include <fstream> #include <memory> namespace CompoundFile { // // File // //! Compound file. class File { public: explicit File( std::istream & stream, const std::string & fileName = "<custom-stream>" ); explicit File( const std::string & fileName ); ~File(); //! \return Directory entry by its name. Directory directory( const std::wstring & name ) const; //! \return is Directory entry exist by its name. bool hasDirectory(const std::wstring & name ) const; //! \return Stream in the directory. std::unique_ptr< Excel::Stream > stream( const Directory & dir ); private: //! Read stream and initialize m_dirs. void initialize( const std::string& fileName ); private: //! Inner file stream. std::ifstream m_fileStream; //! Stream. std::istream & m_stream; //! Header of the compound file. Header m_header; //! SAT. SAT m_sat; //! SSAT. SAT m_ssat; //! SecID of the first sector of the short-sector stream. SecID m_shortStreamFirstSector; //! All directories defined in the compound file. std::vector< Directory > m_dirs; }; // class File // // loadSSAT // inline SAT loadSSAT( const Header & header, std::istream & stream, const SAT & sat ) { std::vector< SecID > ssat; if( header.ssatFirstSecID() != SecID::EndOfChain ) { std::vector< SecID > chain = sat.sectors( header.ssatFirstSecID() ); for( std::vector< SecID >::const_iterator it = chain.begin(), last = chain.end(); it != last; ++it ) { stream.seekg( calcFileOffset( *it, header.sectorSize() ) ); loadSATSector( stream, ssat, header.sectorSize() ); } } return SAT( ssat ); } // loadSSAT //! Size of the dir record. static const int32_t dirRecordSize = 128; // // loadChildDir // inline bool loadChildDir( std::vector< Directory > & dirs, int32_t dirID, Stream & stream ) { if( dirID != -1 ) { stream.seek( dirID * dirRecordSize, Stream::FromBeginning ); Directory dir; dir.load( stream ); dirs.push_back( dir ); return true; } return false; } // loadChildDir // // loadChildDirectories // inline void loadChildDirectories( std::vector< Directory > & dirs, const Directory & parentDir, Stream & stream ) { if( loadChildDir( dirs, parentDir.leftChild(), stream ) ) loadChildDirectories( dirs, dirs.back(), stream ); if( loadChildDir( dirs, parentDir.rightChild(), stream ) ) loadChildDirectories( dirs, dirs.back(), stream ); } // loadChildDirectories // // File // inline File::File( std::istream & stream, const std::string & fileName ) : m_stream( stream ) { initialize( fileName ); } inline File::File( const std::string & fileName ) : m_fileStream( fileName, std::ios::in | std::ios::binary ) , m_stream( m_fileStream ) { initialize( fileName ); } inline File::~File() { m_fileStream.close(); } inline Directory File::directory( const std::wstring & name ) const { for( std::vector< Directory >::const_iterator it = m_dirs.begin(), last = m_dirs.end(); it != last; ++it ) { if( it->name() == name ) return *it; } throw Exception( std::wstring( L"There is no such directory : " ) + name ); } inline bool File::hasDirectory( const std::wstring & name ) const { for( std::vector< Directory >::const_iterator it = m_dirs.begin(), last = m_dirs.end(); it != last; ++it ) { if ( it->name() == name ) return true; } return false; } inline std::unique_ptr< Excel::Stream > File::stream( const Directory & dir ) { return std::unique_ptr< Excel::Stream > ( new Stream( m_header, m_sat, m_ssat, dir, m_shortStreamFirstSector, m_stream ) ); } inline void File::initialize( const std::string & fileName ) { if( m_stream.good() ) { m_header.load( m_stream ); MSAT msat( m_header, m_stream ); m_sat = msat.buildSAT(); m_ssat = loadSSAT( m_header, m_stream, m_sat ); Stream stream( m_header, m_sat, m_header.dirStreamSecID(), m_stream ); Directory root; root.load( stream ); m_shortStreamFirstSector = root.streamSecID(); stream.seek( root.rootNode() * dirRecordSize, Stream::FromBeginning ); Directory rootEntry; rootEntry.load( stream ); m_dirs.push_back( rootEntry ); loadChildDirectories( m_dirs, rootEntry, stream ); } else throw Exception( std::wstring( L"Unable to open file : " ) + std::wstring( fileName.cbegin(), fileName.cend() ) ); } } /* namespace CompoundFile */ #endif // COMPOUNDFILE__COMPOUNDFILE_HPP__INCLUDED <commit_msg>Update read-excel/compoundfile/compoundfile.hpp<commit_after> /*! \file \brief Compound file. \author Igor Mironchik (igor.mironchik at gmail dot com). Copyright (c) 2011-2017 Igor Mironchik 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. */ #ifndef COMPOUNDFILE__COMPOUNDFILE_HPP__INCLUDED #define COMPOUNDFILE__COMPOUNDFILE_HPP__INCLUDED // CompoundFile include. #include "compoundfile_stream_and_dir.hpp" #include "header.hpp" #include "sat.hpp" #include "msat.hpp" #include "utils.hpp" #include "compoundfile_exceptions.hpp" // Excel include. #include "../stream.hpp" // C++ include. #include <string> #include <vector> #include <fstream> #include <memory> namespace CompoundFile { // // File // //! Compound file. class File { public: explicit File( std::istream & stream, const std::string & fileName = "<custom-stream>" ); explicit File( const std::string & fileName ); ~File(); //! \return Directory entry by its name. Directory directory( const std::wstring & name ) const; //! \return is Directory entry exist by its name. bool hasDirectory(const std::wstring & name ) const; //! \return Stream in the directory. std::unique_ptr< Excel::Stream > stream( const Directory & dir ); private: //! Read stream and initialize m_dirs. void initialize( const std::string& fileName ); private: //! Inner file stream. std::ifstream m_fileStream; //! Stream. std::istream & m_stream; //! Header of the compound file. Header m_header; //! SAT. SAT m_sat; //! SSAT. SAT m_ssat; //! SecID of the first sector of the short-sector stream. SecID m_shortStreamFirstSector; //! All directories defined in the compound file. std::vector< Directory > m_dirs; }; // class File // // loadSSAT // inline SAT loadSSAT( const Header & header, std::istream & stream, const SAT & sat ) { std::vector< SecID > ssat; if( header.ssatFirstSecID() != SecID::EndOfChain ) { std::vector< SecID > chain = sat.sectors( header.ssatFirstSecID() ); for( std::vector< SecID >::const_iterator it = chain.begin(), last = chain.end(); it != last; ++it ) { stream.seekg( calcFileOffset( *it, header.sectorSize() ) ); loadSATSector( stream, ssat, header.sectorSize() ); } } return SAT( ssat ); } // loadSSAT //! Size of the dir record. static const int32_t dirRecordSize = 128; // // loadChildDir // inline bool loadChildDir( std::vector< Directory > & dirs, int32_t dirID, Stream & stream ) { if( dirID != -1 ) { stream.seek( dirID * dirRecordSize, Stream::FromBeginning ); Directory dir; dir.load( stream ); dirs.push_back( dir ); return true; } return false; } // loadChildDir // // loadChildDirectories // inline void loadChildDirectories( std::vector< Directory > & dirs, const Directory & parentDir, Stream & stream ) { if( loadChildDir( dirs, parentDir.leftChild(), stream ) ) loadChildDirectories( dirs, dirs.back(), stream ); if( loadChildDir( dirs, parentDir.rightChild(), stream ) ) loadChildDirectories( dirs, dirs.back(), stream ); } // loadChildDirectories // // File // inline File::File( std::istream & stream, const std::string & fileName ) : m_stream( stream ) { initialize( fileName ); } inline File::File( const std::string & fileName ) : m_fileStream( fileName, std::ios::in | std::ios::binary ) , m_stream( m_fileStream ) { initialize( fileName ); } inline File::~File() { m_fileStream.close(); } inline Directory File::directory( const std::wstring & name ) const { for( std::vector< Directory >::const_iterator it = m_dirs.begin(), last = m_dirs.end(); it != last; ++it ) { if( it->name() == name ) return *it; } throw Exception( std::wstring( L"There is no such directory : " ) + name ); } inline bool File::hasDirectory( const std::wstring & name ) const { for( std::vector< Directory >::const_iterator it = m_dirs.begin(), last = m_dirs.end(); it != last; ++it ) { if ( it->name() == name ) return true; } return false; } inline std::unique_ptr< Excel::Stream > File::stream( const Directory & dir ) { return std::unique_ptr< Excel::Stream > ( new Stream( m_header, m_sat, m_ssat, dir, m_shortStreamFirstSector, m_stream ) ); } inline void File::initialize( const std::string & fileName ) { if( m_stream.good() ) { m_header.load( m_stream ); MSAT msat( m_header, m_stream ); m_sat = msat.buildSAT(); m_ssat = loadSSAT( m_header, m_stream, m_sat ); Stream stream( m_header, m_sat, m_header.dirStreamSecID(), m_stream ); Directory root; root.load( stream ); m_shortStreamFirstSector = root.streamSecID(); stream.seek( root.rootNode() * dirRecordSize, Stream::FromBeginning ); Directory rootEntry; rootEntry.load( stream ); m_dirs.push_back( rootEntry ); loadChildDirectories( m_dirs, rootEntry, stream ); } else throw Exception( std::wstring( L"Unable to open file : " ) + std::wstring( fileName.cbegin(), fileName.cend() ) ); } } /* namespace CompoundFile */ #endif // COMPOUNDFILE__COMPOUNDFILE_HPP__INCLUDED <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "savefile.h" #include "qtcassert.h" #include "fileutils.h" #ifdef Q_OS_WIN # include <windows.h> #else # include <unistd.h> # include <sys/stat.h> #endif namespace Utils { QFile::Permissions SaveFile::m_umask = 0; SaveFile::SaveFile(const QString &filename) : m_finalFileName(filename), m_finalized(true), m_backup(false) { } SaveFile::~SaveFile() { QTC_ASSERT(m_finalized, rollback()); } bool SaveFile::open(OpenMode flags) { QTC_ASSERT(!m_finalFileName.isEmpty() && fileName().isEmpty(), return false); QFile ofi(m_finalFileName); // Check whether the existing file is writable if (ofi.exists() && !ofi.open(QIODevice::ReadWrite)) { setErrorString(ofi.errorString()); return false; } setAutoRemove(false); setFileTemplate(m_finalFileName); if (!QTemporaryFile::open(flags)) return false; m_finalized = false; // needs clean up in the end if (ofi.exists()) { setPermissions(ofi.permissions()); // Ignore errors } else { Permissions permAll = QFile::ReadOwner | QFile::ReadGroup | QFile::ReadOther | QFile::WriteOwner | QFile::WriteGroup | QFile::WriteOther; // set permissions with respect to the current umask setPermissions(permAll & ~m_umask); } return true; } void SaveFile::rollback() { remove(); m_finalized = true; } bool SaveFile::commit() { QTC_ASSERT(!m_finalized, return false); m_finalized = true; if (!flush()) { remove(); return false; } #ifdef Q_OS_WIN FlushFileBuffers(reinterpret_cast<HANDLE>(handle())); #elif defined(Q_OS_MAC) fsync(handle()); #else fdatasync(handle()); #endif close(); if (error() != NoError) { remove(); return false; } QString finalFileName = FileUtils::resolveSymlinks(FileName::fromString(m_finalFileName)).toString(); QString bakname = finalFileName + QLatin1Char('~'); QFile::remove(bakname); // Kill old backup QFile::rename(finalFileName, bakname); // Backup current file if (!rename(finalFileName)) { // Replace current file QFile::rename(bakname, finalFileName); // Rollback to current file return false; } if (!m_backup) QFile::remove(bakname); return true; } void SaveFile::initializeUmask() { #ifdef Q_OS_WIN m_umask = QFile::WriteGroup | QFile::WriteOther; #else // Get the current process' file creation mask (umask) // umask() is not thread safe so this has to be done by single threaded // application initialization mode_t mask = umask(0); // get current umask umask(mask); // set it back m_umask = ((mask & S_IRUSR) ? QFile::ReadOwner : QFlags<QFile::Permission>(0)) | ((mask & S_IWUSR) ? QFile::WriteOwner : QFlags<QFile::Permission>(0)) | ((mask & S_IXUSR) ? QFile::ExeOwner : QFlags<QFile::Permission>(0)) | ((mask & S_IRGRP) ? QFile::ReadGroup : QFlags<QFile::Permission>(0)) | ((mask & S_IWGRP) ? QFile::WriteGroup : QFlags<QFile::Permission>(0)) | ((mask & S_IXGRP) ? QFile::ExeGroup : QFlags<QFile::Permission>(0)) | ((mask & S_IROTH) ? QFile::ReadOther : QFlags<QFile::Permission>(0)) | ((mask & S_IWOTH) ? QFile::WriteOther : QFlags<QFile::Permission>(0)) | ((mask & S_IXOTH) ? QFile::ExeOther : QFlags<QFile::Permission>(0)); #endif } } // namespace Utils <commit_msg>Utils: Make sure we only use fdatasync() on systems that have it.<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "savefile.h" #include "qtcassert.h" #include "fileutils.h" #ifdef Q_OS_WIN # include <windows.h> #else # include <unistd.h> # include <sys/stat.h> #endif namespace Utils { QFile::Permissions SaveFile::m_umask = 0; SaveFile::SaveFile(const QString &filename) : m_finalFileName(filename), m_finalized(true), m_backup(false) { } SaveFile::~SaveFile() { QTC_ASSERT(m_finalized, rollback()); } bool SaveFile::open(OpenMode flags) { QTC_ASSERT(!m_finalFileName.isEmpty() && fileName().isEmpty(), return false); QFile ofi(m_finalFileName); // Check whether the existing file is writable if (ofi.exists() && !ofi.open(QIODevice::ReadWrite)) { setErrorString(ofi.errorString()); return false; } setAutoRemove(false); setFileTemplate(m_finalFileName); if (!QTemporaryFile::open(flags)) return false; m_finalized = false; // needs clean up in the end if (ofi.exists()) { setPermissions(ofi.permissions()); // Ignore errors } else { Permissions permAll = QFile::ReadOwner | QFile::ReadGroup | QFile::ReadOther | QFile::WriteOwner | QFile::WriteGroup | QFile::WriteOther; // set permissions with respect to the current umask setPermissions(permAll & ~m_umask); } return true; } void SaveFile::rollback() { remove(); m_finalized = true; } bool SaveFile::commit() { QTC_ASSERT(!m_finalized, return false); m_finalized = true; if (!flush()) { remove(); return false; } #ifdef Q_OS_WIN FlushFileBuffers(reinterpret_cast<HANDLE>(handle())); #elif _POSIX_SYNCHRONIZED_IO > 0 fdatasync(handle()); #else fsync(handle()); #endif close(); if (error() != NoError) { remove(); return false; } QString finalFileName = FileUtils::resolveSymlinks(FileName::fromString(m_finalFileName)).toString(); QString bakname = finalFileName + QLatin1Char('~'); QFile::remove(bakname); // Kill old backup QFile::rename(finalFileName, bakname); // Backup current file if (!rename(finalFileName)) { // Replace current file QFile::rename(bakname, finalFileName); // Rollback to current file return false; } if (!m_backup) QFile::remove(bakname); return true; } void SaveFile::initializeUmask() { #ifdef Q_OS_WIN m_umask = QFile::WriteGroup | QFile::WriteOther; #else // Get the current process' file creation mask (umask) // umask() is not thread safe so this has to be done by single threaded // application initialization mode_t mask = umask(0); // get current umask umask(mask); // set it back m_umask = ((mask & S_IRUSR) ? QFile::ReadOwner : QFlags<QFile::Permission>(0)) | ((mask & S_IWUSR) ? QFile::WriteOwner : QFlags<QFile::Permission>(0)) | ((mask & S_IXUSR) ? QFile::ExeOwner : QFlags<QFile::Permission>(0)) | ((mask & S_IRGRP) ? QFile::ReadGroup : QFlags<QFile::Permission>(0)) | ((mask & S_IWGRP) ? QFile::WriteGroup : QFlags<QFile::Permission>(0)) | ((mask & S_IXGRP) ? QFile::ExeGroup : QFlags<QFile::Permission>(0)) | ((mask & S_IROTH) ? QFile::ReadOther : QFlags<QFile::Permission>(0)) | ((mask & S_IWOTH) ? QFile::WriteOther : QFlags<QFile::Permission>(0)) | ((mask & S_IXOTH) ? QFile::ExeOther : QFlags<QFile::Permission>(0)); #endif } } // namespace Utils <|endoftext|>
<commit_before>/** * MegaMol * Copyright (c) 2009, MegaMol Dev Team * All rights reserved. */ #include "mmstd_gl/renderer/CallGetTransferFunctionGL.h" using namespace megamol::mmstd_gl; /* * view::CallGetTransferFunctionGL::CallGetTransferFunctionGL */ CallGetTransferFunctionGL::CallGetTransferFunctionGL(void) : AbstractCallGetTransferFunction(), texID(0) { // intentionally empty } /* * view::CallGetTransferFunctionGL::~CallGetTransferFunctionGL */ CallGetTransferFunctionGL::~CallGetTransferFunctionGL(void) { // intentionally empty } void CallGetTransferFunctionGL::BindConvenience( vislib_gl::graphics::gl::GLSLShader& shader, GLenum activeTexture, int textureUniform) { glEnable(GL_TEXTURE_1D); glActiveTexture(activeTexture); glBindTexture(GL_TEXTURE_1D, this->texID); glUniform1i(shader.ParameterLocation("tfTexture"), textureUniform); glUniform2fv(shader.ParameterLocation("tfRange"), 1, this->range.data()); } void CallGetTransferFunctionGL::BindConvenience( std::unique_ptr<glowl::GLSLProgram>& shader, GLenum activeTexture, int textureUniform) { BindConvenience(*shader, activeTexture, textureUniform); } void CallGetTransferFunctionGL::BindConvenience( glowl::GLSLProgram& shader, GLenum activeTexture, int textureUniform) { glEnable(GL_TEXTURE_1D); glActiveTexture(activeTexture); glBindTexture(GL_TEXTURE_1D, this->texID); shader.setUniform("tfTexture", textureUniform); glUniform2fv(shader.getUniformLocation("tfRange"), 1, this->range.data()); } void CallGetTransferFunctionGL::UnbindConvenience() { glDisable(GL_TEXTURE_1D); glBindTexture(GL_TEXTURE_1D, 0); } <commit_msg>Format fix.<commit_after>/** * MegaMol * Copyright (c) 2009, MegaMol Dev Team * All rights reserved. */ #include "mmstd_gl/renderer/CallGetTransferFunctionGL.h" using namespace megamol::mmstd_gl; /* * view::CallGetTransferFunctionGL::CallGetTransferFunctionGL */ CallGetTransferFunctionGL::CallGetTransferFunctionGL(void) : AbstractCallGetTransferFunction(), texID(0) { // intentionally empty } /* * view::CallGetTransferFunctionGL::~CallGetTransferFunctionGL */ CallGetTransferFunctionGL::~CallGetTransferFunctionGL(void) { // intentionally empty } void CallGetTransferFunctionGL::BindConvenience( vislib_gl::graphics::gl::GLSLShader& shader, GLenum activeTexture, int textureUniform) { glEnable(GL_TEXTURE_1D); glActiveTexture(activeTexture); glBindTexture(GL_TEXTURE_1D, this->texID); glUniform1i(shader.ParameterLocation("tfTexture"), textureUniform); glUniform2fv(shader.ParameterLocation("tfRange"), 1, this->range.data()); } void CallGetTransferFunctionGL::BindConvenience( std::unique_ptr<glowl::GLSLProgram>& shader, GLenum activeTexture, int textureUniform) { BindConvenience(*shader, activeTexture, textureUniform); } void CallGetTransferFunctionGL::BindConvenience(glowl::GLSLProgram& shader, GLenum activeTexture, int textureUniform) { glEnable(GL_TEXTURE_1D); glActiveTexture(activeTexture); glBindTexture(GL_TEXTURE_1D, this->texID); shader.setUniform("tfTexture", textureUniform); glUniform2fv(shader.getUniformLocation("tfRange"), 1, this->range.data()); } void CallGetTransferFunctionGL::UnbindConvenience() { glDisable(GL_TEXTURE_1D); glBindTexture(GL_TEXTURE_1D, 0); } <|endoftext|>
<commit_before>// fdp.hpp : include file containing templated C++ interfaces to fused dot product // // Copyright (C) 2017-2019 Stillwater Supercomputing, Inc. // // This file is part of the universal numbers project, which is released under an MIT Open Source license. #include <vector> namespace sw { namespace unum { // dot product: the operator vector::x[index] is limited to uint32_t, so the arguments are limited to uint32_t as well // since we do not support arbitrary posit configuration conversions, the element type of the vectors x and y are declared to be the same. // TODO: investigate if the vector<> index is always a 32bit entity? template<typename Ty> Ty dot(size_t n, const std::vector<Ty>& x, size_t incx, const std::vector<Ty>& y, size_t incy) { Ty sum_of_products = 0; size_t cnt, ix, iy; for (cnt = 0, ix = 0, iy = 0; cnt < n && ix < x.size() && iy < y.size(); ++cnt, ix += incx, iy += incy) { Ty product = x[ix] * y[iy]; sum_of_products += product; } return sum_of_products; } /// ////////////////////////////////////////////////////////////////// /// fused dot product operators /// fdp_qc fused dot product with quire continuation /// fdp_stride fused dot product with non-negative stride /// fdp fused dot product of two vectors // Fused dot product with quire continuation template<typename Qy, typename Vector> void fdp_qc(Qy& sum_of_products, size_t n, const Vector& x, size_t incx, const Vector& y, size_t incy) { size_t ix, iy; for (ix = 0, iy = 0; ix < n && iy < n; ix = ix + incx, iy = iy + incy) { sum_of_products += sw::unum::quire_mul(x[ix], y[iy]); } } // Resolved fused dot product, with the option to control capacity bits in the quire template<typename Vector, size_t capacity = 10> typename Vector::value_type fdp_stride(size_t n, const Vector& x, size_t incx, const Vector& y, size_t incy) { constexpr size_t nbits = typename Vector::value_type::nbits; constexpr size_t es = typename Vector::value_type::es; quire<nbits, es, capacity> q = 0; size_t ix, iy; for (ix = 0, iy = 0; ix < n && iy < n; ix = ix + incx, iy = iy + incy) { q += sw::unum::quire_mul(x[ix], y[iy]); if (sw::unum::_trace_quire_add) std::cout << q << '\n'; } typename Vector::value_type sum; convert(q.to_value(), sum); // one and only rounding step of the fused-dot product return sum; } // Specialized resolved fused dot product that assumes unit stride and a standard vector, // with the option to control capacity bits in the quire template<typename Vector, size_t capacity = 10> typename Vector::value_type fdp(const Vector& x, const Vector& y) { constexpr size_t nbits = typename Vector::value_type::nbits; constexpr size_t es = typename Vector::value_type::es; quire<nbits, es, capacity> q = 0; size_t ix, iy, n = size(x); for (ix = 0, iy = 0; ix < n && iy < n; ++ix, ++iy) { q += sw::unum::quire_mul(x[ix], y[iy]); } typename Vector::value_type sum; convert(q.to_value(), sum); // one and only rounding step of the fused-dot product return sum; } #ifdef BLAS_L2 // LEVEL 2 BLAS operators template<typename Ty> void matvec(const std::vector<Ty>& A, const std::vector<Ty>& x, std::vector<Ty>& b) { // preconditions size_t d = x.size(); assert(A.size() == d*d); assert(b.size() == d); for (size_t i = 0; i < d; ++i) { b[i] = 0; for (size_t j = 0; j < d; ++j) { //std::cout << "b[" << i << "] = " << b[i] << std::endl; //std::cout << "A[" << i << "][" << j << "] = " << A[i*d + j] << std::endl; //std::cout << "x[" << j << "] = " << x[j] << std::endl; b[i] = b[i] + A[i*d + j] * x[j]; } //std::cout << "b[" << i << "] = " << b[i] << std::endl; } } // leverage template parameter inference to specialize matvec to use the quire when the inputs are posit vectors template<size_t nbits, size_t es, size_t capacity = 10> void matvec(const std::vector< posit<nbits, es> >& A, const std::vector< posit<nbits, es> >& x, std::vector< posit<nbits, es> >& b) { // preconditions size_t d = x.size(); assert(A.size() == d*d); assert(b.size() == d); for (size_t i = 0; i < d; ++i) { b[i] = 0; quire<nbits, es, capacity> q; // initialized to 0 by constructor for (size_t j = 0; j < d; ++j) { q += quire_mul(A[i*d + j], x[j]); if (sw::unum::_trace_quire_add) std::cout << q << '\n'; } convert(q.to_value(), b[i]); // one and only rounding step of the fused-dot product //std::cout << "b[" << i << "] = " << b[i] << std::endl; } } #endif // BLAS_L2 #ifdef BLAS_L3 // LEVEL 3 BLAS operators // matrix-matrix multiplication template<typename Ty> void matmul(const std::vector<Ty>& A, const std::vector<Ty>& B, std::vector<Ty>& C) { // preconditions size_t d = size_t(std::sqrt(A.size())); assert(A.size() == d*d); assert(B.size() == d*d); assert(C.size() == d*d); for (size_t i = 0; i < d; ++i) { for (size_t j = 0; j < d; ++j) { C[i*d + j] = Ty(0); for (size_t k = 0; k < d; ++k) { C[i*d + j] = C[i*d + j] + A[i*d + k] * B[k*d + j]; } } } } // leverage template parameter inference to specialize matmul to use the quire when the inputs are posit vectors template<size_t nbits, size_t es, size_t capacity = 10> void matmul(const std::vector<posit<nbits,es> >& A, const std::vector< posit<nbits, es> >& B, std::vector< posit<nbits, es> >& C) { // preconditions size_t d = size_t(std::sqrt(A.size())); assert(A.size() == d*d); assert(B.size() == d*d); assert(C.size() == d*d); for (size_t i = 0; i < d; ++i) { for (size_t j = 0; j < d; ++j) { C[i*d + j] = 0; quire<nbits, es, capacity> q; // initialized to 0 by constructor for (size_t k = 0; k < d; ++k) { // C[i*d + j] = C[i*d + j] + A[i*d + k] * B[k*d + j]; q += quire_mul(A[i*d + k], B[k*d + j]); if (sw::unum::_trace_quire_add) std::cout << q << '\n'; } convert(q.to_value(), C[i*d + j]); // one and only rounding step of the fused-dot product } } } #endif // BLAS_L3 } // namespace unum } // namespace sw <commit_msg>bug fix in extracting nbits and es from abstract type<commit_after>// fdp.hpp : include file containing templated C++ interfaces to fused dot product // // Copyright (C) 2017-2019 Stillwater Supercomputing, Inc. // // This file is part of the universal numbers project, which is released under an MIT Open Source license. #include <vector> namespace sw { namespace unum { // dot product: the operator vector::x[index] is limited to uint32_t, so the arguments are limited to uint32_t as well // since we do not support arbitrary posit configuration conversions, the element type of the vectors x and y are declared to be the same. // TODO: investigate if the vector<> index is always a 32bit entity? template<typename Ty> Ty dot(size_t n, const std::vector<Ty>& x, size_t incx, const std::vector<Ty>& y, size_t incy) { Ty sum_of_products = 0; size_t cnt, ix, iy; for (cnt = 0, ix = 0, iy = 0; cnt < n && ix < x.size() && iy < y.size(); ++cnt, ix += incx, iy += incy) { Ty product = x[ix] * y[iy]; sum_of_products += product; } return sum_of_products; } /// ////////////////////////////////////////////////////////////////// /// fused dot product operators /// fdp_qc fused dot product with quire continuation /// fdp_stride fused dot product with non-negative stride /// fdp fused dot product of two vectors // Fused dot product with quire continuation template<typename Qy, typename Vector> void fdp_qc(Qy& sum_of_products, size_t n, const Vector& x, size_t incx, const Vector& y, size_t incy) { size_t ix, iy; for (ix = 0, iy = 0; ix < n && iy < n; ix = ix + incx, iy = iy + incy) { sum_of_products += sw::unum::quire_mul(x[ix], y[iy]); } } // Resolved fused dot product, with the option to control capacity bits in the quire template<typename Vector, size_t capacity = 10> typename Vector::value_type fdp_stride(size_t n, const Vector& x, size_t incx, const Vector& y, size_t incy) { constexpr size_t nbits = Vector::value_type::nbits; constexpr size_t es = Vector::value_type::es; quire<nbits, es, capacity> q = 0; size_t ix, iy; for (ix = 0, iy = 0; ix < n && iy < n; ix = ix + incx, iy = iy + incy) { q += sw::unum::quire_mul(x[ix], y[iy]); if (sw::unum::_trace_quire_add) std::cout << q << '\n'; } typename Vector::value_type sum; convert(q.to_value(), sum); // one and only rounding step of the fused-dot product return sum; } // Specialized resolved fused dot product that assumes unit stride and a standard vector, // with the option to control capacity bits in the quire template<typename Vector, size_t capacity = 10> typename Vector::value_type fdp(const Vector& x, const Vector& y) { constexpr size_t nbits = Vector::value_type::nbits; constexpr size_t es = Vector::value_type::es; quire<nbits, es, capacity> q = 0; size_t ix, iy, n = size(x); for (ix = 0, iy = 0; ix < n && iy < n; ++ix, ++iy) { q += sw::unum::quire_mul(x[ix], y[iy]); } typename Vector::value_type sum; convert(q.to_value(), sum); // one and only rounding step of the fused-dot product return sum; } #ifdef BLAS_L2 // LEVEL 2 BLAS operators template<typename Ty> void matvec(const std::vector<Ty>& A, const std::vector<Ty>& x, std::vector<Ty>& b) { // preconditions size_t d = x.size(); assert(A.size() == d*d); assert(b.size() == d); for (size_t i = 0; i < d; ++i) { b[i] = 0; for (size_t j = 0; j < d; ++j) { //std::cout << "b[" << i << "] = " << b[i] << std::endl; //std::cout << "A[" << i << "][" << j << "] = " << A[i*d + j] << std::endl; //std::cout << "x[" << j << "] = " << x[j] << std::endl; b[i] = b[i] + A[i*d + j] * x[j]; } //std::cout << "b[" << i << "] = " << b[i] << std::endl; } } // leverage template parameter inference to specialize matvec to use the quire when the inputs are posit vectors template<size_t nbits, size_t es, size_t capacity = 10> void matvec(const std::vector< posit<nbits, es> >& A, const std::vector< posit<nbits, es> >& x, std::vector< posit<nbits, es> >& b) { // preconditions size_t d = x.size(); assert(A.size() == d*d); assert(b.size() == d); for (size_t i = 0; i < d; ++i) { b[i] = 0; quire<nbits, es, capacity> q; // initialized to 0 by constructor for (size_t j = 0; j < d; ++j) { q += quire_mul(A[i*d + j], x[j]); if (sw::unum::_trace_quire_add) std::cout << q << '\n'; } convert(q.to_value(), b[i]); // one and only rounding step of the fused-dot product //std::cout << "b[" << i << "] = " << b[i] << std::endl; } } #endif // BLAS_L2 #ifdef BLAS_L3 // LEVEL 3 BLAS operators // matrix-matrix multiplication template<typename Ty> void matmul(const std::vector<Ty>& A, const std::vector<Ty>& B, std::vector<Ty>& C) { // preconditions size_t d = size_t(std::sqrt(A.size())); assert(A.size() == d*d); assert(B.size() == d*d); assert(C.size() == d*d); for (size_t i = 0; i < d; ++i) { for (size_t j = 0; j < d; ++j) { C[i*d + j] = Ty(0); for (size_t k = 0; k < d; ++k) { C[i*d + j] = C[i*d + j] + A[i*d + k] * B[k*d + j]; } } } } // leverage template parameter inference to specialize matmul to use the quire when the inputs are posit vectors template<size_t nbits, size_t es, size_t capacity = 10> void matmul(const std::vector<posit<nbits,es> >& A, const std::vector< posit<nbits, es> >& B, std::vector< posit<nbits, es> >& C) { // preconditions size_t d = size_t(std::sqrt(A.size())); assert(A.size() == d*d); assert(B.size() == d*d); assert(C.size() == d*d); for (size_t i = 0; i < d; ++i) { for (size_t j = 0; j < d; ++j) { C[i*d + j] = 0; quire<nbits, es, capacity> q; // initialized to 0 by constructor for (size_t k = 0; k < d; ++k) { // C[i*d + j] = C[i*d + j] + A[i*d + k] * B[k*d + j]; q += quire_mul(A[i*d + k], B[k*d + j]); if (sw::unum::_trace_quire_add) std::cout << q << '\n'; } convert(q.to_value(), C[i*d + j]); // one and only rounding step of the fused-dot product } } } #endif // BLAS_L3 } // namespace unum } // namespace sw <|endoftext|>
<commit_before>#ifndef __LOCAL_STORE_H #define __LOCAL_STORE_H #include <string> #include "store-api.hh" namespace nix { class Transaction; /* Nix store and database schema version. Version 1 (or 0) was Nix <= 0.7. Version 2 was Nix 0.8 and 0.8. Version 3 is Nix 0.10 and up. */ const int nixSchemaVersion = 3; extern string drvsLogDir; class LocalStore : public StoreAPI { public: /* Open the database environment. If `reserveSpace' is true, make sure that a big empty file exists in /nix/var/nix/db/reserved. If `reserveSpace' is false, delete this file if it exists. The idea is that on normal operation, the file exists; but when we run the garbage collector, it is deleted. This is to ensure that the garbage collector has a small amount of disk space available, which is required to open the Berkeley DB environment. */ LocalStore(bool reserveSpace); ~LocalStore(); /* Implementations of abstract store API methods. */ bool isValidPath(const Path & path); Substitutes querySubstitutes(const Path & srcPath); Hash queryPathHash(const Path & path); void queryReferences(const Path & path, PathSet & references); void queryReferrers(const Path & path, PathSet & referrers); Path addToStore(const Path & srcPath, bool fixed = false, bool recursive = false, string hashAlgo = "", PathFilter & filter = defaultPathFilter); Path addTextToStore(const string & suffix, const string & s, const PathSet & references); void exportPath(const Path & path, bool sign, Sink & sink); Path importPath(bool requireSignature, Source & source); void buildDerivations(const PathSet & drvPaths); void ensurePath(const Path & path); void addTempRoot(const Path & path); void addIndirectRoot(const Path & path); void syncWithGC(); Roots findRoots(); void collectGarbage(GCAction action, const PathSet & pathsToDelete, bool ignoreLiveness, PathSet & result, unsigned long long & bytesFreed); }; /* Get a transaction object. */ void createStoreTransaction(Transaction & txn); /* Copy a path recursively. */ void copyPath(const Path & src, const Path & dst); /* Register a substitute. */ void registerSubstitute(const Transaction & txn, const Path & srcPath, const Substitute & sub); /* Deregister all substitutes. */ void clearSubstitutes(); /* Register the validity of a path, i.e., that `path' exists, that the paths referenced by it exists, and in the case of an output path of a derivation, that it has been produced by a succesful execution of the derivation (or something equivalent). Also register the hash of the file system contents of the path. The hash must be a SHA-256 hash. */ void registerValidPath(const Transaction & txn, const Path & path, const Hash & hash, const PathSet & references, const Path & deriver); struct ValidPathInfo { Path path; Path deriver; Hash hash; PathSet references; }; typedef list<ValidPathInfo> ValidPathInfos; void registerValidPaths(const Transaction & txn, const ValidPathInfos & infos); /* "Fix", or canonicalise, the meta-data of the files in a store path after it has been built. In particular: - the last modification date on each file is set to 0 (i.e., 00:00:00 1/1/1970 UTC) - the permissions are set of 444 or 555 (i.e., read-only with or without execute permission; setuid bits etc. are cleared) - the owner and group are set to the Nix user and group, if we're in a setuid Nix installation. */ void canonicalisePathMetaData(const Path & path); /* Checks whether a path is valid. */ bool isValidPathTxn(const Transaction & txn, const Path & path); /* Sets the set of outgoing FS references for a store path. Use with care! */ void setReferences(const Transaction & txn, const Path & path, const PathSet & references); /* Sets the deriver of a store path. Use with care! */ void setDeriver(const Transaction & txn, const Path & path, const Path & deriver); /* Query the deriver of a store path. Return the empty string if no deriver has been set. */ Path queryDeriver(const Transaction & txn, const Path & path); /* Delete a value from the nixStore directory. */ void deleteFromStore(const Path & path, unsigned long long & bytesFreed); MakeError(PathInUse, Error); void verifyStore(bool checkContents); /* Whether we are in build users mode. */ bool haveBuildUsers(); /* Whether we are root. */ bool amPrivileged(); /* Recursively change the ownership of `path' to the current uid. */ void getOwnership(const Path & path); /* Like deletePath(), but changes the ownership of `path' using the setuid wrapper if necessary (and possible). */ void deletePathWrapped(const Path & path, unsigned long long & bytesFreed); void deletePathWrapped(const Path & path); } #endif /* !__LOCAL_STORE_H */ <commit_msg>* Typo (reported by Marc Weber).<commit_after>#ifndef __LOCAL_STORE_H #define __LOCAL_STORE_H #include <string> #include "store-api.hh" namespace nix { class Transaction; /* Nix store and database schema version. Version 1 (or 0) was Nix <= 0.7. Version 2 was Nix 0.8 and 0.9. Version 3 is Nix 0.10 and up. */ const int nixSchemaVersion = 3; extern string drvsLogDir; class LocalStore : public StoreAPI { public: /* Open the database environment. If `reserveSpace' is true, make sure that a big empty file exists in /nix/var/nix/db/reserved. If `reserveSpace' is false, delete this file if it exists. The idea is that on normal operation, the file exists; but when we run the garbage collector, it is deleted. This is to ensure that the garbage collector has a small amount of disk space available, which is required to open the Berkeley DB environment. */ LocalStore(bool reserveSpace); ~LocalStore(); /* Implementations of abstract store API methods. */ bool isValidPath(const Path & path); Substitutes querySubstitutes(const Path & srcPath); Hash queryPathHash(const Path & path); void queryReferences(const Path & path, PathSet & references); void queryReferrers(const Path & path, PathSet & referrers); Path addToStore(const Path & srcPath, bool fixed = false, bool recursive = false, string hashAlgo = "", PathFilter & filter = defaultPathFilter); Path addTextToStore(const string & suffix, const string & s, const PathSet & references); void exportPath(const Path & path, bool sign, Sink & sink); Path importPath(bool requireSignature, Source & source); void buildDerivations(const PathSet & drvPaths); void ensurePath(const Path & path); void addTempRoot(const Path & path); void addIndirectRoot(const Path & path); void syncWithGC(); Roots findRoots(); void collectGarbage(GCAction action, const PathSet & pathsToDelete, bool ignoreLiveness, PathSet & result, unsigned long long & bytesFreed); }; /* Get a transaction object. */ void createStoreTransaction(Transaction & txn); /* Copy a path recursively. */ void copyPath(const Path & src, const Path & dst); /* Register a substitute. */ void registerSubstitute(const Transaction & txn, const Path & srcPath, const Substitute & sub); /* Deregister all substitutes. */ void clearSubstitutes(); /* Register the validity of a path, i.e., that `path' exists, that the paths referenced by it exists, and in the case of an output path of a derivation, that it has been produced by a succesful execution of the derivation (or something equivalent). Also register the hash of the file system contents of the path. The hash must be a SHA-256 hash. */ void registerValidPath(const Transaction & txn, const Path & path, const Hash & hash, const PathSet & references, const Path & deriver); struct ValidPathInfo { Path path; Path deriver; Hash hash; PathSet references; }; typedef list<ValidPathInfo> ValidPathInfos; void registerValidPaths(const Transaction & txn, const ValidPathInfos & infos); /* "Fix", or canonicalise, the meta-data of the files in a store path after it has been built. In particular: - the last modification date on each file is set to 0 (i.e., 00:00:00 1/1/1970 UTC) - the permissions are set of 444 or 555 (i.e., read-only with or without execute permission; setuid bits etc. are cleared) - the owner and group are set to the Nix user and group, if we're in a setuid Nix installation. */ void canonicalisePathMetaData(const Path & path); /* Checks whether a path is valid. */ bool isValidPathTxn(const Transaction & txn, const Path & path); /* Sets the set of outgoing FS references for a store path. Use with care! */ void setReferences(const Transaction & txn, const Path & path, const PathSet & references); /* Sets the deriver of a store path. Use with care! */ void setDeriver(const Transaction & txn, const Path & path, const Path & deriver); /* Query the deriver of a store path. Return the empty string if no deriver has been set. */ Path queryDeriver(const Transaction & txn, const Path & path); /* Delete a value from the nixStore directory. */ void deleteFromStore(const Path & path, unsigned long long & bytesFreed); MakeError(PathInUse, Error); void verifyStore(bool checkContents); /* Whether we are in build users mode. */ bool haveBuildUsers(); /* Whether we are root. */ bool amPrivileged(); /* Recursively change the ownership of `path' to the current uid. */ void getOwnership(const Path & path); /* Like deletePath(), but changes the ownership of `path' using the setuid wrapper if necessary (and possible). */ void deletePathWrapped(const Path & path, unsigned long long & bytesFreed); void deletePathWrapped(const Path & path); } #endif /* !__LOCAL_STORE_H */ <|endoftext|>
<commit_before>#include "config.hh" #include "args.hh" #include <sstream> #include <gtest/gtest.h> #include <nlohmann/json.hpp> namespace nix { /* ---------------------------------------------------------------------------- * Config * --------------------------------------------------------------------------*/ TEST(Config, setUndefinedSetting) { Config config; ASSERT_EQ(config.set("undefined-key", "value"), false); } TEST(Config, setDefinedSetting) { Config config; std::string value; Setting<std::string> foo{&config, value, "name-of-the-setting", "description"}; ASSERT_EQ(config.set("name-of-the-setting", "value"), true); } TEST(Config, getDefinedSetting) { Config config; std::string value; std::map<std::string, Config::SettingInfo> settings; Setting<std::string> foo{&config, value, "name-of-the-setting", "description"}; config.getSettings(settings, /* overridenOnly = */ false); const auto iter = settings.find("name-of-the-setting"); ASSERT_NE(iter, settings.end()); ASSERT_EQ(iter->second.value, ""); ASSERT_EQ(iter->second.description, "description\n"); } TEST(Config, getDefinedOverridenSettingNotSet) { Config config; std::string value; std::map<std::string, Config::SettingInfo> settings; Setting<std::string> foo{&config, value, "name-of-the-setting", "description"}; config.getSettings(settings, /* overridenOnly = */ true); const auto e = settings.find("name-of-the-setting"); ASSERT_EQ(e, settings.end()); } TEST(Config, getDefinedSettingSet1) { Config config; std::string value; std::map<std::string, Config::SettingInfo> settings; Setting<std::string> setting{&config, value, "name-of-the-setting", "description"}; setting.assign("value"); config.getSettings(settings, /* overridenOnly = */ false); const auto iter = settings.find("name-of-the-setting"); ASSERT_NE(iter, settings.end()); ASSERT_EQ(iter->second.value, "value"); ASSERT_EQ(iter->second.description, "description\n"); } TEST(Config, getDefinedSettingSet2) { Config config; std::map<std::string, Config::SettingInfo> settings; Setting<std::string> setting{&config, "", "name-of-the-setting", "description"}; ASSERT_TRUE(config.set("name-of-the-setting", "value")); config.getSettings(settings, /* overridenOnly = */ false); const auto e = settings.find("name-of-the-setting"); ASSERT_NE(e, settings.end()); ASSERT_EQ(e->second.value, "value"); ASSERT_EQ(e->second.description, "description\n"); } TEST(Config, addSetting) { class TestSetting : public AbstractSetting { public: TestSetting() : AbstractSetting("test", "test", {}) {} void set(const std::string & value) {} std::string to_string() const { return {}; } }; Config config; TestSetting setting; ASSERT_FALSE(config.set("test", "value")); config.addSetting(&setting); ASSERT_TRUE(config.set("test", "value")); } TEST(Config, withInitialValue) { const StringMap initials = { { "key", "value" }, }; Config config(initials); { std::map<std::string, Config::SettingInfo> settings; config.getSettings(settings, /* overridenOnly = */ false); ASSERT_EQ(settings.find("key"), settings.end()); } Setting<std::string> setting{&config, "default-value", "key", "description"}; { std::map<std::string, Config::SettingInfo> settings; config.getSettings(settings, /* overridenOnly = */ false); ASSERT_EQ(settings["key"].value, "value"); } } TEST(Config, resetOverriden) { Config config; config.resetOverriden(); } TEST(Config, resetOverridenWithSetting) { Config config; Setting<std::string> setting{&config, "", "name-of-the-setting", "description"}; { std::map<std::string, Config::SettingInfo> settings; setting.set("foo"); ASSERT_EQ(setting.get(), "foo"); config.getSettings(settings, /* overridenOnly = */ true); ASSERT_TRUE(settings.empty()); } { std::map<std::string, Config::SettingInfo> settings; setting.override("bar"); ASSERT_TRUE(setting.overriden); ASSERT_EQ(setting.get(), "bar"); config.getSettings(settings, /* overridenOnly = */ true); ASSERT_FALSE(settings.empty()); } { std::map<std::string, Config::SettingInfo> settings; config.resetOverriden(); ASSERT_FALSE(setting.overriden); config.getSettings(settings, /* overridenOnly = */ true); ASSERT_TRUE(settings.empty()); } } TEST(Config, toJSONOnEmptyConfig) { ASSERT_EQ(Config().toJSON().dump(), "{}"); } TEST(Config, toJSONOnNonEmptyConfig) { Config config; std::map<std::string, Config::SettingInfo> settings; Setting<std::string> setting{&config, "", "name-of-the-setting", "description"}; setting.assign("value"); ASSERT_EQ(config.toJSON().dump(), R"#({"name-of-the-setting":{"aliases":[],"description":"description\n","value":"value"}})#"); } TEST(Config, setSettingAlias) { Config config; Setting<std::string> setting{&config, "", "some-int", "best number", { "another-int" }}; ASSERT_TRUE(config.set("some-int", "1")); ASSERT_EQ(setting.get(), "1"); ASSERT_TRUE(config.set("another-int", "2")); ASSERT_EQ(setting.get(), "2"); ASSERT_TRUE(config.set("some-int", "3")); ASSERT_EQ(setting.get(), "3"); } /* FIXME: The reapplyUnknownSettings method doesn't seem to do anything * useful (these days). Whenever we add a new setting to Config the * unknown settings are always considered. In which case is this function * actually useful? Is there some way to register a Setting without calling * addSetting? */ TEST(Config, DISABLED_reapplyUnknownSettings) { Config config; ASSERT_FALSE(config.set("name-of-the-setting", "unknownvalue")); Setting<std::string> setting{&config, "default", "name-of-the-setting", "description"}; ASSERT_EQ(setting.get(), "default"); config.reapplyUnknownSettings(); ASSERT_EQ(setting.get(), "unknownvalue"); } TEST(Config, applyConfigEmpty) { Config config; std::map<std::string, Config::SettingInfo> settings; config.applyConfig(""); config.getSettings(settings); ASSERT_TRUE(settings.empty()); } TEST(Config, applyConfigEmptyWithComment) { Config config; std::map<std::string, Config::SettingInfo> settings; config.applyConfig("# just a comment"); config.getSettings(settings); ASSERT_TRUE(settings.empty()); } TEST(Config, applyConfigAssignment) { Config config; std::map<std::string, Config::SettingInfo> settings; Setting<std::string> setting{&config, "", "name-of-the-setting", "description"}; config.applyConfig( "name-of-the-setting = value-from-file #useful comment\n" "# name-of-the-setting = foo\n" ); config.getSettings(settings); ASSERT_FALSE(settings.empty()); ASSERT_EQ(settings["name-of-the-setting"].value, "value-from-file"); } TEST(Config, applyConfigWithReassignedSetting) { Config config; std::map<std::string, Config::SettingInfo> settings; Setting<std::string> setting{&config, "", "name-of-the-setting", "description"}; config.applyConfig( "name-of-the-setting = first-value\n" "name-of-the-setting = second-value\n" ); config.getSettings(settings); ASSERT_FALSE(settings.empty()); ASSERT_EQ(settings["name-of-the-setting"].value, "second-value"); } TEST(Config, applyConfigFailsOnMissingIncludes) { Config config; std::map<std::string, Config::SettingInfo> settings; Setting<std::string> setting{&config, "", "name-of-the-setting", "description"}; ASSERT_THROW(config.applyConfig( "name-of-the-setting = value-from-file\n" "# name-of-the-setting = foo\n" "include /nix/store/does/not/exist.nix" ), Error); } TEST(Config, applyConfigInvalidThrows) { Config config; ASSERT_THROW(config.applyConfig("value == key"), UsageError); ASSERT_THROW(config.applyConfig("value "), UsageError); } } <commit_msg>fixup! Add a default value for the settings<commit_after>#include "config.hh" #include "args.hh" #include <sstream> #include <gtest/gtest.h> #include <nlohmann/json.hpp> namespace nix { /* ---------------------------------------------------------------------------- * Config * --------------------------------------------------------------------------*/ TEST(Config, setUndefinedSetting) { Config config; ASSERT_EQ(config.set("undefined-key", "value"), false); } TEST(Config, setDefinedSetting) { Config config; std::string value; Setting<std::string> foo{&config, value, "name-of-the-setting", "description"}; ASSERT_EQ(config.set("name-of-the-setting", "value"), true); } TEST(Config, getDefinedSetting) { Config config; std::string value; std::map<std::string, Config::SettingInfo> settings; Setting<std::string> foo{&config, value, "name-of-the-setting", "description"}; config.getSettings(settings, /* overridenOnly = */ false); const auto iter = settings.find("name-of-the-setting"); ASSERT_NE(iter, settings.end()); ASSERT_EQ(iter->second.value, ""); ASSERT_EQ(iter->second.description, "description\n"); } TEST(Config, getDefinedOverridenSettingNotSet) { Config config; std::string value; std::map<std::string, Config::SettingInfo> settings; Setting<std::string> foo{&config, value, "name-of-the-setting", "description"}; config.getSettings(settings, /* overridenOnly = */ true); const auto e = settings.find("name-of-the-setting"); ASSERT_EQ(e, settings.end()); } TEST(Config, getDefinedSettingSet1) { Config config; std::string value; std::map<std::string, Config::SettingInfo> settings; Setting<std::string> setting{&config, value, "name-of-the-setting", "description"}; setting.assign("value"); config.getSettings(settings, /* overridenOnly = */ false); const auto iter = settings.find("name-of-the-setting"); ASSERT_NE(iter, settings.end()); ASSERT_EQ(iter->second.value, "value"); ASSERT_EQ(iter->second.description, "description\n"); } TEST(Config, getDefinedSettingSet2) { Config config; std::map<std::string, Config::SettingInfo> settings; Setting<std::string> setting{&config, "", "name-of-the-setting", "description"}; ASSERT_TRUE(config.set("name-of-the-setting", "value")); config.getSettings(settings, /* overridenOnly = */ false); const auto e = settings.find("name-of-the-setting"); ASSERT_NE(e, settings.end()); ASSERT_EQ(e->second.value, "value"); ASSERT_EQ(e->second.description, "description\n"); } TEST(Config, addSetting) { class TestSetting : public AbstractSetting { public: TestSetting() : AbstractSetting("test", "test", {}) {} void set(const std::string & value) {} std::string to_string() const { return {}; } }; Config config; TestSetting setting; ASSERT_FALSE(config.set("test", "value")); config.addSetting(&setting); ASSERT_TRUE(config.set("test", "value")); } TEST(Config, withInitialValue) { const StringMap initials = { { "key", "value" }, }; Config config(initials); { std::map<std::string, Config::SettingInfo> settings; config.getSettings(settings, /* overridenOnly = */ false); ASSERT_EQ(settings.find("key"), settings.end()); } Setting<std::string> setting{&config, "default-value", "key", "description"}; { std::map<std::string, Config::SettingInfo> settings; config.getSettings(settings, /* overridenOnly = */ false); ASSERT_EQ(settings["key"].value, "value"); } } TEST(Config, resetOverriden) { Config config; config.resetOverriden(); } TEST(Config, resetOverridenWithSetting) { Config config; Setting<std::string> setting{&config, "", "name-of-the-setting", "description"}; { std::map<std::string, Config::SettingInfo> settings; setting.set("foo"); ASSERT_EQ(setting.get(), "foo"); config.getSettings(settings, /* overridenOnly = */ true); ASSERT_TRUE(settings.empty()); } { std::map<std::string, Config::SettingInfo> settings; setting.override("bar"); ASSERT_TRUE(setting.overriden); ASSERT_EQ(setting.get(), "bar"); config.getSettings(settings, /* overridenOnly = */ true); ASSERT_FALSE(settings.empty()); } { std::map<std::string, Config::SettingInfo> settings; config.resetOverriden(); ASSERT_FALSE(setting.overriden); config.getSettings(settings, /* overridenOnly = */ true); ASSERT_TRUE(settings.empty()); } } TEST(Config, toJSONOnEmptyConfig) { ASSERT_EQ(Config().toJSON().dump(), "{}"); } TEST(Config, toJSONOnNonEmptyConfig) { Config config; std::map<std::string, Config::SettingInfo> settings; Setting<std::string> setting{&config, "", "name-of-the-setting", "description"}; setting.assign("value"); ASSERT_EQ(config.toJSON().dump(), R"#({"name-of-the-setting":{"aliases":[],"defaultValue":"","description":"description\n","value":"value"}})#"); } TEST(Config, setSettingAlias) { Config config; Setting<std::string> setting{&config, "", "some-int", "best number", { "another-int" }}; ASSERT_TRUE(config.set("some-int", "1")); ASSERT_EQ(setting.get(), "1"); ASSERT_TRUE(config.set("another-int", "2")); ASSERT_EQ(setting.get(), "2"); ASSERT_TRUE(config.set("some-int", "3")); ASSERT_EQ(setting.get(), "3"); } /* FIXME: The reapplyUnknownSettings method doesn't seem to do anything * useful (these days). Whenever we add a new setting to Config the * unknown settings are always considered. In which case is this function * actually useful? Is there some way to register a Setting without calling * addSetting? */ TEST(Config, DISABLED_reapplyUnknownSettings) { Config config; ASSERT_FALSE(config.set("name-of-the-setting", "unknownvalue")); Setting<std::string> setting{&config, "default", "name-of-the-setting", "description"}; ASSERT_EQ(setting.get(), "default"); config.reapplyUnknownSettings(); ASSERT_EQ(setting.get(), "unknownvalue"); } TEST(Config, applyConfigEmpty) { Config config; std::map<std::string, Config::SettingInfo> settings; config.applyConfig(""); config.getSettings(settings); ASSERT_TRUE(settings.empty()); } TEST(Config, applyConfigEmptyWithComment) { Config config; std::map<std::string, Config::SettingInfo> settings; config.applyConfig("# just a comment"); config.getSettings(settings); ASSERT_TRUE(settings.empty()); } TEST(Config, applyConfigAssignment) { Config config; std::map<std::string, Config::SettingInfo> settings; Setting<std::string> setting{&config, "", "name-of-the-setting", "description"}; config.applyConfig( "name-of-the-setting = value-from-file #useful comment\n" "# name-of-the-setting = foo\n" ); config.getSettings(settings); ASSERT_FALSE(settings.empty()); ASSERT_EQ(settings["name-of-the-setting"].value, "value-from-file"); } TEST(Config, applyConfigWithReassignedSetting) { Config config; std::map<std::string, Config::SettingInfo> settings; Setting<std::string> setting{&config, "", "name-of-the-setting", "description"}; config.applyConfig( "name-of-the-setting = first-value\n" "name-of-the-setting = second-value\n" ); config.getSettings(settings); ASSERT_FALSE(settings.empty()); ASSERT_EQ(settings["name-of-the-setting"].value, "second-value"); } TEST(Config, applyConfigFailsOnMissingIncludes) { Config config; std::map<std::string, Config::SettingInfo> settings; Setting<std::string> setting{&config, "", "name-of-the-setting", "description"}; ASSERT_THROW(config.applyConfig( "name-of-the-setting = value-from-file\n" "# name-of-the-setting = foo\n" "include /nix/store/does/not/exist.nix" ), Error); } TEST(Config, applyConfigInvalidThrows) { Config config; ASSERT_THROW(config.applyConfig("value == key"), UsageError); ASSERT_THROW(config.applyConfig("value "), UsageError); } } <|endoftext|>
<commit_before>/// /// @file pi_lmo_parallel.cpp /// @brief Parallel implementation of the Lagarias-Miller-Odlyzko /// prime counting algorithm using OpenMP. This implementation /// uses load balancing and counts the number of unsieved /// elements using POPCNT without using any special counting /// tree data structure. /// /// Copyright (C) 2017 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primecount-internal.hpp> #include <BitSieve.hpp> #include <generate.hpp> #include <generate_phi.hpp> #include <LoadBalancer.hpp> #include <min.hpp> #include <imath.hpp> #include <PhiTiny.hpp> #include <PiTable.hpp> #include <S1.hpp> #include <Wheel.hpp> #include <stdint.h> #include <vector> #ifdef _OPENMP #include <omp.h> #endif using namespace std; using namespace primecount; namespace { /// Cross-off the multiples of prime in the sieve array int64_t cross_off(BitSieve& sieve, int64_t low, int64_t high, int64_t prime, WheelItem& w) { int64_t count = 0; int64_t m = w.next_multiple; int64_t wheel_index = w.wheel_index; for (; m < high; m += prime * Wheel::next_multiple_factor(&wheel_index)) { // +1 if m is unset the first time count += sieve[m - low]; sieve.unset(m - low); } w.set(m, wheel_index); return count; } /// Compute the S2 contribution of the interval /// [low, low + segments * segment_size[ /// int64_t S2_thread(int64_t x, int64_t y, int64_t z, int64_t c, int64_t low, int64_t segments, int64_t segment_size, PiTable& pi, vector<int32_t>& primes, vector<int32_t>& lpf, vector<int32_t>& mu, Runtime& runtime) { int64_t limit = min(low + segments * segment_size, z + 1); int64_t size = pi[min(isqrt(x / low), y)] + 1; int64_t pi_sqrty = pi[isqrt(y)]; int64_t pi_y = pi[y]; int64_t S2_thread = 0; if (c >= size - 1) return 0; runtime.init_start(); BitSieve sieve(segment_size); Wheel wheel(primes, size, low); auto phi = generate_phi(low - 1, size - 1, primes, pi); runtime.init_stop(); // segmented sieve of Eratosthenes for (; low < limit; low += segment_size) { // current segment = [low, high[ int64_t high = min(low + segment_size, limit); int64_t b = c + 1; // pre-sieve multiples of first c primes sieve.pre_sieve(c, low); int64_t count_low_high = sieve.count((high - 1) - low); // For c + 1 <= b <= pi_sqrty // Find all special leaves: n = primes[b] * m // which satisfy: mu[m] != 0 && primes[b] < lpf[m], low <= (x / n) < high for (; b <= min(pi_sqrty, size - 1); b++) { int64_t prime = primes[b]; int64_t min_m = max(x / (prime * high), y / prime); int64_t max_m = min(x / (prime * low), y); int64_t count = 0; int64_t i = 0; if (prime >= max_m) goto next_segment; for (int64_t m = max_m; m > min_m; m--) { if (mu[m] != 0 && prime < lpf[m]) { int64_t xn = x / (prime * m); int64_t stop = xn - low; count += sieve.count(i, stop); i = stop + 1; int64_t phi_xn = phi[b] + count; S2_thread -= mu[m] * phi_xn; } } phi[b] += count_low_high; count_low_high -= cross_off(sieve, low, high, prime, wheel[b]); } // For pi_sqrty < b < pi_y // Find all special leaves: n = primes[b] * prime2 // which satisfy: low <= (x / n) < high for (; b < min(pi_y, size); b++) { int64_t prime = primes[b]; int64_t l = pi[min(x / (prime * low), y)]; int64_t min_m = max(x / (prime * high), prime); int64_t count = 0; int64_t i = 0; if (prime >= primes[l]) goto next_segment; for (; primes[l] > min_m; l--) { int64_t xn = x / (prime * primes[l]); int64_t stop = xn - low; count += sieve.count(i, stop); i = stop + 1; int64_t phi_xn = phi[b] + count; S2_thread += phi_xn; } phi[b] += count_low_high; count_low_high -= cross_off(sieve, low, high, prime, wheel[b]); } next_segment:; } return S2_thread; } /// Calculate the contribution of the special leaves. /// This is a parallel implementation with advanced load balancing. /// As most special leaves tend to be in the first segments we /// start off with a small segment size and few segments /// per thread, after each iteration we dynamically increase /// the segment size and the number of segments. /// int64_t S2(int64_t x, int64_t y, int64_t z, int64_t c, int64_t s2_approx, vector<int32_t>& primes, vector<int32_t>& lpf, vector<int32_t>& mu, int threads) { print(""); print("=== S2(x, y) ==="); print("Computation of the special leaves"); double time = get_wtime(); double alpha = get_alpha(x, y); threads = ideal_num_threads(threads, z); LoadBalancer loadBalancer(x, y, z, alpha, s2_approx); PiTable pi(y); #pragma omp parallel for num_threads(threads) for (int i = 0; i < threads; i++) { int64_t low = 0; int64_t segments = 0; int64_t segment_size = 0; int64_t S2 = 0; Runtime runtime; while (loadBalancer.get_work(&low, &segments, &segment_size, S2, runtime)) { runtime.start(); S2 = S2_thread(x, y, z, c, low, segments, segment_size, pi, primes, lpf, mu, runtime); runtime.stop(); } } int64_t S2 = (int64_t) loadBalancer.get_result(); print("S2", S2, time); return S2; } } // namespace namespace primecount { /// Calculate the number of primes below x using the /// Lagarias-Miller-Odlyzko algorithm. /// Run time: O(x^(2/3) / log x) /// Memory usage: O(x^(1/3) * (log x)^2) /// int64_t pi_lmo_parallel(int64_t x, int threads) { if (x < 2) return 0; double alpha = get_alpha_lmo(x); int64_t x13 = iroot<3>(x); int64_t y = (int64_t) (x13 * alpha); int64_t z = x / y; int64_t c = PhiTiny::get_c(y); print(""); print("=== pi_lmo_parallel(x) ==="); print("pi(x) = S1 + S2 + pi(y) - 1 - P2"); print(x, y, z, c, alpha, threads); int64_t p2 = P2(x, y, threads); auto primes = generate_primes<int32_t>(y); auto lpf = generate_lpf(y); auto mu = generate_moebius(y); int64_t pi_y = primes.size() - 1; int64_t s1 = S1(x, y, c, threads); int64_t s2_approx = S2_approx(x, pi_y, p2, s1); int64_t s2 = S2(x, y, z, c, s2_approx, primes, lpf, mu, threads); int64_t phi = s1 + s2; int64_t sum = phi + pi_y - 1 - p2; return sum; } } // namespace <commit_msg>Remove unused variable<commit_after>/// /// @file pi_lmo_parallel.cpp /// @brief Parallel implementation of the Lagarias-Miller-Odlyzko /// prime counting algorithm using OpenMP. This implementation /// uses load balancing and counts the number of unsieved /// elements using POPCNT without using any special counting /// tree data structure. /// /// Copyright (C) 2017 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primecount-internal.hpp> #include <BitSieve.hpp> #include <generate.hpp> #include <generate_phi.hpp> #include <LoadBalancer.hpp> #include <min.hpp> #include <imath.hpp> #include <PhiTiny.hpp> #include <PiTable.hpp> #include <S1.hpp> #include <Wheel.hpp> #include <stdint.h> #include <vector> #ifdef _OPENMP #include <omp.h> #endif using namespace std; using namespace primecount; namespace { /// Cross-off the multiples of prime in the sieve array int64_t cross_off(BitSieve& sieve, int64_t low, int64_t high, int64_t prime, WheelItem& w) { int64_t count = 0; int64_t m = w.next_multiple; int64_t wheel_index = w.wheel_index; for (; m < high; m += prime * Wheel::next_multiple_factor(&wheel_index)) { // +1 if m is unset the first time count += sieve[m - low]; sieve.unset(m - low); } w.set(m, wheel_index); return count; } /// Compute the S2 contribution of the interval /// [low, low + segments * segment_size[ /// int64_t S2_thread(int64_t x, int64_t y, int64_t z, int64_t c, int64_t low, int64_t segments, int64_t segment_size, PiTable& pi, vector<int32_t>& primes, vector<int32_t>& lpf, vector<int32_t>& mu, Runtime& runtime) { int64_t limit = min(low + segments * segment_size, z + 1); int64_t size = pi[min(isqrt(x / low), y)] + 1; int64_t pi_sqrty = pi[isqrt(y)]; int64_t pi_y = pi[y]; int64_t S2_thread = 0; if (c >= size - 1) return 0; runtime.init_start(); BitSieve sieve(segment_size); Wheel wheel(primes, size, low); auto phi = generate_phi(low - 1, size - 1, primes, pi); runtime.init_stop(); // segmented sieve of Eratosthenes for (; low < limit; low += segment_size) { // current segment = [low, high[ int64_t high = min(low + segment_size, limit); int64_t b = c + 1; // pre-sieve multiples of first c primes sieve.pre_sieve(c, low); int64_t count_low_high = sieve.count((high - 1) - low); // For c + 1 <= b <= pi_sqrty // Find all special leaves: n = primes[b] * m // which satisfy: mu[m] != 0 && primes[b] < lpf[m], low <= (x / n) < high for (; b <= min(pi_sqrty, size - 1); b++) { int64_t prime = primes[b]; int64_t min_m = max(x / (prime * high), y / prime); int64_t max_m = min(x / (prime * low), y); int64_t count = 0; int64_t i = 0; if (prime >= max_m) goto next_segment; for (int64_t m = max_m; m > min_m; m--) { if (mu[m] != 0 && prime < lpf[m]) { int64_t xn = x / (prime * m); int64_t stop = xn - low; count += sieve.count(i, stop); i = stop + 1; int64_t phi_xn = phi[b] + count; S2_thread -= mu[m] * phi_xn; } } phi[b] += count_low_high; count_low_high -= cross_off(sieve, low, high, prime, wheel[b]); } // For pi_sqrty < b < pi_y // Find all special leaves: n = primes[b] * prime2 // which satisfy: low <= (x / n) < high for (; b < min(pi_y, size); b++) { int64_t prime = primes[b]; int64_t l = pi[min(x / (prime * low), y)]; int64_t min_m = max(x / (prime * high), prime); int64_t count = 0; int64_t i = 0; if (prime >= primes[l]) goto next_segment; for (; primes[l] > min_m; l--) { int64_t xn = x / (prime * primes[l]); int64_t stop = xn - low; count += sieve.count(i, stop); i = stop + 1; int64_t phi_xn = phi[b] + count; S2_thread += phi_xn; } phi[b] += count_low_high; count_low_high -= cross_off(sieve, low, high, prime, wheel[b]); } next_segment:; } return S2_thread; } /// Calculate the contribution of the special leaves. /// This is a parallel implementation with advanced load balancing. /// As most special leaves tend to be in the first segments we /// start off with a small segment size and few segments /// per thread, after each iteration we dynamically increase /// the segment size and the number of segments. /// int64_t S2(int64_t x, int64_t y, int64_t z, int64_t c, int64_t s2_approx, vector<int32_t>& primes, vector<int32_t>& lpf, vector<int32_t>& mu, int threads) { print(""); print("=== S2(x, y) ==="); print("Computation of the special leaves"); double time = get_wtime(); threads = ideal_num_threads(threads, z); LoadBalancer loadBalancer(x, y, z, s2_approx); PiTable pi(y); #pragma omp parallel for num_threads(threads) for (int i = 0; i < threads; i++) { int64_t low = 0; int64_t segments = 0; int64_t segment_size = 0; int64_t S2 = 0; Runtime runtime; while (loadBalancer.get_work(&low, &segments, &segment_size, S2, runtime)) { runtime.start(); S2 = S2_thread(x, y, z, c, low, segments, segment_size, pi, primes, lpf, mu, runtime); runtime.stop(); } } int64_t S2 = (int64_t) loadBalancer.get_result(); print("S2", S2, time); return S2; } } // namespace namespace primecount { /// Calculate the number of primes below x using the /// Lagarias-Miller-Odlyzko algorithm. /// Run time: O(x^(2/3) / log x) /// Memory usage: O(x^(1/3) * (log x)^2) /// int64_t pi_lmo_parallel(int64_t x, int threads) { if (x < 2) return 0; double alpha = get_alpha_lmo(x); int64_t x13 = iroot<3>(x); int64_t y = (int64_t) (x13 * alpha); int64_t z = x / y; int64_t c = PhiTiny::get_c(y); print(""); print("=== pi_lmo_parallel(x) ==="); print("pi(x) = S1 + S2 + pi(y) - 1 - P2"); print(x, y, z, c, alpha, threads); int64_t p2 = P2(x, y, threads); auto primes = generate_primes<int32_t>(y); auto lpf = generate_lpf(y); auto mu = generate_moebius(y); int64_t pi_y = primes.size() - 1; int64_t s1 = S1(x, y, c, threads); int64_t s2_approx = S2_approx(x, pi_y, p2, s1); int64_t s2 = S2(x, y, z, c, s2_approx, primes, lpf, mu, threads); int64_t phi = s1 + s2; int64_t sum = phi + pi_y - 1 - p2; return sum; } } // namespace <|endoftext|>
<commit_before>#include "maBiblio.h" bool ValidationLigne(string, int); int OptimiseLongueur(string); vector<string> GrilleLettre(string, int); vector<string> GrilleJeu(string, int); void PromotionEspaceVide(vector<string>&); void EspaceSort(vector<string>&, int, int,int); int Partition(vector<string>&,int,int,int,int); void EcrireFichier(vector<string>, vector<string>, int); void AfficherJeu(vector<string>, vector<string>); bool is_npos(int); int main() { srand(time(NULL)); setlocale(LC_ALL, ""); ifstream ficIn; string nomFichier; string ligneCourante; int nbLigne = 0; int nbrColonnes = 0; int nbGenerer = 0; string cadreHaut = "╔═"; string cadreCote = "║"; string cadreBas = "╚"; do { cout << "Veuillez entrer le nom du fichier contenant les citations : "; cin >> nomFichier; ficIn.open(nomFichier); //Un peu comme Assert, si le fichie n'ouvre pas il affiche un message d'erreur. } while (!ficIn.is_open() && (cout << "Erreur de lecture.\n")); cout << "Fichier :" << nomFichier << " est en mode lecture.\n"; while (ficIn.good()) { nbLigne++; getline(ficIn, ligneCourante); /* int pos = ligneCourante.find_first_not_of("\n "); //find_first_not_of peut retourner string::npos (constante évalué à -1) si rien n'a été trouvé. //Si c'est le cas, ligne vide ou mal formaté, break à l'extérieur du for pour prendre la prochaine ligne. if (pos == string::npos) { cout << "Erreur ligne " << nbLigne << " citation vide.\n"; continue; } ligneCourante = ligneCourante.substr(pos); */ if (!ValidationLigne(ligneCourante, nbLigne)) continue; nbrColonnes = OptimiseLongueur(ligneCourante); vector<string> grilleLettre = GrilleLettre(ligneCourante, nbrColonnes); vector<string> grilleJeu= GrilleJeu(ligneCourante, nbrColonnes); PromotionEspaceVide(grilleLettre); nbGenerer++; AfficherJeu(grilleLettre, grilleJeu); EcrireFichier(grilleLettre, grilleJeu, nbGenerer); system("pause"); } ficIn.close(); cout << "Programme terminé\n"; system("pause"); return 0; } void AfficherJeu(vector<string> haut, vector<string> bas) { cout << endl << endl; for (string s : haut) { cout << s << endl; } cout << endl; for (string s : bas) { cout << s << endl; } cout << endl << endl; } void EcrireFichier(vector<string> sup, vector<string> inf, int nb) { ofstream ficOut; stringstream ss; ss << "Citation" << nb << ".txt"; ficOut.open(ss.str(), ios::out); ficOut << endl; ficOut << endl; for (string s : sup) { ficOut << s; ficOut << endl; } for (string s : inf) { ficOut << endl; ficOut << s; ficOut << endl; } ficOut.close(); cout << "Grille enregistrée à : " << ss.str() << endl;; ss.str(string()); } bool ValidationLigne(string ligne, int nbr) { for (char c : ligne) { int i = c; if (i >= 128 || i < 0) { cout << "Erreur ligne " << nbr << " la citation contient des caractères illegaux.\n"; return false; } } if (ligne.length() < 35) { cout << "Erreur ligne " << nbr << " la citation contient moins que 35 caractères.\n"; return false; } if (ligne.length() > 100) { cout << "Erreur ligne " << nbr << " la citation contient plus que 100 caractères.\n"; return false; } bool bon = is_npos(ligne.find(" ")) & is_npos(ligne.find("--")) & is_npos(ligne.find("''")) & is_npos(ligne.find("..")) & is_npos(ligne.find(",,")); if (!bon) { cout << "Erreur ligne " << nbr << " séparateur de mot consécutifs dans la citation.\n"; return false; } return true; } bool is_npos(int i) { if (i == string::npos) return true; return false; } int OptimiseLongueur(string ligne) { int colonnes = 0; int meilleurTronquage = 9999; for (int i = 13; i < 18; i++) { int motTronquer = 0; int times = ceil((double)ligne.length() /i); for (int t = 1; t <= times; t++) { if ((ligne.length() > ((t * i))) && (ligne[t*i] != ' ') && (ligne[(t*i) -1] != ' ')) { motTronquer++; } } if (motTronquer < meilleurTronquage) { meilleurTronquage = motTronquer; colonnes = i; } } return colonnes; } vector<string> GrilleLettre(string ligne, int colonne) { vector<string> grilleLettre; while (ligne.length() != 0) { grilleLettre.push_back(ligne.substr(0, colonne)); ligne = ligne.substr(ligne.length() <= colonne ? ligne.length() : colonne); } if (grilleLettre[grilleLettre.size() - 1].length() < colonne) { int i = colonne - grilleLettre[grilleLettre.size() - 1].length(); string s(i, ' '); grilleLettre[grilleLettre.size() - 1] += s; } for (int i = 0; i < colonne; i++) { int nbrEchange = rand() % 50 + 1; for (int r = 0; r < nbrEchange; r++) { int premier = rand() % grilleLettre.size();; int deuxieme = rand() % grilleLettre.size();; swap(grilleLettre[premier][i],grilleLettre[deuxieme][i]); } } for (int i = 0; i < grilleLettre.size(); i++) { transform(grilleLettre[i].begin(), grilleLettre[i].end(), grilleLettre[i].begin(), toupper); } return grilleLettre; } vector<string> GrilleJeu(string ligne, int colonne) { vector<string> grilleJeu; for (int i = 0; i < ligne.length();i++) { if (isalnum(ligne[i])) { ligne[i] = '-'; } else ligne[i] = ' '; } while (ligne.length() != 0) { grilleJeu.push_back(ligne.substr(0, colonne)); ligne = ligne.substr(ligne.length() <= colonne ? ligne.length() : colonne); } return grilleJeu; } void PromotionEspaceVide(vector<string>& grille) { for (int i = 0; i < grille[0].length(); i++) { EspaceSort(grille, 0, grille.size() - 1, i); } } void EspaceSort(vector<string>& vecteur, int debut, int fin, int ligne) { if (fin <= debut) return; int indexPivot = rand() % (fin - debut) + debut; indexPivot = Partition(vecteur, debut, fin, indexPivot, ligne); EspaceSort(vecteur, debut, indexPivot - 1, ligne); EspaceSort(vecteur, indexPivot + 1, fin, ligne); } int Partition(vector<string>& vecteur, int debut, int fin, int pivot, int ligne) { char cpivot = vecteur[pivot][ligne]; swap(vecteur[pivot][ligne], vecteur[fin][ligne]); int pivpost = debut; for (int i = debut; i < fin;i++) { if (vecteur[i][ligne] == ' ') { swap(vecteur[pivpost][ligne], vecteur[i][ligne]); pivpost += 1; } } swap(vecteur[pivpost][ligne], vecteur[fin][ligne]); return pivpost; }<commit_msg>Rajout de commentaires<commit_after>#include "maBiblio.h" bool ValidationLigne(string, int); int OptimiseLongueur(string); vector<string> GrilleLettre(string, int); vector<string> GrilleJeu(string, int); void PromotionEspaceVide(vector<string>&); void EspaceSort(vector<string>&, int, int,int); int Partition(vector<string>&,int,int,int,int); void EcrireFichier(vector<string>, vector<string>, int); void AfficherJeu(vector<string>, vector<string>); bool is_npos(int); int main() { srand(time(NULL)); setlocale(LC_ALL, ""); ifstream ficIn; string nomFichier; string ligneCourante; int nbLigne = 0; int nbrColonnes = 0; int nbGenerer = 0; string cadreHaut = "╔═"; string cadreCote = "║"; string cadreBas = "╚"; do { cout << "Veuillez entrer le nom du fichier contenant les citations : "; cin >> nomFichier; ficIn.open(nomFichier); //Un peu comme Assert, si le fichie n'ouvre pas il affiche un message d'erreur. } while (!ficIn.is_open() && (cout << "Erreur de lecture.\n")); cout << "Fichier :" << nomFichier << " est en mode lecture.\n"; while (ficIn.good()) { nbLigne++; getline(ficIn, ligneCourante); /* int pos = ligneCourante.find_first_not_of("\n "); //find_first_not_of peut retourner string::npos (constante évalué à -1) si rien n'a été trouvé. //Si c'est le cas, ligne vide ou mal formaté, break à l'extérieur du for pour prendre la prochaine ligne. if (pos == string::npos) { cout << "Erreur ligne " << nbLigne << " citation vide.\n"; continue; } ligneCourante = ligneCourante.substr(pos); */ //Si la ligne n'est pas valide, continue à la prochaine boucle. //À pour effet d'aller chercher la prochaine ligne. if (!ValidationLigne(ligneCourante, nbLigne)) continue; //Le nombre de colonnes qui sera utilisé pour la grille de jeu de cette citation. nbrColonnes = OptimiseLongueur(ligneCourante); //Chaque string du vector est une ligne différente de la grille. //grilleLettre a les lettres de la grille supérieur. //grilleJeu a la représentation du jeu, l'emplacement où les lettres doivent aller. vector<string> grilleLettre = GrilleLettre(ligneCourante, nbrColonnes); vector<string> grilleJeu= GrilleJeu(ligneCourante, nbrColonnes); PromotionEspaceVide(grilleLettre); //Nombre de grille généré par le programme. nbGenerer++; AfficherJeu(grilleLettre, grilleJeu); EcrireFichier(grilleLettre, grilleJeu, nbGenerer); system("pause"); } ficIn.close(); cout << "Programme terminé\n"; system("pause"); //Si aucune citation a été généré, retourne le code 1. if (nbGenerer == 0) return 1; return 0; } /* Fonction qui prend en paramètre deux vector<string> et qui affiche leur contenue. Pour visualiser les grilles du jeu sur la console. */ void AfficherJeu(vector<string> haut, vector<string> bas) { cout << endl << endl; for (string s : haut) { cout << s << endl; } cout << endl; for (string s : bas) { cout << s << endl; } cout << endl << endl; } /* Fonction qui prend deux vector<string> et un int pour enregistrer le contenue des deux vector dans un fichier. Pour enregistrer les grilles du jeu dans un fichier. Le nom du fichier est en fonction du int qui lui donne le nombre de la citation. */ void EcrireFichier(vector<string> sup, vector<string> inf, int nb) { ofstream ficOut; stringstream ss; //Utilisation de stringstream pour construire un objet string avec un string litteral et une variable int. ss << "Citation" << nb << ".txt"; ficOut.open(ss.str(), ios::out); //Enregistre ligne par ligne le contenue des vector dans le fichier. ficOut << endl; ficOut << endl; for (string s : sup) { ficOut << s; ficOut << endl; } for (string s : inf) { ficOut << endl; ficOut << s; ficOut << endl; } ficOut.close(); cout << "Grille enregistrée à : " << ss.str() << endl;; //Vide le stringstream ss.str(string()); } /* Fonction qui prend un string et un int pour valider le string. Le int est utilisé pour afficher un message d'erreur à l'utilisateur. Valide une citation. Retourne false si incorrect. True pour valide. */ bool ValidationLigne(string ligne, int nbr) { for (char c : ligne) { //Prend le code ascii du char int i = c; //Vérifie si le char est un charactère du ascii de base. if (i >= 128 || i < 0) { cout << "Erreur ligne " << nbr << " la citation contient des caractères illegaux.\n"; return false; } } if (ligne.length() < 35) { cout << "Erreur ligne " << nbr << " la citation contient moins que 35 caractères.\n"; return false; } if (ligne.length() > 100) { cout << "Erreur ligne " << nbr << " la citation contient plus que 100 caractères.\n"; return false; } /* Utilise l'opérateur AND bit-à-bit pour déterminer si deux caractères d'espacement ce situe un à côté de l'autre. La réponse est en un bit (bool). Si une des fonctions retourne un False, le résultat final sera un False. Alors que pour que "bon" soit True, il faut que toutes les fonctions retourne True. string.find() retourne la constante npos s'il n'y a aucun résultat dans la string, ce qui est le cas s'il n'y a pas de dédoublement de caractères d'espacement. is_npos retourne True si, en effet, il n'est pas présent. Permet d'avoir une condition if assez petite. */ bool bon = is_npos(ligne.find(" ")) & is_npos(ligne.find("--")) & is_npos(ligne.find("''")) & is_npos(ligne.find("..")) & is_npos(ligne.find(",,")); if (!bon) { cout << "Erreur ligne " << nbr << " séparateur de mot consécutifs dans la citation.\n"; return false; } return true; } //Retourne true is i est la constante string::npos bool is_npos(int i) { if (i == string::npos) return true; return false; } /* À partir d'un string, détermine le nombre de colonnes qui minimise les mots tronqués. Retourne le int qui en résulte. */ int OptimiseLongueur(string ligne) { int colonnes = 0; //Valeur arbitrairement grosse pour être presque certain (dans la majorité des cas d'utilisation) //qu'un meilleur résultat sera trouvé. int meilleurTronquage = 9999; //Vérifie selon la longueur minimale de 13 caractères par ligne jusqu'au maximum de 17 inclusivement. for (int i = 13; i < 18; i++) { //Compteur de mots tronqués. int motTronquer = 0; //Le nombres de lignes. ceil est pour l'arrondir au plus grand entier supérieur. int times = ceil((double)ligne.length() /i); for (int t = 1; t <= times; t++) { /* Si la longueur de la ligne est plus petite ou égal que le nombre de caractère par ligne * le nombre de ligne, nous pouvons l'écrire sur une ligne au complet donc pas de mot tronqué. */ if ((ligne.length() > ((t * i))) && (ligne[t*i] != ' ') && (ligne[(t*i) -1] != ' ')) { motTronquer++; } } //Trouvé un meilleur résultat if (motTronquer < meilleurTronquage) { meilleurTronquage = motTronquer; colonnes = i; } } return colonnes; } /* Créer la grille de lettre à partir d'un string et du nombre de colonnes. Retourne le résultat sour la forme d'un vector<string> ou chaque string est une ligne différente. */ vector<string> GrilleLettre(string ligne, int colonne) { vector<string> grilleLettre; //Retire des lettres de ligne au fure et à mesure pour les rajouter dans le vector grilleLettre. while (ligne.length() != 0) { //Retire la première ligne de la grille et la rajoute dans le vector. grilleLettre.push_back(ligne.substr(0, colonne)); //Lorsqu'il ne reste pas assez de caractères à la string pour former une ligne au complète (selon le int colonne) //prend le restant de la string au complet. Pour éviter les erreurs d'exécution. ligne = ligne.substr(ligne.length() <= colonne ? ligne.length() : colonne); } //Rajoute des espacements vide à la dernière ligne de la grille pour avoir des string de taille uniforme. if (grilleLettre[grilleLettre.size() - 1].length() < colonne) { int i = colonne - grilleLettre[grilleLettre.size() - 1].length(); string s(i, ' '); grilleLettre[grilleLettre.size() - 1] += s; } //Mélange les caractères des colonnes for (int i = 0; i < colonne; i++) { int nbrEchange = rand() % 50 + 1; for (int r = 0; r < nbrEchange; r++) { int premier = rand() % grilleLettre.size();; int deuxieme = rand() % grilleLettre.size();; //Fonction permuter disponible dans la librairie algorithm. swap(grilleLettre[premier][i],grilleLettre[deuxieme][i]); } } //Utilisation des itérateurs pour transformer chaque char en majuscule. for (int i = 0; i < grilleLettre.size(); i++) { transform(grilleLettre[i].begin(), grilleLettre[i].end(), grilleLettre[i].begin(), toupper); } return grilleLettre; } /* Créer la grille de jeu avec des emplacements vides ou des emplacements pour écrire des lettres du nombre de colonnes données. Retourne un vector<string> qui est la grille formaté où chaque string est une ligne. */ vector<string> GrilleJeu(string ligne, int colonne) { vector<string> grilleJeu; for (int i = 0; i < ligne.length();i++) { //Si le caractère est alpha-numérique, on le remplace par un emplacement lettre. if (isalnum(ligne[i])) { ligne[i] = '-'; } //Sinon, devient un emplacement vide. else ligne[i] = ' '; } //Rajoute les lignes dans la grilleJeu. while (ligne.length() != 0) { grilleJeu.push_back(ligne.substr(0, colonne)); //Lorsqu'il ne reste pas assez de caractères à la string pour former une ligne au complète (selon le int colonne) //prend le restant de la string au complet. Pour éviter les erreurs d'exécution. ligne = ligne.substr(ligne.length() <= colonne ? ligne.length() : colonne); } return grilleJeu; } /* Fonction pour créer un meilleur visuel. Utilise un QuickSort implémenté pour travailler avec les colonnes d'un vector<string> dans le but de positionner les emplacements vide au dessus des emplacements lettre. Lors du mélange des caractères sur la colonnes, les emplacements vide pouvaient ce trouver n'importe où. Puisque QuickSort est un algorithme instable, l'ordre des lettres n'est pas garantit. */ void PromotionEspaceVide(vector<string>& grille) { //Pour chaque colonnes for (int i = 0; i < grille[0].length(); i++) { //Lance EspaceSort, envois le data, l'index du début, l'index de la fin et le numéro de la colonne traité. EspaceSort(grille, 0, grille.size() - 1, i); } } void EspaceSort(vector<string>& vecteur, int debut, int fin, int ligne) { if (fin <= debut) return; int indexPivot = rand() % (fin - debut) + debut; indexPivot = Partition(vecteur, debut, fin, indexPivot, ligne); EspaceSort(vecteur, debut, indexPivot - 1, ligne); EspaceSort(vecteur, indexPivot + 1, fin, ligne); } int Partition(vector<string>& vecteur, int debut, int fin, int pivot, int ligne) { char cpivot = vecteur[pivot][ligne]; swap(vecteur[pivot][ligne], vecteur[fin][ligne]); int pivpost = debut; for (int i = debut; i < fin;i++) { if (vecteur[i][ligne] == ' ') { swap(vecteur[pivpost][ligne], vecteur[i][ligne]); pivpost += 1; } } swap(vecteur[pivpost][ligne], vecteur[fin][ligne]); return pivpost; }<|endoftext|>
<commit_before>/* Copyright (c) 2019, Ford Motor Company, Livio 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 the copyright holders nor the names of their 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 "app_service_rpc_plugin/app_service_mobile_command_factory.h" #include "application_manager/message.h" #include "interfaces/MOBILE_API.h" #include "app_service_rpc_plugin/commands/mobile/get_app_service_data_request.h" #include "app_service_rpc_plugin/commands/mobile/get_app_service_data_request_to_mobile.h" #include "app_service_rpc_plugin/commands/mobile/get_app_service_data_response.h" #include "app_service_rpc_plugin/commands/mobile/get_app_service_data_response_from_mobile.h" #include "app_service_rpc_plugin/commands/mobile/on_app_service_data_notification.h" #include "app_service_rpc_plugin/commands/mobile/on_app_service_data_notification_from_mobile.h" #include "app_service_rpc_plugin/commands/mobile/perform_app_service_interaction_request.h" #include "app_service_rpc_plugin/commands/mobile/perform_app_service_interaction_request_to_mobile.h" #include "app_service_rpc_plugin/commands/mobile/perform_app_service_interaction_response.h" #include "app_service_rpc_plugin/commands/mobile/perform_app_service_interaction_response_from_mobile.h" #include "app_service_rpc_plugin/commands/mobile/publish_app_service_request.h" #include "app_service_rpc_plugin/commands/mobile/publish_app_service_response.h" CREATE_LOGGERPTR_GLOBAL(logger_, "AppServiceRpcPlugin") namespace app_service_rpc_plugin { namespace strings = app_mngr::strings; AppServiceMobileCommandFactory::AppServiceMobileCommandFactory( application_manager::ApplicationManager& application_manager, application_manager::rpc_service::RPCService& rpc_service, application_manager::HMICapabilities& hmi_capabilities, policy::PolicyHandlerInterface& policy_handler) : application_manager_(application_manager) , rpc_service_(rpc_service) , hmi_capabilities_(hmi_capabilities) , policy_handler_(policy_handler) { LOG4CXX_AUTO_TRACE(logger_); } app_mngr::CommandSharedPtr AppServiceMobileCommandFactory::CreateCommand( const app_mngr::commands::MessageSharedPtr& message, app_mngr::commands::Command::CommandSource source) { UNUSED(source); const mobile_apis::FunctionID::eType function_id = static_cast<mobile_apis::FunctionID::eType>( (*message)[strings::params][strings::function_id].asInt()); const mobile_apis::messageType::eType message_type = static_cast<mobile_apis::messageType::eType>( (*message)[strings::params][strings::message_type].asInt()); auto message_type_str = "request"; if (mobile_apis::messageType::response == message_type) { message_type_str = "response"; } else if (mobile_apis::messageType::notification == message_type) { message_type_str = "notification"; } UNUSED(message_type_str); LOG4CXX_DEBUG(logger_, "HMICommandFactory::CreateCommand function_id: " << function_id << ", message type: " << message_type_str); return buildCommandCreator(function_id, message_type, source).create(message); } bool AppServiceMobileCommandFactory::IsAbleToProcess( const int32_t function_id, const app_mngr::commands::Command::CommandSource source) const { UNUSED(source); return buildCommandCreator(function_id, mobile_apis::messageType::INVALID_ENUM, source).CanBeCreated(); } app_mngr::CommandCreator& AppServiceMobileCommandFactory::buildCommandCreator( const int32_t function_id, const int32_t message_type, const app_mngr::commands::Command::CommandSource source) const { auto factory = app_mngr::CommandCreatorFactory( application_manager_, rpc_service_, hmi_capabilities_, policy_handler_); switch (function_id) { case mobile_apis::FunctionID::PublishAppServiceID: return mobile_apis::messageType::request == message_type ? factory.GetCreator<commands::PublishAppServiceRequest>() : factory.GetCreator<commands::PublishAppServiceResponse>(); case mobile_apis::FunctionID::OnAppServiceDataID: return app_mngr::commands::Command::CommandSource::SOURCE_MOBILE == source ? factory.GetCreator< commands::OnAppServiceDataNotificationFromMobile>() : factory.GetCreator<commands::OnAppServiceDataNotification>(); case mobile_apis::FunctionID::GetAppServiceDataID: if (app_mngr::commands::Command::CommandSource::SOURCE_MOBILE == source) { return mobile_apis::messageType::request == message_type ? factory.GetCreator<commands::GetAppServiceDataRequest>() : factory.GetCreator< commands::GetAppServiceDataResponseFromMobile>(); } else if (app_mngr::commands::Command::CommandSource::SOURCE_SDL == source) { return mobile_apis::messageType::request == message_type ? factory.GetCreator< commands::GetAppServiceDataRequestToMobile>() : factory.GetCreator<commands::GetAppServiceDataResponse>(); } break; case mobile_apis::FunctionID::PerformAppServiceInteractionID: if (app_mngr::commands::Command::CommandSource::SOURCE_MOBILE == source) { return mobile_apis::messageType::request == message_type ? factory.GetCreator< commands::PerformAppServiceInteractionRequest>() : factory.GetCreator< commands:: PerformAppServiceInteractionResponseFromMobile>(); } else if (app_mngr::commands::Command::CommandSource::SOURCE_SDL == source) { return mobile_apis::messageType::request == message_type ? factory.GetCreator< commands:: PerformAppServiceInteractionRequestToMobile>() : factory.GetCreator< commands::PerformAppServiceInteractionResponse>(); } break; default: LOG4CXX_WARN(logger_, "Unsupported function_id: " << function_id); } return factory.GetCreator<app_mngr::InvalidCommand>(); } } // namespace vehicle_info_plugin <commit_msg>Add missing check in App Service Command Factory<commit_after>/* Copyright (c) 2019, Ford Motor Company, Livio 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 the copyright holders nor the names of their 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 "app_service_rpc_plugin/app_service_mobile_command_factory.h" #include "application_manager/message.h" #include "interfaces/MOBILE_API.h" #include "app_service_rpc_plugin/commands/mobile/get_app_service_data_request.h" #include "app_service_rpc_plugin/commands/mobile/get_app_service_data_request_to_mobile.h" #include "app_service_rpc_plugin/commands/mobile/get_app_service_data_response.h" #include "app_service_rpc_plugin/commands/mobile/get_app_service_data_response_from_mobile.h" #include "app_service_rpc_plugin/commands/mobile/on_app_service_data_notification.h" #include "app_service_rpc_plugin/commands/mobile/on_app_service_data_notification_from_mobile.h" #include "app_service_rpc_plugin/commands/mobile/perform_app_service_interaction_request.h" #include "app_service_rpc_plugin/commands/mobile/perform_app_service_interaction_request_to_mobile.h" #include "app_service_rpc_plugin/commands/mobile/perform_app_service_interaction_response.h" #include "app_service_rpc_plugin/commands/mobile/perform_app_service_interaction_response_from_mobile.h" #include "app_service_rpc_plugin/commands/mobile/publish_app_service_request.h" #include "app_service_rpc_plugin/commands/mobile/publish_app_service_response.h" CREATE_LOGGERPTR_GLOBAL(logger_, "AppServiceRpcPlugin") namespace app_service_rpc_plugin { namespace strings = app_mngr::strings; AppServiceMobileCommandFactory::AppServiceMobileCommandFactory( application_manager::ApplicationManager& application_manager, application_manager::rpc_service::RPCService& rpc_service, application_manager::HMICapabilities& hmi_capabilities, policy::PolicyHandlerInterface& policy_handler) : application_manager_(application_manager) , rpc_service_(rpc_service) , hmi_capabilities_(hmi_capabilities) , policy_handler_(policy_handler) { LOG4CXX_AUTO_TRACE(logger_); } app_mngr::CommandSharedPtr AppServiceMobileCommandFactory::CreateCommand( const app_mngr::commands::MessageSharedPtr& message, app_mngr::commands::Command::CommandSource source) { UNUSED(source); const mobile_apis::FunctionID::eType function_id = static_cast<mobile_apis::FunctionID::eType>( (*message)[strings::params][strings::function_id].asInt()); const mobile_apis::messageType::eType message_type = static_cast<mobile_apis::messageType::eType>( (*message)[strings::params][strings::message_type].asInt()); auto message_type_str = "request"; if (mobile_apis::messageType::response == message_type) { message_type_str = "response"; } else if (mobile_apis::messageType::notification == message_type) { message_type_str = "notification"; } UNUSED(message_type_str); LOG4CXX_DEBUG(logger_, "HMICommandFactory::CreateCommand function_id: " << function_id << ", message type: " << message_type_str); return buildCommandCreator(function_id, message_type, source).create(message); } bool AppServiceMobileCommandFactory::IsAbleToProcess( const int32_t function_id, const app_mngr::commands::Command::CommandSource source) const { UNUSED(source); return buildCommandCreator(function_id, mobile_apis::messageType::INVALID_ENUM, source).CanBeCreated(); } app_mngr::CommandCreator& AppServiceMobileCommandFactory::buildCommandCreator( const int32_t function_id, const int32_t message_type, const app_mngr::commands::Command::CommandSource source) const { auto factory = app_mngr::CommandCreatorFactory( application_manager_, rpc_service_, hmi_capabilities_, policy_handler_); switch (function_id) { case mobile_apis::FunctionID::PublishAppServiceID: if (app_mngr::commands::Command::CommandSource::SOURCE_MOBILE == source) { return mobile_apis::messageType::request == message_type ? factory.GetCreator<commands::PublishAppServiceRequest>() : factory.GetCreator<commands::PublishAppServiceResponse>(); } break; case mobile_apis::FunctionID::OnAppServiceDataID: return app_mngr::commands::Command::CommandSource::SOURCE_MOBILE == source ? factory.GetCreator< commands::OnAppServiceDataNotificationFromMobile>() : factory.GetCreator<commands::OnAppServiceDataNotification>(); case mobile_apis::FunctionID::GetAppServiceDataID: if (app_mngr::commands::Command::CommandSource::SOURCE_MOBILE == source) { return mobile_apis::messageType::request == message_type ? factory.GetCreator<commands::GetAppServiceDataRequest>() : factory.GetCreator< commands::GetAppServiceDataResponseFromMobile>(); } else if (app_mngr::commands::Command::CommandSource::SOURCE_SDL == source) { return mobile_apis::messageType::request == message_type ? factory.GetCreator< commands::GetAppServiceDataRequestToMobile>() : factory.GetCreator<commands::GetAppServiceDataResponse>(); } break; case mobile_apis::FunctionID::PerformAppServiceInteractionID: if (app_mngr::commands::Command::CommandSource::SOURCE_MOBILE == source) { return mobile_apis::messageType::request == message_type ? factory.GetCreator< commands::PerformAppServiceInteractionRequest>() : factory.GetCreator< commands:: PerformAppServiceInteractionResponseFromMobile>(); } else if (app_mngr::commands::Command::CommandSource::SOURCE_SDL == source) { return mobile_apis::messageType::request == message_type ? factory.GetCreator< commands:: PerformAppServiceInteractionRequestToMobile>() : factory.GetCreator< commands::PerformAppServiceInteractionResponse>(); } break; default: LOG4CXX_WARN(logger_, "Unsupported function_id: " << function_id); } return factory.GetCreator<app_mngr::InvalidCommand>(); } } // namespace vehicle_info_plugin <|endoftext|>
<commit_before>#ifndef LUNAR_SLAB_ALLOCATOR #define LUNAR_SLAB_ALLOCATOR #include <new> #include <limits> #include <stdlib.h> #include "slab.hpp" namespace lunar { template <typename T> class slab_allocator { public: typedef T value_type; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; template <class U> struct rebind { typedef slab_allocator<U> other; }; slab_allocator() throw() { if (slab_allocator<T>::m_refcnt == 0) slab_init(&m_slab, sizeof(T)); slab_allocator<T>::m_refcnt++; } slab_allocator(const slab_allocator&) throw() { if (slab_allocator<T>::m_refcnt == 0) slab_init(&m_slab, sizeof(T)); slab_allocator<T>::m_refcnt++; } template <class U> slab_allocator(const slab_allocator<U>&) throw() { if (slab_allocator<U>::m_refcnt == 0) slab_init(&slab_allocator<U>::m_slab, sizeof(U)); slab_allocator<U>::m_refcnt++; } ~slab_allocator() throw() { m_refcnt--; if (m_refcnt == 0) slab_destroy(&m_slab); } pointer address(reference x) const { return &x; } const_pointer address(const_reference x) const { return &x; } pointer allocate(size_type s, void const * = 0) { if (s == 1) { return (pointer)slab_alloc(&m_slab); } else if (s >= 1) { pointer temp = (pointer)malloc(sizeof(void*) + s * sizeof(T)); if (temp == nullptr) return nullptr; void **vp = (void**)temp; *vp = (void*)~(uint64_t)0; return (pointer)((char*)temp + sizeof(void*)); } else { return nullptr; } } void deallocate(pointer p, size_type) { void **vp = (void**)((char*)p - sizeof(void*)); if (*vp == (void*)~(uint64_t)0) free(vp); else slab_free(&m_slab, p); } size_type max_size() const throw() { return std::numeric_limits<size_t>::max() / sizeof(T); } void construct(pointer p, const T& val) { new((void *)p) T(val); } void destroy(pointer p) { p->~T(); } __thread static uint64_t m_refcnt; __thread static slab_chain m_slab; }; template <typename T> __thread uint64_t slab_allocator<T>::m_refcnt = 0; template <typename T> __thread slab_chain slab_allocator<T>::m_slab; } #endif // LUNAR_SLAB_ALLOCATOR<commit_msg>minor fix<commit_after>#ifndef LUNAR_SLAB_ALLOCATOR #define LUNAR_SLAB_ALLOCATOR #include <new> #include <limits> #include <stdlib.h> #include "slab.hpp" namespace lunar { template <typename T> class slab_allocator { public: typedef T value_type; typedef size_t size_type; typedef ptrdiff_t difference_type; typedef T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; template <class U> struct rebind { typedef slab_allocator<U> other; }; slab_allocator() throw() { if (slab_allocator<T>::m_refcnt == 0) slab_init(&m_slab, sizeof(T)); slab_allocator<T>::m_refcnt++; } slab_allocator(const slab_allocator&) throw() { if (slab_allocator<T>::m_refcnt == 0) slab_init(&m_slab, sizeof(T)); slab_allocator<T>::m_refcnt++; } template <class U> slab_allocator(const slab_allocator<U>&) throw() { if (slab_allocator<U>::m_refcnt == 0) slab_init(&slab_allocator<U>::m_slab, sizeof(U)); slab_allocator<U>::m_refcnt++; } ~slab_allocator() throw() { m_refcnt--; if (m_refcnt == 0) slab_destroy(&m_slab); } pointer address(reference x) const { return &x; } const_pointer address(const_reference x) const { return &x; } pointer allocate(size_type s, void const * = 0) { if (s == 1) { return (pointer)slab_alloc(&m_slab); } else if (s >= 1) { pointer temp = (pointer)malloc(sizeof(void*) + s * sizeof(T)); if (temp == nullptr) return nullptr; void **vp = (void**)temp; *vp = (void*)~(uint64_t)0; return (pointer)((char*)temp + sizeof(void*)); } else { return nullptr; } } void deallocate(pointer p, size_type) { void **vp = (void**)((char*)p - sizeof(void*)); if (*vp == (void*)~(uint64_t)0) free(vp); else slab_free(&m_slab, p); } size_type max_size() const throw() { return std::numeric_limits<size_t>::max() / sizeof(T); } void construct(pointer p, const T& val) { new((void *)p) T(val); } void destroy(pointer p) { p->~T(); } static __thread uint64_t m_refcnt; static __thread slab_chain m_slab; }; template <typename T> __thread uint64_t slab_allocator<T>::m_refcnt = 0; template <typename T> __thread slab_chain slab_allocator<T>::m_slab; } #endif // LUNAR_SLAB_ALLOCATOR<|endoftext|>
<commit_before>#include "cpx/WindowsLibraryLoader.hpp" #include "cpx/Exception.hpp" #include "cpx/PluginFactory.hpp" #include <iostream> namespace cpx { WindowsLibraryLoader::WindowsLibraryLoader(cpx::PluginFactory* pluginFactory): _pluginFactory(pluginFactory) { } void WindowsLibraryLoader::loadLibrary(std::string file) { typedef void (__cdecl *InitFct)(cpx::PluginFactory*); if (_loadedLibHandles.find(file)==_loadedLibHandles.end()) { HINSTANCE lib_handle = LoadLibrary(file.c_str()); if (!lib_handle) { DWORD dwLastError = GetLastError(); const unsigned int N = 256; TCHAR lpBuffer[N]; if(dwLastError != 0) { FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM, // It's a system error NULL, // No string to be formatted needed dwLastError, // Hey Windows: Please explain this error! MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), // Do it in the standard language lpBuffer, // Put the message here N-1, // Number of bytes to store the message NULL ); cpx_throw("Error while opening file: '",file,"': ",lpBuffer); } } InitFct initFct = (InitFct) GetProcAddress(lib_handle, "init"); if (!initFct) { DWORD dwLastError = GetLastError(); const unsigned int N = 256; TCHAR lpBuffer[N]; if(dwLastError != 0) { FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM, // It's a system error NULL, // No string to be formatted needed dwLastError, // Hey Windows: Please explain this error! MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), // Do it in the standard language lpBuffer, // Put the message here N-1, // Number of bytes to store the message NULL ); cpx_throw("Error while initializing file: '",file,"': ",lpBuffer); } } (initFct)(_pluginFactory); _loadedLibHandles[file]=lib_handle; } else { cpx_throw("Plugin file '",file,"' already loaded"); } } WindowsLibraryLoader::~WindowsLibraryLoader() { for (auto handle: _loadedLibHandles) { FreeLibrary(handle.second); } } } <commit_msg>try /->\ replacement<commit_after>#include "cpx/WindowsLibraryLoader.hpp" #include "cpx/Exception.hpp" #include "cpx/PluginFactory.hpp" #include <iostream> #include <algorithm> namespace cpx { WindowsLibraryLoader::WindowsLibraryLoader(cpx::PluginFactory* pluginFactory): _pluginFactory(pluginFactory) { } void WindowsLibraryLoader::loadLibrary(std::string file) { typedef void (__cdecl *InitFct)(cpx::PluginFactory*); std::replace( file.begin(), file.end(), '/', '\\'); if (_loadedLibHandles.find(file)==_loadedLibHandles.end()) { HINSTANCE lib_handle = LoadLibraryEx(file.c_str(),NULL,LOAD_LIBRARY_SEARCH_DEFAULT_DIRS); if (!lib_handle) { DWORD dwLastError = GetLastError(); const unsigned int N = 256; TCHAR lpBuffer[N]; if(dwLastError != 0) { FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM, // It's a system error NULL, // No string to be formatted needed dwLastError, // Hey Windows: Please explain this error! MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), // Do it in the standard language lpBuffer, // Put the message here N-1, // Number of bytes to store the message NULL ); cpx_throw("Error while opening file: '",file,"': ",lpBuffer); } } InitFct initFct = (InitFct) GetProcAddress(lib_handle, "init"); if (!initFct) { DWORD dwLastError = GetLastError(); const unsigned int N = 256; TCHAR lpBuffer[N]; if(dwLastError != 0) { FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM, // It's a system error NULL, // No string to be formatted needed dwLastError, // Hey Windows: Please explain this error! MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), // Do it in the standard language lpBuffer, // Put the message here N-1, // Number of bytes to store the message NULL ); cpx_throw("Error while initializing file: '",file,"': ",lpBuffer); } } (initFct)(_pluginFactory); _loadedLibHandles[file]=lib_handle; } else { cpx_throw("Plugin file '",file,"' already loaded"); } } WindowsLibraryLoader::~WindowsLibraryLoader() { for (auto handle: _loadedLibHandles) { FreeLibrary(handle.second); } } } <|endoftext|>
<commit_before>#ifndef LIMONP_CODE_CONVERTER_HPP #define LIMONP_CODE_CONVERTER_HPP #include <iconv.h> #include <iostream> #include <memory.h> namespace Limonp { using namespace std; class CodeConverter { public: CodeConverter(const char *from_charset,const char *to_charset) { _iconv_handle = iconv_open(to_charset,from_charset); } ~CodeConverter() { iconv_close(_iconv_handle); } bool convert(const string& from, string& to) const { char * pfrom = (char*)from.c_str(); size_t from_size = from.size(); to.resize(from_size * 2); // iconv failed, may be you can raise this 2 to bigger number. char * pto = (char*)to.c_str(); size_t to_size = to.size(); if(-1 == iconv(_iconv_handle, &pfrom, &from_size, &pto, &to_size)) { to.clear(); return false; } to.resize(to.size() - to_size); return true; } private: iconv_t _iconv_handle; }; } #endif <commit_msg>update limonp/codeconverter.hpp<commit_after>#ifndef LIMONP_CODE_CONVERTER_HPP #define LIMONP_CODE_CONVERTER_HPP #include <iconv.h> #include <iostream> #include <memory.h> namespace Limonp { using namespace std; class CodeConverter { public: CodeConverter(const char *from_charset,const char *to_charset) { _iconv_handle = iconv_open(to_charset,from_charset); } ~CodeConverter() { iconv_close(_iconv_handle); } bool convert(const string& from, string& to) const { char * pfrom = (char*)from.c_str(); size_t from_size = from.size(); to.resize(from_size * 2); // iconv failed, may be you can raise this 2 to bigger number. char * pto = (char*)to.c_str(); size_t to_size = to.size(); if(-1 == iconv(_iconv_handle, &pfrom, &from_size, &pto, &to_size)) { to.clear(); return false; } to.resize(to.size() - to_size); return true; } private: iconv_t _iconv_handle; }; inline bool code_convert(const char* from_charset, const char* to_charset, const string& from, string& to) { CodeConverter cc(from_charset, to_charset); return cc.convert(from, to); } } #endif <|endoftext|>
<commit_before> // FastNBT.cpp // Implements the fast NBT parser and writer #include "Globals.h" #include "FastNBT.h" // The number of NBT tags that are reserved when an NBT parsing is started. // You can override this by using a cmdline define #ifndef NBT_RESERVE_SIZE #define NBT_RESERVE_SIZE 200 #endif // NBT_RESERVE_SIZE #ifdef _MSC_VER // Dodge a C4127 (conditional expression is constant) for this specific macro usage #define RETURN_FALSE_IF_FALSE(X) do { if (!X) return false; } while ((false, false)) #else #define RETURN_FALSE_IF_FALSE(X) do { if (!X) return false; } while (false) #endif //////////////////////////////////////////////////////////////////////////////// // cParsedNBT: #define NEEDBYTES(N) \ if (m_Length - m_Pos < (size_t)N) \ { \ return false; \ } cParsedNBT::cParsedNBT(const char * a_Data, size_t a_Length) : m_Data(a_Data), m_Length(a_Length), m_Pos(0) { m_IsValid = Parse(); } bool cParsedNBT::Parse(void) { if (m_Length < 3) { // Data too short return false; } if (m_Data[0] != TAG_Compound) { // The top-level tag must be a Compound return false; } m_Tags.reserve(NBT_RESERVE_SIZE); m_Tags.push_back(cFastNBTTag(TAG_Compound, -1)); m_Pos = 1; RETURN_FALSE_IF_FALSE(ReadString(m_Tags.back().m_NameStart, m_Tags.back().m_NameLength)); RETURN_FALSE_IF_FALSE(ReadCompound()); return true; } bool cParsedNBT::ReadString(size_t & a_StringStart, size_t & a_StringLen) { NEEDBYTES(2); a_StringStart = m_Pos + 2; a_StringLen = (size_t)GetBEShort(m_Data + m_Pos); if (a_StringLen > 0xffff) { // Suspicious string length return false; } m_Pos += 2 + a_StringLen; return true; } bool cParsedNBT::ReadCompound(void) { ASSERT(m_Tags.size() > 0); // Reads the latest tag as a compound int ParentIdx = (int)m_Tags.size() - 1; int PrevSibling = -1; for (;;) { NEEDBYTES(1); eTagType TagType = (eTagType)(m_Data[m_Pos]); m_Pos++; if (TagType == TAG_End) { break; } m_Tags.push_back(cFastNBTTag(TagType, ParentIdx, PrevSibling)); if (PrevSibling >= 0) { m_Tags[PrevSibling].m_NextSibling = (int)m_Tags.size() - 1; } else { m_Tags[ParentIdx].m_FirstChild = (int)m_Tags.size() - 1; } PrevSibling = (int)m_Tags.size() - 1; RETURN_FALSE_IF_FALSE(ReadString(m_Tags.back().m_NameStart, m_Tags.back().m_NameLength)); RETURN_FALSE_IF_FALSE(ReadTag()); } // while (true) m_Tags[ParentIdx].m_LastChild = PrevSibling; return true; } bool cParsedNBT::ReadList(eTagType a_ChildrenType) { // Reads the latest tag as a list of items of type a_ChildrenType // Read the count: NEEDBYTES(4); int Count = GetBEInt(m_Data + m_Pos); m_Pos += 4; if (Count < 0) { return false; } // Read items: int ParentIdx = (int)m_Tags.size() - 1; int PrevSibling = -1; for (int i = 0; i < Count; i++) { m_Tags.push_back(cFastNBTTag(a_ChildrenType, ParentIdx, PrevSibling)); if (PrevSibling >= 0) { m_Tags[PrevSibling].m_NextSibling = (int)m_Tags.size() - 1; } else { m_Tags[ParentIdx].m_FirstChild = (int)m_Tags.size() - 1; } PrevSibling = (int)m_Tags.size() - 1; RETURN_FALSE_IF_FALSE(ReadTag()); } // for (i) m_Tags[ParentIdx].m_LastChild = PrevSibling; return true; } #define CASE_SIMPLE_TAG(TAGTYPE, LEN) \ case TAG_##TAGTYPE: \ { \ NEEDBYTES(LEN); \ Tag.m_DataStart = m_Pos; \ Tag.m_DataLength = LEN; \ m_Pos += LEN; \ return true; \ } bool cParsedNBT::ReadTag(void) { cFastNBTTag & Tag = m_Tags.back(); switch (Tag.m_Type) { CASE_SIMPLE_TAG(Byte, 1) CASE_SIMPLE_TAG(Short, 2) CASE_SIMPLE_TAG(Int, 4) CASE_SIMPLE_TAG(Long, 8) CASE_SIMPLE_TAG(Float, 4) CASE_SIMPLE_TAG(Double, 8) case TAG_String: { return ReadString(Tag.m_DataStart, Tag.m_DataLength); } case TAG_ByteArray: { NEEDBYTES(4); int len = GetBEInt(m_Data + m_Pos); m_Pos += 4; if (len < 0) { // Invalid length return false; } NEEDBYTES(len); Tag.m_DataLength = len; Tag.m_DataStart = m_Pos; m_Pos += len; return true; } case TAG_List: { NEEDBYTES(1); eTagType ItemType = (eTagType)m_Data[m_Pos]; m_Pos++; RETURN_FALSE_IF_FALSE(ReadList(ItemType)); return true; } case TAG_Compound: { RETURN_FALSE_IF_FALSE(ReadCompound()); return true; } case TAG_IntArray: { NEEDBYTES(4); int len = GetBEInt(m_Data + m_Pos); m_Pos += 4; if (len < 0) { // Invalid length return false; } len *= 4; NEEDBYTES(len); Tag.m_DataLength = len; Tag.m_DataStart = m_Pos; m_Pos += len; return true; } default: { ASSERT(!"Unhandled NBT tag type"); return false; } } // switch (iType) } #undef CASE_SIMPLE_TAG int cParsedNBT::FindChildByName(int a_Tag, const char * a_Name, size_t a_NameLength) const { if (a_Tag < 0) { return -1; } if (m_Tags[a_Tag].m_Type != TAG_Compound) { return -1; } if (a_NameLength == 0) { a_NameLength = strlen(a_Name); } for (int Child = m_Tags[a_Tag].m_FirstChild; Child != -1; Child = m_Tags[Child].m_NextSibling) { if ( (m_Tags[Child].m_NameLength == a_NameLength) && (memcmp(m_Data + m_Tags[Child].m_NameStart, a_Name, a_NameLength) == 0) ) { return Child; } } // for Child - children of a_Tag return -1; } int cParsedNBT::FindTagByPath(int a_Tag, const AString & a_Path) const { if (a_Tag < 0) { return -1; } size_t Begin = 0; size_t Length = a_Path.length(); int Tag = a_Tag; for (size_t i = 0; i < Length; i++) { if (a_Path[i] != '\\') { continue; } Tag = FindChildByName(Tag, a_Path.c_str() + Begin, i - Begin); if (Tag < 0) { return -1; } Begin = i + 1; } // for i - a_Path[] if (Begin < Length) { Tag = FindChildByName(Tag, a_Path.c_str() + Begin, Length - Begin); } return Tag; } //////////////////////////////////////////////////////////////////////////////// // cFastNBTWriter: cFastNBTWriter::cFastNBTWriter(const AString & a_RootTagName) : m_CurrentStack(0) { m_Stack[0].m_Type = TAG_Compound; m_Result.reserve(100 * 1024); m_Result.push_back(TAG_Compound); WriteString(a_RootTagName.data(), (UInt16)a_RootTagName.size()); } void cFastNBTWriter::BeginCompound(const AString & a_Name) { if (m_CurrentStack >= MAX_STACK - 1) { ASSERT(!"Stack overflow"); return; } TagCommon(a_Name, TAG_Compound); ++m_CurrentStack; m_Stack[m_CurrentStack].m_Type = TAG_Compound; } void cFastNBTWriter::EndCompound(void) { ASSERT(m_CurrentStack > 0); ASSERT(IsStackTopCompound()); m_Result.push_back(TAG_End); --m_CurrentStack; } void cFastNBTWriter::BeginList(const AString & a_Name, eTagType a_ChildrenType) { if (m_CurrentStack >= MAX_STACK - 1) { ASSERT(!"Stack overflow"); return; } TagCommon(a_Name, TAG_List); m_Result.push_back((char)a_ChildrenType); m_Result.append(4, (char)0); ++m_CurrentStack; m_Stack[m_CurrentStack].m_Type = TAG_List; m_Stack[m_CurrentStack].m_Pos = (int)m_Result.size() - 4; m_Stack[m_CurrentStack].m_Count = 0; m_Stack[m_CurrentStack].m_ItemType = a_ChildrenType; } void cFastNBTWriter::EndList(void) { ASSERT(m_CurrentStack > 0); ASSERT(m_Stack[m_CurrentStack].m_Type == TAG_List); // Update the list count: SetBEInt((char *)(m_Result.c_str() + m_Stack[m_CurrentStack].m_Pos), m_Stack[m_CurrentStack].m_Count); --m_CurrentStack; } void cFastNBTWriter::AddByte(const AString & a_Name, unsigned char a_Value) { TagCommon(a_Name, TAG_Byte); m_Result.push_back(a_Value); } void cFastNBTWriter::AddShort(const AString & a_Name, Int16 a_Value) { TagCommon(a_Name, TAG_Short); Int16 Value = htons(a_Value); m_Result.append((const char *)&Value, 2); } void cFastNBTWriter::AddInt(const AString & a_Name, Int32 a_Value) { TagCommon(a_Name, TAG_Int); Int32 Value = htonl(a_Value); m_Result.append((const char *)&Value, 4); } void cFastNBTWriter::AddLong(const AString & a_Name, Int64 a_Value) { TagCommon(a_Name, TAG_Long); Int64 Value = HostToNetwork8(&a_Value); m_Result.append((const char *)&Value, 8); } void cFastNBTWriter::AddFloat(const AString & a_Name, float a_Value) { TagCommon(a_Name, TAG_Float); Int32 Value = HostToNetwork4(&a_Value); m_Result.append((const char *)&Value, 4); } void cFastNBTWriter::AddDouble(const AString & a_Name, double a_Value) { TagCommon(a_Name, TAG_Double); Int64 Value = HostToNetwork8(&a_Value); m_Result.append((const char *)&Value, 8); } void cFastNBTWriter::AddString(const AString & a_Name, const AString & a_Value) { TagCommon(a_Name, TAG_String); Int16 len = htons((short)(a_Value.size())); m_Result.append((const char *)&len, 2); m_Result.append(a_Value.c_str(), a_Value.size()); } void cFastNBTWriter::AddByteArray(const AString & a_Name, const char * a_Value, size_t a_NumElements) { TagCommon(a_Name, TAG_ByteArray); u_long len = htonl((u_long)a_NumElements); m_Result.append((const char *)&len, 4); m_Result.append(a_Value, a_NumElements); } void cFastNBTWriter::AddIntArray(const AString & a_Name, const int * a_Value, size_t a_NumElements) { TagCommon(a_Name, TAG_IntArray); u_long len = htonl((u_long)a_NumElements); size_t cap = m_Result.capacity(); size_t size = m_Result.length(); if ((cap - size) < (4 + a_NumElements * 4)) { m_Result.reserve(size + 4 + (a_NumElements * 4)); } m_Result.append((const char *)&len, 4); for (size_t i = 0; i < a_NumElements; i++) { int Element = htonl(a_Value[i]); m_Result.append((const char *)&Element, 4); } } void cFastNBTWriter::Finish(void) { ASSERT(m_CurrentStack == 0); m_Result.push_back(TAG_End); } void cFastNBTWriter::WriteString(const char * a_Data, UInt16 a_Length) { Int16 Len = htons(a_Length); m_Result.append((const char *)&Len, 2); m_Result.append(a_Data, a_Length); } <commit_msg>FastNBT: Added a sanity check for number of list items.<commit_after> // FastNBT.cpp // Implements the fast NBT parser and writer #include "Globals.h" #include "FastNBT.h" /** If a list being loaded has more than this number of items, it's considered corrupted. */ static const int MAX_LIST_ITEMS = 10000; // The number of NBT tags that are reserved when an NBT parsing is started. // You can override this by using a cmdline define #ifndef NBT_RESERVE_SIZE #define NBT_RESERVE_SIZE 200 #endif // NBT_RESERVE_SIZE #ifdef _MSC_VER // Dodge a C4127 (conditional expression is constant) for this specific macro usage #define RETURN_FALSE_IF_FALSE(X) do { if (!X) return false; } while ((false, false)) #else #define RETURN_FALSE_IF_FALSE(X) do { if (!X) return false; } while (false) #endif //////////////////////////////////////////////////////////////////////////////// // cParsedNBT: #define NEEDBYTES(N) \ if (m_Length - m_Pos < (size_t)N) \ { \ return false; \ } cParsedNBT::cParsedNBT(const char * a_Data, size_t a_Length) : m_Data(a_Data), m_Length(a_Length), m_Pos(0) { m_IsValid = Parse(); } bool cParsedNBT::Parse(void) { if (m_Length < 3) { // Data too short return false; } if (m_Data[0] != TAG_Compound) { // The top-level tag must be a Compound return false; } m_Tags.reserve(NBT_RESERVE_SIZE); m_Tags.push_back(cFastNBTTag(TAG_Compound, -1)); m_Pos = 1; RETURN_FALSE_IF_FALSE(ReadString(m_Tags.back().m_NameStart, m_Tags.back().m_NameLength)); RETURN_FALSE_IF_FALSE(ReadCompound()); return true; } bool cParsedNBT::ReadString(size_t & a_StringStart, size_t & a_StringLen) { NEEDBYTES(2); a_StringStart = m_Pos + 2; a_StringLen = (size_t)GetBEShort(m_Data + m_Pos); if (a_StringLen > 0xffff) { // Suspicious string length return false; } m_Pos += 2 + a_StringLen; return true; } bool cParsedNBT::ReadCompound(void) { ASSERT(m_Tags.size() > 0); // Reads the latest tag as a compound int ParentIdx = (int)m_Tags.size() - 1; int PrevSibling = -1; for (;;) { NEEDBYTES(1); eTagType TagType = (eTagType)(m_Data[m_Pos]); m_Pos++; if (TagType == TAG_End) { break; } m_Tags.push_back(cFastNBTTag(TagType, ParentIdx, PrevSibling)); if (PrevSibling >= 0) { m_Tags[PrevSibling].m_NextSibling = (int)m_Tags.size() - 1; } else { m_Tags[ParentIdx].m_FirstChild = (int)m_Tags.size() - 1; } PrevSibling = (int)m_Tags.size() - 1; RETURN_FALSE_IF_FALSE(ReadString(m_Tags.back().m_NameStart, m_Tags.back().m_NameLength)); RETURN_FALSE_IF_FALSE(ReadTag()); } // while (true) m_Tags[ParentIdx].m_LastChild = PrevSibling; return true; } bool cParsedNBT::ReadList(eTagType a_ChildrenType) { // Reads the latest tag as a list of items of type a_ChildrenType // Read the count: NEEDBYTES(4); int Count = GetBEInt(m_Data + m_Pos); m_Pos += 4; if ((Count < 0) || (Count > MAX_LIST_ITEMS)) { return false; } // Read items: int ParentIdx = (int)m_Tags.size() - 1; int PrevSibling = -1; for (int i = 0; i < Count; i++) { m_Tags.push_back(cFastNBTTag(a_ChildrenType, ParentIdx, PrevSibling)); if (PrevSibling >= 0) { m_Tags[PrevSibling].m_NextSibling = (int)m_Tags.size() - 1; } else { m_Tags[ParentIdx].m_FirstChild = (int)m_Tags.size() - 1; } PrevSibling = (int)m_Tags.size() - 1; RETURN_FALSE_IF_FALSE(ReadTag()); } // for (i) m_Tags[ParentIdx].m_LastChild = PrevSibling; return true; } #define CASE_SIMPLE_TAG(TAGTYPE, LEN) \ case TAG_##TAGTYPE: \ { \ NEEDBYTES(LEN); \ Tag.m_DataStart = m_Pos; \ Tag.m_DataLength = LEN; \ m_Pos += LEN; \ return true; \ } bool cParsedNBT::ReadTag(void) { cFastNBTTag & Tag = m_Tags.back(); switch (Tag.m_Type) { CASE_SIMPLE_TAG(Byte, 1) CASE_SIMPLE_TAG(Short, 2) CASE_SIMPLE_TAG(Int, 4) CASE_SIMPLE_TAG(Long, 8) CASE_SIMPLE_TAG(Float, 4) CASE_SIMPLE_TAG(Double, 8) case TAG_String: { return ReadString(Tag.m_DataStart, Tag.m_DataLength); } case TAG_ByteArray: { NEEDBYTES(4); int len = GetBEInt(m_Data + m_Pos); m_Pos += 4; if (len < 0) { // Invalid length return false; } NEEDBYTES(len); Tag.m_DataLength = len; Tag.m_DataStart = m_Pos; m_Pos += len; return true; } case TAG_List: { NEEDBYTES(1); eTagType ItemType = (eTagType)m_Data[m_Pos]; m_Pos++; RETURN_FALSE_IF_FALSE(ReadList(ItemType)); return true; } case TAG_Compound: { RETURN_FALSE_IF_FALSE(ReadCompound()); return true; } case TAG_IntArray: { NEEDBYTES(4); int len = GetBEInt(m_Data + m_Pos); m_Pos += 4; if (len < 0) { // Invalid length return false; } len *= 4; NEEDBYTES(len); Tag.m_DataLength = len; Tag.m_DataStart = m_Pos; m_Pos += len; return true; } default: { ASSERT(!"Unhandled NBT tag type"); return false; } } // switch (iType) } #undef CASE_SIMPLE_TAG int cParsedNBT::FindChildByName(int a_Tag, const char * a_Name, size_t a_NameLength) const { if (a_Tag < 0) { return -1; } if (m_Tags[a_Tag].m_Type != TAG_Compound) { return -1; } if (a_NameLength == 0) { a_NameLength = strlen(a_Name); } for (int Child = m_Tags[a_Tag].m_FirstChild; Child != -1; Child = m_Tags[Child].m_NextSibling) { if ( (m_Tags[Child].m_NameLength == a_NameLength) && (memcmp(m_Data + m_Tags[Child].m_NameStart, a_Name, a_NameLength) == 0) ) { return Child; } } // for Child - children of a_Tag return -1; } int cParsedNBT::FindTagByPath(int a_Tag, const AString & a_Path) const { if (a_Tag < 0) { return -1; } size_t Begin = 0; size_t Length = a_Path.length(); int Tag = a_Tag; for (size_t i = 0; i < Length; i++) { if (a_Path[i] != '\\') { continue; } Tag = FindChildByName(Tag, a_Path.c_str() + Begin, i - Begin); if (Tag < 0) { return -1; } Begin = i + 1; } // for i - a_Path[] if (Begin < Length) { Tag = FindChildByName(Tag, a_Path.c_str() + Begin, Length - Begin); } return Tag; } //////////////////////////////////////////////////////////////////////////////// // cFastNBTWriter: cFastNBTWriter::cFastNBTWriter(const AString & a_RootTagName) : m_CurrentStack(0) { m_Stack[0].m_Type = TAG_Compound; m_Result.reserve(100 * 1024); m_Result.push_back(TAG_Compound); WriteString(a_RootTagName.data(), (UInt16)a_RootTagName.size()); } void cFastNBTWriter::BeginCompound(const AString & a_Name) { if (m_CurrentStack >= MAX_STACK - 1) { ASSERT(!"Stack overflow"); return; } TagCommon(a_Name, TAG_Compound); ++m_CurrentStack; m_Stack[m_CurrentStack].m_Type = TAG_Compound; } void cFastNBTWriter::EndCompound(void) { ASSERT(m_CurrentStack > 0); ASSERT(IsStackTopCompound()); m_Result.push_back(TAG_End); --m_CurrentStack; } void cFastNBTWriter::BeginList(const AString & a_Name, eTagType a_ChildrenType) { if (m_CurrentStack >= MAX_STACK - 1) { ASSERT(!"Stack overflow"); return; } TagCommon(a_Name, TAG_List); m_Result.push_back((char)a_ChildrenType); m_Result.append(4, (char)0); ++m_CurrentStack; m_Stack[m_CurrentStack].m_Type = TAG_List; m_Stack[m_CurrentStack].m_Pos = (int)m_Result.size() - 4; m_Stack[m_CurrentStack].m_Count = 0; m_Stack[m_CurrentStack].m_ItemType = a_ChildrenType; } void cFastNBTWriter::EndList(void) { ASSERT(m_CurrentStack > 0); ASSERT(m_Stack[m_CurrentStack].m_Type == TAG_List); // Update the list count: SetBEInt((char *)(m_Result.c_str() + m_Stack[m_CurrentStack].m_Pos), m_Stack[m_CurrentStack].m_Count); --m_CurrentStack; } void cFastNBTWriter::AddByte(const AString & a_Name, unsigned char a_Value) { TagCommon(a_Name, TAG_Byte); m_Result.push_back(a_Value); } void cFastNBTWriter::AddShort(const AString & a_Name, Int16 a_Value) { TagCommon(a_Name, TAG_Short); Int16 Value = htons(a_Value); m_Result.append((const char *)&Value, 2); } void cFastNBTWriter::AddInt(const AString & a_Name, Int32 a_Value) { TagCommon(a_Name, TAG_Int); Int32 Value = htonl(a_Value); m_Result.append((const char *)&Value, 4); } void cFastNBTWriter::AddLong(const AString & a_Name, Int64 a_Value) { TagCommon(a_Name, TAG_Long); Int64 Value = HostToNetwork8(&a_Value); m_Result.append((const char *)&Value, 8); } void cFastNBTWriter::AddFloat(const AString & a_Name, float a_Value) { TagCommon(a_Name, TAG_Float); Int32 Value = HostToNetwork4(&a_Value); m_Result.append((const char *)&Value, 4); } void cFastNBTWriter::AddDouble(const AString & a_Name, double a_Value) { TagCommon(a_Name, TAG_Double); Int64 Value = HostToNetwork8(&a_Value); m_Result.append((const char *)&Value, 8); } void cFastNBTWriter::AddString(const AString & a_Name, const AString & a_Value) { TagCommon(a_Name, TAG_String); Int16 len = htons((short)(a_Value.size())); m_Result.append((const char *)&len, 2); m_Result.append(a_Value.c_str(), a_Value.size()); } void cFastNBTWriter::AddByteArray(const AString & a_Name, const char * a_Value, size_t a_NumElements) { TagCommon(a_Name, TAG_ByteArray); u_long len = htonl((u_long)a_NumElements); m_Result.append((const char *)&len, 4); m_Result.append(a_Value, a_NumElements); } void cFastNBTWriter::AddIntArray(const AString & a_Name, const int * a_Value, size_t a_NumElements) { TagCommon(a_Name, TAG_IntArray); u_long len = htonl((u_long)a_NumElements); size_t cap = m_Result.capacity(); size_t size = m_Result.length(); if ((cap - size) < (4 + a_NumElements * 4)) { m_Result.reserve(size + 4 + (a_NumElements * 4)); } m_Result.append((const char *)&len, 4); for (size_t i = 0; i < a_NumElements; i++) { int Element = htonl(a_Value[i]); m_Result.append((const char *)&Element, 4); } } void cFastNBTWriter::Finish(void) { ASSERT(m_CurrentStack == 0); m_Result.push_back(TAG_End); } void cFastNBTWriter::WriteString(const char * a_Data, UInt16 a_Length) { Int16 Len = htons(a_Length); m_Result.append((const char *)&Len, 2); m_Result.append(a_Data, a_Length); } <|endoftext|>
<commit_before>/* * Copyright 2009-2019 The VOTCA Development Team (http://www.votca.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <cassert> #include "../../include/votca/csg/beadstructure.h" #include <votca/tools/graph_bf_visitor.h> #include <votca/tools/graphalgorithm.h> #include <votca/tools/graphdistvisitor.h> using namespace std; using namespace votca; using namespace votca::csg; using namespace votca::tools; /********************** * Internal Functions * **********************/ void BeadStructure::InitializeGraph_() { if (!graphUpToDate) { std::vector<tools::Edge> connections_vector; for (const tools::Edge &edge : connections_) { connections_vector.push_back(edge); } for (std::pair<const Index, BeadInfo> &id_bead_ptr_pair : beads_) { graphnodes_[id_bead_ptr_pair.first] = BeadInfoToGraphNode_(id_bead_ptr_pair.second); } graph_ = tools::Graph(connections_vector, graphnodes_); graphUpToDate = true; } } void BeadStructure::CalculateStructure_() { InitializeGraph_(); if (!structureIdUpToDate) { structure_id_ = tools::findStructureId<tools::GraphDistVisitor>(graph_); structureIdUpToDate = true; } } tools::GraphNode BeadStructure::BeadInfoToGraphNode_( const BeadInfo &bead_info) { std::unordered_map<std::string, double> attributes1; std::unordered_map<std::string, std::string> attributes2; attributes1["Mass"] = bead_info.mass; attributes2["Name"] = bead_info.name; /// Add graphnodes tools::GraphNode graphnode; graphnode.setDouble(attributes1); graphnode.setStr(attributes2); return graphnode; } /*************************** * Public Facing Functions * ***************************/ BeadStructure BeadStructure::getSubStructure( const std::vector<Index> &bead_ids, const std::vector<tools::Edge> &connections) const { BeadStructure new_beadstructure; for (const Index &bead_id : bead_ids) { new_beadstructure.beads_[bead_id] = beads_.at(bead_id); } for (const tools::Edge &edge : connections) { new_beadstructure.ConnectBeads(edge.getEndPoint1(), edge.getEndPoint2()); } return new_beadstructure; } void BeadStructure::ConnectBeads(const Index &bead1_id, const Index &bead2_id) { if (!(beads_.count(bead1_id)) || !(beads_.count(bead2_id))) { std::string err = "Cannot connect beads in bead structure that do not exist"; throw std::invalid_argument(err); } if (bead1_id == bead2_id) { std::string err = "Beads cannot be self-connected"; throw std::invalid_argument(err); } size_t numberOfConnections = connections_.size(); connections_.insert(tools::Edge(bead1_id, bead2_id)); if (numberOfConnections != connections_.size()) { single_structureUpToDate_ = false; graphUpToDate = false; structureIdUpToDate = false; } } tools::Graph BeadStructure::getGraph() { InitializeGraph_(); return graph_; } bool BeadStructure::isSingleStructure() { InitializeGraph_(); if (single_structureUpToDate_ == false) { std::vector<Index> vertices = graph_.getVertices(); if (vertices.size() == 0) { single_structure_ = false; return single_structure_; } // Choose first vertex that is actually in the graph as the starting vertex tools::Graph_BF_Visitor gv_breadth_first; gv_breadth_first.setStartingVertex(vertices.at(0)); if (!singleNetwork(graph_, gv_breadth_first)) { single_structure_ = false; return single_structure_; } if (beads_.size() == 0) { single_structure_ = false; return single_structure_; } if (vertices.size() != beads_.size()) { single_structure_ = false; return single_structure_; } single_structure_ = true; single_structureUpToDate_ = true; } return single_structure_; } bool BeadStructure::isStructureEquivalent(BeadStructure &beadstructure) { if (!structureIdUpToDate) { CalculateStructure_(); } if (!beadstructure.structureIdUpToDate) { beadstructure.CalculateStructure_(); } return structure_id_.compare(beadstructure.structure_id_) == 0; } std::vector<Index> BeadStructure::getNeighBeadIds(const Index &index) { if (!graphUpToDate) { InitializeGraph_(); } std::vector<Index> neighbor_ids = graph_.getNeighVertices(index); return neighbor_ids; } std::vector<Index> BeadStructure::getBeadIds() const { /// Do not use graph_.getVertices() because this would require that the graph /// is updated vector<Index> bead_ids; for (auto &id_and_bead_info : beads_) { bead_ids.push_back(id_and_bead_info.first); } return bead_ids; } <commit_msg>Added exceptions if method requirements are not satisfied<commit_after>/* * Copyright 2009-2019 The VOTCA Development Team (http://www.votca.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <cassert> #include "../../include/votca/csg/beadstructure.h" #include <votca/tools/graph_bf_visitor.h> #include <votca/tools/graphalgorithm.h> #include <votca/tools/graphdistvisitor.h> using namespace std; using namespace votca; using namespace votca::csg; using namespace votca::tools; /********************** * Internal Functions * **********************/ void BeadStructure::InitializeGraph_() { if (!graphUpToDate) { std::vector<tools::Edge> connections_vector; for (const tools::Edge &edge : connections_) { connections_vector.push_back(edge); } for (std::pair<const Index, BeadInfo> &id_bead_ptr_pair : beads_) { graphnodes_[id_bead_ptr_pair.first] = BeadInfoToGraphNode_(id_bead_ptr_pair.second); } graph_ = tools::Graph(connections_vector, graphnodes_); graphUpToDate = true; } } void BeadStructure::CalculateStructure_() { InitializeGraph_(); if (!structureIdUpToDate) { structure_id_ = tools::findStructureId<tools::GraphDistVisitor>(graph_); structureIdUpToDate = true; } } tools::GraphNode BeadStructure::BeadInfoToGraphNode_( const BeadInfo &bead_info) { std::unordered_map<std::string, double> attributes1; std::unordered_map<std::string, std::string> attributes2; attributes1["Mass"] = bead_info.mass; attributes2["Name"] = bead_info.name; /// Add graphnodes tools::GraphNode graphnode; graphnode.setDouble(attributes1); graphnode.setStr(attributes2); return graphnode; } /*************************** * Public Facing Functions * ***************************/ BeadStructure BeadStructure::getSubStructure( const std::vector<Index> &bead_ids, const std::vector<tools::Edge> &connections) const { BeadStructure new_beadstructure; for (const Index &bead_id : bead_ids) { if (beads_.count(bead_id) == 0) { string error_msg = "Cannot get bead substructure from current " "BeadStructure, bead with id " + to_string(bead_id) + " is not found in" " the BeadStructure"; throw runtime_error(error_msg); } new_beadstructure.beads_[bead_id] = beads_.at(bead_id); } for (const tools::Edge &edge : connections) { if (connections_.count(edge) == 0) { string error_msg = "Cannot get bead substructure from current " "BeadStructure, edge between beads " + to_string(edge.getEndPoint1()) + " and " + to_string(edge.getEndPoint2()) + " is not found in the " "BeadStructure"; throw runtime_error(error_msg); } new_beadstructure.ConnectBeads(edge.getEndPoint1(), edge.getEndPoint2()); } return new_beadstructure; } void BeadStructure::ConnectBeads(const Index &bead1_id, const Index &bead2_id) { if (!(beads_.count(bead1_id)) || !(beads_.count(bead2_id))) { std::string err = "Cannot connect beads in bead structure that do not exist"; throw std::invalid_argument(err); } if (bead1_id == bead2_id) { std::string err = "Beads cannot be self-connected"; throw std::invalid_argument(err); } size_t numberOfConnections = connections_.size(); connections_.insert(tools::Edge(bead1_id, bead2_id)); if (numberOfConnections != connections_.size()) { single_structureUpToDate_ = false; graphUpToDate = false; structureIdUpToDate = false; } } tools::Graph BeadStructure::getGraph() { InitializeGraph_(); return graph_; } bool BeadStructure::isSingleStructure() { InitializeGraph_(); if (single_structureUpToDate_ == false) { std::vector<Index> vertices = graph_.getVertices(); if (vertices.size() == 0) { single_structure_ = false; return single_structure_; } // Choose first vertex that is actually in the graph as the starting vertex tools::Graph_BF_Visitor gv_breadth_first; gv_breadth_first.setStartingVertex(vertices.at(0)); if (!singleNetwork(graph_, gv_breadth_first)) { single_structure_ = false; return single_structure_; } if (beads_.size() == 0) { single_structure_ = false; return single_structure_; } if (vertices.size() != beads_.size()) { single_structure_ = false; return single_structure_; } single_structure_ = true; single_structureUpToDate_ = true; } return single_structure_; } bool BeadStructure::isStructureEquivalent(BeadStructure &beadstructure) { if (!structureIdUpToDate) { CalculateStructure_(); } if (!beadstructure.structureIdUpToDate) { beadstructure.CalculateStructure_(); } return structure_id_.compare(beadstructure.structure_id_) == 0; } std::vector<Index> BeadStructure::getNeighBeadIds(const Index &index) { if (!graphUpToDate) { InitializeGraph_(); } std::vector<Index> neighbor_ids = graph_.getNeighVertices(index); return neighbor_ids; } std::vector<Index> BeadStructure::getBeadIds() const { /// Do not use graph_.getVertices() because this would require that the graph /// is updated vector<Index> bead_ids; for (auto &id_and_bead_info : beads_) { bead_ids.push_back(id_and_bead_info.first); } return bead_ids; } <|endoftext|>
<commit_before>#include "game_window.h" #include <sstream> #include <algorithm> bool GameWindow::sdlInitialized = false; bool GameWindow::initialize() { Logger::getInstance()->writeInformation("Initializing graphics"); if (GameWindow::sdlInitialized) { Logger::getInstance()->writeWarning("SDL already initialized"); } else { atexit(SDL_Quit); if( SDL_Init( SDL_INIT_VIDEO ) < 0 ) { Logger::getInstance()->writeError("SDL could not initialize!"); Logger::getInstance()->writeError(SDL_GetError()); GameWindow::sdlInitialized = false; } else { GameWindow::sdlInitialized = true; } } return GameWindow::sdlInitialized; } GameWindow::GameWindow() { this->parser = new ParserYAML(CONFIG_FILE_PATH); this->parser->parse(); TagPantalla tp = this->parser->getPantalla(); this->model = nullptr; this->exit = false; this->focus_x = 0; this->focus_y = 0; this->alto_pantalla = tp.alto; this->ancho_pantalla = tp.ancho; Logger::getInstance()->writeInformation("Creating window"); GameWindow::initialize(); window = SDL_CreateWindow("Trabajo Práctico 7542", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, tp.ancho, tp.alto, SDL_WINDOW_SHOWN); Logger::getInstance()->writeInformation("Creating renderer"); renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED ); SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); // Color: negro opaco SDL_RenderClear(renderer); // Limpio pantalla inicialmente SDL_RenderPresent( renderer ); } GameWindow::~GameWindow() { map<std::string, SpriteSheet*>::const_iterator itr; for(itr = spritesSheets.begin(); itr != spritesSheets.end(); ++itr){ delete itr->second; } delete parser; delete model; Logger::getInstance()->writeInformation("Destroying renderer"); if (renderer) { SDL_DestroyRenderer(renderer); renderer = nullptr; } Logger::getInstance()->writeInformation("Destroying window"); if (window) { SDL_DestroyWindow(window); } else { Logger::getInstance()->writeWarning("Window never initialized"); } } bool GameWindow::endOfGame(){ return this->exit; } void GameWindow::render(){ // Dibujar SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); SDL_RenderClear(renderer); Board & board = *this->model->getBoard(); // Dibujamos el terreno for (size_t x = 0; x < board.sizeX; x++) { for (size_t y = 0; y < board.sizeY; y++) { Entity & tile = board.getTerrain(x, y); spritesSheets[tile.name]->render(tile, 0, renderer, this->alto_pantalla, this->ancho_pantalla); } } std::vector<std::shared_ptr<Entity>> entities = board.getEntities(); std::map<std::string,SpriteSheet*>::iterator it; SpriteSheet* ss; // Ordenamos las entidades por oclusión std::sort(entities.begin(), entities.end(), [](std::shared_ptr<Entity> a, std::shared_ptr<Entity> b) { return ((a->getX() + a->sizeX < b->getX()) || (a->getY() + a->sizeY < b->getY())) && !((b->getX() + b->sizeX < a->getX()) || (b->getY() + b->sizeY < a->getY())); }); for (std::size_t i =0; i < entities.size(); ++i){ it = this->spritesSheets.find(entities[i]->name); if(it != this->spritesSheets.end()){ ss = it->second; ss->render(*entities[i], 0, renderer, this->alto_pantalla, this->ancho_pantalla); } else Logger::getInstance()->writeWarning("No existe SpriteSheet para este tipo de entidad" + entities[i]->name); } SDL_RenderPresent( renderer ); return; } void GameWindow::restart(){ delete model; map<std::string, SpriteSheet*>::const_iterator itr; for(itr = spritesSheets.begin(); itr != spritesSheets.end(); ++itr){ delete itr->second; } spritesSheets.clear(); this->parser->parse(); init(); { auto protagonist = model->getBoard()->getProtagonist(); focus_x = protagonist.getX(); focus_y = protagonist.getY(); } } void GameWindow::init(){ //NO DEBERIA INICIALIZARSE TODO ACA, ME DIO PROBLEMA DE REFERENCIAS LLEVARLO AL PARSER std::vector<TagTipoEntidad> tte = this->parser->getTiposEntidades(); TagConfiguracion tc = this->parser->getConfiguracion(); TagEscenario te = this->parser->getEscenario(); this->model = new Game(te.size_x, te.size_y); Board* board = this->model->getBoard(); addSpriteSheet(ENTIDAD_DEFAULT_NOMBRE, ENTIDAD_DEFAULT_IMAGEN, ENTIDAD_DEFAULT_PIXEL_REF_X, ENTIDAD_DEFAULT_PIXEL_REF_Y, ENTIDAD_DEFAULT_ALTO_SPRITE, ENTIDAD_DEFAULT_ANCHO_SPRITE, ENTIDAD_DEFAULT_CANTIDAD_SPRITES, ENTIDAD_DEFAULT_FPS, ENTIDAD_DEFAULT_DELAY); board->createEntityFactory(ENTIDAD_DEFAULT_NOMBRE, ENTIDAD_DEFAULT_ANCHO_BASE, ENTIDAD_DEFAULT_ALTO_BASE, 0); addSpriteSheet(TERRENO_DEFAULT_NOMBRE, TERRENO_DEFAULT_IMAGEN, TERRENO_DEFAULT_PIXEL_REF_X, TERRENO_DEFAULT_PIXEL_REF_Y, TERRENO_DEFAULT_ALTO_SPRITE, TERRENO_DEFAULT_ANCHO_SPRITE, TERRENO_DEFAULT_CANTIDAD_SPRITES, TERRENO_DEFAULT_FPS, TERRENO_DEFAULT_DELAY); board->createEntityFactory(TERRENO_DEFAULT_NOMBRE, TERRENO_DEFAULT_ANCHO_BASE, TERRENO_DEFAULT_ALTO_BASE, 0); addSpriteSheet(PROTAGONISTA_DEFAULT_NOMBRE, PROTAGONISTA_DEFAULT_IMAGEN, PROTAGONISTA_DEFAULT_PIXEL_REF_X, PROTAGONISTA_DEFAULT_PIXEL_REF_Y, PROTAGONISTA_DEFAULT_ALTO_SPRITE, PROTAGONISTA_DEFAULT_ANCHO_SPRITE, PROTAGONISTA_DEFAULT_CANTIDAD_SPRITES, PROTAGONISTA_DEFAULT_FPS, PROTAGONISTA_DEFAULT_DELAY); board->createEntityFactory(PROTAGONISTA_DEFAULT_NOMBRE, PROTAGONISTA_DEFAULT_ANCHO_BASE, PROTAGONISTA_DEFAULT_ALTO_BASE, VELOCIDAD_PERSONAJE_DEFAULT); for (std::size_t i =0; i < tte.size(); ++i){ addSpriteSheet(tte[i].nombre, tte[i].imagen, tte[i].pixel_ref_x, tte[i].pixel_ref_y, tte[i].alto_sprite, tte[i].ancho_sprite, tte[i].cantidad_sprites, tte[i].fps, tte[i].delay); board->createEntityFactory(tte[i].nombre, tte[i].ancho_base, tte[i].alto_base,tc.vel_personaje); // LA VELOCIDAD DEBERIA IR SOLO AL PROTAGONISTA } for(std::size_t i =0; i < te.terrenos.size(); ++i){ board->setTerrain(te.terrenos[i].tipoEntidad,te.terrenos[i].pos_x,te.terrenos[i].pos_y); // ACA TENDRIA QE VALIDARSE SUPERPOSICION } board->createProtagonist(te.protagonista.tipoEntidad,te.protagonista.pos_x, te.protagonista.pos_y); for(std::size_t i =0; i < te.entidades.size(); ++i){ board->createEntity(te.entidades[i].tipoEntidad,te.entidades[i].pos_x,te.entidades[i].pos_y); // ACA TENDRIA QE VALIDARSE SUPERPOSICION } for(size_t x = 0; x < board->sizeX; x++) { for(size_t y = 0; y < board->sizeY; y++) { if (!&board->getTerrain(x, y)) { board->setTerrain(TERRENO_DEFAULT_NOMBRE, x, y); // VER QUE EL PASTO NO DEBERIA VENIR EN EL ARCHIVO } } } } void GameWindow::update(){ GameTimer::update(); map<std::string, SpriteSheet*>::const_iterator itr; for(itr = spritesSheets.begin(); itr != spritesSheets.end(); ++itr){ itr->second->update(); } model->update(); return; } void GameWindow::addSpriteSheet(std::string name, std::string pPath, int pixelRefX, int pixelRefY, int altoSprite, int anchoSprite, int cantSprites, double fps, double delay) { std::map<std::string,SpriteSheet*>::iterator it; it = this->spritesSheets.find(name); if(it != this->spritesSheets.end()) Logger::getInstance()->writeError("Ya existe un spriteSheet para el tipo de entidad con nombre " + name); else{ spritesSheets[name] = new SpriteSheet(pPath, pixelRefX, pixelRefY, altoSprite, anchoSprite, cantSprites, fps, delay, *this); Logger::getInstance()->writeInformation("Se agrega spriteSheet para el tipo de entidad con nombre " + name); } } void GameWindow::processInput(){ int mouse_x_screen, mouse_y_screen; // Procesar input del usuario while(SDL_PollEvent(EventHandler::getInstance()->getEvent())) { if(EventHandler::getInstance()->getEvent()->type == SDL_QUIT ) this->exit = true; if(EventHandler::getInstance()->getEvent()->type == SDL_KEYDOWN ){ Logger::getInstance()->writeInformation("Teclado"); if(EventHandler::getInstance()->getEvent()->key.keysym.sym == SDLK_r){ restart(); } } if( EventHandler::getInstance()->getEvent()->type == SDL_MOUSEBUTTONUP ){ SDL_GetMouseState(&mouse_x_screen, &mouse_y_screen); std::ostringstream oss; oss << "Mouse en " << mouse_x_screen << "," << mouse_y_screen; // Conversion de coordenadas en pantalla a coordenadas mapa double XsTerm = (double)((double)mouse_x_screen - ancho_pantalla/2)/(double)TILE_WIDTH_DEFAULT; double YsTerm = (double)((double)mouse_y_screen - alto_pantalla/2)/(double)TILE_HEIGHT_DEFAULT; double x_mapa = focus_x + XsTerm + YsTerm + .5; double y_mapa = focus_y - XsTerm + YsTerm + .5; oss << "; mapa: " << x_mapa << "," << y_mapa; Logger::getInstance()->writeInformation(oss.str().c_str()); if( EventHandler::getInstance()->getEvent()->button.button == SDL_BUTTON_LEFT ) { Logger::getInstance()->writeInformation("Boton Izquierdo"); model->getBoard()->getProtagonist().setTarget(x_mapa, y_mapa); } if( EventHandler::getInstance()->getEvent()->button.button == SDL_BUTTON_RIGHT) { Logger::getInstance()->writeInformation("Boton derecho"); } } } } void GameWindow::scroll(){ Uint8 mouse_b; int mouse_x, mouse_y; const double SCROLL_SPEED = 40; double ds = SCROLL_SPEED * model->getBoard()->dt / 1000; //deltascroll SDL_GetMouseState(&mouse_x, &mouse_y); if(mouse_x <= MARGEN_PANTALLA_DEFAULT) { double dsi = (1.0 - ((double)mouse_x / (double)MARGEN_PANTALLA_DEFAULT)) * ds; focus_x -= dsi; focus_y += dsi; Logger::getInstance()->writeInformation("Scrolleando hacia la izquierda"); } else if(mouse_x >= ancho_pantalla - MARGEN_PANTALLA_DEFAULT){ double dsi = ((double)(mouse_x + MARGEN_PANTALLA_DEFAULT - ancho_pantalla)/(double)MARGEN_PANTALLA_DEFAULT) * ds; focus_x += dsi; focus_y -= dsi; Logger::getInstance()->writeInformation("Scrolleando hacia la derecha"); } if(mouse_y <= MARGEN_PANTALLA_DEFAULT) { double dsi = (1.0 - ((double)mouse_y / (double)MARGEN_PANTALLA_DEFAULT)) * ds; focus_x -= dsi; focus_y -= dsi; Logger::getInstance()->writeInformation("Scrolleando hacia arriba"); } if(mouse_y >= alto_pantalla - MARGEN_PANTALLA_DEFAULT) { double dsi = ((double)(mouse_y + MARGEN_PANTALLA_DEFAULT - alto_pantalla)/(double)MARGEN_PANTALLA_DEFAULT) * ds; focus_x += dsi; focus_y += dsi; Logger::getInstance()->writeInformation("Scrolleando hacia abajo"); } auto & board = *(model->getBoard()); if(focus_x >= board.sizeX - 1){ focus_x = board.sizeX - 1; } else if(focus_x < 0){ focus_x = 0; } if(focus_y >= board.sizeY - 1){ focus_y = board.sizeY - 1; }else if(focus_y < 0){ focus_y = 0; } } int GameWindow::start(){ init(); { auto protagonist = model->getBoard()->getProtagonist(); focus_x = protagonist.getX(); focus_y = protagonist.getY(); } while (!endOfGame()) { scroll(); processInput(); update(); render(); SDL_Delay(model->getBoard()->dt); // TODO: Optimizar, sacar hardcodeo } return 0; }<commit_msg>Afino un poco criterio de oclusión<commit_after>#include "game_window.h" #include <sstream> #include <algorithm> bool GameWindow::sdlInitialized = false; bool GameWindow::initialize() { Logger::getInstance()->writeInformation("Initializing graphics"); if (GameWindow::sdlInitialized) { Logger::getInstance()->writeWarning("SDL already initialized"); } else { atexit(SDL_Quit); if( SDL_Init( SDL_INIT_VIDEO ) < 0 ) { Logger::getInstance()->writeError("SDL could not initialize!"); Logger::getInstance()->writeError(SDL_GetError()); GameWindow::sdlInitialized = false; } else { GameWindow::sdlInitialized = true; } } return GameWindow::sdlInitialized; } GameWindow::GameWindow() { this->parser = new ParserYAML(CONFIG_FILE_PATH); this->parser->parse(); TagPantalla tp = this->parser->getPantalla(); this->model = nullptr; this->exit = false; this->focus_x = 0; this->focus_y = 0; this->alto_pantalla = tp.alto; this->ancho_pantalla = tp.ancho; Logger::getInstance()->writeInformation("Creating window"); GameWindow::initialize(); window = SDL_CreateWindow("Trabajo Práctico 7542", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, tp.ancho, tp.alto, SDL_WINDOW_SHOWN); Logger::getInstance()->writeInformation("Creating renderer"); renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED ); SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); // Color: negro opaco SDL_RenderClear(renderer); // Limpio pantalla inicialmente SDL_RenderPresent( renderer ); } GameWindow::~GameWindow() { map<std::string, SpriteSheet*>::const_iterator itr; for(itr = spritesSheets.begin(); itr != spritesSheets.end(); ++itr){ delete itr->second; } delete parser; delete model; Logger::getInstance()->writeInformation("Destroying renderer"); if (renderer) { SDL_DestroyRenderer(renderer); renderer = nullptr; } Logger::getInstance()->writeInformation("Destroying window"); if (window) { SDL_DestroyWindow(window); } else { Logger::getInstance()->writeWarning("Window never initialized"); } } bool GameWindow::endOfGame(){ return this->exit; } void GameWindow::render(){ // Dibujar SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); SDL_RenderClear(renderer); Board & board = *this->model->getBoard(); // Dibujamos el terreno for (size_t x = 0; x < board.sizeX; x++) { for (size_t y = 0; y < board.sizeY; y++) { Entity & tile = board.getTerrain(x, y); spritesSheets[tile.name]->render(tile, 0, renderer, this->alto_pantalla, this->ancho_pantalla); } } std::vector<std::shared_ptr<Entity>> entities = board.getEntities(); std::map<std::string,SpriteSheet*>::iterator it; SpriteSheet* ss; // Ordenamos las entidades por oclusión std::sort(entities.begin(), entities.end(), [](std::shared_ptr<Entity> a, std::shared_ptr<Entity> b) { return ((a->getX() + a->sizeX <= b->getX()) || (a->getY() + a->sizeY <= b->getY())) && !((b->getX() + b->sizeX <= a->getX()) || (b->getY() + b->sizeY <= a->getY())); }); for (std::size_t i =0; i < entities.size(); ++i){ it = this->spritesSheets.find(entities[i]->name); if(it != this->spritesSheets.end()){ ss = it->second; ss->render(*entities[i], 0, renderer, this->alto_pantalla, this->ancho_pantalla); } else Logger::getInstance()->writeWarning("No existe SpriteSheet para este tipo de entidad" + entities[i]->name); } SDL_RenderPresent( renderer ); return; } void GameWindow::restart(){ delete model; map<std::string, SpriteSheet*>::const_iterator itr; for(itr = spritesSheets.begin(); itr != spritesSheets.end(); ++itr){ delete itr->second; } spritesSheets.clear(); this->parser->parse(); init(); { auto protagonist = model->getBoard()->getProtagonist(); focus_x = protagonist.getX(); focus_y = protagonist.getY(); } } void GameWindow::init(){ //NO DEBERIA INICIALIZARSE TODO ACA, ME DIO PROBLEMA DE REFERENCIAS LLEVARLO AL PARSER std::vector<TagTipoEntidad> tte = this->parser->getTiposEntidades(); TagConfiguracion tc = this->parser->getConfiguracion(); TagEscenario te = this->parser->getEscenario(); this->model = new Game(te.size_x, te.size_y); Board* board = this->model->getBoard(); addSpriteSheet(ENTIDAD_DEFAULT_NOMBRE, ENTIDAD_DEFAULT_IMAGEN, ENTIDAD_DEFAULT_PIXEL_REF_X, ENTIDAD_DEFAULT_PIXEL_REF_Y, ENTIDAD_DEFAULT_ALTO_SPRITE, ENTIDAD_DEFAULT_ANCHO_SPRITE, ENTIDAD_DEFAULT_CANTIDAD_SPRITES, ENTIDAD_DEFAULT_FPS, ENTIDAD_DEFAULT_DELAY); board->createEntityFactory(ENTIDAD_DEFAULT_NOMBRE, ENTIDAD_DEFAULT_ANCHO_BASE, ENTIDAD_DEFAULT_ALTO_BASE, 0); addSpriteSheet(TERRENO_DEFAULT_NOMBRE, TERRENO_DEFAULT_IMAGEN, TERRENO_DEFAULT_PIXEL_REF_X, TERRENO_DEFAULT_PIXEL_REF_Y, TERRENO_DEFAULT_ALTO_SPRITE, TERRENO_DEFAULT_ANCHO_SPRITE, TERRENO_DEFAULT_CANTIDAD_SPRITES, TERRENO_DEFAULT_FPS, TERRENO_DEFAULT_DELAY); board->createEntityFactory(TERRENO_DEFAULT_NOMBRE, TERRENO_DEFAULT_ANCHO_BASE, TERRENO_DEFAULT_ALTO_BASE, 0); addSpriteSheet(PROTAGONISTA_DEFAULT_NOMBRE, PROTAGONISTA_DEFAULT_IMAGEN, PROTAGONISTA_DEFAULT_PIXEL_REF_X, PROTAGONISTA_DEFAULT_PIXEL_REF_Y, PROTAGONISTA_DEFAULT_ALTO_SPRITE, PROTAGONISTA_DEFAULT_ANCHO_SPRITE, PROTAGONISTA_DEFAULT_CANTIDAD_SPRITES, PROTAGONISTA_DEFAULT_FPS, PROTAGONISTA_DEFAULT_DELAY); board->createEntityFactory(PROTAGONISTA_DEFAULT_NOMBRE, PROTAGONISTA_DEFAULT_ANCHO_BASE, PROTAGONISTA_DEFAULT_ALTO_BASE, VELOCIDAD_PERSONAJE_DEFAULT); for (std::size_t i =0; i < tte.size(); ++i){ addSpriteSheet(tte[i].nombre, tte[i].imagen, tte[i].pixel_ref_x, tte[i].pixel_ref_y, tte[i].alto_sprite, tte[i].ancho_sprite, tte[i].cantidad_sprites, tte[i].fps, tte[i].delay); board->createEntityFactory(tte[i].nombre, tte[i].ancho_base, tte[i].alto_base,tc.vel_personaje); // LA VELOCIDAD DEBERIA IR SOLO AL PROTAGONISTA } for(std::size_t i =0; i < te.terrenos.size(); ++i){ board->setTerrain(te.terrenos[i].tipoEntidad,te.terrenos[i].pos_x,te.terrenos[i].pos_y); // ACA TENDRIA QE VALIDARSE SUPERPOSICION } board->createProtagonist(te.protagonista.tipoEntidad,te.protagonista.pos_x, te.protagonista.pos_y); for(std::size_t i =0; i < te.entidades.size(); ++i){ board->createEntity(te.entidades[i].tipoEntidad,te.entidades[i].pos_x,te.entidades[i].pos_y); // ACA TENDRIA QE VALIDARSE SUPERPOSICION } for(size_t x = 0; x < board->sizeX; x++) { for(size_t y = 0; y < board->sizeY; y++) { if (!&board->getTerrain(x, y)) { board->setTerrain(TERRENO_DEFAULT_NOMBRE, x, y); // VER QUE EL PASTO NO DEBERIA VENIR EN EL ARCHIVO } } } } void GameWindow::update(){ GameTimer::update(); map<std::string, SpriteSheet*>::const_iterator itr; for(itr = spritesSheets.begin(); itr != spritesSheets.end(); ++itr){ itr->second->update(); } model->update(); return; } void GameWindow::addSpriteSheet(std::string name, std::string pPath, int pixelRefX, int pixelRefY, int altoSprite, int anchoSprite, int cantSprites, double fps, double delay) { std::map<std::string,SpriteSheet*>::iterator it; it = this->spritesSheets.find(name); if(it != this->spritesSheets.end()) Logger::getInstance()->writeError("Ya existe un spriteSheet para el tipo de entidad con nombre " + name); else{ spritesSheets[name] = new SpriteSheet(pPath, pixelRefX, pixelRefY, altoSprite, anchoSprite, cantSprites, fps, delay, *this); Logger::getInstance()->writeInformation("Se agrega spriteSheet para el tipo de entidad con nombre " + name); } } void GameWindow::processInput(){ int mouse_x_screen, mouse_y_screen; // Procesar input del usuario while(SDL_PollEvent(EventHandler::getInstance()->getEvent())) { if(EventHandler::getInstance()->getEvent()->type == SDL_QUIT ) this->exit = true; if(EventHandler::getInstance()->getEvent()->type == SDL_KEYDOWN ){ Logger::getInstance()->writeInformation("Teclado"); if(EventHandler::getInstance()->getEvent()->key.keysym.sym == SDLK_r){ restart(); } } if( EventHandler::getInstance()->getEvent()->type == SDL_MOUSEBUTTONUP ){ SDL_GetMouseState(&mouse_x_screen, &mouse_y_screen); std::ostringstream oss; oss << "Mouse en " << mouse_x_screen << "," << mouse_y_screen; // Conversion de coordenadas en pantalla a coordenadas mapa double XsTerm = (double)((double)mouse_x_screen - ancho_pantalla/2)/(double)TILE_WIDTH_DEFAULT; double YsTerm = (double)((double)mouse_y_screen - alto_pantalla/2)/(double)TILE_HEIGHT_DEFAULT; double x_mapa = focus_x + XsTerm + YsTerm + .5; double y_mapa = focus_y - XsTerm + YsTerm + .5; oss << "; mapa: " << x_mapa << "," << y_mapa; Logger::getInstance()->writeInformation(oss.str().c_str()); if( EventHandler::getInstance()->getEvent()->button.button == SDL_BUTTON_LEFT ) { Logger::getInstance()->writeInformation("Boton Izquierdo"); model->getBoard()->getProtagonist().setTarget(x_mapa, y_mapa); } if( EventHandler::getInstance()->getEvent()->button.button == SDL_BUTTON_RIGHT) { Logger::getInstance()->writeInformation("Boton derecho"); } } } } void GameWindow::scroll(){ Uint8 mouse_b; int mouse_x, mouse_y; const double SCROLL_SPEED = 40; double ds = SCROLL_SPEED * model->getBoard()->dt / 1000; //deltascroll SDL_GetMouseState(&mouse_x, &mouse_y); if(mouse_x <= MARGEN_PANTALLA_DEFAULT) { double dsi = (1.0 - ((double)mouse_x / (double)MARGEN_PANTALLA_DEFAULT)) * ds; focus_x -= dsi; focus_y += dsi; Logger::getInstance()->writeInformation("Scrolleando hacia la izquierda"); } else if(mouse_x >= ancho_pantalla - MARGEN_PANTALLA_DEFAULT){ double dsi = ((double)(mouse_x + MARGEN_PANTALLA_DEFAULT - ancho_pantalla)/(double)MARGEN_PANTALLA_DEFAULT) * ds; focus_x += dsi; focus_y -= dsi; Logger::getInstance()->writeInformation("Scrolleando hacia la derecha"); } if(mouse_y <= MARGEN_PANTALLA_DEFAULT) { double dsi = (1.0 - ((double)mouse_y / (double)MARGEN_PANTALLA_DEFAULT)) * ds; focus_x -= dsi; focus_y -= dsi; Logger::getInstance()->writeInformation("Scrolleando hacia arriba"); } if(mouse_y >= alto_pantalla - MARGEN_PANTALLA_DEFAULT) { double dsi = ((double)(mouse_y + MARGEN_PANTALLA_DEFAULT - alto_pantalla)/(double)MARGEN_PANTALLA_DEFAULT) * ds; focus_x += dsi; focus_y += dsi; Logger::getInstance()->writeInformation("Scrolleando hacia abajo"); } auto & board = *(model->getBoard()); if(focus_x >= board.sizeX - 1){ focus_x = board.sizeX - 1; } else if(focus_x < 0){ focus_x = 0; } if(focus_y >= board.sizeY - 1){ focus_y = board.sizeY - 1; }else if(focus_y < 0){ focus_y = 0; } } int GameWindow::start(){ init(); { auto protagonist = model->getBoard()->getProtagonist(); focus_x = protagonist.getX(); focus_y = protagonist.getY(); } while (!endOfGame()) { scroll(); processInput(); update(); render(); SDL_Delay(model->getBoard()->dt); // TODO: Optimizar, sacar hardcodeo } return 0; } <|endoftext|>
<commit_before><commit_msg>External: ""glm::decompose()" is using float-type instead of templated-type #869" (https://github.com/g-truc/glm/issues/869) related commit<commit_after><|endoftext|>
<commit_before>#ifndef OPENFLOW_INSTRUCTION_H #define OPENFLOW_INSTRUCTION_H #include "of13action.hh" #include "openflow-13.h" #include <list> #include <set> namespace fluid_msg { namespace of13 { class Instruction { protected: uint16_t type_; uint16_t length_; public: Instruction(); Instruction(uint16_t type, uint16_t length); virtual ~Instruction() { } virtual bool equals(const Instruction & other); virtual bool operator==(const Instruction &other) const; virtual bool operator!=(const Instruction &other) const; virtual uint16_t set_order() const { return 0; } virtual Instruction* clone() { return new Instruction(*this); } virtual size_t pack(uint8_t* buffer); virtual of_error unpack(uint8_t* buffer); uint16_t type() { return this->type_; } uint16_t length() { return this->length_; } void type(uint16_t type) { this->type_ = type; } void length(uint16_t length) { this->length_ = length; } static Instruction* make_instruction(uint16_t type); }; struct comp_inst_set_order { bool operator()(Instruction* lhs, Instruction* rhs) const { return lhs->set_order() < rhs->set_order(); } }; class InstructionSet { private: uint16_t length_; std::set<Instruction*, comp_inst_set_order> instruction_set_; public: InstructionSet() : length_(0) { } InstructionSet(std::set<Instruction*> instruction_set); InstructionSet(const InstructionSet &other); InstructionSet& operator=(InstructionSet other); ~InstructionSet(); bool operator==(const InstructionSet &other) const; bool operator!=(const InstructionSet &other) const; size_t pack(uint8_t* buffer); of_error unpack(uint8_t* buffer); friend void swap(InstructionSet& first, InstructionSet& second); uint16_t length() { return this->length_; } std::set<Instruction*, comp_inst_set_order> instruction_set(){ return this->instruction_set_; } void add_instruction(Instruction &inst); void add_instruction(Instruction *inst); void length(uint16_t length) { this->length_ = length; } }; class GoToTable: public Instruction { private: uint8_t table_id_; const uint16_t set_order_; public: GoToTable() : Instruction(of13::OFPIT_GOTO_TABLE, sizeof(struct of13::ofp_instruction_goto_table)), set_order_(60) { } GoToTable(uint8_t table_id); ~GoToTable() { } uint16_t set_order() const { return this->set_order_; } virtual bool equals(const Instruction & other); virtual GoToTable* clone() { return new GoToTable(*this); } size_t pack(uint8_t* buffer); of_error unpack(uint8_t* buffer); uint8_t table_id() { return this->table_id_; } void table_id(uint8_t table_id) { this->table_id_ = table_id; } }; class WriteMetadata: public Instruction { private: uint64_t metadata_; uint64_t metadata_mask_; const uint16_t set_order_; public: WriteMetadata() : Instruction(of13::OFPIT_WRITE_METADATA, sizeof(struct of13::ofp_instruction_write_metadata)), set_order_(50) { } WriteMetadata(uint64_t metadata, uint64_t metadata_mask); ~WriteMetadata() { } uint16_t set_order() const { return this->set_order_; } virtual bool equals(const Instruction & other); virtual WriteMetadata* clone() { return new WriteMetadata(*this); } size_t pack(uint8_t* buffer); of_error unpack(uint8_t* buffer); uint64_t metadata() { return this->metadata_; } uint64_t metadata_mask() { return this->metadata_mask_; } void metadata(uint64_t metadata) { this->metadata_ = metadata; } void metadata_mask(uint64_t metadata_mask) { this->metadata_mask_ = metadata_mask; } }; class WriteActions: public Instruction { private: ActionSet actions_; const uint16_t set_order_; public: WriteActions() : Instruction(of13::OFPIT_WRITE_ACTIONS, sizeof(struct of13::ofp_instruction_actions)), set_order_(40) { } WriteActions(ActionSet actions); ~WriteActions() { } uint16_t set_order() const { return this->set_order_; } virtual bool equals(const Instruction & other); size_t pack(uint8_t* buffer); virtual WriteActions* clone() { return new WriteActions(*this); } of_error unpack(uint8_t* buffer); ActionSet actions() { return this->actions_; } void actions(ActionSet actions); void add_action(Action &action); void add_action(Action* action); }; class ApplyActions: public Instruction { private: ActionList actions_; const uint16_t set_order_; public: ApplyActions() : Instruction(of13::OFPIT_APPLY_ACTIONS, sizeof(struct of13::ofp_instruction_actions)), set_order_(20) { } ApplyActions(ActionList actions); ~ApplyActions() { } uint16_t set_order() const { return this->set_order_; } virtual bool equals(const Instruction & other); virtual ApplyActions* clone() { return new ApplyActions(*this); } size_t pack(uint8_t* buffer); of_error unpack(uint8_t* buffer); ActionList actions() { return this->actions_; } void actions(ActionList actions); void add_action(Action &action); void add_action(Action* action); }; class ClearActions: public Instruction { private: const uint16_t set_order_; public: ClearActions() : Instruction(of13::OFPIT_CLEAR_ACTIONS, sizeof(struct of13::ofp_instruction) + 4), set_order_(30) { } ~ClearActions() { } uint16_t set_order() const { return this->set_order_; } virtual ClearActions* clone() { return new ClearActions(*this); } size_t pack(uint8_t* buffer); of_error unpack(uint8_t* buffer); }; class Meter: public Instruction { private: uint32_t meter_id_; const uint16_t set_order_; public: Meter() : Instruction(of13::OFPIT_METER, sizeof(struct of13::ofp_instruction_meter)), set_order_(10) { } Meter(uint32_t meter_id); ~Meter() { } uint16_t set_order() const { return this->set_order_; } virtual bool equals(const Instruction & other); virtual Meter* clone() { return new Meter(*this); } size_t pack(uint8_t* buffer); of_error unpack(uint8_t* buffer); uint32_t meter_id() { return this->meter_id_; } void meter_id(uint32_t meter_id) { this->meter_id_ = meter_id; } }; class InstructionExperimenter: public Instruction { protected: uint32_t experimenter_; public: InstructionExperimenter() { } InstructionExperimenter(uint32_t experimenter); ~InstructionExperimenter() { } virtual bool equals(const Instruction & other); virtual InstructionExperimenter* clone() { return new InstructionExperimenter(*this); } size_t pack(uint8_t* buffer); of_error unpack(uint8_t* buffer); uint32_t experimenter() { return this->experimenter_; } void experimenter(uint32_t experimenter) { this->experimenter_ = experimenter; } }; } } //End of namespace fluid_msg #endif <commit_msg>Bugfix: Clear-Actions instruction too long.<commit_after>#ifndef OPENFLOW_INSTRUCTION_H #define OPENFLOW_INSTRUCTION_H #include "of13action.hh" #include "openflow-13.h" #include <list> #include <set> namespace fluid_msg { namespace of13 { class Instruction { protected: uint16_t type_; uint16_t length_; public: Instruction(); Instruction(uint16_t type, uint16_t length); virtual ~Instruction() { } virtual bool equals(const Instruction & other); virtual bool operator==(const Instruction &other) const; virtual bool operator!=(const Instruction &other) const; virtual uint16_t set_order() const { return 0; } virtual Instruction* clone() { return new Instruction(*this); } virtual size_t pack(uint8_t* buffer); virtual of_error unpack(uint8_t* buffer); uint16_t type() { return this->type_; } uint16_t length() { return this->length_; } void type(uint16_t type) { this->type_ = type; } void length(uint16_t length) { this->length_ = length; } static Instruction* make_instruction(uint16_t type); }; struct comp_inst_set_order { bool operator()(Instruction* lhs, Instruction* rhs) const { return lhs->set_order() < rhs->set_order(); } }; class InstructionSet { private: uint16_t length_; std::set<Instruction*, comp_inst_set_order> instruction_set_; public: InstructionSet() : length_(0) { } InstructionSet(std::set<Instruction*> instruction_set); InstructionSet(const InstructionSet &other); InstructionSet& operator=(InstructionSet other); ~InstructionSet(); bool operator==(const InstructionSet &other) const; bool operator!=(const InstructionSet &other) const; size_t pack(uint8_t* buffer); of_error unpack(uint8_t* buffer); friend void swap(InstructionSet& first, InstructionSet& second); uint16_t length() { return this->length_; } std::set<Instruction*, comp_inst_set_order> instruction_set(){ return this->instruction_set_; } void add_instruction(Instruction &inst); void add_instruction(Instruction *inst); void length(uint16_t length) { this->length_ = length; } }; class GoToTable: public Instruction { private: uint8_t table_id_; const uint16_t set_order_; public: GoToTable() : Instruction(of13::OFPIT_GOTO_TABLE, sizeof(struct of13::ofp_instruction_goto_table)), set_order_(60) { } GoToTable(uint8_t table_id); ~GoToTable() { } uint16_t set_order() const { return this->set_order_; } virtual bool equals(const Instruction & other); virtual GoToTable* clone() { return new GoToTable(*this); } size_t pack(uint8_t* buffer); of_error unpack(uint8_t* buffer); uint8_t table_id() { return this->table_id_; } void table_id(uint8_t table_id) { this->table_id_ = table_id; } }; class WriteMetadata: public Instruction { private: uint64_t metadata_; uint64_t metadata_mask_; const uint16_t set_order_; public: WriteMetadata() : Instruction(of13::OFPIT_WRITE_METADATA, sizeof(struct of13::ofp_instruction_write_metadata)), set_order_(50) { } WriteMetadata(uint64_t metadata, uint64_t metadata_mask); ~WriteMetadata() { } uint16_t set_order() const { return this->set_order_; } virtual bool equals(const Instruction & other); virtual WriteMetadata* clone() { return new WriteMetadata(*this); } size_t pack(uint8_t* buffer); of_error unpack(uint8_t* buffer); uint64_t metadata() { return this->metadata_; } uint64_t metadata_mask() { return this->metadata_mask_; } void metadata(uint64_t metadata) { this->metadata_ = metadata; } void metadata_mask(uint64_t metadata_mask) { this->metadata_mask_ = metadata_mask; } }; class WriteActions: public Instruction { private: ActionSet actions_; const uint16_t set_order_; public: WriteActions() : Instruction(of13::OFPIT_WRITE_ACTIONS, sizeof(struct of13::ofp_instruction_actions)), set_order_(40) { } WriteActions(ActionSet actions); ~WriteActions() { } uint16_t set_order() const { return this->set_order_; } virtual bool equals(const Instruction & other); size_t pack(uint8_t* buffer); virtual WriteActions* clone() { return new WriteActions(*this); } of_error unpack(uint8_t* buffer); ActionSet actions() { return this->actions_; } void actions(ActionSet actions); void add_action(Action &action); void add_action(Action* action); }; class ApplyActions: public Instruction { private: ActionList actions_; const uint16_t set_order_; public: ApplyActions() : Instruction(of13::OFPIT_APPLY_ACTIONS, sizeof(struct of13::ofp_instruction_actions)), set_order_(20) { } ApplyActions(ActionList actions); ~ApplyActions() { } uint16_t set_order() const { return this->set_order_; } virtual bool equals(const Instruction & other); virtual ApplyActions* clone() { return new ApplyActions(*this); } size_t pack(uint8_t* buffer); of_error unpack(uint8_t* buffer); ActionList actions() { return this->actions_; } void actions(ActionList actions); void add_action(Action &action); void add_action(Action* action); }; class ClearActions: public Instruction { private: const uint16_t set_order_; public: ClearActions() : Instruction(of13::OFPIT_CLEAR_ACTIONS, sizeof(struct of13::ofp_instruction)), set_order_(30) { } ~ClearActions() { } uint16_t set_order() const { return this->set_order_; } virtual ClearActions* clone() { return new ClearActions(*this); } size_t pack(uint8_t* buffer); of_error unpack(uint8_t* buffer); }; class Meter: public Instruction { private: uint32_t meter_id_; const uint16_t set_order_; public: Meter() : Instruction(of13::OFPIT_METER, sizeof(struct of13::ofp_instruction_meter)), set_order_(10) { } Meter(uint32_t meter_id); ~Meter() { } uint16_t set_order() const { return this->set_order_; } virtual bool equals(const Instruction & other); virtual Meter* clone() { return new Meter(*this); } size_t pack(uint8_t* buffer); of_error unpack(uint8_t* buffer); uint32_t meter_id() { return this->meter_id_; } void meter_id(uint32_t meter_id) { this->meter_id_ = meter_id; } }; class InstructionExperimenter: public Instruction { protected: uint32_t experimenter_; public: InstructionExperimenter() { } InstructionExperimenter(uint32_t experimenter); ~InstructionExperimenter() { } virtual bool equals(const Instruction & other); virtual InstructionExperimenter* clone() { return new InstructionExperimenter(*this); } size_t pack(uint8_t* buffer); of_error unpack(uint8_t* buffer); uint32_t experimenter() { return this->experimenter_; } void experimenter(uint32_t experimenter) { this->experimenter_ = experimenter; } }; } } //End of namespace fluid_msg #endif <|endoftext|>
<commit_before>#include "RenderThread.hpp" #include <Core/Engine.hh> #include <Context/SdlContext.hh> #include <Utils/ThreadName.hpp> #include <Threads/Tasks/ToRenderTasks.hpp> #include <Threads/Commands/ToRenderCommands.hpp> #include <Threads/Tasks/BasicTasks.hpp> #include <Context/SdlContext.hh> #include <Utils/Containers/Vector.hpp> #include <Threads/ThreadManager.hpp> #include <Core/Engine.hh> #include <Context/SdlContext.hh> #include <Render/GeometryManagement/Painting/Painter.hh> #include <Render/Pipelining/Pipelines/CustomPipeline/BasicPipeline.hh> #include <Render/Pipelining/Pipelines/CustomPipeline/DeferredShading.hh> #include <Utils/OpenGL.hh> #include <Utils/Age_Imgui.hpp> #include <Render/Properties/Transformation.hh> #include <SpacePartitioning/Ouptut/RenderCamera.hh> #include <SpacePartitioning/Ouptut/RenderLight.hh> #include <SpacePartitioning/Ouptut/RenderPipeline.hh> #include <Utils/Debug.hpp> namespace AGE { RenderThread::RenderThread() : Thread(AGE::Thread::ThreadType::Render) , _context(nullptr), paintingManager(std::make_shared<PaintingManager>()), pipelines(2) { } RenderThread::~RenderThread() {} bool RenderThread::init() { registerCallback<Tasks::Render::CreateRenderContext>([this](Tasks::Render::CreateRenderContext &msg) { _context = msg.engine->setInstance<SdlContext, IRenderContext>(); if (!_context->init(0, 1280, 720, "~AGE~ V0.00001 Demo")) { msg.setValue(false); return; } //pipelines[DEFERRED] = std::make_unique<DeferredShading>(_context->getScreenSize(), paintingManager); pipelines[BASIC] = std::make_unique<DeferredShading>(glm::uvec2(1280, 720), paintingManager); // pipelines[DEFERRED] = std::make_unique<BasicPipeline>(paintingManager); msg.setValue(true); }); registerCallback<Commands::ToRender::Flush>([&](Commands::ToRender::Flush& msg) { _context->swapContext(); glClear(GL_COLOR_BUFFER_BIT); }); registerCallback<Tasks::Render::GetWindowSize>([&](Tasks::Render::GetWindowSize &msg) { msg.setValue(_context->getScreenSize()); }); registerCallback<Tasks::Render::SetWindowSize>([&](Tasks::Render::SetWindowSize& msg) { _context->setScreenSize(msg.size); }); registerCallback<Commands::ToRender::CopyDrawLists>([&](Commands::ToRender::CopyDrawLists& msg) { _drawlistPtr = msg.listContainer; }); registerCallback<Commands::ToRender::RenderDrawLists>([&](Commands::ToRender::RenderDrawLists& msg) { uint32_t pipelineIdx = 0; if (!_drawlistPtr) // nothing to draw return; AGE_ASSERT(_drawlistPtr != nullptr); for (auto &curPipeline : pipelines) { auto &drawlist = _drawlistPtr->container.cameras; for (auto &curCamera : drawlist) { if (pipelineIdx < curCamera.pipelines.size()) { curPipeline->render(curCamera.pipelines[pipelineIdx], curCamera.lights, curCamera.camInfos); } } ++pipelineIdx; } _drawlistPtr = nullptr; }); registerSharedCallback<AGE::Tasks::Basic::BoolFunction>([&](AGE::Tasks::Basic::BoolFunction& msg) { msg.setValue(msg.function()); }); registerCallback<AGE::Tasks::Basic::VoidFunction>([&](AGE::Tasks::Basic::VoidFunction& msg) { if (msg.function) msg.function(); }); registerCallback<AGE::Tasks::Basic::Exit>([&](AGE::Tasks::Basic::Exit& msg) { AGE::CreateEngine()->deleteInstance<IRenderContext>(); this->_insideRun = false; }); #ifdef USE_IMGUI registerCallback<AGE::RenderImgui>([&](AGE::RenderImgui &msg) { AGE::Imgui::getInstance()->renderThreadRenderFn(msg.cmd_lists); }); #endif return true; } bool RenderThread::release() { return true; } bool RenderThread::launch() { if (!init()) return false; _threadHandle = std::thread(&RenderThread::update, std::ref(*this)); return true; } bool RenderThread::stop() { getQueue()->emplaceTask<Tasks::Basic::Exit>(); if (_threadHandle.joinable()) _threadHandle.join(); return true; } bool RenderThread::update() { /* - Tant qu'il n'y a pas de command -> je pop des task - Une fois que j'ai mes commandes -> pour chacunes d'elles -> je regarde si c'est a moi de les traiter (ex : changement de scene) -> si ca n'est pas a moi de les traiter -> je les passe au render context actif -> si il n'y a pas de render context actif, c'est que j'ai fait une erreur, et j'assert dans ta face :D */ _registerId(); _run = true; _insideRun = true; DWORD threadId = GetThreadId(static_cast<HANDLE>(_threadHandle.native_handle())); SetThreadName(threadId, this->_name.c_str()); TMQ::PtrQueue commands; TMQ::PtrQueue tasks; bool commandSuccess; bool taskSuccess; std::chrono::system_clock::time_point waitStart; std::chrono::system_clock::time_point waitEnd; std::chrono::system_clock::time_point workStart; std::chrono::system_clock::time_point workEnd; while (_run && _insideRun) { waitStart = std::chrono::high_resolution_clock::now(); taskSuccess = commandSuccess = false; do { if (_context) _context->refreshInputs(); getQueue()->getTaskAndCommandQueue(tasks, taskSuccess, commands, commandSuccess, TMQ::HybridQueue::Block); } while (!taskSuccess && !commandSuccess); waitEnd = std::chrono::high_resolution_clock::now(); workStart = std::chrono::high_resolution_clock::now(); if (taskSuccess) { while (!tasks.empty() && _insideRun) { //pop all tasks auto task = tasks.front(); assert(execute(task)); // we receive a task that we cannot treat tasks.pop(); taskCounter--; workEnd = std::chrono::high_resolution_clock::now(); const std::size_t toWait = 33; const std::size_t elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(workEnd - workStart).count(); if (elapsed >= toWait) { std::cout << elapsed << ", "; while (!tasks.empty() && _insideRun) { auto task = tasks.front(); getQueue()->moveTask(task, tasks.getFrontSize()); tasks.pop(); } } } } if (commandSuccess) { // pop all commands while (!commands.empty() && _insideRun) { auto command = commands.front(); assert(execute(command)); commands.pop(); } workEnd = std::chrono::high_resolution_clock::now(); GetThreadManager()->updateThreadStatistics(this->_id , std::chrono::duration_cast<std::chrono::microseconds>(workEnd - workStart).count() , std::chrono::duration_cast<std::chrono::microseconds>(waitEnd - waitStart).count()); } } return true; } }<commit_msg>both activated<commit_after>#include "RenderThread.hpp" #include <Core/Engine.hh> #include <Context/SdlContext.hh> #include <Utils/ThreadName.hpp> #include <Threads/Tasks/ToRenderTasks.hpp> #include <Threads/Commands/ToRenderCommands.hpp> #include <Threads/Tasks/BasicTasks.hpp> #include <Context/SdlContext.hh> #include <Utils/Containers/Vector.hpp> #include <Threads/ThreadManager.hpp> #include <Core/Engine.hh> #include <Context/SdlContext.hh> #include <Render/GeometryManagement/Painting/Painter.hh> #include <Render/Pipelining/Pipelines/CustomPipeline/BasicPipeline.hh> #include <Render/Pipelining/Pipelines/CustomPipeline/DeferredShading.hh> #include <Utils/OpenGL.hh> #include <Utils/Age_Imgui.hpp> #include <Render/Properties/Transformation.hh> #include <SpacePartitioning/Ouptut/RenderCamera.hh> #include <SpacePartitioning/Ouptut/RenderLight.hh> #include <SpacePartitioning/Ouptut/RenderPipeline.hh> #include <Utils/Debug.hpp> namespace AGE { RenderThread::RenderThread() : Thread(AGE::Thread::ThreadType::Render) , _context(nullptr), paintingManager(std::make_shared<PaintingManager>()), pipelines(2) { } RenderThread::~RenderThread() {} bool RenderThread::init() { registerCallback<Tasks::Render::CreateRenderContext>([this](Tasks::Render::CreateRenderContext &msg) { _context = msg.engine->setInstance<SdlContext, IRenderContext>(); if (!_context->init(0, 1280, 720, "~AGE~ V0.00001 Demo")) { msg.setValue(false); return; } //pipelines[DEFERRED] = std::make_unique<DeferredShading>(_context->getScreenSize(), paintingManager); pipelines[DEFERRED] = std::make_unique<DeferredShading>(glm::uvec2(1280, 720), paintingManager); pipelines[BASIC] = std::make_unique<BasicPipeline>(paintingManager); msg.setValue(true); }); registerCallback<Commands::ToRender::Flush>([&](Commands::ToRender::Flush& msg) { _context->swapContext(); glClear(GL_COLOR_BUFFER_BIT); }); registerCallback<Tasks::Render::GetWindowSize>([&](Tasks::Render::GetWindowSize &msg) { msg.setValue(_context->getScreenSize()); }); registerCallback<Tasks::Render::SetWindowSize>([&](Tasks::Render::SetWindowSize& msg) { _context->setScreenSize(msg.size); }); registerCallback<Commands::ToRender::CopyDrawLists>([&](Commands::ToRender::CopyDrawLists& msg) { _drawlistPtr = msg.listContainer; }); registerCallback<Commands::ToRender::RenderDrawLists>([&](Commands::ToRender::RenderDrawLists& msg) { uint32_t pipelineIdx = 0; if (!_drawlistPtr) // nothing to draw return; AGE_ASSERT(_drawlistPtr != nullptr); for (auto &curPipeline : pipelines) { auto &drawlist = _drawlistPtr->container.cameras; for (auto &curCamera : drawlist) { if (pipelineIdx < curCamera.pipelines.size()) { curPipeline->render(curCamera.pipelines[pipelineIdx], curCamera.lights, curCamera.camInfos); } } ++pipelineIdx; } _drawlistPtr = nullptr; }); registerSharedCallback<AGE::Tasks::Basic::BoolFunction>([&](AGE::Tasks::Basic::BoolFunction& msg) { msg.setValue(msg.function()); }); registerCallback<AGE::Tasks::Basic::VoidFunction>([&](AGE::Tasks::Basic::VoidFunction& msg) { if (msg.function) msg.function(); }); registerCallback<AGE::Tasks::Basic::Exit>([&](AGE::Tasks::Basic::Exit& msg) { AGE::CreateEngine()->deleteInstance<IRenderContext>(); this->_insideRun = false; }); #ifdef USE_IMGUI registerCallback<AGE::RenderImgui>([&](AGE::RenderImgui &msg) { AGE::Imgui::getInstance()->renderThreadRenderFn(msg.cmd_lists); }); #endif return true; } bool RenderThread::release() { return true; } bool RenderThread::launch() { if (!init()) return false; _threadHandle = std::thread(&RenderThread::update, std::ref(*this)); return true; } bool RenderThread::stop() { getQueue()->emplaceTask<Tasks::Basic::Exit>(); if (_threadHandle.joinable()) _threadHandle.join(); return true; } bool RenderThread::update() { /* - Tant qu'il n'y a pas de command -> je pop des task - Une fois que j'ai mes commandes -> pour chacunes d'elles -> je regarde si c'est a moi de les traiter (ex : changement de scene) -> si ca n'est pas a moi de les traiter -> je les passe au render context actif -> si il n'y a pas de render context actif, c'est que j'ai fait une erreur, et j'assert dans ta face :D */ _registerId(); _run = true; _insideRun = true; DWORD threadId = GetThreadId(static_cast<HANDLE>(_threadHandle.native_handle())); SetThreadName(threadId, this->_name.c_str()); TMQ::PtrQueue commands; TMQ::PtrQueue tasks; bool commandSuccess; bool taskSuccess; std::chrono::system_clock::time_point waitStart; std::chrono::system_clock::time_point waitEnd; std::chrono::system_clock::time_point workStart; std::chrono::system_clock::time_point workEnd; while (_run && _insideRun) { waitStart = std::chrono::high_resolution_clock::now(); taskSuccess = commandSuccess = false; do { if (_context) _context->refreshInputs(); getQueue()->getTaskAndCommandQueue(tasks, taskSuccess, commands, commandSuccess, TMQ::HybridQueue::Block); } while (!taskSuccess && !commandSuccess); waitEnd = std::chrono::high_resolution_clock::now(); workStart = std::chrono::high_resolution_clock::now(); if (taskSuccess) { while (!tasks.empty() && _insideRun) { //pop all tasks auto task = tasks.front(); assert(execute(task)); // we receive a task that we cannot treat tasks.pop(); taskCounter--; workEnd = std::chrono::high_resolution_clock::now(); const std::size_t toWait = 33; const std::size_t elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(workEnd - workStart).count(); if (elapsed >= toWait) { std::cout << elapsed << ", "; while (!tasks.empty() && _insideRun) { auto task = tasks.front(); getQueue()->moveTask(task, tasks.getFrontSize()); tasks.pop(); } } } } if (commandSuccess) { // pop all commands while (!commands.empty() && _insideRun) { auto command = commands.front(); assert(execute(command)); commands.pop(); } workEnd = std::chrono::high_resolution_clock::now(); GetThreadManager()->updateThreadStatistics(this->_id , std::chrono::duration_cast<std::chrono::microseconds>(workEnd - workStart).count() , std::chrono::duration_cast<std::chrono::microseconds>(waitEnd - waitStart).count()); } } return true; } }<|endoftext|>
<commit_before>// Copyright 2016 Benjamin Glatzel // // 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. // Precompiled header file #include "stdafx.h" #include "stdafx_editor.h" // Ui #include "ui_IntrinsicEdPropertyEditorRotation.h" IntrinsicEdPropertyEditorRotation::IntrinsicEdPropertyEditorRotation( rapidjson::Document* p_Document, rapidjson::Value* p_CurrentProperties, rapidjson::Value* p_CurrentProperty, const char* p_PropertyName, QWidget* parent) : QWidget(parent), _properties(p_CurrentProperties), _property(p_CurrentProperty), _propertyName(p_PropertyName), _document(p_Document) { _ui.setupUi(this); updateFromProperty(); QObject::connect(_ui.yaw, SIGNAL(valueChanged(double)), this, SLOT(onValueChanged())); QObject::connect(_ui.pitch, SIGNAL(valueChanged(double)), this, SLOT(onValueChanged())); QObject::connect(_ui.roll, SIGNAL(valueChanged(double)), this, SLOT(onValueChanged())); QObject::connect(_ui.sYaw, SIGNAL(valueChanged(int)), this, SLOT(onSliderValueChanged())); QObject::connect(_ui.sPitch, SIGNAL(valueChanged(int)), this, SLOT(onSliderValueChanged())); QObject::connect(_ui.sRoll, SIGNAL(valueChanged(int)), this, SLOT(onSliderValueChanged())); } IntrinsicEdPropertyEditorRotation::~IntrinsicEdPropertyEditorRotation() {} void IntrinsicEdPropertyEditorRotation::updateFromProperty() { _INTR_ASSERT(_property); const rapidjson::Value& prop = *_property; if (prop["readOnly"].GetBool()) { _ui.yaw->setReadOnly(true); _ui.pitch->setReadOnly(true); _ui.roll->setReadOnly(true); _ui.sYaw->setDisabled(true); _ui.sPitch->setDisabled(true); _ui.sRoll->setDisabled(true); } glm::vec3 euler; if (strcmp(prop["type"].GetString(), "quat") == 0u) { const glm::quat quat = glm::quat(prop["values"][3].GetFloat(), prop["values"][0].GetFloat(), prop["values"][1].GetFloat(), prop["values"][3].GetFloat()); euler = glm::eulerAngles(quat); } else if (strcmp(prop["type"].GetString(), "vec3") == 0u) { euler = glm::vec3(glm::radians(glm::mod(prop["values"][0].GetFloat(), 360.0f)), glm::radians(glm::mod(prop["values"][1].GetFloat(), 360.0f)), glm::radians(glm::mod(prop["values"][2].GetFloat(), 360.0f))); } _ui.yaw->setValue(glm::degrees(euler.x)); _ui.pitch->setValue(glm::degrees(euler.y)); _ui.roll->setValue(glm::degrees(euler.z)); _ui.sYaw->setValue(glm::degrees(euler.x)); _ui.sPitch->setValue(glm::degrees(euler.y)); _ui.sRoll->setValue(glm::degrees(euler.z)); _ui.propertyTitle->setText(_propertyName.c_str()); } void IntrinsicEdPropertyEditorRotation::onValueChanged() { _INTR_ASSERT(_property); rapidjson::Value& prop = *_property; _ui.sYaw->setValue(_ui.yaw->value()); _ui.sPitch->setValue(_ui.pitch->value()); _ui.sRoll->setValue(_ui.roll->value()); const glm::vec3 euler = glm::vec3(glm::radians(_ui.yaw->value()), glm::radians(_ui.pitch->value()), glm::radians(_ui.roll->value())); if (strcmp(prop["type"].GetString(), "quat") == 0u) { const glm::quat quat = glm::quat(euler); prop["values"][0].SetFloat(quat.x); prop["values"][1].SetFloat(quat.y); prop["values"][2].SetFloat(quat.z); prop["values"][3].SetFloat(quat.w); } else if (strcmp(prop["type"].GetString(), "vec3") == 0u) { prop["values"][0].SetFloat(glm::degrees(euler.x)); prop["values"][1].SetFloat(glm::degrees(euler.y)); prop["values"][2].SetFloat(glm::degrees(euler.z)); } emit valueChanged(*_properties); } void IntrinsicEdPropertyEditorRotation::onSliderValueChanged() { _INTR_ASSERT(_property); rapidjson::Value& prop = *_property; _ui.yaw->setValue(_ui.sYaw->value()); _ui.pitch->setValue(_ui.sPitch->value()); _ui.roll->setValue(_ui.sRoll->value()); onValueChanged(); } <commit_msg>Fix: Typo in the IntrinsicEd rotation <> quaternion conversion<commit_after>// Copyright 2016 Benjamin Glatzel // // 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. // Precompiled header file #include "stdafx.h" #include "stdafx_editor.h" // Ui #include "ui_IntrinsicEdPropertyEditorRotation.h" IntrinsicEdPropertyEditorRotation::IntrinsicEdPropertyEditorRotation( rapidjson::Document* p_Document, rapidjson::Value* p_CurrentProperties, rapidjson::Value* p_CurrentProperty, const char* p_PropertyName, QWidget* parent) : QWidget(parent), _properties(p_CurrentProperties), _property(p_CurrentProperty), _propertyName(p_PropertyName), _document(p_Document) { _ui.setupUi(this); updateFromProperty(); QObject::connect(_ui.yaw, SIGNAL(valueChanged(double)), this, SLOT(onValueChanged())); QObject::connect(_ui.pitch, SIGNAL(valueChanged(double)), this, SLOT(onValueChanged())); QObject::connect(_ui.roll, SIGNAL(valueChanged(double)), this, SLOT(onValueChanged())); QObject::connect(_ui.sYaw, SIGNAL(valueChanged(int)), this, SLOT(onSliderValueChanged())); QObject::connect(_ui.sPitch, SIGNAL(valueChanged(int)), this, SLOT(onSliderValueChanged())); QObject::connect(_ui.sRoll, SIGNAL(valueChanged(int)), this, SLOT(onSliderValueChanged())); } IntrinsicEdPropertyEditorRotation::~IntrinsicEdPropertyEditorRotation() {} void IntrinsicEdPropertyEditorRotation::updateFromProperty() { _INTR_ASSERT(_property); const rapidjson::Value& prop = *_property; if (prop["readOnly"].GetBool()) { _ui.yaw->setReadOnly(true); _ui.pitch->setReadOnly(true); _ui.roll->setReadOnly(true); _ui.sYaw->setDisabled(true); _ui.sPitch->setDisabled(true); _ui.sRoll->setDisabled(true); } glm::vec3 euler; if (strcmp(prop["type"].GetString(), "quat") == 0u) { const glm::quat quat = glm::quat(prop["values"][3].GetFloat(), prop["values"][0].GetFloat(), prop["values"][1].GetFloat(), prop["values"][2].GetFloat()); euler = glm::eulerAngles(quat); } else if (strcmp(prop["type"].GetString(), "vec3") == 0u) { euler = glm::vec3(glm::radians(glm::mod(prop["values"][0].GetFloat(), 360.0f)), glm::radians(glm::mod(prop["values"][1].GetFloat(), 360.0f)), glm::radians(glm::mod(prop["values"][2].GetFloat(), 360.0f))); } _ui.yaw->setValue(glm::degrees(euler.x)); _ui.pitch->setValue(glm::degrees(euler.y)); _ui.roll->setValue(glm::degrees(euler.z)); _ui.sYaw->setValue(glm::degrees(euler.x)); _ui.sPitch->setValue(glm::degrees(euler.y)); _ui.sRoll->setValue(glm::degrees(euler.z)); _ui.propertyTitle->setText(_propertyName.c_str()); } void IntrinsicEdPropertyEditorRotation::onValueChanged() { _INTR_ASSERT(_property); rapidjson::Value& prop = *_property; _ui.sYaw->setValue(_ui.yaw->value()); _ui.sPitch->setValue(_ui.pitch->value()); _ui.sRoll->setValue(_ui.roll->value()); const glm::vec3 euler = glm::vec3(glm::radians(_ui.yaw->value()), glm::radians(_ui.pitch->value()), glm::radians(_ui.roll->value())); if (strcmp(prop["type"].GetString(), "quat") == 0u) { const glm::quat quat = glm::quat(euler); prop["values"][0].SetFloat(quat.x); prop["values"][1].SetFloat(quat.y); prop["values"][2].SetFloat(quat.z); prop["values"][3].SetFloat(quat.w); } else if (strcmp(prop["type"].GetString(), "vec3") == 0u) { prop["values"][0].SetFloat(glm::degrees(euler.x)); prop["values"][1].SetFloat(glm::degrees(euler.y)); prop["values"][2].SetFloat(glm::degrees(euler.z)); } emit valueChanged(*_properties); } void IntrinsicEdPropertyEditorRotation::onSliderValueChanged() { _INTR_ASSERT(_property); rapidjson::Value& prop = *_property; _ui.yaw->setValue(_ui.sYaw->value()); _ui.pitch->setValue(_ui.sPitch->value()); _ui.roll->setValue(_ui.sRoll->value()); onValueChanged(); } <|endoftext|>
<commit_before>#pragma once #include <string> #include <chrono> #include <functional> #include <deque> #include "optional.hpp" #include "abstbuff.hpp" #include "serialization/chars.hpp" #include <boost/serialization/access.hpp> #include <boost/serialization/deque.hpp> #include <boost/serialization/vector.hpp> #include <boost/serialization/base_object.hpp> struct stat; namespace spn { class PathBlock { public: enum { Beg = 0, End = 0xffff }; protected: using Path = std::deque<char32_t>; using Segment = std::deque<int>; using OPChar = spn::Optional<char>; //! 絶対パスにおける先頭スラッシュを除いたパス Path _path; //! 区切り文字の前からのオフセット Segment _segment; const static char32_t SC, //!< セパレート文字 DOT, //!< 拡張子の前の記号 EOS, //!< 終端記号 CLN; //!< コロン : bool _bAbsolute; OPChar _driveLetter; //!< ドライブ文字(Windows用。Linuxでは無視) \0=無効 static bool _IsSC(char32_t c); //! パスを分解しながらセグメント長をカウントし、コールバック関数を呼ぶ /*! fromからtoまで1文字ずつ見ながら区切り文字を直す */ template <class CB> static void _ReWriteSC(Path::iterator from, Path::iterator to, char32_t sc, CB cb); static int _ExtGetNum(const std::string& ext); static int _ExtIncNum(std::string& ext, int n=1); template <class CB> void _iterateSegment(const char32_t* c, int /*len*/, char32_t /*sc*/, CB cb) { char32_t tc[128]; auto* pTc = tc; while(*c != EOS) { if(_IsSC(*c)) { *pTc = EOS; cb(tc, pTc-tc); pTc = tc; } else *pTc++ = *c; ++c; } } template <class Itr> static auto _GetDriveLetter(Itr from, Itr to) -> spn::Optional<typename std::decay<decltype(*from)>::type> { using CH = typename std::decay<decltype(*from)>::type; auto cnvToCh = [](char c) { char32_t c2 = static_cast<char32_t>(c); return UTFToN<CH>(reinterpret_cast<const char*>(&c2)).code; }; Itr tmp_from = from; if(to - from >= 3) { auto c = *from; CH cA = cnvToCh('A'), cZ = cnvToCh('Z'), ca = cnvToCh('a'), cz = cnvToCh('z'), col = cnvToCh(':'); if((c >= cA && c <= cZ) || (c >= ca && c <= cz)) { if(*(++from) == col && _IsSC(UTFToN<char32_t>(&*(++from)).code)) return *tmp_from; } } return spn::none; } void _outputHeader(std::u32string& dst, bool bAbs) const; private: friend class boost::serialization::access; template <class Archive> void serialize(Archive& ar, const unsigned int) { std::vector<uint32_t> sv; if(typename Archive::is_saving()) { std::copy(_path.begin(), _path.end(), std::back_inserter(sv)); ar & boost::serialization::make_nvp("path", sv); } if(typename Archive::is_loading()) { ar & boost::serialization::make_nvp("path", sv); _path.clear(); std::copy(sv.begin(), sv.end(), std::back_inserter(_path)); } ar & BOOST_SERIALIZATION_NVP(_segment) & BOOST_SERIALIZATION_NVP(_bAbsolute); } public: template <class C> struct StripResult { using OpC = spn::Optional<C>; bool bAbsolute; OpC driveLetter; int nread; }; template <class C> using OPStripResult = spn::Optional<StripResult<C>>; //! 前後の余分な区切り文字を省く /*! \return [NeedOperation, AbsoluteFlag] */ template <class Itr> static auto StripSC(Itr from, Itr to) -> OPStripResult<typename std::decay<decltype(*from)>::type>; /*! Windowsの場合は何もせずfromを返す Linuxの場合は先頭のドライブ文字を削った後のポインタを返す */ static const char* RemoveDriveLetter(const char* from, const char* to); PathBlock(); PathBlock(const PathBlock&) = default; PathBlock(PathBlock&& p); PathBlock(To32Str p); bool operator == (const PathBlock& p) const; bool operator != (const PathBlock& p) const; PathBlock& operator = (const PathBlock&) = default; PathBlock& operator = (PathBlock&& p); PathBlock& operator <<= (To32Str elem); PathBlock& operator <<= (const PathBlock& p); //! パスを後ろに追加。引数が絶対パスの時は置き換える void pushBack(To32Str elem); void pushBack(const PathBlock& p); void popBack(); //! パスを前に追加。thisが絶対パスの時は置き換える void pushFront(To32Str elem); void pushFront(const PathBlock& p); void popFront(); std::string plain_utf8(bool bAbs=true) const; std::string getFirst_utf8(bool bAbs=true) const; std::string getLast_utf8() const; std::string getSegment_utf8(int beg, int end) const; std::string getHeader_utf8() const; std::u32string plain_utf32(bool bAbs=true) const; std::u32string getFirst_utf32(bool bAbs=true) const; std::u32string getLast_utf32() const; std::u32string getSegment_utf32(int beg, int end) const; std::u32string getHeader_utf32() const; OPChar getDriveLetter() const; int size() const; int segments() const; void setPath(To32Str p); bool isAbsolute() const; bool hasExtention() const; void setExtension(To32Str ext); std::string getExtension(bool bRaw=false) const; int getExtNum() const; int addExtNum(int n=1); void clear(); bool empty() const; }; class URI : public PathBlock { const static std::string SEP; const static std::u32string SEP32; std::string _type; friend class boost::serialization::access; template <class Archive> void serialize(Archive& ar, const unsigned int) { ar & BOOST_SERIALIZATION_NVP(_type) & BOOST_SERIALIZATION_BASE_OBJECT_NVP(PathBlock); } public: URI(); URI(To8Str p); URI(const URI& u) = default; URI(URI&& u); URI(To8Str typ, To8Str path); URI(To8Str typ, const PathBlock& pb); URI& operator = (const URI&) = default; URI& operator = (URI&& u); void setPath(To8Str p); const std::string& getType_utf8() const; std::string plainUri_utf8() const; std::u32string plainUri_utf32() const; void setType(To8Str typ); const PathBlock& path() const; PathBlock& path(); }; uint64_t UnixTime2WinTime(time_t t); time_t WinTime2UnixTime(uint64_t ft); uint64_t u32_u64(uint32_t valH, uint32_t valL); //! ファイルアクセス時間比較用 struct FTime { uint64_t tmAccess, tmModify, tmCreated; bool operator == (const FTime& ft) const; bool operator != (const FTime& ft) const; }; struct FStatus { enum Flag : uint32_t { UserRead = 0x100, UserWrite = 0x80, UserExec = 0x40, UserRWX = UserRead | UserWrite | UserExec, GroupRead = 0x20, GroupWrite = 0x10, GroupExec = 0x08, GroupRWX = GroupRead | GroupWrite | GroupExec, OtherRead = 0x04, OtherWrite = 0x02, OtherExec = 0x01, OtherRWX = OtherRead | OtherWrite | OtherExec, AllRead = UserRead | GroupRead | OtherRead, AllWrite = UserWrite | GroupWrite | OtherWrite, AllExec = UserExec | GroupExec | OtherExec, AllRW = AllRead | AllWrite, FileType = 0x200, DirectoryType = 0x400, NotAvailable = 0x800 }; uint32_t flag; uint32_t userId, groupId; uint64_t size; FTime ftime; FStatus() = default; FStatus(uint32_t flag); bool operator == (const FStatus& fs) const; bool operator != (const FStatus& fs) const; }; } <commit_msg>PathBlock: シリアライズデータ形式を変更<commit_after>#pragma once #include <string> #include <chrono> #include <functional> #include <deque> #include "optional.hpp" #include "abstbuff.hpp" #include "serialization/chars.hpp" #include <boost/serialization/access.hpp> #include <boost/serialization/deque.hpp> #include <boost/serialization/vector.hpp> #include <boost/serialization/base_object.hpp> struct stat; namespace spn { class PathBlock { public: enum { Beg = 0, End = 0xffff }; protected: using Path = std::deque<char32_t>; using Segment = std::deque<int>; using OPChar = spn::Optional<char>; //! 絶対パスにおける先頭スラッシュを除いたパス Path _path; //! 区切り文字の前からのオフセット Segment _segment; const static char32_t SC, //!< セパレート文字 DOT, //!< 拡張子の前の記号 EOS, //!< 終端記号 CLN; //!< コロン : bool _bAbsolute; OPChar _driveLetter; //!< ドライブ文字(Windows用。Linuxでは無視) \0=無効 static bool _IsSC(char32_t c); //! パスを分解しながらセグメント長をカウントし、コールバック関数を呼ぶ /*! fromからtoまで1文字ずつ見ながら区切り文字を直す */ template <class CB> static void _ReWriteSC(Path::iterator from, Path::iterator to, char32_t sc, CB cb); static int _ExtGetNum(const std::string& ext); static int _ExtIncNum(std::string& ext, int n=1); template <class CB> void _iterateSegment(const char32_t* c, int /*len*/, char32_t /*sc*/, CB cb) { char32_t tc[128]; auto* pTc = tc; while(*c != EOS) { if(_IsSC(*c)) { *pTc = EOS; cb(tc, pTc-tc); pTc = tc; } else *pTc++ = *c; ++c; } } template <class Itr> static auto _GetDriveLetter(Itr from, Itr to) -> spn::Optional<typename std::decay<decltype(*from)>::type> { using CH = typename std::decay<decltype(*from)>::type; auto cnvToCh = [](char c) { char32_t c2 = static_cast<char32_t>(c); return UTFToN<CH>(reinterpret_cast<const char*>(&c2)).code; }; Itr tmp_from = from; if(to - from >= 3) { auto c = *from; CH cA = cnvToCh('A'), cZ = cnvToCh('Z'), ca = cnvToCh('a'), cz = cnvToCh('z'), col = cnvToCh(':'); if((c >= cA && c <= cZ) || (c >= ca && c <= cz)) { if(*(++from) == col && _IsSC(UTFToN<char32_t>(&*(++from)).code)) return *tmp_from; } } return spn::none; } void _outputHeader(std::u32string& dst, bool bAbs) const; private: friend class boost::serialization::access; template <class Archive> void serialize(Archive& ar, const unsigned int) { // UTF-8文字列として書き出し std::string path; if(typename Archive::is_saving()) { path = plain_utf8(); ar & BOOST_SERIALIZATION_NVP(path); } if(typename Archive::is_loading()) { ar & BOOST_SERIALIZATION_NVP(path); setPath(path); } } public: template <class C> struct StripResult { using OpC = spn::Optional<C>; bool bAbsolute; OpC driveLetter; int nread; }; template <class C> using OPStripResult = spn::Optional<StripResult<C>>; //! 前後の余分な区切り文字を省く /*! \return [NeedOperation, AbsoluteFlag] */ template <class Itr> static auto StripSC(Itr from, Itr to) -> OPStripResult<typename std::decay<decltype(*from)>::type>; /*! Windowsの場合は何もせずfromを返す Linuxの場合は先頭のドライブ文字を削った後のポインタを返す */ static const char* RemoveDriveLetter(const char* from, const char* to); PathBlock(); PathBlock(const PathBlock&) = default; PathBlock(PathBlock&& p); PathBlock(To32Str p); bool operator == (const PathBlock& p) const; bool operator != (const PathBlock& p) const; PathBlock& operator = (const PathBlock&) = default; PathBlock& operator = (PathBlock&& p); PathBlock& operator <<= (To32Str elem); PathBlock& operator <<= (const PathBlock& p); //! パスを後ろに追加。引数が絶対パスの時は置き換える void pushBack(To32Str elem); void pushBack(const PathBlock& p); void popBack(); //! パスを前に追加。thisが絶対パスの時は置き換える void pushFront(To32Str elem); void pushFront(const PathBlock& p); void popFront(); std::string plain_utf8(bool bAbs=true) const; std::string getFirst_utf8(bool bAbs=true) const; std::string getLast_utf8() const; std::string getSegment_utf8(int beg, int end) const; std::string getHeader_utf8() const; std::u32string plain_utf32(bool bAbs=true) const; std::u32string getFirst_utf32(bool bAbs=true) const; std::u32string getLast_utf32() const; std::u32string getSegment_utf32(int beg, int end) const; std::u32string getHeader_utf32() const; OPChar getDriveLetter() const; int size() const; int segments() const; void setPath(To32Str p); bool isAbsolute() const; bool hasExtention() const; void setExtension(To32Str ext); std::string getExtension(bool bRaw=false) const; int getExtNum() const; int addExtNum(int n=1); void clear(); bool empty() const; }; class URI : public PathBlock { const static std::string SEP; const static std::u32string SEP32; std::string _type; friend class boost::serialization::access; template <class Archive> void serialize(Archive& ar, const unsigned int) { ar & BOOST_SERIALIZATION_NVP(_type) & BOOST_SERIALIZATION_BASE_OBJECT_NVP(PathBlock); } public: URI(); URI(To8Str p); URI(const URI& u) = default; URI(URI&& u); URI(To8Str typ, To8Str path); URI(To8Str typ, const PathBlock& pb); URI& operator = (const URI&) = default; URI& operator = (URI&& u); void setPath(To8Str p); const std::string& getType_utf8() const; std::string plainUri_utf8() const; std::u32string plainUri_utf32() const; void setType(To8Str typ); const PathBlock& path() const; PathBlock& path(); }; uint64_t UnixTime2WinTime(time_t t); time_t WinTime2UnixTime(uint64_t ft); uint64_t u32_u64(uint32_t valH, uint32_t valL); //! ファイルアクセス時間比較用 struct FTime { uint64_t tmAccess, tmModify, tmCreated; bool operator == (const FTime& ft) const; bool operator != (const FTime& ft) const; }; struct FStatus { enum Flag : uint32_t { UserRead = 0x100, UserWrite = 0x80, UserExec = 0x40, UserRWX = UserRead | UserWrite | UserExec, GroupRead = 0x20, GroupWrite = 0x10, GroupExec = 0x08, GroupRWX = GroupRead | GroupWrite | GroupExec, OtherRead = 0x04, OtherWrite = 0x02, OtherExec = 0x01, OtherRWX = OtherRead | OtherWrite | OtherExec, AllRead = UserRead | GroupRead | OtherRead, AllWrite = UserWrite | GroupWrite | OtherWrite, AllExec = UserExec | GroupExec | OtherExec, AllRW = AllRead | AllWrite, FileType = 0x200, DirectoryType = 0x400, NotAvailable = 0x800 }; uint32_t flag; uint32_t userId, groupId; uint64_t size; FTime ftime; FStatus() = default; FStatus(uint32_t flag); bool operator == (const FStatus& fs) const; bool operator != (const FStatus& fs) const; }; } <|endoftext|>
<commit_before>/* Copyright (C) 2013-2015 The Communi Project 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 copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 "bufferproxymodel.h" #include "simplecrypt.h" #include "zncmanager.h" #include <QCoreApplication> #include <QTimer> #include <IrcBufferModel> #include <IrcConnection> #include <IrcBuffer> IRC_USE_NAMESPACE class IrcServerBuffer : public IrcBuffer { Q_OBJECT public: explicit IrcServerBuffer(QObject* parent = 0) : IrcBuffer(parent) { } ~IrcServerBuffer() { quit(tr("%1 %2").arg(qApp->applicationName(), qApp->applicationVersion())); } public slots: void close(const QString& reason) { quit(reason); IrcBuffer::close(reason); } private slots: void quit(const QString& reason) { IrcConnection* connection = IrcBuffer::connection(); if (connection && connection->isActive()) { connection->quit(reason); connection->close(); } } }; BufferProxyModel::BufferProxyModel(QObject* parent) : RowsJoinerProxy(parent) { } IrcBuffer* BufferProxyModel::get(int index) const { foreach (QAbstractItemModel* aim, RowsJoinerProxy::models()) { IrcBufferModel* model = qobject_cast<IrcBufferModel*>(aim); if (model) { int count = model->count(); if (index < count) return model->get(index); index -= count; } } return 0; } int BufferProxyModel::indexOf(IrcBuffer* buffer) const { int count = 0; foreach (QAbstractItemModel* aim, RowsJoinerProxy::models()) { IrcBufferModel* model = qobject_cast<IrcBufferModel*>(aim); if (model) { int index = model->indexOf(buffer); if (index != -1) return count + index; count += model->count(); } } return -1; } QList<QObject*> BufferProxyModel::models() const { return m_models; } QList<QObject*> BufferProxyModel::servers() const { return m_servers; } QList<QObject*> BufferProxyModel::connections() const { return m_connections; } IrcBuffer* BufferProxyModel::currentBuffer() const { return m_current; } void BufferProxyModel::setCurrentBuffer(IrcBuffer* buffer) { if (m_current != buffer) { m_current = buffer; emit currentBufferChanged(buffer); } } QObject* BufferProxyModel::model(IrcConnection* connection) const { if (connection) return connection->findChild<IrcBufferModel*>(); return 0; } QObject* BufferProxyModel::server(IrcConnection* connection) const { if (connection) return connection->findChild<IrcServerBuffer*>(); return 0; } void BufferProxyModel::addConnection(IrcConnection* connection) { IrcBufferModel* model = new IrcBufferModel(connection); model->setSortMethod(Irc::SortByTitle); connect(model, SIGNAL(added(IrcBuffer*)), this, SIGNAL(bufferAdded(IrcBuffer*))); connect(model, SIGNAL(removed(IrcBuffer*)), this, SIGNAL(bufferRemoved(IrcBuffer*))); connect(model, SIGNAL(aboutToBeAdded(IrcBuffer*)), this, SIGNAL(bufferAboutToBeAdded(IrcBuffer*))); connect(model, SIGNAL(aboutToBeRemoved(IrcBuffer*)), this, SIGNAL(bufferAboutToBeRemoved(IrcBuffer*))); ZncManager* znc = new ZncManager(model); znc->setModel(model); IrcServerBuffer* buffer = new IrcServerBuffer(model); connect(buffer, SIGNAL(destroyed(IrcBuffer*)), this, SLOT(closeConnection(IrcBuffer*))); buffer->setName(connection->displayName()); buffer->setSticky(true); model->add(buffer); connection->setReconnectDelay(15); // TODO: settings? connect(connection, SIGNAL(displayNameChanged(QString)), buffer, SLOT(setName(QString))); connect(model, SIGNAL(messageIgnored(IrcMessage*)), this, SLOT(processMessage(IrcMessage*))); connect(connection, SIGNAL(connected()), this, SLOT(onConnected())); connect(connection, SIGNAL(disconnected()), this, SLOT(onDisconnected())); connect(connection, SIGNAL(enabledChanged(bool)), this, SLOT(onConnectionEnabledChanged(bool))); connect(connection, SIGNAL(nickNameRequired(QString,QString*)), this, SLOT(onNickNameRequired(QString))); connect(connection, SIGNAL(channelKeyRequired(QString,QString*)), this, SLOT(onChannelKeyRequired(QString))); // Give bouncers a sec or two to start joining channels after getting connected. // If that happens, the saved buffers shouldn't be restored to avoid restoring // a buffer that was closed using another client meanwhile. QTimer* timer = new QTimer(connection); timer->setSingleShot(true); timer->setInterval(2000); connect(connection, SIGNAL(connected()), timer, SLOT(start())); QObject::connect(timer, &QTimer::timeout, [=]() -> void { bool hasActiveChannels = false; foreach (const QString& name, model->channels()) { IrcBuffer* channel = model->find(name); if (channel && channel->isActive()) { hasActiveChannels = true; break; } } if (!hasActiveChannels) model->restoreState(model->property("savedState").toByteArray()); connect(model, SIGNAL(buffersChanged(QList<IrcBuffer*>)), this, SLOT(onModelBuffersChanged())); }); m_connections.append(connection); m_servers.append(buffer); m_models.append(model); emit connectionAdded(connection); emit connectionsChanged(); emit serversChanged(); emit modelsChanged(); insertSourceModel(model); } void BufferProxyModel::removeConnection(IrcConnection* connection) { disconnect(connection, SIGNAL(connected()), this, SLOT(onConnected())); disconnect(connection, SIGNAL(disconnected()), this, SLOT(onDisconnected())); IrcBufferModel* model = connection->findChild<IrcBufferModel*>(); if (model) { disconnect(model, SIGNAL(added(IrcBuffer*)), this, SIGNAL(bufferAdded(IrcBuffer*))); disconnect(model, SIGNAL(removed(IrcBuffer*)), this, SIGNAL(bufferRemoved(IrcBuffer*))); disconnect(model, SIGNAL(aboutToBeAdded(IrcBuffer*)), this, SIGNAL(bufferAboutToBeAdded(IrcBuffer*))); disconnect(model, SIGNAL(aboutToBeRemoved(IrcBuffer*)), this, SIGNAL(bufferAboutToBeRemoved(IrcBuffer*))); int index = m_connections.indexOf(connection); if (index != -1) { if (QObject* server = m_servers.takeAt(index)) server->disconnect(this); if (QObject* model = m_models.takeAt(index)) model->deleteLater(); if (QObject* connection = m_connections.takeAt(index)) connection->deleteLater(); emit connectionRemoved(connection); emit connectionsChanged(); emit serversChanged(); emit modelsChanged(); removeSourceModel(model); if (m_models.isEmpty()) emit reseted(); } } } QHash<int, QByteArray> BufferProxyModel::roleNames() const { QHash<int, QByteArray> roles; roles[Qt::DisplayRole] = "display"; roles[Qt::UserRole] = "section"; roles[Irc::BufferRole] = "buffer"; roles[Irc::ChannelRole] = "channel"; roles[Irc::NameRole] = "name"; roles[Irc::PrefixRole] = "prefix"; roles[Irc::TitleRole] = "title"; return roles; } QVariant BufferProxyModel::data(const QModelIndex& index, int role) const { if (role == Qt::UserRole) { IrcBuffer* buffer = data(index, Irc::BufferRole).value<IrcBuffer*>(); if (buffer) return m_connections.indexOf(buffer->connection()); // TODO: optimize } return RowsJoinerProxy::data(index, role); } QByteArray BufferProxyModel::saveState() const { QVariantList modelStates; QVariantList connectionStates; SimpleCrypt crypto(Q_UINT64_C(0xff610ed9de767b09)); foreach (QAbstractItemModel* aim, RowsJoinerProxy::models()) { IrcBufferModel* model = qobject_cast<IrcBufferModel*>(aim); if (model) { IrcConnection* connection = model->connection(); connectionStates += crypto.encryptToByteArray(connection->saveState()); // do not save the server buffer - let addConnection() handle it when restoring bool wasConnected = connection->isEnabled() && connection->isConnected(); model->remove(model->get(0)); if (wasConnected) modelStates += crypto.encryptToByteArray(model->saveState()); else modelStates += crypto.encryptToByteArray(model->property("savedState").toByteArray()); } } QVariantMap state; state.insert("models", modelStates); state.insert("connections", connectionStates); QByteArray data; QDataStream out(&data, QIODevice::WriteOnly); out << state; return data; } bool BufferProxyModel::restoreState(const QByteArray& data) { QVariantMap state; QDataStream in(data); in >> state; if (in.status() != QDataStream::Ok) return false; QVariantList modelStates = state.value("models").toList(); QVariantList connectionStates = state.value("connections").toList(); SimpleCrypt crypto(Q_UINT64_C(0xff610ed9de767b09)); for (int i = 0; i < connectionStates.length(); ++i) { IrcConnection* connection = new IrcConnection(this); QByteArray cs = crypto.decryptToByteArray(connectionStates.at(i).toByteArray()); connection->restoreState(!crypto.lastError() ? cs : connectionStates.at(i).toByteArray()); addConnection(connection); IrcBufferModel* model = connection->findChild<IrcBufferModel*>(); QByteArray ms = crypto.decryptToByteArray(modelStates.value(i).toByteArray()); model->setProperty("savedState", !crypto.lastError() ? ms : modelStates.value(i)); } return true; } void BufferProxyModel::onConnected() { IrcConnection* connection = qobject_cast<IrcConnection*>(sender()); if (connection) emit connected(connection); } void BufferProxyModel::onDisconnected() { IrcConnection* connection = qobject_cast<IrcConnection*>(sender()); if (connection) emit disconnected(connection); } void BufferProxyModel::onModelBuffersChanged() { IrcBufferModel* model = qobject_cast<IrcBufferModel*>(sender()); if (model) { IrcConnection* connection = model->connection(); if (connection && connection->isConnected()) model->setProperty("savedState", model->saveState()); } } void BufferProxyModel::onConnectionEnabledChanged(bool enabled) { // store the model state when a connection is disabled // see #25: Don't save/restore buffers for disabled connections if (!enabled) { IrcConnection* connection = qobject_cast<IrcConnection*>(sender()); if (connection) { IrcBufferModel* model = connection->findChild<IrcBufferModel*>(); if (model && model->count() > 1) model->setProperty("savedState", model->saveState()); } } } void BufferProxyModel::closeConnection(IrcBuffer* buffer) { removeConnection(buffer->connection()); } void BufferProxyModel::onChannelKeyRequired(const QString& channel) { IrcConnection* connection = qobject_cast<IrcConnection*>(sender()); if (connection) emit channelKeyRequired(connection, channel); } void BufferProxyModel::onNickNameRequired(const QString& reserved) { IrcConnection* connection = qobject_cast<IrcConnection*>(sender()); if (connection) emit nickNameRequired(connection, reserved); } void BufferProxyModel::processMessage(IrcMessage* message) { IrcBufferModel* model = message->connection()->findChild<IrcBufferModel*>(); if (model) { // deliver targeted ChanServ notices to the target channel // ":ChanServ!ChanServ@services. NOTICE myself :[#channel] foo bar..." if (message->type() == IrcMessage::Notice) { if (message->prefix() == "ChanServ!ChanServ@services.") { QString content = static_cast<IrcNoticeMessage*>(message)->content(); if (content.startsWith("[")) { int i = content.indexOf("]"); if (i != -1) { QString title = content.mid(1, i - 1); IrcBuffer* buffer = model->find(title); if (buffer) { message->setProperty("forwarded", true); buffer->receiveMessage(message); return; } } } } if (m_current && m_current->model() == model) { m_current->receiveMessage(message); return; } } if (IrcBuffer* buffer = model->get(0)) buffer->receiveMessage(message); } } #include "bufferproxymodel.moc" <commit_msg>Use IrcCommandQueue<commit_after>/* Copyright (C) 2013-2015 The Communi Project 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 copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 "bufferproxymodel.h" #include "simplecrypt.h" #include "zncmanager.h" #include <QCoreApplication> #include <QTimer> #include <IrcCommandQueue> #include <IrcBufferModel> #include <IrcConnection> #include <IrcBuffer> IRC_USE_NAMESPACE class IrcServerBuffer : public IrcBuffer { Q_OBJECT public: explicit IrcServerBuffer(QObject* parent = 0) : IrcBuffer(parent) { } ~IrcServerBuffer() { quit(tr("%1 %2").arg(qApp->applicationName(), qApp->applicationVersion())); } public slots: void close(const QString& reason) { quit(reason); IrcBuffer::close(reason); } private slots: void quit(const QString& reason) { IrcConnection* connection = IrcBuffer::connection(); if (connection && connection->isActive()) { connection->quit(reason); connection->close(); } } }; BufferProxyModel::BufferProxyModel(QObject* parent) : RowsJoinerProxy(parent) { } IrcBuffer* BufferProxyModel::get(int index) const { foreach (QAbstractItemModel* aim, RowsJoinerProxy::models()) { IrcBufferModel* model = qobject_cast<IrcBufferModel*>(aim); if (model) { int count = model->count(); if (index < count) return model->get(index); index -= count; } } return 0; } int BufferProxyModel::indexOf(IrcBuffer* buffer) const { int count = 0; foreach (QAbstractItemModel* aim, RowsJoinerProxy::models()) { IrcBufferModel* model = qobject_cast<IrcBufferModel*>(aim); if (model) { int index = model->indexOf(buffer); if (index != -1) return count + index; count += model->count(); } } return -1; } QList<QObject*> BufferProxyModel::models() const { return m_models; } QList<QObject*> BufferProxyModel::servers() const { return m_servers; } QList<QObject*> BufferProxyModel::connections() const { return m_connections; } IrcBuffer* BufferProxyModel::currentBuffer() const { return m_current; } void BufferProxyModel::setCurrentBuffer(IrcBuffer* buffer) { if (m_current != buffer) { m_current = buffer; emit currentBufferChanged(buffer); } } QObject* BufferProxyModel::model(IrcConnection* connection) const { if (connection) return connection->findChild<IrcBufferModel*>(); return 0; } QObject* BufferProxyModel::server(IrcConnection* connection) const { if (connection) return connection->findChild<IrcServerBuffer*>(); return 0; } void BufferProxyModel::addConnection(IrcConnection* connection) { IrcBufferModel* model = new IrcBufferModel(connection); model->setSortMethod(Irc::SortByTitle); connect(model, SIGNAL(added(IrcBuffer*)), this, SIGNAL(bufferAdded(IrcBuffer*))); connect(model, SIGNAL(removed(IrcBuffer*)), this, SIGNAL(bufferRemoved(IrcBuffer*))); connect(model, SIGNAL(aboutToBeAdded(IrcBuffer*)), this, SIGNAL(bufferAboutToBeAdded(IrcBuffer*))); connect(model, SIGNAL(aboutToBeRemoved(IrcBuffer*)), this, SIGNAL(bufferAboutToBeRemoved(IrcBuffer*))); ZncManager* znc = new ZncManager(model); znc->setModel(model); IrcCommandQueue* queue = new IrcCommandQueue(connection); queue->setConnection(connection); IrcServerBuffer* buffer = new IrcServerBuffer(model); connect(buffer, SIGNAL(destroyed(IrcBuffer*)), this, SLOT(closeConnection(IrcBuffer*))); buffer->setName(connection->displayName()); buffer->setSticky(true); model->add(buffer); connection->setReconnectDelay(15); // TODO: settings? connect(connection, SIGNAL(displayNameChanged(QString)), buffer, SLOT(setName(QString))); connect(model, SIGNAL(messageIgnored(IrcMessage*)), this, SLOT(processMessage(IrcMessage*))); connect(connection, SIGNAL(connected()), this, SLOT(onConnected())); connect(connection, SIGNAL(disconnected()), this, SLOT(onDisconnected())); connect(connection, SIGNAL(enabledChanged(bool)), this, SLOT(onConnectionEnabledChanged(bool))); connect(connection, SIGNAL(nickNameRequired(QString,QString*)), this, SLOT(onNickNameRequired(QString))); connect(connection, SIGNAL(channelKeyRequired(QString,QString*)), this, SLOT(onChannelKeyRequired(QString))); // Give bouncers a sec or two to start joining channels after getting connected. // If that happens, the saved buffers shouldn't be restored to avoid restoring // a buffer that was closed using another client meanwhile. QTimer* timer = new QTimer(connection); timer->setSingleShot(true); timer->setInterval(2000); connect(connection, SIGNAL(connected()), timer, SLOT(start())); QObject::connect(timer, &QTimer::timeout, [=]() -> void { bool hasActiveChannels = false; foreach (const QString& name, model->channels()) { IrcBuffer* channel = model->find(name); if (channel && channel->isActive()) { hasActiveChannels = true; break; } } if (!hasActiveChannels) model->restoreState(model->property("savedState").toByteArray()); connect(model, SIGNAL(buffersChanged(QList<IrcBuffer*>)), this, SLOT(onModelBuffersChanged())); }); m_connections.append(connection); m_servers.append(buffer); m_models.append(model); emit connectionAdded(connection); emit connectionsChanged(); emit serversChanged(); emit modelsChanged(); insertSourceModel(model); } void BufferProxyModel::removeConnection(IrcConnection* connection) { disconnect(connection, SIGNAL(connected()), this, SLOT(onConnected())); disconnect(connection, SIGNAL(disconnected()), this, SLOT(onDisconnected())); IrcBufferModel* model = connection->findChild<IrcBufferModel*>(); if (model) { disconnect(model, SIGNAL(added(IrcBuffer*)), this, SIGNAL(bufferAdded(IrcBuffer*))); disconnect(model, SIGNAL(removed(IrcBuffer*)), this, SIGNAL(bufferRemoved(IrcBuffer*))); disconnect(model, SIGNAL(aboutToBeAdded(IrcBuffer*)), this, SIGNAL(bufferAboutToBeAdded(IrcBuffer*))); disconnect(model, SIGNAL(aboutToBeRemoved(IrcBuffer*)), this, SIGNAL(bufferAboutToBeRemoved(IrcBuffer*))); int index = m_connections.indexOf(connection); if (index != -1) { if (QObject* server = m_servers.takeAt(index)) server->disconnect(this); if (QObject* model = m_models.takeAt(index)) model->deleteLater(); if (QObject* connection = m_connections.takeAt(index)) connection->deleteLater(); emit connectionRemoved(connection); emit connectionsChanged(); emit serversChanged(); emit modelsChanged(); removeSourceModel(model); if (m_models.isEmpty()) emit reseted(); } } } QHash<int, QByteArray> BufferProxyModel::roleNames() const { QHash<int, QByteArray> roles; roles[Qt::DisplayRole] = "display"; roles[Qt::UserRole] = "section"; roles[Irc::BufferRole] = "buffer"; roles[Irc::ChannelRole] = "channel"; roles[Irc::NameRole] = "name"; roles[Irc::PrefixRole] = "prefix"; roles[Irc::TitleRole] = "title"; return roles; } QVariant BufferProxyModel::data(const QModelIndex& index, int role) const { if (role == Qt::UserRole) { IrcBuffer* buffer = data(index, Irc::BufferRole).value<IrcBuffer*>(); if (buffer) return m_connections.indexOf(buffer->connection()); // TODO: optimize } return RowsJoinerProxy::data(index, role); } QByteArray BufferProxyModel::saveState() const { QVariantList modelStates; QVariantList connectionStates; SimpleCrypt crypto(Q_UINT64_C(0xff610ed9de767b09)); foreach (QAbstractItemModel* aim, RowsJoinerProxy::models()) { IrcBufferModel* model = qobject_cast<IrcBufferModel*>(aim); if (model) { IrcConnection* connection = model->connection(); connectionStates += crypto.encryptToByteArray(connection->saveState()); // do not save the server buffer - let addConnection() handle it when restoring bool wasConnected = connection->isEnabled() && connection->isConnected(); model->remove(model->get(0)); if (wasConnected) modelStates += crypto.encryptToByteArray(model->saveState()); else modelStates += crypto.encryptToByteArray(model->property("savedState").toByteArray()); } } QVariantMap state; state.insert("models", modelStates); state.insert("connections", connectionStates); QByteArray data; QDataStream out(&data, QIODevice::WriteOnly); out << state; return data; } bool BufferProxyModel::restoreState(const QByteArray& data) { QVariantMap state; QDataStream in(data); in >> state; if (in.status() != QDataStream::Ok) return false; QVariantList modelStates = state.value("models").toList(); QVariantList connectionStates = state.value("connections").toList(); SimpleCrypt crypto(Q_UINT64_C(0xff610ed9de767b09)); for (int i = 0; i < connectionStates.length(); ++i) { IrcConnection* connection = new IrcConnection(this); QByteArray cs = crypto.decryptToByteArray(connectionStates.at(i).toByteArray()); connection->restoreState(!crypto.lastError() ? cs : connectionStates.at(i).toByteArray()); addConnection(connection); IrcBufferModel* model = connection->findChild<IrcBufferModel*>(); QByteArray ms = crypto.decryptToByteArray(modelStates.value(i).toByteArray()); model->setProperty("savedState", !crypto.lastError() ? ms : modelStates.value(i)); } return true; } void BufferProxyModel::onConnected() { IrcConnection* connection = qobject_cast<IrcConnection*>(sender()); if (connection) emit connected(connection); } void BufferProxyModel::onDisconnected() { IrcConnection* connection = qobject_cast<IrcConnection*>(sender()); if (connection) emit disconnected(connection); } void BufferProxyModel::onModelBuffersChanged() { IrcBufferModel* model = qobject_cast<IrcBufferModel*>(sender()); if (model) { IrcConnection* connection = model->connection(); if (connection && connection->isConnected()) model->setProperty("savedState", model->saveState()); } } void BufferProxyModel::onConnectionEnabledChanged(bool enabled) { // store the model state when a connection is disabled // see #25: Don't save/restore buffers for disabled connections if (!enabled) { IrcConnection* connection = qobject_cast<IrcConnection*>(sender()); if (connection) { IrcBufferModel* model = connection->findChild<IrcBufferModel*>(); if (model && model->count() > 1) model->setProperty("savedState", model->saveState()); } } } void BufferProxyModel::closeConnection(IrcBuffer* buffer) { removeConnection(buffer->connection()); } void BufferProxyModel::onChannelKeyRequired(const QString& channel) { IrcConnection* connection = qobject_cast<IrcConnection*>(sender()); if (connection) emit channelKeyRequired(connection, channel); } void BufferProxyModel::onNickNameRequired(const QString& reserved) { IrcConnection* connection = qobject_cast<IrcConnection*>(sender()); if (connection) emit nickNameRequired(connection, reserved); } void BufferProxyModel::processMessage(IrcMessage* message) { IrcBufferModel* model = message->connection()->findChild<IrcBufferModel*>(); if (model) { // deliver targeted ChanServ notices to the target channel // ":ChanServ!ChanServ@services. NOTICE myself :[#channel] foo bar..." if (message->type() == IrcMessage::Notice) { if (message->prefix() == "ChanServ!ChanServ@services.") { QString content = static_cast<IrcNoticeMessage*>(message)->content(); if (content.startsWith("[")) { int i = content.indexOf("]"); if (i != -1) { QString title = content.mid(1, i - 1); IrcBuffer* buffer = model->find(title); if (buffer) { message->setProperty("forwarded", true); buffer->receiveMessage(message); return; } } } } if (m_current && m_current->model() == model) { m_current->receiveMessage(message); return; } } if (IrcBuffer* buffer = model->get(0)) buffer->receiveMessage(message); } } #include "bufferproxymodel.moc" <|endoftext|>
<commit_before>#include <miopen.h> #include "test.hpp" #include <array> #include <iterator> #include <memory> #include <utility> #include <iostream> #include <miopen/tensor.hpp> #include <miopen/convolution.hpp> #include <limits> // #include "network_data.hpp" #include "tensor_holder.hpp" #include "verify.hpp" #include "driver.hpp" #include "get_handle.hpp" template<class T> tensor<T> get_output_tensor(const miopen::ConvolutionDescriptor& filter, const tensor<T>& input, const tensor<T>& weights) { assert(filter.GetBackwardOutputTensor(filter.GetForwardOutputTensor(input.desc, weights.desc), weights.desc) == input.desc); return tensor<T>{filter.GetForwardOutputTensor(input.desc, weights.desc)}; } template<class T> struct conv_base { tensor<T> input; tensor<T> weights; tensor<T> out; miopen::ConvolutionDescriptor filter; int bias; void fail(float=0) { std::cout << "Input tensor: " << input.desc.ToString() << std::endl; std::cout << "Weights tensor: " << weights.desc.ToString() << std::endl; std::cout << "Output tensor: " << out.desc.ToString() << std::endl; std::cout << "Filter: " << filter << std::endl; } }; template<class T> struct verify_forward_conv : conv_base<T> { using conv_base<T>::input; using conv_base<T>::weights; using conv_base<T>::out; using conv_base<T>::filter; using conv_base<T>::bias; verify_forward_conv(const tensor<T>& pinput, const tensor<T>& pweights, const miopen::ConvolutionDescriptor& pfilter, int pbias = 0) { input = pinput; weights = pweights; filter = pfilter; bias = pbias; } tensor<T> cpu() { out = get_output_tensor(filter, input, weights); int in_h, in_w; std::tie(std::ignore, std::ignore, in_h, in_w) = miopen::tie4(input.desc.GetLengths()); int wei_c, wei_h, wei_w; std::tie(std::ignore, wei_c, wei_h, wei_w) = miopen::tie4(weights.desc.GetLengths()); out.par_for_each([&](int o, int w, int i, int j) { const int start_x = i * filter.v - filter.pad_h; const int start_y = j * filter.u - filter.pad_w; double acc = bias; ford(wei_c, wei_h, wei_w)([&](int k, int x, int y) { const int in_x = start_x + x; const int in_y = start_y + y; if(in_x >= 0 && in_x < in_h && in_y >= 0 && in_y < in_w) { acc += input(o, k, in_x, in_y) * weights(w, k, x, y); } }); out(o, w, i, j) = acc; }); return out; } tensor<T> gpu() { auto&& handle = get_handle(); out = get_output_tensor(filter, input, weights); auto in_dev = handle.Write(input.data); auto wei_dev = handle.Write(weights.data); auto out_dev = handle.Write(out.data); size_t workspace_size = filter.ForwardGetWorkSpaceSize(handle, weights.desc, input.desc, out.desc); std::vector<char> workspace(workspace_size); auto workspace_dev = workspace_size != 0 ? handle.Write(workspace) : nullptr; int ret_algo_count; miopenConvAlgoPerf_t perf; int alpha = 1, beta = 1; filter.FindConvFwdAlgorithm(handle, input.desc, in_dev.get(), weights.desc, wei_dev.get(), out.desc, out_dev.get(), 1, &ret_algo_count, &perf, workspace_dev.get(), workspace_size, 0); // MD: Not performing exhaustiveSearch by default for now filter.ConvolutionForward(handle, &alpha, input.desc, in_dev.get(), weights.desc, wei_dev.get(), perf.fwd_algo, &beta, out.desc, out_dev.get(), workspace_dev.get(), workspace_size); out.data = handle.Read<T>(out_dev, out.data.size()); return out; } void fail(float=0) { std::cout << "Forward convolution: " << std::endl; this->conv_base<T>::fail(); } }; template<class T> struct verify_backward_conv : conv_base<T> { using conv_base<T>::input; using conv_base<T>::weights; using conv_base<T>::out; using conv_base<T>::filter; using conv_base<T>::bias; verify_backward_conv(const tensor<T>& pinput, const tensor<T>& pweights, const tensor<T>& pout, const miopen::ConvolutionDescriptor& pfilter, int pbias = 0) { input = pinput; weights = pweights; out = pout; filter = pfilter; bias = pbias; } tensor<T> cpu() { std::fill(input.begin(), input.end(), 0); int in_h, in_w; std::tie(std::ignore, std::ignore, in_h, in_w) = miopen::tie4(input.desc.GetLengths()); int wei_c, wei_h, wei_w; std::tie(std::ignore, wei_c, wei_h, wei_w) = miopen::tie4(weights.desc.GetLengths()); int out_n, out_c, out_h, out_w; std::tie(out_n, out_c, out_h, out_w) = miopen::tie4(out.desc.GetLengths()); par_ford(out_n, wei_c)([&](int o, int k) { ford(out_c, out_h, out_w, wei_h, wei_w)([&](int w, int i, int j, int x, int y) { const int start_x = i * filter.v - filter.pad_h; const int start_y = j * filter.u - filter.pad_w; const int in_x = start_x + x; const int in_y = start_y + y; if(in_x >= 0 && in_x < in_h && in_y >= 0 && in_y < in_w) { input(o, k, in_x, in_y) += out(o, w, i, j) * weights(w, k, x, y); } }); }); return input; } tensor<T> gpu() { auto&& handle = get_handle(); std::fill(input.begin(), input.end(), 0); auto out_dev = handle.Write(out.data); auto wei_dev = handle.Write(weights.data); auto in_dev = handle.Write(input.data); int ret_algo_count; miopenConvAlgoPerf_t perf; int alpha = 1, beta = 1; filter.FindConvBwdDataAlgorithm(handle, out.desc, out_dev.get(), weights.desc, wei_dev.get(), input.desc, in_dev.get(), 1, &ret_algo_count, &perf, nullptr, 10, 0); // MD: Not performing exhaustiveSearch by default for now filter.ConvolutionBackwardData(handle, &alpha, out.desc, out_dev.get(), weights.desc, wei_dev.get(), perf.bwd_data_algo, &beta, input.desc, in_dev.get(), nullptr, 0); input.data = handle.Read<T>(in_dev, input.data.size()); return input; } void fail(float) { std::cout << "Backward convolution: " << std::endl; this->conv_base<T>::fail(); } }; template<class T> struct verify_backward_weights_conv : conv_base<T> { using conv_base<T>::input; using conv_base<T>::weights; using conv_base<T>::out; using conv_base<T>::filter; using conv_base<T>::bias; verify_backward_weights_conv(const tensor<T>& pinput, const tensor<T>& pweights, const tensor<T>& pout, const miopen::ConvolutionDescriptor& pfilter, int pbias = 0) { input = pinput; weights = pweights; out = pout; filter = pfilter; bias = pbias; } tensor<T> cpu() { std::fill(weights.begin(), weights.end(), 0); int in_h, in_w; std::tie(std::ignore, std::ignore, in_h, in_w) = miopen::tie4(input.desc.GetLengths()); int wei_c, wei_h, wei_w; std::tie(std::ignore, wei_c, wei_h, wei_w) = miopen::tie4(weights.desc.GetLengths()); int out_n, out_c, out_h, out_w; std::tie(out_n, out_c, out_h, out_w) = miopen::tie4(out.desc.GetLengths()); par_ford(out_c, wei_c, wei_h, wei_w)([&](int w, int k, int x, int y) { double acc = 0.0; ford(out_n, out_h, out_w)([&](int o, int i, int j) { const int start_x = i * filter.v - filter.pad_h; const int start_y = j * filter.u - filter.pad_w; const int in_x = start_x + x; const int in_y = start_y + y; if(in_x >= 0 && in_x < in_h && in_y >= 0 && in_y < in_w) { acc += input(o, k, in_x, in_y) * out(o, w, i, j); } }); weights(w, k, x, y) = acc; }); return weights; } tensor<T> gpu() { auto&& handle = get_handle(); std::fill(weights.begin(), weights.end(), 0); auto out_dev = handle.Write(out.data); auto wei_dev = handle.Write(weights.data); auto in_dev = handle.Write(input.data); std::size_t workspace_size = filter.ConvolutionBackwardWeightsGetWorkSpaceSize(handle, out.desc, input.desc, weights.desc); std::vector<char> workspace(workspace_size); auto workspace_dev = handle.Write(workspace); int ret_algo_count; miopenConvAlgoPerf_t perf; int alpha = 1, beta = 1; filter.FindConvBwdWeightsAlgorithm(handle, out.desc, out_dev.get(), input.desc, in_dev.get(), weights.desc, wei_dev.get(), 1, &ret_algo_count, &perf, workspace_dev.get(), workspace_size, 0); // MD: Not performing exhaustiveSearch by default for now filter.ConvolutionBackwardWeights(handle, &alpha, out.desc, out_dev.get(), input.desc, in_dev.get(), perf.bwd_weights_algo, &beta, weights.desc, wei_dev.get(), workspace_dev.get(), workspace_size); weights.data = handle.Read<T>(wei_dev, weights.data.size()); return weights; } void fail(float) { std::cout << "Backward weights convolution: " << std::endl; this->conv_base<T>::fail(); } }; template<class T> struct conv_driver : test_driver { tensor<T> input; tensor<T> weights; miopen::ConvolutionDescriptor filter; bool enable_backward_weights = false; bool do_backward_data = true; conv_driver() { add(input, "input", get_input_tensor()); add(weights, "weights", get_weights_tensor()); add(filter, "filter", generate_data(get_filters())); add(enable_backward_weights, "enable-backward-weights", flag()); add(do_backward_data, "disable-backward-data", set_value(false)); } std::vector<miopen::ConvolutionDescriptor> get_filters() { return { miopen::ConvolutionDescriptor{ 0, 0, 1, 1 }, // miopen::ConvolutionDescriptor{ 0, 0, 2, 2 }, miopen::ConvolutionDescriptor{ 1, 1, 1, 1 }, miopen::ConvolutionDescriptor{ 1, 1, 2, 2 }, miopen::ConvolutionDescriptor{ 2, 2, 1, 1 }, miopen::ConvolutionDescriptor{ 3, 3, 2, 2 } }; } void run() { int wei_h, wei_w; std::tie(std::ignore, std::ignore, wei_h, wei_w) = miopen::tie4(weights.desc.GetLengths()); if (input.desc.GetLengths().at(1) == weights.desc.GetLengths().at(1) && wei_h > 2*filter.pad_h && wei_w > 2*filter.pad_w ) { auto out_p = verify(verify_forward_conv<T>{input, weights, filter}); for(auto& x:out_p.first) x = (long(x+1)*2) % 17; // Clamp big numbers if (do_backward_data) verify(verify_backward_conv<T>{input, weights, out_p.first, filter}); if(enable_backward_weights or MIOPEN_USE_TINYGEMM) { verify(verify_backward_weights_conv<T>{input, weights, out_p.first, filter}); } } } }; int main(int argc, const char *argv[]) { test_drive<conv_driver<float>>(argc, argv); } <commit_msg>added zero-size check<commit_after>#include <miopen.h> #include "test.hpp" #include <array> #include <iterator> #include <memory> #include <utility> #include <iostream> #include <miopen/tensor.hpp> #include <miopen/convolution.hpp> #include <limits> // #include "network_data.hpp" #include "tensor_holder.hpp" #include "verify.hpp" #include "driver.hpp" #include "get_handle.hpp" template<class T> tensor<T> get_output_tensor(const miopen::ConvolutionDescriptor& filter, const tensor<T>& input, const tensor<T>& weights) { assert(filter.GetBackwardOutputTensor(filter.GetForwardOutputTensor(input.desc, weights.desc), weights.desc) == input.desc); return tensor<T>{filter.GetForwardOutputTensor(input.desc, weights.desc)}; } template<class T> struct conv_base { tensor<T> input; tensor<T> weights; tensor<T> out; miopen::ConvolutionDescriptor filter; int bias; void fail(float=0) { std::cout << "Input tensor: " << input.desc.ToString() << std::endl; std::cout << "Weights tensor: " << weights.desc.ToString() << std::endl; std::cout << "Output tensor: " << out.desc.ToString() << std::endl; std::cout << "Filter: " << filter << std::endl; } }; template<class T> struct verify_forward_conv : conv_base<T> { using conv_base<T>::input; using conv_base<T>::weights; using conv_base<T>::out; using conv_base<T>::filter; using conv_base<T>::bias; verify_forward_conv(const tensor<T>& pinput, const tensor<T>& pweights, const miopen::ConvolutionDescriptor& pfilter, int pbias = 0) { input = pinput; weights = pweights; filter = pfilter; bias = pbias; } tensor<T> cpu() { out = get_output_tensor(filter, input, weights); int in_h, in_w; std::tie(std::ignore, std::ignore, in_h, in_w) = miopen::tie4(input.desc.GetLengths()); int wei_c, wei_h, wei_w; std::tie(std::ignore, wei_c, wei_h, wei_w) = miopen::tie4(weights.desc.GetLengths()); out.par_for_each([&](int o, int w, int i, int j) { const int start_x = i * filter.v - filter.pad_h; const int start_y = j * filter.u - filter.pad_w; double acc = bias; ford(wei_c, wei_h, wei_w)([&](int k, int x, int y) { const int in_x = start_x + x; const int in_y = start_y + y; if(in_x >= 0 && in_x < in_h && in_y >= 0 && in_y < in_w) { acc += input(o, k, in_x, in_y) * weights(w, k, x, y); } }); out(o, w, i, j) = acc; }); return out; } tensor<T> gpu() { auto&& handle = get_handle(); out = get_output_tensor(filter, input, weights); auto in_dev = handle.Write(input.data); auto wei_dev = handle.Write(weights.data); auto out_dev = handle.Write(out.data); size_t workspace_size = filter.ForwardGetWorkSpaceSize(handle, weights.desc, input.desc, out.desc); std::vector<char> workspace(workspace_size); auto workspace_dev = workspace_size != 0 ? handle.Write(workspace) : nullptr; int ret_algo_count; miopenConvAlgoPerf_t perf; int alpha = 1, beta = 1; filter.FindConvFwdAlgorithm(handle, input.desc, in_dev.get(), weights.desc, wei_dev.get(), out.desc, out_dev.get(), 1, &ret_algo_count, &perf, workspace_dev.get(), workspace_size, 0); // MD: Not performing exhaustiveSearch by default for now filter.ConvolutionForward(handle, &alpha, input.desc, in_dev.get(), weights.desc, wei_dev.get(), perf.fwd_algo, &beta, out.desc, out_dev.get(), workspace_dev.get(), workspace_size); out.data = handle.Read<T>(out_dev, out.data.size()); return out; } void fail(float=0) { std::cout << "Forward convolution: " << std::endl; this->conv_base<T>::fail(); } }; template<class T> struct verify_backward_conv : conv_base<T> { using conv_base<T>::input; using conv_base<T>::weights; using conv_base<T>::out; using conv_base<T>::filter; using conv_base<T>::bias; verify_backward_conv(const tensor<T>& pinput, const tensor<T>& pweights, const tensor<T>& pout, const miopen::ConvolutionDescriptor& pfilter, int pbias = 0) { input = pinput; weights = pweights; out = pout; filter = pfilter; bias = pbias; } tensor<T> cpu() { std::fill(input.begin(), input.end(), 0); int in_h, in_w; std::tie(std::ignore, std::ignore, in_h, in_w) = miopen::tie4(input.desc.GetLengths()); int wei_c, wei_h, wei_w; std::tie(std::ignore, wei_c, wei_h, wei_w) = miopen::tie4(weights.desc.GetLengths()); int out_n, out_c, out_h, out_w; std::tie(out_n, out_c, out_h, out_w) = miopen::tie4(out.desc.GetLengths()); par_ford(out_n, wei_c)([&](int o, int k) { ford(out_c, out_h, out_w, wei_h, wei_w)([&](int w, int i, int j, int x, int y) { const int start_x = i * filter.v - filter.pad_h; const int start_y = j * filter.u - filter.pad_w; const int in_x = start_x + x; const int in_y = start_y + y; if(in_x >= 0 && in_x < in_h && in_y >= 0 && in_y < in_w) { input(o, k, in_x, in_y) += out(o, w, i, j) * weights(w, k, x, y); } }); }); return input; } tensor<T> gpu() { auto&& handle = get_handle(); std::fill(input.begin(), input.end(), 0); auto out_dev = handle.Write(out.data); auto wei_dev = handle.Write(weights.data); auto in_dev = handle.Write(input.data); int ret_algo_count; miopenConvAlgoPerf_t perf; int alpha = 1, beta = 1; filter.FindConvBwdDataAlgorithm(handle, out.desc, out_dev.get(), weights.desc, wei_dev.get(), input.desc, in_dev.get(), 1, &ret_algo_count, &perf, nullptr, 10, 0); // MD: Not performing exhaustiveSearch by default for now filter.ConvolutionBackwardData(handle, &alpha, out.desc, out_dev.get(), weights.desc, wei_dev.get(), perf.bwd_data_algo, &beta, input.desc, in_dev.get(), nullptr, 0); input.data = handle.Read<T>(in_dev, input.data.size()); return input; } void fail(float) { std::cout << "Backward convolution: " << std::endl; this->conv_base<T>::fail(); } }; template<class T> struct verify_backward_weights_conv : conv_base<T> { using conv_base<T>::input; using conv_base<T>::weights; using conv_base<T>::out; using conv_base<T>::filter; using conv_base<T>::bias; verify_backward_weights_conv(const tensor<T>& pinput, const tensor<T>& pweights, const tensor<T>& pout, const miopen::ConvolutionDescriptor& pfilter, int pbias = 0) { input = pinput; weights = pweights; out = pout; filter = pfilter; bias = pbias; } tensor<T> cpu() { std::fill(weights.begin(), weights.end(), 0); int in_h, in_w; std::tie(std::ignore, std::ignore, in_h, in_w) = miopen::tie4(input.desc.GetLengths()); int wei_c, wei_h, wei_w; std::tie(std::ignore, wei_c, wei_h, wei_w) = miopen::tie4(weights.desc.GetLengths()); int out_n, out_c, out_h, out_w; std::tie(out_n, out_c, out_h, out_w) = miopen::tie4(out.desc.GetLengths()); par_ford(out_c, wei_c, wei_h, wei_w)([&](int w, int k, int x, int y) { double acc = 0.0; ford(out_n, out_h, out_w)([&](int o, int i, int j) { const int start_x = i * filter.v - filter.pad_h; const int start_y = j * filter.u - filter.pad_w; const int in_x = start_x + x; const int in_y = start_y + y; if(in_x >= 0 && in_x < in_h && in_y >= 0 && in_y < in_w) { acc += input(o, k, in_x, in_y) * out(o, w, i, j); } }); weights(w, k, x, y) = acc; }); return weights; } tensor<T> gpu() { auto&& handle = get_handle(); std::fill(weights.begin(), weights.end(), 0); auto out_dev = handle.Write(out.data); auto wei_dev = handle.Write(weights.data); auto in_dev = handle.Write(input.data); std::size_t workspace_size = filter.ConvolutionBackwardWeightsGetWorkSpaceSize(handle, out.desc, input.desc, weights.desc); std::vector<char> workspace(workspace_size); auto workspace_dev = workspace_size != 0 ? handle.Write(workspace) : nullptr; int ret_algo_count; miopenConvAlgoPerf_t perf; int alpha = 1, beta = 1; filter.FindConvBwdWeightsAlgorithm(handle, out.desc, out_dev.get(), input.desc, in_dev.get(), weights.desc, wei_dev.get(), 1, &ret_algo_count, &perf, workspace_dev.get(), workspace_size, 0); // MD: Not performing exhaustiveSearch by default for now filter.ConvolutionBackwardWeights(handle, &alpha, out.desc, out_dev.get(), input.desc, in_dev.get(), perf.bwd_weights_algo, &beta, weights.desc, wei_dev.get(), workspace_dev.get(), workspace_size); weights.data = handle.Read<T>(wei_dev, weights.data.size()); return weights; } void fail(float) { std::cout << "Backward weights convolution: " << std::endl; this->conv_base<T>::fail(); } }; template<class T> struct conv_driver : test_driver { tensor<T> input; tensor<T> weights; miopen::ConvolutionDescriptor filter; bool enable_backward_weights = false; bool do_backward_data = true; conv_driver() { add(input, "input", get_input_tensor()); add(weights, "weights", get_weights_tensor()); add(filter, "filter", generate_data(get_filters())); add(enable_backward_weights, "enable-backward-weights", flag()); add(do_backward_data, "disable-backward-data", set_value(false)); } std::vector<miopen::ConvolutionDescriptor> get_filters() { return { miopen::ConvolutionDescriptor{ 0, 0, 1, 1 }, // miopen::ConvolutionDescriptor{ 0, 0, 2, 2 }, miopen::ConvolutionDescriptor{ 1, 1, 1, 1 }, miopen::ConvolutionDescriptor{ 1, 1, 2, 2 }, miopen::ConvolutionDescriptor{ 2, 2, 1, 1 }, miopen::ConvolutionDescriptor{ 3, 3, 2, 2 } }; } void run() { int wei_h, wei_w; std::tie(std::ignore, std::ignore, wei_h, wei_w) = miopen::tie4(weights.desc.GetLengths()); if (input.desc.GetLengths().at(1) == weights.desc.GetLengths().at(1) && wei_h > 2*filter.pad_h && wei_w > 2*filter.pad_w ) { auto out_p = verify(verify_forward_conv<T>{input, weights, filter}); for(auto& x:out_p.first) x = (long(x+1)*2) % 17; // Clamp big numbers if (do_backward_data) verify(verify_backward_conv<T>{input, weights, out_p.first, filter}); if(enable_backward_weights or MIOPEN_USE_TINYGEMM) { verify(verify_backward_weights_conv<T>{input, weights, out_p.first, filter}); } } } }; int main(int argc, const char *argv[]) { test_drive<conv_driver<float>>(argc, argv); } <|endoftext|>
<commit_before>#include "urlviewformaction.h" #include <sstream> #include "config.h" #include "formatstring.h" #include "listformatter.h" #include "strprintf.h" #include "utils.h" #include "view.h" namespace newsboat { /* * The UrlViewFormAction is probably the simplest dialog of all. It * displays a list of URLs, and makes it possible to open the URLs * in a browser or to bookmark them. */ UrlViewFormAction::UrlViewFormAction(View* vv, std::shared_ptr<RssFeed>& feed, std::string formstr, ConfigContainer* cfg) : FormAction(vv, formstr, cfg) , quit(false) , feed(feed) { } UrlViewFormAction::~UrlViewFormAction() {} void UrlViewFormAction::process_operation(Operation op, bool /* automatic */, std::vector<std::string>* /* args */) { bool hardquit = false; switch (op) { case OP_OPENINBROWSER: case OP_OPEN: { std::string posstr = f->get("feedpos"); if (posstr.length() > 0) { unsigned int idx = utils::to_u(posstr, 0); v->set_status(_("Starting browser...")); v->open_in_browser(links[idx].first); v->set_status(""); } else { v->show_error(_("No link selected!")); } } break; case OP_BOOKMARK: { std::string posstr = f->get("feedpos"); if (posstr.length() > 0) { unsigned int idx = utils::to_u(posstr, 0); this->start_bookmark_qna( "", links[idx].first, "", feed->title()); } else { v->show_error(_("No link selected!")); } } break; case OP_1: case OP_2: case OP_3: case OP_4: case OP_5: case OP_6: case OP_7: case OP_8: case OP_9: case OP_0: { unsigned int idx = op - OP_1; if (idx < links.size()) { v->set_status(_("Starting browser...")); v->open_in_browser(links[idx].first); v->set_status(""); } } break; case OP_QUIT: quit = true; break; case OP_HARDQUIT: hardquit = true; break; default: // nothing break; } if (hardquit) { while (v->formaction_stack_size() > 0) { v->pop_current_formaction(); } } else if (quit) { v->pop_current_formaction(); } } void UrlViewFormAction::prepare() { if (do_redraw) { ListFormatter listfmt; unsigned int i = 0; for (const auto& link : links) { listfmt.add_line( strprintf::fmt("%2u %s", i + 1, link.first), i); i++; } f->modify("urls", "replace_inner", listfmt.format_list()); } } void UrlViewFormAction::init() { v->set_status(""); std::string viewwidth = f->get("urls:w"); unsigned int width = utils::to_u(viewwidth, 80); FmtStrFormatter fmt; fmt.register_fmt('N', PROGRAM_NAME); fmt.register_fmt('V', PROGRAM_VERSION); f->set("head", fmt.do_format( cfg->get_configvalue("urlview-title-format"), width)); do_redraw = true; quit = false; set_keymap_hints(); } KeyMapHintEntry* UrlViewFormAction::get_keymap_hint() { static KeyMapHintEntry hints[] = {{OP_QUIT, _("Quit")}, {OP_OPEN, _("Open in Browser")}, {OP_BOOKMARK, _("Save Bookmark")}, {OP_NIL, nullptr}}; return hints; } void UrlViewFormAction::handle_cmdline(const std::string& cmd) { unsigned int idx = 0; if (1 == sscanf(cmd.c_str(), "%u", &idx)) { if (idx < 1 || idx > links.size()) { v->show_error(_("Invalid position!")); } else { f->set("feedpos", std::to_string(idx - 1)); } } else { FormAction::handle_cmdline(cmd); } } std::string UrlViewFormAction::title() { return _("URLs"); } } // namespace newsboat <commit_msg>Initialize `cfg` member in UrlViewFormAction<commit_after>#include "urlviewformaction.h" #include <sstream> #include "config.h" #include "formatstring.h" #include "listformatter.h" #include "strprintf.h" #include "utils.h" #include "view.h" namespace newsboat { /* * The UrlViewFormAction is probably the simplest dialog of all. It * displays a list of URLs, and makes it possible to open the URLs * in a browser or to bookmark them. */ UrlViewFormAction::UrlViewFormAction(View* vv, std::shared_ptr<RssFeed>& feed, std::string formstr, ConfigContainer* cfg) : FormAction(vv, formstr, cfg) , quit(false) , feed(feed) , cfg(cfg) { } UrlViewFormAction::~UrlViewFormAction() {} void UrlViewFormAction::process_operation(Operation op, bool /* automatic */, std::vector<std::string>* /* args */) { bool hardquit = false; switch (op) { case OP_OPENINBROWSER: case OP_OPEN: { std::string posstr = f->get("feedpos"); if (posstr.length() > 0) { unsigned int idx = utils::to_u(posstr, 0); v->set_status(_("Starting browser...")); v->open_in_browser(links[idx].first); v->set_status(""); } else { v->show_error(_("No link selected!")); } } break; case OP_BOOKMARK: { std::string posstr = f->get("feedpos"); if (posstr.length() > 0) { unsigned int idx = utils::to_u(posstr, 0); this->start_bookmark_qna( "", links[idx].first, "", feed->title()); } else { v->show_error(_("No link selected!")); } } break; case OP_1: case OP_2: case OP_3: case OP_4: case OP_5: case OP_6: case OP_7: case OP_8: case OP_9: case OP_0: { unsigned int idx = op - OP_1; if (idx < links.size()) { v->set_status(_("Starting browser...")); v->open_in_browser(links[idx].first); v->set_status(""); } } break; case OP_QUIT: quit = true; break; case OP_HARDQUIT: hardquit = true; break; default: // nothing break; } if (hardquit) { while (v->formaction_stack_size() > 0) { v->pop_current_formaction(); } } else if (quit) { v->pop_current_formaction(); } } void UrlViewFormAction::prepare() { if (do_redraw) { ListFormatter listfmt; unsigned int i = 0; for (const auto& link : links) { listfmt.add_line( strprintf::fmt("%2u %s", i + 1, link.first), i); i++; } f->modify("urls", "replace_inner", listfmt.format_list()); } } void UrlViewFormAction::init() { v->set_status(""); std::string viewwidth = f->get("urls:w"); unsigned int width = utils::to_u(viewwidth, 80); FmtStrFormatter fmt; fmt.register_fmt('N', PROGRAM_NAME); fmt.register_fmt('V', PROGRAM_VERSION); f->set("head", fmt.do_format( cfg->get_configvalue("urlview-title-format"), width)); do_redraw = true; quit = false; set_keymap_hints(); } KeyMapHintEntry* UrlViewFormAction::get_keymap_hint() { static KeyMapHintEntry hints[] = {{OP_QUIT, _("Quit")}, {OP_OPEN, _("Open in Browser")}, {OP_BOOKMARK, _("Save Bookmark")}, {OP_NIL, nullptr}}; return hints; } void UrlViewFormAction::handle_cmdline(const std::string& cmd) { unsigned int idx = 0; if (1 == sscanf(cmd.c_str(), "%u", &idx)) { if (idx < 1 || idx > links.size()) { v->show_error(_("Invalid position!")); } else { f->set("feedpos", std::to_string(idx - 1)); } } else { FormAction::handle_cmdline(cmd); } } std::string UrlViewFormAction::title() { return _("URLs"); } } // namespace newsboat <|endoftext|>
<commit_before>/* * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "itkCastImageFilter.h" #include "otbVectorRescaleIntensityImageFilter.h" #include "itkCastImageFilter.h" #include "otbUnaryImageFunctorWithVectorImageFilter.h" #include "otbStreamingShrinkImageFilter.h" #include "itkListSample.h" #include "otbListSampleToHistogramListGenerator.h" #include "itkImageRegionConstIterator.h" namespace otb { namespace Wrapper { namespace Functor { template< class TScalar > class ITK_EXPORT LogFunctor { public: LogFunctor(){}; ~LogFunctor(){}; TScalar operator() (const TScalar& v) const { return vcl_log(v); } }; } // end namespace Functor class Convert : public Application { public: /** Standard class typedefs. */ typedef Convert Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(Convert, otb::Application); /** Filters typedef */ typedef itk::Statistics::ListSample<FloatVectorImageType::PixelType> ListSampleType; typedef itk::Statistics::DenseFrequencyContainer2 DFContainerType; typedef ListSampleToHistogramListGenerator<ListSampleType, FloatVectorImageType::InternalPixelType, DFContainerType> HistogramsGeneratorType; typedef StreamingShrinkImageFilter<FloatVectorImageType, FloatVectorImageType> ShrinkFilterType; typedef Functor::LogFunctor<FloatVectorImageType::InternalPixelType> TransferLogFunctor; typedef UnaryImageFunctorWithVectorImageFilter<FloatVectorImageType, FloatVectorImageType, TransferLogFunctor> TransferLogType; private: void DoInit() ITK_OVERRIDE { SetName("Convert"); SetDescription("Convert an image to a different format, eventually rescaling the data" " and/or changing the pixel type."); // Documentation SetDocName("Image Conversion"); SetDocLongDescription("This application performs an image pixel type conversion (short, ushort, uchar, int, uint, float and double types are handled). The output image is written in the specified format (ie. that corresponds to the given extension).\n The conversion can include a rescale using the image 2 percent minimum and maximum values. The rescale can be linear or log2."); SetDocLimitations("None"); SetDocAuthors("OTB-Team"); SetDocSeeAlso("Rescale"); AddDocTag(Tags::Manip); AddDocTag("Conversion"); AddDocTag("Image Dynamic"); AddParameter(ParameterType_InputImage, "in", "Input image"); SetParameterDescription("in", "Input image"); AddParameter(ParameterType_Choice, "type", "Rescale type"); SetParameterDescription("type", "Transfer function for the rescaling"); AddChoice("type.none", "None"); AddChoice("type.linear", "Linear"); AddChoice("type.log2", "Log2"); SetParameterString("type", "none", false); AddParameter(ParameterType_Float,"type.linear.gamma","Gamma correction factor"); SetParameterDescription("type.linear.gamma","Gamma correction factor"); SetDefaultParameterFloat("type.linear.gamma",1.0); MandatoryOff("type.linear.gamma"); AddParameter(ParameterType_InputImage, "mask", "Input mask"); SetParameterDescription("mask", "The masked pixels won't be used to adapt the dynamic (the mask must have the same dimensions as the input image)"); MandatoryOff("mask"); DisableParameter("mask"); AddParameter(ParameterType_Group,"hcp","Histogram Cutting Parameters"); SetParameterDescription("hcp","Parameters to cut the histogram edges before rescaling"); AddParameter(ParameterType_Float, "hcp.high", "High Cut Quantile"); SetParameterDescription("hcp.high", "Quantiles to cut from histogram high values before computing min/max rescaling (in percent, 2 by default)"); MandatoryOff("hcp.high"); SetDefaultParameterFloat("hcp.high", 2.0); DisableParameter("hcp.high"); AddParameter(ParameterType_Float, "hcp.low", "Low Cut Quantile"); SetParameterDescription("hcp.low", "Quantiles to cut from histogram low values before computing min/max rescaling (in percent, 2 by default)"); MandatoryOff("hcp.low"); SetDefaultParameterFloat("hcp.low", 2.0); DisableParameter("hcp.low"); AddParameter(ParameterType_OutputImage, "out", "Output Image"); SetParameterDescription("out", "Output image"); AddRAMParameter(); // Doc example parameter settings SetDocExampleParameterValue("in", "QB_Toulouse_Ortho_XS.tif"); SetDocExampleParameterValue("out", "otbConvertWithScalingOutput.png uint8"); SetDocExampleParameterValue("type", "linear"); SetOfficialDocLink(); } void DoUpdateParameters() ITK_OVERRIDE { // Nothing to do here for the parameters : all are independent } template<class TImageType> void GenericDoExecute() { typename TImageType::Pointer castIm; std::string rescaleType = this->GetParameterString("type"); if( (rescaleType != "none") && (rescaleType != "linear") && (rescaleType != "log2") ) { itkExceptionMacro("Unknown rescale type "<<rescaleType<<"."); } if( rescaleType == "none" ) { castIm = this->GetParameterImage<TImageType>("in"); } else { FloatVectorImageType::Pointer input = this->GetParameterImage("in"); FloatVectorImageType::Pointer mask; bool useMask = false; if (IsParameterEnabled("mask")) { mask = this->GetParameterImage("mask"); useMask = true; } const unsigned int nbComp(input->GetNumberOfComponentsPerPixel()); typedef otb::VectorRescaleIntensityImageFilter<FloatVectorImageType, TImageType> RescalerType; typename TImageType::PixelType minimum; typename TImageType::PixelType maximum; minimum.SetSize(nbComp); maximum.SetSize(nbComp); minimum.Fill( itk::NumericTraits<typename TImageType::InternalPixelType>::min() ); maximum.Fill( itk::NumericTraits<typename TImageType::InternalPixelType>::max() ); typename RescalerType::Pointer rescaler = RescalerType::New(); rescaler->SetOutputMinimum(minimum); rescaler->SetOutputMaximum(maximum); // We need to subsample the input image in order to estimate its // histogram typename ShrinkFilterType::Pointer shrinkFilter = ShrinkFilterType::New(); // Shrink factor is computed so as to load a quicklook of 1000 // pixels square at most typename FloatVectorImageType::SizeType imageSize = input->GetLargestPossibleRegion().GetSize(); unsigned int shrinkFactor = std::max(imageSize[0], imageSize[1]) < 1000 ? 1 : std::max(imageSize[0], imageSize[1])/1000; otbAppLogDEBUG( << "Shrink factor used to compute Min/Max: "<<shrinkFactor ); otbAppLogDEBUG( << "Shrink starts..." ); shrinkFilter->SetShrinkFactor(shrinkFactor); shrinkFilter->GetStreamer()->SetAutomaticAdaptativeStreaming(GetParameterInt("ram")); AddProcess(shrinkFilter->GetStreamer(), "Computing shrink Image for min/max estimation..."); if ( rescaleType == "log2") { //define the transfer log m_TransferLog = TransferLogType::New(); m_TransferLog->SetInput(input); m_TransferLog->UpdateOutputInformation(); shrinkFilter->SetInput(m_TransferLog->GetOutput()); rescaler->SetInput(m_TransferLog->GetOutput()); shrinkFilter->Update(); } else { shrinkFilter->SetInput(input); rescaler->SetInput(input); shrinkFilter->Update(); } ShrinkFilterType::Pointer maskShrinkFilter = ShrinkFilterType::New(); if (useMask) { maskShrinkFilter->SetShrinkFactor(shrinkFactor); maskShrinkFilter->SetInput(mask); maskShrinkFilter->GetStreamer()->SetAutomaticAdaptativeStreaming(GetParameterInt("ram")); maskShrinkFilter->Update(); } otbAppLogDEBUG( << "Shrink done" ); otbAppLogDEBUG( << "Evaluating input Min/Max..." ); itk::ImageRegionConstIterator<FloatVectorImageType> it(shrinkFilter->GetOutput(), shrinkFilter->GetOutput()->GetLargestPossibleRegion()); itk::ImageRegionConstIterator<FloatVectorImageType> itMask; if (useMask) { itMask = itk::ImageRegionConstIterator<FloatVectorImageType>(maskShrinkFilter->GetOutput(),maskShrinkFilter->GetOutput()->GetLargestPossibleRegion()); } typename ListSampleType::Pointer listSample = ListSampleType::New(); listSample->SetMeasurementVectorSize(input->GetNumberOfComponentsPerPixel()); // Now we generate the list of samples if (useMask) { // Remove masked pixels it.GoToBegin(); itMask.GoToBegin(); while (!it.IsAtEnd()) { // float values, so the threshold is set to 0.5 if (itMask.Get()[0] < 0.5) { listSample->PushBack(it.Get()); } ++it; ++itMask; } } else { for(it.GoToBegin(); !it.IsAtEnd(); ++it) { listSample->PushBack(it.Get()); } } // if all pixels were masked, we assume a wrong mask and then include all image if (listSample->Size() == 0) { otbAppLogINFO( << "All pixels were masked, the application assume a wrong mask and include all the image"); for(it.GoToBegin(); !it.IsAtEnd(); ++it) { listSample->PushBack(it.Get()); } } // And then the histogram typename HistogramsGeneratorType::Pointer histogramsGenerator = HistogramsGeneratorType::New(); histogramsGenerator->SetListSample(listSample); histogramsGenerator->SetNumberOfBins(255); histogramsGenerator->NoDataFlagOn(); histogramsGenerator->Update(); // And extract the lower and upper quantile typename FloatVectorImageType::PixelType inputMin(nbComp), inputMax(nbComp); for(unsigned int i = 0; i < nbComp; ++i) { inputMin[i] = histogramsGenerator->GetOutput()->GetNthElement(i)->Quantile(0, 0.01 * GetParameterFloat("hcp.low")); inputMax[i] = histogramsGenerator->GetOutput()->GetNthElement(i)->Quantile(0, 1.0 - 0.01 * GetParameterFloat("hcp.high")); } otbAppLogDEBUG( << std::setprecision(5) << "Min/Max computation done : min=" << inputMin << " max=" << inputMax ); rescaler->AutomaticInputMinMaxComputationOff(); rescaler->SetInputMinimum(inputMin); rescaler->SetInputMaximum(inputMax); if ( rescaleType == "linear") { rescaler->SetGamma(GetParameterFloat("type.linear.gamma")); } m_TmpFilter = rescaler; castIm = rescaler->GetOutput(); } SetParameterOutputImage<TImageType>("out", castIm); } void DoExecute() ITK_OVERRIDE { switch ( this->GetParameterOutputImagePixelType("out") ) { case ImagePixelType_uint8: GenericDoExecute<UInt8VectorImageType>(); break; case ImagePixelType_int16: GenericDoExecute<Int16VectorImageType>(); break; case ImagePixelType_uint16: GenericDoExecute<UInt16VectorImageType>(); break; case ImagePixelType_int32: GenericDoExecute<Int32VectorImageType>(); break; case ImagePixelType_uint32: GenericDoExecute<UInt32VectorImageType>(); break; case ImagePixelType_float: GenericDoExecute<FloatVectorImageType>(); break; case ImagePixelType_double: GenericDoExecute<DoubleVectorImageType>(); break; default: itkExceptionMacro("Unknown pixel type "<<this->GetParameterOutputImagePixelType("out")<<"."); break; } } itk::ProcessObject::Pointer m_TmpFilter; TransferLogType::Pointer m_TransferLog; }; } } OTB_APPLICATION_EXPORT(otb::Wrapper::Convert) <commit_msg>BUG: Typo in Convert app description<commit_after>/* * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "itkCastImageFilter.h" #include "otbVectorRescaleIntensityImageFilter.h" #include "itkCastImageFilter.h" #include "otbUnaryImageFunctorWithVectorImageFilter.h" #include "otbStreamingShrinkImageFilter.h" #include "itkListSample.h" #include "otbListSampleToHistogramListGenerator.h" #include "itkImageRegionConstIterator.h" namespace otb { namespace Wrapper { namespace Functor { template< class TScalar > class ITK_EXPORT LogFunctor { public: LogFunctor(){}; ~LogFunctor(){}; TScalar operator() (const TScalar& v) const { return vcl_log(v); } }; } // end namespace Functor class Convert : public Application { public: /** Standard class typedefs. */ typedef Convert Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(Convert, otb::Application); /** Filters typedef */ typedef itk::Statistics::ListSample<FloatVectorImageType::PixelType> ListSampleType; typedef itk::Statistics::DenseFrequencyContainer2 DFContainerType; typedef ListSampleToHistogramListGenerator<ListSampleType, FloatVectorImageType::InternalPixelType, DFContainerType> HistogramsGeneratorType; typedef StreamingShrinkImageFilter<FloatVectorImageType, FloatVectorImageType> ShrinkFilterType; typedef Functor::LogFunctor<FloatVectorImageType::InternalPixelType> TransferLogFunctor; typedef UnaryImageFunctorWithVectorImageFilter<FloatVectorImageType, FloatVectorImageType, TransferLogFunctor> TransferLogType; private: void DoInit() ITK_OVERRIDE { SetName("Convert"); SetDescription("Convert an image to a different format, optionally rescaling the data" " and/or changing the pixel type."); // Documentation SetDocName("Image Conversion"); SetDocLongDescription("This application performs an image pixel type conversion (short, ushort, uchar, int, uint, float and double types are handled). The output image is written in the specified format (ie. that corresponds to the given extension).\n The conversion can include a rescale using the image 2 percent minimum and maximum values. The rescale can be linear or log2."); SetDocLimitations("None"); SetDocAuthors("OTB-Team"); SetDocSeeAlso("Rescale"); AddDocTag(Tags::Manip); AddDocTag("Conversion"); AddDocTag("Image Dynamic"); AddParameter(ParameterType_InputImage, "in", "Input image"); SetParameterDescription("in", "Input image"); AddParameter(ParameterType_Choice, "type", "Rescale type"); SetParameterDescription("type", "Transfer function for the rescaling"); AddChoice("type.none", "None"); AddChoice("type.linear", "Linear"); AddChoice("type.log2", "Log2"); SetParameterString("type", "none", false); AddParameter(ParameterType_Float,"type.linear.gamma","Gamma correction factor"); SetParameterDescription("type.linear.gamma","Gamma correction factor"); SetDefaultParameterFloat("type.linear.gamma",1.0); MandatoryOff("type.linear.gamma"); AddParameter(ParameterType_InputImage, "mask", "Input mask"); SetParameterDescription("mask", "The masked pixels won't be used to adapt the dynamic (the mask must have the same dimensions as the input image)"); MandatoryOff("mask"); DisableParameter("mask"); AddParameter(ParameterType_Group,"hcp","Histogram Cutting Parameters"); SetParameterDescription("hcp","Parameters to cut the histogram edges before rescaling"); AddParameter(ParameterType_Float, "hcp.high", "High Cut Quantile"); SetParameterDescription("hcp.high", "Quantiles to cut from histogram high values before computing min/max rescaling (in percent, 2 by default)"); MandatoryOff("hcp.high"); SetDefaultParameterFloat("hcp.high", 2.0); DisableParameter("hcp.high"); AddParameter(ParameterType_Float, "hcp.low", "Low Cut Quantile"); SetParameterDescription("hcp.low", "Quantiles to cut from histogram low values before computing min/max rescaling (in percent, 2 by default)"); MandatoryOff("hcp.low"); SetDefaultParameterFloat("hcp.low", 2.0); DisableParameter("hcp.low"); AddParameter(ParameterType_OutputImage, "out", "Output Image"); SetParameterDescription("out", "Output image"); AddRAMParameter(); // Doc example parameter settings SetDocExampleParameterValue("in", "QB_Toulouse_Ortho_XS.tif"); SetDocExampleParameterValue("out", "otbConvertWithScalingOutput.png uint8"); SetDocExampleParameterValue("type", "linear"); SetOfficialDocLink(); } void DoUpdateParameters() ITK_OVERRIDE { // Nothing to do here for the parameters : all are independent } template<class TImageType> void GenericDoExecute() { typename TImageType::Pointer castIm; std::string rescaleType = this->GetParameterString("type"); if( (rescaleType != "none") && (rescaleType != "linear") && (rescaleType != "log2") ) { itkExceptionMacro("Unknown rescale type "<<rescaleType<<"."); } if( rescaleType == "none" ) { castIm = this->GetParameterImage<TImageType>("in"); } else { FloatVectorImageType::Pointer input = this->GetParameterImage("in"); FloatVectorImageType::Pointer mask; bool useMask = false; if (IsParameterEnabled("mask")) { mask = this->GetParameterImage("mask"); useMask = true; } const unsigned int nbComp(input->GetNumberOfComponentsPerPixel()); typedef otb::VectorRescaleIntensityImageFilter<FloatVectorImageType, TImageType> RescalerType; typename TImageType::PixelType minimum; typename TImageType::PixelType maximum; minimum.SetSize(nbComp); maximum.SetSize(nbComp); minimum.Fill( itk::NumericTraits<typename TImageType::InternalPixelType>::min() ); maximum.Fill( itk::NumericTraits<typename TImageType::InternalPixelType>::max() ); typename RescalerType::Pointer rescaler = RescalerType::New(); rescaler->SetOutputMinimum(minimum); rescaler->SetOutputMaximum(maximum); // We need to subsample the input image in order to estimate its // histogram typename ShrinkFilterType::Pointer shrinkFilter = ShrinkFilterType::New(); // Shrink factor is computed so as to load a quicklook of 1000 // pixels square at most typename FloatVectorImageType::SizeType imageSize = input->GetLargestPossibleRegion().GetSize(); unsigned int shrinkFactor = std::max(imageSize[0], imageSize[1]) < 1000 ? 1 : std::max(imageSize[0], imageSize[1])/1000; otbAppLogDEBUG( << "Shrink factor used to compute Min/Max: "<<shrinkFactor ); otbAppLogDEBUG( << "Shrink starts..." ); shrinkFilter->SetShrinkFactor(shrinkFactor); shrinkFilter->GetStreamer()->SetAutomaticAdaptativeStreaming(GetParameterInt("ram")); AddProcess(shrinkFilter->GetStreamer(), "Computing shrink Image for min/max estimation..."); if ( rescaleType == "log2") { //define the transfer log m_TransferLog = TransferLogType::New(); m_TransferLog->SetInput(input); m_TransferLog->UpdateOutputInformation(); shrinkFilter->SetInput(m_TransferLog->GetOutput()); rescaler->SetInput(m_TransferLog->GetOutput()); shrinkFilter->Update(); } else { shrinkFilter->SetInput(input); rescaler->SetInput(input); shrinkFilter->Update(); } ShrinkFilterType::Pointer maskShrinkFilter = ShrinkFilterType::New(); if (useMask) { maskShrinkFilter->SetShrinkFactor(shrinkFactor); maskShrinkFilter->SetInput(mask); maskShrinkFilter->GetStreamer()->SetAutomaticAdaptativeStreaming(GetParameterInt("ram")); maskShrinkFilter->Update(); } otbAppLogDEBUG( << "Shrink done" ); otbAppLogDEBUG( << "Evaluating input Min/Max..." ); itk::ImageRegionConstIterator<FloatVectorImageType> it(shrinkFilter->GetOutput(), shrinkFilter->GetOutput()->GetLargestPossibleRegion()); itk::ImageRegionConstIterator<FloatVectorImageType> itMask; if (useMask) { itMask = itk::ImageRegionConstIterator<FloatVectorImageType>(maskShrinkFilter->GetOutput(),maskShrinkFilter->GetOutput()->GetLargestPossibleRegion()); } typename ListSampleType::Pointer listSample = ListSampleType::New(); listSample->SetMeasurementVectorSize(input->GetNumberOfComponentsPerPixel()); // Now we generate the list of samples if (useMask) { // Remove masked pixels it.GoToBegin(); itMask.GoToBegin(); while (!it.IsAtEnd()) { // float values, so the threshold is set to 0.5 if (itMask.Get()[0] < 0.5) { listSample->PushBack(it.Get()); } ++it; ++itMask; } } else { for(it.GoToBegin(); !it.IsAtEnd(); ++it) { listSample->PushBack(it.Get()); } } // if all pixels were masked, we assume a wrong mask and then include all image if (listSample->Size() == 0) { otbAppLogINFO( << "All pixels were masked, the application assume a wrong mask and include all the image"); for(it.GoToBegin(); !it.IsAtEnd(); ++it) { listSample->PushBack(it.Get()); } } // And then the histogram typename HistogramsGeneratorType::Pointer histogramsGenerator = HistogramsGeneratorType::New(); histogramsGenerator->SetListSample(listSample); histogramsGenerator->SetNumberOfBins(255); histogramsGenerator->NoDataFlagOn(); histogramsGenerator->Update(); // And extract the lower and upper quantile typename FloatVectorImageType::PixelType inputMin(nbComp), inputMax(nbComp); for(unsigned int i = 0; i < nbComp; ++i) { inputMin[i] = histogramsGenerator->GetOutput()->GetNthElement(i)->Quantile(0, 0.01 * GetParameterFloat("hcp.low")); inputMax[i] = histogramsGenerator->GetOutput()->GetNthElement(i)->Quantile(0, 1.0 - 0.01 * GetParameterFloat("hcp.high")); } otbAppLogDEBUG( << std::setprecision(5) << "Min/Max computation done : min=" << inputMin << " max=" << inputMax ); rescaler->AutomaticInputMinMaxComputationOff(); rescaler->SetInputMinimum(inputMin); rescaler->SetInputMaximum(inputMax); if ( rescaleType == "linear") { rescaler->SetGamma(GetParameterFloat("type.linear.gamma")); } m_TmpFilter = rescaler; castIm = rescaler->GetOutput(); } SetParameterOutputImage<TImageType>("out", castIm); } void DoExecute() ITK_OVERRIDE { switch ( this->GetParameterOutputImagePixelType("out") ) { case ImagePixelType_uint8: GenericDoExecute<UInt8VectorImageType>(); break; case ImagePixelType_int16: GenericDoExecute<Int16VectorImageType>(); break; case ImagePixelType_uint16: GenericDoExecute<UInt16VectorImageType>(); break; case ImagePixelType_int32: GenericDoExecute<Int32VectorImageType>(); break; case ImagePixelType_uint32: GenericDoExecute<UInt32VectorImageType>(); break; case ImagePixelType_float: GenericDoExecute<FloatVectorImageType>(); break; case ImagePixelType_double: GenericDoExecute<DoubleVectorImageType>(); break; default: itkExceptionMacro("Unknown pixel type "<<this->GetParameterOutputImagePixelType("out")<<"."); break; } } itk::ProcessObject::Pointer m_TmpFilter; TransferLogType::Pointer m_TransferLog; }; } } OTB_APPLICATION_EXPORT(otb::Wrapper::Convert) <|endoftext|>
<commit_before>//=========================================================================== // // File: Identity.C // // Created: // // Author: Vibeke Skytt // // Revision: // // Description: Check for identical and embedded entities // //=========================================================================== #include "GoTools/intersections/Identity.h" #include "GoTools/intersections/ParamSurfaceInt.h" #include "GoTools/intersections/ParamCurveInt.h" #include "GoTools/intersections/Coincidence.h" #include "GoTools/intersections/GeoTol.h" using std::vector; namespace Go { int Identity::identicalSfs(shared_ptr<ParamSurface> sf1, shared_ptr<ParamSurface> sf2, double tol) { // Initialize intersection objects shared_ptr<ParamSurfaceInt> intsf1 = shared_ptr<ParamSurfaceInt>(new ParamSurfaceInt(sf1)); shared_ptr<ParamSurfaceInt> intsf2 = shared_ptr<ParamSurfaceInt>(new ParamSurfaceInt(sf2)); shared_ptr<GeoTol> eps = shared_ptr<GeoTol>(new GeoTol(tol)); // Fetch boundary elements vector<shared_ptr<BoundaryGeomInt> > bd_cvs1; vector<shared_ptr<BoundaryGeomInt> > bd_cvs2; intsf1->getBoundaryObjects(bd_cvs1); intsf2->getBoundaryObjects(bd_cvs2); // Check identity of boundary curves int ki, kj; int coincident = 0; double start1, start2, end1, end2; for (ki=0; ki<int(bd_cvs1.size()); ++ki) { ParamCurveInt *cv1 = bd_cvs1[ki]->getObject()->getParamCurveInt(); start1 = cv1->startParam(0); end1 = cv1->endParam(0); for (kj=0; kj<int(bd_cvs2.size()); ++kj) { ParamCurveInt *cv2 = bd_cvs2[kj]->getObject()->getParamCurveInt(); start2 = cv2->startParam(0); end2 = cv2->endParam(0); // Check orientation Point pt1, pt2, pt3, pt4; cv1->point(pt1, &start1); cv1->point(pt2, &end1); cv2->point(pt3, &start2); cv2->point(pt4, &end2); if (!(pt1.dist(pt3) < tol || pt1.dist(pt4) < tol)) continue; if (!(pt2.dist(pt3) < tol || pt2.dist(pt4) < tol)) continue; if (pt1.dist(pt3) < pt1.dist(pt4)) coincident = checkCoincide(cv1, start1, end1, eps, cv2, start2, end2); else coincident = checkCoincide(cv1, start1, end1, eps, cv2, end2, start2); if (coincident) break; } if (kj == int(bd_cvs2.size())) break; // No coincidence for this boundary curve } if (ki == int(bd_cvs1.size())) { // Coincidence of boundary curves found. Check the inner coincident = internalCoincidence(intsf1, intsf2, eps); if (coincident) return 1; } // Check if the boundary curves of surface 1 lies in surface 2 for (ki=0; ki<int(bd_cvs1.size()); ++ki) { ParamCurveInt *cv1 = bd_cvs1[ki]->getObject()->getParamCurveInt(); start1 = cv1->startParam(0); end1 = cv1->endParam(0); // Project the endpoints onto surface 2 Point pt1, pt2, clo_pt1, clo_pt2; double u1, v1, u2, v2, dist1, dist2; cv1->point(pt1, &start1); cv1->point(pt2, &end1); sf2->closestPoint(pt1, u1, v1, clo_pt1, dist1, tol); if (dist1 > tol) break; // No coincidence sf2->closestPoint(pt2, u2, v2, clo_pt2, dist2, tol); if (dist2 > tol) break; // No coincidence // Check curve coincident = checkCoincide(cv1, start1, end1, intsf2.get(), Point(u1,v1), Point(u2,v2), eps); if (!coincident) break; } if (ki == int(bd_cvs1.size())) { // Coincidence of boundary curves found. Check the inner coincident = internalCoincidence(intsf1, intsf2, eps); if (coincident) return 2; } // Check if the boundary curves of surface 2 lies in surface 1 for (ki=0; ki<int(bd_cvs2.size()); ++ki) { ParamCurveInt *cv2 = bd_cvs2[ki]->getObject()->getParamCurveInt(); start2 = cv2->startParam(0); end2 = cv2->endParam(0); // Project the endpoints onto surface 2 Point pt1, pt2, clo_pt1, clo_pt2; double u1, v1, u2, v2, dist1, dist2; cv2->point(pt1, &start2); cv2->point(pt2, &end2); sf1->closestPoint(pt1, u1, v1, clo_pt1, dist1, tol); if (dist1 > tol) break; // No coincidence sf1->closestPoint(pt2, u2, v2, clo_pt2, dist2, tol); if (dist1 > tol) break; // No coincidence // Check curve coincident = checkCoincide(cv2, start2, end2, intsf1.get(), Point(u1,v1), Point(u2,v2), eps); if (!coincident) break; } if (ki == int(bd_cvs2.size())) { // Coincidence of boundary curves found. Check the inner coincident = internalCoincidence(intsf2, intsf1, eps); if (coincident) return 3; } // The surfaces are neither identical nor is one embedded in the other return 0; } int Identity::identicalCvs(shared_ptr<ParamCurve> cv1, double start1, double end1, shared_ptr<ParamCurve> cv2, double start2, double end2, double tol) // Check if two curves are identical, or one is embedded in the other. // The curve extension is limited by start and end parameters of each curve { // Box test BoundingBox box1 = cv1->boundingBox(); BoundingBox box2 = cv2->boundingBox(); if (!box1.overlaps(box2, tol)) return 0; // Initialize intersection objects shared_ptr<ParamCurveInt> intcv1 = shared_ptr<ParamCurveInt>(new ParamCurveInt(cv1)); shared_ptr<ParamCurveInt> intcv2 = shared_ptr<ParamCurveInt>(new ParamCurveInt(cv2)); shared_ptr<GeoTol> eps = shared_ptr<GeoTol>(new GeoTol(tol)); // Check endpoints Point pt1, pt2, pt3, pt4; intcv1->point(pt1, &start1); intcv1->point(pt2, &end1); intcv2->point(pt3, &start2); intcv2->point(pt4, &end2); // First check coincidence int coincident = 0; if (pt1.dist(pt3) <= tol && pt2.dist(pt4) <= tol) coincident = checkCoincide(intcv1.get(), start1, end1, eps, intcv2.get(), start2, end2); else if (pt1.dist(pt4) <= tol && pt2.dist(pt3) <= tol) coincident = checkCoincide(intcv1.get(), start1, end1, eps, intcv2.get(), end2, start2); else { // Project the endpoints on one curve onto the other curve and // check for embedded curves // First check if the first curve is embedded into the second Point clo_pt1, clo_pt2; double clo_dist1, clo_dist2; double clo_par1, clo_par2; cv2->closestPoint(pt1, start2, end2, clo_par1, clo_pt1, clo_dist1); cv2->closestPoint(pt2, start2, end2, clo_par2, clo_pt2, clo_dist2); if (clo_dist1 <= tol && clo_dist2 <= tol) { // Posibility for embedded curve coincident = checkCoincide(intcv1.get(), start1, end1, eps, intcv2.get(), clo_par1, clo_par2); if (coincident) coincident = 2; } if (!coincident) { // Check if curve two is embedded in curve one cv1->closestPoint(pt3, start1, end1, clo_par1, clo_pt1, clo_dist1); cv2->closestPoint(pt4, start1, end1, clo_par2, clo_pt2, clo_dist2); if (clo_dist1 <= tol && clo_dist2 <= tol) { // Posibility for embedded curve coincident = checkCoincide(intcv2.get(), start2, end2, eps, intcv1.get(), clo_par1, clo_par2); if (coincident) coincident = 3; } } } return coincident; } int Identity::internalCoincidence(shared_ptr<ParamSurfaceInt>& intsf1, shared_ptr<ParamSurfaceInt>& intsf2, shared_ptr<GeoTol>& eps) { // Check if the first surface lies in the other. // The surface boundaries are already tested const RectDomain& domain = intsf1->getDomain(); // Surrounding parameter domain double umin = domain.umin(); double umax = domain.umax(); double vmin = domain.vmin(); double vmax = domain.vmax(); int nmb_sample_crvs = 10; double tint1 = (umax - umin)/(int)(nmb_sample_crvs+1); // Only parameter values in the inner double tint2 = (vmax - vmin)/(int)(nmb_sample_crvs+1); // Check coincidence with surface 2 along a number of constant parameter curves of // surface 1 in both parameter directions // 1. parameter direction double par; int ki, kj; int coincident; shared_ptr<ParamSurface> surf1 = intsf1->getParamSurface(); shared_ptr<ParamSurface> surf2 = intsf2->getParamSurface(); double tol = eps->getEpsge(); for (ki=0, par=umin+tint1; ki<nmb_sample_crvs; ++ki, par+=tint1) { vector<shared_ptr<ParamCurve> > const_crvs = surf1->constParamCurves(par, false); for (kj=0; kj<int(const_crvs.size()); ++kj) { shared_ptr<ParamCurveInt> intcrv = shared_ptr<ParamCurveInt>(new ParamCurveInt(const_crvs[kj])); // Project the endpoints onto surface 2 double start, end; Point pt1, pt2, clo_pt1, clo_pt2; double u1, v1, u2, v2, dist1, dist2; start = intcrv->startParam(0); end = intcrv->endParam(0); intcrv->point(pt1, &start); intcrv->point(pt2, &end); surf2->closestPoint(pt1, u1, v1, clo_pt1, dist1, tol); if (dist1 > tol) return 0; // No coincidence surf2->closestPoint(pt2, u2, v2, clo_pt2, dist2, tol); if (dist1 > tol) return 0; // No coincidence // Check curve coincident = checkCoincide(intcrv.get(), start, end, intsf2.get(), Point(u1,v1), Point(u2,v2), eps); if (!coincident) return 0; } } // 2. parameter direction for (ki=0, par=vmin+tint2; ki<nmb_sample_crvs; ++ki, par+=tint2) { vector<shared_ptr<ParamCurve> > const_crvs = surf1->constParamCurves(par, true); for (kj=0; kj<int(const_crvs.size()); ++kj) { shared_ptr<ParamCurveInt> intcrv = shared_ptr<ParamCurveInt>(new ParamCurveInt(const_crvs[kj])); // Project the endpoints onto surface 2 double start, end; Point pt1, pt2, clo_pt1, clo_pt2; double u1, v1, u2, v2, dist1, dist2; start = intcrv->startParam(0); end = intcrv->endParam(0); intcrv->point(pt1, &start); intcrv->point(pt2, &end); surf2->closestPoint(pt1, u1, v1, clo_pt1, dist1, tol); if (dist1 > tol) return 0; // No coincidence surf2->closestPoint(pt2, u2, v2, clo_pt2, dist2, tol); if (dist1 > tol) return 0; // No coincidence // Check curve coincident = checkCoincide(intcrv.get(), start, end, intsf2.get(), Point(u1,v1), Point(u2,v2), eps); if (!coincident) return 0; } } return 1; // Coincidence } } <commit_msg>Fix for closed configurations<commit_after>//=========================================================================== // // File: Identity.C // // Created: // // Author: Vibeke Skytt // // Revision: // // Description: Check for identical and embedded entities // //=========================================================================== #include "GoTools/intersections/Identity.h" #include "GoTools/intersections/ParamSurfaceInt.h" #include "GoTools/intersections/ParamCurveInt.h" #include "GoTools/intersections/Coincidence.h" #include "GoTools/intersections/GeoTol.h" using std::vector; namespace Go { int Identity::identicalSfs(shared_ptr<ParamSurface> sf1, shared_ptr<ParamSurface> sf2, double tol) { // Initialize intersection objects shared_ptr<ParamSurfaceInt> intsf1 = shared_ptr<ParamSurfaceInt>(new ParamSurfaceInt(sf1)); shared_ptr<ParamSurfaceInt> intsf2 = shared_ptr<ParamSurfaceInt>(new ParamSurfaceInt(sf2)); shared_ptr<GeoTol> eps = shared_ptr<GeoTol>(new GeoTol(tol)); // Fetch boundary elements vector<shared_ptr<BoundaryGeomInt> > bd_cvs1; vector<shared_ptr<BoundaryGeomInt> > bd_cvs2; intsf1->getBoundaryObjects(bd_cvs1); intsf2->getBoundaryObjects(bd_cvs2); // Check identity of boundary curves int ki, kj; int coincident = 0; double start1, start2, end1, end2; for (ki=0; ki<int(bd_cvs1.size()); ++ki) { ParamCurveInt *cv1 = bd_cvs1[ki]->getObject()->getParamCurveInt(); start1 = cv1->startParam(0); end1 = cv1->endParam(0); for (kj=0; kj<int(bd_cvs2.size()); ++kj) { ParamCurveInt *cv2 = bd_cvs2[kj]->getObject()->getParamCurveInt(); start2 = cv2->startParam(0); end2 = cv2->endParam(0); // Check orientation Point pt1, pt2, pt3, pt4; cv1->point(pt1, &start1); cv1->point(pt2, &end1); cv2->point(pt3, &start2); cv2->point(pt4, &end2); if (!(pt1.dist(pt3) < tol || pt1.dist(pt4) < tol)) continue; if (!(pt2.dist(pt3) < tol || pt2.dist(pt4) < tol)) continue; if (pt1.dist(pt3) < pt1.dist(pt4)) coincident = checkCoincide(cv1, start1, end1, eps, cv2, start2, end2); else coincident = checkCoincide(cv1, start1, end1, eps, cv2, end2, start2); if (coincident) break; } if (kj == int(bd_cvs2.size())) break; // No coincidence for this boundary curve } if (ki == int(bd_cvs1.size())) { // Coincidence of boundary curves found. Check the inner coincident = internalCoincidence(intsf1, intsf2, eps); if (coincident) return 1; } // Check if the boundary curves of surface 1 lies in surface 2 for (ki=0; ki<int(bd_cvs1.size()); ++ki) { ParamCurveInt *cv1 = bd_cvs1[ki]->getObject()->getParamCurveInt(); start1 = cv1->startParam(0); end1 = cv1->endParam(0); // Project the endpoints onto surface 2 Point pt1, pt2, clo_pt1, clo_pt2; double u1, v1, u2, v2, dist1, dist2; cv1->point(pt1, &start1); cv1->point(pt2, &end1); sf2->closestPoint(pt1, u1, v1, clo_pt1, dist1, tol); if (dist1 > tol) break; // No coincidence sf2->closestPoint(pt2, u2, v2, clo_pt2, dist2, tol); if (dist2 > tol) break; // No coincidence // Check curve coincident = checkCoincide(cv1, start1, end1, intsf2.get(), Point(u1,v1), Point(u2,v2), eps); if (!coincident) break; } if (ki == int(bd_cvs1.size())) { // Coincidence of boundary curves found. Check the inner coincident = internalCoincidence(intsf1, intsf2, eps); if (coincident) return 2; } // Check if the boundary curves of surface 2 lies in surface 1 for (ki=0; ki<int(bd_cvs2.size()); ++ki) { ParamCurveInt *cv2 = bd_cvs2[ki]->getObject()->getParamCurveInt(); start2 = cv2->startParam(0); end2 = cv2->endParam(0); // Project the endpoints onto surface 2 Point pt1, pt2, clo_pt1, clo_pt2; double u1, v1, u2, v2, dist1, dist2; cv2->point(pt1, &start2); cv2->point(pt2, &end2); sf1->closestPoint(pt1, u1, v1, clo_pt1, dist1, tol); if (dist1 > tol) break; // No coincidence sf1->closestPoint(pt2, u2, v2, clo_pt2, dist2, tol); if (dist1 > tol) break; // No coincidence // Check curve coincident = checkCoincide(cv2, start2, end2, intsf1.get(), Point(u1,v1), Point(u2,v2), eps); if (!coincident) break; } if (ki == int(bd_cvs2.size())) { // Coincidence of boundary curves found. Check the inner coincident = internalCoincidence(intsf2, intsf1, eps); if (coincident) return 3; } // The surfaces are neither identical nor is one embedded in the other return 0; } int Identity::identicalCvs(shared_ptr<ParamCurve> cv1, double start1, double end1, shared_ptr<ParamCurve> cv2, double start2, double end2, double tol) // Check if two curves are identical, or one is embedded in the other. // The curve extension is limited by start and end parameters of each curve { // Box test BoundingBox box1 = cv1->boundingBox(); BoundingBox box2 = cv2->boundingBox(); if (!box1.overlaps(box2, tol)) return 0; // Initialize intersection objects shared_ptr<ParamCurveInt> intcv1 = shared_ptr<ParamCurveInt>(new ParamCurveInt(cv1)); shared_ptr<ParamCurveInt> intcv2 = shared_ptr<ParamCurveInt>(new ParamCurveInt(cv2)); shared_ptr<GeoTol> eps = shared_ptr<GeoTol>(new GeoTol(tol)); // Check endpoints Point pt1, pt2, pt3, pt4; intcv1->point(pt1, &start1); intcv1->point(pt2, &end1); intcv2->point(pt3, &start2); intcv2->point(pt4, &end2); // First check coincidence int coincident = 0; if (pt1.dist(pt3) <= tol && pt2.dist(pt4) <= tol) coincident = checkCoincide(intcv1.get(), start1, end1, eps, intcv2.get(), start2, end2); else if (pt1.dist(pt4) <= tol && pt2.dist(pt3) <= tol) coincident = checkCoincide(intcv1.get(), start1, end1, eps, intcv2.get(), end2, start2); else { // Project the endpoints on one curve onto the other curve and // check for embedded curves // First check if the first curve is embedded into the second Point clo_pt1, clo_pt2; double clo_dist1, clo_dist2; double clo_par1, clo_par2; cv2->closestPoint(pt1, start2, end2, clo_par1, clo_pt1, clo_dist1); cv2->closestPoint(pt2, start2, end2, clo_par2, clo_pt2, clo_dist2); if (clo_dist1 <= tol && clo_dist2 <= tol) { // Posibility for embedded curve coincident = checkCoincide(intcv1.get(), start1, end1, eps, intcv2.get(), clo_par1, clo_par2); if (coincident) coincident = 2; } if (!coincident) { // Check if curve two is embedded in curve one cv1->closestPoint(pt3, start1, end1, clo_par1, clo_pt1, clo_dist1); cv2->closestPoint(pt4, start1, end1, clo_par2, clo_pt2, clo_dist2); if (clo_dist1 <= tol && clo_dist2 <= tol) { // Posibility for embedded curve coincident = checkCoincide(intcv2.get(), start2, end2, eps, intcv1.get(), clo_par1, clo_par2); if (coincident) coincident = 3; } } } return coincident; } int Identity::internalCoincidence(shared_ptr<ParamSurfaceInt>& intsf1, shared_ptr<ParamSurfaceInt>& intsf2, shared_ptr<GeoTol>& eps) { // Check if the first surface lies in the other. // The surface boundaries are already tested const RectDomain& domain = intsf1->getDomain(); // Surrounding parameter domain double umin = domain.umin(); double umax = domain.umax(); double vmin = domain.vmin(); double vmax = domain.vmax(); int nmb_sample_crvs = 10; double tint1 = (umax - umin)/(int)(nmb_sample_crvs+1); // Only parameter values in the inner double tint2 = (vmax - vmin)/(int)(nmb_sample_crvs+1); // Check coincidence with surface 2 along a number of constant parameter curves of // surface 1 in both parameter directions // 1. parameter direction double par; int ki, kj; int coincident; shared_ptr<ParamSurface> surf1 = intsf1->getParamSurface(); shared_ptr<ParamSurface> surf2 = intsf2->getParamSurface(); double tol = eps->getEpsge(); double rel_par_res = eps->getRelParRes(); for (ki=0, par=umin+tint1; ki<nmb_sample_crvs; ++ki, par+=tint1) { vector<shared_ptr<ParamCurve> > const_crvs = surf1->constParamCurves(par, false); for (kj=0; kj<int(const_crvs.size()); ++kj) { shared_ptr<ParamCurveInt> intcrv = shared_ptr<ParamCurveInt>(new ParamCurveInt(const_crvs[kj])); // Project the endpoints onto surface 2 double start, end; Point pt1, pt2, clo_pt1, clo_pt2; double u1, v1, u2, v2, dist1, dist2; start = intcrv->startParam(0); end = intcrv->endParam(0); intcrv->point(pt1, &start); intcrv->point(pt2, &end); surf2->closestPoint(pt1, u1, v1, clo_pt1, dist1, tol); if (dist1 > tol) return 0; // No coincidence surf2->closestPoint(pt2, u2, v2, clo_pt2, dist2, tol); if (dist1 > tol) return 0; // No coincidence // Check curve Point parpt1(u1, v1); Point parpt2(u2, v2); coincident = checkCoincide(intcrv.get(), start, end, intsf2.get(), parpt1, parpt2, eps); if (!coincident) { // Extra check in closed configurations if (pt1.dist(pt2) < tol && parpt1.dist(parpt2) < rel_par_res) { double seed[2]; Point pt3 = const_crvs[kj]->point(start + 0.1*(end-start)); surf2->closestPoint(pt3, seed[0], seed[1], clo_pt1, dist1, tol); surf2->closestPoint(pt1, u1, v1, clo_pt1, dist1, tol, NULL, seed); Point pt4 = const_crvs[kj]->point(end - 0.1*(end-start)); surf2->closestPoint(pt4, seed[0], seed[1], clo_pt2, dist2, tol); surf2->closestPoint(pt2, u2, v2, clo_pt2, dist2, tol, NULL, seed); if (dist1 > tol) return 0; // No coincidence // Check curve parpt1 = Point(u1, v1); parpt2 = Point(u2, v2); coincident = checkCoincide(intcrv.get(), start, end, intsf2.get(), parpt1, parpt2, eps); if (!coincident) return 0; } else return 0; } } } // 2. parameter direction for (ki=0, par=vmin+tint2; ki<nmb_sample_crvs; ++ki, par+=tint2) { vector<shared_ptr<ParamCurve> > const_crvs = surf1->constParamCurves(par, true); for (kj=0; kj<int(const_crvs.size()); ++kj) { shared_ptr<ParamCurveInt> intcrv = shared_ptr<ParamCurveInt>(new ParamCurveInt(const_crvs[kj])); // Project the endpoints onto surface 2 double start, end; Point pt1, pt2, clo_pt1, clo_pt2; double u1, v1, u2, v2, dist1, dist2; start = intcrv->startParam(0); end = intcrv->endParam(0); intcrv->point(pt1, &start); intcrv->point(pt2, &end); surf2->closestPoint(pt1, u1, v1, clo_pt1, dist1, tol); if (dist1 > tol) return 0; // No coincidence surf2->closestPoint(pt2, u2, v2, clo_pt2, dist2, tol); if (dist1 > tol) return 0; // No coincidence // Check curve Point parpt1(u1, v1); Point parpt2(u2, v2); coincident = checkCoincide(intcrv.get(), start, end, intsf2.get(), parpt1, parpt2, eps); if (!coincident) { // Extra check in closed configurations if (pt1.dist(pt2) < tol && parpt1.dist(parpt2) < rel_par_res) { double seed[2]; Point pt3 = const_crvs[kj]->point(start + 0.1*(end-start)); surf2->closestPoint(pt3, seed[0], seed[1], clo_pt1, dist1, tol); surf2->closestPoint(pt1, u1, v1, clo_pt1, dist1, tol, NULL, seed); Point pt4 = const_crvs[kj]->point(end - 0.1*(end-start)); surf2->closestPoint(pt4, seed[0], seed[1], clo_pt2, dist2, tol); surf2->closestPoint(pt2, u2, v2, clo_pt2, dist2, tol, NULL, seed); if (dist1 > tol) return 0; // No coincidence // Check curve parpt1 = Point(u1, v1); parpt2 = Point(u2, v2); coincident = checkCoincide(intcrv.get(), start, end, intsf2.get(), parpt1, parpt2, eps); if (!coincident) return 0; } else return 0; } } } return 1; // Coincidence } } <|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 "base/bind_helpers.h" #include "base/location.h" #include "base/memory/scoped_ptr.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/strings/utf_string_conversions.h" #include "base/thread_task_runner_handle.h" #include "chrome/browser/plugins/chrome_plugin_service_filter.h" #include "chrome/browser/plugins/plugin_prefs.h" #include "chrome/browser/printing/print_preview_dialog_controller.h" #include "chrome/browser/task_management/task_management_browsertest_util.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/chrome_content_client.h" #include "chrome/common/url_constants.h" #include "chrome/grit/generated_resources.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "components/printing/common/print_messages.h" #include "content/public/browser/plugin_service.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/test/browser_test_utils.h" #include "ipc/ipc_message_macros.h" #include "ui/base/l10n/l10n_util.h" #include "url/gurl.h" using content::WebContents; using content::WebContentsObserver; namespace { class RequestPrintPreviewObserver : public WebContentsObserver { public: explicit RequestPrintPreviewObserver(WebContents* dialog) : WebContentsObserver(dialog) { } ~RequestPrintPreviewObserver() override {} void set_quit_closure(const base::Closure& quit_closure) { quit_closure_ = quit_closure; } private: // content::WebContentsObserver implementation. bool OnMessageReceived(const IPC::Message& message) override { IPC_BEGIN_MESSAGE_MAP(RequestPrintPreviewObserver, message) IPC_MESSAGE_HANDLER(PrintHostMsg_RequestPrintPreview, OnRequestPrintPreview) IPC_MESSAGE_UNHANDLED(break;) IPC_END_MESSAGE_MAP(); return false; // Report not handled so the real handler receives it. } void OnRequestPrintPreview( const PrintHostMsg_RequestPrintPreview_Params& /* params */) { base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, quit_closure_); } base::Closure quit_closure_; DISALLOW_COPY_AND_ASSIGN(RequestPrintPreviewObserver); }; class PrintPreviewDialogClonedObserver : public WebContentsObserver { public: explicit PrintPreviewDialogClonedObserver(WebContents* dialog) : WebContentsObserver(dialog) { } ~PrintPreviewDialogClonedObserver() override {} RequestPrintPreviewObserver* request_preview_dialog_observer() { return request_preview_dialog_observer_.get(); } private: // content::WebContentsObserver implementation. void DidCloneToNewWebContents(WebContents* old_web_contents, WebContents* new_web_contents) override { request_preview_dialog_observer_.reset( new RequestPrintPreviewObserver(new_web_contents)); } scoped_ptr<RequestPrintPreviewObserver> request_preview_dialog_observer_; DISALLOW_COPY_AND_ASSIGN(PrintPreviewDialogClonedObserver); }; class PrintPreviewDialogDestroyedObserver : public WebContentsObserver { public: explicit PrintPreviewDialogDestroyedObserver(WebContents* dialog) : WebContentsObserver(dialog), dialog_destroyed_(false) { } ~PrintPreviewDialogDestroyedObserver() override {} bool dialog_destroyed() const { return dialog_destroyed_; } private: // content::WebContentsObserver implementation. void WebContentsDestroyed() override { dialog_destroyed_ = true; } bool dialog_destroyed_; DISALLOW_COPY_AND_ASSIGN(PrintPreviewDialogDestroyedObserver); }; void PluginsLoadedCallback( const base::Closure& quit_closure, const std::vector<content::WebPluginInfo>& /* info */) { quit_closure.Run(); } bool GetPdfPluginInfo(content::WebPluginInfo* info) { base::FilePath pdf_plugin_path = base::FilePath::FromUTF8Unsafe( ChromeContentClient::kPDFPluginPath); return content::PluginService::GetInstance()->GetPluginInfoByPath( pdf_plugin_path, info); } const char kDummyPrintUrl[] = "chrome://print/dummy.pdf"; void CountFrames(int* frame_count, content::RenderFrameHost* frame) { ++(*frame_count); } void CheckPdfPluginForRenderFrame(content::RenderFrameHost* frame) { content::WebPluginInfo pdf_plugin_info; ASSERT_TRUE(GetPdfPluginInfo(&pdf_plugin_info)); ChromePluginServiceFilter* filter = ChromePluginServiceFilter::GetInstance(); EXPECT_TRUE(filter->IsPluginAvailable( frame->GetProcess()->GetID(), frame->GetRoutingID(), nullptr, GURL(kDummyPrintUrl), GURL(), &pdf_plugin_info)); } } // namespace class PrintPreviewDialogControllerBrowserTest : public InProcessBrowserTest { public: PrintPreviewDialogControllerBrowserTest() : initiator_(nullptr) {} ~PrintPreviewDialogControllerBrowserTest() override {} WebContents* initiator() { return initiator_; } void PrintPreview() { base::RunLoop run_loop; request_preview_dialog_observer()->set_quit_closure(run_loop.QuitClosure()); chrome::Print(browser()); run_loop.Run(); } WebContents* GetPrintPreviewDialog() { printing::PrintPreviewDialogController* dialog_controller = printing::PrintPreviewDialogController::GetInstance(); return dialog_controller->GetPrintPreviewForContents(initiator_); } private: void SetUpOnMainThread() override { WebContents* first_tab = browser()->tab_strip_model()->GetActiveWebContents(); ASSERT_TRUE(first_tab); // Open a new tab so |cloned_tab_observer_| can see it first and attach a // RequestPrintPreviewObserver to it before the real // PrintPreviewMessageHandler gets created. Thus enabling // RequestPrintPreviewObserver to get messages first for the purposes of // this test. cloned_tab_observer_.reset(new PrintPreviewDialogClonedObserver(first_tab)); chrome::DuplicateTab(browser()); initiator_ = browser()->tab_strip_model()->GetActiveWebContents(); ASSERT_TRUE(initiator_); ASSERT_NE(first_tab, initiator_); content::PluginService::GetInstance()->Init(); content::PluginService::GetInstance()->DisablePluginsDiscoveryForTesting(); } void TearDownOnMainThread() override { cloned_tab_observer_.reset(); initiator_ = nullptr; } RequestPrintPreviewObserver* request_preview_dialog_observer() { return cloned_tab_observer_->request_preview_dialog_observer(); } scoped_ptr<PrintPreviewDialogClonedObserver> cloned_tab_observer_; WebContents* initiator_; DISALLOW_COPY_AND_ASSIGN(PrintPreviewDialogControllerBrowserTest); }; // Test to verify that when a initiator navigates, we can create a new preview // dialog for the new tab contents. // http://crbug.com/377337 #if defined(OS_WIN) #define MAYBE_NavigateFromInitiatorTab DISABLED_NavigateFromInitiatorTab #else #define MAYBE_NavigateFromInitiatorTab NavigateFromInitiatorTab #endif IN_PROC_BROWSER_TEST_F(PrintPreviewDialogControllerBrowserTest, MAYBE_NavigateFromInitiatorTab) { // Print for the first time. PrintPreview(); // Get the preview dialog for the initiator tab. WebContents* preview_dialog = GetPrintPreviewDialog(); // Check a new print preview dialog got created. ASSERT_TRUE(preview_dialog); ASSERT_NE(initiator(), preview_dialog); // Navigate in the initiator tab. Make sure navigating destroys the print // preview dialog. PrintPreviewDialogDestroyedObserver dialog_destroyed_observer(preview_dialog); ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL)); ASSERT_TRUE(dialog_destroyed_observer.dialog_destroyed()); // Try printing again. PrintPreview(); // Get the print preview dialog for the initiator tab. WebContents* new_preview_dialog = GetPrintPreviewDialog(); // Check a new preview dialog got created. EXPECT_TRUE(new_preview_dialog); } // Test to verify that after reloading the initiator, it creates a new print // preview dialog. // http://crbug.com/377337 #if defined(OS_WIN) #define MAYBE_ReloadInitiatorTab DISABLED_ReloadInitiatorTab #else #define MAYBE_ReloadInitiatorTab ReloadInitiatorTab #endif IN_PROC_BROWSER_TEST_F(PrintPreviewDialogControllerBrowserTest, MAYBE_ReloadInitiatorTab) { // Print for the first time. PrintPreview(); WebContents* preview_dialog = GetPrintPreviewDialog(); // Check a new print preview dialog got created. ASSERT_TRUE(preview_dialog); ASSERT_NE(initiator(), preview_dialog); // Reload the initiator. Make sure reloading destroys the print preview // dialog. PrintPreviewDialogDestroyedObserver dialog_destroyed_observer(preview_dialog); chrome::Reload(browser(), CURRENT_TAB); content::WaitForLoadStop( browser()->tab_strip_model()->GetActiveWebContents()); ASSERT_TRUE(dialog_destroyed_observer.dialog_destroyed()); // Try printing again. PrintPreview(); // Create a preview dialog for the initiator tab. WebContents* new_preview_dialog = GetPrintPreviewDialog(); EXPECT_TRUE(new_preview_dialog); } // Test to verify that after print preview works even when the PDF plugin is // disabled for webpages. IN_PROC_BROWSER_TEST_F(PrintPreviewDialogControllerBrowserTest, PdfPluginDisabled) { // Make sure plugins are loaded. { base::RunLoop run_loop; content::PluginService::GetInstance()->GetPlugins( base::Bind(&PluginsLoadedCallback, run_loop.QuitClosure())); run_loop.Run(); } // Get the PDF plugin info. content::WebPluginInfo pdf_plugin_info; ASSERT_TRUE(GetPdfPluginInfo(&pdf_plugin_info)); // Disable the PDF plugin. PluginPrefs::GetForProfile(browser()->profile())->EnablePluginGroup( false, base::ASCIIToUTF16(ChromeContentClient::kPDFPluginName)); // Make sure it is actually disabled for webpages. ChromePluginServiceFilter* filter = ChromePluginServiceFilter::GetInstance(); content::WebPluginInfo dummy_pdf_plugin_info = pdf_plugin_info; EXPECT_FALSE(filter->IsPluginAvailable( initiator()->GetRenderProcessHost()->GetID(), initiator()->GetMainFrame()->GetRoutingID(), nullptr, GURL("http://google.com"), GURL(), &dummy_pdf_plugin_info)); PrintPreview(); // Check a new print preview dialog got created. WebContents* preview_dialog = GetPrintPreviewDialog(); ASSERT_TRUE(preview_dialog); ASSERT_NE(initiator(), preview_dialog); // Wait until the <iframe> in the print preview renderer has loaded. // |frame_count| should be 2. The other frame is the main frame. const int kExpectedFrameCount = 2; int frame_count; do { base::RunLoop run_loop; base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, run_loop.QuitClosure(), base::TimeDelta::FromSeconds(1)); run_loop.Run(); frame_count = 0; preview_dialog->ForEachFrame( base::Bind(&CountFrames, base::Unretained(&frame_count))); } while (frame_count < kExpectedFrameCount); ASSERT_EQ(kExpectedFrameCount, frame_count); // Make sure all the frames in the dialog has access to the PDF plugin. preview_dialog->ForEachFrame(base::Bind(&CheckPdfPluginForRenderFrame)); } #if defined(ENABLE_TASK_MANAGER) namespace { base::string16 GetExpectedPrefix() { return l10n_util::GetStringFUTF16(IDS_TASK_MANAGER_PRINT_PREFIX, base::string16()); } const std::vector<task_management::WebContentsTag*>& GetTrackedTags() { return task_management::WebContentsTagsManager::GetInstance()-> tracked_tags(); } IN_PROC_BROWSER_TEST_F(PrintPreviewDialogControllerBrowserTest, TaskManagementTest) { // This test starts with two tabs open. EXPECT_EQ(2U, GetTrackedTags().size()); PrintPreview(); EXPECT_EQ(3U, GetTrackedTags().size()); // Create a task manager and expect the pre-existing print previews are // provided. task_management::MockWebContentsTaskManager task_manager; EXPECT_TRUE(task_manager.tasks().empty()); task_manager.StartObserving(); EXPECT_EQ(3U, task_manager.tasks().size()); const task_management::Task* pre_existing_task = task_manager.tasks().back(); EXPECT_EQ(task_management::Task::RENDERER, pre_existing_task->GetType()); const base::string16 pre_existing_title = pre_existing_task->title(); const base::string16 expected_prefix = GetExpectedPrefix(); EXPECT_TRUE(base::StartsWith(pre_existing_title, expected_prefix, base::CompareCase::INSENSITIVE_ASCII)); // Navigating away from the current page in the current tab for which a print // preview is displayed will cancel the print preview and hence the task // manger shouldn't show a printing task. ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL)); EXPECT_EQ(2U, GetTrackedTags().size()); EXPECT_EQ(2U, task_manager.tasks().size()); // Now start another print preview after the had already been created and // validated that a corresponding task is reported. PrintPreview(); EXPECT_EQ(3U, GetTrackedTags().size()); EXPECT_EQ(3U, task_manager.tasks().size()); const task_management::Task* task = task_manager.tasks().back(); EXPECT_EQ(task_management::Task::RENDERER, task->GetType()); const base::string16 title = task->title(); EXPECT_TRUE(base::StartsWith(title, expected_prefix, base::CompareCase::INSENSITIVE_ASCII)); } } // namespace #endif // defined(ENABLE_TASK_MANAGER) <commit_msg>Make The task manager browser tests for the print preview work under --site-per-process<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 "base/bind_helpers.h" #include "base/location.h" #include "base/memory/scoped_ptr.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/strings/utf_string_conversions.h" #include "base/thread_task_runner_handle.h" #include "chrome/browser/plugins/chrome_plugin_service_filter.h" #include "chrome/browser/plugins/plugin_prefs.h" #include "chrome/browser/printing/print_preview_dialog_controller.h" #include "chrome/browser/task_management/task_management_browsertest_util.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/chrome_content_client.h" #include "chrome/common/url_constants.h" #include "chrome/grit/generated_resources.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "components/printing/common/print_messages.h" #include "content/public/browser/plugin_service.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/test/browser_test_utils.h" #include "ipc/ipc_message_macros.h" #include "ui/base/l10n/l10n_util.h" #include "url/gurl.h" using content::WebContents; using content::WebContentsObserver; namespace { class RequestPrintPreviewObserver : public WebContentsObserver { public: explicit RequestPrintPreviewObserver(WebContents* dialog) : WebContentsObserver(dialog) { } ~RequestPrintPreviewObserver() override {} void set_quit_closure(const base::Closure& quit_closure) { quit_closure_ = quit_closure; } private: // content::WebContentsObserver implementation. bool OnMessageReceived(const IPC::Message& message) override { IPC_BEGIN_MESSAGE_MAP(RequestPrintPreviewObserver, message) IPC_MESSAGE_HANDLER(PrintHostMsg_RequestPrintPreview, OnRequestPrintPreview) IPC_MESSAGE_UNHANDLED(break;) IPC_END_MESSAGE_MAP(); return false; // Report not handled so the real handler receives it. } void OnRequestPrintPreview( const PrintHostMsg_RequestPrintPreview_Params& /* params */) { base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, quit_closure_); } base::Closure quit_closure_; DISALLOW_COPY_AND_ASSIGN(RequestPrintPreviewObserver); }; class PrintPreviewDialogClonedObserver : public WebContentsObserver { public: explicit PrintPreviewDialogClonedObserver(WebContents* dialog) : WebContentsObserver(dialog) { } ~PrintPreviewDialogClonedObserver() override {} RequestPrintPreviewObserver* request_preview_dialog_observer() { return request_preview_dialog_observer_.get(); } private: // content::WebContentsObserver implementation. void DidCloneToNewWebContents(WebContents* old_web_contents, WebContents* new_web_contents) override { request_preview_dialog_observer_.reset( new RequestPrintPreviewObserver(new_web_contents)); } scoped_ptr<RequestPrintPreviewObserver> request_preview_dialog_observer_; DISALLOW_COPY_AND_ASSIGN(PrintPreviewDialogClonedObserver); }; class PrintPreviewDialogDestroyedObserver : public WebContentsObserver { public: explicit PrintPreviewDialogDestroyedObserver(WebContents* dialog) : WebContentsObserver(dialog), dialog_destroyed_(false) { } ~PrintPreviewDialogDestroyedObserver() override {} bool dialog_destroyed() const { return dialog_destroyed_; } private: // content::WebContentsObserver implementation. void WebContentsDestroyed() override { dialog_destroyed_ = true; } bool dialog_destroyed_; DISALLOW_COPY_AND_ASSIGN(PrintPreviewDialogDestroyedObserver); }; void PluginsLoadedCallback( const base::Closure& quit_closure, const std::vector<content::WebPluginInfo>& /* info */) { quit_closure.Run(); } bool GetPdfPluginInfo(content::WebPluginInfo* info) { base::FilePath pdf_plugin_path = base::FilePath::FromUTF8Unsafe( ChromeContentClient::kPDFPluginPath); return content::PluginService::GetInstance()->GetPluginInfoByPath( pdf_plugin_path, info); } const char kDummyPrintUrl[] = "chrome://print/dummy.pdf"; void CountFrames(int* frame_count, content::RenderFrameHost* frame) { ++(*frame_count); } void CheckPdfPluginForRenderFrame(content::RenderFrameHost* frame) { content::WebPluginInfo pdf_plugin_info; ASSERT_TRUE(GetPdfPluginInfo(&pdf_plugin_info)); ChromePluginServiceFilter* filter = ChromePluginServiceFilter::GetInstance(); EXPECT_TRUE(filter->IsPluginAvailable( frame->GetProcess()->GetID(), frame->GetRoutingID(), nullptr, GURL(kDummyPrintUrl), GURL(), &pdf_plugin_info)); } } // namespace class PrintPreviewDialogControllerBrowserTest : public InProcessBrowserTest { public: PrintPreviewDialogControllerBrowserTest() : initiator_(nullptr) {} ~PrintPreviewDialogControllerBrowserTest() override {} WebContents* initiator() { return initiator_; } void PrintPreview() { base::RunLoop run_loop; request_preview_dialog_observer()->set_quit_closure(run_loop.QuitClosure()); chrome::Print(browser()); run_loop.Run(); } WebContents* GetPrintPreviewDialog() { printing::PrintPreviewDialogController* dialog_controller = printing::PrintPreviewDialogController::GetInstance(); return dialog_controller->GetPrintPreviewForContents(initiator_); } private: void SetUpOnMainThread() override { WebContents* first_tab = browser()->tab_strip_model()->GetActiveWebContents(); ASSERT_TRUE(first_tab); // Open a new tab so |cloned_tab_observer_| can see it first and attach a // RequestPrintPreviewObserver to it before the real // PrintPreviewMessageHandler gets created. Thus enabling // RequestPrintPreviewObserver to get messages first for the purposes of // this test. cloned_tab_observer_.reset(new PrintPreviewDialogClonedObserver(first_tab)); chrome::DuplicateTab(browser()); initiator_ = browser()->tab_strip_model()->GetActiveWebContents(); ASSERT_TRUE(initiator_); ASSERT_NE(first_tab, initiator_); content::PluginService::GetInstance()->Init(); content::PluginService::GetInstance()->DisablePluginsDiscoveryForTesting(); } void TearDownOnMainThread() override { cloned_tab_observer_.reset(); initiator_ = nullptr; } RequestPrintPreviewObserver* request_preview_dialog_observer() { return cloned_tab_observer_->request_preview_dialog_observer(); } scoped_ptr<PrintPreviewDialogClonedObserver> cloned_tab_observer_; WebContents* initiator_; DISALLOW_COPY_AND_ASSIGN(PrintPreviewDialogControllerBrowserTest); }; // Test to verify that when a initiator navigates, we can create a new preview // dialog for the new tab contents. // http://crbug.com/377337 #if defined(OS_WIN) #define MAYBE_NavigateFromInitiatorTab DISABLED_NavigateFromInitiatorTab #else #define MAYBE_NavigateFromInitiatorTab NavigateFromInitiatorTab #endif IN_PROC_BROWSER_TEST_F(PrintPreviewDialogControllerBrowserTest, MAYBE_NavigateFromInitiatorTab) { // Print for the first time. PrintPreview(); // Get the preview dialog for the initiator tab. WebContents* preview_dialog = GetPrintPreviewDialog(); // Check a new print preview dialog got created. ASSERT_TRUE(preview_dialog); ASSERT_NE(initiator(), preview_dialog); // Navigate in the initiator tab. Make sure navigating destroys the print // preview dialog. PrintPreviewDialogDestroyedObserver dialog_destroyed_observer(preview_dialog); ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL)); ASSERT_TRUE(dialog_destroyed_observer.dialog_destroyed()); // Try printing again. PrintPreview(); // Get the print preview dialog for the initiator tab. WebContents* new_preview_dialog = GetPrintPreviewDialog(); // Check a new preview dialog got created. EXPECT_TRUE(new_preview_dialog); } // Test to verify that after reloading the initiator, it creates a new print // preview dialog. // http://crbug.com/377337 #if defined(OS_WIN) #define MAYBE_ReloadInitiatorTab DISABLED_ReloadInitiatorTab #else #define MAYBE_ReloadInitiatorTab ReloadInitiatorTab #endif IN_PROC_BROWSER_TEST_F(PrintPreviewDialogControllerBrowserTest, MAYBE_ReloadInitiatorTab) { // Print for the first time. PrintPreview(); WebContents* preview_dialog = GetPrintPreviewDialog(); // Check a new print preview dialog got created. ASSERT_TRUE(preview_dialog); ASSERT_NE(initiator(), preview_dialog); // Reload the initiator. Make sure reloading destroys the print preview // dialog. PrintPreviewDialogDestroyedObserver dialog_destroyed_observer(preview_dialog); chrome::Reload(browser(), CURRENT_TAB); content::WaitForLoadStop( browser()->tab_strip_model()->GetActiveWebContents()); ASSERT_TRUE(dialog_destroyed_observer.dialog_destroyed()); // Try printing again. PrintPreview(); // Create a preview dialog for the initiator tab. WebContents* new_preview_dialog = GetPrintPreviewDialog(); EXPECT_TRUE(new_preview_dialog); } // Test to verify that after print preview works even when the PDF plugin is // disabled for webpages. IN_PROC_BROWSER_TEST_F(PrintPreviewDialogControllerBrowserTest, PdfPluginDisabled) { // Make sure plugins are loaded. { base::RunLoop run_loop; content::PluginService::GetInstance()->GetPlugins( base::Bind(&PluginsLoadedCallback, run_loop.QuitClosure())); run_loop.Run(); } // Get the PDF plugin info. content::WebPluginInfo pdf_plugin_info; ASSERT_TRUE(GetPdfPluginInfo(&pdf_plugin_info)); // Disable the PDF plugin. PluginPrefs::GetForProfile(browser()->profile())->EnablePluginGroup( false, base::ASCIIToUTF16(ChromeContentClient::kPDFPluginName)); // Make sure it is actually disabled for webpages. ChromePluginServiceFilter* filter = ChromePluginServiceFilter::GetInstance(); content::WebPluginInfo dummy_pdf_plugin_info = pdf_plugin_info; EXPECT_FALSE(filter->IsPluginAvailable( initiator()->GetRenderProcessHost()->GetID(), initiator()->GetMainFrame()->GetRoutingID(), nullptr, GURL("http://google.com"), GURL(), &dummy_pdf_plugin_info)); PrintPreview(); // Check a new print preview dialog got created. WebContents* preview_dialog = GetPrintPreviewDialog(); ASSERT_TRUE(preview_dialog); ASSERT_NE(initiator(), preview_dialog); // Wait until the <iframe> in the print preview renderer has loaded. // |frame_count| should be 2. The other frame is the main frame. const int kExpectedFrameCount = 2; int frame_count; do { base::RunLoop run_loop; base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, run_loop.QuitClosure(), base::TimeDelta::FromSeconds(1)); run_loop.Run(); frame_count = 0; preview_dialog->ForEachFrame( base::Bind(&CountFrames, base::Unretained(&frame_count))); } while (frame_count < kExpectedFrameCount); ASSERT_EQ(kExpectedFrameCount, frame_count); // Make sure all the frames in the dialog has access to the PDF plugin. preview_dialog->ForEachFrame(base::Bind(&CheckPdfPluginForRenderFrame)); } #if defined(ENABLE_TASK_MANAGER) namespace { base::string16 GetExpectedPrefix() { return l10n_util::GetStringFUTF16(IDS_TASK_MANAGER_PRINT_PREFIX, base::string16()); } const std::vector<task_management::WebContentsTag*>& GetTrackedTags() { return task_management::WebContentsTagsManager::GetInstance()-> tracked_tags(); } IN_PROC_BROWSER_TEST_F(PrintPreviewDialogControllerBrowserTest, TaskManagementTest) { // This test starts with two tabs open. EXPECT_EQ(2U, GetTrackedTags().size()); PrintPreview(); EXPECT_EQ(3U, GetTrackedTags().size()); // Create a task manager and expect the pre-existing print previews are // provided. task_management::MockWebContentsTaskManager task_manager; EXPECT_TRUE(task_manager.tasks().empty()); task_manager.StartObserving(); EXPECT_EQ(3U, task_manager.tasks().size()); const task_management::Task* pre_existing_task = task_manager.tasks().back(); EXPECT_EQ(task_management::Task::RENDERER, pre_existing_task->GetType()); const base::string16 pre_existing_title = pre_existing_task->title(); const base::string16 expected_prefix = GetExpectedPrefix(); EXPECT_TRUE(base::StartsWith(pre_existing_title, expected_prefix, base::CompareCase::INSENSITIVE_ASCII)); // Navigating away from the current page in the current tab for which a print // preview is displayed will cancel the print preview and hence the task // manger shouldn't show a printing task. ui_test_utils::NavigateToURL(browser(), GURL("about:blank")); EXPECT_EQ(2U, GetTrackedTags().size()); EXPECT_EQ(2U, task_manager.tasks().size()); // Now start another print preview after the had already been created and // validated that a corresponding task is reported. PrintPreview(); EXPECT_EQ(3U, GetTrackedTags().size()); EXPECT_EQ(3U, task_manager.tasks().size()); const task_management::Task* task = task_manager.tasks().back(); EXPECT_EQ(task_management::Task::RENDERER, task->GetType()); const base::string16 title = task->title(); EXPECT_TRUE(base::StartsWith(title, expected_prefix, base::CompareCase::INSENSITIVE_ASCII)); } } // namespace #endif // defined(ENABLE_TASK_MANAGER) <|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/browsing_data/browsing_data_helper.h" #include "chrome/browser/browsing_data/browsing_data_remover.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_tabstrip.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/download_manager.h" #include "content/public/browser/web_contents.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/download_test_observer.h" #include "content/test/net/url_request_mock_http_job.h" #include "testing/gtest/include/gtest/gtest.h" class BrowsingDataRemoverBrowserTest : public InProcessBrowserTest { public: BrowsingDataRemoverBrowserTest() {} void RunScriptAndCheckResult(const std::wstring& script, const std::string& result) { std::string data; ASSERT_TRUE(content::ExecuteJavaScriptAndExtractString( chrome::GetActiveWebContents(browser())->GetRenderViewHost(), L"", script, &data)); ASSERT_EQ(data, result); } void RemoveAndWait(int remove_mask) { content::WindowedNotificationObserver signal( chrome::NOTIFICATION_BROWSING_DATA_REMOVED, content::Source<Profile>(browser()->profile())); BrowsingDataRemover* remover = new BrowsingDataRemover( browser()->profile(), BrowsingDataRemover::LAST_HOUR, base::Time::Now() + base::TimeDelta::FromMilliseconds(10)); remover->Remove(remove_mask, BrowsingDataHelper::UNPROTECTED_WEB); signal.Wait(); } }; // Test BrowsingDataRemover for downloads. IN_PROC_BROWSER_TEST_F(BrowsingDataRemoverBrowserTest, Download) { // Start a download. content::DownloadManager* download_manager = content::BrowserContext::GetDownloadManager(browser()->profile()); scoped_ptr<content::DownloadTestObserver> observer( new content::DownloadTestObserverTerminal( download_manager, 1, content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT)); GURL download_url = ui_test_utils::GetTestUrl( FilePath().AppendASCII("downloads"), FilePath().AppendASCII("a_zip_file.zip")); ui_test_utils::NavigateToURL(browser(), download_url); observer->WaitForFinished(); std::vector<content::DownloadItem*> downloads; download_manager->GetAllDownloads(FilePath(), &downloads); EXPECT_EQ(1u, downloads.size()); RemoveAndWait(BrowsingDataRemover::REMOVE_DOWNLOADS); downloads.clear(); download_manager->GetAllDownloads(FilePath(), &downloads); EXPECT_TRUE(downloads.empty()); } #if !defined(OS_LINUX) // Verify can modify database after deleting it. IN_PROC_BROWSER_TEST_F(BrowsingDataRemoverBrowserTest, Database) { ASSERT_TRUE(test_server()->Start()); GURL url = test_server()->GetURL("files/database/simple_database.html"); ui_test_utils::NavigateToURL(browser(), url); RunScriptAndCheckResult(L"createTable()", "done"); RunScriptAndCheckResult(L"insertRecord('text')", "done"); RunScriptAndCheckResult(L"getRecords()", "text"); RemoveAndWait(BrowsingDataRemover::REMOVE_SITE_DATA); ui_test_utils::NavigateToURL(browser(), url); RunScriptAndCheckResult(L"createTable()", "done"); RunScriptAndCheckResult(L"insertRecord('text2')", "done"); RunScriptAndCheckResult(L"getRecords()", "text2"); } #endif <commit_msg>Disable the right test<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/browsing_data/browsing_data_helper.h" #include "chrome/browser/browsing_data/browsing_data_remover.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_tabstrip.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/download_manager.h" #include "content/public/browser/web_contents.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/download_test_observer.h" #include "content/test/net/url_request_mock_http_job.h" #include "testing/gtest/include/gtest/gtest.h" class BrowsingDataRemoverBrowserTest : public InProcessBrowserTest { public: BrowsingDataRemoverBrowserTest() {} void RunScriptAndCheckResult(const std::wstring& script, const std::string& result) { std::string data; ASSERT_TRUE(content::ExecuteJavaScriptAndExtractString( chrome::GetActiveWebContents(browser())->GetRenderViewHost(), L"", script, &data)); ASSERT_EQ(data, result); } void RemoveAndWait(int remove_mask) { content::WindowedNotificationObserver signal( chrome::NOTIFICATION_BROWSING_DATA_REMOVED, content::Source<Profile>(browser()->profile())); BrowsingDataRemover* remover = new BrowsingDataRemover( browser()->profile(), BrowsingDataRemover::LAST_HOUR, base::Time::Now() + base::TimeDelta::FromMilliseconds(10)); remover->Remove(remove_mask, BrowsingDataHelper::UNPROTECTED_WEB); signal.Wait(); } }; #if !defined(OS_LINUX) // Test BrowsingDataRemover for downloads. IN_PROC_BROWSER_TEST_F(BrowsingDataRemoverBrowserTest, Download) { // Start a download. content::DownloadManager* download_manager = content::BrowserContext::GetDownloadManager(browser()->profile()); scoped_ptr<content::DownloadTestObserver> observer( new content::DownloadTestObserverTerminal( download_manager, 1, content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT)); GURL download_url = ui_test_utils::GetTestUrl( FilePath().AppendASCII("downloads"), FilePath().AppendASCII("a_zip_file.zip")); ui_test_utils::NavigateToURL(browser(), download_url); observer->WaitForFinished(); std::vector<content::DownloadItem*> downloads; download_manager->GetAllDownloads(FilePath(), &downloads); EXPECT_EQ(1u, downloads.size()); RemoveAndWait(BrowsingDataRemover::REMOVE_DOWNLOADS); downloads.clear(); download_manager->GetAllDownloads(FilePath(), &downloads); EXPECT_TRUE(downloads.empty()); } #endif // Verify can modify database after deleting it. IN_PROC_BROWSER_TEST_F(BrowsingDataRemoverBrowserTest, Database) { ASSERT_TRUE(test_server()->Start()); GURL url = test_server()->GetURL("files/database/simple_database.html"); ui_test_utils::NavigateToURL(browser(), url); RunScriptAndCheckResult(L"createTable()", "done"); RunScriptAndCheckResult(L"insertRecord('text')", "done"); RunScriptAndCheckResult(L"getRecords()", "text"); RemoveAndWait(BrowsingDataRemover::REMOVE_SITE_DATA); ui_test_utils::NavigateToURL(browser(), url); RunScriptAndCheckResult(L"createTable()", "done"); RunScriptAndCheckResult(L"insertRecord('text2')", "done"); RunScriptAndCheckResult(L"getRecords()", "text2"); } <|endoftext|>
<commit_before>// Copyright (c) 2009 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/renderer_host/gtk_key_bindings_handler.h" #include <gdk/gdkkeysyms.h> #include <string> #include <utility> #include <vector> #include "base/basictypes.h" #include "base/file_util.h" #include "base/path_service.h" #include "base/string_util.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/edit_command.h" #include "chrome/common/native_web_keyboard_event.h" #include "testing/gtest/include/gtest/gtest.h" class GtkKeyBindingsHandlerTest : public testing::Test { protected: struct EditCommand { const char* name; const char* value; }; GtkKeyBindingsHandlerTest() : window_(gtk_window_new(GTK_WINDOW_TOPLEVEL)), handler_(NULL) { FilePath gtkrc; PathService::Get(chrome::DIR_TEST_DATA, &gtkrc); gtkrc = gtkrc.AppendASCII("gtk_key_bindings_test_gtkrc"); gtk_rc_parse(gtkrc.value().c_str()); GtkWidget* fixed = gtk_fixed_new(); handler_ = new GtkKeyBindingsHandler(fixed); gtk_container_add(GTK_CONTAINER(window_), fixed); gtk_widget_show(fixed); gtk_widget_show(window_); } ~GtkKeyBindingsHandlerTest() { gtk_widget_destroy(window_); delete handler_; } NativeWebKeyboardEvent NewNativeWebKeyboardEvent(guint keyval, guint state) { GdkKeymap* keymap = gdk_keymap_get_for_display(gtk_widget_get_display(window_)); GdkKeymapKey *keys = NULL; gint n_keys = 0; if (gdk_keymap_get_entries_for_keyval(keymap, keyval, &keys, &n_keys)) { GdkEventKey event; event.type = GDK_KEY_PRESS; event.window = NULL; event.send_event = 0; event.time = 0; event.state = state; event.keyval = keyval; event.length = 0; event.string = NULL; event.hardware_keycode = keys[0].keycode; event.group = keys[0].group; event.is_modifier = 0; g_free(keys); return NativeWebKeyboardEvent(&event); } return NativeWebKeyboardEvent(); } void TestKeyBinding(const NativeWebKeyboardEvent& event, const EditCommand expected_result[], size_t size) { EditCommands result; ASSERT_TRUE(handler_->Match(event, &result)); ASSERT_EQ(size, result.size()); for (size_t i = 0; i < size; ++i) { ASSERT_STREQ(expected_result[i].name, result[i].name.c_str()); ASSERT_STREQ(expected_result[i].value, result[i].value.c_str()); } } protected: GtkWidget* window_; GtkKeyBindingsHandler* handler_; }; TEST_F(GtkKeyBindingsHandlerTest, MoveCursor) { static const EditCommand kEditCommands[] = { // "move-cursor" (logical-positions, -2, 0) { "MoveBackward", "" }, { "MoveBackward", "" }, // "move-cursor" (logical-positions, 2, 0) { "MoveForward", "" }, { "MoveForward", "" }, // "move-cursor" (visual-positions, -1, 1) { "MoveLeftAndModifySelection", "" }, // "move-cursor" (visual-positions, 1, 1) { "MoveRightAndModifySelection", "" }, // "move-cursor" (words, -1, 0) { "MoveWordBackward", "" }, // "move-cursor" (words, 1, 0) { "MoveWordForward", "" }, // "move-cursor" (display-lines, -1, 0) { "MoveUp", "" }, // "move-cursor" (display-lines, 1, 0) { "MoveDown", "" }, // "move-cursor" (display-line-ends, -1, 0) { "MoveToBeginningOfLine", "" }, // "move-cursor" (display-line-ends, 1, 0) { "MoveToEndOfLine", "" }, // "move-cursor" (paragraph-ends, -1, 0) { "MoveToBeginningOfParagraph", "" }, // "move-cursor" (paragraph-ends, 1, 0) { "MoveToEndOfParagraph", "" }, // "move-cursor" (pages, -1, 0) { "MovePageUp", "" }, // "move-cursor" (pages, 1, 0) { "MovePageDown", "" }, // "move-cursor" (buffer-ends, -1, 0) { "MoveToBeginningOfDocument", "" }, // "move-cursor" (buffer-ends, 1, 0) { "MoveToEndOfDocument", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_1, GDK_CONTROL_MASK), kEditCommands, arraysize(kEditCommands)); } TEST_F(GtkKeyBindingsHandlerTest, DeleteFromCursor) { static const EditCommand kEditCommands[] = { // "delete-from-cursor" (chars, -2) { "DeleteBackward", "" }, { "DeleteBackward", "" }, // "delete-from-cursor" (chars, 2) { "DeleteForward", "" }, { "DeleteForward", "" }, // "delete-from-cursor" (word-ends, -1) { "DeleteWordBackward", "" }, // "delete-from-cursor" (word-ends, 1) { "DeleteWordForward", "" }, // "delete-from-cursor" (words, -1) { "MoveWordBackward", "" }, { "DeleteWordForward", "" }, // "delete-from-cursor" (words, 1) { "MoveWordForward", "" }, { "DeleteWordBackward", "" }, // "delete-from-cursor" (display-lines, -1) { "MoveToBeginningOfLine", "" }, { "DeleteToEndOfLine", "" }, // "delete-from-cursor" (display-lines, 1) { "MoveToBeginningOfLine", "" }, { "DeleteToEndOfLine", "" }, // "delete-from-cursor" (display-line-ends, -1) { "DeleteToBeginningOfLine", "" }, // "delete-from-cursor" (display-line-ends, 1) { "DeleteToEndOfLine", "" }, // "delete-from-cursor" (paragraph-ends, -1) { "DeleteToBeginningOfParagraph", "" }, // "delete-from-cursor" (paragraph-ends, 1) { "DeleteToEndOfParagraph", "" }, // "delete-from-cursor" (paragraphs, -1) { "MoveToBeginningOfParagraph", "" }, { "DeleteToEndOfParagraph", "" }, // "delete-from-cursor" (paragraphs, 1) { "MoveToBeginningOfParagraph", "" }, { "DeleteToEndOfParagraph", "" }, }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_2, GDK_CONTROL_MASK), kEditCommands, arraysize(kEditCommands)); } TEST_F(GtkKeyBindingsHandlerTest, OtherActions) { static const EditCommand kBackspace[] = { { "DeleteBackward", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_3, GDK_CONTROL_MASK), kBackspace, arraysize(kBackspace)); static const EditCommand kCopyClipboard[] = { { "Copy", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_4, GDK_CONTROL_MASK), kCopyClipboard, arraysize(kCopyClipboard)); static const EditCommand kCutClipboard[] = { { "Cut", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_5, GDK_CONTROL_MASK), kCutClipboard, arraysize(kCutClipboard)); static const EditCommand kInsertAtCursor[] = { { "InsertText", "hello" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_6, GDK_CONTROL_MASK), kInsertAtCursor, arraysize(kInsertAtCursor)); static const EditCommand kPasteClipboard[] = { { "Paste", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_7, GDK_CONTROL_MASK), kPasteClipboard, arraysize(kPasteClipboard)); static const EditCommand kSelectAll[] = { { "Unselect", "" }, { "SelectAll", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_8, GDK_CONTROL_MASK), kSelectAll, arraysize(kSelectAll)); static const EditCommand kSetAnchor[] = { { "SetMark", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_9, GDK_CONTROL_MASK), kSetAnchor, arraysize(kSetAnchor)); } <commit_msg>Mark the GtkKeyBindingsHandlerTest tests as flaky since they don't work in a chroot.<commit_after>// Copyright (c) 2009 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/renderer_host/gtk_key_bindings_handler.h" #include <gdk/gdkkeysyms.h> #include <string> #include <utility> #include <vector> #include "base/basictypes.h" #include "base/file_util.h" #include "base/path_service.h" #include "base/string_util.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/edit_command.h" #include "chrome/common/native_web_keyboard_event.h" #include "testing/gtest/include/gtest/gtest.h" class GtkKeyBindingsHandlerTest : public testing::Test { protected: struct EditCommand { const char* name; const char* value; }; GtkKeyBindingsHandlerTest() : window_(gtk_window_new(GTK_WINDOW_TOPLEVEL)), handler_(NULL) { FilePath gtkrc; PathService::Get(chrome::DIR_TEST_DATA, &gtkrc); gtkrc = gtkrc.AppendASCII("gtk_key_bindings_test_gtkrc"); gtk_rc_parse(gtkrc.value().c_str()); GtkWidget* fixed = gtk_fixed_new(); handler_ = new GtkKeyBindingsHandler(fixed); gtk_container_add(GTK_CONTAINER(window_), fixed); gtk_widget_show(fixed); gtk_widget_show(window_); } ~GtkKeyBindingsHandlerTest() { gtk_widget_destroy(window_); delete handler_; } NativeWebKeyboardEvent NewNativeWebKeyboardEvent(guint keyval, guint state) { GdkKeymap* keymap = gdk_keymap_get_for_display(gtk_widget_get_display(window_)); GdkKeymapKey *keys = NULL; gint n_keys = 0; if (gdk_keymap_get_entries_for_keyval(keymap, keyval, &keys, &n_keys)) { GdkEventKey event; event.type = GDK_KEY_PRESS; event.window = NULL; event.send_event = 0; event.time = 0; event.state = state; event.keyval = keyval; event.length = 0; event.string = NULL; event.hardware_keycode = keys[0].keycode; event.group = keys[0].group; event.is_modifier = 0; g_free(keys); return NativeWebKeyboardEvent(&event); } return NativeWebKeyboardEvent(); } void TestKeyBinding(const NativeWebKeyboardEvent& event, const EditCommand expected_result[], size_t size) { EditCommands result; ASSERT_TRUE(handler_->Match(event, &result)); ASSERT_EQ(size, result.size()); for (size_t i = 0; i < size; ++i) { ASSERT_STREQ(expected_result[i].name, result[i].name.c_str()); ASSERT_STREQ(expected_result[i].value, result[i].value.c_str()); } } protected: GtkWidget* window_; GtkKeyBindingsHandler* handler_; }; // Does not work in a chroot. See bug 60363. TEST_F(GtkKeyBindingsHandlerTest, FLAKY_MoveCursor) { static const EditCommand kEditCommands[] = { // "move-cursor" (logical-positions, -2, 0) { "MoveBackward", "" }, { "MoveBackward", "" }, // "move-cursor" (logical-positions, 2, 0) { "MoveForward", "" }, { "MoveForward", "" }, // "move-cursor" (visual-positions, -1, 1) { "MoveLeftAndModifySelection", "" }, // "move-cursor" (visual-positions, 1, 1) { "MoveRightAndModifySelection", "" }, // "move-cursor" (words, -1, 0) { "MoveWordBackward", "" }, // "move-cursor" (words, 1, 0) { "MoveWordForward", "" }, // "move-cursor" (display-lines, -1, 0) { "MoveUp", "" }, // "move-cursor" (display-lines, 1, 0) { "MoveDown", "" }, // "move-cursor" (display-line-ends, -1, 0) { "MoveToBeginningOfLine", "" }, // "move-cursor" (display-line-ends, 1, 0) { "MoveToEndOfLine", "" }, // "move-cursor" (paragraph-ends, -1, 0) { "MoveToBeginningOfParagraph", "" }, // "move-cursor" (paragraph-ends, 1, 0) { "MoveToEndOfParagraph", "" }, // "move-cursor" (pages, -1, 0) { "MovePageUp", "" }, // "move-cursor" (pages, 1, 0) { "MovePageDown", "" }, // "move-cursor" (buffer-ends, -1, 0) { "MoveToBeginningOfDocument", "" }, // "move-cursor" (buffer-ends, 1, 0) { "MoveToEndOfDocument", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_1, GDK_CONTROL_MASK), kEditCommands, arraysize(kEditCommands)); } // Does not work in a chroot. See bug 60363. TEST_F(GtkKeyBindingsHandlerTest, FLAKY_DeleteFromCursor) { static const EditCommand kEditCommands[] = { // "delete-from-cursor" (chars, -2) { "DeleteBackward", "" }, { "DeleteBackward", "" }, // "delete-from-cursor" (chars, 2) { "DeleteForward", "" }, { "DeleteForward", "" }, // "delete-from-cursor" (word-ends, -1) { "DeleteWordBackward", "" }, // "delete-from-cursor" (word-ends, 1) { "DeleteWordForward", "" }, // "delete-from-cursor" (words, -1) { "MoveWordBackward", "" }, { "DeleteWordForward", "" }, // "delete-from-cursor" (words, 1) { "MoveWordForward", "" }, { "DeleteWordBackward", "" }, // "delete-from-cursor" (display-lines, -1) { "MoveToBeginningOfLine", "" }, { "DeleteToEndOfLine", "" }, // "delete-from-cursor" (display-lines, 1) { "MoveToBeginningOfLine", "" }, { "DeleteToEndOfLine", "" }, // "delete-from-cursor" (display-line-ends, -1) { "DeleteToBeginningOfLine", "" }, // "delete-from-cursor" (display-line-ends, 1) { "DeleteToEndOfLine", "" }, // "delete-from-cursor" (paragraph-ends, -1) { "DeleteToBeginningOfParagraph", "" }, // "delete-from-cursor" (paragraph-ends, 1) { "DeleteToEndOfParagraph", "" }, // "delete-from-cursor" (paragraphs, -1) { "MoveToBeginningOfParagraph", "" }, { "DeleteToEndOfParagraph", "" }, // "delete-from-cursor" (paragraphs, 1) { "MoveToBeginningOfParagraph", "" }, { "DeleteToEndOfParagraph", "" }, }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_2, GDK_CONTROL_MASK), kEditCommands, arraysize(kEditCommands)); } // Does not work in a chroot. See bug 60363. TEST_F(GtkKeyBindingsHandlerTest, FLAKY_OtherActions) { static const EditCommand kBackspace[] = { { "DeleteBackward", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_3, GDK_CONTROL_MASK), kBackspace, arraysize(kBackspace)); static const EditCommand kCopyClipboard[] = { { "Copy", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_4, GDK_CONTROL_MASK), kCopyClipboard, arraysize(kCopyClipboard)); static const EditCommand kCutClipboard[] = { { "Cut", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_5, GDK_CONTROL_MASK), kCutClipboard, arraysize(kCutClipboard)); static const EditCommand kInsertAtCursor[] = { { "InsertText", "hello" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_6, GDK_CONTROL_MASK), kInsertAtCursor, arraysize(kInsertAtCursor)); static const EditCommand kPasteClipboard[] = { { "Paste", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_7, GDK_CONTROL_MASK), kPasteClipboard, arraysize(kPasteClipboard)); static const EditCommand kSelectAll[] = { { "Unselect", "" }, { "SelectAll", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_8, GDK_CONTROL_MASK), kSelectAll, arraysize(kSelectAll)); static const EditCommand kSetAnchor[] = { { "SetMark", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_9, GDK_CONTROL_MASK), kSetAnchor, arraysize(kSetAnchor)); } <|endoftext|>
<commit_before>// Copyright (c) 2006, Google 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 Google Inc. 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. // minidump_dump.cc: Print the contents of a minidump file in somewhat // readable text. // // Author: Mark Mentovai #include <stdio.h> #include "google_breakpad/processor/minidump.h" #include "processor/logging.h" namespace { using google_breakpad::Minidump; using google_breakpad::MinidumpThreadList; using google_breakpad::MinidumpModuleList; using google_breakpad::MinidumpMemoryList; using google_breakpad::MinidumpException; using google_breakpad::MinidumpAssertion; using google_breakpad::MinidumpSystemInfo; using google_breakpad::MinidumpMiscInfo; using google_breakpad::MinidumpBreakpadInfo; static bool PrintMinidumpDump(const char *minidump_file) { Minidump minidump(minidump_file); if (!minidump.Read()) { BPLOG(ERROR) << "minidump.Read() failed"; return false; } minidump.Print(); int errors = 0; MinidumpThreadList *thread_list = minidump.GetThreadList(); if (!thread_list) { ++errors; BPLOG(ERROR) << "minidump.GetThreadList() failed"; } else { thread_list->Print(); } MinidumpModuleList *module_list = minidump.GetModuleList(); if (!module_list) { ++errors; BPLOG(ERROR) << "minidump.GetModuleList() failed"; } else { module_list->Print(); } MinidumpMemoryList *memory_list = minidump.GetMemoryList(); if (!memory_list) { ++errors; BPLOG(ERROR) << "minidump.GetMemoryList() failed"; } else { memory_list->Print(); } MinidumpException *exception = minidump.GetException(); if (!exception) { BPLOG(INFO) << "minidump.GetException() failed"; } else { exception->Print(); } MinidumpAssertion *assertion = minidump.GetAssertion(); if (!assertion) { BPLOG(INFO) << "minidump.GetAssertion() failed"; } else { assertion->Print(); } MinidumpSystemInfo *system_info = minidump.GetSystemInfo(); if (!system_info) { ++errors; BPLOG(ERROR) << "minidump.GetSystemInfo() failed"; } else { system_info->Print(); } MinidumpMiscInfo *misc_info = minidump.GetMiscInfo(); if (!misc_info) { ++errors; BPLOG(ERROR) << "minidump.GetMiscInfo() failed"; } else { misc_info->Print(); } MinidumpBreakpadInfo *breakpad_info = minidump.GetBreakpadInfo(); if (!breakpad_info) { // Breakpad info is optional, so don't treat this as an error. BPLOG(INFO) << "minidump.GetBreakpadInfo() failed"; } else { breakpad_info->Print(); } return errors == 0; } } // namespace int main(int argc, char **argv) { BPLOG_INIT(&argc, &argv); if (argc != 2) { fprintf(stderr, "usage: %s <file>\n", argv[0]); return 1; } return PrintMinidumpDump(argv[1]) ? 0 : 1; } <commit_msg>Enable dumping of the Linux extension streams.<commit_after>// Copyright (c) 2006, Google 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 Google Inc. 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. // minidump_dump.cc: Print the contents of a minidump file in somewhat // readable text. // // Author: Mark Mentovai #include <stdio.h> #include <string.h> #include "client/linux/minidump_writer/minidump_extension_linux.h" #include "google_breakpad/processor/minidump.h" #include "processor/logging.h" #include "processor/scoped_ptr.h" namespace { using google_breakpad::Minidump; using google_breakpad::MinidumpThreadList; using google_breakpad::MinidumpModuleList; using google_breakpad::MinidumpMemoryList; using google_breakpad::MinidumpException; using google_breakpad::MinidumpAssertion; using google_breakpad::MinidumpSystemInfo; using google_breakpad::MinidumpMiscInfo; using google_breakpad::MinidumpBreakpadInfo; static void DumpRawStream(Minidump *minidump, u_int32_t stream_type, const char *stream_name, int *errors) { u_int32_t length = 0; if (!minidump->SeekToStreamType(stream_type, &length)) { return; } printf("Stream %s:\n", stream_name); if (length == 0) { printf("\n"); return; } std::vector<char> contents(length); if (!minidump->ReadBytes(&contents[0], length)) { ++*errors; BPLOG(ERROR) << "minidump.ReadBytes failed"; return; } size_t current_offset = 0; while (current_offset < length) { size_t remaining = length - current_offset; printf("%.*s", remaining, &contents[current_offset]); char *next_null = reinterpret_cast<char *>( memchr(&contents[current_offset], 0, remaining)); if (next_null == NULL) break; printf("\\0\n"); size_t null_offset = next_null - &contents[0]; current_offset = null_offset + 1; } printf("\n\n"); } static bool PrintMinidumpDump(const char *minidump_file) { Minidump minidump(minidump_file); if (!minidump.Read()) { BPLOG(ERROR) << "minidump.Read() failed"; return false; } minidump.Print(); int errors = 0; MinidumpThreadList *thread_list = minidump.GetThreadList(); if (!thread_list) { ++errors; BPLOG(ERROR) << "minidump.GetThreadList() failed"; } else { thread_list->Print(); } MinidumpModuleList *module_list = minidump.GetModuleList(); if (!module_list) { ++errors; BPLOG(ERROR) << "minidump.GetModuleList() failed"; } else { module_list->Print(); } MinidumpMemoryList *memory_list = minidump.GetMemoryList(); if (!memory_list) { ++errors; BPLOG(ERROR) << "minidump.GetMemoryList() failed"; } else { memory_list->Print(); } MinidumpException *exception = minidump.GetException(); if (!exception) { BPLOG(INFO) << "minidump.GetException() failed"; } else { exception->Print(); } MinidumpAssertion *assertion = minidump.GetAssertion(); if (!assertion) { BPLOG(INFO) << "minidump.GetAssertion() failed"; } else { assertion->Print(); } MinidumpSystemInfo *system_info = minidump.GetSystemInfo(); if (!system_info) { ++errors; BPLOG(ERROR) << "minidump.GetSystemInfo() failed"; } else { system_info->Print(); } MinidumpMiscInfo *misc_info = minidump.GetMiscInfo(); if (!misc_info) { ++errors; BPLOG(ERROR) << "minidump.GetMiscInfo() failed"; } else { misc_info->Print(); } MinidumpBreakpadInfo *breakpad_info = minidump.GetBreakpadInfo(); if (!breakpad_info) { // Breakpad info is optional, so don't treat this as an error. BPLOG(INFO) << "minidump.GetBreakpadInfo() failed"; } else { breakpad_info->Print(); } DumpRawStream(&minidump, MD_LINUX_CMD_LINE, "MD_LINUX_CMD_LINE", &errors); DumpRawStream(&minidump, MD_LINUX_ENVIRON, "MD_LINUX_ENVIRON", &errors); DumpRawStream(&minidump, MD_LINUX_LSB_RELEASE, "MD_LINUX_LSB_RELEASE", &errors); DumpRawStream(&minidump, MD_LINUX_PROC_STATUS, "MD_LINUX_PROC_STATUS", &errors); DumpRawStream(&minidump, MD_LINUX_CPU_INFO, "MD_LINUX_CPU_INFO", &errors); return errors == 0; } } // namespace int main(int argc, char **argv) { BPLOG_INIT(&argc, &argv); if (argc != 2) { fprintf(stderr, "usage: %s <file>\n", argv[0]); return 1; } return PrintMinidumpDump(argv[1]) ? 0 : 1; } <|endoftext|>
<commit_before>#include <annis/join/seed.h> #include <annis/annosearch/annotationsearch.h> using namespace annis; AnnoKeySeedJoin::AnnoKeySeedJoin(const DB &db, std::shared_ptr<Operator> op, std::shared_ptr<Iterator> lhs, size_t lhsIdx, const std::set<AnnotationKey> &rightAnnoKeys) : db(db), op(op), currentMatchValid(false), left(lhs), lhsIdx(lhsIdx), rightAnnoKeys(rightAnnoKeys) { nextLeftMatch(); } bool AnnoKeySeedJoin::next(std::vector<Match>& tuple) { tuple.clear(); bool found = false; if(!op || !left || !currentMatchValid || rightAnnoKeys.empty()) { return false; } if(nextRightAnnotation()) { tuple.reserve(currentLHSMatch.size()+1); tuple.insert(tuple.end(), currentLHSMatch.begin(), currentLHSMatch.end()); tuple.push_back(currentRHSMatch); return true; } do { while(matchesByOperator && matchesByOperator->next(currentRHSMatch)) { if(rightAnnoKeys.size() == 1) { // only check the annotation key, not the value const AnnotationKey& key = *(rightAnnoKeys.begin()); std::pair<bool, Annotation> foundAnno = db.nodeAnnos.getNodeAnnotation(currentRHSMatch.node, key.ns, key.name); if(foundAnno.first && checkReflexitivity(currentLHSMatch[lhsIdx].node, currentLHSMatch[lhsIdx].anno, currentRHSMatch.node, foundAnno.second)) { currentRHSMatch.anno = foundAnno.second; tuple.reserve(currentLHSMatch.size()+1); tuple.insert(tuple.end(), currentLHSMatch.begin(), currentLHSMatch.end()); tuple.push_back(currentRHSMatch); return true; } } else { // use the annotation keys as filter for(const auto& key : rightAnnoKeys) { std::pair<bool, Annotation> foundAnno = db.nodeAnnos.getNodeAnnotation(currentRHSMatch.node, key.ns, key.name); if(foundAnno.first) { matchingRightAnnos.push_back(foundAnno.second); } } if(nextRightAnnotation()) { tuple.reserve(currentLHSMatch.size()+1); tuple.insert(tuple.end(), currentLHSMatch.begin(), currentLHSMatch.end()); tuple.push_back(currentRHSMatch); return true; } } } // end while there are right candidates } while(nextLeftMatch()); // end while left has match return false; } void AnnoKeySeedJoin::reset() { if(left) { left->reset(); } matchesByOperator.reset(nullptr); matchingRightAnnos.clear(); currentMatchValid = false; // start the iterations nextLeftMatch(); } bool AnnoKeySeedJoin::nextLeftMatch() { matchingRightAnnos.clear(); if(op && op->valid() && left && left->next(currentLHSMatch)) { currentMatchValid = true; matchesByOperator = op->retrieveMatches(currentLHSMatch[lhsIdx]); if(matchesByOperator) { return true; } } return false; } bool AnnoKeySeedJoin::nextRightAnnotation() { while(!matchingRightAnnos.empty()) { if(checkReflexitivity(currentLHSMatch[lhsIdx].node, currentLHSMatch[lhsIdx].anno, currentRHSMatch.node, matchingRightAnnos.front())) { currentRHSMatch.anno = matchingRightAnnos.front(); matchingRightAnnos.pop_front(); return true; } } return false; } MaterializedSeedJoin::MaterializedSeedJoin(const DB &db, std::shared_ptr<Operator> op, std::shared_ptr<Iterator> lhs, size_t lhsIdx, const std::unordered_set<Annotation>& rightAnno) : db(db), op(op), currentMatchValid(false), left(lhs), lhsIdx(lhsIdx), right(rightAnno) { nextLeftMatch(); } bool MaterializedSeedJoin::next(std::vector<Match>& tuple) { tuple.clear(); // check some conditions where we can't perform a join if(!op || !left || !currentMatchValid || right.empty()) { return false; } if(nextRightAnnotation()) { tuple.reserve(currentLHSMatch.size()+1); tuple.insert(tuple.end(), currentLHSMatch.begin(), currentLHSMatch.end()); tuple.push_back(currentRHSMatch); return true; } do { while(matchesByOperator && matchesByOperator->next(currentRHSMatch)) { if(right.size() == 1) { // directly get the one node annotation const auto& rightAnno = *(right.begin()); auto foundAnno = db.nodeAnnos.getNodeAnnotation(currentRHSMatch.node, rightAnno.ns, rightAnno.name); if(foundAnno.first && foundAnno.second.val == rightAnno.val && checkReflexitivity(currentLHSMatch[lhsIdx].node, currentLHSMatch[lhsIdx].anno, currentRHSMatch.node, foundAnno.second)) { currentRHSMatch.anno = foundAnno.second; tuple.reserve(currentLHSMatch.size()+1); tuple.insert(tuple.end(), currentLHSMatch.begin(), currentLHSMatch.end()); tuple.push_back(currentRHSMatch); return true; } } else { // check all annotations which of them matches std::list<Annotation> annos = db.nodeAnnos.getNodeAnnotationsByID(currentRHSMatch.node); for(const auto& a : annos) { if(right.find(a) != right.end()) { matchingRightAnnos.push_back(a); } } if(nextRightAnnotation()) { tuple.reserve(currentLHSMatch.size()+1); tuple.insert(tuple.end(), currentLHSMatch.begin(), currentLHSMatch.end()); tuple.push_back(currentRHSMatch); return true; } } } // end while there are right candidates } while(nextLeftMatch()); // end while left has match return false; } void MaterializedSeedJoin::reset() { if(left) { left->reset(); } matchesByOperator.reset(nullptr); matchingRightAnnos.clear(); currentMatchValid = false; // start the iterations nextLeftMatch(); } bool MaterializedSeedJoin::nextLeftMatch() { matchingRightAnnos.clear(); if(op && op->valid() && left && left->next(currentLHSMatch)) { currentMatchValid = true; matchesByOperator = op->retrieveMatches(currentLHSMatch[lhsIdx]); if(matchesByOperator) { return true; } } return false; } bool MaterializedSeedJoin::nextRightAnnotation() { while(matchingRightAnnos.size() > 0) { if(checkReflexitivity(currentLHSMatch[lhsIdx].node, currentLHSMatch[lhsIdx].anno, currentRHSMatch.node, matchingRightAnnos.front())) { currentRHSMatch.anno = matchingRightAnnos.front(); matchingRightAnnos.pop_front(); return true; } } return false; } <commit_msg>don't fetch any tuples in constructor of the seed join(s)<commit_after>#include <annis/join/seed.h> #include <annis/annosearch/annotationsearch.h> using namespace annis; AnnoKeySeedJoin::AnnoKeySeedJoin(const DB &db, std::shared_ptr<Operator> op, std::shared_ptr<Iterator> lhs, size_t lhsIdx, const std::set<AnnotationKey> &rightAnnoKeys) : db(db), op(op), currentMatchValid(false), left(lhs), lhsIdx(lhsIdx), rightAnnoKeys(rightAnnoKeys) { } bool AnnoKeySeedJoin::next(std::vector<Match>& tuple) { tuple.clear(); bool found = false; if(!currentMatchValid) { nextLeftMatch(); } if(!op || !left || !currentMatchValid || rightAnnoKeys.empty()) { return false; } if(nextRightAnnotation()) { tuple.reserve(currentLHSMatch.size()+1); tuple.insert(tuple.end(), currentLHSMatch.begin(), currentLHSMatch.end()); tuple.push_back(currentRHSMatch); return true; } do { while(matchesByOperator && matchesByOperator->next(currentRHSMatch)) { if(rightAnnoKeys.size() == 1) { // only check the annotation key, not the value const AnnotationKey& key = *(rightAnnoKeys.begin()); std::pair<bool, Annotation> foundAnno = db.nodeAnnos.getNodeAnnotation(currentRHSMatch.node, key.ns, key.name); if(foundAnno.first && checkReflexitivity(currentLHSMatch[lhsIdx].node, currentLHSMatch[lhsIdx].anno, currentRHSMatch.node, foundAnno.second)) { currentRHSMatch.anno = foundAnno.second; tuple.reserve(currentLHSMatch.size()+1); tuple.insert(tuple.end(), currentLHSMatch.begin(), currentLHSMatch.end()); tuple.push_back(currentRHSMatch); return true; } } else { // use the annotation keys as filter for(const auto& key : rightAnnoKeys) { std::pair<bool, Annotation> foundAnno = db.nodeAnnos.getNodeAnnotation(currentRHSMatch.node, key.ns, key.name); if(foundAnno.first) { matchingRightAnnos.push_back(foundAnno.second); } } if(nextRightAnnotation()) { tuple.reserve(currentLHSMatch.size()+1); tuple.insert(tuple.end(), currentLHSMatch.begin(), currentLHSMatch.end()); tuple.push_back(currentRHSMatch); return true; } } } // end while there are right candidates } while(nextLeftMatch()); // end while left has match return false; } void AnnoKeySeedJoin::reset() { if(left) { left->reset(); } matchesByOperator.reset(nullptr); matchingRightAnnos.clear(); currentMatchValid = false; // start the iterations nextLeftMatch(); } bool AnnoKeySeedJoin::nextLeftMatch() { matchingRightAnnos.clear(); if(op && op->valid() && left && left->next(currentLHSMatch)) { currentMatchValid = true; matchesByOperator = op->retrieveMatches(currentLHSMatch[lhsIdx]); if(matchesByOperator) { return true; } } return false; } bool AnnoKeySeedJoin::nextRightAnnotation() { while(!matchingRightAnnos.empty()) { if(checkReflexitivity(currentLHSMatch[lhsIdx].node, currentLHSMatch[lhsIdx].anno, currentRHSMatch.node, matchingRightAnnos.front())) { currentRHSMatch.anno = matchingRightAnnos.front(); matchingRightAnnos.pop_front(); return true; } } return false; } MaterializedSeedJoin::MaterializedSeedJoin(const DB &db, std::shared_ptr<Operator> op, std::shared_ptr<Iterator> lhs, size_t lhsIdx, const std::unordered_set<Annotation>& rightAnno) : db(db), op(op), currentMatchValid(false), left(lhs), lhsIdx(lhsIdx), right(rightAnno) { } bool MaterializedSeedJoin::next(std::vector<Match>& tuple) { tuple.clear(); if(!currentMatchValid) { nextLeftMatch(); } // check some conditions where we can't perform a join if(!op || !left || !currentMatchValid || right.empty()) { return false; } if(nextRightAnnotation()) { tuple.reserve(currentLHSMatch.size()+1); tuple.insert(tuple.end(), currentLHSMatch.begin(), currentLHSMatch.end()); tuple.push_back(currentRHSMatch); return true; } do { while(matchesByOperator && matchesByOperator->next(currentRHSMatch)) { if(right.size() == 1) { // directly get the one node annotation const auto& rightAnno = *(right.begin()); auto foundAnno = db.nodeAnnos.getNodeAnnotation(currentRHSMatch.node, rightAnno.ns, rightAnno.name); if(foundAnno.first && foundAnno.second.val == rightAnno.val && checkReflexitivity(currentLHSMatch[lhsIdx].node, currentLHSMatch[lhsIdx].anno, currentRHSMatch.node, foundAnno.second)) { currentRHSMatch.anno = foundAnno.second; tuple.reserve(currentLHSMatch.size()+1); tuple.insert(tuple.end(), currentLHSMatch.begin(), currentLHSMatch.end()); tuple.push_back(currentRHSMatch); return true; } } else { // check all annotations which of them matches std::list<Annotation> annos = db.nodeAnnos.getNodeAnnotationsByID(currentRHSMatch.node); for(const auto& a : annos) { if(right.find(a) != right.end()) { matchingRightAnnos.push_back(a); } } if(nextRightAnnotation()) { tuple.reserve(currentLHSMatch.size()+1); tuple.insert(tuple.end(), currentLHSMatch.begin(), currentLHSMatch.end()); tuple.push_back(currentRHSMatch); return true; } } } // end while there are right candidates } while(nextLeftMatch()); // end while left has match return false; } void MaterializedSeedJoin::reset() { if(left) { left->reset(); } matchesByOperator.reset(nullptr); matchingRightAnnos.clear(); currentMatchValid = false; // start the iterations nextLeftMatch(); } bool MaterializedSeedJoin::nextLeftMatch() { matchingRightAnnos.clear(); if(op && op->valid() && left && left->next(currentLHSMatch)) { currentMatchValid = true; matchesByOperator = op->retrieveMatches(currentLHSMatch[lhsIdx]); if(matchesByOperator) { return true; } } return false; } bool MaterializedSeedJoin::nextRightAnnotation() { while(matchingRightAnnos.size() > 0) { if(checkReflexitivity(currentLHSMatch[lhsIdx].node, currentLHSMatch[lhsIdx].anno, currentRHSMatch.node, matchingRightAnnos.front())) { currentRHSMatch.anno = matchingRightAnnos.front(); matchingRightAnnos.pop_front(); return true; } } return false; } <|endoftext|>
<commit_before>#include "Geometry.h" #include <cstdio> #include <fstream> #include <stdexcept> #include "spruce.hh" using std::string; using std::istringstream; using std::ifstream; using Eigen::Vector3i; using Eigen::Vector3d; using Eigen::RowVectorXd; using Eigen::Matrix3Xd; using Eigen::Matrix3Xi; namespace DrakeShapes { const int Geometry::NUM_BBOX_POINTS = 8; const int Sphere::NUM_POINTS = 1; const int Capsule::NUM_POINTS = 2; std::string ShapeToString(Shape ss) { switch (ss) { case UNKNOWN: return "UNKNOWN"; case BOX: return "BOX"; case SPHERE: return "SPHERE"; case CYLINDER: return "CYLINDER"; case MESH: return "MESH"; case MESH_POINTS: return "MESH_POINTS"; case CAPSULE: return "CAPSULE"; } return "UNDEFINED"; } Geometry::Geometry() : shape(UNKNOWN) {} Geometry::Geometry(const Geometry &other) { shape = other.getShape(); } Geometry::Geometry(Shape shape) : shape(shape) {} Shape Geometry::getShape() const { return shape; } Geometry *Geometry::clone() const { return new Geometry(*this); } void Geometry::getPoints(Matrix3Xd &points) const { points = Matrix3Xd(); } void Geometry::getBoundingBoxPoints(Matrix3Xd &points) const { points = Matrix3Xd(); } void Geometry::getBoundingBoxPoints(double x_half_width, double y_half_width, double z_half_width, Eigen::Matrix3Xd &points) const { // Return axis-aligned bounding-box vertices points.resize(3, NUM_BBOX_POINTS); RowVectorXd cx(NUM_BBOX_POINTS), cy(NUM_BBOX_POINTS), cz(NUM_BBOX_POINTS); cx << -1, 1, 1, -1, -1, 1, 1, -1; cy << 1, 1, 1, 1, -1, -1, -1, -1; cz << 1, 1, -1, -1, -1, -1, 1, 1; cx = cx * x_half_width; cy = cy * y_half_width; cz = cz * z_half_width; points << cx, cy, cz; } std::ostream &operator<<(std::ostream &out, const Geometry &gg) { out << ShapeToString(gg.getShape()) << ", " << gg.NUM_BBOX_POINTS; return out; } Sphere::Sphere(double radius) : Geometry(SPHERE), radius(radius) {} Sphere *Sphere::clone() const { return new Sphere(*this); } void Sphere::getPoints(Matrix3Xd &points) const { points = Matrix3Xd::Zero(3, NUM_POINTS); } void Sphere::getBoundingBoxPoints(Matrix3Xd &points) const { Geometry::getBoundingBoxPoints(radius, radius, radius, points); } void Sphere::getTerrainContactPoints(Matrix3Xd &points) const { if (radius < 1e-6) getPoints(points); else points = Matrix3Xd(); } std::ostream &operator<<(std::ostream &out, const Sphere &ss) { out << static_cast<const Geometry &>(ss) << ", " << ss.radius << ", " << ss.NUM_POINTS; return out; } Box::Box(const Eigen::Vector3d &size) : Geometry(BOX), size(size) {} Box *Box::clone() const { return new Box(*this); } void Box::getPoints(Matrix3Xd &points) const { Geometry::getBoundingBoxPoints(size(0) / 2.0, size(1) / 2.0, size(2) / 2.0, points); } void Box::getBoundingBoxPoints(Matrix3Xd &points) const { getPoints(points); } void Box::getTerrainContactPoints(Matrix3Xd &points) const { getPoints(points); } std::ostream &operator<<(std::ostream &out, const Box &bb) { out << static_cast<const Geometry &>(bb) << ", " << bb.size.transpose(); return out; } Cylinder::Cylinder(double radius, double length) : Geometry(CYLINDER), radius(radius), length(length) {} Cylinder *Cylinder::clone() const { return new Cylinder(*this); } void Cylinder::getPoints(Matrix3Xd &points) const { static bool warnOnce = true; if (warnOnce) { std::cerr << "Warning: DrakeShapes::Cylinder::getPoints(): " "This method returns the vertices of the cylinder''s bounding-box." << std::endl; warnOnce = false; } getBoundingBoxPoints(points); } void Cylinder::getBoundingBoxPoints(Matrix3Xd &points) const { Geometry::getBoundingBoxPoints(radius, radius, length / 2.0, points); } std::ostream &operator<<(std::ostream &out, const Cylinder &cc) { out << static_cast<const Geometry &>(cc) << ", " << cc.radius << ", " << cc.length; return out; } Capsule::Capsule(double radius, double length) : Geometry(CAPSULE), radius(radius), length(length) {} Capsule *Capsule::clone() const { return new Capsule(*this); } void Capsule::getPoints(Matrix3Xd &points) const { // Return segment end-points points.resize(Eigen::NoChange, NUM_POINTS); RowVectorXd cx = RowVectorXd::Zero(NUM_POINTS); RowVectorXd cy = RowVectorXd::Zero(NUM_POINTS); RowVectorXd cz = RowVectorXd::Zero(NUM_POINTS); cz << length / 2.0, -length / 2.0; points << cx, cy, cz; } void Capsule::getBoundingBoxPoints(Matrix3Xd &points) const { Geometry::getBoundingBoxPoints(radius, radius, (length / 2.0 + radius), points); } std::ostream &operator<<(std::ostream &out, const Capsule &cc) { out << static_cast<const Geometry &>(cc) << ", " << cc.radius << ", " << cc.length; return out; } Mesh::Mesh(const string &filename) : Geometry(MESH), scale(1.0, 1.0, 1.0), filename(filename) {} Mesh::Mesh(const string &filename, const string &resolved_filename) : Geometry(MESH), scale(1.0, 1.0, 1.0), filename(filename), resolved_filename(resolved_filename) {} bool Mesh::extractMeshVertices(Matrix3Xd& vertex_coordinates) const { if (resolved_filename.empty()) return false; string obj_file_name = FindFileWithObjExtension(); ifstream file(obj_file_name); if (!file) { throw std::runtime_error( "Error opening file \"" + obj_file_name + "\"."); } string line; // Count the number of vertices and resize vertex_coordinates. int num_vertices = 0; while (getline(file, line)) { istringstream iss(line); string type; if (iss >> type && type == "v") { ++num_vertices; } } vertex_coordinates.resize(3, num_vertices); file.clear(); file.seekg(0, file.beg); double d; int j = 0; while (getline(file, line)) { istringstream iss(line); string type; if (iss >> type && type == "v") { int i = 0; while (iss >> d) { vertex_coordinates(i++, j) = d; } ++j; } } return true; } string Mesh::FindFileWithObjExtension() const { spruce::path spath(resolved_filename); string ext = spath.extension(); std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); if (ext.compare(".obj") == 0) { // Checks if the file with the obj extension exists. if (!spath.exists()) { throw std::runtime_error( "Unable to open file \"" + spath.getStr() + "\"."); } } else { // Tries changing the extension to obj. spath.setExtension(".obj"); if (!spath.exists()) { throw std::runtime_error( "Unable to resolve an obj file from the filename \"" + spath.getStr() + "\" provided."); } } return spath.getStr(); } void Mesh::LoadObjFile(PointsVector* vertices, TrianglesVector* triangles) const { string obj_file_name = FindFileWithObjExtension(); ifstream file(obj_file_name); if (!file) { throw std::runtime_error( "Error opening file \"" + obj_file_name + "\"."); } std::string line; int line_number = 0; while (!file.eof()) { ++line_number; std::getline(file, line); std::stringstream ss(line); std::string key; ss >> key; if (key == "v") { // Reads a 3D vertex. double x, y, z; ss >> x; ss >> y; ss >> z; if (ss.fail()) { throw std::runtime_error( "In file \"" + obj_file_name + "\" " "(L." + std::to_string(line_number) + "). " "Vertex in the wrong format."); } vertices->push_back(Vector3d(x, y, z)); } else if (key == "f") { // Reads the connectivity for a single triangle. std::vector<int> indices; int index; while (ss >> index) { // Ignores line until the next whitespace. // This effectively ignores texture coordinates and normals. // The first entry always corresponds to an index in the face. ss.ignore(line.size(), ' '); if (ss.fail()) { throw std::runtime_error( "In file \"" + obj_file_name + "\" " "(L." + std::to_string(line_number) + "). " "Triangle face in the wrong format."); } indices.push_back(index); } if (indices.size() != 3) { throw std::runtime_error( "In file \"" + obj_file_name + "\" " "(L." + std::to_string(line_number) + "). " "Only triangular faces supported. However " + std::to_string(indices.size()) + " indices are provided."); } triangles->push_back(Vector3i(indices[0]-1, indices[1]-1, indices[2]-1)); } } } Mesh *Mesh::clone() const { return new Mesh(*this); } void Mesh::getPoints(Eigen::Matrix3Xd &point_matrix) const { extractMeshVertices(point_matrix); } void Mesh::getBoundingBoxPoints(Matrix3Xd &bbox_points) const { Matrix3Xd mesh_vertices; extractMeshVertices(mesh_vertices); Vector3d min_pos = mesh_vertices.rowwise().minCoeff(); Vector3d max_pos = mesh_vertices.rowwise().maxCoeff(); bbox_points.resize(Eigen::NoChange, NUM_BBOX_POINTS); bbox_points << min_pos(0), min_pos(0), min_pos(0), min_pos(0), max_pos(0), max_pos(0), max_pos(0), max_pos(0), min_pos(1), min_pos(1), max_pos(1), max_pos(1), min_pos(1), min_pos(1), max_pos(1), max_pos(1), min_pos(2), max_pos(2), min_pos(2), max_pos(2), min_pos(2), max_pos(2), min_pos(2), max_pos(2); } std::ostream &operator<<(std::ostream &out, const Mesh &mm) { out << static_cast<const Geometry &>(mm) << ", " << mm.scale << ", " << mm.filename << ", " << mm.resolved_filename << ", " << mm.root_dir; return out; } MeshPoints::MeshPoints(const Eigen::Matrix3Xd &points) : Geometry(MESH_POINTS), points(points) {} MeshPoints *MeshPoints::clone() const { return new MeshPoints(*this); } void MeshPoints::getPoints(Eigen::Matrix3Xd &point_matrix) const { point_matrix = points; } void MeshPoints::getBoundingBoxPoints(Matrix3Xd &bbox_points) const { Vector3d min_pos = points.rowwise().minCoeff(); Vector3d max_pos = points.rowwise().maxCoeff(); bbox_points.resize(Eigen::NoChange, NUM_BBOX_POINTS); bbox_points << min_pos(0), min_pos(0), min_pos(0), min_pos(0), max_pos(0), max_pos(0), max_pos(0), max_pos(0), min_pos(1), min_pos(1), max_pos(1), max_pos(1), min_pos(1), min_pos(1), max_pos(1), max_pos(1), min_pos(2), max_pos(2), min_pos(2), max_pos(2), min_pos(2), max_pos(2), min_pos(2), max_pos(2); } std::ostream &operator<<(std::ostream &out, const MeshPoints &mp) { out << static_cast<const Geometry &>(mp) << ",\n" << mp.points; return out; } } // namespace DrakeShapes <commit_msg>std::ostream --> ostream<commit_after>#include "Geometry.h" #include <cstdio> #include <fstream> #include <stdexcept> #include "spruce.hh" using std::string; using std::ostream; using std::istringstream; using std::ifstream; using Eigen::Vector3i; using Eigen::Vector3d; using Eigen::RowVectorXd; using Eigen::Matrix3Xd; using Eigen::Matrix3Xi; namespace DrakeShapes { const int Geometry::NUM_BBOX_POINTS = 8; const int Sphere::NUM_POINTS = 1; const int Capsule::NUM_POINTS = 2; string ShapeToString(Shape ss) { switch (ss) { case UNKNOWN: return "UNKNOWN"; case BOX: return "BOX"; case SPHERE: return "SPHERE"; case CYLINDER: return "CYLINDER"; case MESH: return "MESH"; case MESH_POINTS: return "MESH_POINTS"; case CAPSULE: return "CAPSULE"; } return "UNDEFINED"; } Geometry::Geometry() : shape(UNKNOWN) {} Geometry::Geometry(const Geometry &other) { shape = other.getShape(); } Geometry::Geometry(Shape shape) : shape(shape) {} Shape Geometry::getShape() const { return shape; } Geometry *Geometry::clone() const { return new Geometry(*this); } void Geometry::getPoints(Matrix3Xd &points) const { points = Matrix3Xd(); } void Geometry::getBoundingBoxPoints(Matrix3Xd &points) const { points = Matrix3Xd(); } void Geometry::getBoundingBoxPoints(double x_half_width, double y_half_width, double z_half_width, Eigen::Matrix3Xd &points) const { // Return axis-aligned bounding-box vertices points.resize(3, NUM_BBOX_POINTS); RowVectorXd cx(NUM_BBOX_POINTS), cy(NUM_BBOX_POINTS), cz(NUM_BBOX_POINTS); cx << -1, 1, 1, -1, -1, 1, 1, -1; cy << 1, 1, 1, 1, -1, -1, -1, -1; cz << 1, 1, -1, -1, -1, -1, 1, 1; cx = cx * x_half_width; cy = cy * y_half_width; cz = cz * z_half_width; points << cx, cy, cz; } ostream &operator<<(ostream &out, const Geometry &gg) { out << ShapeToString(gg.getShape()) << ", " << gg.NUM_BBOX_POINTS; return out; } Sphere::Sphere(double radius) : Geometry(SPHERE), radius(radius) {} Sphere *Sphere::clone() const { return new Sphere(*this); } void Sphere::getPoints(Matrix3Xd &points) const { points = Matrix3Xd::Zero(3, NUM_POINTS); } void Sphere::getBoundingBoxPoints(Matrix3Xd &points) const { Geometry::getBoundingBoxPoints(radius, radius, radius, points); } void Sphere::getTerrainContactPoints(Matrix3Xd &points) const { if (radius < 1e-6) getPoints(points); else points = Matrix3Xd(); } ostream &operator<<(ostream &out, const Sphere &ss) { out << static_cast<const Geometry &>(ss) << ", " << ss.radius << ", " << ss.NUM_POINTS; return out; } Box::Box(const Eigen::Vector3d &size) : Geometry(BOX), size(size) {} Box *Box::clone() const { return new Box(*this); } void Box::getPoints(Matrix3Xd &points) const { Geometry::getBoundingBoxPoints(size(0) / 2.0, size(1) / 2.0, size(2) / 2.0, points); } void Box::getBoundingBoxPoints(Matrix3Xd &points) const { getPoints(points); } void Box::getTerrainContactPoints(Matrix3Xd &points) const { getPoints(points); } ostream &operator<<(ostream &out, const Box &bb) { out << static_cast<const Geometry &>(bb) << ", " << bb.size.transpose(); return out; } Cylinder::Cylinder(double radius, double length) : Geometry(CYLINDER), radius(radius), length(length) {} Cylinder *Cylinder::clone() const { return new Cylinder(*this); } void Cylinder::getPoints(Matrix3Xd &points) const { static bool warnOnce = true; if (warnOnce) { std::cerr << "Warning: DrakeShapes::Cylinder::getPoints(): " "This method returns the vertices of the cylinder''s bounding-box." << std::endl; warnOnce = false; } getBoundingBoxPoints(points); } void Cylinder::getBoundingBoxPoints(Matrix3Xd &points) const { Geometry::getBoundingBoxPoints(radius, radius, length / 2.0, points); } ostream &operator<<(ostream &out, const Cylinder &cc) { out << static_cast<const Geometry &>(cc) << ", " << cc.radius << ", " << cc.length; return out; } Capsule::Capsule(double radius, double length) : Geometry(CAPSULE), radius(radius), length(length) {} Capsule *Capsule::clone() const { return new Capsule(*this); } void Capsule::getPoints(Matrix3Xd &points) const { // Return segment end-points points.resize(Eigen::NoChange, NUM_POINTS); RowVectorXd cx = RowVectorXd::Zero(NUM_POINTS); RowVectorXd cy = RowVectorXd::Zero(NUM_POINTS); RowVectorXd cz = RowVectorXd::Zero(NUM_POINTS); cz << length / 2.0, -length / 2.0; points << cx, cy, cz; } void Capsule::getBoundingBoxPoints(Matrix3Xd &points) const { Geometry::getBoundingBoxPoints(radius, radius, (length / 2.0 + radius), points); } ostream &operator<<(ostream &out, const Capsule &cc) { out << static_cast<const Geometry &>(cc) << ", " << cc.radius << ", " << cc.length; return out; } Mesh::Mesh(const string &filename) : Geometry(MESH), scale(1.0, 1.0, 1.0), filename(filename) {} Mesh::Mesh(const string &filename, const string &resolved_filename) : Geometry(MESH), scale(1.0, 1.0, 1.0), filename(filename), resolved_filename(resolved_filename) {} bool Mesh::extractMeshVertices(Matrix3Xd& vertex_coordinates) const { if (resolved_filename.empty()) return false; string obj_file_name = FindFileWithObjExtension(); ifstream file(obj_file_name); if (!file) { throw std::runtime_error( "Error opening file \"" + obj_file_name + "\"."); } string line; // Count the number of vertices and resize vertex_coordinates. int num_vertices = 0; while (getline(file, line)) { istringstream iss(line); string type; if (iss >> type && type == "v") { ++num_vertices; } } vertex_coordinates.resize(3, num_vertices); file.clear(); file.seekg(0, file.beg); double d; int j = 0; while (getline(file, line)) { istringstream iss(line); string type; if (iss >> type && type == "v") { int i = 0; while (iss >> d) { vertex_coordinates(i++, j) = d; } ++j; } } return true; } string Mesh::FindFileWithObjExtension() const { spruce::path spath(resolved_filename); string ext = spath.extension(); std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); if (ext.compare(".obj") == 0) { // Checks if the file with the obj extension exists. if (!spath.exists()) { throw std::runtime_error( "Unable to open file \"" + spath.getStr() + "\"."); } } else { // Tries changing the extension to obj. spath.setExtension(".obj"); if (!spath.exists()) { throw std::runtime_error( "Unable to resolve an obj file from the filename \"" + spath.getStr() + "\" provided."); } } return spath.getStr(); } void Mesh::LoadObjFile(PointsVector* vertices, TrianglesVector* triangles) const { string obj_file_name = FindFileWithObjExtension(); ifstream file(obj_file_name); if (!file) { throw std::runtime_error( "Error opening file \"" + obj_file_name + "\"."); } std::string line; int line_number = 0; while (!file.eof()) { ++line_number; std::getline(file, line); std::stringstream ss(line); std::string key; ss >> key; if (key == "v") { // Reads a 3D vertex. double x, y, z; ss >> x; ss >> y; ss >> z; if (ss.fail()) { throw std::runtime_error( "In file \"" + obj_file_name + "\" " "(L." + std::to_string(line_number) + "). " "Vertex in the wrong format."); } vertices->push_back(Vector3d(x, y, z)); } else if (key == "f") { // Reads the connectivity for a single triangle. std::vector<int> indices; int index; while (ss >> index) { // Ignores line until the next whitespace. // This effectively ignores texture coordinates and normals. // The first entry always corresponds to an index in the face. ss.ignore(line.size(), ' '); if (ss.fail()) { throw std::runtime_error( "In file \"" + obj_file_name + "\" " "(L." + std::to_string(line_number) + "). " "Triangle face in the wrong format."); } indices.push_back(index); } if (indices.size() != 3) { throw std::runtime_error( "In file \"" + obj_file_name + "\" " "(L." + std::to_string(line_number) + "). " "Only triangular faces supported. However " + std::to_string(indices.size()) + " indices are provided."); } triangles->push_back(Vector3i(indices[0]-1, indices[1]-1, indices[2]-1)); } } } Mesh *Mesh::clone() const { return new Mesh(*this); } void Mesh::getPoints(Eigen::Matrix3Xd &point_matrix) const { extractMeshVertices(point_matrix); } void Mesh::getBoundingBoxPoints(Matrix3Xd &bbox_points) const { Matrix3Xd mesh_vertices; extractMeshVertices(mesh_vertices); Vector3d min_pos = mesh_vertices.rowwise().minCoeff(); Vector3d max_pos = mesh_vertices.rowwise().maxCoeff(); bbox_points.resize(Eigen::NoChange, NUM_BBOX_POINTS); bbox_points << min_pos(0), min_pos(0), min_pos(0), min_pos(0), max_pos(0), max_pos(0), max_pos(0), max_pos(0), min_pos(1), min_pos(1), max_pos(1), max_pos(1), min_pos(1), min_pos(1), max_pos(1), max_pos(1), min_pos(2), max_pos(2), min_pos(2), max_pos(2), min_pos(2), max_pos(2), min_pos(2), max_pos(2); } ostream &operator<<(ostream &out, const Mesh &mm) { out << static_cast<const Geometry &>(mm) << ", " << mm.scale << ", " << mm.filename << ", " << mm.resolved_filename << ", " << mm.root_dir; return out; } MeshPoints::MeshPoints(const Eigen::Matrix3Xd &points) : Geometry(MESH_POINTS), points(points) {} MeshPoints *MeshPoints::clone() const { return new MeshPoints(*this); } void MeshPoints::getPoints(Eigen::Matrix3Xd &point_matrix) const { point_matrix = points; } void MeshPoints::getBoundingBoxPoints(Matrix3Xd &bbox_points) const { Vector3d min_pos = points.rowwise().minCoeff(); Vector3d max_pos = points.rowwise().maxCoeff(); bbox_points.resize(Eigen::NoChange, NUM_BBOX_POINTS); bbox_points << min_pos(0), min_pos(0), min_pos(0), min_pos(0), max_pos(0), max_pos(0), max_pos(0), max_pos(0), min_pos(1), min_pos(1), max_pos(1), max_pos(1), min_pos(1), min_pos(1), max_pos(1), max_pos(1), min_pos(2), max_pos(2), min_pos(2), max_pos(2), min_pos(2), max_pos(2), min_pos(2), max_pos(2); } ostream &operator<<(ostream &out, const MeshPoints &mp) { out << static_cast<const Geometry &>(mp) << ",\n" << mp.points; return out; } } // namespace DrakeShapes <|endoftext|>
<commit_before>//============================================================================ // vSMC/example/pf/include/pf_mpi_do.hpp //---------------------------------------------------------------------------- // vSMC: Scalable Monte Carlo //---------------------------------------------------------------------------- // Copyright (c) 2013,2014, Yan Zhou // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. //============================================================================ #ifndef VSMC_EXAMPLE_PF_MPI_DO_HPP #define VSMC_EXAMPLE_PF_MPI_DO_HPP template <vsmc::MatrixOrder Order> inline void cv_do (vsmc::ResampleScheme res, char **argv, const std::string &name) { vsmc::Seed::instance().set(101); std::size_t N = (ParticleNum / 3) * static_cast<std::size_t>(boost::mpi::communicator().rank() + 1); vsmc::Sampler<cv_state<Order> > sampler(N, res, 0.5); sampler .init(cv_init<Order>()) .move(vsmc::MoveAdapter< cv_state<Order>, BASE_MOVE, cv_move<Order> >(), true) .monitor("pos", 2, vsmc::MonitorEvalAdapter< cv_state<Order>, BASE_MONITOR>(cv_est<Order>)); sampler.monitor("pos").name(0) = "pos.x"; sampler.monitor("pos").name(1) = "pos.y"; std::stringstream ss; ss << name << ".r" << sampler.particle().value().world().rank(); std::string rname(ss.str()); #if VSMC_HAS_HDF5 sampler.initialize(argv[1]); vsmc::hdf5store(sampler.particle().value(), argv[2] + rname + ".trace.h5", "Trace.0"); for (std::size_t i = 0; i != DataNum - 1; ++i) { std::stringstream tss; tss << "Trace." << (i + 1); sampler.iterate(); vsmc::hdf5store(sampler.particle().value(), argv[2] + rname + ".trace.h5", tss.str(), true); } #else sampler.initialize(argv[1]); sampler.iterate(DataNum - 1); #endif std::string est_file_name(argv[2] + rname + ".tsv"); std::ofstream est_file; est_file.open(est_file_name.c_str()); est_file << sampler << std::endl; est_file.close(); est_file_name = argv[2] + rname + ".trace.tsv"; est_file.open(est_file_name.c_str()); est_file << sampler.particle().value() << std::endl; est_file.close(); const std::vector<std::size_t> &send_num = sampler.particle().value().copy_send_num(); std::string send_file_name(argv[2] + rname + ".send"); std::ofstream send_file; send_file.open(send_file_name.c_str()); for (std::size_t i = 0; i != send_num.size(); ++i) send_file << send_num[i] << '\n'; send_file.close(); #if VSMC_HAS_HDF5 vsmc::hdf5store(sampler, argv[2] + rname + ".h5", "Sampler"); #endif } #endif // VSMC_EXAMPLE_PF_MPI_DO_HPP <commit_msg>remove use of send num<commit_after>//============================================================================ // vSMC/example/pf/include/pf_mpi_do.hpp //---------------------------------------------------------------------------- // vSMC: Scalable Monte Carlo //---------------------------------------------------------------------------- // Copyright (c) 2013,2014, Yan Zhou // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. //============================================================================ #ifndef VSMC_EXAMPLE_PF_MPI_DO_HPP #define VSMC_EXAMPLE_PF_MPI_DO_HPP template <vsmc::MatrixOrder Order> inline void cv_do (vsmc::ResampleScheme res, char **argv, const std::string &name) { vsmc::Seed::instance().set(101); std::size_t N = (ParticleNum / 3) * static_cast<std::size_t>(boost::mpi::communicator().rank() + 1); vsmc::Sampler<cv_state<Order> > sampler(N, res, 0.5); sampler .init(cv_init<Order>()) .move(vsmc::MoveAdapter< cv_state<Order>, BASE_MOVE, cv_move<Order> >(), true) .monitor("pos", 2, vsmc::MonitorEvalAdapter< cv_state<Order>, BASE_MONITOR>(cv_est<Order>)); sampler.monitor("pos").name(0) = "pos.x"; sampler.monitor("pos").name(1) = "pos.y"; std::stringstream ss; ss << name << ".r" << sampler.particle().value().world().rank(); std::string rname(ss.str()); #if VSMC_HAS_HDF5 sampler.initialize(argv[1]); vsmc::hdf5store(sampler.particle().value(), argv[2] + rname + ".trace.h5", "Trace.0"); for (std::size_t i = 0; i != DataNum - 1; ++i) { std::stringstream tss; tss << "Trace." << (i + 1); sampler.iterate(); vsmc::hdf5store(sampler.particle().value(), argv[2] + rname + ".trace.h5", tss.str(), true); } #else sampler.initialize(argv[1]); sampler.iterate(DataNum - 1); #endif std::string est_file_name(argv[2] + rname + ".tsv"); std::ofstream est_file; est_file.open(est_file_name.c_str()); est_file << sampler << std::endl; est_file.close(); est_file_name = argv[2] + rname + ".trace.tsv"; est_file.open(est_file_name.c_str()); est_file << sampler.particle().value() << std::endl; est_file.close(); #if VSMC_HAS_HDF5 vsmc::hdf5store(sampler, argv[2] + rname + ".h5", "Sampler"); #endif } #endif // VSMC_EXAMPLE_PF_MPI_DO_HPP <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ed_ioleobject.cxx,v $ * * $Revision: 1.19 $ * * last change: $Author: obo $ $Date: 2007-01-25 11:36:17 $ * * 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 "embeddoc.hxx" #ifndef _OSL_DIAGNOSE_H_ #include <ols/diagnose.h> #endif #ifndef _COM_SUN_STAR_FRAME_XController_HPP_ #include <com/sun/star/frame/XController.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif using namespace ::com::sun::star; extern ::rtl::OUString getFilterNameFromGUID_Impl( GUID* ); //------------------------------------------------------------------------------- // IOleObject STDMETHODIMP EmbedDocument_Impl::SetClientSite( IOleClientSite* pSite ) { m_pClientSite = pSite; return S_OK; } STDMETHODIMP EmbedDocument_Impl::GetClientSite( IOleClientSite** pSite ) { *pSite = m_pClientSite; return S_OK; } STDMETHODIMP EmbedDocument_Impl::SetHostNames( LPCOLESTR szContainerApp, LPCOLESTR szContainerObj ) { // the code should be ignored for links if ( !m_aFileName.getLength() ) { m_pDocHolder->setTitle( rtl::OUString( (sal_Unicode*)szContainerObj)); m_pDocHolder->setContainerName( rtl::OUString( (sal_Unicode*)szContainerApp)); } return S_OK; } STDMETHODIMP EmbedDocument_Impl::Close( DWORD dwSaveOption ) { if ( dwSaveOption == 2 && m_aFileName.getLength() ) { // ask the user about saving if ( m_pDocHolder->ExecuteSuspendCloseFrame() ) { m_pDocHolder->CloseDocument(); return S_OK; } else return OLE_E_PROMPTSAVECANCELLED; } HRESULT hr = S_OK; if ( dwSaveOption != 1 ) hr = SaveObject(); // ADVF_DATAONSTOP); m_pDocHolder->FreeOffice(); m_pDocHolder->CloseDocument(); m_pDocHolder->CloseFrame(); OLENotifyClosing(); return hr; } HRESULT EmbedDocument_Impl::OLENotifyClosing() { HRESULT hr = S_OK; if ( m_pClientSite ) m_pClientSite->OnShowWindow( FALSE ); AdviseSinkHashMap aAHM(m_aAdviseHashMap); for ( AdviseSinkHashMapIterator iAdvise = aAHM.begin(); iAdvise != aAHM.end(); iAdvise++ ) { if ( iAdvise->second ) iAdvise->second->OnClose(); } return hr; } STDMETHODIMP EmbedDocument_Impl::SetMoniker( DWORD /*dwWhichMoniker*/, IMoniker * /*pmk*/ ) { return E_NOTIMPL; } STDMETHODIMP EmbedDocument_Impl::GetMoniker( DWORD /*dwAssign*/, DWORD /*dwWhichMoniker*/, IMoniker ** /*ppmk*/ ) { return E_NOTIMPL; } STDMETHODIMP EmbedDocument_Impl::InitFromData( IDataObject * /*pDataObject*/, BOOL /*fCreation*/, DWORD /*dwReserved*/ ) { return E_NOTIMPL; } STDMETHODIMP EmbedDocument_Impl::GetClipboardData( DWORD /*dwReserved*/, IDataObject ** /*ppDataObject*/ ) { return E_NOTIMPL; } /** * Well, this is a not so very inefficient way to deliver * */ STDMETHODIMP EmbedDocument_Impl::DoVerb( LONG iVerb, LPMSG, IOleClientSite *pActiveSite, LONG, HWND, LPCRECT ) { // no locking is used since the OLE must use the same thread always if ( m_bIsInVerbHandling ) return OLEOBJ_S_CANNOT_DOVERB_NOW; BooleanGuard_Impl aGuard( m_bIsInVerbHandling ); if ( iVerb == OLEIVERB_PRIMARY ) { if ( m_aFileName.getLength() ) { // that should be a link iVerb = OLEIVERB_OPEN; } else iVerb = OLEIVERB_SHOW; } try { switch(iVerb) { case OLEIVERB_DISCARDUNDOSTATE: // free any undostate? break; case OLEIVERB_INPLACEACTIVATE: OSL_ENSURE(m_pDocHolder,"no document for inplace activation"); return m_pDocHolder->InPlaceActivate(pActiveSite,FALSE); break; case OLEIVERB_UIACTIVATE: OSL_ENSURE(m_pDocHolder,"no document for inplace activation"); return m_pDocHolder->InPlaceActivate(pActiveSite,TRUE); break; case OLEIVERB_PRIMARY: case OLEIVERB_SHOW: OSL_ENSURE(m_pDocHolder,"no document for inplace activation"); if(m_pDocHolder->isActive()) return NOERROR; //Already active if(SUCCEEDED( m_pDocHolder->InPlaceActivate( pActiveSite,TRUE))) return NOERROR; // intended fall trough case OLEIVERB_OPEN: OSL_ENSURE(m_pDocHolder,"no document to open"); // the commented code could be usefull in case // outer window would be resized depending from inner one // RECTL aEmbArea; // m_pDocHolder->GetVisArea( &aEmbArea ); // m_pDocHolder->show(); // m_pDocHolder->SetVisArea( &aEmbArea ); if(m_pDocHolder->isActive()) { m_pDocHolder->InPlaceDeactivate(); m_pDocHolder->DisableInplaceActivation(true); } SIZEL aEmbSize; m_pDocHolder->GetExtent( &aEmbSize ); m_pDocHolder->show(); m_pDocHolder->resizeWin( aEmbSize ); if ( m_pClientSite ) m_pClientSite->OnShowWindow( TRUE ); notify(); break; case OLEIVERB_HIDE: OSL_ENSURE(m_pDocHolder,"no document to hide"); if(m_pDocHolder->isActive()) m_pDocHolder->InPlaceDeactivate(); else { m_pDocHolder->hide(); if( m_pClientSite ) m_pClientSite->OnShowWindow(FALSE); } break; default: break; } } catch( uno::Exception& ) { return OLEOBJ_S_CANNOT_DOVERB_NOW; } return NOERROR; } STDMETHODIMP EmbedDocument_Impl::EnumVerbs( IEnumOLEVERB ** /*ppEnumOleVerb*/ ) { return OLE_S_USEREG; } STDMETHODIMP EmbedDocument_Impl::Update() { return S_OK; } STDMETHODIMP EmbedDocument_Impl::IsUpToDate() { return S_OK; } STDMETHODIMP EmbedDocument_Impl::GetUserClassID( CLSID *pClsid ) { return GetClassID( pClsid ); } STDMETHODIMP EmbedDocument_Impl::GetUserType( DWORD /*dwFormOfTypeUe*/, LPOLESTR * /*pszUserType*/ ) { return OLE_S_USEREG; } STDMETHODIMP EmbedDocument_Impl::SetExtent( DWORD /*dwDrawAspect*/, SIZEL *psizel ) { if ( !psizel ) return E_FAIL; m_pDocHolder->SetExtent( psizel ); return S_OK; } STDMETHODIMP EmbedDocument_Impl::GetExtent( DWORD /*dwDrawAspect*/, SIZEL * psizel ) { if ( !psizel ) return E_INVALIDARG; if ( FAILED( m_pDocHolder->GetExtent( psizel ) ) ) { // return default values psizel->cx = 500; psizel->cy = 500; } return S_OK; } STDMETHODIMP EmbedDocument_Impl::Advise( IAdviseSink *pAdvSink, DWORD *pdwConnection ) { if ( m_nAdviseNum == 0xFFFFFFFF ) return E_OUTOFMEMORY; pAdvSink->AddRef(); m_aAdviseHashMap.insert( ::std::pair< DWORD, IAdviseSink* >( m_nAdviseNum, pAdvSink ) ); *pdwConnection = m_nAdviseNum++; return S_OK; } STDMETHODIMP EmbedDocument_Impl::Unadvise( DWORD dwConnection ) { AdviseSinkHashMapIterator iAdvise = m_aAdviseHashMap.find( dwConnection ); if ( iAdvise != m_aAdviseHashMap.end() ) { iAdvise->second->Release(); m_aAdviseHashMap.erase( iAdvise ); } else return OLE_E_NOCONNECTION; return S_OK; } STDMETHODIMP EmbedDocument_Impl::EnumAdvise( IEnumSTATDATA ** /*ppenumAdvise*/ ) { return E_NOTIMPL; } STDMETHODIMP EmbedDocument_Impl::GetMiscStatus( DWORD /*dwAspect*/, DWORD * /*pdwStatus*/ ) { return OLE_S_USEREG; } STDMETHODIMP EmbedDocument_Impl::SetColorScheme( LOGPALETTE * /*pLogpal*/ ) { return E_NOTIMPL; } //------------------------------------------------------------------------------- // IDispatch STDMETHODIMP EmbedDocument_Impl::GetTypeInfoCount( unsigned int FAR* pctinfo ) { if ( m_pDocHolder->GetIDispatch() ) return m_pDocHolder->GetIDispatch()->GetTypeInfoCount( pctinfo ); return E_NOTIMPL; } STDMETHODIMP EmbedDocument_Impl::GetTypeInfo( unsigned int iTInfo, LCID lcid, ITypeInfo FAR* FAR* ppTInfo ) { if ( m_pDocHolder->GetIDispatch() ) return m_pDocHolder->GetIDispatch()->GetTypeInfo( iTInfo, lcid, ppTInfo ); return DISP_E_BADINDEX; // the only error that can be returned } STDMETHODIMP EmbedDocument_Impl::GetIDsOfNames( REFIID riid, OLECHAR FAR* FAR* rgszNames, unsigned int cNames, LCID lcid, DISPID FAR* rgDispId ) { if ( m_pDocHolder->GetIDispatch() ) return m_pDocHolder->GetIDispatch()->GetIDsOfNames( riid, rgszNames, cNames, lcid, rgDispId ); for ( unsigned int ind = 0; ind < cNames; ind++ ) rgDispId[ind] = DISPID_UNKNOWN; return DISP_E_UNKNOWNNAME; } STDMETHODIMP EmbedDocument_Impl::Invoke( DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS FAR* pDispParams, VARIANT FAR* pVarResult, EXCEPINFO FAR* pExcepInfo, unsigned int FAR* puArgErr ) { if ( m_pDocHolder->GetIDispatch() ) return m_pDocHolder->GetIDispatch()->Invoke( dispIdMember, riid, lcid, wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr ); return DISP_E_MEMBERNOTFOUND; } // C++ - methods HRESULT EmbedDocument_Impl::SaveObject() { HRESULT hr = S_OK; if(m_pClientSite) { hr = m_pClientSite->SaveObject(); for ( AdviseSinkHashMapIterator iAdvise = m_aAdviseHashMap.begin(); iAdvise != m_aAdviseHashMap.end(); iAdvise++ ) if ( iAdvise->second ) iAdvise->second->OnSave( ); } else if ( m_aFileName.getLength() && IsDirty() == S_OK ) { ::rtl::OUString aPreservFileName = m_aFileName; // in case of links the containers does not provide client site sometimes hr = Save( (LPCOLESTR)NULL, FALSE ); // triggers saving to the link location SaveCompleted( (LPCOLESTR)aPreservFileName.getStr() ); } notify( false ); return hr; } HRESULT EmbedDocument_Impl::ShowObject() { HRESULT hr = S_OK; if(m_pClientSite) hr = m_pClientSite->ShowObject(); return hr; } void EmbedDocument_Impl::notify( bool bDataChanged ) { for ( AdviseSinkHashMapIterator iAdvise = m_aAdviseHashMap.begin(); iAdvise != m_aAdviseHashMap.end(); iAdvise++ ) if ( iAdvise->second ) iAdvise->second->OnViewChange( DVASPECT_CONTENT, -1 ); if ( m_pDAdviseHolder && bDataChanged ) m_pDAdviseHolder->SendOnDataChange( (IDataObject*)this, 0, 0 ); } // Fix strange warnings about some // ATL::CAxHostWindow::QueryInterface|AddRef|Releae functions. // warning C4505: 'xxx' : unreferenced local function has been removed #if defined(_MSC_VER) #pragma warning(disable: 4505) #endif <commit_msg>INTEGRATION: CWS changefileheader (1.19.28); FILE MERGED 2008/04/01 21:31:42 thb 1.19.28.4: #i85898# Corrected misspelled header name; removed misspelled include guard 2008/04/01 15:13:58 thb 1.19.28.3: #i85898# Stripping all external header guards 2008/04/01 12:29:01 thb 1.19.28.2: #i85898# Stripping all external header guards 2008/03/31 13:33:41 rt 1.19.28.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: ed_ioleobject.cxx,v $ * $Revision: 1.20 $ * * 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. * ************************************************************************/ #include "embeddoc.hxx" #include <osl/diagnose.h> #include <com/sun/star/frame/XController.hpp> #include <com/sun/star/beans/PropertyValue.hpp> using namespace ::com::sun::star; extern ::rtl::OUString getFilterNameFromGUID_Impl( GUID* ); //------------------------------------------------------------------------------- // IOleObject STDMETHODIMP EmbedDocument_Impl::SetClientSite( IOleClientSite* pSite ) { m_pClientSite = pSite; return S_OK; } STDMETHODIMP EmbedDocument_Impl::GetClientSite( IOleClientSite** pSite ) { *pSite = m_pClientSite; return S_OK; } STDMETHODIMP EmbedDocument_Impl::SetHostNames( LPCOLESTR szContainerApp, LPCOLESTR szContainerObj ) { // the code should be ignored for links if ( !m_aFileName.getLength() ) { m_pDocHolder->setTitle( rtl::OUString( (sal_Unicode*)szContainerObj)); m_pDocHolder->setContainerName( rtl::OUString( (sal_Unicode*)szContainerApp)); } return S_OK; } STDMETHODIMP EmbedDocument_Impl::Close( DWORD dwSaveOption ) { if ( dwSaveOption == 2 && m_aFileName.getLength() ) { // ask the user about saving if ( m_pDocHolder->ExecuteSuspendCloseFrame() ) { m_pDocHolder->CloseDocument(); return S_OK; } else return OLE_E_PROMPTSAVECANCELLED; } HRESULT hr = S_OK; if ( dwSaveOption != 1 ) hr = SaveObject(); // ADVF_DATAONSTOP); m_pDocHolder->FreeOffice(); m_pDocHolder->CloseDocument(); m_pDocHolder->CloseFrame(); OLENotifyClosing(); return hr; } HRESULT EmbedDocument_Impl::OLENotifyClosing() { HRESULT hr = S_OK; if ( m_pClientSite ) m_pClientSite->OnShowWindow( FALSE ); AdviseSinkHashMap aAHM(m_aAdviseHashMap); for ( AdviseSinkHashMapIterator iAdvise = aAHM.begin(); iAdvise != aAHM.end(); iAdvise++ ) { if ( iAdvise->second ) iAdvise->second->OnClose(); } return hr; } STDMETHODIMP EmbedDocument_Impl::SetMoniker( DWORD /*dwWhichMoniker*/, IMoniker * /*pmk*/ ) { return E_NOTIMPL; } STDMETHODIMP EmbedDocument_Impl::GetMoniker( DWORD /*dwAssign*/, DWORD /*dwWhichMoniker*/, IMoniker ** /*ppmk*/ ) { return E_NOTIMPL; } STDMETHODIMP EmbedDocument_Impl::InitFromData( IDataObject * /*pDataObject*/, BOOL /*fCreation*/, DWORD /*dwReserved*/ ) { return E_NOTIMPL; } STDMETHODIMP EmbedDocument_Impl::GetClipboardData( DWORD /*dwReserved*/, IDataObject ** /*ppDataObject*/ ) { return E_NOTIMPL; } /** * Well, this is a not so very inefficient way to deliver * */ STDMETHODIMP EmbedDocument_Impl::DoVerb( LONG iVerb, LPMSG, IOleClientSite *pActiveSite, LONG, HWND, LPCRECT ) { // no locking is used since the OLE must use the same thread always if ( m_bIsInVerbHandling ) return OLEOBJ_S_CANNOT_DOVERB_NOW; BooleanGuard_Impl aGuard( m_bIsInVerbHandling ); if ( iVerb == OLEIVERB_PRIMARY ) { if ( m_aFileName.getLength() ) { // that should be a link iVerb = OLEIVERB_OPEN; } else iVerb = OLEIVERB_SHOW; } try { switch(iVerb) { case OLEIVERB_DISCARDUNDOSTATE: // free any undostate? break; case OLEIVERB_INPLACEACTIVATE: OSL_ENSURE(m_pDocHolder,"no document for inplace activation"); return m_pDocHolder->InPlaceActivate(pActiveSite,FALSE); break; case OLEIVERB_UIACTIVATE: OSL_ENSURE(m_pDocHolder,"no document for inplace activation"); return m_pDocHolder->InPlaceActivate(pActiveSite,TRUE); break; case OLEIVERB_PRIMARY: case OLEIVERB_SHOW: OSL_ENSURE(m_pDocHolder,"no document for inplace activation"); if(m_pDocHolder->isActive()) return NOERROR; //Already active if(SUCCEEDED( m_pDocHolder->InPlaceActivate( pActiveSite,TRUE))) return NOERROR; // intended fall trough case OLEIVERB_OPEN: OSL_ENSURE(m_pDocHolder,"no document to open"); // the commented code could be usefull in case // outer window would be resized depending from inner one // RECTL aEmbArea; // m_pDocHolder->GetVisArea( &aEmbArea ); // m_pDocHolder->show(); // m_pDocHolder->SetVisArea( &aEmbArea ); if(m_pDocHolder->isActive()) { m_pDocHolder->InPlaceDeactivate(); m_pDocHolder->DisableInplaceActivation(true); } SIZEL aEmbSize; m_pDocHolder->GetExtent( &aEmbSize ); m_pDocHolder->show(); m_pDocHolder->resizeWin( aEmbSize ); if ( m_pClientSite ) m_pClientSite->OnShowWindow( TRUE ); notify(); break; case OLEIVERB_HIDE: OSL_ENSURE(m_pDocHolder,"no document to hide"); if(m_pDocHolder->isActive()) m_pDocHolder->InPlaceDeactivate(); else { m_pDocHolder->hide(); if( m_pClientSite ) m_pClientSite->OnShowWindow(FALSE); } break; default: break; } } catch( uno::Exception& ) { return OLEOBJ_S_CANNOT_DOVERB_NOW; } return NOERROR; } STDMETHODIMP EmbedDocument_Impl::EnumVerbs( IEnumOLEVERB ** /*ppEnumOleVerb*/ ) { return OLE_S_USEREG; } STDMETHODIMP EmbedDocument_Impl::Update() { return S_OK; } STDMETHODIMP EmbedDocument_Impl::IsUpToDate() { return S_OK; } STDMETHODIMP EmbedDocument_Impl::GetUserClassID( CLSID *pClsid ) { return GetClassID( pClsid ); } STDMETHODIMP EmbedDocument_Impl::GetUserType( DWORD /*dwFormOfTypeUe*/, LPOLESTR * /*pszUserType*/ ) { return OLE_S_USEREG; } STDMETHODIMP EmbedDocument_Impl::SetExtent( DWORD /*dwDrawAspect*/, SIZEL *psizel ) { if ( !psizel ) return E_FAIL; m_pDocHolder->SetExtent( psizel ); return S_OK; } STDMETHODIMP EmbedDocument_Impl::GetExtent( DWORD /*dwDrawAspect*/, SIZEL * psizel ) { if ( !psizel ) return E_INVALIDARG; if ( FAILED( m_pDocHolder->GetExtent( psizel ) ) ) { // return default values psizel->cx = 500; psizel->cy = 500; } return S_OK; } STDMETHODIMP EmbedDocument_Impl::Advise( IAdviseSink *pAdvSink, DWORD *pdwConnection ) { if ( m_nAdviseNum == 0xFFFFFFFF ) return E_OUTOFMEMORY; pAdvSink->AddRef(); m_aAdviseHashMap.insert( ::std::pair< DWORD, IAdviseSink* >( m_nAdviseNum, pAdvSink ) ); *pdwConnection = m_nAdviseNum++; return S_OK; } STDMETHODIMP EmbedDocument_Impl::Unadvise( DWORD dwConnection ) { AdviseSinkHashMapIterator iAdvise = m_aAdviseHashMap.find( dwConnection ); if ( iAdvise != m_aAdviseHashMap.end() ) { iAdvise->second->Release(); m_aAdviseHashMap.erase( iAdvise ); } else return OLE_E_NOCONNECTION; return S_OK; } STDMETHODIMP EmbedDocument_Impl::EnumAdvise( IEnumSTATDATA ** /*ppenumAdvise*/ ) { return E_NOTIMPL; } STDMETHODIMP EmbedDocument_Impl::GetMiscStatus( DWORD /*dwAspect*/, DWORD * /*pdwStatus*/ ) { return OLE_S_USEREG; } STDMETHODIMP EmbedDocument_Impl::SetColorScheme( LOGPALETTE * /*pLogpal*/ ) { return E_NOTIMPL; } //------------------------------------------------------------------------------- // IDispatch STDMETHODIMP EmbedDocument_Impl::GetTypeInfoCount( unsigned int FAR* pctinfo ) { if ( m_pDocHolder->GetIDispatch() ) return m_pDocHolder->GetIDispatch()->GetTypeInfoCount( pctinfo ); return E_NOTIMPL; } STDMETHODIMP EmbedDocument_Impl::GetTypeInfo( unsigned int iTInfo, LCID lcid, ITypeInfo FAR* FAR* ppTInfo ) { if ( m_pDocHolder->GetIDispatch() ) return m_pDocHolder->GetIDispatch()->GetTypeInfo( iTInfo, lcid, ppTInfo ); return DISP_E_BADINDEX; // the only error that can be returned } STDMETHODIMP EmbedDocument_Impl::GetIDsOfNames( REFIID riid, OLECHAR FAR* FAR* rgszNames, unsigned int cNames, LCID lcid, DISPID FAR* rgDispId ) { if ( m_pDocHolder->GetIDispatch() ) return m_pDocHolder->GetIDispatch()->GetIDsOfNames( riid, rgszNames, cNames, lcid, rgDispId ); for ( unsigned int ind = 0; ind < cNames; ind++ ) rgDispId[ind] = DISPID_UNKNOWN; return DISP_E_UNKNOWNNAME; } STDMETHODIMP EmbedDocument_Impl::Invoke( DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS FAR* pDispParams, VARIANT FAR* pVarResult, EXCEPINFO FAR* pExcepInfo, unsigned int FAR* puArgErr ) { if ( m_pDocHolder->GetIDispatch() ) return m_pDocHolder->GetIDispatch()->Invoke( dispIdMember, riid, lcid, wFlags, pDispParams, pVarResult, pExcepInfo, puArgErr ); return DISP_E_MEMBERNOTFOUND; } // C++ - methods HRESULT EmbedDocument_Impl::SaveObject() { HRESULT hr = S_OK; if(m_pClientSite) { hr = m_pClientSite->SaveObject(); for ( AdviseSinkHashMapIterator iAdvise = m_aAdviseHashMap.begin(); iAdvise != m_aAdviseHashMap.end(); iAdvise++ ) if ( iAdvise->second ) iAdvise->second->OnSave( ); } else if ( m_aFileName.getLength() && IsDirty() == S_OK ) { ::rtl::OUString aPreservFileName = m_aFileName; // in case of links the containers does not provide client site sometimes hr = Save( (LPCOLESTR)NULL, FALSE ); // triggers saving to the link location SaveCompleted( (LPCOLESTR)aPreservFileName.getStr() ); } notify( false ); return hr; } HRESULT EmbedDocument_Impl::ShowObject() { HRESULT hr = S_OK; if(m_pClientSite) hr = m_pClientSite->ShowObject(); return hr; } void EmbedDocument_Impl::notify( bool bDataChanged ) { for ( AdviseSinkHashMapIterator iAdvise = m_aAdviseHashMap.begin(); iAdvise != m_aAdviseHashMap.end(); iAdvise++ ) if ( iAdvise->second ) iAdvise->second->OnViewChange( DVASPECT_CONTENT, -1 ); if ( m_pDAdviseHolder && bDataChanged ) m_pDAdviseHolder->SendOnDataChange( (IDataObject*)this, 0, 0 ); } // Fix strange warnings about some // ATL::CAxHostWindow::QueryInterface|AddRef|Releae functions. // warning C4505: 'xxx' : unreferenced local function has been removed #if defined(_MSC_VER) #pragma warning(disable: 4505) #endif <|endoftext|>
<commit_before>#include <algorithm> #include <iostream> #include <string> #include <unordered_map> #include <utility> #include <vector> #include <climits> using namespace std; vector<int> dx = {0, 1, 0, -1}; vector<int> dy = {1, 0, -1, 0}; template <typename T> void show(T a) { for (auto i : a) { cout << i << " "; } cout << endl; } template <typename T> void showmatrix(T a) { for (auto j : a) { for (auto i : j) { cout << i; } cout << endl; } cout << endl; } void check(int i = 0) { cout << "checkpoint:[" << i << "]" << endl; } int main(int argc, char *argv[]) { ios::sync_with_stdio(false); cin.tie(NULL); } <commit_msg>update template<commit_after>#include <algorithm> #include <iostream> #include <string> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> #include <climits> #include <stack> using namespace std; using ll=long long; vector<int> dx = {0, 1, 0, -1}; vector<int> dy = {1, 0, -1, 0}; template <typename T> void show(T a) { for (auto i : a) { cout << i << " "; } cout << endl; } template <typename T> void showmatrix(T a) { for (auto j : a) { for (auto i : j) { cout << i; } cout << endl; } cout << endl; } void check(int i = 0) { cout << "checkpoint:[" << i << "]" << endl; } int main(int argc, char *argv[]) { ios::sync_with_stdio(false); cin.tie(NULL); } <|endoftext|>
<commit_before>/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "RootShadowNode.h" #include <react/components/view/conversions.h> #include <react/debug/SystraceSection.h> namespace facebook { namespace react { const char RootComponentName[] = "RootView"; void RootShadowNode::layout() { SystraceSection s("RootShadowNode::layout"); ensureUnsealed(); layout(getProps()->layoutContext); // This is the rare place where shadow node must layout (set `layoutMetrics`) // itself because there is no a parent node which usually should do it. if (getHasNewLayout()) { setLayoutMetrics(layoutMetricsFromYogaNode(yogaNode_)); setHasNewLayout(false); } } UnsharedRootShadowNode RootShadowNode::clone( const LayoutConstraints &layoutConstraints, const LayoutContext &layoutContext) const { auto props = std::make_shared<const RootProps>( *getProps(), layoutConstraints, layoutContext); auto newRootShadowNode = std::make_shared<RootShadowNode>( *this, ShadowNodeFragment{ /* .tag = */ ShadowNodeFragment::tagPlaceholder(), /* .rootTag = */ ShadowNodeFragment::surfaceIdPlaceholder(), /* .props = */ props, }); return newRootShadowNode; } UnsharedRootShadowNode RootShadowNode::clone( const SharedShadowNode &oldShadowNode, const SharedShadowNode &newShadowNode) const { std::vector<std::reference_wrapper<const ShadowNode>> ancestors; if (!oldShadowNode->constructAncestorPath(*this, ancestors)) { return UnsharedRootShadowNode{nullptr}; } auto oldChild = oldShadowNode; auto newChild = newShadowNode; for (const auto &ancestor : ancestors) { auto oldParent = ancestor.get().shared_from_this(); auto children = oldParent->getChildren(); std::replace(children.begin(), children.end(), oldChild, newChild); auto sharedChildren = std::make_shared<SharedShadowNodeList>(children); auto newParent = oldParent->clone({ /* .tag = */ ShadowNodeFragment::tagPlaceholder(), /* .rootTag = */ ShadowNodeFragment::surfaceIdPlaceholder(), /* .props = */ ShadowNodeFragment::propsPlaceholder(), /* .eventEmitter = */ ShadowNodeFragment::eventEmitterPlaceholder(), /* .children = */ sharedChildren, }); newParent->replaceChild(oldChild, newChild); oldChild = oldParent; newChild = newParent; } return std::const_pointer_cast<RootShadowNode>( std::static_pointer_cast<const RootShadowNode>(newChild)); } } // namespace react } // namespace facebook <commit_msg>Fabric: Removed unnecessary call in `RootShadowNode::clone`<commit_after>/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "RootShadowNode.h" #include <react/components/view/conversions.h> #include <react/debug/SystraceSection.h> namespace facebook { namespace react { const char RootComponentName[] = "RootView"; void RootShadowNode::layout() { SystraceSection s("RootShadowNode::layout"); ensureUnsealed(); layout(getProps()->layoutContext); // This is the rare place where shadow node must layout (set `layoutMetrics`) // itself because there is no a parent node which usually should do it. if (getHasNewLayout()) { setLayoutMetrics(layoutMetricsFromYogaNode(yogaNode_)); setHasNewLayout(false); } } UnsharedRootShadowNode RootShadowNode::clone( const LayoutConstraints &layoutConstraints, const LayoutContext &layoutContext) const { auto props = std::make_shared<const RootProps>( *getProps(), layoutConstraints, layoutContext); auto newRootShadowNode = std::make_shared<RootShadowNode>( *this, ShadowNodeFragment{ /* .tag = */ ShadowNodeFragment::tagPlaceholder(), /* .rootTag = */ ShadowNodeFragment::surfaceIdPlaceholder(), /* .props = */ props, }); return newRootShadowNode; } UnsharedRootShadowNode RootShadowNode::clone( const SharedShadowNode &oldShadowNode, const SharedShadowNode &newShadowNode) const { std::vector<std::reference_wrapper<const ShadowNode>> ancestors; if (!oldShadowNode->constructAncestorPath(*this, ancestors)) { return UnsharedRootShadowNode{nullptr}; } auto oldChild = oldShadowNode; auto newChild = newShadowNode; for (const auto &ancestor : ancestors) { auto oldParent = ancestor.get().shared_from_this(); auto children = oldParent->getChildren(); std::replace(children.begin(), children.end(), oldChild, newChild); auto sharedChildren = std::make_shared<SharedShadowNodeList>(children); auto newParent = oldParent->clone({ /* .tag = */ ShadowNodeFragment::tagPlaceholder(), /* .rootTag = */ ShadowNodeFragment::surfaceIdPlaceholder(), /* .props = */ ShadowNodeFragment::propsPlaceholder(), /* .eventEmitter = */ ShadowNodeFragment::eventEmitterPlaceholder(), /* .children = */ sharedChildren, }); oldChild = oldParent; newChild = newParent; } return std::const_pointer_cast<RootShadowNode>( std::static_pointer_cast<const RootShadowNode>(newChild)); } } // namespace react } // namespace facebook <|endoftext|>
<commit_before>/** @file A brief file description @section license License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /**************************************************************************** OneWayTunnel.cc A OneWayTunnel is a module that connects two virtual connections, a source vc and a target vc, and copies the data between source and target. This class used to be called HttpTunnelVC, but it doesn't seem to have anything to do with HTTP, so it has been renamed to OneWayTunnel. ****************************************************************************/ #include "P_EventSystem.h" #include "I_OneWayTunnel.h" // #define TEST ////////////////////////////////////////////////////////////////////////////// // // OneWayTunnel::OneWayTunnel() // ////////////////////////////////////////////////////////////////////////////// ClassAllocator<OneWayTunnel> OneWayTunnelAllocator("OneWayTunnelAllocator"); inline void transfer_data(MIOBufferAccessor &in_buf, MIOBufferAccessor &out_buf) { ink_release_assert(!"Not Implemented."); int64_t n = in_buf.reader()->read_avail(); int64_t o = out_buf.writer()->write_avail(); if (n > o) n = o; if (!n) return; memcpy(in_buf.reader()->start(), out_buf.writer()->end(), n); in_buf.reader()->consume(n); out_buf.writer()->fill(n); } OneWayTunnel::OneWayTunnel() : Continuation(0), vioSource(0), vioTarget(0), cont(0), manipulate_fn(0), n_connections(0), lerrno(0), single_buffer(0), close_source(0), close_target(0), tunnel_till_done(0), tunnel_peer(0), free_vcs(true) { } OneWayTunnel * OneWayTunnel::OneWayTunnel_alloc() { return OneWayTunnelAllocator.alloc(); } void OneWayTunnel::OneWayTunnel_free(OneWayTunnel *pOWT) { pOWT->mutex = NULL; OneWayTunnelAllocator.free(pOWT); } void OneWayTunnel::SetupTwoWayTunnel(OneWayTunnel *east, OneWayTunnel *west) { // make sure the both use the same mutex ink_assert(east->mutex == west->mutex); east->tunnel_peer = west; west->tunnel_peer = east; } OneWayTunnel::~OneWayTunnel() { } OneWayTunnel::OneWayTunnel(Continuation *aCont, Transform_fn aManipulate_fn, bool aclose_source, bool aclose_target) : Continuation(aCont ? (ProxyMutex *)aCont->mutex : new_ProxyMutex()), cont(aCont), manipulate_fn(aManipulate_fn), n_connections(2), lerrno(0), single_buffer(true), close_source(aclose_source), close_target(aclose_target), tunnel_till_done(false), free_vcs(false) { ink_assert(!"This form of OneWayTunnel() constructor not supported"); } void OneWayTunnel::init(VConnection *vcSource, VConnection *vcTarget, Continuation *aCont, int size_estimate, ProxyMutex *aMutex, int64_t nbytes, bool asingle_buffer, bool aclose_source, bool aclose_target, Transform_fn aManipulate_fn, int water_mark) { mutex = aCont ? (ProxyMutex *)aCont->mutex : (aMutex ? aMutex : new_ProxyMutex()); cont = aMutex ? NULL : aCont; single_buffer = asingle_buffer; manipulate_fn = aManipulate_fn; n_connections = 2; close_source = aclose_source; close_target = aclose_target; lerrno = 0; tunnel_till_done = (nbytes == TUNNEL_TILL_DONE); SET_HANDLER(&OneWayTunnel::startEvent); int64_t size_index = 0; if (size_estimate) size_index = buffer_size_to_index(size_estimate); else size_index = default_large_iobuffer_size; Debug("one_way_tunnel", "buffer size index [%" PRId64 "] [%d]\n", size_index, size_estimate); // enqueue read request on vcSource. MIOBuffer *buf1 = new_MIOBuffer(size_index); MIOBuffer *buf2 = NULL; if (single_buffer) buf2 = buf1; else buf2 = new_MIOBuffer(size_index); buf1->water_mark = water_mark; SCOPED_MUTEX_LOCK(lock, mutex, this_ethread()); vioSource = vcSource->do_io_read(this, nbytes, buf1); vioTarget = vcTarget->do_io_write(this, nbytes, buf2->alloc_reader(), 0); ink_assert(vioSource && vioTarget); return; } void OneWayTunnel::init(VConnection *vcSource, VConnection *vcTarget, Continuation *aCont, VIO *SourceVio, IOBufferReader *reader, bool aclose_source, bool aclose_target) { (void)vcSource; mutex = aCont ? (ProxyMutex *)aCont->mutex : new_ProxyMutex(); cont = aCont; single_buffer = true; manipulate_fn = 0; n_connections = 2; close_source = aclose_source; close_target = aclose_target; tunnel_till_done = true; // Prior to constructing the OneWayTunnel, we initiated a do_io(VIO::READ) // on the source VC. We wish to use the same MIO buffer in the tunnel. // do_io() read already posted on vcSource. SET_HANDLER(&OneWayTunnel::startEvent); SourceVio->set_continuation(this); SCOPED_MUTEX_LOCK(lock, mutex, this_ethread()); vioSource = SourceVio; vioTarget = vcTarget->do_io_write(this, TUNNEL_TILL_DONE, reader, 0); ink_assert(vioSource && vioTarget); } void OneWayTunnel::init(Continuation *aCont, VIO *SourceVio, VIO *TargetVio, bool aclose_source, bool aclose_target) { mutex = aCont ? (ProxyMutex *)aCont->mutex : new_ProxyMutex(); cont = aCont; single_buffer = true; manipulate_fn = 0; n_connections = 2; close_source = aclose_source; close_target = aclose_target; tunnel_till_done = true; // do_io_read() read already posted on vcSource. // do_io_write() already posted on vcTarget SET_HANDLER(&OneWayTunnel::startEvent); ink_assert(SourceVio && TargetVio); SourceVio->set_continuation(this); TargetVio->set_continuation(this); vioSource = SourceVio; vioTarget = TargetVio; } void OneWayTunnel::transform(MIOBufferAccessor &in_buf, MIOBufferAccessor &out_buf) { if (manipulate_fn) manipulate_fn(in_buf, out_buf); else if (in_buf.writer() != out_buf.writer()) transfer_data(in_buf, out_buf); } ////////////////////////////////////////////////////////////////////////////// // // int OneWayTunnel::startEvent() // ////////////////////////////////////////////////////////////////////////////// // // tunnel was invoked with an event // int OneWayTunnel::startEvent(int event, void *data) { VIO *vio = (VIO *)data; int ret = VC_EVENT_DONE; int result = 0; #ifdef TEST const char *event_origin = (vio == vioSource ? "source" : "target"), *event_name = get_vc_event_name(event); printf("OneWayTunnel --- %s received from %s VC\n", event_name, event_origin); #endif if (!vioTarget) goto Lerror; // handle the event // switch (event) { case ONE_WAY_TUNNEL_EVENT_PEER_CLOSE: /* This event is sent out by our peer */ ink_assert(tunnel_peer); tunnel_peer = NULL; free_vcs = false; goto Ldone; case VC_EVENT_READ_READY: transform(vioSource->buffer, vioTarget->buffer); vioTarget->reenable(); ret = VC_EVENT_CONT; break; case VC_EVENT_WRITE_READY: if (vioSource) vioSource->reenable(); ret = VC_EVENT_CONT; break; case VC_EVENT_EOS: if (!tunnel_till_done && vio->ntodo()) goto Lerror; if (vio == vioSource) { transform(vioSource->buffer, vioTarget->buffer); goto Lread_complete; } else goto Ldone; Lread_complete: case VC_EVENT_READ_COMPLETE: // set write nbytes to the current buffer size // vioTarget->nbytes = vioTarget->ndone + vioTarget->buffer.reader()->read_avail(); if (vioTarget->nbytes == vioTarget->ndone) goto Ldone; vioTarget->reenable(); if (!tunnel_peer) close_source_vio(0); break; Lerror: case VC_EVENT_ERROR: lerrno = ((VIO *)data)->vc_server->lerrno; case VC_EVENT_INACTIVITY_TIMEOUT: case VC_EVENT_ACTIVE_TIMEOUT: result = -1; Ldone: case VC_EVENT_WRITE_COMPLETE: if (tunnel_peer) { // inform the peer: tunnel_peer->startEvent(ONE_WAY_TUNNEL_EVENT_PEER_CLOSE, data); } close_source_vio(result); close_target_vio(result); connection_closed(result); break; default: ink_assert(!"bad case"); ret = VC_EVENT_CONT; break; } #ifdef TEST printf(" (OneWayTunnel returning value: %s)\n", (ret == VC_EVENT_DONE ? "VC_EVENT_DONE" : "VC_EVENT_CONT")); #endif return ret; } // If result is Non-zero, the vc should be aborted. void OneWayTunnel::close_source_vio(int result) { if (vioSource) { if (last_connection() || !single_buffer) { free_MIOBuffer(vioSource->buffer.writer()); vioSource->buffer.clear(); } if (close_source && free_vcs) { vioSource->vc_server->do_io_close(result ? lerrno : -1); } vioSource = NULL; n_connections--; } } void OneWayTunnel::close_target_vio(int result, VIO *vio) { (void)vio; if (vioTarget) { if (last_connection() || !single_buffer) { free_MIOBuffer(vioTarget->buffer.writer()); vioTarget->buffer.clear(); } if (close_target && free_vcs) { vioTarget->vc_server->do_io_close(result ? lerrno : -1); } vioTarget = NULL; n_connections--; } } ////////////////////////////////////////////////////////////////////////////// // // void OneWayTunnel::connection_closed // ////////////////////////////////////////////////////////////////////////////// void OneWayTunnel::connection_closed(int result) { if (cont) { #ifdef TEST cout << "OneWayTunnel::connection_closed() ... calling cont" << endl; #endif cont->handleEvent(result ? VC_EVENT_ERROR : VC_EVENT_EOS, cont); } else { OneWayTunnel_free(this); } } void OneWayTunnel::reenable_all() { if (vioSource) vioSource->reenable(); if (vioTarget) vioTarget->reenable(); } bool OneWayTunnel::last_connection() { return n_connections == 1; } <commit_msg>TS-4201: call cont->handleEvent with OneWayTunnel object This closes #476.<commit_after>/** @file A brief file description @section license License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /**************************************************************************** OneWayTunnel.cc A OneWayTunnel is a module that connects two virtual connections, a source vc and a target vc, and copies the data between source and target. This class used to be called HttpTunnelVC, but it doesn't seem to have anything to do with HTTP, so it has been renamed to OneWayTunnel. ****************************************************************************/ #include "P_EventSystem.h" #include "I_OneWayTunnel.h" // #define TEST ////////////////////////////////////////////////////////////////////////////// // // OneWayTunnel::OneWayTunnel() // ////////////////////////////////////////////////////////////////////////////// ClassAllocator<OneWayTunnel> OneWayTunnelAllocator("OneWayTunnelAllocator"); inline void transfer_data(MIOBufferAccessor &in_buf, MIOBufferAccessor &out_buf) { ink_release_assert(!"Not Implemented."); int64_t n = in_buf.reader()->read_avail(); int64_t o = out_buf.writer()->write_avail(); if (n > o) n = o; if (!n) return; memcpy(in_buf.reader()->start(), out_buf.writer()->end(), n); in_buf.reader()->consume(n); out_buf.writer()->fill(n); } OneWayTunnel::OneWayTunnel() : Continuation(0), vioSource(0), vioTarget(0), cont(0), manipulate_fn(0), n_connections(0), lerrno(0), single_buffer(0), close_source(0), close_target(0), tunnel_till_done(0), tunnel_peer(0), free_vcs(true) { } OneWayTunnel * OneWayTunnel::OneWayTunnel_alloc() { return OneWayTunnelAllocator.alloc(); } void OneWayTunnel::OneWayTunnel_free(OneWayTunnel *pOWT) { pOWT->mutex = NULL; OneWayTunnelAllocator.free(pOWT); } void OneWayTunnel::SetupTwoWayTunnel(OneWayTunnel *east, OneWayTunnel *west) { // make sure the both use the same mutex ink_assert(east->mutex == west->mutex); east->tunnel_peer = west; west->tunnel_peer = east; } OneWayTunnel::~OneWayTunnel() { } OneWayTunnel::OneWayTunnel(Continuation *aCont, Transform_fn aManipulate_fn, bool aclose_source, bool aclose_target) : Continuation(aCont ? (ProxyMutex *)aCont->mutex : new_ProxyMutex()), cont(aCont), manipulate_fn(aManipulate_fn), n_connections(2), lerrno(0), single_buffer(true), close_source(aclose_source), close_target(aclose_target), tunnel_till_done(false), free_vcs(false) { ink_assert(!"This form of OneWayTunnel() constructor not supported"); } void OneWayTunnel::init(VConnection *vcSource, VConnection *vcTarget, Continuation *aCont, int size_estimate, ProxyMutex *aMutex, int64_t nbytes, bool asingle_buffer, bool aclose_source, bool aclose_target, Transform_fn aManipulate_fn, int water_mark) { mutex = aCont ? (ProxyMutex *)aCont->mutex : (aMutex ? aMutex : new_ProxyMutex()); cont = aMutex ? NULL : aCont; single_buffer = asingle_buffer; manipulate_fn = aManipulate_fn; n_connections = 2; close_source = aclose_source; close_target = aclose_target; lerrno = 0; tunnel_till_done = (nbytes == TUNNEL_TILL_DONE); SET_HANDLER(&OneWayTunnel::startEvent); int64_t size_index = 0; if (size_estimate) size_index = buffer_size_to_index(size_estimate); else size_index = default_large_iobuffer_size; Debug("one_way_tunnel", "buffer size index [%" PRId64 "] [%d]\n", size_index, size_estimate); // enqueue read request on vcSource. MIOBuffer *buf1 = new_MIOBuffer(size_index); MIOBuffer *buf2 = NULL; if (single_buffer) buf2 = buf1; else buf2 = new_MIOBuffer(size_index); buf1->water_mark = water_mark; SCOPED_MUTEX_LOCK(lock, mutex, this_ethread()); vioSource = vcSource->do_io_read(this, nbytes, buf1); vioTarget = vcTarget->do_io_write(this, nbytes, buf2->alloc_reader(), 0); ink_assert(vioSource && vioTarget); return; } void OneWayTunnel::init(VConnection *vcSource, VConnection *vcTarget, Continuation *aCont, VIO *SourceVio, IOBufferReader *reader, bool aclose_source, bool aclose_target) { (void)vcSource; mutex = aCont ? (ProxyMutex *)aCont->mutex : new_ProxyMutex(); cont = aCont; single_buffer = true; manipulate_fn = 0; n_connections = 2; close_source = aclose_source; close_target = aclose_target; tunnel_till_done = true; // Prior to constructing the OneWayTunnel, we initiated a do_io(VIO::READ) // on the source VC. We wish to use the same MIO buffer in the tunnel. // do_io() read already posted on vcSource. SET_HANDLER(&OneWayTunnel::startEvent); SourceVio->set_continuation(this); SCOPED_MUTEX_LOCK(lock, mutex, this_ethread()); vioSource = SourceVio; vioTarget = vcTarget->do_io_write(this, TUNNEL_TILL_DONE, reader, 0); ink_assert(vioSource && vioTarget); } void OneWayTunnel::init(Continuation *aCont, VIO *SourceVio, VIO *TargetVio, bool aclose_source, bool aclose_target) { mutex = aCont ? (ProxyMutex *)aCont->mutex : new_ProxyMutex(); cont = aCont; single_buffer = true; manipulate_fn = 0; n_connections = 2; close_source = aclose_source; close_target = aclose_target; tunnel_till_done = true; // do_io_read() read already posted on vcSource. // do_io_write() already posted on vcTarget SET_HANDLER(&OneWayTunnel::startEvent); ink_assert(SourceVio && TargetVio); SourceVio->set_continuation(this); TargetVio->set_continuation(this); vioSource = SourceVio; vioTarget = TargetVio; } void OneWayTunnel::transform(MIOBufferAccessor &in_buf, MIOBufferAccessor &out_buf) { if (manipulate_fn) manipulate_fn(in_buf, out_buf); else if (in_buf.writer() != out_buf.writer()) transfer_data(in_buf, out_buf); } ////////////////////////////////////////////////////////////////////////////// // // int OneWayTunnel::startEvent() // ////////////////////////////////////////////////////////////////////////////// // // tunnel was invoked with an event // int OneWayTunnel::startEvent(int event, void *data) { VIO *vio = (VIO *)data; int ret = VC_EVENT_DONE; int result = 0; #ifdef TEST const char *event_origin = (vio == vioSource ? "source" : "target"), *event_name = get_vc_event_name(event); printf("OneWayTunnel --- %s received from %s VC\n", event_name, event_origin); #endif if (!vioTarget) goto Lerror; // handle the event // switch (event) { case ONE_WAY_TUNNEL_EVENT_PEER_CLOSE: /* This event is sent out by our peer */ ink_assert(tunnel_peer); tunnel_peer = NULL; free_vcs = false; goto Ldone; case VC_EVENT_READ_READY: transform(vioSource->buffer, vioTarget->buffer); vioTarget->reenable(); ret = VC_EVENT_CONT; break; case VC_EVENT_WRITE_READY: if (vioSource) vioSource->reenable(); ret = VC_EVENT_CONT; break; case VC_EVENT_EOS: if (!tunnel_till_done && vio->ntodo()) goto Lerror; if (vio == vioSource) { transform(vioSource->buffer, vioTarget->buffer); goto Lread_complete; } else goto Ldone; Lread_complete: case VC_EVENT_READ_COMPLETE: // set write nbytes to the current buffer size // vioTarget->nbytes = vioTarget->ndone + vioTarget->buffer.reader()->read_avail(); if (vioTarget->nbytes == vioTarget->ndone) goto Ldone; vioTarget->reenable(); if (!tunnel_peer) close_source_vio(0); break; Lerror: case VC_EVENT_ERROR: lerrno = ((VIO *)data)->vc_server->lerrno; case VC_EVENT_INACTIVITY_TIMEOUT: case VC_EVENT_ACTIVE_TIMEOUT: result = -1; Ldone: case VC_EVENT_WRITE_COMPLETE: if (tunnel_peer) { // inform the peer: tunnel_peer->startEvent(ONE_WAY_TUNNEL_EVENT_PEER_CLOSE, data); } close_source_vio(result); close_target_vio(result); connection_closed(result); break; default: ink_assert(!"bad case"); ret = VC_EVENT_CONT; break; } #ifdef TEST printf(" (OneWayTunnel returning value: %s)\n", (ret == VC_EVENT_DONE ? "VC_EVENT_DONE" : "VC_EVENT_CONT")); #endif return ret; } // If result is Non-zero, the vc should be aborted. void OneWayTunnel::close_source_vio(int result) { if (vioSource) { if (last_connection() || !single_buffer) { free_MIOBuffer(vioSource->buffer.writer()); vioSource->buffer.clear(); } if (close_source && free_vcs) { vioSource->vc_server->do_io_close(result ? lerrno : -1); } vioSource = NULL; n_connections--; } } void OneWayTunnel::close_target_vio(int result, VIO *vio) { (void)vio; if (vioTarget) { if (last_connection() || !single_buffer) { free_MIOBuffer(vioTarget->buffer.writer()); vioTarget->buffer.clear(); } if (close_target && free_vcs) { vioTarget->vc_server->do_io_close(result ? lerrno : -1); } vioTarget = NULL; n_connections--; } } ////////////////////////////////////////////////////////////////////////////// // // void OneWayTunnel::connection_closed // ////////////////////////////////////////////////////////////////////////////// void OneWayTunnel::connection_closed(int result) { if (cont) { #ifdef TEST cout << "OneWayTunnel::connection_closed() ... calling cont" << endl; #endif cont->handleEvent(result ? VC_EVENT_ERROR : VC_EVENT_EOS, this); } else { OneWayTunnel_free(this); } } void OneWayTunnel::reenable_all() { if (vioSource) vioSource->reenable(); if (vioTarget) vioTarget->reenable(); } bool OneWayTunnel::last_connection() { return n_connections == 1; } <|endoftext|>
<commit_before>#ifdef USE_ALLEGRO #include <allegro.h> #endif #include "music-player.h" #include "globals.h" #include <iostream> #include "configuration.h" #include "sound.h" #include "dumb/include/dumb.h" #include "gme/Music_Emu.h" #ifdef USE_ALLEGRO #include "dumb/include/aldumb.h" #include "ogg/logg.h" #ifdef _WIN32 /* what do we need winalleg for? * reason: ... */ #include <winalleg.h> #endif #endif #ifdef USE_SDL #include "sdl/mixer/SDL_mixer.h" #endif #include "exceptions/exception.h" #include <sstream> namespace Util{ class MusicException: public Exception::Base { public: MusicException(const std::string & file, int line, const std::string & reason): Exception::Base(file, line), reason(reason){ } MusicException(const MusicException & copy): Exception::Base(copy), reason(copy.reason){ } virtual ~MusicException() throw(){ } protected: virtual const std::string getReason() const { return reason; } virtual Exception::Base * copy() const { return new MusicException(*this); } std::string reason; }; static double scaleVolume(double start){ return start; } MusicPlayer::MusicPlayer(): volume(1.0){ } MusicPlayer::~MusicPlayer(){ } static const char * typeToExtension( int i ){ switch (i){ case 0 : return ".xm"; case 1 : return ".s3m"; case 2 : return ".it"; case 3 : return ".mod"; default : return ""; } } DUH * DumbPlayer::loadDumbFile(const char * path){ DUH * what; for (int i = 0; i < 4; i++){ /* the order of trying xm/s3m/it/mod matters because mod could be * confused with one of the other formats, so load it last. */ switch (i){ case 0 : { what = dumb_load_xm_quick(path); break; } case 1 : { what = dumb_load_s3m_quick(path); break; } case 2 : { what = dumb_load_it_quick(path); break; } case 3 : { what = dumb_load_mod_quick(path); break; } } if (what != NULL){ Global::debug(0) << "Loaded " << path << " type " << typeToExtension(i) << "(" << i << ")" << std::endl; return what; } } return NULL; } #ifdef USE_ALLEGRO DumbPlayer::DumbPlayer(const char * path){ music_file = loadDumbFile(path); if (music_file != NULL){ int buf = 1 << 11; player = al_start_duh(music_file, 2, 0, scaleVolume(volume), buf, Sound::FREQUENCY); } else { std::ostringstream error; error << "Could not DUMB file load " << path; throw MusicException(__FILE__, __LINE__, error.str()); } } void DumbPlayer::play(){ al_resume_duh(this->player); } void DumbPlayer::poll(){ if (al_poll_duh(this->player) != 0){ } } void DumbPlayer::pause(){ al_pause_duh(this->player); } void DumbPlayer::setVolume(double volume){ this->volume = volume; al_duh_set_volume(player, scaleVolume(volume)); } DumbPlayer::~DumbPlayer(){ al_stop_duh(player); unload_duh(music_file); } static const int GME_BUFFER_SIZE = 1 << 11; GMEPlayer::GMEPlayer(const char * path){ gme_err_t fail = gme_open_file(path, &emulator, Sound::FREQUENCY); if (fail != NULL){ Global::debug(0) << "GME load error for " << path << ": " << fail << std::endl; throw MusicException(__FILE__, __LINE__, "Could not load GME file"); } emulator->start_track(0); Global::debug(0) << "Loaded GME file " << path << std::endl; stream = play_audio_stream(GME_BUFFER_SIZE, 16, 1, Sound::FREQUENCY, 255, 128); voice_set_priority(stream->voice, 255); } void GMEPlayer::play(){ voice_start(stream->voice); } void GMEPlayer::poll(){ short * buffer = (short*) get_audio_stream_buffer(stream); if (buffer){ /* size in 16-bit samples is buffer size * channels */ emulator->play(GME_BUFFER_SIZE * 2, buffer); if (emulator->track_ended()){ gme_info_t * info; gme_track_info(emulator, &info, 0); int intro = info->intro_length; emulator->start_track(0); // Global::debug(0) << "Seeking " << intro << "ms. Track length " << info->length << "ms" << std::endl; /* skip past the intro if there is a loop */ if (info->loop_length != 0){ emulator->seek(intro); } } /* allegro wants unsigned data but gme produces signed so to convert * signed samples to unsigned samples we have to raise each value * by half the maximum value of a short (0xffff+1)/2 = 0x8000 */ for (int i = 0; i < GME_BUFFER_SIZE * 2; i++){ buffer[i] += 0x8000; } free_audio_stream_buffer(stream); } } void GMEPlayer::pause(){ voice_stop(stream->voice); } void GMEPlayer::setVolume(double volume){ /* FIXME */ } GMEPlayer::~GMEPlayer(){ delete emulator; stop_audio_stream(stream); } #ifdef HAVE_OGG OggPlayer::OggPlayer(const char * path){ stream = logg_get_stream(path, scaleVolume(volume) * 255, 128, 1); if (stream == NULL){ throw MusicException(__FILE__, __LINE__, "Could not load ogg file"); } } void OggPlayer::play(){ } void OggPlayer::poll(){ logg_update_stream(stream); } void OggPlayer::pause(){ } void OggPlayer::setVolume(double volume){ } OggPlayer::~OggPlayer(){ logg_destroy_stream(stream); } #endif /* OGG */ #endif /* ALlEGRO */ #ifdef USE_SDL DumbPlayer::DumbPlayer(const char * path){ music_file = loadDumbFile(path); if (music_file == NULL){ std::ostringstream error; error << "Could not load DUMB file " << path; throw MusicException(__FILE__, __LINE__, error.str()); } int n_channels = 2; int position = 0; renderer = duh_start_sigrenderer(music_file, 0, n_channels, position); if (!renderer){ Global::debug(0) << "Could not create renderer" << std::endl; throw Exception::Base(__FILE__, __LINE__); } } void DumbPlayer::render(Uint8 * stream, int length){ double delta = 65536.0 / Sound::FREQUENCY; /* a frame is 32 bits, 16 bit samples with 2 channels = 2 * 16, * so we have to divide the number of 'dumb samples' by the * size of each frame, 32 bits = 4 bytes */ /* FIXME: use global music volume to scale the output here */ int n = duh_render(renderer, 16, 0, volume, delta, length / 4, stream); if (n == 0){ Global::debug(0) << "Sound finished?" << std::endl; } /* short large = 0; for (int i = 0; i < length / 2; i++){ short z = ((short *) stream)[i]; if (z < 0){ z = -z; } if (z > large){ large = z; } } Global::debug(0) << "Largest amplitude " << large << std::endl; */ } struct DumbPlayerInfo{ MusicPlayer * who; }; void DumbPlayer::mixer(void * player_, Uint8 * stream, int length){ DumbPlayerInfo * info = (DumbPlayerInfo *) player_; DumbPlayer * player = (DumbPlayer *) info->who; player->render(stream, length); } void DumbPlayer::pause(){ Mix_HookMusic(NULL, NULL); } void DumbPlayer::play(){ DumbPlayerInfo * me = new DumbPlayerInfo; me->who = this; Mix_HookMusic(mixer, me); } void DumbPlayer::poll(){ } /* volume should be in the range 0.0 to 1.0 */ void DumbPlayer::setVolume(double volume){ this->volume = volume; /* Mix_VolumeMusic only handles volume for formats it handles natively. * for custom formats (like all these players) we have to handle volume * ourselves. */ // Mix_VolumeMusic(MIX_MAX_VOLUME * volume); } DumbPlayer::~DumbPlayer(){ DumbPlayerInfo * info = (DumbPlayerInfo*) Mix_GetMusicHookData(); Mix_HookMusic(NULL, NULL); if (info != NULL){ delete info; } /* I'm pretty sure if we get this far then there is no chance * that our mixer function will still be active. */ duh_end_sigrenderer(renderer); unload_duh(music_file); } struct GMEInfo{ GMEPlayer * player; }; GMEPlayer::GMEPlayer(const char * path){ gme_err_t fail = gme_open_file(path, &emulator, Sound::FREQUENCY); if (fail != NULL){ Global::debug(0) << "GME load error for " << path << ": " << fail << std::endl; throw MusicException(__FILE__, __LINE__, "Could not load GME file"); } emulator->start_track(0); Global::debug(0) << "Loaded GME file " << path << std::endl; } void GMEPlayer::mixer(void * arg, Uint8 * stream, int length){ GMEInfo * info = (GMEInfo*) arg; info->player->render(stream, length); } void GMEPlayer::render(Uint8 * stream, int length){ /* length/2 to convert bytes to short */ emulator->play(length / 2, (short*) stream); /* scale for volume */ for (int i = 0; i < length / 2; i++){ short & sample = ((short *) stream)[i]; sample *= volume; } /* short large = 0; short small = 0; for (int i = 0; i < length / 2; i++){ // ((short *) stream)[i] *= 2; short z = ((short *) stream)[i]; if (z < small){ small = z; } if (z > large){ large = z; } } Global::debug(0) << "Largest " << large << " Smallest " << small << std::endl; */ } void GMEPlayer::play(){ GMEInfo * me = new GMEInfo; me->player = this; Mix_HookMusic(mixer, me); } void GMEPlayer::poll(){ } void GMEPlayer::pause(){ } void GMEPlayer::setVolume(double volume){ this->volume = volume; // Mix_VolumeMusic(volume * MIX_MAX_VOLUME); } GMEPlayer::~GMEPlayer(){ GMEInfo * info = (GMEInfo*) Mix_GetMusicHookData(); Mix_HookMusic(NULL, NULL); if (info != NULL){ delete info; } delete emulator; } #ifdef HAVE_OGG OggPlayer::OggPlayer(const char * path){ music = Mix_LoadMUS(path); if (music == NULL){ throw MusicException(__FILE__, __LINE__, "Could not load OGG file"); } } void OggPlayer::play(){ Mix_PlayMusic(music, -1); } void OggPlayer::poll(){ } void OggPlayer::pause(){ Mix_PauseMusic(); } void OggPlayer::setVolume(double volume){ this->volume = volume; Mix_VolumeMusic(volume * MIX_MAX_VOLUME); } OggPlayer::~OggPlayer(){ Mix_FreeMusic(music); } #endif /* OGG */ #endif /* SDL */ } <commit_msg>set volume for allegro gme player<commit_after>#ifdef USE_ALLEGRO #include <allegro.h> #endif #include "music-player.h" #include "globals.h" #include <iostream> #include "configuration.h" #include "sound.h" #include "dumb/include/dumb.h" #include "gme/Music_Emu.h" #ifdef USE_ALLEGRO #include "dumb/include/aldumb.h" #include "ogg/logg.h" #ifdef _WIN32 /* what do we need winalleg for? * reason: ... */ #include <winalleg.h> #endif #endif #ifdef USE_SDL #include "sdl/mixer/SDL_mixer.h" #endif #include "exceptions/exception.h" #include <sstream> namespace Util{ class MusicException: public Exception::Base { public: MusicException(const std::string & file, int line, const std::string & reason): Exception::Base(file, line), reason(reason){ } MusicException(const MusicException & copy): Exception::Base(copy), reason(copy.reason){ } virtual ~MusicException() throw(){ } protected: virtual const std::string getReason() const { return reason; } virtual Exception::Base * copy() const { return new MusicException(*this); } std::string reason; }; static double scaleVolume(double start){ return start; } MusicPlayer::MusicPlayer(): volume(1.0){ } MusicPlayer::~MusicPlayer(){ } static const char * typeToExtension( int i ){ switch (i){ case 0 : return ".xm"; case 1 : return ".s3m"; case 2 : return ".it"; case 3 : return ".mod"; default : return ""; } } DUH * DumbPlayer::loadDumbFile(const char * path){ DUH * what; for (int i = 0; i < 4; i++){ /* the order of trying xm/s3m/it/mod matters because mod could be * confused with one of the other formats, so load it last. */ switch (i){ case 0 : { what = dumb_load_xm_quick(path); break; } case 1 : { what = dumb_load_s3m_quick(path); break; } case 2 : { what = dumb_load_it_quick(path); break; } case 3 : { what = dumb_load_mod_quick(path); break; } } if (what != NULL){ Global::debug(0) << "Loaded " << path << " type " << typeToExtension(i) << "(" << i << ")" << std::endl; return what; } } return NULL; } #ifdef USE_ALLEGRO DumbPlayer::DumbPlayer(const char * path){ music_file = loadDumbFile(path); if (music_file != NULL){ int buf = 1 << 11; player = al_start_duh(music_file, 2, 0, scaleVolume(volume), buf, Sound::FREQUENCY); } else { std::ostringstream error; error << "Could not DUMB file load " << path; throw MusicException(__FILE__, __LINE__, error.str()); } } void DumbPlayer::play(){ al_resume_duh(this->player); } void DumbPlayer::poll(){ if (al_poll_duh(this->player) != 0){ } } void DumbPlayer::pause(){ al_pause_duh(this->player); } void DumbPlayer::setVolume(double volume){ this->volume = volume; al_duh_set_volume(player, scaleVolume(volume)); } DumbPlayer::~DumbPlayer(){ al_stop_duh(player); unload_duh(music_file); } static const int GME_BUFFER_SIZE = 1 << 11; GMEPlayer::GMEPlayer(const char * path){ gme_err_t fail = gme_open_file(path, &emulator, Sound::FREQUENCY); if (fail != NULL){ Global::debug(0) << "GME load error for " << path << ": " << fail << std::endl; throw MusicException(__FILE__, __LINE__, "Could not load GME file"); } emulator->start_track(0); Global::debug(0) << "Loaded GME file " << path << std::endl; stream = play_audio_stream(GME_BUFFER_SIZE, 16, 1, Sound::FREQUENCY, 255, 128); voice_set_priority(stream->voice, 255); } void GMEPlayer::play(){ voice_start(stream->voice); } void GMEPlayer::poll(){ short * buffer = (short*) get_audio_stream_buffer(stream); if (buffer){ /* size in 16-bit samples is buffer size * channels */ emulator->play(GME_BUFFER_SIZE * 2, buffer); if (emulator->track_ended()){ gme_info_t * info; gme_track_info(emulator, &info, 0); int intro = info->intro_length; emulator->start_track(0); // Global::debug(0) << "Seeking " << intro << "ms. Track length " << info->length << "ms" << std::endl; /* skip past the intro if there is a loop */ if (info->loop_length != 0){ emulator->seek(intro); } } /* allegro wants unsigned data but gme produces signed so to convert * signed samples to unsigned samples we have to raise each value * by half the maximum value of a short (0xffff+1)/2 = 0x8000 */ for (int i = 0; i < GME_BUFFER_SIZE * 2; i++){ buffer[i] *= volume; buffer[i] += 0x8000; } free_audio_stream_buffer(stream); } } void GMEPlayer::pause(){ voice_stop(stream->voice); } void GMEPlayer::setVolume(double volume){ this->volume = volume; } GMEPlayer::~GMEPlayer(){ delete emulator; stop_audio_stream(stream); } #ifdef HAVE_OGG OggPlayer::OggPlayer(const char * path){ stream = logg_get_stream(path, scaleVolume(volume) * 255, 128, 1); if (stream == NULL){ throw MusicException(__FILE__, __LINE__, "Could not load ogg file"); } } void OggPlayer::play(){ } void OggPlayer::poll(){ logg_update_stream(stream); } void OggPlayer::pause(){ } void OggPlayer::setVolume(double volume){ } OggPlayer::~OggPlayer(){ logg_destroy_stream(stream); } #endif /* OGG */ #endif /* ALlEGRO */ #ifdef USE_SDL DumbPlayer::DumbPlayer(const char * path){ music_file = loadDumbFile(path); if (music_file == NULL){ std::ostringstream error; error << "Could not load DUMB file " << path; throw MusicException(__FILE__, __LINE__, error.str()); } int n_channels = 2; int position = 0; renderer = duh_start_sigrenderer(music_file, 0, n_channels, position); if (!renderer){ Global::debug(0) << "Could not create renderer" << std::endl; throw Exception::Base(__FILE__, __LINE__); } } void DumbPlayer::render(Uint8 * stream, int length){ double delta = 65536.0 / Sound::FREQUENCY; /* a frame is 32 bits, 16 bit samples with 2 channels = 2 * 16, * so we have to divide the number of 'dumb samples' by the * size of each frame, 32 bits = 4 bytes */ /* FIXME: use global music volume to scale the output here */ int n = duh_render(renderer, 16, 0, volume, delta, length / 4, stream); if (n == 0){ Global::debug(0) << "Sound finished?" << std::endl; } /* short large = 0; for (int i = 0; i < length / 2; i++){ short z = ((short *) stream)[i]; if (z < 0){ z = -z; } if (z > large){ large = z; } } Global::debug(0) << "Largest amplitude " << large << std::endl; */ } struct DumbPlayerInfo{ MusicPlayer * who; }; void DumbPlayer::mixer(void * player_, Uint8 * stream, int length){ DumbPlayerInfo * info = (DumbPlayerInfo *) player_; DumbPlayer * player = (DumbPlayer *) info->who; player->render(stream, length); } void DumbPlayer::pause(){ Mix_HookMusic(NULL, NULL); } void DumbPlayer::play(){ DumbPlayerInfo * me = new DumbPlayerInfo; me->who = this; Mix_HookMusic(mixer, me); } void DumbPlayer::poll(){ } /* volume should be in the range 0.0 to 1.0 */ void DumbPlayer::setVolume(double volume){ this->volume = volume; /* Mix_VolumeMusic only handles volume for formats it handles natively. * for custom formats (like all these players) we have to handle volume * ourselves. */ // Mix_VolumeMusic(MIX_MAX_VOLUME * volume); } DumbPlayer::~DumbPlayer(){ DumbPlayerInfo * info = (DumbPlayerInfo*) Mix_GetMusicHookData(); Mix_HookMusic(NULL, NULL); if (info != NULL){ delete info; } /* I'm pretty sure if we get this far then there is no chance * that our mixer function will still be active. */ duh_end_sigrenderer(renderer); unload_duh(music_file); } struct GMEInfo{ GMEPlayer * player; }; GMEPlayer::GMEPlayer(const char * path){ gme_err_t fail = gme_open_file(path, &emulator, Sound::FREQUENCY); if (fail != NULL){ Global::debug(0) << "GME load error for " << path << ": " << fail << std::endl; throw MusicException(__FILE__, __LINE__, "Could not load GME file"); } emulator->start_track(0); Global::debug(0) << "Loaded GME file " << path << std::endl; } void GMEPlayer::mixer(void * arg, Uint8 * stream, int length){ GMEInfo * info = (GMEInfo*) arg; info->player->render(stream, length); } void GMEPlayer::render(Uint8 * stream, int length){ /* length/2 to convert bytes to short */ emulator->play(length / 2, (short*) stream); /* scale for volume */ for (int i = 0; i < length / 2; i++){ short & sample = ((short *) stream)[i]; sample *= volume; } /* short large = 0; short small = 0; for (int i = 0; i < length / 2; i++){ // ((short *) stream)[i] *= 2; short z = ((short *) stream)[i]; if (z < small){ small = z; } if (z > large){ large = z; } } Global::debug(0) << "Largest " << large << " Smallest " << small << std::endl; */ } void GMEPlayer::play(){ GMEInfo * me = new GMEInfo; me->player = this; Mix_HookMusic(mixer, me); } void GMEPlayer::poll(){ } void GMEPlayer::pause(){ } void GMEPlayer::setVolume(double volume){ this->volume = volume; // Mix_VolumeMusic(volume * MIX_MAX_VOLUME); } GMEPlayer::~GMEPlayer(){ GMEInfo * info = (GMEInfo*) Mix_GetMusicHookData(); Mix_HookMusic(NULL, NULL); if (info != NULL){ delete info; } delete emulator; } #ifdef HAVE_OGG OggPlayer::OggPlayer(const char * path){ music = Mix_LoadMUS(path); if (music == NULL){ throw MusicException(__FILE__, __LINE__, "Could not load OGG file"); } } void OggPlayer::play(){ Mix_PlayMusic(music, -1); } void OggPlayer::poll(){ } void OggPlayer::pause(){ Mix_PauseMusic(); } void OggPlayer::setVolume(double volume){ this->volume = volume; Mix_VolumeMusic(volume * MIX_MAX_VOLUME); } OggPlayer::~OggPlayer(){ Mix_FreeMusic(music); } #endif /* OGG */ #endif /* SDL */ } <|endoftext|>
<commit_before>// // Created by manuel on 08.06.15. // #include "AssemblyParser.h" #include <fstream> #include <sstream> #include <string> #include <algorithm> #include <bitset> #include <cstdint> const std::string AssemblyParser::ROUTINE_DIRECTIVE = ".FUNCT"; const std::string AssemblyParser::GVAR_DIRECTIVE = ".GVAR"; const std::string AssemblyParser::NEW_LINE_COMMAND = "new_line"; const std::string AssemblyParser::PRINT_COMMAND = "print"; const std::string AssemblyParser::JE_COMMAND = "je"; const std::string AssemblyParser::QUIT_COMMAND = "quit"; const std::string AssemblyParser::READ_CHAR_COMMAND = "read_char"; const std::string AssemblyParser::CALL_COMMAND = "call"; const std::string AssemblyParser::JUMP_COMMAND = "jump"; const char AssemblyParser::SPLITTER_BETWEEN_LEXEMES_IN_AN_COMMAND = ' '; // 9 is ascii for tab const char AssemblyParser::STRING_IDENTIFIER = '\"'; // 9 is ascii for tab const std::string AssemblyParser::ASSIGNMENT_OPERATOR = "->"; std::string trim(const std::string& str, const std::string& whitespace = " \t") { const auto strBegin = str.find_first_not_of(whitespace); if (strBegin == std::string::npos) return ""; // no content const auto strEnd = str.find_last_not_of(whitespace); const auto strRange = strEnd - strBegin + 1; return str.substr(strBegin, strRange); } void AssemblyParser::readAssembly(std::istream& input, std::vector <std::bitset<8>> &highMemoryZcode, size_t offset) { std::cout << "Compiler: Parse Assembly File\n"; for(std::string line; getline(input, line);) { std::vector<std::string> lineComps; this->split(line, SPLITTER_BETWEEN_LEXEMES_IN_AN_COMMAND, lineComps); if(lineComps.size()) { std::string firstComp = lineComps.at(0); if(line.at(0) == '.') { // directive if(firstComp.compare(ROUTINE_DIRECTIVE) == 0) { std::cout << "found routine" << std::endl; if(lineComps.size() < 2) { std::cerr << "invalid routine declaration" << std::endl; throw; } // currentGenerator exists, so we can get its code if(currentGenerator) { finishRoutine(highMemoryZcode); } std::string routineName = lineComps.at(1); currentGenerator.reset(new RoutineGenerator(routineName, 0, highMemoryZcode, offset)); } else if(firstComp.compare(GVAR_DIRECTIVE) == 0) { std::cout << "found gvar" << std::endl; this->split(line, SPLITTER_BETWEEN_LEXEMES_IN_AN_COMMAND, lineComps); if(lineComps.size() < 2) { std::cerr << "empty gvar declaration" << std::endl; } std::string gvar = lineComps.at(1); addGlobal(gvar); } } else { // normal instruction // check for label auto pos = line.find(":"); if(pos != std::string::npos) { std::cout << ":::::: new label: "; std::string labelName = line.substr(0, pos); currentGenerator->newLabel(labelName); std::cout << labelName << std::endl; std::string afterLabel = line.substr(pos + 1, line.length() - 1); executeCommand(afterLabel, *currentGenerator); } else { executeCommand(line, *currentGenerator); } } } } if(currentGenerator) { finishRoutine(highMemoryZcode); } } void AssemblyParser::finishRoutine(std::vector <std::bitset<8>> &highMemoryZcode) { std::cout << "adding routine to zcode" << std::endl; auto routineCode = currentGenerator->getRoutine(); Utils::append(highMemoryZcode, routineCode); } void AssemblyParser::addGlobal(std::string globalName) { // TODO: check if maximum gvar limit is reached unsigned index = (unsigned) globalVariableStack.size(); std::cout << "adding gvar " << globalName << " at index " << std::to_string(index) << std::endl; this->globalVariableStack[globalName] = index; } RoutineGenerator& AssemblyParser::executePRINTCommand(const std::string &printCommand, RoutineGenerator &routineGenerator) { std::vector <std::string> commandParts = this->split(printCommand, AssemblyParser::STRING_IDENTIFIER); routineGenerator.printString(commandParts.at(1)); std::cout << commandParts.at(1) << std::endl; return routineGenerator; } RoutineGenerator& AssemblyParser::executeREADCommand(const std::string &readCommand, RoutineGenerator &routineGenerator) { //this->globalVariableStack.insert(std::pair<std::string, int>("sp", variableUsed)); std::vector <std::string> commandParts = this->split(readCommand, AssemblyParser::ASSIGNMENT_OPERATOR); if(commandParts.size() < 2) { // TODO: decide on whether to allow no args for read_char return routineGenerator; } auto last = trim(commandParts.back()); routineGenerator.readChar(getAddressForId(last)); //TODO: get available address return routineGenerator; } RoutineGenerator& AssemblyParser::executeJECommand(const std::string &jeCommand, RoutineGenerator &routineGenerator) { std::vector <std::string> commandParts = this->split(jeCommand, '?'); std::string label = commandParts.at(1); std::cout << label << std::endl; routineGenerator.jumpEquals(label, true, 0x10, 49, true, false); return routineGenerator; } RoutineGenerator& AssemblyParser::executeJUMPCommand(const std::string &jumpCommand, RoutineGenerator &routineGenerator) { std::vector <std::string> commandParts = this->split(jumpCommand, '?'); std::string label = commandParts.at(1); std::cout << label << std::endl; routineGenerator.jump(label); return routineGenerator; } RoutineGenerator& AssemblyParser::executeCALLCommand(const std::string &callCommand, RoutineGenerator &routineGenerator) { std::vector <std::string> commandParts = this->split(callCommand, ' '); std::string callRoutineName = commandParts.at(1); std::cout << callRoutineName << std::endl; routineGenerator.callRoutine(callRoutineName); return routineGenerator; } RoutineGenerator& AssemblyParser::executeCommand(const std::string& command, RoutineGenerator &routineGenerator) { std::vector <std::string> commandParts = this->split(command, AssemblyParser::SPLITTER_BETWEEN_LEXEMES_IN_AN_COMMAND); if(!commandParts.size()) return routineGenerator; std::string commandPart = commandParts.at(0); if (commandPart.compare(AssemblyParser::NEW_LINE_COMMAND) == 0) { routineGenerator.newLine(); std::cout << ":::::: new line" << std::endl; } else if (commandPart.compare(AssemblyParser::PRINT_COMMAND) == 0) { std::cout << ":::::: new print "; routineGenerator = executePRINTCommand(command, routineGenerator); } else if (commandPart.compare(AssemblyParser::JE_COMMAND) == 0) { std::cout << ":::::: new je "; routineGenerator = executeJECommand(command, routineGenerator); } else if (commandPart.compare(AssemblyParser::QUIT_COMMAND) == 0) { routineGenerator.quitRoutine(); std::cout << ":::::: new quit" << std::endl; } else if (commandPart.compare(AssemblyParser::READ_CHAR_COMMAND) == 0) { routineGenerator = executeREADCommand(command, routineGenerator); std::cout << ":::::: new read" << std::endl; } else if (commandPart.compare(AssemblyParser::CALL_COMMAND) == 0) { std::cout << ":::::: new call "; routineGenerator = executeCALLCommand(command, routineGenerator); } else if(command.compare(AssemblyParser::JUMP_COMMAND) == 0) { std::cout << ":::::: new jump "; routineGenerator = executeJUMPCommand(command, routineGenerator); } else { // TODO: handle this error more appropriately std::cout << "unknown command: " << command << std::endl; throw; } return routineGenerator; } bool AssemblyParser::checkIfCommandRoutineStart(const std::string &command) { std::vector <std::string> commandParts = this->split(command, ' '); for (unsigned int i = 0; i < commandParts.size(); i++) { if (commandParts.at(i).compare(ROUTINE_DIRECTIVE) == 0) { return true; } } return false; } uint8_t AssemblyParser::getAddressForId(const std::string& id) { // TODO: check local variables if(id.compare("sp") == 0) { return 0x0; } // check global variables try { return globalVariableStack.at(id); } catch(std::out_of_range) { std::cout << "Could not find global " << id << std::endl; throw; } } std::vector <std::string> &AssemblyParser::split(const std::string &s, char delim, std::vector <std::string> &elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } std::vector <std::string> AssemblyParser::split(const std::string &s, char delim) { std::vector <std::string> elems; split(s, delim, elems); return elems; } std::vector <std::string> AssemblyParser::split(const std::string &s, const std::string &delim) { std::string s_copy = s; size_t pos = 0; std::string token; std::vector<std::string> tokens; while ((pos = s_copy.find(delim)) != std::string::npos) { token = s_copy.substr(0, pos); std::cout << "found token " << token << std::endl; tokens.push_back(token); s_copy.erase(0, pos + delim.length()); } tokens.push_back(s_copy); return tokens; } <commit_msg>trims extraneous spaces<commit_after>// // Created by manuel on 08.06.15. // #include "AssemblyParser.h" #include <fstream> #include <sstream> #include <string> #include <algorithm> #include <bitset> #include <cstdint> const std::string AssemblyParser::ROUTINE_DIRECTIVE = ".FUNCT"; const std::string AssemblyParser::GVAR_DIRECTIVE = ".GVAR"; const std::string AssemblyParser::NEW_LINE_COMMAND = "new_line"; const std::string AssemblyParser::PRINT_COMMAND = "print"; const std::string AssemblyParser::JE_COMMAND = "je"; const std::string AssemblyParser::QUIT_COMMAND = "quit"; const std::string AssemblyParser::READ_CHAR_COMMAND = "read_char"; const std::string AssemblyParser::CALL_COMMAND = "call"; const std::string AssemblyParser::JUMP_COMMAND = "jump"; const char AssemblyParser::SPLITTER_BETWEEN_LEXEMES_IN_AN_COMMAND = ' '; // 9 is ascii for tab const char AssemblyParser::STRING_IDENTIFIER = '\"'; // 9 is ascii for tab const std::string AssemblyParser::ASSIGNMENT_OPERATOR = "->"; std::string trim(const std::string& str, const std::string& whitespace = " \t") { const auto strBegin = str.find_first_not_of(whitespace); if (strBegin == std::string::npos) return ""; // no content const auto strEnd = str.find_last_not_of(whitespace); const auto strRange = strEnd - strBegin + 1; return str.substr(strBegin, strRange); } void AssemblyParser::readAssembly(std::istream& input, std::vector <std::bitset<8>> &highMemoryZcode, size_t offset) { std::cout << "Compiler: Parse Assembly File\n"; for(std::string line; getline(input, line);) { line = trim(line); std::vector<std::string> lineComps; this->split(line, SPLITTER_BETWEEN_LEXEMES_IN_AN_COMMAND, lineComps); if(lineComps.size()) { std::string firstComp = lineComps.at(0); if(line.at(0) == '.') { // directive if(firstComp.compare(ROUTINE_DIRECTIVE) == 0) { std::cout << "found routine" << std::endl; if(lineComps.size() < 2) { std::cerr << "invalid routine declaration" << std::endl; throw; } // currentGenerator exists, so we can get its code if(currentGenerator) { finishRoutine(highMemoryZcode); } std::string routineName = lineComps.at(1); currentGenerator.reset(new RoutineGenerator(routineName, 0, highMemoryZcode, offset)); } else if(firstComp.compare(GVAR_DIRECTIVE) == 0) { std::cout << "found gvar" << std::endl; this->split(line, SPLITTER_BETWEEN_LEXEMES_IN_AN_COMMAND, lineComps); if(lineComps.size() < 2) { std::cerr << "empty gvar declaration" << std::endl; } std::string gvar = lineComps.at(1); addGlobal(gvar); } } else { // normal instruction // check for label auto pos = line.find(":"); if(pos != std::string::npos) { std::cout << ":::::: new label: "; std::string labelName = line.substr(0, pos); currentGenerator->newLabel(labelName); std::cout << labelName << std::endl; std::string afterLabel = line.substr(pos + 1, line.length() - 1); executeCommand(trim(afterLabel), *currentGenerator); } else { executeCommand(line, *currentGenerator); } } } } if(currentGenerator) { finishRoutine(highMemoryZcode); } } void AssemblyParser::finishRoutine(std::vector <std::bitset<8>> &highMemoryZcode) { std::cout << "adding routine to zcode" << std::endl; auto routineCode = currentGenerator->getRoutine(); Utils::append(highMemoryZcode, routineCode); } void AssemblyParser::addGlobal(std::string globalName) { // TODO: check if maximum gvar limit is reached unsigned index = (unsigned) globalVariableStack.size(); std::cout << "adding gvar " << globalName << " at index " << std::to_string(index) << std::endl; this->globalVariableStack[globalName] = index; } RoutineGenerator& AssemblyParser::executePRINTCommand(const std::string &printCommand, RoutineGenerator &routineGenerator) { std::vector <std::string> commandParts = this->split(printCommand, AssemblyParser::STRING_IDENTIFIER); routineGenerator.printString(commandParts.at(1)); std::cout << commandParts.at(1) << std::endl; return routineGenerator; } RoutineGenerator& AssemblyParser::executeREADCommand(const std::string &readCommand, RoutineGenerator &routineGenerator) { //this->globalVariableStack.insert(std::pair<std::string, int>("sp", variableUsed)); std::vector <std::string> commandParts = this->split(readCommand, AssemblyParser::ASSIGNMENT_OPERATOR); if(commandParts.size() < 2) { // TODO: decide on whether to allow no args for read_char return routineGenerator; } auto last = trim(commandParts.back()); routineGenerator.readChar(getAddressForId(last)); //TODO: get available address return routineGenerator; } RoutineGenerator& AssemblyParser::executeJECommand(const std::string &jeCommand, RoutineGenerator &routineGenerator) { std::vector <std::string> commandParts = this->split(jeCommand, '?'); std::string label = commandParts.at(1); std::cout << label << std::endl; routineGenerator.jumpEquals(label, true, 0x10, 49, true, false); return routineGenerator; } RoutineGenerator& AssemblyParser::executeJUMPCommand(const std::string &jumpCommand, RoutineGenerator &routineGenerator) { std::vector <std::string> commandParts = this->split(jumpCommand, '?'); std::string label = commandParts.at(1); std::cout << label << std::endl; routineGenerator.jump(label); return routineGenerator; } RoutineGenerator& AssemblyParser::executeCALLCommand(const std::string &callCommand, RoutineGenerator &routineGenerator) { std::vector <std::string> commandParts = this->split(callCommand, ' '); std::string callRoutineName = commandParts.at(1); std::cout << callRoutineName << std::endl; routineGenerator.callRoutine(callRoutineName); return routineGenerator; } RoutineGenerator& AssemblyParser::executeCommand(const std::string& command, RoutineGenerator &routineGenerator) { std::vector <std::string> commandParts = this->split(command, AssemblyParser::SPLITTER_BETWEEN_LEXEMES_IN_AN_COMMAND); if(!commandParts.size()) return routineGenerator; std::string commandPart = commandParts.at(0); if (commandPart.compare(AssemblyParser::NEW_LINE_COMMAND) == 0) { routineGenerator.newLine(); std::cout << ":::::: new line" << std::endl; } else if (commandPart.compare(AssemblyParser::PRINT_COMMAND) == 0) { std::cout << ":::::: new print "; routineGenerator = executePRINTCommand(command, routineGenerator); } else if (commandPart.compare(AssemblyParser::JE_COMMAND) == 0) { std::cout << ":::::: new je "; routineGenerator = executeJECommand(command, routineGenerator); } else if (commandPart.compare(AssemblyParser::QUIT_COMMAND) == 0) { routineGenerator.quitRoutine(); std::cout << ":::::: new quit" << std::endl; } else if (commandPart.compare(AssemblyParser::READ_CHAR_COMMAND) == 0) { routineGenerator = executeREADCommand(command, routineGenerator); std::cout << ":::::: new read" << std::endl; } else if (commandPart.compare(AssemblyParser::CALL_COMMAND) == 0) { std::cout << ":::::: new call "; routineGenerator = executeCALLCommand(command, routineGenerator); } else if(command.compare(AssemblyParser::JUMP_COMMAND) == 0) { std::cout << ":::::: new jump "; routineGenerator = executeJUMPCommand(command, routineGenerator); } else { // TODO: handle this error more appropriately std::cout << "unknown command: " << command << std::endl; throw; } return routineGenerator; } bool AssemblyParser::checkIfCommandRoutineStart(const std::string &command) { std::vector <std::string> commandParts = this->split(command, ' '); for (unsigned int i = 0; i < commandParts.size(); i++) { if (commandParts.at(i).compare(ROUTINE_DIRECTIVE) == 0) { return true; } } return false; } uint8_t AssemblyParser::getAddressForId(const std::string& id) { // TODO: check local variables if(id.compare("sp") == 0) { return 0x0; } // check global variables try { return globalVariableStack.at(id); } catch(std::out_of_range) { std::cout << "Could not find global " << id << std::endl; throw; } } std::vector <std::string> &AssemblyParser::split(const std::string &s, char delim, std::vector <std::string> &elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } std::vector <std::string> AssemblyParser::split(const std::string &s, char delim) { std::vector <std::string> elems; split(s, delim, elems); return elems; } std::vector <std::string> AssemblyParser::split(const std::string &s, const std::string &delim) { std::string s_copy = s; size_t pos = 0; std::string token; std::vector<std::string> tokens; while ((pos = s_copy.find(delim)) != std::string::npos) { token = s_copy.substr(0, pos); std::cout << "found token " << token << std::endl; tokens.push_back(token); s_copy.erase(0, pos + delim.length()); } tokens.push_back(s_copy); return tokens; } <|endoftext|>
<commit_before>// [AsmJit] // Complete x86/x64 JIT and Remote Assembler for C++. // // [License] // Zlib - See LICENSE.md file in the package. // [Export] #define ASMJIT_EXPORTS // [Dependencies - AsmJit] #include "../base/cputicks.h" // [Dependencies - Posix] #if defined(ASMJIT_OS_POSIX) # include <time.h> # include <unistd.h> #endif // ASMJIT_OS_POSIX // [Dependencies - Mac] #if defined(ASMJIT_OS_MAC) # include <mach/mach_time.h> #endif // ASMJIT_OS_MAC // [Api-Begin] #include "../apibegin.h" namespace asmjit { // ============================================================================ // [asmjit::CpuTicks - Windows] // ============================================================================ #if defined(ASMJIT_OS_WINDOWS) static volatile uint32_t CpuTicks_hiResOk; static volatile double CpuTicks_hiResFreq; uint32_t CpuTicks::now() { do { uint32_t hiResOk = CpuTicks_hiResOk; if (hiResOk == 1) { LARGE_INTEGER now; if (!::QueryPerformanceCounter(&now)) break; return (int64_t)(double(now.QuadPart) / CpuTicks_hiResFreq); } if (hiResOk == 0) { LARGE_INTEGER qpf; if (!::QueryPerformanceFrequency(&qpf)) { _InterlockedCompareExchange((LONG*)&CpuTicks_hiResOk, 0xFFFFFFFF, 0); break; } LARGE_INTEGER now; if (!::QueryPerformanceCounter(&now)) { _InterlockedCompareExchange((LONG*)&CpuTicks_hiResOk, 0xFFFFFFFF, 0); break; } double freqDouble = double(qpf.QuadPart) / 1000.0; CpuTicks_hiResFreq = freqDouble; _InterlockedCompareExchange((LONG*)&CpuTicks_hiResOk, 1, 0); return static_cast<uint32_t>( static_cast<int64_t>(double(now.QuadPart) / freqDouble) & 0xFFFFFFFF); } } while (0); // Bail to mmsystem. return ::GetTickCount(); } // ============================================================================ // [asmjit::CpuTicks - Mac] // ============================================================================ #elif defined(ASMJIT_OS_MAC) static mach_timebase_info_data_t CpuTicks_machTime; uint32_t CpuTicks::now() { // Initialize the first time CpuTicks::now() is called (See Apple's QA1398). if (CpuTicks_machTime.denom == 0) { if (mach_timebase_info(&CpuTicks_machTime) != KERN_SUCCESS); return 0; } // mach_absolute_time() returns nanoseconds, we need just milliseconds. uint64_t t = mach_absolute_time() / 1000000; t = t * CpuTicks_machTime.numer / CpuTicks_machTime.denom; return static_cast<uint32_t>(t & 0xFFFFFFFFU); } // ============================================================================ // [asmjit::CpuTicks - Posix] // ============================================================================ #else uint32_t CpuTicks::now() { #if defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0 struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) return 0; uint64_t t = (uint64_t(ts.tv_sec ) * 1000) + (uint64_t(ts.tv_nsec) / 1000000); return static_cast<uint32_t>(t & 0xFFFFFFFFU); #else // _POSIX_MONOTONIC_CLOCK #error "AsmJit - Unsupported OS." return 0; #endif // _POSIX_MONOTONIC_CLOCK } #endif // ASMJIT_OS } // asmjit namespace // [Api-End] #include "../apiend.h" <commit_msg>Minor.<commit_after>// [AsmJit] // Complete x86/x64 JIT and Remote Assembler for C++. // // [License] // Zlib - See LICENSE.md file in the package. // [Export] #define ASMJIT_EXPORTS // [Dependencies - AsmJit] #include "../base/cputicks.h" // [Dependencies - Posix] #if defined(ASMJIT_OS_POSIX) # include <time.h> # include <unistd.h> #endif // ASMJIT_OS_POSIX // [Dependencies - Mac] #if defined(ASMJIT_OS_MAC) # include <mach/mach_time.h> #endif // ASMJIT_OS_MAC // [Api-Begin] #include "../apibegin.h" namespace asmjit { // ============================================================================ // [asmjit::CpuTicks - Windows] // ============================================================================ #if defined(ASMJIT_OS_WINDOWS) static volatile uint32_t CpuTicks_hiResOk; static volatile double CpuTicks_hiResFreq; uint32_t CpuTicks::now() { do { uint32_t hiResOk = CpuTicks_hiResOk; if (hiResOk == 1) { LARGE_INTEGER now; if (!::QueryPerformanceCounter(&now)) break; return (int64_t)(double(now.QuadPart) / CpuTicks_hiResFreq); } if (hiResOk == 0) { LARGE_INTEGER qpf; if (!::QueryPerformanceFrequency(&qpf)) { _InterlockedCompareExchange((LONG*)&CpuTicks_hiResOk, 0xFFFFFFFF, 0); break; } LARGE_INTEGER now; if (!::QueryPerformanceCounter(&now)) { _InterlockedCompareExchange((LONG*)&CpuTicks_hiResOk, 0xFFFFFFFF, 0); break; } double freqDouble = double(qpf.QuadPart) / 1000.0; CpuTicks_hiResFreq = freqDouble; _InterlockedCompareExchange((LONG*)&CpuTicks_hiResOk, 1, 0); return static_cast<uint32_t>( static_cast<int64_t>(double(now.QuadPart) / freqDouble) & 0xFFFFFFFF); } } while (0); // Bail to a less precise GetTickCount(). return ::GetTickCount(); } // ============================================================================ // [asmjit::CpuTicks - Mac] // ============================================================================ #elif defined(ASMJIT_OS_MAC) static mach_timebase_info_data_t CpuTicks_machTime; uint32_t CpuTicks::now() { // Initialize the first time CpuTicks::now() is called (See Apple's QA1398). if (CpuTicks_machTime.denom == 0) { if (mach_timebase_info(&CpuTicks_machTime) != KERN_SUCCESS); return 0; } // mach_absolute_time() returns nanoseconds, we need just milliseconds. uint64_t t = mach_absolute_time() / 1000000; t = t * CpuTicks_machTime.numer / CpuTicks_machTime.denom; return static_cast<uint32_t>(t & 0xFFFFFFFFU); } // ============================================================================ // [asmjit::CpuTicks - Posix] // ============================================================================ #else uint32_t CpuTicks::now() { #if defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0 struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) return 0; uint64_t t = (uint64_t(ts.tv_sec ) * 1000) + (uint64_t(ts.tv_nsec) / 1000000); return static_cast<uint32_t>(t & 0xFFFFFFFFU); #else // _POSIX_MONOTONIC_CLOCK #error "AsmJit - Unsupported OS." return 0; #endif // _POSIX_MONOTONIC_CLOCK } #endif // ASMJIT_OS } // asmjit namespace // [Api-End] #include "../apiend.h" <|endoftext|>
<commit_before>/*---------------------------------------------------------------------------*\ * OpenSG * * * * * * Copyright (C) 2000-2002 by the OpenSG Forum * * * * www.opensg.org * * * * contact: [email protected], [email protected], [email protected] * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * License * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Library General Public License as published * * by the Free Software Foundation, version 2. * * * * This library is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; ifnot, write to the Free Software * * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * Changes * * * * * * * * * * * * * \*---------------------------------------------------------------------------*/ //--------------------------------------------------------------------------- // Includes //--------------------------------------------------------------------------- #include <cstdlib> #include <cstdio> #include "OSGConfig.h" #include "OSGGL.h" #include "OSGFieldContainer.h" #include "OSGNode.h" #include "OSGAction.h" #include "OSGViewport.h" #include "OSGCamera.h" #include "OSGWindow.h" #include "OSGBackground.h" #include "OSGGradientBackground.h" #include "OSGTileCameraDecorator.h" #include "OSGDrawEnv.h" OSG_USING_NAMESPACE // Documentation for this class is emited in the // OSGGradientBackgroundBase.cpp file. // To modify it, please change the .fcd file (OSGGradientBackground.fcd) and // regenerate the base file. /***************************************************************************\ * Class variables * \***************************************************************************/ const OSG::BitVector GradientBackground::LineFieldMask = (GradientBackground::PositionFieldMask | GradientBackground::ColorFieldMask ); /***************************************************************************\ * Class methods * \***************************************************************************/ void GradientBackground::initMethod(InitPhase ePhase) { Inherited::initMethod(ePhase); } /***************************************************************************\ * Instance methods * \***************************************************************************/ /*------------- constructors & destructors --------------------------------*/ GradientBackground::GradientBackground(void) : Inherited() { } GradientBackground::GradientBackground(const GradientBackground &source) : Inherited(source) { } GradientBackground::~GradientBackground(void) { } void GradientBackground::changed(ConstFieldMaskArg whichField, UInt32 origin, BitVector details) { Inherited::changed(whichField, origin, details); } /*-------------------------- your_category---------------------------------*/ void GradientBackground::clear(DrawEnv *pEnv) { Int32 bit = getClearStencilBit(); glClearDepth(1.f); if(_mfPosition.size() < 2) { Real32 r = 0.f, g = 0.f, b = 0.f; if(_mfPosition.size() == 1) { Color3f col = _mfColor[0]; col.getValuesRGB(r, g, b); } glClearColor(r, g, b, 1); if (bit >= 0) { glClearStencil(bit); glClear((GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT )); } else { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } } else { glPushAttrib(GL_POLYGON_BIT | GL_DEPTH_BUFFER_BIT | GL_LIGHTING_BIT); glDisable(GL_LIGHTING); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glDisable(GL_DEPTH_TEST); glDisable(GL_COLOR_MATERIAL); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); #if 0 UInt32 width = pEnv->getPixelWidth(), height = pEnv->getPixelHeight(); Camera *cP = getCPtr(pPort->getCamera()); TileCameraDecorator *cdP = dynamic_cast<TileCameraDecorator*>(cP); while(cdP != NULL) { width = cdP->getFullWidth() ? cdP->getFullWidth() : width; height = cdP->getFullHeight() ? cdP->getFullHeight() : height; cP = getCPtr(cdP->getDecoratee()); cdP = dynamic_cast<TileCameraDecorator*>(cP); } cP = getCPtr(pEnv->getCamera()); cdP = dynamic_cast<TileCameraDecorator*>(cP); if(cdP != NULL) { Real32 left = cdP->getLeft(), right = cdP->getRight(), top = cdP->getTop(), bottom = cdP->getBottom(); glOrtho(left , right, bottom, top, 0, 1); } else { glOrtho(0, 1, 0, 1, 0, 1); } #endif glOrtho(pEnv->getPixelLeft (), pEnv->getPixelRight (), pEnv->getPixelBottom(), pEnv->getPixelTop (), 0.f, 1.f); Real32 r1, g1, b1; UInt32 size = _mfPosition.size(); glBegin(GL_QUAD_STRIP); Real32 pos = _mfPosition[0]; if(pos > 0) { glColor3f(0.0, 0.0, 0.0); glVertex3f(0, 0, 0); glVertex3f(1, 0, 0); } for(UInt32 i = 0; i < size; i++) { pos = _mfPosition[i]; Color3f col1 = _mfColor[i]; col1.getValuesRGB(r1, g1, b1); glColor3f(r1, g1, b1); glVertex3f(0, pos, 0); glVertex3f(1, pos, 0); } if(pos < 1) { glColor3f(0.0, 0.0, 0.0); glVertex3f(0, 1, 0); glVertex3f(1, 1, 0); } glEnd(); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); glPopAttrib(); if(bit >= 0) { glClearStencil(bit); glClear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); } else { glClear(GL_DEPTH_BUFFER_BIT); } } } /*------------------------------- dump ----------------------------------*/ void GradientBackground::dump( UInt32 OSG_CHECK_ARG(uiIndent), const BitVector OSG_CHECK_ARG(bvFlags)) const { SLOG << "Dump GradientBackground NI" << std::endl; } <commit_msg>fixed: make GradientBackground respect Backgound field values don't use viewport pixel size for glOrtho<commit_after>/*---------------------------------------------------------------------------*\ * OpenSG * * * * * * Copyright (C) 2000-2002 by the OpenSG Forum * * * * www.opensg.org * * * * contact: [email protected], [email protected], [email protected] * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * License * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Library General Public License as published * * by the Free Software Foundation, version 2. * * * * This library is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; ifnot, write to the Free Software * * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * Changes * * * * * * * * * * * * * \*---------------------------------------------------------------------------*/ //--------------------------------------------------------------------------- // Includes //--------------------------------------------------------------------------- #include <cstdlib> #include <cstdio> #include "OSGConfig.h" #include "OSGGL.h" #include "OSGFieldContainer.h" #include "OSGNode.h" #include "OSGAction.h" #include "OSGViewport.h" #include "OSGCamera.h" #include "OSGWindow.h" #include "OSGBackground.h" #include "OSGGradientBackground.h" #include "OSGTileCameraDecorator.h" #include "OSGDrawEnv.h" OSG_USING_NAMESPACE // Documentation for this class is emited in the // OSGGradientBackgroundBase.cpp file. // To modify it, please change the .fcd file (OSGGradientBackground.fcd) and // regenerate the base file. /***************************************************************************\ * Class variables * \***************************************************************************/ const OSG::BitVector GradientBackground::LineFieldMask = (GradientBackground::PositionFieldMask | GradientBackground::ColorFieldMask ); /***************************************************************************\ * Class methods * \***************************************************************************/ void GradientBackground::initMethod(InitPhase ePhase) { Inherited::initMethod(ePhase); } /***************************************************************************\ * Instance methods * \***************************************************************************/ /*------------- constructors & destructors --------------------------------*/ GradientBackground::GradientBackground(void) : Inherited() { } GradientBackground::GradientBackground(const GradientBackground &source) : Inherited(source) { } GradientBackground::~GradientBackground(void) { } void GradientBackground::changed(ConstFieldMaskArg whichField, UInt32 origin, BitVector details) { Inherited::changed(whichField, origin, details); } /*-------------------------- your_category---------------------------------*/ void GradientBackground::clear(DrawEnv *pEnv) { Int32 stencilBit = getClearStencilBit(); // 0x0 GLbitfield clearMask = 0; if(getClearColor() == true) { if(_mfPosition.size() < 2) { // too few positions for a real gradient - just clear the buffer clearMask |= GL_COLOR_BUFFER_BIT; if(_mfPosition.size() == 1) { const Color3f &col = _mfColor[0]; GLP::glClearColor(col[0], col[1], col[2], 1.0); } } else { // draw gradient - don't need to clear the color buffer glPushAttrib(GL_POLYGON_BIT | GL_DEPTH_BUFFER_BIT | GL_LIGHTING_BIT ); glDisable(GL_LIGHTING); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glDisable(GL_DEPTH_TEST); glDisable(GL_COLOR_MATERIAL); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); // FIXME This does not work with TileCameraDecorator glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0); UInt32 size = _mfPosition.size(); glBegin(GL_QUAD_STRIP); Real32 pos = _mfPosition[0]; if(pos > 0.0f) { glColor3f(0.0, 0.0, 0.0); glVertex3f(0, 0, 0); glVertex3f(1, 0, 0); } for(UInt32 i = 0; i < size; i++) { pos = _mfPosition[i]; const Color3f &col = _mfColor[i]; glColor3f(col[0], col[1], col[2]); glVertex3f(0, pos, 0); glVertex3f(1, pos, 0); } if(pos < 1.0f) { glColor3f(0.0, 0.0, 0.0); glVertex3f(0, 1, 0); glVertex3f(1, 1, 0); } glEnd(); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); glPopAttrib(); } } if(getClearDepth() == true) { clearMask |= GL_DEPTH_BUFFER_BIT; GLP::glClearDepth(getDepth()); } if(stencilBit >= 0) { clearMask |= GL_STENCIL_BUFFER_BIT; glClearStencil(stencilBit); } if(clearMask != 0) { glClear(clearMask); } } /*------------------------------- dump ----------------------------------*/ void GradientBackground::dump( UInt32 OSG_CHECK_ARG(uiIndent), const BitVector OSG_CHECK_ARG(bvFlags)) const { SLOG << "Dump GradientBackground NI" << std::endl; } <|endoftext|>
<commit_before>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * RDMCommandTest.cpp * Test fixture for the RDMCommand classes * Copyright (C) 2010 Simon Newton */ #include <cppunit/extensions/HelperMacros.h> #include <string> #include <iomanip> #include "ola/Logging.h" #include "ola/rdm/RDMCommand.h" #include "ola/rdm/UID.h" using std::string; using ola::rdm::RDMCommand; using ola::rdm::RDMRequest; using ola::rdm::RDMGetRequest; using ola::rdm::RDMSetRequest; using ola::rdm::RDMResponse; using ola::rdm::UID; class RDMCommandTest: public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(RDMCommandTest); CPPUNIT_TEST(testRDMCommand); CPPUNIT_TEST(testRequestInflation); CPPUNIT_TEST(testResponseInflation); CPPUNIT_TEST_SUITE_END(); public: void setUp(); void testRDMCommand(); void testRequestInflation(); void testResponseInflation(); private: void PackAndVerify(const RDMCommand &command, const uint8_t *expected, unsigned int expected_length); void UpdateChecksum(uint8_t *expected, unsigned int expected_length); static uint8_t EXPECTED_GET_BUFFER[]; static uint8_t EXPECTED_SET_BUFFER[]; static uint8_t EXPECTED_GET_RESPONSE_BUFFER[]; }; CPPUNIT_TEST_SUITE_REGISTRATION(RDMCommandTest); uint8_t RDMCommandTest::EXPECTED_GET_BUFFER[] = { 1, 24, // sub code & length 0, 3, 0, 0, 0, 4, // dst uid 0, 1, 0, 0, 0, 2, // src uid 0, 1, 0, 0, 10, // transaction, port id, msg count & sub device 32, 1, 40, 0, // command, param id, param data length 0, 0 // checksum, filled in below }; uint8_t RDMCommandTest::EXPECTED_SET_BUFFER[] = { 1, 28, // sub code & length 0, 3, 0, 0, 0, 4, // dst uid 0, 1, 0, 0, 0, 2, // src uid 0, 1, 0, 0, 10, // transaction, port id, msg count & sub device 48, 1, 40, 4, // command, param id, param data length 0xa5, 0xa5, 0xa5, 0xa5, // param data 0, 0 // checksum, filled in below }; uint8_t RDMCommandTest::EXPECTED_GET_RESPONSE_BUFFER[] = { 1, 28, // sub code & length 0, 3, 0, 0, 0, 4, // dst uid 0, 1, 0, 0, 0, 2, // src uid 0, 1, 0, 0, 10, // transaction, port id, msg count & sub device 33, 1, 40, 4, // command, param id, param data length 0x5a, 0x5a, 0x5a, 0x5a, // param data 0, 0 // checksum, filled in below }; /* * Fill in the checksums */ void RDMCommandTest::setUp() { ola::InitLogging(ola::OLA_LOG_INFO, ola::OLA_LOG_STDERR); UpdateChecksum(EXPECTED_GET_BUFFER, sizeof(EXPECTED_GET_BUFFER)); UpdateChecksum(EXPECTED_SET_BUFFER, sizeof(EXPECTED_SET_BUFFER)); UpdateChecksum(EXPECTED_GET_RESPONSE_BUFFER, sizeof(EXPECTED_GET_RESPONSE_BUFFER)); } /* * Test the RDMCommands work. */ void RDMCommandTest::testRDMCommand() { UID source(1, 2); UID destination(3, 4); RDMGetRequest command(source, destination, 0, // transaction # 1, // port id 0, // message count 10, // sub device 296, // param id NULL, // data 0); // data length CPPUNIT_ASSERT_EQUAL(source, command.SourceUID()); CPPUNIT_ASSERT_EQUAL(destination, command.DestinationUID()); CPPUNIT_ASSERT_EQUAL((uint8_t) 0, command.TransactionNumber()); CPPUNIT_ASSERT_EQUAL((uint8_t) 1, command.PortId()); CPPUNIT_ASSERT_EQUAL((uint8_t) 0, command.MessageCount()); CPPUNIT_ASSERT_EQUAL((uint16_t) 10, command.SubDevice()); CPPUNIT_ASSERT_EQUAL(RDMCommand::GET_COMMAND, command.CommandClass()); CPPUNIT_ASSERT_EQUAL((uint16_t) 296, command.ParamId()); CPPUNIT_ASSERT_EQUAL(reinterpret_cast<uint8_t*>(NULL), command.ParamData()); CPPUNIT_ASSERT_EQUAL((unsigned int) 0, command.ParamDataSize()); CPPUNIT_ASSERT_EQUAL((unsigned int) 25, command.Size()); // try one with extra long data uint8_t *data = new uint8_t[232]; RDMGetRequest long_command(source, destination, 0, // transaction # 1, // port id 0, // message count 10, // sub device 123, // param id data, // data 232); // data length CPPUNIT_ASSERT_EQUAL((unsigned int) 231, long_command.ParamDataSize()); CPPUNIT_ASSERT_EQUAL((unsigned int) 256, long_command.Size()); PackAndVerify(command, EXPECTED_GET_BUFFER, sizeof(EXPECTED_GET_BUFFER)); uint32_t data_value = 0xa5a5a5a5; RDMSetRequest command3(source, destination, 0, // transaction # 1, // port id 0, // message count 10, // sub device 296, // param id reinterpret_cast<uint8_t*>(&data_value), // data sizeof(data_value)); // data length CPPUNIT_ASSERT_EQUAL((unsigned int) 29, command3.Size()); PackAndVerify(command3, EXPECTED_SET_BUFFER, sizeof(EXPECTED_SET_BUFFER)); delete[] data; } /* * Test that we can inflate RDM request messages correctly */ void RDMCommandTest::testRequestInflation() { RDMRequest *command = RDMRequest::InflateFromData(NULL, 10); CPPUNIT_ASSERT_EQUAL(reinterpret_cast<RDMRequest*>(NULL), command); command = RDMRequest::InflateFromData(EXPECTED_GET_BUFFER, 0); CPPUNIT_ASSERT_EQUAL(reinterpret_cast<RDMRequest*>(NULL), command); command = RDMRequest::InflateFromData( EXPECTED_GET_BUFFER, sizeof(EXPECTED_GET_BUFFER)); CPPUNIT_ASSERT(NULL != command); delete command; command = RDMRequest::InflateFromData( EXPECTED_SET_BUFFER, sizeof(EXPECTED_SET_BUFFER)); CPPUNIT_ASSERT(NULL != command); uint8_t expected_data[] = {0xa5, 0xa5, 0xa5, 0xa5}; CPPUNIT_ASSERT_EQUAL((unsigned int) 4, command->ParamDataSize()); CPPUNIT_ASSERT(0 == memcmp(expected_data, command->ParamData(), command->ParamDataSize())); delete command; // change the param length and make sure the checksum fails uint8_t *bad_packet = new uint8_t[sizeof(EXPECTED_GET_BUFFER)]; memcpy(bad_packet, EXPECTED_GET_BUFFER, sizeof(EXPECTED_GET_BUFFER)); bad_packet[22] = 255; command = RDMRequest::InflateFromData( bad_packet, sizeof(EXPECTED_GET_BUFFER)); CPPUNIT_ASSERT(NULL == command); // now make sure we can't pass a bad param length larger than the buffer UpdateChecksum(bad_packet, sizeof(EXPECTED_GET_BUFFER)); command = RDMRequest::InflateFromData( bad_packet, sizeof(EXPECTED_GET_BUFFER)); CPPUNIT_ASSERT(NULL == command); delete[] bad_packet; // change the param length of another packet and make sure the checksum fails bad_packet = new uint8_t[sizeof(EXPECTED_SET_BUFFER)]; memcpy(bad_packet, EXPECTED_SET_BUFFER, sizeof(EXPECTED_SET_BUFFER)); bad_packet[22] = 5; UpdateChecksum(bad_packet, sizeof(EXPECTED_SET_BUFFER)); command = RDMRequest::InflateFromData( bad_packet, sizeof(EXPECTED_SET_BUFFER)); CPPUNIT_ASSERT(NULL == command); delete[] bad_packet; // now try to inflate a response command = RDMRequest::InflateFromData( EXPECTED_GET_RESPONSE_BUFFER, sizeof(EXPECTED_GET_RESPONSE_BUFFER)); CPPUNIT_ASSERT_EQUAL(reinterpret_cast<RDMRequest*>(NULL), command); } /* * Calculate the checksum for a packet, and verify */ void RDMCommandTest::PackAndVerify(const RDMCommand &command, const uint8_t *expected, unsigned int expected_length) { // now check packing unsigned int buffer_size = command.Size(); uint8_t *buffer = new uint8_t[buffer_size]; CPPUNIT_ASSERT(command.Pack(buffer, &buffer_size)); for (unsigned int i = 0 ; i < expected_length; i++) { std::stringstream str; str << "Offset " << i << ", expected " << static_cast<int>(expected[i]) << ", got " << static_cast<int>(buffer[i]); CPPUNIT_ASSERT_MESSAGE(str.str(), buffer[i] == expected[i]); } delete[] buffer; } /* * Test that we can inflate RDM response correctly */ void RDMCommandTest::testResponseInflation() { RDMResponse *command = RDMResponse::InflateFromData(NULL, 10); CPPUNIT_ASSERT_EQUAL(reinterpret_cast<RDMResponse*>(NULL), command); command = RDMResponse::InflateFromData(EXPECTED_GET_RESPONSE_BUFFER, 0); CPPUNIT_ASSERT_EQUAL(reinterpret_cast<RDMResponse*>(NULL), command); command = RDMResponse::InflateFromData( EXPECTED_GET_RESPONSE_BUFFER, sizeof(EXPECTED_GET_RESPONSE_BUFFER)); CPPUNIT_ASSERT(NULL != command); uint8_t expected_data[] = {0x5a, 0x5a, 0x5a, 0x5a}; CPPUNIT_ASSERT_EQUAL((unsigned int) 4, command->ParamDataSize()); CPPUNIT_ASSERT(0 == memcmp(expected_data, command->ParamData(), command->ParamDataSize())); delete command; // change the param length and make sure the checksum fails uint8_t *bad_packet = new uint8_t[sizeof(EXPECTED_GET_RESPONSE_BUFFER)]; memcpy(bad_packet, EXPECTED_GET_RESPONSE_BUFFER, sizeof(EXPECTED_GET_RESPONSE_BUFFER)); bad_packet[22] = 255; command = RDMResponse::InflateFromData( bad_packet, sizeof(EXPECTED_GET_RESPONSE_BUFFER)); CPPUNIT_ASSERT(NULL == command); // now make sure we can't pass a bad param length larger than the buffer UpdateChecksum(bad_packet, sizeof(EXPECTED_GET_RESPONSE_BUFFER)); command = RDMResponse::InflateFromData( bad_packet, sizeof(EXPECTED_GET_RESPONSE_BUFFER)); CPPUNIT_ASSERT(NULL == command); delete[] bad_packet; // change the param length of another packet and make sure the checksum fails bad_packet = new uint8_t[sizeof(EXPECTED_SET_BUFFER)]; memcpy(bad_packet, EXPECTED_SET_BUFFER, sizeof(EXPECTED_SET_BUFFER)); bad_packet[22] = 5; UpdateChecksum(bad_packet, sizeof(EXPECTED_SET_BUFFER)); command = RDMResponse::InflateFromData( bad_packet, sizeof(EXPECTED_SET_BUFFER)); CPPUNIT_ASSERT(NULL == command); delete[] bad_packet; // now try to inflate a response command = RDMResponse::InflateFromData( EXPECTED_GET_BUFFER, sizeof(EXPECTED_GET_BUFFER)); CPPUNIT_ASSERT_EQUAL(reinterpret_cast<RDMResponse*>(NULL), command); } /* * Calculate a checksum for a packet and update it */ void RDMCommandTest::UpdateChecksum(uint8_t *expected, unsigned int expected_length) { unsigned int checksum = RDMCommand::START_CODE; for (unsigned int i = 0 ; i < expected_length - 2; i++) checksum += expected[i]; expected[expected_length - 2] = checksum >> 8; expected[expected_length - 1] = checksum & 0xff; } <commit_msg> * fix a test<commit_after>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * RDMCommandTest.cpp * Test fixture for the RDMCommand classes * Copyright (C) 2010 Simon Newton */ #include <cppunit/extensions/HelperMacros.h> #include <string.h> #include <string> #include <iomanip> #include "ola/Logging.h" #include "ola/rdm/RDMCommand.h" #include "ola/rdm/UID.h" using std::string; using ola::rdm::RDMCommand; using ola::rdm::RDMRequest; using ola::rdm::RDMGetRequest; using ola::rdm::RDMSetRequest; using ola::rdm::RDMResponse; using ola::rdm::UID; class RDMCommandTest: public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(RDMCommandTest); CPPUNIT_TEST(testRDMCommand); CPPUNIT_TEST(testRequestInflation); CPPUNIT_TEST(testResponseInflation); CPPUNIT_TEST_SUITE_END(); public: void setUp(); void testRDMCommand(); void testRequestInflation(); void testResponseInflation(); private: void PackAndVerify(const RDMCommand &command, const uint8_t *expected, unsigned int expected_length); void UpdateChecksum(uint8_t *expected, unsigned int expected_length); static uint8_t EXPECTED_GET_BUFFER[]; static uint8_t EXPECTED_SET_BUFFER[]; static uint8_t EXPECTED_GET_RESPONSE_BUFFER[]; }; CPPUNIT_TEST_SUITE_REGISTRATION(RDMCommandTest); uint8_t RDMCommandTest::EXPECTED_GET_BUFFER[] = { 1, 24, // sub code & length 0, 3, 0, 0, 0, 4, // dst uid 0, 1, 0, 0, 0, 2, // src uid 0, 1, 0, 0, 10, // transaction, port id, msg count & sub device 32, 1, 40, 0, // command, param id, param data length 0, 0 // checksum, filled in below }; uint8_t RDMCommandTest::EXPECTED_SET_BUFFER[] = { 1, 28, // sub code & length 0, 3, 0, 0, 0, 4, // dst uid 0, 1, 0, 0, 0, 2, // src uid 0, 1, 0, 0, 10, // transaction, port id, msg count & sub device 48, 1, 40, 4, // command, param id, param data length 0xa5, 0xa5, 0xa5, 0xa5, // param data 0, 0 // checksum, filled in below }; uint8_t RDMCommandTest::EXPECTED_GET_RESPONSE_BUFFER[] = { 1, 28, // sub code & length 0, 3, 0, 0, 0, 4, // dst uid 0, 1, 0, 0, 0, 2, // src uid 0, 1, 0, 0, 10, // transaction, port id, msg count & sub device 33, 1, 40, 4, // command, param id, param data length 0x5a, 0x5a, 0x5a, 0x5a, // param data 0, 0 // checksum, filled in below }; /* * Fill in the checksums */ void RDMCommandTest::setUp() { ola::InitLogging(ola::OLA_LOG_INFO, ola::OLA_LOG_STDERR); UpdateChecksum(EXPECTED_GET_BUFFER, sizeof(EXPECTED_GET_BUFFER)); UpdateChecksum(EXPECTED_SET_BUFFER, sizeof(EXPECTED_SET_BUFFER)); UpdateChecksum(EXPECTED_GET_RESPONSE_BUFFER, sizeof(EXPECTED_GET_RESPONSE_BUFFER)); } /* * Test the RDMCommands work. */ void RDMCommandTest::testRDMCommand() { UID source(1, 2); UID destination(3, 4); RDMGetRequest command(source, destination, 0, // transaction # 1, // port id 0, // message count 10, // sub device 296, // param id NULL, // data 0); // data length CPPUNIT_ASSERT_EQUAL(source, command.SourceUID()); CPPUNIT_ASSERT_EQUAL(destination, command.DestinationUID()); CPPUNIT_ASSERT_EQUAL((uint8_t) 0, command.TransactionNumber()); CPPUNIT_ASSERT_EQUAL((uint8_t) 1, command.PortId()); CPPUNIT_ASSERT_EQUAL((uint8_t) 0, command.MessageCount()); CPPUNIT_ASSERT_EQUAL((uint16_t) 10, command.SubDevice()); CPPUNIT_ASSERT_EQUAL(RDMCommand::GET_COMMAND, command.CommandClass()); CPPUNIT_ASSERT_EQUAL((uint16_t) 296, command.ParamId()); CPPUNIT_ASSERT_EQUAL(reinterpret_cast<uint8_t*>(NULL), command.ParamData()); CPPUNIT_ASSERT_EQUAL((unsigned int) 0, command.ParamDataSize()); CPPUNIT_ASSERT_EQUAL((unsigned int) 25, command.Size()); // try one with extra long data uint8_t *data = new uint8_t[232]; RDMGetRequest long_command(source, destination, 0, // transaction # 1, // port id 0, // message count 10, // sub device 123, // param id data, // data 232); // data length CPPUNIT_ASSERT_EQUAL((unsigned int) 231, long_command.ParamDataSize()); CPPUNIT_ASSERT_EQUAL((unsigned int) 256, long_command.Size()); PackAndVerify(command, EXPECTED_GET_BUFFER, sizeof(EXPECTED_GET_BUFFER)); uint32_t data_value = 0xa5a5a5a5; RDMSetRequest command3(source, destination, 0, // transaction # 1, // port id 0, // message count 10, // sub device 296, // param id reinterpret_cast<uint8_t*>(&data_value), // data sizeof(data_value)); // data length CPPUNIT_ASSERT_EQUAL((unsigned int) 29, command3.Size()); PackAndVerify(command3, EXPECTED_SET_BUFFER, sizeof(EXPECTED_SET_BUFFER)); delete[] data; } /* * Test that we can inflate RDM request messages correctly */ void RDMCommandTest::testRequestInflation() { RDMRequest *command = RDMRequest::InflateFromData(NULL, 10); CPPUNIT_ASSERT_EQUAL(reinterpret_cast<RDMRequest*>(NULL), command); command = RDMRequest::InflateFromData(EXPECTED_GET_BUFFER, 0); CPPUNIT_ASSERT_EQUAL(reinterpret_cast<RDMRequest*>(NULL), command); command = RDMRequest::InflateFromData( EXPECTED_GET_BUFFER, sizeof(EXPECTED_GET_BUFFER)); CPPUNIT_ASSERT(NULL != command); delete command; command = RDMRequest::InflateFromData( EXPECTED_SET_BUFFER, sizeof(EXPECTED_SET_BUFFER)); CPPUNIT_ASSERT(NULL != command); uint8_t expected_data[] = {0xa5, 0xa5, 0xa5, 0xa5}; CPPUNIT_ASSERT_EQUAL((unsigned int) 4, command->ParamDataSize()); CPPUNIT_ASSERT(0 == memcmp(expected_data, command->ParamData(), command->ParamDataSize())); delete command; // change the param length and make sure the checksum fails uint8_t *bad_packet = new uint8_t[sizeof(EXPECTED_GET_BUFFER)]; memcpy(bad_packet, EXPECTED_GET_BUFFER, sizeof(EXPECTED_GET_BUFFER)); bad_packet[22] = 255; command = RDMRequest::InflateFromData( bad_packet, sizeof(EXPECTED_GET_BUFFER)); CPPUNIT_ASSERT(NULL == command); // now make sure we can't pass a bad param length larger than the buffer UpdateChecksum(bad_packet, sizeof(EXPECTED_GET_BUFFER)); command = RDMRequest::InflateFromData( bad_packet, sizeof(EXPECTED_GET_BUFFER)); CPPUNIT_ASSERT(NULL == command); delete[] bad_packet; // change the param length of another packet and make sure the checksum fails bad_packet = new uint8_t[sizeof(EXPECTED_SET_BUFFER)]; memcpy(bad_packet, EXPECTED_SET_BUFFER, sizeof(EXPECTED_SET_BUFFER)); bad_packet[22] = 5; UpdateChecksum(bad_packet, sizeof(EXPECTED_SET_BUFFER)); command = RDMRequest::InflateFromData( bad_packet, sizeof(EXPECTED_SET_BUFFER)); CPPUNIT_ASSERT(NULL == command); delete[] bad_packet; // now try to inflate a response command = RDMRequest::InflateFromData( EXPECTED_GET_RESPONSE_BUFFER, sizeof(EXPECTED_GET_RESPONSE_BUFFER)); CPPUNIT_ASSERT_EQUAL(reinterpret_cast<RDMRequest*>(NULL), command); } /* * Calculate the checksum for a packet, and verify */ void RDMCommandTest::PackAndVerify(const RDMCommand &command, const uint8_t *expected, unsigned int expected_length) { // now check packing unsigned int buffer_size = command.Size(); uint8_t *buffer = new uint8_t[buffer_size]; CPPUNIT_ASSERT(command.Pack(buffer, &buffer_size)); for (unsigned int i = 0 ; i < expected_length; i++) { std::stringstream str; str << "Offset " << i << ", expected " << static_cast<int>(expected[i]) << ", got " << static_cast<int>(buffer[i]); CPPUNIT_ASSERT_MESSAGE(str.str(), buffer[i] == expected[i]); } delete[] buffer; } /* * Test that we can inflate RDM response correctly */ void RDMCommandTest::testResponseInflation() { RDMResponse *command = RDMResponse::InflateFromData(NULL, 10); CPPUNIT_ASSERT_EQUAL(reinterpret_cast<RDMResponse*>(NULL), command); command = RDMResponse::InflateFromData(EXPECTED_GET_RESPONSE_BUFFER, 0); CPPUNIT_ASSERT_EQUAL(reinterpret_cast<RDMResponse*>(NULL), command); command = RDMResponse::InflateFromData( EXPECTED_GET_RESPONSE_BUFFER, sizeof(EXPECTED_GET_RESPONSE_BUFFER)); CPPUNIT_ASSERT(NULL != command); uint8_t expected_data[] = {0x5a, 0x5a, 0x5a, 0x5a}; CPPUNIT_ASSERT_EQUAL((unsigned int) 4, command->ParamDataSize()); CPPUNIT_ASSERT(0 == memcmp(expected_data, command->ParamData(), command->ParamDataSize())); delete command; // change the param length and make sure the checksum fails uint8_t *bad_packet = new uint8_t[sizeof(EXPECTED_GET_RESPONSE_BUFFER)]; memcpy(bad_packet, EXPECTED_GET_RESPONSE_BUFFER, sizeof(EXPECTED_GET_RESPONSE_BUFFER)); bad_packet[22] = 255; command = RDMResponse::InflateFromData( bad_packet, sizeof(EXPECTED_GET_RESPONSE_BUFFER)); CPPUNIT_ASSERT(NULL == command); // now make sure we can't pass a bad param length larger than the buffer UpdateChecksum(bad_packet, sizeof(EXPECTED_GET_RESPONSE_BUFFER)); command = RDMResponse::InflateFromData( bad_packet, sizeof(EXPECTED_GET_RESPONSE_BUFFER)); CPPUNIT_ASSERT(NULL == command); delete[] bad_packet; // change the param length of another packet and make sure the checksum fails bad_packet = new uint8_t[sizeof(EXPECTED_SET_BUFFER)]; memcpy(bad_packet, EXPECTED_SET_BUFFER, sizeof(EXPECTED_SET_BUFFER)); bad_packet[22] = 5; UpdateChecksum(bad_packet, sizeof(EXPECTED_SET_BUFFER)); command = RDMResponse::InflateFromData( bad_packet, sizeof(EXPECTED_SET_BUFFER)); CPPUNIT_ASSERT(NULL == command); delete[] bad_packet; // now try to inflate a response command = RDMResponse::InflateFromData( EXPECTED_GET_BUFFER, sizeof(EXPECTED_GET_BUFFER)); CPPUNIT_ASSERT_EQUAL(reinterpret_cast<RDMResponse*>(NULL), command); } /* * Calculate a checksum for a packet and update it */ void RDMCommandTest::UpdateChecksum(uint8_t *expected, unsigned int expected_length) { unsigned int checksum = RDMCommand::START_CODE; for (unsigned int i = 0 ; i < expected_length - 2; i++) checksum += expected[i]; expected[expected_length - 2] = checksum >> 8; expected[expected_length - 1] = checksum & 0xff; } <|endoftext|>
<commit_before>/* * RewriteLink.cc * * Copyright (C) 2017 Nil Geisweiller * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the * exceptions at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public * License along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <string> #include <opencog/util/mt19937ar.h> #include <opencog/util/random.h> #include <opencog/util/Logger.h> #include <opencog/atoms/base/ClassServer.h> #include <opencog/atoms/core/TypeNode.h> #include <opencog/atomutils/TypeUtils.h> #include <opencog/atomutils/FindUtils.h> #include "LambdaLink.h" #include "RewriteLink.h" using namespace opencog; void RewriteLink::init(void) { Type t = get_type(); if (not classserver().isA(t, REWRITE_LINK)) { const std::string& tname = classserver().getTypeName(t); throw InvalidParamException(TRACE_INFO, "Expecting a RewriteLink, got %s", tname.c_str()); } } RewriteLink::RewriteLink(const Handle& vars, const Handle& body) : ScopeLink(HandleSeq({vars, body}), REWRITE_LINK), _silent(false) { init(); } RewriteLink::RewriteLink(const HandleSeq& oset, Type t) : ScopeLink(oset, t), _silent(false) { if (skip_init(t)) return; init(); } RewriteLink::RewriteLink(const Link &l) : ScopeLink(l), _silent(false) { if (skip_init(l.get_type())) return; init(); } /* ================================================================= */ inline Handle append_rand_str(const Handle& var) { std::string new_var_name = randstr(var->get_name() + "-"); return createNode(VARIABLE_NODE, new_var_name); } inline HandleSeq append_rand_str(const HandleSeq& vars) { HandleSeq new_vars; for (const Handle& h : vars) new_vars.push_back(append_rand_str(h)); return new_vars; } Handle RewriteLink::alpha_convert() const { HandleSeq vars = append_rand_str(_varlist.varseq); return alpha_convert(vars); } Handle RewriteLink::alpha_convert(const HandleSeq& vars) const { // Perform alpha conversion HandleSeq hs; for (size_t i = 0; i < get_arity(); ++i) hs.push_back(_varlist.substitute_nocheck(getOutgoingAtom(i), vars, _silent)); // Create the alpha converted scope link return createLink(hs, get_type()); } Handle RewriteLink::alpha_convert(const HandleMap& vsmap) const { HandleSeq vars; for (const Handle& var : _varlist.varseq) { auto it = vsmap.find(var); vars.push_back(it == vsmap.end() ? append_rand_str(var) : it->second); } return alpha_convert(vars); } /* ================================================================= */ Handle RewriteLink::beta_reduce(const HandleMap& vm) const { // Perform substitution over the variable declaration Handle nvardecl = substitute_vardecl(vm); // Perform substitution over the bodies HandleSeq hs = substitute_bodies(nvardecl, vm); // Filter vardecl nvardecl = filter_vardecl(nvardecl, hs); // Insert vardecl in the outgoing set, if defined if (nvardecl) { hs.insert(hs.begin(), nvardecl); } else { // Its illegal to create a PutLink that is not in the // form of a redex, i.e. doesn't have variable declarations // in it. So we must not call createLink(), below. Type t = get_type(); if (PUT_LINK == t) return hs[0]; } // Create the substituted scope. I suspect that this is a bad // idea, when nvardecl==nullptr, I mean, its just gonna be weird, // and cause issues thhrought the code ... but ... whatever. return createLink(hs, get_type()); } Handle RewriteLink::beta_reduce(const HandleSeq& vals) const { const Variables& vars = get_variables(); if (vals.size() != vars.size()) { if (1 != vals.size() or LAMBDA_LINK != vals[0]->get_type()) { if (_silent) return Handle::UNDEFINED; throw SyntaxException(TRACE_INFO, "RewriteLink has mismatched arity, expecting %lu == %lu", vars.size(), vals.size()); } // Verify that eta reduction is possible... LambdaLinkPtr lam(LambdaLinkCast(vals[0])); const Handle& body = lam->get_body(); if (body->get_arity() != vars.size()) { if (_silent) return Handle::UNDEFINED; throw SyntaxException(TRACE_INFO, "RewriteLink has mismatched eta, expecting %lu == %lu", vars.size(), body->get_arity()); } } if (1 == vals.size() and LAMBDA_LINK == vals[0]->get_type()) { // Perform a very simple-minded eta reduction. LambdaLinkPtr lam(LambdaLinkCast(vals[0])); const Handle& body = lam->get_body(); const HandleSeq& eta = body->getOutgoingSet(); HandleMap vm; for (size_t i=0; i<eta.size(); i++) vm.insert({vars.varseq[i], eta[i]}); return beta_reduce(vm); } HandleMap vm; for (size_t i=0; i<vals.size(); i++) { vm.insert({vars.varseq[i], vals[i]}); } return beta_reduce(vm); } HandleSeq RewriteLink::substitute_bodies(const Handle& nvardecl, const HandleMap& vm) const { const Variables& variables = get_variables(); return beta_reduce_bodies(nvardecl, variables.make_sequence(vm)); } HandleSeq RewriteLink::beta_reduce_bodies(const Handle& nvardecl, const HandleSeq& values) const { HandleSeq hs; for (size_t i = (get_vardecl() ? 1 : 0); i < get_arity(); ++i) { const Handle& h = getOutgoingAtom(i); hs.push_back(substitute_body(nvardecl, h, values)); } return hs; } Handle RewriteLink::substitute_body(const Handle& nvardecl, const Handle& body, const HandleSeq& values) const { Handle nbody = get_variables().substitute(body, values, _silent); nbody = consume_ill_quotations(nvardecl, nbody); return nbody; } Handle RewriteLink::substitute_vardecl(const HandleMap& vm) const { if (not get_vardecl()) return Handle::UNDEFINED; return substitute_vardecl(get_vardecl(), vm); } Handle RewriteLink::substitute_vardecl(const Handle& vardecl, const HandleMap& vm) { Type t = vardecl->get_type(); // Base cases if (t == VARIABLE_NODE) { auto it = vm.find(vardecl); // Only substitute if the variable is substituted by another variable if (it == vm.end()) return vardecl; if (it->second->get_type() == VARIABLE_NODE) return it->second; return Handle::UNDEFINED; } // Recursive cases HandleSeq oset; if (t == VARIABLE_LIST) { for (const Handle& h : vardecl->getOutgoingSet()) { Handle nh = substitute_vardecl(h, vm); if (nh) oset.push_back(nh); } if (oset.empty()) return Handle::UNDEFINED; } else if (t == TYPED_VARIABLE_LINK) { Handle new_var = substitute_vardecl(vardecl->getOutgoingAtom(0), vm); if (new_var) { oset.push_back(new_var); oset.push_back(vardecl->getOutgoingAtom(1)); } else return Handle::UNDEFINED; } else { OC_ASSERT(false, "Not implemented"); } return createLink(oset, t); } Handle RewriteLink::consume_ill_quotations() const { Handle vardecl = get_vardecl(); const Variables& variables = get_variables(); HandleSeq nouts; for (size_t i = (get_vardecl() ? 1 : 0); i < get_arity(); ++i) { Handle nbody = consume_ill_quotations(variables, getOutgoingAtom(i)); nouts.push_back(nbody); // If the new body has terms with free variables but no // vardecl it means that some quotations are missing. Rather // than adding them we set vardecl to an empty VariableList. if (not vardecl and not get_free_variables(nbody).empty()) vardecl = Handle(createVariableList(HandleSeq{})); } if (vardecl) nouts.insert(nouts.begin(), vardecl); // Recreate the scope return createLink(nouts, get_type()); } Handle RewriteLink::consume_ill_quotations(const Handle& vardecl, const Handle& h) { return consume_ill_quotations(gen_variables(h, vardecl), h); } Handle RewriteLink::consume_ill_quotations(const Variables& variables, Handle h, Quotation quotation, bool escape) { // Base case if (h->is_node()) return h; // Recursive cases Type t = h->get_type(); if (quotation.consumable(t)) { if (t == QUOTE_LINK) { Handle qh = h->getOutgoingAtom(0); // If it's a scope, check whether its vardecl is bound to // itself rather than the ancestor scope, if so the Quote // is harmful, consume it. Otherwise, for other quoted // link types, do not consume the quote and the subsequent // unquotes. if (classserver().isA(qh->get_type(), SCOPE_LINK) and not is_bound_to_ancestor(variables, qh)) { quotation.update(t); return consume_ill_quotations(variables, qh, quotation); } else { escape = true; } } else if (t == UNQUOTE_LINK) { Handle uh = h->getOutgoingAtom(0); // Either remove subsequent unquote associated by a // removed quote, or useless unquote because there are no // free variables to unquote if (not escape or get_free_variables(uh).empty()) { quotation.update(t); return consume_ill_quotations(variables, h->getOutgoingAtom(0), quotation); } } // Ignore LocalQuotes as they supposedly used only to quote // pattern matcher connectors. } quotation.update(t); HandleSeq consumed; for (const Handle outh : h->getOutgoingSet()) consumed.push_back(consume_ill_quotations(variables, outh, quotation, escape)); return createLink(consumed, t); } bool RewriteLink::is_bound_to_ancestor(const Variables& variables, const Handle& local_scope) { Handle unquote = local_scope->getOutgoingAtom(0); if (unquote->get_type() == UNQUOTE_LINK) { Handle var = unquote->getOutgoingAtom(0); return variables.is_in_varset(var); } return false; } /* ================================================================= */ DEFINE_LINK_FACTORY(RewriteLink, REWRITE_LINK); /* ===================== END OF FILE ===================== */ <commit_msg>Whoops, should not have done that!<commit_after>/* * RewriteLink.cc * * Copyright (C) 2017 Nil Geisweiller * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the * exceptions at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public * License along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <string> #include <opencog/util/mt19937ar.h> #include <opencog/util/random.h> #include <opencog/util/Logger.h> #include <opencog/atoms/base/ClassServer.h> #include <opencog/atoms/core/TypeNode.h> #include <opencog/atomutils/TypeUtils.h> #include <opencog/atomutils/FindUtils.h> #include "LambdaLink.h" #include "RewriteLink.h" using namespace opencog; void RewriteLink::init(void) { Type t = get_type(); if (not classserver().isA(t, REWRITE_LINK)) { const std::string& tname = classserver().getTypeName(t); throw InvalidParamException(TRACE_INFO, "Expecting a RewriteLink, got %s", tname.c_str()); } } RewriteLink::RewriteLink(const Handle& vars, const Handle& body) : ScopeLink(HandleSeq({vars, body}), REWRITE_LINK), _silent(false) { init(); } RewriteLink::RewriteLink(const HandleSeq& oset, Type t) : ScopeLink(oset, t), _silent(false) { if (skip_init(t)) return; init(); } RewriteLink::RewriteLink(const Link &l) : ScopeLink(l), _silent(false) { if (skip_init(l.get_type())) return; init(); } /* ================================================================= */ inline Handle append_rand_str(const Handle& var) { std::string new_var_name = randstr(var->get_name() + "-"); return createNode(VARIABLE_NODE, new_var_name); } inline HandleSeq append_rand_str(const HandleSeq& vars) { HandleSeq new_vars; for (const Handle& h : vars) new_vars.push_back(append_rand_str(h)); return new_vars; } Handle RewriteLink::alpha_convert() const { HandleSeq vars = append_rand_str(_varlist.varseq); return alpha_convert(vars); } Handle RewriteLink::alpha_convert(const HandleSeq& vars) const { // Perform alpha conversion HandleSeq hs; for (size_t i = 0; i < get_arity(); ++i) hs.push_back(_varlist.substitute_nocheck(getOutgoingAtom(i), vars, _silent)); // Create the alpha converted scope link return createLink(hs, get_type()); } Handle RewriteLink::alpha_convert(const HandleMap& vsmap) const { HandleSeq vars; for (const Handle& var : _varlist.varseq) { auto it = vsmap.find(var); vars.push_back(it == vsmap.end() ? append_rand_str(var) : it->second); } return alpha_convert(vars); } /* ================================================================= */ Handle RewriteLink::beta_reduce(const HandleMap& vm) const { // Perform substitution over the variable declaration Handle nvardecl = substitute_vardecl(vm); // Perform substitution over the bodies HandleSeq hs = substitute_bodies(nvardecl, vm); // Filter vardecl nvardecl = filter_vardecl(nvardecl, hs); // Insert vardecl in the outgoing set, if defined if (nvardecl) { hs.insert(hs.begin(), nvardecl); } else { // Its illegal to create a PutLink that is not in the // form of a redex, i.e. doesn't have variable declarations // in it. So we must not call createLink(), below. Type t = get_type(); if (PUT_LINK == t or LAMBDA_LINK == t) return hs[0]; } // Create the substituted scope. I suspect that this is a bad // idea, when nvardecl==nullptr, I mean, its just gonna be weird, // and cause issues thhrought the code ... but ... whatever. return createLink(hs, get_type()); } Handle RewriteLink::beta_reduce(const HandleSeq& vals) const { const Variables& vars = get_variables(); if (vals.size() != vars.size()) { if (1 != vals.size() or LAMBDA_LINK != vals[0]->get_type()) { if (_silent) return Handle::UNDEFINED; throw SyntaxException(TRACE_INFO, "RewriteLink has mismatched arity, expecting %lu == %lu", vars.size(), vals.size()); } // Verify that eta reduction is possible... LambdaLinkPtr lam(LambdaLinkCast(vals[0])); const Handle& body = lam->get_body(); if (body->get_arity() != vars.size()) { if (_silent) return Handle::UNDEFINED; throw SyntaxException(TRACE_INFO, "RewriteLink has mismatched eta, expecting %lu == %lu", vars.size(), body->get_arity()); } } if (1 == vals.size() and LAMBDA_LINK == vals[0]->get_type()) { // Perform a very simple-minded eta reduction. LambdaLinkPtr lam(LambdaLinkCast(vals[0])); const Handle& body = lam->get_body(); const HandleSeq& eta = body->getOutgoingSet(); HandleMap vm; for (size_t i=0; i<eta.size(); i++) vm.insert({vars.varseq[i], eta[i]}); return beta_reduce(vm); } HandleMap vm; for (size_t i=0; i<vals.size(); i++) { vm.insert({vars.varseq[i], vals[i]}); } return beta_reduce(vm); } HandleSeq RewriteLink::substitute_bodies(const Handle& nvardecl, const HandleMap& vm) const { const Variables& variables = get_variables(); return beta_reduce_bodies(nvardecl, variables.make_sequence(vm)); } HandleSeq RewriteLink::beta_reduce_bodies(const Handle& nvardecl, const HandleSeq& values) const { HandleSeq hs; for (size_t i = (get_vardecl() ? 1 : 0); i < get_arity(); ++i) { const Handle& h = getOutgoingAtom(i); hs.push_back(substitute_body(nvardecl, h, values)); } return hs; } Handle RewriteLink::substitute_body(const Handle& nvardecl, const Handle& body, const HandleSeq& values) const { Handle nbody = get_variables().substitute(body, values, _silent); nbody = consume_ill_quotations(nvardecl, nbody); return nbody; } Handle RewriteLink::substitute_vardecl(const HandleMap& vm) const { if (not get_vardecl()) return Handle::UNDEFINED; return substitute_vardecl(get_vardecl(), vm); } Handle RewriteLink::substitute_vardecl(const Handle& vardecl, const HandleMap& vm) { Type t = vardecl->get_type(); // Base cases if (t == VARIABLE_NODE) { auto it = vm.find(vardecl); // Only substitute if the variable is substituted by another variable if (it == vm.end()) return vardecl; if (it->second->get_type() == VARIABLE_NODE) return it->second; return Handle::UNDEFINED; } // Recursive cases HandleSeq oset; if (t == VARIABLE_LIST) { for (const Handle& h : vardecl->getOutgoingSet()) { Handle nh = substitute_vardecl(h, vm); if (nh) oset.push_back(nh); } if (oset.empty()) return Handle::UNDEFINED; } else if (t == TYPED_VARIABLE_LINK) { Handle new_var = substitute_vardecl(vardecl->getOutgoingAtom(0), vm); if (new_var) { oset.push_back(new_var); oset.push_back(vardecl->getOutgoingAtom(1)); } else return Handle::UNDEFINED; } else { OC_ASSERT(false, "Not implemented"); } return createLink(oset, t); } Handle RewriteLink::consume_ill_quotations() const { Handle vardecl = get_vardecl(); const Variables& variables = get_variables(); HandleSeq nouts; for (size_t i = (get_vardecl() ? 1 : 0); i < get_arity(); ++i) { Handle nbody = consume_ill_quotations(variables, getOutgoingAtom(i)); nouts.push_back(nbody); // If the new body has terms with free variables but no // vardecl it means that some quotations are missing. Rather // than adding them we set vardecl to an empty VariableList. if (not vardecl and not get_free_variables(nbody).empty()) vardecl = Handle(createVariableList(HandleSeq{})); } if (vardecl) nouts.insert(nouts.begin(), vardecl); // Recreate the scope return createLink(nouts, get_type()); } Handle RewriteLink::consume_ill_quotations(const Handle& vardecl, const Handle& h) { return consume_ill_quotations(gen_variables(h, vardecl), h); } Handle RewriteLink::consume_ill_quotations(const Variables& variables, Handle h, Quotation quotation, bool escape) { // Base case if (h->is_node()) return h; // Recursive cases Type t = h->get_type(); if (quotation.consumable(t)) { if (t == QUOTE_LINK) { Handle qh = h->getOutgoingAtom(0); // If it's a scope, check whether its vardecl is bound to // itself rather than the ancestor scope, if so the Quote // is harmful, consume it. Otherwise, for other quoted // link types, do not consume the quote and the subsequent // unquotes. if (classserver().isA(qh->get_type(), SCOPE_LINK) and not is_bound_to_ancestor(variables, qh)) { quotation.update(t); return consume_ill_quotations(variables, qh, quotation); } else { escape = true; } } else if (t == UNQUOTE_LINK) { Handle uh = h->getOutgoingAtom(0); // Either remove subsequent unquote associated by a // removed quote, or useless unquote because there are no // free variables to unquote if (not escape or get_free_variables(uh).empty()) { quotation.update(t); return consume_ill_quotations(variables, h->getOutgoingAtom(0), quotation); } } // Ignore LocalQuotes as they supposedly used only to quote // pattern matcher connectors. } quotation.update(t); HandleSeq consumed; for (const Handle outh : h->getOutgoingSet()) consumed.push_back(consume_ill_quotations(variables, outh, quotation, escape)); return createLink(consumed, t); } bool RewriteLink::is_bound_to_ancestor(const Variables& variables, const Handle& local_scope) { Handle unquote = local_scope->getOutgoingAtom(0); if (unquote->get_type() == UNQUOTE_LINK) { Handle var = unquote->getOutgoingAtom(0); return variables.is_in_varset(var); } return false; } /* ================================================================= */ DEFINE_LINK_FACTORY(RewriteLink, REWRITE_LINK); /* ===================== END OF FILE ===================== */ <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2011, 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 Willow Garage, Inc. 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$ * */ #include <gtest/gtest.h> #include <pcl/point_types.h> #include <pcl/point_cloud.h> #include <pcl/pcl_tests.h> using namespace pcl; using namespace pcl::test; PointCloud<PointXYZ> cloud; const size_t size = 10 * 480; TEST (PointCloud, size) { EXPECT_EQ(cloud.points.size (), cloud.size ()); } TEST (PointCloud, sq_brackets_wrapper) { for (uint32_t i = 0; i < size; ++i) EXPECT_EQ_VECTORS (cloud.points[i].getVector3fMap (), cloud[i].getVector3fMap ()); } TEST (PointCloud, at) { for (uint32_t i = 0; i < size; ++i) EXPECT_EQ_VECTORS (cloud.points.at (i).getVector3fMap (), cloud.at (i).getVector3fMap ()); } TEST (PointCloud, front) { EXPECT_EQ_VECTORS (cloud.points.front ().getVector3fMap (), cloud.front ().getVector3fMap ()); } TEST (PointCloud, back) { EXPECT_EQ_VECTORS (cloud.points.back ().getVector3fMap (), cloud.back ().getVector3fMap ()); } TEST (PointCloud, constructor_with_allocation) { PointCloud<PointXYZ> cloud2 (5, 80); EXPECT_EQ (cloud2.width, 5); EXPECT_EQ (cloud2.height, 80); EXPECT_EQ (cloud2.size (), 5*80); } TEST (PointCloud, insert_range) { PointCloud<PointXYZ> cloud2 (10, 1); for (uint32_t i = 0; i < 10; ++i) cloud2[i] = PointXYZ (5*i+0,5*i+1,5*i+2); uint32_t old_size = cloud.size (); cloud.insert (cloud.begin (), cloud2.begin (), cloud2.end ()); EXPECT_EQ (cloud.width, cloud.size ()); EXPECT_EQ (cloud.height, 1); EXPECT_EQ (cloud.width, old_size + cloud2.size ()); PointCloud<PointXYZ>::const_iterator pit = cloud.begin (); PointCloud<PointXYZ>::const_iterator pit2 = cloud2.begin (); for (; pit2 < cloud2.end (); ++pit2, ++pit) EXPECT_EQ_VECTORS (pit->getVector3fMap (), pit2->getVector3fMap ()); } int main (int argc, char** argv) { cloud.width = 10; cloud.height = 480; for (uint32_t i = 0; i < size; ++i) cloud.points.push_back (PointXYZ (3*i+0,3*i+1,3*i+2)); testing::InitGoogleTest (&argc, argv); return (RUN_ALL_TESTS ()); } <commit_msg>Add a test case for iterators<commit_after>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2011, 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 Willow Garage, Inc. 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$ * */ #include <gtest/gtest.h> #include <pcl/point_types.h> #include <pcl/point_cloud.h> #include <pcl/pcl_tests.h> using namespace pcl; using namespace pcl::test; PointCloud<PointXYZ> cloud; const size_t size = 10 * 480; TEST (PointCloud, size) { EXPECT_EQ(cloud.points.size (), cloud.size ()); } TEST (PointCloud, sq_brackets_wrapper) { for (uint32_t i = 0; i < size; ++i) EXPECT_EQ_VECTORS (cloud.points[i].getVector3fMap (), cloud[i].getVector3fMap ()); } TEST (PointCloud, at) { for (uint32_t i = 0; i < size; ++i) EXPECT_EQ_VECTORS (cloud.points.at (i).getVector3fMap (), cloud.at (i).getVector3fMap ()); } TEST (PointCloud, front) { EXPECT_EQ_VECTORS (cloud.points.front ().getVector3fMap (), cloud.front ().getVector3fMap ()); } TEST (PointCloud, back) { EXPECT_EQ_VECTORS (cloud.points.back ().getVector3fMap (), cloud.back ().getVector3fMap ()); } TEST (PointCloud, constructor_with_allocation) { PointCloud<PointXYZ> cloud2 (5, 80); EXPECT_EQ (cloud2.width, 5); EXPECT_EQ (cloud2.height, 80); EXPECT_EQ (cloud2.size (), 5*80); } TEST (PointCloud, iterators) { EXPECT_EQ_VECTORS (cloud.begin ()->getVector3fMap (), cloud.points.begin ()->getVector3fMap ()); EXPECT_EQ_VECTORS (cloud.end ()->getVector3fMap (), cloud.points.end ()->getVector3fMap ()); PointCloud<PointXYZ>::const_iterator pit = cloud.begin (); PointCloud<PointXYZ>::VectorType::const_iterator pit2 = cloud.points.begin (); for (; pit < cloud.end (); ++pit2, ++pit) EXPECT_EQ_VECTORS (pit->getVector3fMap (), pit2->getVector3fMap ()); } TEST (PointCloud, insert_range) { PointCloud<PointXYZ> cloud2 (10, 1); for (uint32_t i = 0; i < 10; ++i) cloud2[i] = PointXYZ (5*i+0,5*i+1,5*i+2); uint32_t old_size = cloud.size (); cloud.insert (cloud.begin (), cloud2.begin (), cloud2.end ()); EXPECT_EQ (cloud.width, cloud.size ()); EXPECT_EQ (cloud.height, 1); EXPECT_EQ (cloud.width, old_size + cloud2.size ()); PointCloud<PointXYZ>::const_iterator pit = cloud.begin (); PointCloud<PointXYZ>::const_iterator pit2 = cloud2.begin (); for (; pit2 < cloud2.end (); ++pit2, ++pit) EXPECT_EQ_VECTORS (pit->getVector3fMap (), pit2->getVector3fMap ()); } int main (int argc, char** argv) { cloud.width = 10; cloud.height = 480; for (uint32_t i = 0; i < size; ++i) cloud.points.push_back (PointXYZ (3*i+0,3*i+1,3*i+2)); testing::InitGoogleTest (&argc, argv); return (RUN_ALL_TESTS ()); } <|endoftext|>
<commit_before>#include <ros/ros.h> #include <sensor_msgs/PointCloud2.h> #include <pcl_ros/point_cloud.h> #include <pcl/point_types.h> #include <boost/thread/thread.hpp> #include <tf/transform_listener.h> #include <Eigen/Dense> ros::Publisher pub; double height; Eigen::Vector3d normal; void callback(const sensor_msgs::PointCloud2::ConstPtr& msg) { pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>()); pcl::fromROSMsg(*msg, *cloud); for (size_t i = 0; i < cloud->size(); ++i) { } sensor_msgs::PointCloud2 msg_cloud; pcl::toROSMsg(voxel_cloud, msg_cloud); msg_cloud.header.frame_id = msg->header.frame_id; pub.publish(msg_cloud); } int main(int argc, char** argv) { ros::init(argc, argv, "subsample_cloud"); ros::NodeHandle n; ros::NodeHandle pn("~"); // topic of input cloud if (!pn.hasParam("input")) { ROS_ERROR("Could not find parameter input."); return -1; } std::string input; pn.getParam("input", input); // topic of output cloud if (!pn.hasParam("obstacle_output")) { ROS_ERROR("Could not find parameter obstacle_output."); return -1; } std::string obstacle_output; pn.getParam("obstacle_output", obstacle_output); // topic of output cloud if (!pn.hasParam("camera_frame")) { ROS_ERROR("Could not find parameter camera_frame."); return -1; } std::string camera_frame; pn.getParam("camera_frame", camera_frame); // topic of output cloud if (!pn.hasParam("floor_output")) { ROS_ERROR("Could not find parameter floor_output."); return -1; } std::string floor_output; pn.getParam("floor_output", floor_output); ros::Subscriber sub = n.subscribe(input, 1, callback); pub = n.advertise<sensor_msgs::PointCloud2>(output, 1); tf::TransformListener listener; geometry_msgs::PointStamped pout; geometry_msgs::PointStamped pin; pin.point.x = 0; pin.point.y = 0; pin.point.z = 0; geometry_msgs::Vector3Stamped vout; geometry_msgs::Vector3Stamped vin; vin.vector.x = 0; vin.vector.y = 0; vin.vector.z = 1; ros::Rate rate(0.05); // updating at 5 hz, slightly faster than move_base while (n.ok()) { tf::StampedTransform transform; try { listener.lookupTransform("/base_link", camera_frame, ros::Time(0), transform); transform.transformPoint(camera_frame, ros::Time(0), pin, "/base_link", pout); height = pout.point.z; transform.transformVector3(camera_frame, ros::Time(0), vin, "/base_link", vout); normal = Eigen::Vector3d(vout.vector.x, vout.vector.y, vout.vector.z); } catch (tf::TransformException ex) { ROS_ERROR("%s",ex.what()); } rate.sleep(); ros::spinOnce(); } return 0; } <commit_msg>Got the transforms working<commit_after>#include <ros/ros.h> #include <sensor_msgs/PointCloud2.h> #include <pcl_ros/point_cloud.h> #include <pcl/point_types.h> #include <boost/thread/thread.hpp> #include <tf/transform_listener.h> #include <Eigen/Dense> ros::Publisher pub; double height; Eigen::Vector3d normal; void callback(const sensor_msgs::PointCloud2::ConstPtr& msg) { pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>()); pcl::fromROSMsg(*msg, *cloud); for (size_t i = 0; i < cloud->size(); ++i) { } sensor_msgs::PointCloud2 msg_cloud; //pcl::toROSMsg(voxel_cloud, msg_cloud); msg_cloud.header.frame_id = msg->header.frame_id; pub.publish(msg_cloud); } int main(int argc, char** argv) { ros::init(argc, argv, "subsample_cloud"); ros::NodeHandle n; ros::NodeHandle pn("~"); // topic of input cloud if (!pn.hasParam("input")) { ROS_ERROR("Could not find parameter input."); return -1; } std::string input; pn.getParam("input", input); // topic of output cloud if (!pn.hasParam("obstacle_output")) { ROS_ERROR("Could not find parameter obstacle_output."); return -1; } std::string obstacle_output; pn.getParam("obstacle_output", obstacle_output); // topic of output cloud if (!pn.hasParam("camera_frame")) { ROS_ERROR("Could not find parameter camera_frame."); return -1; } std::string camera_frame; pn.getParam("camera_frame", camera_frame); // topic of output cloud if (!pn.hasParam("floor_output")) { ROS_ERROR("Could not find parameter floor_output."); return -1; } std::string floor_output; pn.getParam("floor_output", floor_output); ros::Subscriber sub = n.subscribe(input, 1, callback); pub = n.advertise<sensor_msgs::PointCloud2>(obstacle_output, 1); std::string base_frame("map");//"base_link"); tf::TransformListener listener; geometry_msgs::PointStamped pout; geometry_msgs::PointStamped pin; pin.header.frame_id = base_frame; pin.point.x = 0; pin.point.y = 0; pin.point.z = 0; geometry_msgs::Vector3Stamped vout; geometry_msgs::Vector3Stamped vin; vin.header.frame_id = base_frame; vin.vector.x = 0; vin.vector.y = 0; vin.vector.z = 1; ros::Rate rate(5); // updating at 5 hz, slightly faster than move_base while (n.ok()) { tf::StampedTransform transform; try { //listener.lookupTransform(camera_frame, "base_link", ros::Time(0), transform); listener.transformPoint(camera_frame, ros::Time(0), pin, base_frame, pout); height = pout.point.z; listener.transformVector(camera_frame, ros::Time(0), vin, base_frame, vout); normal = Eigen::Vector3d(vout.vector.x, vout.vector.y, vout.vector.z); //std::cout << transform << std::endl; } catch (tf::TransformException ex) { ROS_ERROR("%s",ex.what()); } std::cout << height << std::endl; std::cout << normal.transpose() << std::endl; rate.sleep(); ros::spinOnce(); } return 0; } <|endoftext|>
<commit_before>#include "Accumulate.h" #include "../Data.h" VariableAccumulate::VariableAccumulate(const Options& iOptions, const Data& iData) : Variable(iOptions, iData), mTimeWindow(Global::MV) { // Which base variable should be accumulated? iOptions.getRequiredValue("baseVariable", mBaseVariable); //! Over how many hours should the variable be accumulated? //! Defaults to the beginning of the forecast period iOptions.getValue("timeWindow", mTimeWindow); loadOptionsFromBaseVariable(); iOptions.check(); } float VariableAccumulate::computeCore(int iDate, int iInit, float iOffset, const Location& iLocation, const Member& iMember, Input::Type iType) const { float total = 0; /////////////////////////////// // Accumulating observations // /////////////////////////////// // When accumulating observations, we are allowed to look at yesterday's values. // This can happen for low offsets, where the accumulation window crosses into yesterday if(iType == Input::typeObservation) { float startOffset = iOffset - mTimeWindow; // Allowed to be negative std::string dataset = iMember.getDataset(); std::vector<float> offsets = mData.getInput(dataset)->getOffsets(); for(int i = 0; i < offsets.size(); i++) { float offset = offsets[i]; if(offset < 24) { // Observations should never have offsets above 24, but just in case // Use a value from today if(offset > startOffset && offset <= iOffset) { float value = mData.getValue(iDate, iInit, offset, iLocation, iMember, mBaseVariable); if(Global::isValid(value)) total += value; else return Global::MV; } // Use a value from yesterday else if(offset > startOffset+24 && offset <= iOffset + 24) { int date = Global::getDate(iDate, -24); // yesterday float value = mData.getValue(date, iInit, offset, iLocation, iMember, mBaseVariable); if(Global::isValid(value)) total += value; else return Global::MV; } } } } //////////////////////////// // Accumulating forecasts // //////////////////////////// // Only accumulate values for forecasts valid at this initialization date/time else { if(Global::isValid(mTimeWindow) && iOffset > mTimeWindow) { // Do a regular sum between start and end offsets float startOffset = iOffset - mTimeWindow; std::string dataset = iMember.getDataset(); std::vector<float> offsets = mData.getInput(dataset)->getOffsets(); for(int i = 0; i < offsets.size(); i++) { float offset = offsets[i]; if(offset > startOffset && offset <= iOffset) { float value = mData.getValue(iDate, iInit, offset, iLocation, iMember, mBaseVariable); if(Global::isValid(value)) total += value; else return Global::MV; } } } else { return Global::MV; } } return total; } std::string VariableAccumulate::getBaseVariable() const { // TODO: std::stringstream ss; if(Global::isValid(mTimeWindow)) ss << mBaseVariable << "_" << (int) mTimeWindow; else ss << mBaseVariable << "_Acc"; return ss.str(); } <commit_msg>Fixed bug when accumulating<commit_after>#include "Accumulate.h" #include "../Data.h" VariableAccumulate::VariableAccumulate(const Options& iOptions, const Data& iData) : Variable(iOptions, iData), mTimeWindow(Global::MV) { // Which base variable should be accumulated? iOptions.getRequiredValue("baseVariable", mBaseVariable); //! Over how many hours should the variable be accumulated? //! Defaults to the beginning of the forecast period iOptions.getValue("timeWindow", mTimeWindow); loadOptionsFromBaseVariable(); iOptions.check(); } float VariableAccumulate::computeCore(int iDate, int iInit, float iOffset, const Location& iLocation, const Member& iMember, Input::Type iType) const { float total = 0; /////////////////////////////// // Accumulating observations // /////////////////////////////// // When accumulating observations, we are allowed to look at yesterday's values. // This can happen for low offsets, where the accumulation window crosses into yesterday if(iType == Input::typeObservation) { float startOffset = iOffset - mTimeWindow; // Allowed to be negative std::string dataset = iMember.getDataset(); std::vector<float> offsets = mData.getInput(dataset)->getOffsets(); for(int i = 0; i < offsets.size(); i++) { float offset = offsets[i]; if(offset < 24) { // Observations should never have offsets above 24, but just in case // Use a value from today if(offset > startOffset && offset <= iOffset) { float value = mData.getValue(iDate, iInit, offset, iLocation, iMember, mBaseVariable); if(Global::isValid(value)) total += value; else return Global::MV; } // Use a value from yesterday else if(offset > startOffset+24 && offset <= iOffset + 24) { int date = Global::getDate(iDate, -24); // yesterday float value = mData.getValue(date, iInit, offset, iLocation, iMember, mBaseVariable); if(Global::isValid(value)) total += value; else return Global::MV; } } } } //////////////////////////// // Accumulating forecasts // //////////////////////////// // Only accumulate values for forecasts valid at this initialization date/time else { if(Global::isValid(mTimeWindow) && iOffset >= mTimeWindow) { // Do a regular sum between start and end offsets float startOffset = iOffset - mTimeWindow; std::string dataset = iMember.getDataset(); std::vector<float> offsets = mData.getInput(dataset)->getOffsets(); for(int i = 0; i < offsets.size(); i++) { float offset = offsets[i]; if(offset > startOffset && offset <= iOffset) { float value = mData.getValue(iDate, iInit, offset, iLocation, iMember, mBaseVariable); if(Global::isValid(value)) total += value; else return Global::MV; } } } else { return Global::MV; } } return total; } std::string VariableAccumulate::getBaseVariable() const { // TODO: std::stringstream ss; if(Global::isValid(mTimeWindow)) ss << mBaseVariable << "_" << (int) mTimeWindow; else ss << mBaseVariable << "_Acc"; return ss.str(); } <|endoftext|>
<commit_before>#include <coffee/core/plat/linking/libraries.h> #include <coffee/core/coffee_strings.h> #if defined(COFFEE_LINUX) #include <dlfcn.h> #elif defined(COFFEE_WINDOWS) #include <Windows.h> #endif namespace Coffee{ namespace CLibraryLoader{ #if defined(COFFEE_LINUX) struct CNativeObject { void* handle; void* funptr; }; void* _coffee_dlopen(cstring fname) { void* handle = dlopen(fname,RTLD_NOW); if(!handle) { cLog(__FILE__,__LINE__,"CObjectLoader",CFStrings::Lib_load_error_format,fname); } return handle; } CNativeObject* _coffee_get_library(cstring file, cstring loaderFunction, const _cbasic_version<int32> *libver) { CNativeObject *e = new CNativeObject; CString plat_file_name = "lib"; plat_file_name += file; plat_file_name += ".so"; e->handle = _coffee_dlopen(plat_file_name.c_str()); if(libver&&!e->handle) { plat_file_name.append(cStringFormat( ".{0}.{1}.{2}", libver->major, libver->minor, libver->revision)); e->handle = _coffee_dlopen(plat_file_name.c_str()); } if(!e->handle) { delete e; return nullptr; } cstring error = nullptr; e->funptr = dlsym(e->handle,loaderFunction); if((error = dlerror()) != NULL) { cLog(__FILE__,__LINE__,CFStrings::Lib_Identifier, CFStrings::Lib_symb_error_format,error); _coffee_close_library(e); return nullptr; } return e; } void _coffee_close_library(CNativeObject* object) { if(object->handle) dlclose(object->handle); delete object; } void* _coffee_get_funptr(CNativeObject* object) { return object->funptr; } #endif #if defined(COFFEE_WINDOWS) struct CNativeObject { HINSTANCE hinstLib; void* procedure; }; CNativeObject* _coffee_get_library(cstring file, cstring loaderFunction, const _cbasic_version<int32> *libver) { CNativeObject* e = new CNativeObject; CString plat_file_name = file; plat_file_name += ".dll"; e->hinstLib = LoadLibrary(plat_file_name.c_str()); if(!e->hinstLib) { cWarning(CFStrings::Lib_load_error_format,plat_file_name.c_str()); _coffee_close_library(e); return nullptr; } e->procedure = GetProcAddress(e->hinstLib,loaderFunction); if(!e->procedure) { cWarning(CFStrings::Lib_symb_error_format,plat_file_name.c_str()); _coffee_close_library(e); return nullptr; } return e; } void _coffee_close_library(CNativeObject* library) { if(library->hinstLib) FreeLibrary(library->hinstLib); delete library; } void* _coffee_get_funptr(CNativeObject *object) { return object->procedure; } #endif } } <commit_msg> - Cast library pointer<commit_after>#include <coffee/core/plat/linking/libraries.h> #include <coffee/core/coffee_strings.h> #if defined(COFFEE_LINUX) #include <dlfcn.h> #elif defined(COFFEE_WINDOWS) #include <Windows.h> #endif namespace Coffee{ namespace CLibraryLoader{ #if defined(COFFEE_LINUX) struct CNativeObject { void* handle; void* funptr; }; void* _coffee_dlopen(cstring fname) { void* handle = dlopen(fname,RTLD_NOW); if(!handle) { cLog(__FILE__,__LINE__,"CObjectLoader",CFStrings::Lib_load_error_format,fname); } return handle; } CNativeObject* _coffee_get_library(cstring file, cstring loaderFunction, const _cbasic_version<int32> *libver) { CNativeObject *e = new CNativeObject; CString plat_file_name = "lib"; plat_file_name += file; plat_file_name += ".so"; e->handle = _coffee_dlopen(plat_file_name.c_str()); if(libver&&!e->handle) { plat_file_name.append(cStringFormat( ".{0}.{1}.{2}", libver->major, libver->minor, libver->revision)); e->handle = _coffee_dlopen(plat_file_name.c_str()); } if(!e->handle) { delete e; return nullptr; } cstring error = nullptr; e->funptr = dlsym(e->handle,loaderFunction); if((error = dlerror()) != NULL) { cLog(__FILE__,__LINE__,CFStrings::Lib_Identifier, CFStrings::Lib_symb_error_format,error); _coffee_close_library(e); return nullptr; } return e; } void _coffee_close_library(CNativeObject* object) { if(object->handle) dlclose(object->handle); delete object; } void* _coffee_get_funptr(CNativeObject* object) { return object->funptr; } #endif #if defined(COFFEE_WINDOWS) struct CNativeObject { HINSTANCE hinstLib; void* procedure; }; CNativeObject* _coffee_get_library(cstring file, cstring loaderFunction, const _cbasic_version<int32> *libver) { CNativeObject* e = new CNativeObject; CString plat_file_name = file; plat_file_name += ".dll"; e->hinstLib = LoadLibrary(plat_file_name.c_str()); if(!e->hinstLib) { cWarning(CFStrings::Lib_load_error_format,plat_file_name.c_str()); _coffee_close_library(e); return nullptr; } e->procedure = (void*)GetProcAddress(e->hinstLib,loaderFunction); if(!e->procedure) { cWarning(CFStrings::Lib_symb_error_format,plat_file_name.c_str()); _coffee_close_library(e); return nullptr; } return e; } void _coffee_close_library(CNativeObject* library) { if(library->hinstLib) FreeLibrary(library->hinstLib); delete library; } void* _coffee_get_funptr(CNativeObject *object) { return object->procedure; } #endif } } <|endoftext|>
<commit_before>/* Copyright (c) 2012 Carsten Burstedde, Donna Calhoun All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "amr_includes.H" #include "no_solver_user.H" #ifdef __cplusplus extern "C" { #if 0 } #endif #endif void no_solver_linker(fclaw2d_domain_t* domain) { link_problem_setup(domain,no_solver_setprob); /* Initialize data but don't do anything */ fclaw2d_solver_functions_t* sf = get_solver_functions(domain); sf->f_patch_initialize = &no_solver_patch_initialize; sf->f_patch_single_step_update = &no_solver_update; fclaw2d_output_functions* of = get_output_functions(domain); of->f_patch_write_header = &matlab_parallel_write_header; of->f_patch_write_output = &matlab_parallel_write_output; link_regrid_functions(domain,no_solver_patch_tag4refinement, no_solver_patch_tag4coarsening); } void no_solver_setprob(fclaw2d_domain_t* domain) { set_maptype_(); } void no_solver_patch_initialize(fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx) { set_block_(&this_block_idx); // Global parameters const amr_options_t *gparms = get_domain_parms(domain); int mx = gparms->mx; int my = gparms->my; int mbc = gparms->mbc; int meqn = gparms->meqn; // Parameters specific to this patch ClawPatch *cp = get_clawpatch(this_patch); double xlower = cp->xlower(); double ylower = cp->ylower(); double dx = cp->dx(); double dy = cp->dy(); // Pointers needed for the fortran double* q = cp->q(); int mpirank = domain->mpirank; initialize_(mx,my,meqn,mbc,xlower,ylower,dx,dy,q,mpirank); } double no_solver_update(fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx, double t, double dt) { ClawPatch *cp = get_clawpatch(this_patch); // save the current time step for time interpolation. Otherwise, we get // unitialized values. cp->save_current_step(); // Save for time interpolation // Reinitialize with new proc data /* no_solver_patch_initialize(domain,this_patch, this_block_idx,this_patch_idx); */ return 1.0; } /* ----------------------------------------------------------------- Default routine for tagging patches for refinement and coarsening ----------------------------------------------------------------- */ fclaw_bool no_solver_patch_tag4refinement(fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx, int initflag) { /* ----------------------------------------------------------- */ // Global parameters const amr_options_t *gparms = get_domain_parms(domain); int mx = gparms->mx; int my = gparms->my; int mbc = gparms->mbc; int meqn = gparms->meqn; /* ----------------------------------------------------------- */ // Patch specific parameters ClawPatch *cp = get_clawpatch(this_patch); double xlower = cp->xlower(); double ylower = cp->ylower(); double dx = cp->dx(); double dy = cp->dy(); /* ------------------------------------------------------------ */ // Pointers needed to pass to Fortran double* q = cp->q(); int tag_patch; // == 0 or 1 no_solver_tag4refinement_(mx,my,mbc,meqn,xlower,ylower,dx,dy,q,initflag,tag_patch); return tag_patch == 1; } fclaw_bool no_solver_patch_tag4coarsening(fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch, int blockno, int patchno) { // This might come in handy if we want to debug a coarsening routine without // worrying about solvers. /* ----------------------------------------------------------- */ // Global parameters const amr_options_t *gparms = get_domain_parms(domain); int mx = gparms->mx; int my = gparms->my; int mbc = gparms->mbc; int meqn = gparms->meqn; /* ----------------------------------------------------------- */ // Patch specific parameters ClawPatch *cp = get_clawpatch(this_patch); double xlower = cp->xlower(); double ylower = cp->ylower(); double dx = cp->dx(); double dy = cp->dy(); /* ------------------------------------------------------------ */ // Pointers needed to pass to Fortran double* qcoarse = cp->q(); int tag_patch; // == 0 or 1 no_solver_tag4coarsening_(mx,my,mbc,meqn,xlower,ylower,dx,dy,qcoarse,tag_patch); return tag_patch == 0; } void matlab_parallel_write_header(fclaw2d_domain_t* domain, int iframe, int ngrids) { const amr_options_t *gparms = get_domain_parms(domain); double time = get_domain_time(domain); printf("Matlab output Frame %d at time %16.8e\n\n",iframe,time); // Write out header file containing global information for 'iframe' int meqn = gparms->meqn; int maux = 0; write_tfile_(iframe,time,meqn,ngrids,maux); // This opens file 'fort.qXXXX' for replace (where XXXX = <zero padding><iframe>, e.g. 0001, // 0010, 0114), and closes the file. new_qfile_(iframe); } void matlab_parallel_write_output(fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx, int iframe,int num,int level) { // In case this is needed by the setaux routine set_block_(&this_block_idx); /* ----------------------------------------------------------- */ // Global parameters const amr_options_t *gparms = get_domain_parms(domain); int mx = gparms->mx; int my = gparms->my; int mbc = gparms->mbc; int meqn = gparms->meqn; /* ----------------------------------------------------------- */ // Patch specific parameters ClawPatch *cp = get_clawpatch(this_patch); double xlower = cp->xlower(); double ylower = cp->ylower(); double dx = cp->dx(); double dy = cp->dy(); /* ------------------------------------------------------------ */ // Pointers needed to pass to Fortran double* q = cp->q(); // Other input arguments int maxmx = mx; int maxmy = my; /* ------------------------------------------------------------- */ // This opens a file for append. Now, the style is in the 'clawout' style. int matlab_level = level + 1; write_qfile_(maxmx,maxmy,meqn,mbc,mx,my,xlower,ylower,dx,dy,q, iframe,num,matlab_level,this_block_idx); } #ifdef __cplusplus #if 0 { #endif } #endif <commit_msg>Return desired_cfl guarantees time step will never change throughout run<commit_after>/* Copyright (c) 2012 Carsten Burstedde, Donna Calhoun All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "amr_includes.H" #include "no_solver_user.H" #ifdef __cplusplus extern "C" { #if 0 } #endif #endif void no_solver_linker(fclaw2d_domain_t* domain) { link_problem_setup(domain,no_solver_setprob); /* Initialize data but don't do anything */ fclaw2d_solver_functions_t* sf = get_solver_functions(domain); sf->f_patch_initialize = &no_solver_patch_initialize; sf->f_patch_single_step_update = &no_solver_update; fclaw2d_output_functions* of = get_output_functions(domain); of->f_patch_write_header = &matlab_parallel_write_header; of->f_patch_write_output = &matlab_parallel_write_output; link_regrid_functions(domain,no_solver_patch_tag4refinement, no_solver_patch_tag4coarsening); } void no_solver_setprob(fclaw2d_domain_t* domain) { set_maptype_(); } void no_solver_patch_initialize(fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx) { set_block_(&this_block_idx); // Global parameters const amr_options_t *gparms = get_domain_parms(domain); int mx = gparms->mx; int my = gparms->my; int mbc = gparms->mbc; int meqn = gparms->meqn; // Parameters specific to this patch ClawPatch *cp = get_clawpatch(this_patch); double xlower = cp->xlower(); double ylower = cp->ylower(); double dx = cp->dx(); double dy = cp->dy(); // Pointers needed for the fortran double* q = cp->q(); int mpirank = domain->mpirank; initialize_(mx,my,meqn,mbc,xlower,ylower,dx,dy,q,mpirank); } double no_solver_update(fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx, double t, double dt) { const amr_options_t *gparms = get_domain_parms(domain); ClawPatch *cp = get_clawpatch(this_patch); // save the current time step for time interpolation. Otherwise, we get // unitialized values. cp->save_current_step(); // Save for time interpolation // Reinitialize with new proc data /* no_solver_patch_initialize(domain,this_patch, this_block_idx,this_patch_idx); */ return gparms->desired_cfl; } /* ----------------------------------------------------------------- Default routine for tagging patches for refinement and coarsening ----------------------------------------------------------------- */ fclaw_bool no_solver_patch_tag4refinement(fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx, int initflag) { /* ----------------------------------------------------------- */ // Global parameters const amr_options_t *gparms = get_domain_parms(domain); int mx = gparms->mx; int my = gparms->my; int mbc = gparms->mbc; int meqn = gparms->meqn; /* ----------------------------------------------------------- */ // Patch specific parameters ClawPatch *cp = get_clawpatch(this_patch); double xlower = cp->xlower(); double ylower = cp->ylower(); double dx = cp->dx(); double dy = cp->dy(); /* ------------------------------------------------------------ */ // Pointers needed to pass to Fortran double* q = cp->q(); int tag_patch; // == 0 or 1 no_solver_tag4refinement_(mx,my,mbc,meqn,xlower,ylower,dx,dy,q,initflag,tag_patch); return tag_patch == 1; } fclaw_bool no_solver_patch_tag4coarsening(fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch, int blockno, int patchno) { // This might come in handy if we want to debug a coarsening routine without // worrying about solvers. /* ----------------------------------------------------------- */ // Global parameters const amr_options_t *gparms = get_domain_parms(domain); int mx = gparms->mx; int my = gparms->my; int mbc = gparms->mbc; int meqn = gparms->meqn; /* ----------------------------------------------------------- */ // Patch specific parameters ClawPatch *cp = get_clawpatch(this_patch); double xlower = cp->xlower(); double ylower = cp->ylower(); double dx = cp->dx(); double dy = cp->dy(); /* ------------------------------------------------------------ */ // Pointers needed to pass to Fortran double* qcoarse = cp->q(); int tag_patch; // == 0 or 1 no_solver_tag4coarsening_(mx,my,mbc,meqn,xlower,ylower,dx,dy,qcoarse,tag_patch); return tag_patch == 0; } void matlab_parallel_write_header(fclaw2d_domain_t* domain, int iframe, int ngrids) { const amr_options_t *gparms = get_domain_parms(domain); double time = get_domain_time(domain); printf("Matlab output Frame %d at time %16.8e\n\n",iframe,time); // Write out header file containing global information for 'iframe' int meqn = gparms->meqn; int maux = 0; write_tfile_(iframe,time,meqn,ngrids,maux); // This opens file 'fort.qXXXX' for replace (where XXXX = <zero padding><iframe>, e.g. 0001, // 0010, 0114), and closes the file. new_qfile_(iframe); } void matlab_parallel_write_output(fclaw2d_domain_t *domain, fclaw2d_patch_t *this_patch, int this_block_idx, int this_patch_idx, int iframe,int num,int level) { // In case this is needed by the setaux routine set_block_(&this_block_idx); /* ----------------------------------------------------------- */ // Global parameters const amr_options_t *gparms = get_domain_parms(domain); int mx = gparms->mx; int my = gparms->my; int mbc = gparms->mbc; int meqn = gparms->meqn; /* ----------------------------------------------------------- */ // Patch specific parameters ClawPatch *cp = get_clawpatch(this_patch); double xlower = cp->xlower(); double ylower = cp->ylower(); double dx = cp->dx(); double dy = cp->dy(); /* ------------------------------------------------------------ */ // Pointers needed to pass to Fortran double* q = cp->q(); // Other input arguments int maxmx = mx; int maxmy = my; /* ------------------------------------------------------------- */ // This opens a file for append. Now, the style is in the 'clawout' style. int matlab_level = level + 1; write_qfile_(maxmx,maxmy,meqn,mbc,mx,my,xlower,ylower,dx,dy,q, iframe,num,matlab_level,this_block_idx); } #ifdef __cplusplus #if 0 { #endif } #endif <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief 波形描画テンプレート・クラス @author 平松邦仁 ([email protected]) @copyright Copyright (C) 2017 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include <vector> #include "gl_fw/glutils.hpp" namespace view { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief render_waves template class @param[in] UNIT 波形の型 @param[in] LIMIT 最大波形数 */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <typename UNIT, uint32_t LIMIT> class render_waves { std::vector<UNIT> units_; double div_; public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// render_waves() : units_(), div_(0.0) { } //-----------------------------------------------------------------// /*! @brief 波形生成 @param[in] time 生成時間 [sec] @param[in] div 分解能 [sec] @return 生成した数 */ //-----------------------------------------------------------------// uint32_t create_waves(double time, double div) { if(div <= 0.0 || time <= 0.0) return 0; auto n = time / div; if(n <= 0.0) return 0; else if(n > static_cast<double>(LIMIT)) return 0; units_.resize(static_cast<uint32_t>(n)); div_ = div; // 分解能 return n; } //-----------------------------------------------------------------// /*! @brief テスト波形生成 @param[in] frq 周波数 [Hz] */ //-----------------------------------------------------------------// void create_sin(double frq) { for(uint32_t i = 0; i < units_.size(); ++i) { double t = 1.0 / frq; units_[i] = static_cast<UNIT>(sin(2.0 * vtx::get_pi<double>() * t * i) * 32767.0) + 32768; } } //-----------------------------------------------------------------// /*! @brief 描画 @param[in] width 横幅(ピクセル) */ //-----------------------------------------------------------------// void render(uint32_t width) { vtx::sposs list; list.resize(width); for(uint32_t i = 0; i < width; ++i) { list[i] = vtx::spos(i, units_[i] / 256); } gl::draw_line_strip(list); } }; } <commit_msg>update sign<commit_after>#pragma once //=====================================================================// /*! @file @brief 波形描画テンプレート・クラス @author 平松邦仁 ([email protected]) @copyright Copyright (C) 2017 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include <vector> #include "gl_fw/glutils.hpp" namespace view { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief render_waves template class @param[in] UNIT 波形の型 @param[in] LIMIT 最大波形数 */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <typename UNIT, uint32_t LIMIT> class render_waves { std::vector<UNIT> units_; double div_; public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// render_waves() : units_(), div_(0.0) { } //-----------------------------------------------------------------// /*! @brief 波形生成 @param[in] time 生成時間 [sec] @param[in] div 分解能 [sec] @return 生成した数 */ //-----------------------------------------------------------------// uint32_t create_waves(double time, double div) { if(div <= 0.0 || time <= 0.0) return 0; auto n = time / div; if(n <= 0.0) return 0; else if(n > static_cast<double>(LIMIT)) return 0; units_.resize(static_cast<uint32_t>(n)); div_ = div; // 分解能 return n; } //-----------------------------------------------------------------// /*! @brief テスト波形生成 @param[in] frq 周波数 [Hz] */ //-----------------------------------------------------------------// void create_sin(double frq) { for(uint32_t i = 0; i < units_.size(); ++i) { double t = 1.0 / frq; units_[i] = 32768 - static_cast<UNIT>(sin(2.0 * vtx::get_pi<double>() * t * i) * 32767.0); } } //-----------------------------------------------------------------// /*! @brief 描画 @param[in] width 横幅(ピクセル) */ //-----------------------------------------------------------------// void render(uint32_t width) { vtx::sposs list; list.resize(width); for(uint32_t i = 0; i < width; ++i) { list[i] = vtx::spos(i, units_[i] / 256); } gl::draw_line_strip(list); } }; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: b3dentty.cxx,v $ * * $Revision: 1.1.1.1 $ * * last change: $Author: hr $ $Date: 2000-09-18 16:30:10 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _B3D_B3DENTITY_HXX #include "b3dentty.hxx" #endif #ifndef _B3D_B3DCOMMN_HXX #include "b3dcommn.hxx" #endif #ifndef _B3D_B3DTRANS_HXX #include "b3dtrans.hxx" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif /************************************************************************* |* |* Kopieren eine 3DEntity |* \************************************************************************/ void B3dEntity::Copy(B3dEntity& rEnt) { aPoint = rEnt.Point(); bDeviceCoor = rEnt.IsDeviceCoor(); bValid = rEnt.IsValid(); bEdgeFlag = rEnt.IsEdgeVisible(); aPlaneNormal = rEnt.PlaneNormal(); if(bNormalUsed = rEnt.IsNormalUsed()) aNormal = rEnt.Normal(); if(bTexCoorUsed = rEnt.IsTexCoorUsed()) aTexCoor = rEnt.TexCoor(); aColor = rEnt.Color(); } /************************************************************************* |* |* Flags auf Ausgangsposition |* \************************************************************************/ void B3dEntity::Reset() { bValid = bNormalUsed = bTexCoorUsed = bDeviceCoor = FALSE; bEdgeFlag = TRUE; } /************************************************************************* |* |* Device Koordinaten des Punktes berechnen |* \************************************************************************/ void B3dEntity::ImplToDeviceCoor(B3dTransformationSet* pSet) { if(pSet && !bDeviceCoor) { const Vector3D& rScale = pSet->GetScale(); const Vector3D& rTrans = pSet->GetTranslate(); aPoint.Homogenize(); aPoint[0] = (aPoint[0] * rScale[0]) + rTrans[0]; aPoint[1] = (aPoint[1] * rScale[1]) + rTrans[1]; aPoint[2] = (aPoint[2] * rScale[2]) + rTrans[2]; bDeviceCoor = TRUE; } } /************************************************************************* |* |* aus Device Koordinaten des Punktes 3D Koor im canonical view volume |* berechnen |* \************************************************************************/ void B3dEntity::ImplTo3DCoor(B3dTransformationSet* pSet) { if(pSet && bDeviceCoor) { const Vector3D& rScale = pSet->GetScale(); const Vector3D& rTrans = pSet->GetTranslate(); aPoint.Homogenize(); if(rScale[0] != 0.0) aPoint[0] = (aPoint[0] - rTrans[0]) / rScale[0]; if(rScale[1] != 0.0) aPoint[1] = (aPoint[1] - rTrans[1]) / rScale[1]; if(rScale[2] != 0.0) aPoint[2] = (aPoint[2] - rTrans[2]) / rScale[2]; bDeviceCoor = FALSE; } } /************************************************************************* |* |* Garantiere eine gemeinsame Datenbasis (ClipKoordinaten oder |* Devicekoordinaten) |* \************************************************************************/ void B3dEntity::ForceEqualBase(B3dTransformationSet* pSet, B3dEntity& rOld) { if(IsDeviceCoor() && rOld.IsDeviceCoor()) { SetDeviceCoor(); } else { if(IsDeviceCoor()) To3DCoor(pSet); if(rOld.IsDeviceCoor()) rOld.To3DCoor(pSet); } } /************************************************************************* |* |* Garantiere eine gemeinsame Datenbasis (ClipKoordinaten oder |* Devicekoordinaten) |* \************************************************************************/ void B3dEntity::ForceEqualBase(B3dTransformationSet* pSet, B3dEntity& rOld1, B3dEntity& rOld2) { if(!IsDeviceCoor() && rOld1.IsDeviceCoor() && rOld2.IsDeviceCoor()) { if(IsDeviceCoor()) To3DCoor(pSet); if(rOld1.IsDeviceCoor()) rOld1.To3DCoor(pSet); if(rOld2.IsDeviceCoor()) rOld2.To3DCoor(pSet); } } /************************************************************************* |* |* Neuen Punkt an der stelle t des parametrisierten Vektors rOld1, rOld2 |* berechnen und fuellen |* \************************************************************************/ void B3dEntity::CalcInBetween(B3dEntity& rOld1, B3dEntity& rOld2, double t) { // DeviceCoor der ersten Quelle benutzen, die Basis sollte // vorher abgeglichen sein SetDeviceCoor(rOld1.IsDeviceCoor()); // Punktkoordinaten berechnen aPoint.CalcInBetween(rOld1.Point(), rOld2.Point(), t); SetValid(); // PlaneNormal Koordinaten berechnen rOld1.PlaneNormal().Normalize(); rOld2.PlaneNormal().Normalize(); aPlaneNormal.CalcInBetween(rOld1.PlaneNormal(), rOld2.PlaneNormal(), t); aPlaneNormal.Normalize(); // Vektor berechnen if(rOld1.IsNormalUsed() && rOld2.IsNormalUsed()) { rOld1.Normal().Normalize(); rOld2.Normal().Normalize(); aNormal.CalcInBetween(rOld1.Normal(), rOld2.Normal(), t); aNormal.Normalize(); SetNormalUsed(); } // Texturkoordinaten berechnen if(rOld1.IsTexCoorUsed() && rOld2.IsTexCoorUsed()) { aTexCoor.CalcInBetween(rOld1.TexCoor(), rOld2.TexCoor(), t); SetTexCoorUsed(); } // EdgeVisible berechnen SetEdgeVisible(rOld1.IsEdgeVisible()); // Farbe berechnen aColor.CalcInBetween(rOld1.Color(), rOld2.Color(), t); } /************************************************************************* |* |* Neuen Punkt in der Mitte des parametrisierten Vektors rOld1, rOld2 |* berechnen und fuellen |* \************************************************************************/ void B3dEntity::CalcMiddle(B3dEntity& rOld1, B3dEntity& rOld2) { // DeviceCoor der ersten Quelle benutzen, die Basis sollte // vorher abgeglichen sein SetDeviceCoor(rOld1.IsDeviceCoor()); // Punktkoordinaten berechnen aPoint.CalcMiddle(rOld1.Point(), rOld2.Point()); SetValid(); // PlaneNormal Koordinaten berechnen rOld1.PlaneNormal().Normalize(); rOld2.PlaneNormal().Normalize(); aPlaneNormal.CalcMiddle(rOld1.PlaneNormal(), rOld2.PlaneNormal()); aPlaneNormal.Normalize(); // Vektor berechnen if(rOld1.IsNormalUsed() && rOld2.IsNormalUsed()) { rOld1.Normal().Normalize(); rOld2.Normal().Normalize(); aNormal.CalcMiddle(rOld1.Normal(), rOld2.Normal()); aNormal.Normalize(); SetNormalUsed(); } // Texturkoordinaten berechnen if(rOld1.IsTexCoorUsed() && rOld2.IsTexCoorUsed()) { aTexCoor.CalcMiddle(rOld1.TexCoor(), rOld2.TexCoor()); SetTexCoorUsed(); } // EdgeVisible berechnen SetEdgeVisible(rOld1.IsEdgeVisible()); // Farbe berechnen aColor.CalcMiddle(rOld1.Color(), rOld2.Color()); } /************************************************************************* |* |* Neuen Punkt in der Mitte des Dreiecks rOld1, rOld2, rOld3 |* berechnen und fuellen |* \************************************************************************/ void B3dEntity::CalcMiddle(B3dEntity& rOld1, B3dEntity& rOld2, B3dEntity& rOld3) { // DeviceCoor der ersten Quelle benutzen, die Basis sollte // vorher abgeglichen sein SetDeviceCoor(rOld1.IsDeviceCoor()); // Punktkoordinaten berechnen aPoint.CalcMiddle(rOld1.Point(), rOld2.Point(), rOld3.Point()); SetValid(); // PlaneNormal Koordinaten berechnen rOld1.PlaneNormal().Normalize(); rOld2.PlaneNormal().Normalize(); rOld3.PlaneNormal().Normalize(); aPlaneNormal.CalcMiddle(rOld1.PlaneNormal(), rOld2.PlaneNormal(), rOld3.PlaneNormal()); aPlaneNormal.Normalize(); // Vektor berechnen if(rOld1.IsNormalUsed() && rOld2.IsNormalUsed() && rOld3.IsNormalUsed()) { rOld1.Normal().Normalize(); rOld2.Normal().Normalize(); rOld3.Normal().Normalize(); aNormal.CalcMiddle(rOld1.Normal(), rOld2.Normal(), rOld3.Normal()); aNormal.Normalize(); SetNormalUsed(); } // Texturkoordinaten berechnen if(rOld1.IsTexCoorUsed() && rOld2.IsTexCoorUsed() && rOld3.IsTexCoorUsed()) { aTexCoor.CalcMiddle(rOld1.TexCoor(), rOld2.TexCoor(), rOld3.TexCoor()); SetTexCoorUsed(); } // Farbe berechnen aColor.CalcMiddle(rOld1.Color(), rOld2.Color(), rOld3.Color()); } /************************************************************************* |* |* Eine beliebige Transformation auf die Geometrie anwenden |* \************************************************************************/ void B3dEntity::Transform(const Matrix4D& rMat) { aPoint *= rMat; if(bNormalUsed) rMat.RotateAndNormalize(aNormal); } /************************************************************************* |* |* Bucket fuer geometrische Daten |* \************************************************************************/ BASE3D_IMPL_BUCKET(B3dEntity, Bucket) <commit_msg>INTEGRATION: CWS ooo20040815 (1.1.1.1.240); FILE MERGED 2004/08/04 13:31:01 waratah 1.1.1.1.240.1: #i32569# separate assignment from if statements<commit_after>/************************************************************************* * * $RCSfile: b3dentty.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: hr $ $Date: 2004-09-09 11:25:03 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _B3D_B3DENTITY_HXX #include "b3dentty.hxx" #endif #ifndef _B3D_B3DCOMMN_HXX #include "b3dcommn.hxx" #endif #ifndef _B3D_B3DTRANS_HXX #include "b3dtrans.hxx" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif /************************************************************************* |* |* Kopieren eine 3DEntity |* \************************************************************************/ void B3dEntity::Copy(B3dEntity& rEnt) { aPoint = rEnt.Point(); bDeviceCoor = rEnt.IsDeviceCoor(); bValid = rEnt.IsValid(); bEdgeFlag = rEnt.IsEdgeVisible(); aPlaneNormal = rEnt.PlaneNormal(); bNormalUsed = rEnt.IsNormalUsed(); if( bNormalUsed ) aNormal = rEnt.Normal(); bTexCoorUsed = rEnt.IsTexCoorUsed(); if( bTexCoorUsed ) aTexCoor = rEnt.TexCoor(); aColor = rEnt.Color(); } /************************************************************************* |* |* Flags auf Ausgangsposition |* \************************************************************************/ void B3dEntity::Reset() { bValid = bNormalUsed = bTexCoorUsed = bDeviceCoor = FALSE; bEdgeFlag = TRUE; } /************************************************************************* |* |* Device Koordinaten des Punktes berechnen |* \************************************************************************/ void B3dEntity::ImplToDeviceCoor(B3dTransformationSet* pSet) { if(pSet && !bDeviceCoor) { const Vector3D& rScale = pSet->GetScale(); const Vector3D& rTrans = pSet->GetTranslate(); aPoint.Homogenize(); aPoint[0] = (aPoint[0] * rScale[0]) + rTrans[0]; aPoint[1] = (aPoint[1] * rScale[1]) + rTrans[1]; aPoint[2] = (aPoint[2] * rScale[2]) + rTrans[2]; bDeviceCoor = TRUE; } } /************************************************************************* |* |* aus Device Koordinaten des Punktes 3D Koor im canonical view volume |* berechnen |* \************************************************************************/ void B3dEntity::ImplTo3DCoor(B3dTransformationSet* pSet) { if(pSet && bDeviceCoor) { const Vector3D& rScale = pSet->GetScale(); const Vector3D& rTrans = pSet->GetTranslate(); aPoint.Homogenize(); if(rScale[0] != 0.0) aPoint[0] = (aPoint[0] - rTrans[0]) / rScale[0]; if(rScale[1] != 0.0) aPoint[1] = (aPoint[1] - rTrans[1]) / rScale[1]; if(rScale[2] != 0.0) aPoint[2] = (aPoint[2] - rTrans[2]) / rScale[2]; bDeviceCoor = FALSE; } } /************************************************************************* |* |* Garantiere eine gemeinsame Datenbasis (ClipKoordinaten oder |* Devicekoordinaten) |* \************************************************************************/ void B3dEntity::ForceEqualBase(B3dTransformationSet* pSet, B3dEntity& rOld) { if(IsDeviceCoor() && rOld.IsDeviceCoor()) { SetDeviceCoor(); } else { if(IsDeviceCoor()) To3DCoor(pSet); if(rOld.IsDeviceCoor()) rOld.To3DCoor(pSet); } } /************************************************************************* |* |* Garantiere eine gemeinsame Datenbasis (ClipKoordinaten oder |* Devicekoordinaten) |* \************************************************************************/ void B3dEntity::ForceEqualBase(B3dTransformationSet* pSet, B3dEntity& rOld1, B3dEntity& rOld2) { if(!IsDeviceCoor() && rOld1.IsDeviceCoor() && rOld2.IsDeviceCoor()) { if(IsDeviceCoor()) To3DCoor(pSet); if(rOld1.IsDeviceCoor()) rOld1.To3DCoor(pSet); if(rOld2.IsDeviceCoor()) rOld2.To3DCoor(pSet); } } /************************************************************************* |* |* Neuen Punkt an der stelle t des parametrisierten Vektors rOld1, rOld2 |* berechnen und fuellen |* \************************************************************************/ void B3dEntity::CalcInBetween(B3dEntity& rOld1, B3dEntity& rOld2, double t) { // DeviceCoor der ersten Quelle benutzen, die Basis sollte // vorher abgeglichen sein SetDeviceCoor(rOld1.IsDeviceCoor()); // Punktkoordinaten berechnen aPoint.CalcInBetween(rOld1.Point(), rOld2.Point(), t); SetValid(); // PlaneNormal Koordinaten berechnen rOld1.PlaneNormal().Normalize(); rOld2.PlaneNormal().Normalize(); aPlaneNormal.CalcInBetween(rOld1.PlaneNormal(), rOld2.PlaneNormal(), t); aPlaneNormal.Normalize(); // Vektor berechnen if(rOld1.IsNormalUsed() && rOld2.IsNormalUsed()) { rOld1.Normal().Normalize(); rOld2.Normal().Normalize(); aNormal.CalcInBetween(rOld1.Normal(), rOld2.Normal(), t); aNormal.Normalize(); SetNormalUsed(); } // Texturkoordinaten berechnen if(rOld1.IsTexCoorUsed() && rOld2.IsTexCoorUsed()) { aTexCoor.CalcInBetween(rOld1.TexCoor(), rOld2.TexCoor(), t); SetTexCoorUsed(); } // EdgeVisible berechnen SetEdgeVisible(rOld1.IsEdgeVisible()); // Farbe berechnen aColor.CalcInBetween(rOld1.Color(), rOld2.Color(), t); } /************************************************************************* |* |* Neuen Punkt in der Mitte des parametrisierten Vektors rOld1, rOld2 |* berechnen und fuellen |* \************************************************************************/ void B3dEntity::CalcMiddle(B3dEntity& rOld1, B3dEntity& rOld2) { // DeviceCoor der ersten Quelle benutzen, die Basis sollte // vorher abgeglichen sein SetDeviceCoor(rOld1.IsDeviceCoor()); // Punktkoordinaten berechnen aPoint.CalcMiddle(rOld1.Point(), rOld2.Point()); SetValid(); // PlaneNormal Koordinaten berechnen rOld1.PlaneNormal().Normalize(); rOld2.PlaneNormal().Normalize(); aPlaneNormal.CalcMiddle(rOld1.PlaneNormal(), rOld2.PlaneNormal()); aPlaneNormal.Normalize(); // Vektor berechnen if(rOld1.IsNormalUsed() && rOld2.IsNormalUsed()) { rOld1.Normal().Normalize(); rOld2.Normal().Normalize(); aNormal.CalcMiddle(rOld1.Normal(), rOld2.Normal()); aNormal.Normalize(); SetNormalUsed(); } // Texturkoordinaten berechnen if(rOld1.IsTexCoorUsed() && rOld2.IsTexCoorUsed()) { aTexCoor.CalcMiddle(rOld1.TexCoor(), rOld2.TexCoor()); SetTexCoorUsed(); } // EdgeVisible berechnen SetEdgeVisible(rOld1.IsEdgeVisible()); // Farbe berechnen aColor.CalcMiddle(rOld1.Color(), rOld2.Color()); } /************************************************************************* |* |* Neuen Punkt in der Mitte des Dreiecks rOld1, rOld2, rOld3 |* berechnen und fuellen |* \************************************************************************/ void B3dEntity::CalcMiddle(B3dEntity& rOld1, B3dEntity& rOld2, B3dEntity& rOld3) { // DeviceCoor der ersten Quelle benutzen, die Basis sollte // vorher abgeglichen sein SetDeviceCoor(rOld1.IsDeviceCoor()); // Punktkoordinaten berechnen aPoint.CalcMiddle(rOld1.Point(), rOld2.Point(), rOld3.Point()); SetValid(); // PlaneNormal Koordinaten berechnen rOld1.PlaneNormal().Normalize(); rOld2.PlaneNormal().Normalize(); rOld3.PlaneNormal().Normalize(); aPlaneNormal.CalcMiddle(rOld1.PlaneNormal(), rOld2.PlaneNormal(), rOld3.PlaneNormal()); aPlaneNormal.Normalize(); // Vektor berechnen if(rOld1.IsNormalUsed() && rOld2.IsNormalUsed() && rOld3.IsNormalUsed()) { rOld1.Normal().Normalize(); rOld2.Normal().Normalize(); rOld3.Normal().Normalize(); aNormal.CalcMiddle(rOld1.Normal(), rOld2.Normal(), rOld3.Normal()); aNormal.Normalize(); SetNormalUsed(); } // Texturkoordinaten berechnen if(rOld1.IsTexCoorUsed() && rOld2.IsTexCoorUsed() && rOld3.IsTexCoorUsed()) { aTexCoor.CalcMiddle(rOld1.TexCoor(), rOld2.TexCoor(), rOld3.TexCoor()); SetTexCoorUsed(); } // Farbe berechnen aColor.CalcMiddle(rOld1.Color(), rOld2.Color(), rOld3.Color()); } /************************************************************************* |* |* Eine beliebige Transformation auf die Geometrie anwenden |* \************************************************************************/ void B3dEntity::Transform(const Matrix4D& rMat) { aPoint *= rMat; if(bNormalUsed) rMat.RotateAndNormalize(aNormal); } /************************************************************************* |* |* Bucket fuer geometrische Daten |* \************************************************************************/ BASE3D_IMPL_BUCKET(B3dEntity, Bucket) <|endoftext|>
<commit_before>/* * Copyright 2011 Esrille Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "StackingContext.h" #include <new> #include <iostream> namespace org { namespace w3c { namespace dom { namespace bootstrap { StackingContext* StackingContext::removeChild(StackingContext* item) { StackingContext* next = item->nextSibling; StackingContext* prev = item->previousSibling; if (!next) lastChild = prev; else next->previousSibling = prev; if (!prev) firstChild = next; else prev->nextSibling = next; item->parent = 0; --childCount; return item; } StackingContext* StackingContext::insertBefore(StackingContext* item, StackingContext* after) { if (!after) return appendChild(item); item->previousSibling = after->previousSibling; item->nextSibling = after; after->previousSibling = item; if (!item->previousSibling) firstChild = item; else item->previousSibling->nextSibling = item; item->parent = this; ++childCount; return item; } StackingContext* StackingContext::appendChild(StackingContext* item) { StackingContext* prev = lastChild; if (!prev) firstChild = item; else prev->nextSibling = item; item->previousSibling = prev; item->nextSibling = 0; lastChild = item; item->parent = this; ++childCount; return item; } StackingContext::StackingContext(int zIndex) : zIndex(zIndex), z1(0.0f), z3(0.0f), parent(0), firstChild(0), lastChild(0), previousSibling(0), nextSibling(0), childCount(0), zero(0) { } StackingContext::~StackingContext() { if (parent) parent->removeChild(this); while (0 < childCount) { StackingContext* child = removeChild(firstChild); delete child; } } StackingContext* StackingContext::getAuto() { if (zIndex == 0) return this; if (!zero) zero = addContext(0); return zero; } StackingContext* StackingContext::addContext(int zIndex) { if (isAuto()) return parent->addContext(zIndex); StackingContext* after = 0; for (auto i = getFirstChild(); i; i = i->getNextSibling()) { if (zIndex < i->zIndex) { after = i; break; } } StackingContext* item = new(std::nothrow) StackingContext(zIndex); if (item) insertBefore(item, after); return item; } float StackingContext::eval(float z) { z += 1.0f; z1 = z3 = z; for (auto i = getFirstChild(); i; i = i->getNextSibling()) { z = i->eval(z); if (i->zIndex < 0) { z += 1.0f; z3 = z; } } return z; } void StackingContext::dump(std::string indent) { std::cout << indent << "z-index: " << zIndex << " " << z1 << " " << z3 << "\n"; indent += " "; for (auto child = getFirstChild(); child; child = child->getNextSibling()) child->dump(indent); } }}}} // org::w3c::dom::bootstrap<commit_msg>(StackingContext::getAuto) : Fix a bug.<commit_after>/* * Copyright 2011 Esrille Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "StackingContext.h" #include <new> #include <iostream> namespace org { namespace w3c { namespace dom { namespace bootstrap { StackingContext* StackingContext::removeChild(StackingContext* item) { StackingContext* next = item->nextSibling; StackingContext* prev = item->previousSibling; if (!next) lastChild = prev; else next->previousSibling = prev; if (!prev) firstChild = next; else prev->nextSibling = next; item->parent = 0; --childCount; return item; } StackingContext* StackingContext::insertBefore(StackingContext* item, StackingContext* after) { if (!after) return appendChild(item); item->previousSibling = after->previousSibling; item->nextSibling = after; after->previousSibling = item; if (!item->previousSibling) firstChild = item; else item->previousSibling->nextSibling = item; item->parent = this; ++childCount; return item; } StackingContext* StackingContext::appendChild(StackingContext* item) { StackingContext* prev = lastChild; if (!prev) firstChild = item; else prev->nextSibling = item; item->previousSibling = prev; item->nextSibling = 0; lastChild = item; item->parent = this; ++childCount; return item; } StackingContext::StackingContext(int zIndex) : zIndex(zIndex), z1(0.0f), z3(0.0f), parent(0), firstChild(0), lastChild(0), previousSibling(0), nextSibling(0), childCount(0), zero(0) { } StackingContext::~StackingContext() { if (parent) parent->removeChild(this); while (0 < childCount) { StackingContext* child = removeChild(firstChild); delete child; } } StackingContext* StackingContext::getAuto() { if (isAuto()) return this; if (!zero) zero = addContext(0); return zero; } StackingContext* StackingContext::addContext(int zIndex) { if (isAuto()) return parent->addContext(zIndex); StackingContext* after = 0; for (auto i = getFirstChild(); i; i = i->getNextSibling()) { if (zIndex < i->zIndex) { after = i; break; } } StackingContext* item = new(std::nothrow) StackingContext(zIndex); if (item) insertBefore(item, after); return item; } float StackingContext::eval(float z) { z += 1.0f; z1 = z3 = z; for (auto i = getFirstChild(); i; i = i->getNextSibling()) { z = i->eval(z); if (i->zIndex < 0) { z += 1.0f; z3 = z; } } return z; } void StackingContext::dump(std::string indent) { std::cout << indent << "z-index: " << zIndex << " " << z1 << " " << z3 << "\n"; indent += " "; for (auto child = getFirstChild(); child; child = child->getNextSibling()) child->dump(indent); } }}}} // org::w3c::dom::bootstrap<|endoftext|>
<commit_before>/* * jcom.oscroute * External for Jamoma: parse and pass OpenSoundControl messages * By Tim Place, Copyright 2006 * * License: This code is licensed under the terms of the GNU LGPL * http://www.gnu.org/licenses/lgpl.html */ #include "Jamoma.h" #define MAX_ARGCOUNT 100 #define MAX_MESS_SIZE 2048 typedef struct _oscroute{ // Data Structure for this object t_object ob; // REQUIRED: Our object void *obex; // REQUIRED: Object Extensions used by Jitter/Attribute stuff void *outlets[MAX_ARGCOUNT]; // my outlet array void *outlet_overflow; // this outlet doubles as the dumpout outlet t_symbol *arguments[MAX_ARGCOUNT]; // symbols to match long unsigned arglen[MAX_ARGCOUNT]; // strlen of symbols to match short num_args; long attr_strip; // ATTRIBUTE: 1 = strip leading slash off any messages void *proxy_inlet; // pointer to the second inlet (when present) } t_oscroute; // Prototypes for our methods: void *oscroute_new(t_symbol *s, long argc, t_atom *argv); void oscroute_free(t_oscroute *x); void oscroute_assist(t_oscroute *x, void *b, long msg, long arg, char *dst); void oscroute_bang(t_oscroute *x); void oscroute_int(t_oscroute *x, long n); void oscroute_float(t_oscroute *x, double f); void oscroute_list(t_oscroute *x, t_symbol *msg, long argc, t_atom *argv); void oscroute_symbol(t_oscroute *x, t_symbol *msg, long argc, t_atom *argv); //void oscroute_list(t_oscroute *x, t_symbol *msg, long argc, t_atom *argv); // Globals t_class *oscroute_class; // Required: Global pointer for our class /************************************************************************************/ // Main() Function int main(void) // main recieves a copy of the Max function macros table { long attrflags = 0; t_class *c; t_object *attr; // Initialize Globals jamoma_init(); // Define our class c = class_new("jcom.oscroute",(method)oscroute_new, (method)oscroute_free, (short)sizeof(t_oscroute), (method)0L, A_GIMME, 0); class_obexoffset_set(c, calcoffset(t_oscroute, obex)); // Make methods accessible for our class: class_addmethod(c, (method)oscroute_bang, "bang", 0L, 0L); class_addmethod(c, (method)oscroute_int, "int", A_DEFLONG, 0L); class_addmethod(c, (method)oscroute_float, "float", A_DEFFLOAT, 0L); class_addmethod(c, (method)oscroute_list, "list", A_GIMME, 0L); class_addmethod(c, (method)oscroute_symbol, "anything", A_GIMME, 0L); class_addmethod(c, (method)oscroute_assist, "assist", A_CANT, 0L); class_addmethod(c, (method)object_obex_dumpout, "dumpout", A_CANT, 0); class_addmethod(c, (method)object_obex_quickref, "quickref", A_CANT, 0); // ATTRIBUTE: strip attr = attr_offset_new("strip", _sym_long, attrflags, (method)0, (method)0, calcoffset(t_oscroute, attr_strip)); class_addattr(c, attr); // Finalize our class class_register(CLASS_BOX, c); oscroute_class = c; return 0; } /************************************************************************************/ // Object Life void *oscroute_new(t_symbol *s, long argc, t_atom *argv) { short i; t_oscroute *x = (t_oscroute *)object_alloc(oscroute_class); if(x){ x->outlet_overflow = outlet_new(x, 0); // overflow outlet //object_obex_store((void *)x, _sym_dumpout, (object *)x->outlet_overflow); // dumpout x->num_args = argc; if(argc < 1){ // if no args are provided, we provide a way to set the arg using an inlet x->num_args = 1; x->arguments[0] = gensym("/nil"); x->arglen[0] = 4; x->proxy_inlet = proxy_new(x, 1, 0L); x->outlets[0] = outlet_new(x, 0); } else{ x->proxy_inlet = 0; for(i=x->num_args-1; i >= 0; i--){ x->outlets[i] = outlet_new(x, 0); // Create Outlet switch(argv[i].a_type){ case A_SYM: //atom_setsym(&(x->arguments[i]), atom_getsym(argv+i)); x->arguments[i] = atom_getsym(argv+i); x->arglen[i] = strlen(atom_getsym(argv+i)->s_name); break; default: error("jcom.oscroute - invalid arguments - all args must be symbols"); } } } //attr_args_process(x, argc, argv); //handle attribute args } return (x); // return the pointer to our new instantiation } void oscroute_free(t_oscroute *x) { if(x->proxy_inlet != 0) freeobject((t_object *)(x->proxy_inlet)); } /************************************************************************************/ // Methods bound to input/inlets // Method for Assistance Messages void oscroute_assist(t_oscroute *x, void *b, long msg, long arg, char *dst) { if(msg==1) // Inlet strcpy(dst, "Input"); else if(msg==2){ // Outlets if(arg < x->num_args) strcpy(dst, x->arguments[arg]->s_name); else strcpy(dst, "dumpout / overflow from non-matching input"); } } // BANG INPUT: STRAIGHT TO OVERFLOW void oscroute_bang(t_oscroute *x) { outlet_bang(x->outlet_overflow); } // INT INPUT: STRAIGHT TO OVERFLOW void oscroute_int(t_oscroute *x, long n) { outlet_int(x->outlet_overflow, n); } // FLOAT INPUT: STRAIGHT TO OVERFLOW void oscroute_float(t_oscroute *x, double f) { outlet_float(x->outlet_overflow, f); } // LIST INPUT: STRAIGHT TO OVERFLOW void oscroute_list(t_oscroute *x, t_symbol *msg, long argc, t_atom *argv) { outlet_list(x->outlet_overflow, _sym_list, argc , argv); } char* matchesWildcard(const char *msg, const char *arg, unsigned long len) { if(strncmp(msg, arg, len) == 0) return strstr((char*)msg, "/"); return NULL; } inline int wildCardOffset(unsigned int numberOfWc) { return 2 * numberOfWc; } // SYMBOL INPUT void oscroute_symbol(t_oscroute *x, t_symbol *msg, long argc, t_atom *argv) { short i; t_symbol *message; // our input message to match t_symbol *output; char input[MAX_MESS_SIZE]; // our input string long inlet = proxy_getinlet((t_object *)x); // If the message comes in the second inlet, then set the string to match... if(inlet == 1){ x->arguments[0] = msg; x->arglen[0] = strlen(msg->s_name); return; } // Otherwise match the stored string(s) and output... strcpy(input, msg->s_name); // Make sure we are dealing with valid OSC input by looking for a leading slash if(input[0] != '/') { outlet_anything(x->outlet_overflow, msg, argc , argv); return; } message = gensym(input); char *wc, *c; int wcCount = 0; // wild card count bool overFlow = true; for (i=0; i < x->num_args; i++) { // Look for exact matches first. if (strncmp(msg->s_name, x->arguments[i]->s_name, x->arglen[i])==0) { // If incoming message is longer than argument... if (strlen(msg->s_name) > x->arglen[i]){ // ...it is only a match if it continues with a slash if (input[x->arglen[i]] == '/') { output = gensym(msg->s_name + x->arglen[i]); outlet_anything(x->outlets[i], output, argc , argv); overFlow = false; break; } } // If the incoming message is no longer we know that we have a match else { // We then have to check what message to return. // The message received has no arguments: if (argc == 0) { outlet_bang(x->outlets[i]); overFlow = false; break; } // The message received has one argument only: else if (argc==1) { overFlow = false; // int argument if (argv->a_type==A_LONG) { outlet_int(x->outlets[i],argv->a_w.w_long); break; } // float argument else if (argv->a_type==A_FLOAT) { outlet_float(x->outlets[i],argv->a_w.w_float); break; } // something else else if (argv->a_type==A_SYM) { outlet_anything(x->outlets[i],argv->a_w.w_sym,0,0); break; } } // There are two or more arguments: check if first is A_SYM else { if (argv->a_type==A_SYM) { output = argv->a_w.w_sym; argc--; argv++; } else output = _sym_list; outlet_anything(x->outlets[i], output, argc , argv); overFlow = false; break; } } } } // If no exact matches, look for wildcards. for (i=0; i < x->num_args; i++) { // Check to see if this argument has a wildcard if(wc = strstr(x->arguments[i]->s_name, "/*")) { if(*(wc+2) == '\0') { // Wildcard follows parameter names, i.e. /fifth/moon/of/aragon/* if(c = matchesWildcard(msg->s_name, x->arguments[i]->s_name, x->arglen[i] - 1)) { // Need to strip off preceeding part of message outlet_anything(x->outlets[i], gensym(strstr(c+1, "/")), argc, argv); return; } else { // We break here because if the strncmp() fails it means we have a wildcard following an // OSC message i.e. /robot/* but the incoming message doesn't begin with /robot // break; } } else { while(wc && *(wc + 2) == '/') { wcCount++; // Skip to next potential wildcard wc += 2; wc = strstr(wc, "/*"); } c = msg->s_name + 1; for(int skipCnt = 0; skipCnt < wcCount; ++skipCnt) { c = strstr(c + 1, "/"); } if(c = matchesWildcard(c, x->arguments[i]->s_name + wildCardOffset(wcCount), strlen(c))) { outlet_anything(x->outlets[i], gensym(c), argc, argv); return; } else { wcCount = 0; } } } } // the message was never reckognised if(overFlow) outlet_anything(x->outlet_overflow, msg, argc , argv); }<commit_msg>no longer crashes as per bug #1854416 reported by Pascal<commit_after>/* * jcom.oscroute * External for Jamoma: parse and pass OpenSoundControl messages * By Tim Place, Copyright 2006 * * License: This code is licensed under the terms of the GNU LGPL * http://www.gnu.org/licenses/lgpl.html */ #include "Jamoma.h" #define MAX_ARGCOUNT 100 #define MAX_MESS_SIZE 2048 typedef struct _oscroute{ // Data Structure for this object t_object ob; // REQUIRED: Our object void *obex; // REQUIRED: Object Extensions used by Jitter/Attribute stuff void *outlets[MAX_ARGCOUNT]; // my outlet array void *outlet_overflow; // this outlet doubles as the dumpout outlet t_symbol *arguments[MAX_ARGCOUNT]; // symbols to match long unsigned arglen[MAX_ARGCOUNT]; // strlen of symbols to match short num_args; long attr_strip; // ATTRIBUTE: 1 = strip leading slash off any messages void *proxy_inlet; // pointer to the second inlet (when present) } t_oscroute; // Prototypes for our methods: void *oscroute_new(t_symbol *s, long argc, t_atom *argv); void oscroute_free(t_oscroute *x); void oscroute_assist(t_oscroute *x, void *b, long msg, long arg, char *dst); void oscroute_bang(t_oscroute *x); void oscroute_int(t_oscroute *x, long n); void oscroute_float(t_oscroute *x, double f); void oscroute_list(t_oscroute *x, t_symbol *msg, long argc, t_atom *argv); void oscroute_symbol(t_oscroute *x, t_symbol *msg, long argc, t_atom *argv); //void oscroute_list(t_oscroute *x, t_symbol *msg, long argc, t_atom *argv); // Globals t_class *oscroute_class; // Required: Global pointer for our class /************************************************************************************/ // Main() Function int main(void) // main recieves a copy of the Max function macros table { long attrflags = 0; t_class *c; t_object *attr; // Initialize Globals jamoma_init(); // Define our class c = class_new("jcom.oscroute",(method)oscroute_new, (method)oscroute_free, (short)sizeof(t_oscroute), (method)0L, A_GIMME, 0); class_obexoffset_set(c, calcoffset(t_oscroute, obex)); // Make methods accessible for our class: class_addmethod(c, (method)oscroute_bang, "bang", 0L, 0L); class_addmethod(c, (method)oscroute_int, "int", A_DEFLONG, 0L); class_addmethod(c, (method)oscroute_float, "float", A_DEFFLOAT, 0L); class_addmethod(c, (method)oscroute_list, "list", A_GIMME, 0L); class_addmethod(c, (method)oscroute_symbol, "anything", A_GIMME, 0L); class_addmethod(c, (method)oscroute_assist, "assist", A_CANT, 0L); class_addmethod(c, (method)object_obex_dumpout, "dumpout", A_CANT, 0); class_addmethod(c, (method)object_obex_quickref, "quickref", A_CANT, 0); // ATTRIBUTE: strip attr = attr_offset_new("strip", _sym_long, attrflags, (method)0, (method)0, calcoffset(t_oscroute, attr_strip)); class_addattr(c, attr); // Finalize our class class_register(CLASS_BOX, c); oscroute_class = c; return 0; } /************************************************************************************/ // Object Life void *oscroute_new(t_symbol *s, long argc, t_atom *argv) { short i; t_oscroute *x = (t_oscroute *)object_alloc(oscroute_class); if(x){ x->outlet_overflow = outlet_new(x, 0); // overflow outlet //object_obex_store((void *)x, _sym_dumpout, (object *)x->outlet_overflow); // dumpout x->num_args = argc; if(argc < 1){ // if no args are provided, we provide a way to set the arg using an inlet x->num_args = 1; x->arguments[0] = gensym("/nil"); x->arglen[0] = 4; x->proxy_inlet = proxy_new(x, 1, 0L); x->outlets[0] = outlet_new(x, 0); } else{ x->proxy_inlet = 0; for(i=x->num_args-1; i >= 0; i--){ x->outlets[i] = outlet_new(x, 0); // Create Outlet switch(argv[i].a_type){ case A_SYM: //atom_setsym(&(x->arguments[i]), atom_getsym(argv+i)); x->arguments[i] = atom_getsym(argv+i); x->arglen[i] = strlen(atom_getsym(argv+i)->s_name); break; default: error("jcom.oscroute - invalid arguments - all args must be symbols"); } } } //attr_args_process(x, argc, argv); //handle attribute args } return (x); // return the pointer to our new instantiation } void oscroute_free(t_oscroute *x) { if(x->proxy_inlet != 0) freeobject((t_object *)(x->proxy_inlet)); } /************************************************************************************/ // Methods bound to input/inlets // Method for Assistance Messages void oscroute_assist(t_oscroute *x, void *b, long msg, long arg, char *dst) { if(msg==1) // Inlet strcpy(dst, "Input"); else if(msg==2){ // Outlets if(arg < x->num_args) strcpy(dst, x->arguments[arg]->s_name); else strcpy(dst, "dumpout / overflow from non-matching input"); } } // BANG INPUT: STRAIGHT TO OVERFLOW void oscroute_bang(t_oscroute *x) { outlet_bang(x->outlet_overflow); } // INT INPUT: STRAIGHT TO OVERFLOW void oscroute_int(t_oscroute *x, long n) { outlet_int(x->outlet_overflow, n); } // FLOAT INPUT: STRAIGHT TO OVERFLOW void oscroute_float(t_oscroute *x, double f) { outlet_float(x->outlet_overflow, f); } // LIST INPUT: STRAIGHT TO OVERFLOW void oscroute_list(t_oscroute *x, t_symbol *msg, long argc, t_atom *argv) { outlet_list(x->outlet_overflow, _sym_list, argc , argv); } char* matchesWildcard(const char *msg, const char *arg, unsigned long len) { if(strncmp(msg, arg, len) == 0) return strstr((char*)msg, "/"); return NULL; } inline int wildCardOffset(unsigned int numberOfWc) { return 2 * numberOfWc; } // SYMBOL INPUT void oscroute_symbol(t_oscroute *x, t_symbol *msg, long argc, t_atom *argv) { short i; t_symbol *message; // our input message to match t_symbol *output; char input[MAX_MESS_SIZE]; // our input string long inlet = proxy_getinlet((t_object *)x); // If the message comes in the second inlet, then set the string to match... if(inlet == 1){ x->arguments[0] = msg; x->arglen[0] = strlen(msg->s_name); return; } // Otherwise match the stored string(s) and output... strcpy(input, msg->s_name); // Make sure we are dealing with valid OSC input by looking for a leading slash if(input[0] != '/') { outlet_anything(x->outlet_overflow, msg, argc , argv); return; } message = gensym(input); char *wc, *c; int wcCount = 0; // wild card count bool overFlow = true; for (i=0; i < x->num_args; i++) { // Look for exact matches first. if (strncmp(msg->s_name, x->arguments[i]->s_name, x->arglen[i])==0) { // If incoming message is longer than argument... if (strlen(msg->s_name) > x->arglen[i]){ // ...it is only a match if it continues with a slash if (input[x->arglen[i]] == '/') { output = gensym(msg->s_name + x->arglen[i]); outlet_anything(x->outlets[i], output, argc , argv); overFlow = false; break; } } // If the incoming message is no longer we know that we have a match else { // We then have to check what message to return. // The message received has no arguments: if (argc == 0) { outlet_bang(x->outlets[i]); overFlow = false; break; } // The message received has one argument only: else if (argc==1) { overFlow = false; // int argument if (argv->a_type==A_LONG) { outlet_int(x->outlets[i],argv->a_w.w_long); break; } // float argument else if (argv->a_type==A_FLOAT) { outlet_float(x->outlets[i],argv->a_w.w_float); break; } // something else else if (argv->a_type==A_SYM) { outlet_anything(x->outlets[i],argv->a_w.w_sym,0,0); break; } } // There are two or more arguments: check if first is A_SYM else { if (argv->a_type==A_SYM) { output = argv->a_w.w_sym; argc--; argv++; } else output = _sym_list; outlet_anything(x->outlets[i], output, argc , argv); overFlow = false; break; } } } } // If no exact matches, look for wildcards. for (i=0; i < x->num_args; i++) { // Check to see if this argument has a wildcard if(wc = strstr(x->arguments[i]->s_name, "/*")) { if(*(wc+2) == '\0') { // Wildcard follows parameter names, i.e. /fifth/moon/of/aragon/* if(c = matchesWildcard(msg->s_name, x->arguments[i]->s_name, x->arglen[i] - 1)) { // Need to strip off preceeding part of message char *temp = strstr(c+1, "/"); if(temp) outlet_anything(x->outlets[i], gensym(temp), argc, argv); return; } else { // We break here because if the strncmp() fails it means we have a wildcard following an // OSC message i.e. /robot/* but the incoming message doesn't begin with /robot // break; } } else { while(wc && *(wc + 2) == '/') { wcCount++; // Skip to next potential wildcard wc += 2; wc = strstr(wc, "/*"); } c = msg->s_name + 1; for(int skipCnt = 0; skipCnt < wcCount; ++skipCnt) { c = strstr(c + 1, "/"); } if(c = matchesWildcard(c, x->arguments[i]->s_name + wildCardOffset(wcCount), strlen(c))) { outlet_anything(x->outlets[i], gensym(c), argc, argv); return; } else { wcCount = 0; } } } } // the message was never reckognised if(overFlow) outlet_anything(x->outlet_overflow, msg, argc , argv); }<|endoftext|>
<commit_before>/* * Copyright 2009 The VOTCA Development Team (http://www.votca.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <votca/tools/version.h> #include <iostream> #include "version.h" #include "config.h" namespace gmx { #ifndef GMX4DEV extern "C" { #endif #include <copyrite.h> #ifndef GMX4DEV } #endif // this one is needed because of bool is defined in one of the headers included by gmx #undef bool } namespace votca { namespace csg { #ifdef HGVERSION static const std::string version_str = VERSION " " HGVERSION " (compiled " __DATE__ ", " __TIME__ ")"; #else static const std::string version_str = VERSION "(compiled " __DATE__ ", " __TIME__ ")"; #endif const std::string &CsgVersionStr() { return version_str; } void HelpTextHeader(const std::string &tool_name) { std::cout << "==================================================\n" << "======== VOTCA (http://www.votca.org) ========\n" << "==================================================\n\n" << "please submit bugs to " PACKAGE_BUGREPORT "\n\n" << tool_name << ", version " << votca::csg::CsgVersionStr() << "\nvotca_tools, version " << votca::tools::ToolsVersionStr() << "\ngromacs, " << gmx::GromacsVersion() << "\n\n"; } }} <commit_msg>gcc-4.4 fix: gmx::GromacsVersion->GromacsVersion<commit_after>/* * Copyright 2009 The VOTCA Development Team (http://www.votca.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <votca/tools/version.h> #include <iostream> #include "version.h" #include "config.h" #ifndef GMX4DEV extern "C" { #endif #include <copyrite.h> #ifndef GMX4DEV } #endif // this one is needed because of bool is defined in one of the headers included by gmx #undef bool namespace votca { namespace csg { #ifdef HGVERSION static const std::string version_str = VERSION " " HGVERSION " (compiled " __DATE__ ", " __TIME__ ")"; #else static const std::string version_str = VERSION "(compiled " __DATE__ ", " __TIME__ ")"; #endif const std::string &CsgVersionStr() { return version_str; } void HelpTextHeader(const std::string &tool_name) { std::cout << "==================================================\n" << "======== VOTCA (http://www.votca.org) ========\n" << "==================================================\n\n" << "please submit bugs to " PACKAGE_BUGREPORT "\n\n" << tool_name << ", version " << votca::csg::CsgVersionStr() << "\nvotca_tools, version " << votca::tools::ToolsVersionStr() << "\ngromacs, " << GromacsVersion() << "\n\n"; } }} <|endoftext|>
<commit_before>#include "globals.hh" #include "shared.hh" #include "store-api.hh" #include "util.hh" #include <algorithm> #include <cctype> #include <exception> #include <iostream> #include <mutex> #include <cstdlib> #include <sys/time.h> #include <sys/stat.h> #include <unistd.h> #include <signal.h> #include <openssl/crypto.h> namespace nix { static bool gcWarning = true; void printGCWarning() { if (!gcWarning) return; static bool haveWarned = false; warnOnce(haveWarned, "you did not specify '--add-root'; " "the result might be removed by the garbage collector"); } void printMissing(ref<Store> store, const PathSet & paths, Verbosity lvl) { unsigned long long downloadSize, narSize; PathSet willBuild, willSubstitute, unknown; store->queryMissing(paths, willBuild, willSubstitute, unknown, downloadSize, narSize); printMissing(store, willBuild, willSubstitute, unknown, downloadSize, narSize, lvl); } void printMissing(ref<Store> store, const PathSet & willBuild, const PathSet & willSubstitute, const PathSet & unknown, unsigned long long downloadSize, unsigned long long narSize, Verbosity lvl) { if (!willBuild.empty()) { printMsg(lvl, "these derivations will be built:"); Paths sorted = store->topoSortPaths(willBuild); reverse(sorted.begin(), sorted.end()); for (auto & i : sorted) printMsg(lvl, fmt(" %s", i)); } if (!willSubstitute.empty()) { printMsg(lvl, fmt("these paths will be fetched (%.2f MiB download, %.2f MiB unpacked):", downloadSize / (1024.0 * 1024.0), narSize / (1024.0 * 1024.0))); for (auto & i : willSubstitute) printMsg(lvl, fmt(" %s", i)); } if (!unknown.empty()) { printMsg(lvl, fmt("don't know how to build these paths%s:", (settings.readOnlyMode ? " (may be caused by read-only store access)" : ""))); for (auto & i : unknown) printMsg(lvl, fmt(" %s", i)); } } string getArg(const string & opt, Strings::iterator & i, const Strings::iterator & end) { ++i; if (i == end) throw UsageError(format("'%1%' requires an argument") % opt); return *i; } /* OpenSSL is not thread-safe by default - it will randomly crash unless the user supplies a mutex locking function. So let's do that. */ static std::vector<std::mutex> opensslLocks; static void opensslLockCallback(int mode, int type, const char * file, int line) { if (mode & CRYPTO_LOCK) opensslLocks[type].lock(); else opensslLocks[type].unlock(); } static void sigHandler(int signo) { } void initNix() { /* Turn on buffering for cerr. */ #if HAVE_PUBSETBUF static char buf[1024]; std::cerr.rdbuf()->pubsetbuf(buf, sizeof(buf)); #endif /* Initialise OpenSSL locking. */ opensslLocks = std::vector<std::mutex>(CRYPTO_num_locks()); CRYPTO_set_locking_callback(opensslLockCallback); settings.loadConfFile(); startSignalHandlerThread(); /* Reset SIGCHLD to its default. */ struct sigaction act; sigemptyset(&act.sa_mask); act.sa_handler = SIG_DFL; act.sa_flags = 0; if (sigaction(SIGCHLD, &act, 0)) throw SysError("resetting SIGCHLD"); /* Install a dummy SIGUSR1 handler for use with pthread_kill(). */ act.sa_handler = sigHandler; if (sigaction(SIGUSR1, &act, 0)) throw SysError("handling SIGUSR1"); /* Register a SIGSEGV handler to detect stack overflows. */ detectStackOverflow(); /* There is no privacy in the Nix system ;-) At least not for now. In particular, store objects should be readable by everybody. */ umask(0022); /* Initialise the PRNG. */ struct timeval tv; gettimeofday(&tv, 0); srandom(tv.tv_usec); /* On macOS, don't use the per-session TMPDIR (as set e.g. by sshd). This breaks build users because they don't have access to the TMPDIR, in particular in ‘nix-store --serve’. */ #if __APPLE__ if (getuid() == 0 && hasPrefix(getEnv("TMPDIR"), "/var/folders/")) unsetenv("TMPDIR"); #endif } LegacyArgs::LegacyArgs(const std::string & programName, std::function<bool(Strings::iterator & arg, const Strings::iterator & end)> parseArg) : MixCommonArgs(programName), parseArg(parseArg) { mkFlag() .longName("no-build-output") .shortName('Q') .description("do not show build output") .set(&settings.verboseBuild, false); mkFlag() .longName("keep-failed") .shortName('K') .description("keep temporary directories of failed builds") .set(&(bool&) settings.keepFailed, true); mkFlag() .longName("keep-going") .shortName('k') .description("keep going after a build fails") .set(&(bool&) settings.keepGoing, true); mkFlag() .longName("fallback") .description("build from source if substitution fails") .set(&(bool&) settings.tryFallback, true); mkFlag1('j', "max-jobs", "jobs", "maximum number of parallel builds", [=](std::string s) { settings.set("max-jobs", s); }); auto intSettingAlias = [&](char shortName, const std::string & longName, const std::string & description, const std::string & dest) { mkFlag<unsigned int>(shortName, longName, description, [=](unsigned int n) { settings.set(dest, std::to_string(n)); }); }; intSettingAlias(0, "cores", "maximum number of CPU cores to use inside a build", "cores"); intSettingAlias(0, "max-silent-time", "number of seconds of silence before a build is killed", "max-silent-time"); intSettingAlias(0, "timeout", "number of seconds before a build is killed", "timeout"); mkFlag(0, "readonly-mode", "do not write to the Nix store", &settings.readOnlyMode); mkFlag(0, "no-gc-warning", "disable warning about not using '--add-root'", &gcWarning, false); mkFlag() .longName("store") .label("store-uri") .description("URI of the Nix store to use") .dest(&(std::string&) settings.storeUri); } bool LegacyArgs::processFlag(Strings::iterator & pos, Strings::iterator end) { if (MixCommonArgs::processFlag(pos, end)) return true; bool res = parseArg(pos, end); if (res) ++pos; return res; } bool LegacyArgs::processArgs(const Strings & args, bool finish) { if (args.empty()) return true; assert(args.size() == 1); Strings ss(args); auto pos = ss.begin(); if (!parseArg(pos, ss.end())) throw UsageError(format("unexpected argument '%1%'") % args.front()); return true; } void parseCmdLine(int argc, char * * argv, std::function<bool(Strings::iterator & arg, const Strings::iterator & end)> parseArg) { parseCmdLine(baseNameOf(argv[0]), argvToStrings(argc, argv), parseArg); } void parseCmdLine(const string & programName, const Strings & args, std::function<bool(Strings::iterator & arg, const Strings::iterator & end)> parseArg) { LegacyArgs(programName, parseArg).parseCmdline(args); } void printVersion(const string & programName) { std::cout << format("%1% (Nix) %2%") % programName % nixVersion << std::endl; if (verbosity > lvlInfo) { Strings cfg; #if HAVE_BOEHMGC cfg.push_back("gc"); #endif #if HAVE_SODIUM cfg.push_back("signed-caches"); #endif std::cout << "Features: " << concatStringsSep(", ", cfg) << "\n"; std::cout << "Configuration file: " << settings.nixConfDir + "/nix.conf" << "\n"; std::cout << "Store directory: " << settings.nixStore << "\n"; std::cout << "State directory: " << settings.nixStateDir << "\n"; } throw Exit(); } void showManPage(const string & name) { restoreSignals(); setenv("MANPATH", settings.nixManDir.c_str(), 1); execlp("man", "man", name.c_str(), NULL); throw SysError(format("command 'man %1%' failed") % name.c_str()); } int handleExceptions(const string & programName, std::function<void()> fun) { ReceiveInterrupts receiveInterrupts; // FIXME: need better place for this string error = ANSI_RED "error:" ANSI_NORMAL " "; try { try { fun(); } catch (...) { /* Subtle: we have to make sure that any `interrupted' condition is discharged before we reach printMsg() below, since otherwise it will throw an (uncaught) exception. */ setInterruptThrown(); throw; } } catch (Exit & e) { return e.status; } catch (UsageError & e) { printError( format(error + "%1%\nTry '%2% --help' for more information.") % e.what() % programName); return 1; } catch (BaseError & e) { printError(format(error + "%1%%2%") % (settings.showTrace ? e.prefix() : "") % e.msg()); if (e.prefix() != "" && !settings.showTrace) printError("(use '--show-trace' to show detailed location information)"); return e.status; } catch (std::bad_alloc & e) { printError(error + "out of memory"); return 1; } catch (std::exception & e) { printError(error + e.what()); return 1; } return 0; } RunPager::RunPager() { if (!isatty(STDOUT_FILENO)) return; char * pager = getenv("NIX_PAGER"); if (!pager) pager = getenv("PAGER"); if (pager && ((string) pager == "" || (string) pager == "cat")) return; Pipe toPager; toPager.create(); pid = startProcess([&]() { if (dup2(toPager.readSide.get(), STDIN_FILENO) == -1) throw SysError("dupping stdin"); if (!getenv("LESS")) setenv("LESS", "FRSXMK", 1); restoreSignals(); if (pager) execl("/bin/sh", "sh", "-c", pager, NULL); execlp("pager", "pager", NULL); execlp("less", "less", NULL); execlp("more", "more", NULL); throw SysError(format("executing '%1%'") % pager); }); pid.setKillSignal(SIGINT); if (dup2(toPager.writeSide.get(), STDOUT_FILENO) == -1) throw SysError("dupping stdout"); } RunPager::~RunPager() { try { if (pid != -1) { std::cout.flush(); close(STDOUT_FILENO); pid.wait(); } } catch (...) { ignoreException(); } } string showBytes(unsigned long long bytes) { return (format("%.2f MiB") % (bytes / (1024.0 * 1024.0))).str(); } PrintFreed::~PrintFreed() { if (show) std::cout << format("%1% store paths deleted, %2% freed\n") % results.paths.size() % showBytes(results.bytesFreed); } Exit::~Exit() { } } <commit_msg>execl: cast NULL sentinel to (char *), per man page and compiler warning<commit_after>#include "globals.hh" #include "shared.hh" #include "store-api.hh" #include "util.hh" #include <algorithm> #include <cctype> #include <exception> #include <iostream> #include <mutex> #include <cstdlib> #include <sys/time.h> #include <sys/stat.h> #include <unistd.h> #include <signal.h> #include <openssl/crypto.h> namespace nix { static bool gcWarning = true; void printGCWarning() { if (!gcWarning) return; static bool haveWarned = false; warnOnce(haveWarned, "you did not specify '--add-root'; " "the result might be removed by the garbage collector"); } void printMissing(ref<Store> store, const PathSet & paths, Verbosity lvl) { unsigned long long downloadSize, narSize; PathSet willBuild, willSubstitute, unknown; store->queryMissing(paths, willBuild, willSubstitute, unknown, downloadSize, narSize); printMissing(store, willBuild, willSubstitute, unknown, downloadSize, narSize, lvl); } void printMissing(ref<Store> store, const PathSet & willBuild, const PathSet & willSubstitute, const PathSet & unknown, unsigned long long downloadSize, unsigned long long narSize, Verbosity lvl) { if (!willBuild.empty()) { printMsg(lvl, "these derivations will be built:"); Paths sorted = store->topoSortPaths(willBuild); reverse(sorted.begin(), sorted.end()); for (auto & i : sorted) printMsg(lvl, fmt(" %s", i)); } if (!willSubstitute.empty()) { printMsg(lvl, fmt("these paths will be fetched (%.2f MiB download, %.2f MiB unpacked):", downloadSize / (1024.0 * 1024.0), narSize / (1024.0 * 1024.0))); for (auto & i : willSubstitute) printMsg(lvl, fmt(" %s", i)); } if (!unknown.empty()) { printMsg(lvl, fmt("don't know how to build these paths%s:", (settings.readOnlyMode ? " (may be caused by read-only store access)" : ""))); for (auto & i : unknown) printMsg(lvl, fmt(" %s", i)); } } string getArg(const string & opt, Strings::iterator & i, const Strings::iterator & end) { ++i; if (i == end) throw UsageError(format("'%1%' requires an argument") % opt); return *i; } /* OpenSSL is not thread-safe by default - it will randomly crash unless the user supplies a mutex locking function. So let's do that. */ static std::vector<std::mutex> opensslLocks; static void opensslLockCallback(int mode, int type, const char * file, int line) { if (mode & CRYPTO_LOCK) opensslLocks[type].lock(); else opensslLocks[type].unlock(); } static void sigHandler(int signo) { } void initNix() { /* Turn on buffering for cerr. */ #if HAVE_PUBSETBUF static char buf[1024]; std::cerr.rdbuf()->pubsetbuf(buf, sizeof(buf)); #endif /* Initialise OpenSSL locking. */ opensslLocks = std::vector<std::mutex>(CRYPTO_num_locks()); CRYPTO_set_locking_callback(opensslLockCallback); settings.loadConfFile(); startSignalHandlerThread(); /* Reset SIGCHLD to its default. */ struct sigaction act; sigemptyset(&act.sa_mask); act.sa_handler = SIG_DFL; act.sa_flags = 0; if (sigaction(SIGCHLD, &act, 0)) throw SysError("resetting SIGCHLD"); /* Install a dummy SIGUSR1 handler for use with pthread_kill(). */ act.sa_handler = sigHandler; if (sigaction(SIGUSR1, &act, 0)) throw SysError("handling SIGUSR1"); /* Register a SIGSEGV handler to detect stack overflows. */ detectStackOverflow(); /* There is no privacy in the Nix system ;-) At least not for now. In particular, store objects should be readable by everybody. */ umask(0022); /* Initialise the PRNG. */ struct timeval tv; gettimeofday(&tv, 0); srandom(tv.tv_usec); /* On macOS, don't use the per-session TMPDIR (as set e.g. by sshd). This breaks build users because they don't have access to the TMPDIR, in particular in ‘nix-store --serve’. */ #if __APPLE__ if (getuid() == 0 && hasPrefix(getEnv("TMPDIR"), "/var/folders/")) unsetenv("TMPDIR"); #endif } LegacyArgs::LegacyArgs(const std::string & programName, std::function<bool(Strings::iterator & arg, const Strings::iterator & end)> parseArg) : MixCommonArgs(programName), parseArg(parseArg) { mkFlag() .longName("no-build-output") .shortName('Q') .description("do not show build output") .set(&settings.verboseBuild, false); mkFlag() .longName("keep-failed") .shortName('K') .description("keep temporary directories of failed builds") .set(&(bool&) settings.keepFailed, true); mkFlag() .longName("keep-going") .shortName('k') .description("keep going after a build fails") .set(&(bool&) settings.keepGoing, true); mkFlag() .longName("fallback") .description("build from source if substitution fails") .set(&(bool&) settings.tryFallback, true); mkFlag1('j', "max-jobs", "jobs", "maximum number of parallel builds", [=](std::string s) { settings.set("max-jobs", s); }); auto intSettingAlias = [&](char shortName, const std::string & longName, const std::string & description, const std::string & dest) { mkFlag<unsigned int>(shortName, longName, description, [=](unsigned int n) { settings.set(dest, std::to_string(n)); }); }; intSettingAlias(0, "cores", "maximum number of CPU cores to use inside a build", "cores"); intSettingAlias(0, "max-silent-time", "number of seconds of silence before a build is killed", "max-silent-time"); intSettingAlias(0, "timeout", "number of seconds before a build is killed", "timeout"); mkFlag(0, "readonly-mode", "do not write to the Nix store", &settings.readOnlyMode); mkFlag(0, "no-gc-warning", "disable warning about not using '--add-root'", &gcWarning, false); mkFlag() .longName("store") .label("store-uri") .description("URI of the Nix store to use") .dest(&(std::string&) settings.storeUri); } bool LegacyArgs::processFlag(Strings::iterator & pos, Strings::iterator end) { if (MixCommonArgs::processFlag(pos, end)) return true; bool res = parseArg(pos, end); if (res) ++pos; return res; } bool LegacyArgs::processArgs(const Strings & args, bool finish) { if (args.empty()) return true; assert(args.size() == 1); Strings ss(args); auto pos = ss.begin(); if (!parseArg(pos, ss.end())) throw UsageError(format("unexpected argument '%1%'") % args.front()); return true; } void parseCmdLine(int argc, char * * argv, std::function<bool(Strings::iterator & arg, const Strings::iterator & end)> parseArg) { parseCmdLine(baseNameOf(argv[0]), argvToStrings(argc, argv), parseArg); } void parseCmdLine(const string & programName, const Strings & args, std::function<bool(Strings::iterator & arg, const Strings::iterator & end)> parseArg) { LegacyArgs(programName, parseArg).parseCmdline(args); } void printVersion(const string & programName) { std::cout << format("%1% (Nix) %2%") % programName % nixVersion << std::endl; if (verbosity > lvlInfo) { Strings cfg; #if HAVE_BOEHMGC cfg.push_back("gc"); #endif #if HAVE_SODIUM cfg.push_back("signed-caches"); #endif std::cout << "Features: " << concatStringsSep(", ", cfg) << "\n"; std::cout << "Configuration file: " << settings.nixConfDir + "/nix.conf" << "\n"; std::cout << "Store directory: " << settings.nixStore << "\n"; std::cout << "State directory: " << settings.nixStateDir << "\n"; } throw Exit(); } void showManPage(const string & name) { restoreSignals(); setenv("MANPATH", settings.nixManDir.c_str(), 1); execlp("man", "man", name.c_str(), (char *)NULL); throw SysError(format("command 'man %1%' failed") % name.c_str()); } int handleExceptions(const string & programName, std::function<void()> fun) { ReceiveInterrupts receiveInterrupts; // FIXME: need better place for this string error = ANSI_RED "error:" ANSI_NORMAL " "; try { try { fun(); } catch (...) { /* Subtle: we have to make sure that any `interrupted' condition is discharged before we reach printMsg() below, since otherwise it will throw an (uncaught) exception. */ setInterruptThrown(); throw; } } catch (Exit & e) { return e.status; } catch (UsageError & e) { printError( format(error + "%1%\nTry '%2% --help' for more information.") % e.what() % programName); return 1; } catch (BaseError & e) { printError(format(error + "%1%%2%") % (settings.showTrace ? e.prefix() : "") % e.msg()); if (e.prefix() != "" && !settings.showTrace) printError("(use '--show-trace' to show detailed location information)"); return e.status; } catch (std::bad_alloc & e) { printError(error + "out of memory"); return 1; } catch (std::exception & e) { printError(error + e.what()); return 1; } return 0; } RunPager::RunPager() { if (!isatty(STDOUT_FILENO)) return; char * pager = getenv("NIX_PAGER"); if (!pager) pager = getenv("PAGER"); if (pager && ((string) pager == "" || (string) pager == "cat")) return; Pipe toPager; toPager.create(); pid = startProcess([&]() { if (dup2(toPager.readSide.get(), STDIN_FILENO) == -1) throw SysError("dupping stdin"); if (!getenv("LESS")) setenv("LESS", "FRSXMK", 1); restoreSignals(); if (pager) execl("/bin/sh", "sh", "-c", pager, (char *)NULL); execlp("pager", "pager", (char *)NULL); execlp("less", "less", (char *)NULL); execlp("more", "more", (char *)NULL); throw SysError(format("executing '%1%'") % pager); }); pid.setKillSignal(SIGINT); if (dup2(toPager.writeSide.get(), STDOUT_FILENO) == -1) throw SysError("dupping stdout"); } RunPager::~RunPager() { try { if (pid != -1) { std::cout.flush(); close(STDOUT_FILENO); pid.wait(); } } catch (...) { ignoreException(); } } string showBytes(unsigned long long bytes) { return (format("%.2f MiB") % (bytes / (1024.0 * 1024.0))).str(); } PrintFreed::~PrintFreed() { if (show) std::cout << format("%1% store paths deleted, %2% freed\n") % results.paths.size() % showBytes(results.bytesFreed); } Exit::~Exit() { } } <|endoftext|>
<commit_before>#include "globals.hh" #include "shared.hh" #include "store-api.hh" #include "util.hh" #include "loggers.hh" #include <algorithm> #include <cctype> #include <exception> #include <iostream> #include <mutex> #include <cstdlib> #include <sys/time.h> #include <sys/stat.h> #include <unistd.h> #include <signal.h> #include <openssl/crypto.h> namespace nix { static bool gcWarning = true; void printGCWarning() { if (!gcWarning) return; static bool haveWarned = false; warnOnce(haveWarned, "you did not specify '--add-root'; " "the result might be removed by the garbage collector"); } void printMissing(ref<Store> store, const std::vector<StorePathWithOutputs> & paths, Verbosity lvl) { unsigned long long downloadSize, narSize; StorePathSet willBuild, willSubstitute, unknown; store->queryMissing(paths, willBuild, willSubstitute, unknown, downloadSize, narSize); printMissing(store, willBuild, willSubstitute, unknown, downloadSize, narSize, lvl); } void printMissing(ref<Store> store, const StorePathSet & willBuild, const StorePathSet & willSubstitute, const StorePathSet & unknown, unsigned long long downloadSize, unsigned long long narSize, Verbosity lvl) { if (!willBuild.empty()) { if (willBuild.size() == 1) printMsg(lvl, fmt("this derivation will be built:")); else printMsg(lvl, fmt("these %d derivations will be built:", willBuild.size())); auto sorted = store->topoSortPaths(willBuild); reverse(sorted.begin(), sorted.end()); for (auto & i : sorted) printMsg(lvl, fmt(" %s", store->printStorePath(i))); } if (!willSubstitute.empty()) { const float downloadSizeMiB = downloadSize / (1024.f * 1024.f); const float narSizeMiB = narSize / (1024.f * 1024.f); if (willSubstitute.size() == 1) { printMsg(lvl, fmt("this path will be fetched (%.2f MiB download, %.2f MiB unpacked):", downloadSizeMiB, narSizeMiB)); } else { printMsg(lvl, fmt("these %d paths will be fetched (%.2f MiB download, %.2f MiB unpacked):", willSubstitute.size(), downloadSizeMiB, narSizeMiB)); } for (auto & i : willSubstitute) printMsg(lvl, fmt(" %s", store->printStorePath(i))); } if (!unknown.empty()) { printMsg(lvl, fmt("don't know how to build these paths%s:", (settings.readOnlyMode ? " (may be caused by read-only store access)" : ""))); for (auto & i : unknown) printMsg(lvl, fmt(" %s", store->printStorePath(i))); } } string getArg(const string & opt, Strings::iterator & i, const Strings::iterator & end) { ++i; if (i == end) throw UsageError("'%1%' requires an argument", opt); return *i; } #if OPENSSL_VERSION_NUMBER < 0x10101000L /* OpenSSL is not thread-safe by default - it will randomly crash unless the user supplies a mutex locking function. So let's do that. */ static std::vector<std::mutex> opensslLocks; static void opensslLockCallback(int mode, int type, const char * file, int line) { if (mode & CRYPTO_LOCK) opensslLocks[type].lock(); else opensslLocks[type].unlock(); } #endif static void sigHandler(int signo) { } void initNix() { /* Turn on buffering for cerr. */ #if HAVE_PUBSETBUF static char buf[1024]; std::cerr.rdbuf()->pubsetbuf(buf, sizeof(buf)); #endif #if OPENSSL_VERSION_NUMBER < 0x10101000L /* Initialise OpenSSL locking. */ opensslLocks = std::vector<std::mutex>(CRYPTO_num_locks()); CRYPTO_set_locking_callback(opensslLockCallback); #endif loadConfFile(); startSignalHandlerThread(); /* Reset SIGCHLD to its default. */ struct sigaction act; sigemptyset(&act.sa_mask); act.sa_handler = SIG_DFL; act.sa_flags = 0; if (sigaction(SIGCHLD, &act, 0)) throw SysError("resetting SIGCHLD"); /* Install a dummy SIGUSR1 handler for use with pthread_kill(). */ act.sa_handler = sigHandler; if (sigaction(SIGUSR1, &act, 0)) throw SysError("handling SIGUSR1"); #if __APPLE__ /* HACK: on darwin, we need can’t use sigprocmask with SIGWINCH. * Instead, add a dummy sigaction handler, and signalHandlerThread * can handle the rest. */ struct sigaction sa; sa.sa_handler = sigHandler; if (sigaction(SIGWINCH, &sa, 0)) throw SysError("handling SIGWINCH"); #endif /* Register a SIGSEGV handler to detect stack overflows. */ detectStackOverflow(); /* There is no privacy in the Nix system ;-) At least not for now. In particular, store objects should be readable by everybody. */ umask(0022); /* Initialise the PRNG. */ struct timeval tv; gettimeofday(&tv, 0); srandom(tv.tv_usec); /* On macOS, don't use the per-session TMPDIR (as set e.g. by sshd). This breaks build users because they don't have access to the TMPDIR, in particular in ‘nix-store --serve’. */ #if __APPLE__ if (hasPrefix(getEnv("TMPDIR").value_or("/tmp"), "/var/folders/")) unsetenv("TMPDIR"); #endif } LegacyArgs::LegacyArgs(const std::string & programName, std::function<bool(Strings::iterator & arg, const Strings::iterator & end)> parseArg) : MixCommonArgs(programName), parseArg(parseArg) { addFlag({ .longName = "no-build-output", .shortName = 'Q', .description = "do not show build output", .handler = {[&]() {setLogFormat(LogFormat::raw); }}, }); addFlag({ .longName = "keep-failed", .shortName ='K', .description = "keep temporary directories of failed builds", .handler = {&(bool&) settings.keepFailed, true}, }); addFlag({ .longName = "keep-going", .shortName ='k', .description = "keep going after a build fails", .handler = {&(bool&) settings.keepGoing, true}, }); addFlag({ .longName = "fallback", .description = "build from source if substitution fails", .handler = {&(bool&) settings.tryFallback, true}, }); auto intSettingAlias = [&](char shortName, const std::string & longName, const std::string & description, const std::string & dest) { mkFlag<unsigned int>(shortName, longName, description, [=](unsigned int n) { settings.set(dest, std::to_string(n)); }); }; intSettingAlias(0, "cores", "maximum number of CPU cores to use inside a build", "cores"); intSettingAlias(0, "max-silent-time", "number of seconds of silence before a build is killed", "max-silent-time"); intSettingAlias(0, "timeout", "number of seconds before a build is killed", "timeout"); mkFlag(0, "readonly-mode", "do not write to the Nix store", &settings.readOnlyMode); mkFlag(0, "no-gc-warning", "disable warning about not using '--add-root'", &gcWarning, false); addFlag({ .longName = "store", .description = "URI of the Nix store to use", .labels = {"store-uri"}, .handler = {&(std::string&) settings.storeUri}, }); } bool LegacyArgs::processFlag(Strings::iterator & pos, Strings::iterator end) { if (MixCommonArgs::processFlag(pos, end)) return true; bool res = parseArg(pos, end); if (res) ++pos; return res; } bool LegacyArgs::processArgs(const Strings & args, bool finish) { if (args.empty()) return true; assert(args.size() == 1); Strings ss(args); auto pos = ss.begin(); if (!parseArg(pos, ss.end())) throw UsageError("unexpected argument '%1%'", args.front()); return true; } void parseCmdLine(int argc, char * * argv, std::function<bool(Strings::iterator & arg, const Strings::iterator & end)> parseArg) { parseCmdLine(std::string(baseNameOf(argv[0])), argvToStrings(argc, argv), parseArg); } void parseCmdLine(const string & programName, const Strings & args, std::function<bool(Strings::iterator & arg, const Strings::iterator & end)> parseArg) { LegacyArgs(programName, parseArg).parseCmdline(args); } void printVersion(const string & programName) { std::cout << format("%1% (Nix) %2%") % programName % nixVersion << std::endl; if (verbosity > lvlInfo) { Strings cfg; #if HAVE_BOEHMGC cfg.push_back("gc"); #endif #if HAVE_SODIUM cfg.push_back("signed-caches"); #endif std::cout << "Features: " << concatStringsSep(", ", cfg) << "\n"; std::cout << "System configuration file: " << settings.nixConfDir + "/nix.conf" << "\n"; std::cout << "User configuration files: " << concatStringsSep(":", settings.nixUserConfFiles) << "\n"; std::cout << "Store directory: " << settings.nixStore << "\n"; std::cout << "State directory: " << settings.nixStateDir << "\n"; } throw Exit(); } void showManPage(const string & name) { restoreSignals(); setenv("MANPATH", settings.nixManDir.c_str(), 1); execlp("man", "man", name.c_str(), nullptr); throw SysError("command 'man %1%' failed", name.c_str()); } int handleExceptions(const string & programName, std::function<void()> fun) { ReceiveInterrupts receiveInterrupts; // FIXME: need better place for this ErrorInfo::programName = baseNameOf(programName); string error = ANSI_RED "error:" ANSI_NORMAL " "; try { try { fun(); } catch (...) { /* Subtle: we have to make sure that any `interrupted' condition is discharged before we reach printMsg() below, since otherwise it will throw an (uncaught) exception. */ setInterruptThrown(); throw; } } catch (Exit & e) { return e.status; } catch (UsageError & e) { logError(e.info()); printError("Try '%1% --help' for more information.", programName); return 1; } catch (BaseError & e) { logError(e.info()); if (e.hasTrace() && !loggerSettings.showTrace.get()) printError("(use '--show-trace' to show detailed location information)"); return e.status; } catch (std::bad_alloc & e) { printError(error + "out of memory"); return 1; } catch (std::exception & e) { printError(error + e.what()); return 1; } return 0; } RunPager::RunPager() { if (!isatty(STDOUT_FILENO)) return; char * pager = getenv("NIX_PAGER"); if (!pager) pager = getenv("PAGER"); if (pager && ((string) pager == "" || (string) pager == "cat")) return; Pipe toPager; toPager.create(); pid = startProcess([&]() { if (dup2(toPager.readSide.get(), STDIN_FILENO) == -1) throw SysError("dupping stdin"); if (!getenv("LESS")) setenv("LESS", "FRSXMK", 1); restoreSignals(); if (pager) execl("/bin/sh", "sh", "-c", pager, nullptr); execlp("pager", "pager", nullptr); execlp("less", "less", nullptr); execlp("more", "more", nullptr); throw SysError("executing '%1%'", pager); }); pid.setKillSignal(SIGINT); if (dup2(toPager.writeSide.get(), STDOUT_FILENO) == -1) throw SysError("dupping stdout"); } RunPager::~RunPager() { try { if (pid != -1) { std::cout.flush(); close(STDOUT_FILENO); pid.wait(); } } catch (...) { ignoreException(); } } string showBytes(unsigned long long bytes) { return (format("%.2f MiB") % (bytes / (1024.0 * 1024.0))).str(); } PrintFreed::~PrintFreed() { if (show) std::cout << format("%1% store paths deleted, %2% freed\n") % results.paths.size() % showBytes(results.bytesFreed); } Exit::~Exit() { } } <commit_msg>printVersion(): Show system types<commit_after>#include "globals.hh" #include "shared.hh" #include "store-api.hh" #include "util.hh" #include "loggers.hh" #include <algorithm> #include <cctype> #include <exception> #include <iostream> #include <mutex> #include <cstdlib> #include <sys/time.h> #include <sys/stat.h> #include <unistd.h> #include <signal.h> #include <openssl/crypto.h> namespace nix { static bool gcWarning = true; void printGCWarning() { if (!gcWarning) return; static bool haveWarned = false; warnOnce(haveWarned, "you did not specify '--add-root'; " "the result might be removed by the garbage collector"); } void printMissing(ref<Store> store, const std::vector<StorePathWithOutputs> & paths, Verbosity lvl) { unsigned long long downloadSize, narSize; StorePathSet willBuild, willSubstitute, unknown; store->queryMissing(paths, willBuild, willSubstitute, unknown, downloadSize, narSize); printMissing(store, willBuild, willSubstitute, unknown, downloadSize, narSize, lvl); } void printMissing(ref<Store> store, const StorePathSet & willBuild, const StorePathSet & willSubstitute, const StorePathSet & unknown, unsigned long long downloadSize, unsigned long long narSize, Verbosity lvl) { if (!willBuild.empty()) { if (willBuild.size() == 1) printMsg(lvl, fmt("this derivation will be built:")); else printMsg(lvl, fmt("these %d derivations will be built:", willBuild.size())); auto sorted = store->topoSortPaths(willBuild); reverse(sorted.begin(), sorted.end()); for (auto & i : sorted) printMsg(lvl, fmt(" %s", store->printStorePath(i))); } if (!willSubstitute.empty()) { const float downloadSizeMiB = downloadSize / (1024.f * 1024.f); const float narSizeMiB = narSize / (1024.f * 1024.f); if (willSubstitute.size() == 1) { printMsg(lvl, fmt("this path will be fetched (%.2f MiB download, %.2f MiB unpacked):", downloadSizeMiB, narSizeMiB)); } else { printMsg(lvl, fmt("these %d paths will be fetched (%.2f MiB download, %.2f MiB unpacked):", willSubstitute.size(), downloadSizeMiB, narSizeMiB)); } for (auto & i : willSubstitute) printMsg(lvl, fmt(" %s", store->printStorePath(i))); } if (!unknown.empty()) { printMsg(lvl, fmt("don't know how to build these paths%s:", (settings.readOnlyMode ? " (may be caused by read-only store access)" : ""))); for (auto & i : unknown) printMsg(lvl, fmt(" %s", store->printStorePath(i))); } } string getArg(const string & opt, Strings::iterator & i, const Strings::iterator & end) { ++i; if (i == end) throw UsageError("'%1%' requires an argument", opt); return *i; } #if OPENSSL_VERSION_NUMBER < 0x10101000L /* OpenSSL is not thread-safe by default - it will randomly crash unless the user supplies a mutex locking function. So let's do that. */ static std::vector<std::mutex> opensslLocks; static void opensslLockCallback(int mode, int type, const char * file, int line) { if (mode & CRYPTO_LOCK) opensslLocks[type].lock(); else opensslLocks[type].unlock(); } #endif static void sigHandler(int signo) { } void initNix() { /* Turn on buffering for cerr. */ #if HAVE_PUBSETBUF static char buf[1024]; std::cerr.rdbuf()->pubsetbuf(buf, sizeof(buf)); #endif #if OPENSSL_VERSION_NUMBER < 0x10101000L /* Initialise OpenSSL locking. */ opensslLocks = std::vector<std::mutex>(CRYPTO_num_locks()); CRYPTO_set_locking_callback(opensslLockCallback); #endif loadConfFile(); startSignalHandlerThread(); /* Reset SIGCHLD to its default. */ struct sigaction act; sigemptyset(&act.sa_mask); act.sa_handler = SIG_DFL; act.sa_flags = 0; if (sigaction(SIGCHLD, &act, 0)) throw SysError("resetting SIGCHLD"); /* Install a dummy SIGUSR1 handler for use with pthread_kill(). */ act.sa_handler = sigHandler; if (sigaction(SIGUSR1, &act, 0)) throw SysError("handling SIGUSR1"); #if __APPLE__ /* HACK: on darwin, we need can’t use sigprocmask with SIGWINCH. * Instead, add a dummy sigaction handler, and signalHandlerThread * can handle the rest. */ struct sigaction sa; sa.sa_handler = sigHandler; if (sigaction(SIGWINCH, &sa, 0)) throw SysError("handling SIGWINCH"); #endif /* Register a SIGSEGV handler to detect stack overflows. */ detectStackOverflow(); /* There is no privacy in the Nix system ;-) At least not for now. In particular, store objects should be readable by everybody. */ umask(0022); /* Initialise the PRNG. */ struct timeval tv; gettimeofday(&tv, 0); srandom(tv.tv_usec); /* On macOS, don't use the per-session TMPDIR (as set e.g. by sshd). This breaks build users because they don't have access to the TMPDIR, in particular in ‘nix-store --serve’. */ #if __APPLE__ if (hasPrefix(getEnv("TMPDIR").value_or("/tmp"), "/var/folders/")) unsetenv("TMPDIR"); #endif } LegacyArgs::LegacyArgs(const std::string & programName, std::function<bool(Strings::iterator & arg, const Strings::iterator & end)> parseArg) : MixCommonArgs(programName), parseArg(parseArg) { addFlag({ .longName = "no-build-output", .shortName = 'Q', .description = "do not show build output", .handler = {[&]() {setLogFormat(LogFormat::raw); }}, }); addFlag({ .longName = "keep-failed", .shortName ='K', .description = "keep temporary directories of failed builds", .handler = {&(bool&) settings.keepFailed, true}, }); addFlag({ .longName = "keep-going", .shortName ='k', .description = "keep going after a build fails", .handler = {&(bool&) settings.keepGoing, true}, }); addFlag({ .longName = "fallback", .description = "build from source if substitution fails", .handler = {&(bool&) settings.tryFallback, true}, }); auto intSettingAlias = [&](char shortName, const std::string & longName, const std::string & description, const std::string & dest) { mkFlag<unsigned int>(shortName, longName, description, [=](unsigned int n) { settings.set(dest, std::to_string(n)); }); }; intSettingAlias(0, "cores", "maximum number of CPU cores to use inside a build", "cores"); intSettingAlias(0, "max-silent-time", "number of seconds of silence before a build is killed", "max-silent-time"); intSettingAlias(0, "timeout", "number of seconds before a build is killed", "timeout"); mkFlag(0, "readonly-mode", "do not write to the Nix store", &settings.readOnlyMode); mkFlag(0, "no-gc-warning", "disable warning about not using '--add-root'", &gcWarning, false); addFlag({ .longName = "store", .description = "URI of the Nix store to use", .labels = {"store-uri"}, .handler = {&(std::string&) settings.storeUri}, }); } bool LegacyArgs::processFlag(Strings::iterator & pos, Strings::iterator end) { if (MixCommonArgs::processFlag(pos, end)) return true; bool res = parseArg(pos, end); if (res) ++pos; return res; } bool LegacyArgs::processArgs(const Strings & args, bool finish) { if (args.empty()) return true; assert(args.size() == 1); Strings ss(args); auto pos = ss.begin(); if (!parseArg(pos, ss.end())) throw UsageError("unexpected argument '%1%'", args.front()); return true; } void parseCmdLine(int argc, char * * argv, std::function<bool(Strings::iterator & arg, const Strings::iterator & end)> parseArg) { parseCmdLine(std::string(baseNameOf(argv[0])), argvToStrings(argc, argv), parseArg); } void parseCmdLine(const string & programName, const Strings & args, std::function<bool(Strings::iterator & arg, const Strings::iterator & end)> parseArg) { LegacyArgs(programName, parseArg).parseCmdline(args); } void printVersion(const string & programName) { std::cout << format("%1% (Nix) %2%") % programName % nixVersion << std::endl; if (verbosity > lvlInfo) { Strings cfg; #if HAVE_BOEHMGC cfg.push_back("gc"); #endif #if HAVE_SODIUM cfg.push_back("signed-caches"); #endif std::cout << "System type: " << settings.thisSystem << "\n"; std::cout << "Additional system types: " << concatStringsSep(", ", settings.extraPlatforms.get()) << "\n"; std::cout << "Features: " << concatStringsSep(", ", cfg) << "\n"; std::cout << "System configuration file: " << settings.nixConfDir + "/nix.conf" << "\n"; std::cout << "User configuration files: " << concatStringsSep(":", settings.nixUserConfFiles) << "\n"; std::cout << "Store directory: " << settings.nixStore << "\n"; std::cout << "State directory: " << settings.nixStateDir << "\n"; } throw Exit(); } void showManPage(const string & name) { restoreSignals(); setenv("MANPATH", settings.nixManDir.c_str(), 1); execlp("man", "man", name.c_str(), nullptr); throw SysError("command 'man %1%' failed", name.c_str()); } int handleExceptions(const string & programName, std::function<void()> fun) { ReceiveInterrupts receiveInterrupts; // FIXME: need better place for this ErrorInfo::programName = baseNameOf(programName); string error = ANSI_RED "error:" ANSI_NORMAL " "; try { try { fun(); } catch (...) { /* Subtle: we have to make sure that any `interrupted' condition is discharged before we reach printMsg() below, since otherwise it will throw an (uncaught) exception. */ setInterruptThrown(); throw; } } catch (Exit & e) { return e.status; } catch (UsageError & e) { logError(e.info()); printError("Try '%1% --help' for more information.", programName); return 1; } catch (BaseError & e) { logError(e.info()); if (e.hasTrace() && !loggerSettings.showTrace.get()) printError("(use '--show-trace' to show detailed location information)"); return e.status; } catch (std::bad_alloc & e) { printError(error + "out of memory"); return 1; } catch (std::exception & e) { printError(error + e.what()); return 1; } return 0; } RunPager::RunPager() { if (!isatty(STDOUT_FILENO)) return; char * pager = getenv("NIX_PAGER"); if (!pager) pager = getenv("PAGER"); if (pager && ((string) pager == "" || (string) pager == "cat")) return; Pipe toPager; toPager.create(); pid = startProcess([&]() { if (dup2(toPager.readSide.get(), STDIN_FILENO) == -1) throw SysError("dupping stdin"); if (!getenv("LESS")) setenv("LESS", "FRSXMK", 1); restoreSignals(); if (pager) execl("/bin/sh", "sh", "-c", pager, nullptr); execlp("pager", "pager", nullptr); execlp("less", "less", nullptr); execlp("more", "more", nullptr); throw SysError("executing '%1%'", pager); }); pid.setKillSignal(SIGINT); if (dup2(toPager.writeSide.get(), STDOUT_FILENO) == -1) throw SysError("dupping stdout"); } RunPager::~RunPager() { try { if (pid != -1) { std::cout.flush(); close(STDOUT_FILENO); pid.wait(); } } catch (...) { ignoreException(); } } string showBytes(unsigned long long bytes) { return (format("%.2f MiB") % (bytes / (1024.0 * 1024.0))).str(); } PrintFreed::~PrintFreed() { if (show) std::cout << format("%1% store paths deleted, %2% freed\n") % results.paths.size() % showBytes(results.bytesFreed); } Exit::~Exit() { } } <|endoftext|>
<commit_before>/* Copyright (C) 2005-2008, Thorvald Natvig <[email protected]> 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 Mumble Developers 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 FOUNDATION 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 "ConfigDialog.h" #include "AudioInput.h" #include "AudioOutput.h" #include "Global.h" QMap<int, ConfigWidgetNew> *ConfigRegistrar::c_qmNew; ConfigRegistrar::ConfigRegistrar(int priority, ConfigWidgetNew n) { if (! c_qmNew) c_qmNew = new QMap<int, ConfigWidgetNew>(); c_qmNew->insert(priority,n); } ConfigWidget::ConfigWidget(Settings &st) : s(st) { } QIcon ConfigWidget::icon() const { return qApp->windowIcon(); } void ConfigWidget::accept() const { } void ConfigWidget::loadSlider(QSlider *s, int v) { if (v != s->value()) { s->setValue(v); } else if (v != s->minimum()) { s->setValue(s->minimum()); s->setValue(v); } else { s->setValue(s->maximum()); s->setValue(v); } } void ConfigWidget::loadCheckBox(QAbstractButton *c, bool v) { c->setChecked(! v); c->setChecked(v); } void ConfigWidget::loadComboBox(QComboBox *c, int v) { if (c->currentIndex() != v) { c->setCurrentIndex(v); } else if (v != 0) { c->setCurrentIndex(0); c->setCurrentIndex(v); } else if (c->count() >= 2) { c->setCurrentIndex(1); c->setCurrentIndex(v); } } ConfigDialog::ConfigDialog(QWidget *p) : QDialog(p) { setupUi(this); s = g.s; QWidget *w; while ((w = qswPages->widget(0))) delete w; qcbExpert->setChecked(g.s.bExpert); ConfigWidgetNew cwn; foreach(cwn, *ConfigRegistrar::c_qmNew) { addPage(cwn(s)); } if (qlwIcons->count() > 0) qlwIcons->setCurrentItem(qlwIcons->item(0)); on_qcbExpert_clicked(g.s.bExpert); QPushButton *okButton = dialogButtonBox->button(QDialogButtonBox::Ok); okButton->setToolTip(tr("Accept changes")); okButton->setWhatsThis(tr("This button will accept current settings and return to the application.<br />" "The settings will be stored to disk when you leave the application.")); QPushButton *cancelButton = dialogButtonBox->button(QDialogButtonBox::Cancel); cancelButton->setToolTip(tr("Reject changes")); cancelButton->setWhatsThis(tr("This button will reject all changes and return to the application.<br />" "The settings will be reset to the previous positions.")); QPushButton *applyButton = dialogButtonBox->button(QDialogButtonBox::Apply); applyButton->setToolTip(tr("Apply changes")); applyButton->setWhatsThis(tr("This button will immediately apply all changes.")); QPushButton *resetButton = pageButtonBox->button(QDialogButtonBox::Reset); resetButton->setToolTip(tr("Undo changes for current page")); resetButton->setWhatsThis(tr("This button will revert any changes done on the current page to the most recent applied settings.")); QPushButton *restoreButton = pageButtonBox->button(QDialogButtonBox::RestoreDefaults); restoreButton->setToolTip(tr("Restore defaults for current page")); restoreButton->setWhatsThis(tr("This button will restore the settings for the current page only to their defaults. Other pages will be not be changed.<br />" "To restore all settings to their defaults, you will have to use this button on every page." )); } void ConfigDialog::addPage(ConfigWidget *cw) { QDesktopWidget dw; QRect ds=dw.availableGeometry(this); QSize ms=cw->minimumSizeHint(); cw->resize(ms); cw->setMinimumSize(ms); ms.rwidth() += 128; ms.rheight() += 64; if ((ms.width() > ds.width()) || (ms.height() > ds.height())) { QScrollArea *qsa=new QScrollArea(this); qsa->setWidgetResizable(true); qsa->setWidget(cw); qswPages->addWidget(qsa); qWarning("Widget %s has size %d %d (%d %d)", qPrintable(cw->title()), ms.width(), ms.height(),ds.width(), ds.height()); } else { qswPages->addWidget(cw); } QListWidgetItem *i = new QListWidgetItem(qlwIcons); i->setIcon(cw->icon()); i->setText(cw->title()); i->setTextAlignment(Qt::AlignHCenter); i->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); widgets << cw; cw->load(g.s); } void ConfigDialog::on_qlwIcons_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous) { if (!current) current = previous; if (current) qswPages->setCurrentIndex(qlwIcons->row(current)); } void ConfigDialog::on_pageButtonBox_clicked(QAbstractButton *b) { ConfigWidget *conf = qobject_cast<ConfigWidget *>(qswPages->currentWidget()); switch (pageButtonBox->standardButton(b)) { case QDialogButtonBox::RestoreDefaults: { Settings def; if (conf) conf->load(def); break; } case QDialogButtonBox::Reset: { if (conf) conf->load(g.s); break; } default: break; } } void ConfigDialog::on_dialogButtonBox_clicked(QAbstractButton *b) { switch (dialogButtonBox->standardButton(b)) { case QDialogButtonBox::Apply: { apply(); break; } default: break; } } void ConfigDialog::on_qcbExpert_clicked(bool b) { int idx = 0; foreach(ConfigWidget *cw, widgets) { bool showit = cw->expert(b); showit = showit || b; QListWidgetItem *qlwi = qlwIcons->item(idx++); if (qlwi) qlwi->setHidden(!showit); } } void ConfigDialog::apply() { foreach(ConfigWidget *cw, widgets) cw->save(); boost::weak_ptr<AudioInput> wai(g.ai); boost::weak_ptr<AudioOutput> wao(g.ao); g.ai.reset(); g.ao.reset(); while (! wai.expired() || ! wao.expired()) { // Where is QThread::yield() ? } g.s = s; foreach(ConfigWidget *cw, widgets) cw->accept(); g.ai = AudioInputRegistrar::newFromChoice(g.s.qsAudioInput); g.ai->start(QThread::HighestPriority); g.ao = AudioOutputRegistrar::newFromChoice(g.s.qsAudioOutput); g.ao->start(QThread::HighPriority); // They might have changed their keys. g.iPushToTalk = 0; g.iAltSpeak = 0; g.s.bExpert = qcbExpert->isChecked(); } void ConfigDialog::accept() { apply(); QDialog::accept(); } <commit_msg>Increase safety size for config widgets<commit_after>/* Copyright (C) 2005-2008, Thorvald Natvig <[email protected]> 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 Mumble Developers 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 FOUNDATION 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 "ConfigDialog.h" #include "AudioInput.h" #include "AudioOutput.h" #include "Global.h" QMap<int, ConfigWidgetNew> *ConfigRegistrar::c_qmNew; ConfigRegistrar::ConfigRegistrar(int priority, ConfigWidgetNew n) { if (! c_qmNew) c_qmNew = new QMap<int, ConfigWidgetNew>(); c_qmNew->insert(priority,n); } ConfigWidget::ConfigWidget(Settings &st) : s(st) { } QIcon ConfigWidget::icon() const { return qApp->windowIcon(); } void ConfigWidget::accept() const { } void ConfigWidget::loadSlider(QSlider *s, int v) { if (v != s->value()) { s->setValue(v); } else if (v != s->minimum()) { s->setValue(s->minimum()); s->setValue(v); } else { s->setValue(s->maximum()); s->setValue(v); } } void ConfigWidget::loadCheckBox(QAbstractButton *c, bool v) { c->setChecked(! v); c->setChecked(v); } void ConfigWidget::loadComboBox(QComboBox *c, int v) { if (c->currentIndex() != v) { c->setCurrentIndex(v); } else if (v != 0) { c->setCurrentIndex(0); c->setCurrentIndex(v); } else if (c->count() >= 2) { c->setCurrentIndex(1); c->setCurrentIndex(v); } } ConfigDialog::ConfigDialog(QWidget *p) : QDialog(p) { setupUi(this); s = g.s; QWidget *w; while ((w = qswPages->widget(0))) delete w; qcbExpert->setChecked(g.s.bExpert); ConfigWidgetNew cwn; foreach(cwn, *ConfigRegistrar::c_qmNew) { addPage(cwn(s)); } if (qlwIcons->count() > 0) qlwIcons->setCurrentItem(qlwIcons->item(0)); on_qcbExpert_clicked(g.s.bExpert); QPushButton *okButton = dialogButtonBox->button(QDialogButtonBox::Ok); okButton->setToolTip(tr("Accept changes")); okButton->setWhatsThis(tr("This button will accept current settings and return to the application.<br />" "The settings will be stored to disk when you leave the application.")); QPushButton *cancelButton = dialogButtonBox->button(QDialogButtonBox::Cancel); cancelButton->setToolTip(tr("Reject changes")); cancelButton->setWhatsThis(tr("This button will reject all changes and return to the application.<br />" "The settings will be reset to the previous positions.")); QPushButton *applyButton = dialogButtonBox->button(QDialogButtonBox::Apply); applyButton->setToolTip(tr("Apply changes")); applyButton->setWhatsThis(tr("This button will immediately apply all changes.")); QPushButton *resetButton = pageButtonBox->button(QDialogButtonBox::Reset); resetButton->setToolTip(tr("Undo changes for current page")); resetButton->setWhatsThis(tr("This button will revert any changes done on the current page to the most recent applied settings.")); QPushButton *restoreButton = pageButtonBox->button(QDialogButtonBox::RestoreDefaults); restoreButton->setToolTip(tr("Restore defaults for current page")); restoreButton->setWhatsThis(tr("This button will restore the settings for the current page only to their defaults. Other pages will be not be changed.<br />" "To restore all settings to their defaults, you will have to use this button on every page." )); } void ConfigDialog::addPage(ConfigWidget *cw) { QDesktopWidget dw; QRect ds=dw.availableGeometry(this); QSize ms=cw->minimumSizeHint(); cw->resize(ms); cw->setMinimumSize(ms); ms.rwidth() += 128; ms.rheight() += 192; if ((ms.width() > ds.width()) || (ms.height() > ds.height())) { QScrollArea *qsa=new QScrollArea(this); qsa->setWidgetResizable(true); qsa->setWidget(cw); qswPages->addWidget(qsa); qWarning("Widget %s has size %d %d (%d %d)", qPrintable(cw->title()), ms.width(), ms.height(),ds.width(), ds.height()); } else { qswPages->addWidget(cw); } QListWidgetItem *i = new QListWidgetItem(qlwIcons); i->setIcon(cw->icon()); i->setText(cw->title()); i->setTextAlignment(Qt::AlignHCenter); i->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); widgets << cw; cw->load(g.s); } void ConfigDialog::on_qlwIcons_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous) { if (!current) current = previous; if (current) qswPages->setCurrentIndex(qlwIcons->row(current)); } void ConfigDialog::on_pageButtonBox_clicked(QAbstractButton *b) { ConfigWidget *conf = qobject_cast<ConfigWidget *>(qswPages->currentWidget()); switch (pageButtonBox->standardButton(b)) { case QDialogButtonBox::RestoreDefaults: { Settings def; if (conf) conf->load(def); break; } case QDialogButtonBox::Reset: { if (conf) conf->load(g.s); break; } default: break; } } void ConfigDialog::on_dialogButtonBox_clicked(QAbstractButton *b) { switch (dialogButtonBox->standardButton(b)) { case QDialogButtonBox::Apply: { apply(); break; } default: break; } } void ConfigDialog::on_qcbExpert_clicked(bool b) { int idx = 0; foreach(ConfigWidget *cw, widgets) { bool showit = cw->expert(b); showit = showit || b; QListWidgetItem *qlwi = qlwIcons->item(idx++); if (qlwi) qlwi->setHidden(!showit); } } void ConfigDialog::apply() { foreach(ConfigWidget *cw, widgets) cw->save(); boost::weak_ptr<AudioInput> wai(g.ai); boost::weak_ptr<AudioOutput> wao(g.ao); g.ai.reset(); g.ao.reset(); while (! wai.expired() || ! wao.expired()) { // Where is QThread::yield() ? } g.s = s; foreach(ConfigWidget *cw, widgets) cw->accept(); g.ai = AudioInputRegistrar::newFromChoice(g.s.qsAudioInput); g.ai->start(QThread::HighestPriority); g.ao = AudioOutputRegistrar::newFromChoice(g.s.qsAudioOutput); g.ao->start(QThread::HighPriority); // They might have changed their keys. g.iPushToTalk = 0; g.iAltSpeak = 0; g.s.bExpert = qcbExpert->isChecked(); } void ConfigDialog::accept() { apply(); QDialog::accept(); } <|endoftext|>
<commit_before>// Copyright (c) 2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpcnestedtests.h" #include "chainparams.h" #include "consensus/validation.h" #include "validation.h" #include "rpc/register.h" #include "rpc/server.h" #include "rpcconsole.h" #include "test/testutil.h" #include "univalue.h" #include "util.h" #include <QDir> #include <QtGlobal> #include <boost/filesystem.hpp> static UniValue rpcNestedTest_rpc(const JSONRPCRequest& request) { if (request.fHelp) { return "help message"; } return request.params.write(0, 0); } static const CRPCCommand vRPCCommands[] = { { "test", "rpcNestedTest", &rpcNestedTest_rpc, true, {} }, }; void RPCNestedTests::rpcNestedTests() { UniValue jsonRPCError; // do some test setup // could be moved to a more generic place when we add more tests on QT level const CChainParams& chainparams = Params(); RegisterAllCoreRPCCommands(tableRPC); tableRPC.appendCommand("rpcNestedTest", &vRPCCommands[0]); ClearDatadirCache(); std::string path = QDir::tempPath().toStdString() + "/" + strprintf("test_goldcoin_qt_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000))); QDir dir(QString::fromStdString(path)); dir.mkpath("."); ForceSetArg("-datadir", path); //mempool.setSanityCheck(1.0); pblocktree = new CBlockTreeDB(1 << 20, true); pcoinsdbview = new CCoinsViewDB(1 << 23, true); pcoinsTip = new CCoinsViewCache(pcoinsdbview); InitBlockIndex(chainparams); { CValidationState state; bool ok = ActivateBestChain(state, chainparams); QVERIFY(ok); } SetRPCWarmupFinished(); std::string result; std::string result2; std::string filtered; RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()[chain]", &filtered); //simple result filtering with path QVERIFY(result=="main"); QVERIFY(filtered == "getblockchaininfo()[chain]"); RPCConsole::RPCExecuteCommandLine(result, "getblock(getbestblockhash())"); //simple 2 level nesting RPCConsole::RPCExecuteCommandLine(result, "getblock(getblock(getbestblockhash())[hash], true)"); RPCConsole::RPCExecuteCommandLine(result, "getblock( getblock( getblock(getbestblockhash())[hash] )[hash], true)"); //4 level nesting with whitespace, filtering path and boolean parameter RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo"); QVERIFY(result.substr(0,1) == "{"); RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()"); QVERIFY(result.substr(0,1) == "{"); RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo "); //whitespace at the end will be tolerated QVERIFY(result.substr(0,1) == "{"); (RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()[\"chain\"]")); //Quote path identifier are allowed, but look after a child contaning the quotes in the key QVERIFY(result == "null"); (RPCConsole::RPCExecuteCommandLine(result, "createrawtransaction [] {} 0")); //parameter not in brackets are allowed (RPCConsole::RPCExecuteCommandLine(result2, "createrawtransaction([],{},0)")); //parameter in brackets are allowed QVERIFY(result == result2); (RPCConsole::RPCExecuteCommandLine(result2, "createrawtransaction( [], {} , 0 )")); //whitespace between parametres is allowed QVERIFY(result == result2); RPCConsole::RPCExecuteCommandLine(result, "getblock(getbestblockhash())[tx][0]", &filtered); QVERIFY(result == "97ddfbbae6be97fd6cdf3e7ca13232a3afff2353e29badfab7f73011edd4ced9"); QVERIFY(filtered == "getblock(getbestblockhash())[tx][0]"); RPCConsole::RPCParseCommandLine(result, "importprivkey", false, &filtered); QVERIFY(filtered == "importprivkey(…)"); RPCConsole::RPCParseCommandLine(result, "signmessagewithprivkey abc", false, &filtered); QVERIFY(filtered == "signmessagewithprivkey(…)"); RPCConsole::RPCParseCommandLine(result, "signmessagewithprivkey abc,def", false, &filtered); QVERIFY(filtered == "signmessagewithprivkey(…)"); RPCConsole::RPCParseCommandLine(result, "signrawtransaction(abc)", false, &filtered); QVERIFY(filtered == "signrawtransaction(…)"); RPCConsole::RPCParseCommandLine(result, "walletpassphrase(help())", false, &filtered); QVERIFY(filtered == "walletpassphrase(…)"); RPCConsole::RPCParseCommandLine(result, "walletpassphrasechange(help(walletpassphrasechange(abc)))", false, &filtered); QVERIFY(filtered == "walletpassphrasechange(…)"); RPCConsole::RPCParseCommandLine(result, "help(encryptwallet(abc, def))", false, &filtered); QVERIFY(filtered == "help(encryptwallet(…))"); RPCConsole::RPCParseCommandLine(result, "help(importprivkey())", false, &filtered); QVERIFY(filtered == "help(importprivkey(…))"); RPCConsole::RPCParseCommandLine(result, "help(importprivkey(help()))", false, &filtered); QVERIFY(filtered == "help(importprivkey(…))"); RPCConsole::RPCParseCommandLine(result, "help(importprivkey(abc), walletpassphrase(def))", false, &filtered); QVERIFY(filtered == "help(importprivkey(…), walletpassphrase(…))"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest"); QVERIFY(result == "[]"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest ''"); QVERIFY(result == "[\"\"]"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest \"\""); QVERIFY(result == "[\"\"]"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest '' abc"); QVERIFY(result == "[\"\",\"abc\"]"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc '' abc"); QVERIFY(result == "[\"abc\",\"\",\"abc\"]"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc abc"); QVERIFY(result == "[\"abc\",\"abc\"]"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc\t\tabc"); QVERIFY(result == "[\"abc\",\"abc\"]"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest(abc )"); QVERIFY(result == "[\"abc\"]"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest( abc )"); QVERIFY(result == "[\"abc\"]"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest( abc , cba )"); QVERIFY(result == "[\"abc\",\"cba\"]"); #if QT_VERSION >= 0x050300 // do the QVERIFY_EXCEPTION_THROWN checks only with Qt5.3 and higher (QVERIFY_EXCEPTION_THROWN was introduced in Qt5.3) QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo() .\n"), std::runtime_error); //invalid syntax QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo() getblockchaininfo()"), std::runtime_error); //invalid syntax (RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo(")); //tolerate non closing brackets if we have no arguments (RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()()()")); //tolerate non command brackts QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo(True)"), UniValue); //invalid argument QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "a(getblockchaininfo(True))"), UniValue); //method not found QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc,,abc"), std::runtime_error); //don't tollerate empty arguments when using , QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest(abc,,abc)"), std::runtime_error); //don't tollerate empty arguments when using , QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest(abc,,)"), std::runtime_error); //don't tollerate empty arguments when using , #endif delete pcoinsTip; delete pcoinsdbview; delete pblocktree; boost::filesystem::remove_all(boost::filesystem::path(path)); } <commit_msg>Unit Tests (#12): Fix rpcnestedtests by putting the correct transaction id for the coinbase of the genesis block of GoldCoin.<commit_after>// Copyright (c) 2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpcnestedtests.h" #include "chainparams.h" #include "consensus/validation.h" #include "validation.h" #include "rpc/register.h" #include "rpc/server.h" #include "rpcconsole.h" #include "test/testutil.h" #include "univalue.h" #include "util.h" #include <QDir> #include <QtGlobal> #include <boost/filesystem.hpp> static UniValue rpcNestedTest_rpc(const JSONRPCRequest& request) { if (request.fHelp) { return "help message"; } return request.params.write(0, 0); } static const CRPCCommand vRPCCommands[] = { { "test", "rpcNestedTest", &rpcNestedTest_rpc, true, {} }, }; void RPCNestedTests::rpcNestedTests() { UniValue jsonRPCError; // do some test setup // could be moved to a more generic place when we add more tests on QT level const CChainParams& chainparams = Params(); RegisterAllCoreRPCCommands(tableRPC); tableRPC.appendCommand("rpcNestedTest", &vRPCCommands[0]); ClearDatadirCache(); std::string path = QDir::tempPath().toStdString() + "/" + strprintf("test_goldcoin_qt_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000))); QDir dir(QString::fromStdString(path)); dir.mkpath("."); ForceSetArg("-datadir", path); //mempool.setSanityCheck(1.0); pblocktree = new CBlockTreeDB(1 << 20, true); pcoinsdbview = new CCoinsViewDB(1 << 23, true); pcoinsTip = new CCoinsViewCache(pcoinsdbview); InitBlockIndex(chainparams); { CValidationState state; bool ok = ActivateBestChain(state, chainparams); QVERIFY(ok); } SetRPCWarmupFinished(); std::string result; std::string result2; std::string filtered; RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()[chain]", &filtered); //simple result filtering with path QVERIFY(result=="main"); QVERIFY(filtered == "getblockchaininfo()[chain]"); RPCConsole::RPCExecuteCommandLine(result, "getblock(getbestblockhash())"); //simple 2 level nesting RPCConsole::RPCExecuteCommandLine(result, "getblock(getblock(getbestblockhash())[hash], true)"); RPCConsole::RPCExecuteCommandLine(result, "getblock( getblock( getblock(getbestblockhash())[hash] )[hash], true)"); //4 level nesting with whitespace, filtering path and boolean parameter RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo"); QVERIFY(result.substr(0,1) == "{"); RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()"); QVERIFY(result.substr(0,1) == "{"); RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo "); //whitespace at the end will be tolerated QVERIFY(result.substr(0,1) == "{"); (RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()[\"chain\"]")); //Quote path identifier are allowed, but look after a child contaning the quotes in the key QVERIFY(result == "null"); (RPCConsole::RPCExecuteCommandLine(result, "createrawtransaction [] {} 0")); //parameter not in brackets are allowed (RPCConsole::RPCExecuteCommandLine(result2, "createrawtransaction([],{},0)")); //parameter in brackets are allowed QVERIFY(result == result2); (RPCConsole::RPCExecuteCommandLine(result2, "createrawtransaction( [], {} , 0 )")); //whitespace between parametres is allowed QVERIFY(result == result2); RPCConsole::RPCExecuteCommandLine(result, "getblock(getbestblockhash())[tx][0]", &filtered); QVERIFY(result == "a215e67ba165202f75b6458d22fedd1a3ec4f03449a4c6b2a4b8130bfebd3b15"); QVERIFY(filtered == "getblock(getbestblockhash())[tx][0]"); RPCConsole::RPCParseCommandLine(result, "importprivkey", false, &filtered); QVERIFY(filtered == "importprivkey(…)"); RPCConsole::RPCParseCommandLine(result, "signmessagewithprivkey abc", false, &filtered); QVERIFY(filtered == "signmessagewithprivkey(…)"); RPCConsole::RPCParseCommandLine(result, "signmessagewithprivkey abc,def", false, &filtered); QVERIFY(filtered == "signmessagewithprivkey(…)"); RPCConsole::RPCParseCommandLine(result, "signrawtransaction(abc)", false, &filtered); QVERIFY(filtered == "signrawtransaction(…)"); RPCConsole::RPCParseCommandLine(result, "walletpassphrase(help())", false, &filtered); QVERIFY(filtered == "walletpassphrase(…)"); RPCConsole::RPCParseCommandLine(result, "walletpassphrasechange(help(walletpassphrasechange(abc)))", false, &filtered); QVERIFY(filtered == "walletpassphrasechange(…)"); RPCConsole::RPCParseCommandLine(result, "help(encryptwallet(abc, def))", false, &filtered); QVERIFY(filtered == "help(encryptwallet(…))"); RPCConsole::RPCParseCommandLine(result, "help(importprivkey())", false, &filtered); QVERIFY(filtered == "help(importprivkey(…))"); RPCConsole::RPCParseCommandLine(result, "help(importprivkey(help()))", false, &filtered); QVERIFY(filtered == "help(importprivkey(…))"); RPCConsole::RPCParseCommandLine(result, "help(importprivkey(abc), walletpassphrase(def))", false, &filtered); QVERIFY(filtered == "help(importprivkey(…), walletpassphrase(…))"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest"); QVERIFY(result == "[]"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest ''"); QVERIFY(result == "[\"\"]"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest \"\""); QVERIFY(result == "[\"\"]"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest '' abc"); QVERIFY(result == "[\"\",\"abc\"]"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc '' abc"); QVERIFY(result == "[\"abc\",\"\",\"abc\"]"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc abc"); QVERIFY(result == "[\"abc\",\"abc\"]"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc\t\tabc"); QVERIFY(result == "[\"abc\",\"abc\"]"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest(abc )"); QVERIFY(result == "[\"abc\"]"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest( abc )"); QVERIFY(result == "[\"abc\"]"); RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest( abc , cba )"); QVERIFY(result == "[\"abc\",\"cba\"]"); #if QT_VERSION >= 0x050300 // do the QVERIFY_EXCEPTION_THROWN checks only with Qt5.3 and higher (QVERIFY_EXCEPTION_THROWN was introduced in Qt5.3) QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo() .\n"), std::runtime_error); //invalid syntax QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo() getblockchaininfo()"), std::runtime_error); //invalid syntax (RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo(")); //tolerate non closing brackets if we have no arguments (RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()()()")); //tolerate non command brackts QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo(True)"), UniValue); //invalid argument QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "a(getblockchaininfo(True))"), UniValue); //method not found QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc,,abc"), std::runtime_error); //don't tollerate empty arguments when using , QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest(abc,,abc)"), std::runtime_error); //don't tollerate empty arguments when using , QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest(abc,,)"), std::runtime_error); //don't tollerate empty arguments when using , #endif delete pcoinsTip; delete pcoinsdbview; delete pblocktree; boost::filesystem::remove_all(boost::filesystem::path(path)); } <|endoftext|>
<commit_before> #include <xpcc/architecture/platform.hpp> using namespace xpcc::atmega; // Create a new UART object and configure it to a baudrate of 115200 Uart0 uart(115200); int main() { // Enable interrupts, this is needed for every buffered UART sei(); // Write some characters uart.write('H'); uart.write('e'); uart.write('l'); uart.write('l'); uart.write('o'); uart.write('\n'); while (1) { } } <commit_msg>Fix AVR Uart exammple<commit_after> #include <xpcc/architecture/platform.hpp> using namespace xpcc::atmega; typedef xpcc::avr::SystemClock clock; // Create a new UART object and configure it to a baudrate of 115200 typedef Uart0 uart; int main() { GpioOutputD1::connect(Uart0::Tx); GpioInputD0::connect(Uart0::Rx); uart::initialize<clock, 115200>(); // Enable interrupts, this is needed for every buffered UART sei(); // Write some characters uart::write('H'); uart::write('e'); uart::write('l'); uart::write('l'); uart::write('o'); uart::write('\n'); while (1) { } } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////// // // Copyright 2020 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// #include <realm/object-store/set.hpp> #include <realm/object-store/impl/set_notifier.hpp> #include <realm/object-store/impl/realm_coordinator.hpp> #include <realm/object-store/object_schema.hpp> #include <realm/object-store/object_store.hpp> #include <realm/object-store/results.hpp> #include <realm/object-store/schema.hpp> #include <realm/object-store/shared_realm.hpp> namespace realm::object_store { using namespace _impl; Set::Set() noexcept = default; Set::~Set() = default; Set::Set(const Set&) = default; Set::Set(Set&&) = default; Set& Set::operator=(const Set&) = default; Set& Set::operator=(Set&&) = default; Set::Set(std::shared_ptr<Realm> r, const Obj& parent_obj, ColKey col) : Collection(std::move(r), parent_obj, col) , m_set_base(std::dynamic_pointer_cast<SetBase>(m_coll_base)) { } Set::Set(std::shared_ptr<Realm> r, const SetBase& set) : Collection(std::move(r), set) , m_set_base(std::dynamic_pointer_cast<SetBase>(m_coll_base)) { } Query Set::get_query() const { verify_attached(); if (m_type == PropertyType::Object) { return static_cast<LnkSet&>(*m_set_base).get_target_table()->where(as<Obj>()); } throw std::runtime_error("not implemented"); } ConstTableRef Set::get_target_table() const { auto table = m_set_base->get_table(); auto col = m_set_base->get_col_key(); if (col.get_type() != col_type_Link) return nullptr; return table->get_link_target(col); } template <class T> size_t Set::find(const T& value) const { verify_attached(); return as<T>().find(value); } size_t Set::find(Query&& q) const { verify_attached(); if (m_type == PropertyType::Object) { ObjKey key = get_query().and_query(std::move(q)).find(); return key ? as<Obj>().find_first(key) : not_found; } throw std::runtime_error("not implemented"); } template <typename T> T Set::get(size_t row_ndx) const { verify_valid_row(row_ndx); return as<T>().get(row_ndx); } template <class T> std::pair<size_t, bool> Set::insert(T value) { verify_in_transaction(); return as<T>().insert(value); } template <class T> std::pair<size_t, bool> Set::remove(const T& value) { verify_in_transaction(); return as<T>().erase(value); } util::Optional<Mixed> Set::max(ColKey col) const { if (get_type() == PropertyType::Object) return as_results().max(col); size_t out_ndx = not_found; auto result = m_set_base->max(&out_ndx); if (result.is_null()) { throw realm::Results::UnsupportedColumnTypeException(m_set_base->get_col_key(), m_set_base->get_table(), "max"); } return out_ndx == not_found ? none : util::make_optional(result); } util::Optional<Mixed> Set::min(ColKey col) const { if (get_type() == PropertyType::Object) return as_results().min(col); size_t out_ndx = not_found; auto result = m_set_base->min(&out_ndx); if (result.is_null()) { throw realm::Results::UnsupportedColumnTypeException(m_set_base->get_col_key(), m_set_base->get_table(), "min"); } return out_ndx == not_found ? none : util::make_optional(result); } Mixed Set::sum(ColKey col) const { if (get_type() == PropertyType::Object) return *as_results().sum(col); auto result = m_set_base->sum(); if (result.is_null()) { throw realm::Results::UnsupportedColumnTypeException(m_set_base->get_col_key(), m_set_base->get_table(), "sum"); } return result; } util::Optional<Mixed> Set::average(ColKey col) const { if (get_type() == PropertyType::Object) return as_results().average(col); size_t count = 0; auto result = m_set_base->avg(&count); if (result.is_null()) { throw realm::Results::UnsupportedColumnTypeException(m_set_base->get_col_key(), m_set_base->get_table(), "average"); } return count == 0 ? none : util::make_optional(result); } bool Set::operator==(const Set& rgt) const noexcept { return m_set_base->get_table() == rgt.m_set_base->get_table() && m_set_base->get_key() == rgt.m_set_base->get_key() && m_set_base->get_col_key() == rgt.m_set_base->get_col_key(); } Results Set::snapshot() const { return as_results().snapshot(); } Results Set::sort(SortDescriptor order) const { verify_attached(); if ((m_type == PropertyType::Object)) { return Results(m_realm, std::dynamic_pointer_cast<LnkSet>(m_set_base), util::none, std::move(order)); } else { DescriptorOrdering o; o.append_sort(order); return Results(m_realm, m_set_base, std::move(o)); } } Results Set::sort(const std::vector<std::pair<std::string, bool>>& keypaths) const { return as_results().sort(keypaths); } Results Set::filter(Query q) const { verify_attached(); return Results(m_realm, std::dynamic_pointer_cast<LnkSet>(m_set_base), get_query().and_query(std::move(q))); } Set Set::freeze(const std::shared_ptr<Realm>& frozen_realm) const { return Set(frozen_realm, *frozen_realm->import_copy_of(*m_set_base)); } NotificationToken Set::add_notification_callback(CollectionChangeCallback cb) & { if (m_notifier && !m_notifier->have_callbacks()) m_notifier.reset(); if (!m_notifier) { m_notifier = std::make_shared<SetNotifier>(m_realm, *m_set_base, m_type); RealmCoordinator::register_notifier(m_notifier); } return {m_notifier, m_notifier->add_callback(std::move(cb))}; } #define REALM_PRIMITIVE_SET_TYPE(T) \ template T Set::get<T>(size_t) const; \ template size_t Set::find<T>(const T&) const; \ template std::pair<size_t, bool> Set::remove<T>(T const&); \ template std::pair<size_t, bool> Set::insert<T>(T); REALM_PRIMITIVE_SET_TYPE(bool) REALM_PRIMITIVE_SET_TYPE(int64_t) REALM_PRIMITIVE_SET_TYPE(float) REALM_PRIMITIVE_SET_TYPE(double) REALM_PRIMITIVE_SET_TYPE(StringData) REALM_PRIMITIVE_SET_TYPE(BinaryData) REALM_PRIMITIVE_SET_TYPE(Timestamp) REALM_PRIMITIVE_SET_TYPE(ObjKey) REALM_PRIMITIVE_SET_TYPE(ObjectId) REALM_PRIMITIVE_SET_TYPE(Decimal) REALM_PRIMITIVE_SET_TYPE(UUID) REALM_PRIMITIVE_SET_TYPE(Mixed) REALM_PRIMITIVE_SET_TYPE(util::Optional<bool>) REALM_PRIMITIVE_SET_TYPE(util::Optional<int64_t>) REALM_PRIMITIVE_SET_TYPE(util::Optional<float>) REALM_PRIMITIVE_SET_TYPE(util::Optional<double>) REALM_PRIMITIVE_SET_TYPE(util::Optional<ObjectId>) REALM_PRIMITIVE_SET_TYPE(util::Optional<UUID>) #undef REALM_PRIMITIVE_SET_TYPE template <> std::pair<size_t, bool> Set::insert<int>(int value) { return insert(int64_t(value)); } template <> std::pair<size_t, bool> Set::remove<int>(const int& value) { return remove(int64_t(value)); } std::pair<size_t, bool> Set::insert_any(Mixed value) { verify_in_transaction(); return m_set_base->insert_any(value); } Mixed Set::get_any(size_t ndx) const { verify_valid_row(ndx); return m_set_base->get_any(ndx); } std::pair<size_t, bool> Set::remove_any(Mixed value) { verify_in_transaction(); return m_set_base->erase_any(value); } size_t Set::find_any(Mixed value) const { return m_set_base->find_any(value); } void Set::delete_all() { verify_in_transaction(); if (m_type == PropertyType::Object) as<Obj>().remove_all_target_rows(); else m_set_base->clear(); } void Set::remove_all() { verify_in_transaction(); m_set_base->clear(); } template <> size_t Set::find<int>(const int& value) const { return find(int64_t(value)); } template <> Obj Set::get<Obj>(size_t row_ndx) const { verify_valid_row(row_ndx); auto& set = as<Obj>(); return set.get_object(row_ndx); } template <> size_t Set::find<Obj>(const Obj& obj) const { verify_attached(); validate(obj); // FIXME: Handle Mixed / ObjLink return as<ObjKey>().find(obj.get_key()); } template <> std::pair<size_t, bool> Set::remove<Obj>(const Obj& obj) { verify_in_transaction(); validate(obj); // FIXME: Handle Mixed / ObjLink return as<ObjKey>().erase(obj.get_key()); } template <> std::pair<size_t, bool> Set::insert<Obj>(Obj obj) { verify_in_transaction(); validate(obj); // FIXME: Handle Mixed / ObjLink return as<ObjKey>().insert(obj.get_key()); } bool Set::is_subset_of(const Set& rhs) const { return dispatch([&](auto t) { return this->as<std::decay_t<decltype(*t)>>().is_subset_of(rhs.as<std::decay_t<decltype(*t)>>()); }); } bool Set::is_strict_subset_of(const Set& rhs) const { return dispatch([&](auto t) { return this->as<std::decay_t<decltype(*t)>>().is_strict_subset_of(rhs.as<std::decay_t<decltype(*t)>>()); }); } bool Set::is_superset_of(const Set& rhs) const { return dispatch([&](auto t) { return this->as<std::decay_t<decltype(*t)>>().is_superset_of(rhs.as<std::decay_t<decltype(*t)>>()); }); } bool Set::is_strict_superset_of(const Set& rhs) const { return dispatch([&](auto t) { return this->as<std::decay_t<decltype(*t)>>().is_strict_superset_of(rhs.as<std::decay_t<decltype(*t)>>()); }); } bool Set::intersects(const Set& rhs) const { return dispatch([&](auto t) { return this->as<std::decay_t<decltype(*t)>>().intersects(rhs.as<std::decay_t<decltype(*t)>>()); }); } bool Set::set_equals(const Set& rhs) const { return dispatch([&](auto t) { return this->as<std::decay_t<decltype(*t)>>().set_equals(rhs.as<std::decay_t<decltype(*t)>>()); }); } void Set::assign_intersection(const Set& rhs) { return dispatch([&](auto t) { return this->as<std::decay_t<decltype(*t)>>().assign_intersection(rhs.as<std::decay_t<decltype(*t)>>()); }); } void Set::assign_union(const Set& rhs) { return dispatch([&](auto t) { return this->as<std::decay_t<decltype(*t)>>().assign_union(rhs.as<std::decay_t<decltype(*t)>>()); }); } void Set::assign_difference(const Set& rhs) { return dispatch([&](auto t) { return this->as<std::decay_t<decltype(*t)>>().assign_difference(rhs.as<std::decay_t<decltype(*t)>>()); }); } void Set::assign_symmetric_difference(const Set& rhs) { return dispatch([&](auto t) { return this->as<std::decay_t<decltype(*t)>>().assign_symmetric_difference(rhs.as<std::decay_t<decltype(*t)>>()); }); } } // namespace realm::object_store namespace { size_t hash_combine() { return 0; } template <typename T, typename... Rest> size_t hash_combine(const T& v, Rest... rest) { size_t h = hash_combine(rest...); h ^= std::hash<T>()(v) + 0x9e3779b9 + (h << 6) + (h >> 2); return h; } } // namespace namespace std { size_t hash<realm::object_store::Set>::operator()(realm::object_store::Set const& set) const { auto& impl = *set.m_set_base; return hash_combine(impl.get_key().value, impl.get_table()->get_key().value, impl.get_col_key().value); } } // namespace std <commit_msg>Satisfy the linter<commit_after>//////////////////////////////////////////////////////////////////////////// // // Copyright 2020 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// #include <realm/object-store/set.hpp> #include <realm/object-store/impl/set_notifier.hpp> #include <realm/object-store/impl/realm_coordinator.hpp> #include <realm/object-store/object_schema.hpp> #include <realm/object-store/object_store.hpp> #include <realm/object-store/results.hpp> #include <realm/object-store/schema.hpp> #include <realm/object-store/shared_realm.hpp> namespace realm::object_store { using namespace _impl; Set::Set() noexcept = default; Set::~Set() = default; Set::Set(const Set&) = default; Set::Set(Set&&) = default; Set& Set::operator=(const Set&) = default; Set& Set::operator=(Set&&) = default; Set::Set(std::shared_ptr<Realm> r, const Obj& parent_obj, ColKey col) : Collection(std::move(r), parent_obj, col) , m_set_base(std::dynamic_pointer_cast<SetBase>(m_coll_base)) { } Set::Set(std::shared_ptr<Realm> r, const SetBase& set) : Collection(std::move(r), set) , m_set_base(std::dynamic_pointer_cast<SetBase>(m_coll_base)) { } Query Set::get_query() const { verify_attached(); if (m_type == PropertyType::Object) { return static_cast<LnkSet&>(*m_set_base).get_target_table()->where(as<Obj>()); } throw std::runtime_error("not implemented"); } ConstTableRef Set::get_target_table() const { auto table = m_set_base->get_table(); auto col = m_set_base->get_col_key(); if (col.get_type() != col_type_Link) return nullptr; return table->get_link_target(col); } template <class T> size_t Set::find(const T& value) const { verify_attached(); return as<T>().find(value); } size_t Set::find(Query&& q) const { verify_attached(); if (m_type == PropertyType::Object) { ObjKey key = get_query().and_query(std::move(q)).find(); return key ? as<Obj>().find_first(key) : not_found; } throw std::runtime_error("not implemented"); } template <typename T> T Set::get(size_t row_ndx) const { verify_valid_row(row_ndx); return as<T>().get(row_ndx); } template <class T> std::pair<size_t, bool> Set::insert(T value) { verify_in_transaction(); return as<T>().insert(value); } template <class T> std::pair<size_t, bool> Set::remove(const T& value) { verify_in_transaction(); return as<T>().erase(value); } util::Optional<Mixed> Set::max(ColKey col) const { if (get_type() == PropertyType::Object) return as_results().max(col); size_t out_ndx = not_found; auto result = m_set_base->max(&out_ndx); if (result.is_null()) { throw realm::Results::UnsupportedColumnTypeException(m_set_base->get_col_key(), m_set_base->get_table(), "max"); } return out_ndx == not_found ? none : util::make_optional(result); } util::Optional<Mixed> Set::min(ColKey col) const { if (get_type() == PropertyType::Object) return as_results().min(col); size_t out_ndx = not_found; auto result = m_set_base->min(&out_ndx); if (result.is_null()) { throw realm::Results::UnsupportedColumnTypeException(m_set_base->get_col_key(), m_set_base->get_table(), "min"); } return out_ndx == not_found ? none : util::make_optional(result); } Mixed Set::sum(ColKey col) const { if (get_type() == PropertyType::Object) return *as_results().sum(col); auto result = m_set_base->sum(); if (result.is_null()) { throw realm::Results::UnsupportedColumnTypeException(m_set_base->get_col_key(), m_set_base->get_table(), "sum"); } return result; } util::Optional<Mixed> Set::average(ColKey col) const { if (get_type() == PropertyType::Object) return as_results().average(col); size_t count = 0; auto result = m_set_base->avg(&count); if (result.is_null()) { throw realm::Results::UnsupportedColumnTypeException(m_set_base->get_col_key(), m_set_base->get_table(), "average"); } return count == 0 ? none : util::make_optional(result); } bool Set::operator==(const Set& rgt) const noexcept { return m_set_base->get_table() == rgt.m_set_base->get_table() && m_set_base->get_key() == rgt.m_set_base->get_key() && m_set_base->get_col_key() == rgt.m_set_base->get_col_key(); } Results Set::snapshot() const { return as_results().snapshot(); } Results Set::sort(SortDescriptor order) const { verify_attached(); if ((m_type == PropertyType::Object)) { return Results(m_realm, std::dynamic_pointer_cast<LnkSet>(m_set_base), util::none, std::move(order)); } else { DescriptorOrdering o; o.append_sort(order); return Results(m_realm, m_set_base, std::move(o)); } } Results Set::sort(const std::vector<std::pair<std::string, bool>>& keypaths) const { return as_results().sort(keypaths); } Results Set::filter(Query q) const { verify_attached(); return Results(m_realm, std::dynamic_pointer_cast<LnkSet>(m_set_base), get_query().and_query(std::move(q))); } Set Set::freeze(const std::shared_ptr<Realm>& frozen_realm) const { return Set(frozen_realm, *frozen_realm->import_copy_of(*m_set_base)); } NotificationToken Set::add_notification_callback(CollectionChangeCallback cb) & { if (m_notifier && !m_notifier->have_callbacks()) m_notifier.reset(); if (!m_notifier) { m_notifier = std::make_shared<SetNotifier>(m_realm, *m_set_base, m_type); RealmCoordinator::register_notifier(m_notifier); } return {m_notifier, m_notifier->add_callback(std::move(cb))}; } #define REALM_PRIMITIVE_SET_TYPE(T) \ template T Set::get<T>(size_t) const; \ template size_t Set::find<T>(const T&) const; \ template std::pair<size_t, bool> Set::remove<T>(T const&); \ template std::pair<size_t, bool> Set::insert<T>(T); REALM_PRIMITIVE_SET_TYPE(bool) REALM_PRIMITIVE_SET_TYPE(int64_t) REALM_PRIMITIVE_SET_TYPE(float) REALM_PRIMITIVE_SET_TYPE(double) REALM_PRIMITIVE_SET_TYPE(StringData) REALM_PRIMITIVE_SET_TYPE(BinaryData) REALM_PRIMITIVE_SET_TYPE(Timestamp) REALM_PRIMITIVE_SET_TYPE(ObjKey) REALM_PRIMITIVE_SET_TYPE(ObjectId) REALM_PRIMITIVE_SET_TYPE(Decimal) REALM_PRIMITIVE_SET_TYPE(UUID) REALM_PRIMITIVE_SET_TYPE(Mixed) REALM_PRIMITIVE_SET_TYPE(util::Optional<bool>) REALM_PRIMITIVE_SET_TYPE(util::Optional<int64_t>) REALM_PRIMITIVE_SET_TYPE(util::Optional<float>) REALM_PRIMITIVE_SET_TYPE(util::Optional<double>) REALM_PRIMITIVE_SET_TYPE(util::Optional<ObjectId>) REALM_PRIMITIVE_SET_TYPE(util::Optional<UUID>) #undef REALM_PRIMITIVE_SET_TYPE template <> std::pair<size_t, bool> Set::insert<int>(int value) { return insert(int64_t(value)); } template <> std::pair<size_t, bool> Set::remove<int>(const int& value) { return remove(int64_t(value)); } std::pair<size_t, bool> Set::insert_any(Mixed value) { verify_in_transaction(); return m_set_base->insert_any(value); } Mixed Set::get_any(size_t ndx) const { verify_valid_row(ndx); return m_set_base->get_any(ndx); } std::pair<size_t, bool> Set::remove_any(Mixed value) { verify_in_transaction(); return m_set_base->erase_any(value); } size_t Set::find_any(Mixed value) const { return m_set_base->find_any(value); } void Set::delete_all() { verify_in_transaction(); if (m_type == PropertyType::Object) as<Obj>().remove_all_target_rows(); else m_set_base->clear(); } void Set::remove_all() { verify_in_transaction(); m_set_base->clear(); } template <> size_t Set::find<int>(const int& value) const { return find(int64_t(value)); } template <> Obj Set::get<Obj>(size_t row_ndx) const { verify_valid_row(row_ndx); auto& set = as<Obj>(); return set.get_object(row_ndx); } template <> size_t Set::find<Obj>(const Obj& obj) const { verify_attached(); validate(obj); // FIXME: Handle Mixed / ObjLink return as<ObjKey>().find(obj.get_key()); } template <> std::pair<size_t, bool> Set::remove<Obj>(const Obj& obj) { verify_in_transaction(); validate(obj); // FIXME: Handle Mixed / ObjLink return as<ObjKey>().erase(obj.get_key()); } template <> std::pair<size_t, bool> Set::insert<Obj>(Obj obj) { verify_in_transaction(); validate(obj); // FIXME: Handle Mixed / ObjLink return as<ObjKey>().insert(obj.get_key()); } bool Set::is_subset_of(const Set& rhs) const { return dispatch([&](auto t) { return this->as<std::decay_t<decltype(*t)>>().is_subset_of(rhs.as<std::decay_t<decltype(*t)>>()); }); } bool Set::is_strict_subset_of(const Set& rhs) const { return dispatch([&](auto t) { return this->as<std::decay_t<decltype(*t)>>().is_strict_subset_of(rhs.as<std::decay_t<decltype(*t)>>()); }); } bool Set::is_superset_of(const Set& rhs) const { return dispatch([&](auto t) { return this->as<std::decay_t<decltype(*t)>>().is_superset_of(rhs.as<std::decay_t<decltype(*t)>>()); }); } bool Set::is_strict_superset_of(const Set& rhs) const { return dispatch([&](auto t) { return this->as<std::decay_t<decltype(*t)>>().is_strict_superset_of(rhs.as<std::decay_t<decltype(*t)>>()); }); } bool Set::intersects(const Set& rhs) const { return dispatch([&](auto t) { return this->as<std::decay_t<decltype(*t)>>().intersects(rhs.as<std::decay_t<decltype(*t)>>()); }); } bool Set::set_equals(const Set& rhs) const { return dispatch([&](auto t) { return this->as<std::decay_t<decltype(*t)>>().set_equals(rhs.as<std::decay_t<decltype(*t)>>()); }); } void Set::assign_intersection(const Set& rhs) { return dispatch([&](auto t) { return this->as<std::decay_t<decltype(*t)>>().assign_intersection(rhs.as<std::decay_t<decltype(*t)>>()); }); } void Set::assign_union(const Set& rhs) { return dispatch([&](auto t) { return this->as<std::decay_t<decltype(*t)>>().assign_union(rhs.as<std::decay_t<decltype(*t)>>()); }); } void Set::assign_difference(const Set& rhs) { return dispatch([&](auto t) { return this->as<std::decay_t<decltype(*t)>>().assign_difference(rhs.as<std::decay_t<decltype(*t)>>()); }); } void Set::assign_symmetric_difference(const Set& rhs) { return dispatch([&](auto t) { return this->as<std::decay_t<decltype(*t)>>().assign_symmetric_difference( rhs.as<std::decay_t<decltype(*t)>>()); }); } } // namespace realm::object_store namespace { size_t hash_combine() { return 0; } template <typename T, typename... Rest> size_t hash_combine(const T& v, Rest... rest) { size_t h = hash_combine(rest...); h ^= std::hash<T>()(v) + 0x9e3779b9 + (h << 6) + (h >> 2); return h; } } // namespace namespace std { size_t hash<realm::object_store::Set>::operator()(realm::object_store::Set const& set) const { auto& impl = *set.m_set_base; return hash_combine(impl.get_key().value, impl.get_table()->get_key().value, impl.get_col_key().value); } } // namespace std <|endoftext|>
<commit_before>// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Engine - Core module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Core/Algorithm.hpp> #include <Nazara/Core/Debug.hpp> namespace Nz { /*! * \brief Constructs a ByteStream object with a stream */ inline ByteStream::ByteStream(Stream* stream) { m_context.stream = stream; } /*! * \brief Constructs a ByteStream object by move semantic * * \param stream ByteStream to move into this */ inline ByteStream::ByteStream(ByteStream&& stream) : m_ownedStream(std::move(stream.m_ownedStream)), m_context(stream.m_context) { stream.m_context.stream = nullptr; } /*! * \brief Destructs the object and calls FlushBits * * \remark Produces a NazaraWarning if flush did not work * * \see FlushBits */ inline ByteStream::~ByteStream() { if (!FlushBits()) NazaraWarning("Failed to flush bits at serializer destruction"); } /*! * \brief Gets the stream endianness * \return Type of the endianness */ inline Endianness ByteStream::GetDataEndianness() const { return m_context.endianness; } /*! * \brief Gets the size of the byte stream * \return Size of the stream */ inline Nz::UInt64 ByteStream::GetSize() const { if (m_context.stream) return m_context.stream->GetSize(); else return 0; } /*! * \brief Gets the internal stream * \return Internal stream */ inline Stream* ByteStream::GetStream() const { return m_context.stream; } /*! * \brief Flushes the stream * \return true if flushing is successful */ inline bool ByteStream::FlushBits() { if (!m_context.stream) return true; if (m_context.currentBitPos != 8) { m_context.currentBitPos = 8; //< To prevent Serialize to flush bits itself if (!Serialize(m_context, m_context.currentByte)) return false; } return true; } /*! * \brief Reads data * \return Number of data read * * \param ptr Preallocated buffer to contain information read * \param size Size of the read and thus of the buffer */ inline std::size_t ByteStream::Read(void* ptr, std::size_t size) { if (!m_context.stream) OnEmptyStream(); FlushBits(); return m_context.stream->Read(ptr, size); } /*! * \brief Sets the stream endianness * * \param endiannes Type of the endianness */ inline void ByteStream::SetDataEndianness(Endianness endiannes) { m_context.endianness = endiannes; } /*! * \brief Sets this with a stream * * \param stream Stream existing * * \remark Produces a NazaraAssert if stream is invalid */ inline void ByteStream::SetStream(Stream* stream) { NazaraAssert(stream, "Invalid stream"); // We don't want to lose some bits.. FlushBits(); m_context.stream = stream; m_ownedStream.reset(); } /*! * \brief Writes data * \return Number of data written * * \param buffer Preallocated buffer containing information to write * \param size Size of the writting and thus of the buffer * * \remark Produces a NazaraAssert if buffer is nullptr */ inline std::size_t ByteStream::Write(const void* data, std::size_t size) { if (!m_context.stream) OnEmptyStream(); FlushBits(); return m_context.stream->Write(data, size); } /*! * \brief Outputs a data from the stream * \return A reference to this * * \param value Value to unserialize * * \remark Produces a NazaraError if unserialization failed */ template<typename T> ByteStream& ByteStream::operator>>(T& value) { if (!m_context.stream) OnEmptyStream(); if (!Unserialize(m_context, &value)) NazaraError("Failed to serialize value"); return *this; } /*! * \brief Adds the data to the stream * \return A reference to this * * \param value Value to serialize * * \remark Produces a NazaraError if serialization failed */ template<typename T> ByteStream& ByteStream::operator<<(const T& value) { if (!m_context.stream) OnEmptyStream(); if (!Serialize(m_context, value)) NazaraError("Failed to serialize value"); return *this; } /*! * \brief Moves the other byte stream into this * \return A reference to this * * \param stream ByteStream to move in this */ inline ByteStream& ByteStream::operator=(ByteStream&& stream) { m_context = stream.m_context; m_ownedStream = std::move(stream.m_ownedStream); stream.m_context.stream = nullptr; return *this; } } #include <Nazara/Core/DebugOff.hpp> <commit_msg>Fix compilation<commit_after>// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Engine - Core module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Core/Algorithm.hpp> #include <Nazara/Core/Debug.hpp> namespace Nz { /*! * \brief Constructs a ByteStream object with a stream */ inline ByteStream::ByteStream(Stream* stream) { m_context.stream = stream; } /*! * \brief Constructs a ByteStream object by move semantic * * \param stream ByteStream to move into this */ inline ByteStream::ByteStream(ByteStream&& stream) : m_ownedStream(std::move(stream.m_ownedStream)), m_context(stream.m_context) { stream.m_context.stream = nullptr; } /*! * \brief Destructs the object and calls FlushBits * * \remark Produces a NazaraWarning if flush did not work * * \see FlushBits */ inline ByteStream::~ByteStream() { if (!FlushBits()) NazaraWarning("Failed to flush bits at serializer destruction"); } /*! * \brief Gets the stream endianness * \return Type of the endianness */ inline Endianness ByteStream::GetDataEndianness() const { return m_context.endianness; } /*! * \brief Gets the size of the byte stream * \return Size of the stream */ inline Nz::UInt64 ByteStream::GetSize() const { if (m_context.stream) return m_context.stream->GetSize(); else return 0; } /*! * \brief Gets the internal stream * \return Internal stream */ inline Stream* ByteStream::GetStream() const { return m_context.stream; } /*! * \brief Flushes the stream * \return true if flushing is successful */ inline bool ByteStream::FlushBits() { if (!m_context.stream) return true; if (m_context.writeBitPos != 8) { m_context.writeBitPos = 8; //< To prevent Serialize to flush bits itself if (!Serialize(m_context, m_context.writeByte)) return false; } return true; } /*! * \brief Reads data * \return Number of data read * * \param ptr Preallocated buffer to contain information read * \param size Size of the read and thus of the buffer */ inline std::size_t ByteStream::Read(void* ptr, std::size_t size) { if (!m_context.stream) OnEmptyStream(); FlushBits(); return m_context.stream->Read(ptr, size); } /*! * \brief Sets the stream endianness * * \param endiannes Type of the endianness */ inline void ByteStream::SetDataEndianness(Endianness endiannes) { m_context.endianness = endiannes; } /*! * \brief Sets this with a stream * * \param stream Stream existing * * \remark Produces a NazaraAssert if stream is invalid */ inline void ByteStream::SetStream(Stream* stream) { NazaraAssert(stream, "Invalid stream"); // We don't want to lose some bits.. FlushBits(); m_context.stream = stream; m_ownedStream.reset(); } /*! * \brief Writes data * \return Number of data written * * \param buffer Preallocated buffer containing information to write * \param size Size of the writting and thus of the buffer * * \remark Produces a NazaraAssert if buffer is nullptr */ inline std::size_t ByteStream::Write(const void* data, std::size_t size) { if (!m_context.stream) OnEmptyStream(); FlushBits(); return m_context.stream->Write(data, size); } /*! * \brief Outputs a data from the stream * \return A reference to this * * \param value Value to unserialize * * \remark Produces a NazaraError if unserialization failed */ template<typename T> ByteStream& ByteStream::operator>>(T& value) { if (!m_context.stream) OnEmptyStream(); if (!Unserialize(m_context, &value)) NazaraError("Failed to serialize value"); return *this; } /*! * \brief Adds the data to the stream * \return A reference to this * * \param value Value to serialize * * \remark Produces a NazaraError if serialization failed */ template<typename T> ByteStream& ByteStream::operator<<(const T& value) { if (!m_context.stream) OnEmptyStream(); if (!Serialize(m_context, value)) NazaraError("Failed to serialize value"); return *this; } /*! * \brief Moves the other byte stream into this * \return A reference to this * * \param stream ByteStream to move in this */ inline ByteStream& ByteStream::operator=(ByteStream&& stream) { m_context = stream.m_context; m_ownedStream = std::move(stream.m_ownedStream); stream.m_context.stream = nullptr; return *this; } } #include <Nazara/Core/DebugOff.hpp> <|endoftext|>
<commit_before>/* * Copyright (C) 2013 Vaclav Slavik <[email protected]> * 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 schemaation and/or other materials provided with the * distribution. * 3. Neither the name of the Author nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR * 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. */ // xmlwrapp includes #include "xmlwrapp/errors.h" #include "utility.h" #include "errors_impl.h" namespace xml { error_handler_throw_on_error throw_on_error; error_handler_throw_on_error_or_warning throw_on_error_or_warning; // ------------------------------------------------------------------------ // xml::exception // ------------------------------------------------------------------------ exception::exception(const std::string& what) : std::runtime_error(what) { } exception::exception(const error_messages& what) : std::runtime_error(what.print()) { } // ------------------------------------------------------------------------ // xml::error_messages // ------------------------------------------------------------------------ void error_messages::on_error(const std::string& msg) { messages_.push_back(error_message(msg, error_message::type_error)); has_errors_ = true; } void error_messages::on_warning(const std::string& msg) { messages_.push_back(error_message(msg, error_message::type_warning)); has_warnings_ = true; } std::string error_messages::print() const { std::string buffer; messages_type::const_iterator begin(messages_.begin()); messages_type::const_iterator end(messages_.end()); for (messages_type::const_iterator k = begin; k != end; ++k) { if (k != begin) buffer += "\n"; buffer += format_for_print(*k); } return buffer; } std::string error_messages::format_for_print(const error_message& msg) const { switch (msg.type()) { case error_message::type_error: return "error: " + msg.message(); case error_message::type_warning: return "warning: " + msg.message(); } } // ------------------------------------------------------------------------ // libxml2 callbacks interface // ------------------------------------------------------------------------ namespace impl { // Notice that these callbacks are called from C code, not C++. Although // throwing exceptions through C code does work in some implementations, it // is not guaranteed to. We therefore need to make sure no exception // propagates outside of the callbacks by catching them. // // This is also the reason for errors_collector's existence: we cannot safely // call error_handler's methods, because they may throw (it is in fact often // desirable). So we collect the errors and "replay" them after returning from // C code. extern "C" void cb_messages_warning_v(void *out, const char *message, va_list ap) { try { error_messages *err = static_cast<error_messages*>(out); std::string text; printf2string(text, message, ap); err->on_warning(text); } catch (...) {} } extern "C" void cb_messages_error_v(void *out, const char *message, va_list ap) { try { error_messages *err = static_cast<error_messages*>(out); std::string text; printf2string(text, message, ap); err->on_error(text); } catch (...) {} } extern "C" void cb_messages_warning(void *out, const char *message, ...) { CALL_CB_MESSAGES_WARNING(out, message); } extern "C" void cb_messages_error(void *out, const char *message, ...) { CALL_CB_MESSAGES_ERROR(out, message); } void errors_collector::replay(error_handler& dest) { const messages_type& msg = messages(); for ( messages_type::const_iterator i = msg.begin(); i != msg.end(); ++i ) { switch ( i->type() ) { case error_message::type_error: dest.on_error(i->message()); break; case error_message::type_warning: dest.on_warning(i->message()); break; } } } std::string errors_collector::format_for_print(const error_message& msg) const { // The errors_collector class is also used to provide backward // compatibility errors reporting in tree_parser and xslt::stylesheet. The // "error: " prefix wasn't included there, so don't add it now either so // that we don't break user UI output. On the other hand, include "warning: // " to make it clear these aren't errors. switch (msg.type()) { case error_message::type_error: return msg.message(); case error_message::type_warning: return "warning: " + msg.message(); } } } // namespace impl } // namespace xml <commit_msg>Silence bogus gcc warnings.<commit_after>/* * Copyright (C) 2013 Vaclav Slavik <[email protected]> * 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 schemaation and/or other materials provided with the * distribution. * 3. Neither the name of the Author nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR * 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. */ // xmlwrapp includes #include "xmlwrapp/errors.h" #include "utility.h" #include "errors_impl.h" namespace xml { error_handler_throw_on_error throw_on_error; error_handler_throw_on_error_or_warning throw_on_error_or_warning; // ------------------------------------------------------------------------ // xml::exception // ------------------------------------------------------------------------ exception::exception(const std::string& what) : std::runtime_error(what) { } exception::exception(const error_messages& what) : std::runtime_error(what.print()) { } // ------------------------------------------------------------------------ // xml::error_messages // ------------------------------------------------------------------------ void error_messages::on_error(const std::string& msg) { messages_.push_back(error_message(msg, error_message::type_error)); has_errors_ = true; } void error_messages::on_warning(const std::string& msg) { messages_.push_back(error_message(msg, error_message::type_warning)); has_warnings_ = true; } std::string error_messages::print() const { std::string buffer; messages_type::const_iterator begin(messages_.begin()); messages_type::const_iterator end(messages_.end()); for (messages_type::const_iterator k = begin; k != end; ++k) { if (k != begin) buffer += "\n"; buffer += format_for_print(*k); } return buffer; } std::string error_messages::format_for_print(const error_message& msg) const { switch (msg.type()) { case error_message::type_error: return "error: " + msg.message(); case error_message::type_warning: return "warning: " + msg.message(); } return msg.message(); // silence bogus gcc warning } // ------------------------------------------------------------------------ // libxml2 callbacks interface // ------------------------------------------------------------------------ namespace impl { // Notice that these callbacks are called from C code, not C++. Although // throwing exceptions through C code does work in some implementations, it // is not guaranteed to. We therefore need to make sure no exception // propagates outside of the callbacks by catching them. // // This is also the reason for errors_collector's existence: we cannot safely // call error_handler's methods, because they may throw (it is in fact often // desirable). So we collect the errors and "replay" them after returning from // C code. extern "C" void cb_messages_warning_v(void *out, const char *message, va_list ap) { try { error_messages *err = static_cast<error_messages*>(out); std::string text; printf2string(text, message, ap); err->on_warning(text); } catch (...) {} } extern "C" void cb_messages_error_v(void *out, const char *message, va_list ap) { try { error_messages *err = static_cast<error_messages*>(out); std::string text; printf2string(text, message, ap); err->on_error(text); } catch (...) {} } extern "C" void cb_messages_warning(void *out, const char *message, ...) { CALL_CB_MESSAGES_WARNING(out, message); } extern "C" void cb_messages_error(void *out, const char *message, ...) { CALL_CB_MESSAGES_ERROR(out, message); } void errors_collector::replay(error_handler& dest) { const messages_type& msg = messages(); for ( messages_type::const_iterator i = msg.begin(); i != msg.end(); ++i ) { switch ( i->type() ) { case error_message::type_error: dest.on_error(i->message()); break; case error_message::type_warning: dest.on_warning(i->message()); break; } } } std::string errors_collector::format_for_print(const error_message& msg) const { // The errors_collector class is also used to provide backward // compatibility errors reporting in tree_parser and xslt::stylesheet. The // "error: " prefix wasn't included there, so don't add it now either so // that we don't break user UI output. On the other hand, include "warning: // " to make it clear these aren't errors. switch (msg.type()) { case error_message::type_error: return msg.message(); case error_message::type_warning: return "warning: " + msg.message(); } return msg.message(); // silence bogus gcc warning } } // namespace impl } // namespace xml <|endoftext|>
<commit_before>// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #include "common.h" #include "eventpipebuffermanager.h" #include "eventpipeeventinstance.h" #include "sampleprofiler.h" #include "hosting.h" #include "threadsuspend.h" #ifdef FEATURE_PERFTRACING Volatile<BOOL> SampleProfiler::s_profilingEnabled = false; Thread* SampleProfiler::s_pSamplingThread = NULL; const WCHAR* SampleProfiler::s_providerName = W("Microsoft-DotNETCore-SampleProfiler"); EventPipeProvider* SampleProfiler::s_pEventPipeProvider = NULL; EventPipeEvent* SampleProfiler::s_pThreadTimeEvent = NULL; BYTE* SampleProfiler::s_pPayloadExternal = NULL; BYTE* SampleProfiler::s_pPayloadManaged = NULL; CLREventStatic SampleProfiler::s_threadShutdownEvent; long SampleProfiler::s_samplingRateInNs = 1000000; // 1ms void SampleProfiler::Enable() { CONTRACTL { THROWS; GC_TRIGGERS; MODE_ANY; PRECONDITION(s_pSamplingThread == NULL); // Synchronization of multiple callers occurs in EventPipe::Enable. PRECONDITION(EventPipe::GetLock()->OwnedByCurrentThread()); } CONTRACTL_END; if(s_pEventPipeProvider == NULL) { s_pEventPipeProvider = EventPipe::CreateProvider(SL(s_providerName)); s_pThreadTimeEvent = s_pEventPipeProvider->AddEvent( 0, /* eventID */ 0, /* keywords */ 0, /* eventVersion */ EventPipeEventLevel::Informational, false /* NeedStack */); } if(s_pPayloadExternal == NULL) { s_pPayloadExternal = new BYTE[sizeof(unsigned int)]; *((unsigned int *)s_pPayloadExternal) = static_cast<unsigned int>(SampleProfilerSampleType::External); s_pPayloadManaged = new BYTE[sizeof(unsigned int)]; *((unsigned int *)s_pPayloadManaged) = static_cast<unsigned int>(SampleProfilerSampleType::Managed); } s_profilingEnabled = true; s_pSamplingThread = SetupUnstartedThread(); if(s_pSamplingThread->CreateNewThread(0, ThreadProc, NULL)) { // Start the sampling thread. s_pSamplingThread->SetBackground(TRUE); s_pSamplingThread->StartThread(); } else { _ASSERT(!"Unable to create sample profiler thread."); } } void SampleProfiler::Disable() { CONTRACTL { THROWS; GC_TRIGGERS; MODE_ANY; // Synchronization of multiple callers occurs in EventPipe::Disable. PRECONDITION(EventPipe::GetLock()->OwnedByCurrentThread()); } CONTRACTL_END; // Bail early if profiling is not enabled. if(!s_profilingEnabled) { return; } // Reset the event before shutdown. s_threadShutdownEvent.Reset(); // The sampling thread will watch this value and exit // when profiling is disabled. s_profilingEnabled = false; // Wait for the sampling thread to clean itself up. s_threadShutdownEvent.Wait(0, FALSE /* bAlertable */); } void SampleProfiler::SetSamplingRate(long nanoseconds) { LIMITED_METHOD_CONTRACT; s_samplingRateInNs = nanoseconds; } DWORD WINAPI SampleProfiler::ThreadProc(void *args) { CONTRACTL { NOTHROW; GC_TRIGGERS; MODE_PREEMPTIVE; PRECONDITION(s_pSamplingThread != NULL); } CONTRACTL_END; // Complete thread initialization and start the profiling loop. if(s_pSamplingThread->HasStarted()) { // Switch to pre-emptive mode so that this thread doesn't starve the GC. GCX_PREEMP(); while(s_profilingEnabled) { // Check to see if we can suspend managed execution. if(ThreadSuspend::SysIsSuspendInProgress() || (ThreadSuspend::GetSuspensionThread() != 0)) { // Skip the current sample. PAL_nanosleep(s_samplingRateInNs); continue; } // Actually suspend managed execution. ThreadSuspend::SuspendEE(ThreadSuspend::SUSPEND_REASON::SUSPEND_OTHER); // Walk all managed threads and capture stacks. WalkManagedThreads(); // Resume managed execution. ThreadSuspend::RestartEE(FALSE /* bFinishedGC */, TRUE /* SuspendSucceeded */); // Wait until it's time to sample again. PAL_nanosleep(s_samplingRateInNs); } } // Destroy the sampling thread when it is done running. DestroyThread(s_pSamplingThread); s_pSamplingThread = NULL; // Signal Disable() that the thread has been destroyed. s_threadShutdownEvent.Set(); return S_OK; } // The thread store lock must already be held by the thread before this function // is called. ThreadSuspend::SuspendEE acquires the thread store lock. void SampleProfiler::WalkManagedThreads() { CONTRACTL { NOTHROW; GC_TRIGGERS; MODE_PREEMPTIVE; } CONTRACTL_END; Thread *pTargetThread = NULL; // Iterate over all managed threads. // Assumes that the ThreadStoreLock is held because we've suspended all threads. while ((pTargetThread = ThreadStore::GetThreadList(pTargetThread)) != NULL) { StackContents stackContents; // Walk the stack and write it out as an event. if(EventPipe::WalkManagedStackForThread(pTargetThread, stackContents) && !stackContents.IsEmpty()) { // Set the payload. If the GC mode on suspension > 0, then the thread was in cooperative mode. // Even though there are some cases where this is not managed code, we assume it is managed code here. // If the GC mode on suspension == 0 then the thread was in preemptive mode, which we qualify as external here. BYTE *pPayload = s_pPayloadExternal; if(pTargetThread->GetGCModeOnSuspension()) { pPayload = s_pPayloadManaged; } // Write the sample. EventPipe::WriteSampleProfileEvent(s_pSamplingThread, s_pThreadTimeEvent, pTargetThread, stackContents, pPayload, c_payloadSize); } // Reset the GC mode. pTargetThread->ClearGCModeOnSuspension(); } } #endif // FEATURE_PERFTRACING <commit_msg>Don't create the sampling thread if the threadtime event is disabled. (#15473)<commit_after>// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #include "common.h" #include "eventpipebuffermanager.h" #include "eventpipeeventinstance.h" #include "sampleprofiler.h" #include "hosting.h" #include "threadsuspend.h" #ifdef FEATURE_PERFTRACING Volatile<BOOL> SampleProfiler::s_profilingEnabled = false; Thread* SampleProfiler::s_pSamplingThread = NULL; const WCHAR* SampleProfiler::s_providerName = W("Microsoft-DotNETCore-SampleProfiler"); EventPipeProvider* SampleProfiler::s_pEventPipeProvider = NULL; EventPipeEvent* SampleProfiler::s_pThreadTimeEvent = NULL; BYTE* SampleProfiler::s_pPayloadExternal = NULL; BYTE* SampleProfiler::s_pPayloadManaged = NULL; CLREventStatic SampleProfiler::s_threadShutdownEvent; long SampleProfiler::s_samplingRateInNs = 1000000; // 1ms void SampleProfiler::Enable() { CONTRACTL { THROWS; GC_TRIGGERS; MODE_ANY; PRECONDITION(s_pSamplingThread == NULL); // Synchronization of multiple callers occurs in EventPipe::Enable. PRECONDITION(EventPipe::GetLock()->OwnedByCurrentThread()); } CONTRACTL_END; if(s_pEventPipeProvider == NULL) { s_pEventPipeProvider = EventPipe::CreateProvider(SL(s_providerName)); s_pThreadTimeEvent = s_pEventPipeProvider->AddEvent( 0, /* eventID */ 0, /* keywords */ 0, /* eventVersion */ EventPipeEventLevel::Informational, false /* NeedStack */); } // Check to see if the sample profiler event is enabled. If it is not, do not spin up the sampling thread. if(!s_pThreadTimeEvent->IsEnabled()) { return; } if(s_pPayloadExternal == NULL) { s_pPayloadExternal = new BYTE[sizeof(unsigned int)]; *((unsigned int *)s_pPayloadExternal) = static_cast<unsigned int>(SampleProfilerSampleType::External); s_pPayloadManaged = new BYTE[sizeof(unsigned int)]; *((unsigned int *)s_pPayloadManaged) = static_cast<unsigned int>(SampleProfilerSampleType::Managed); } s_profilingEnabled = true; s_pSamplingThread = SetupUnstartedThread(); if(s_pSamplingThread->CreateNewThread(0, ThreadProc, NULL)) { // Start the sampling thread. s_pSamplingThread->SetBackground(TRUE); s_pSamplingThread->StartThread(); } else { _ASSERT(!"Unable to create sample profiler thread."); } } void SampleProfiler::Disable() { CONTRACTL { THROWS; GC_TRIGGERS; MODE_ANY; // Synchronization of multiple callers occurs in EventPipe::Disable. PRECONDITION(EventPipe::GetLock()->OwnedByCurrentThread()); } CONTRACTL_END; // Bail early if profiling is not enabled. if(!s_profilingEnabled) { return; } // Reset the event before shutdown. s_threadShutdownEvent.Reset(); // The sampling thread will watch this value and exit // when profiling is disabled. s_profilingEnabled = false; // Wait for the sampling thread to clean itself up. s_threadShutdownEvent.Wait(0, FALSE /* bAlertable */); } void SampleProfiler::SetSamplingRate(long nanoseconds) { LIMITED_METHOD_CONTRACT; s_samplingRateInNs = nanoseconds; } DWORD WINAPI SampleProfiler::ThreadProc(void *args) { CONTRACTL { NOTHROW; GC_TRIGGERS; MODE_PREEMPTIVE; PRECONDITION(s_pSamplingThread != NULL); } CONTRACTL_END; // Complete thread initialization and start the profiling loop. if(s_pSamplingThread->HasStarted()) { // Switch to pre-emptive mode so that this thread doesn't starve the GC. GCX_PREEMP(); while(s_profilingEnabled) { // Check to see if we can suspend managed execution. if(ThreadSuspend::SysIsSuspendInProgress() || (ThreadSuspend::GetSuspensionThread() != 0)) { // Skip the current sample. PAL_nanosleep(s_samplingRateInNs); continue; } // Actually suspend managed execution. ThreadSuspend::SuspendEE(ThreadSuspend::SUSPEND_REASON::SUSPEND_OTHER); // Walk all managed threads and capture stacks. WalkManagedThreads(); // Resume managed execution. ThreadSuspend::RestartEE(FALSE /* bFinishedGC */, TRUE /* SuspendSucceeded */); // Wait until it's time to sample again. PAL_nanosleep(s_samplingRateInNs); } } // Destroy the sampling thread when it is done running. DestroyThread(s_pSamplingThread); s_pSamplingThread = NULL; // Signal Disable() that the thread has been destroyed. s_threadShutdownEvent.Set(); return S_OK; } // The thread store lock must already be held by the thread before this function // is called. ThreadSuspend::SuspendEE acquires the thread store lock. void SampleProfiler::WalkManagedThreads() { CONTRACTL { NOTHROW; GC_TRIGGERS; MODE_PREEMPTIVE; } CONTRACTL_END; Thread *pTargetThread = NULL; // Iterate over all managed threads. // Assumes that the ThreadStoreLock is held because we've suspended all threads. while ((pTargetThread = ThreadStore::GetThreadList(pTargetThread)) != NULL) { StackContents stackContents; // Walk the stack and write it out as an event. if(EventPipe::WalkManagedStackForThread(pTargetThread, stackContents) && !stackContents.IsEmpty()) { // Set the payload. If the GC mode on suspension > 0, then the thread was in cooperative mode. // Even though there are some cases where this is not managed code, we assume it is managed code here. // If the GC mode on suspension == 0 then the thread was in preemptive mode, which we qualify as external here. BYTE *pPayload = s_pPayloadExternal; if(pTargetThread->GetGCModeOnSuspension()) { pPayload = s_pPayloadManaged; } // Write the sample. EventPipe::WriteSampleProfileEvent(s_pSamplingThread, s_pThreadTimeEvent, pTargetThread, stackContents, pPayload, c_payloadSize); } // Reset the GC mode. pTargetThread->ClearGCModeOnSuspension(); } } #endif // FEATURE_PERFTRACING <|endoftext|>
<commit_before>#ifndef INC_AL_CONTROL_NAV_HPP #define INC_AL_CONTROL_NAV_HPP #include "allocore/io/al_Window.hpp" #include "allocore/spatial/al_CoordinateFrame.hpp" namespace al { /// Mapping from keyboard and mouse controls to a Nav object struct NavInputControl : public InputEventHandler { NavInputControl(Nav * nav, double vscale = 0.125, double tscale = 2.) : mNav(nav), mVScale(vscale), mTScale(tscale) {} virtual ~NavInputControl() {} void nav(Nav * v){ mNav=v; } virtual bool onKeyDown(const Keyboard& k){ double vs = nav().velScale(); double a = mTScale * vs; // rotational speed: degrees per update double v = mVScale * vs; // speed: units per update switch(k.key()){ case '`': nav().halt().home(); return false; case 's': nav().halt(); return false; case Key::Up: nav().spinR(-a); return false; case Key::Down: nav().spinR( a); return false; case Key::Right: nav().spinU( a); return false; case Key::Left: nav().spinU(-a); return false; case 'q': nav().spinF( a); return false; case 'z': nav().spinF(-a); return false; case 'a': nav().moveR(-v); return false; case 'd': nav().moveR( v); return false; case 'e': nav().moveU( v); return false; case 'c': nav().moveU(-v); return false; case 'x': nav().moveF(-v); return false; case 'w': nav().moveF( v); return false; default:; } return true; } virtual bool onKeyUp(const Keyboard& k) { switch (k.key()) { case Key::Up: case Key::Down: nav().spinR(0); return false; case Key::Right: case Key::Left: nav().spinU(0); return false; case 'q': case 'z': nav().spinF(0); return false; case 'a': case 'd': nav().moveR(0); return false; case 'e': case 'c': nav().moveU(0); return false; case 'x': case 'w': nav().moveF(0); return false; default:; } return true; } virtual bool onMouseDrag(const Mouse& m){ if(m.left()){ nav().turnU(m.dx() * 0.2); nav().turnR(m.dy() * 0.2); } else if(m.right()){ nav().turnF(m.dx() * 0.2); //incBehind(m.dy()*0.005); } return false; } Nav& nav(){ return *mNav; } double vscale() { return mVScale; } NavInputControl& vscale(double v) { mVScale=v; return *this; } double tscale() { return mTScale; } NavInputControl& tscale(double v) { mTScale=v; return *this; } protected: Nav * mNav; double mVScale, mTScale; }; struct NavInputControlCosm : public NavInputControl { NavInputControlCosm(Nav * nav, double vscale = 0.125, double tscale = 2.): NavInputControl(nav, vscale, tscale){} virtual ~NavInputControlCosm() {} virtual bool onKeyDown(const Keyboard& k){ double vs = nav().velScale(); double a = mTScale * vs; // rotational speed: degrees per update double v = mVScale * vs; // speed: units per update switch(k.key()){ case '`': nav().halt().home(); return false; case 'w': nav().spinR(-a); return false; case 'x': nav().spinR( a); return false; case Key::Right: nav().spinU( a); return false; case Key::Left: nav().spinU(-a); return false; case 'a': nav().spinF( a); return false; case 'd': nav().spinF(-a); return false; case ',': nav().moveR(-v); return false; case '.': nav().moveR( v); return false; case '\'': nav().moveU( v); return false; case '/': nav().moveU(-v); return false; case Key::Up: nav().moveF( v); return false; case Key::Down: nav().moveF(-v); return false; default:; } return true; } virtual bool onKeyUp(const Keyboard& k) { switch (k.key()) { case 'w': case 'x': nav().spinR(0); return false; case Key::Right: case Key::Left: nav().spinU(0); return false; case 'a': case 'd': nav().spinF(0); return false; case ',': case '.': nav().moveR(0); return false; case '\'': case '/': nav().moveU(0); return false; case Key::Up: case Key::Down: nav().moveF(0); return false; default:; } return true; } virtual bool onMouseDrag(const Mouse& m){ return true; } }; } // al:: #endif <commit_msg>ControlNav: speed booster<commit_after>#ifndef INC_AL_CONTROL_NAV_HPP #define INC_AL_CONTROL_NAV_HPP #include "allocore/io/al_Window.hpp" #include "allocore/spatial/al_CoordinateFrame.hpp" namespace al { /// Mapping from keyboard and mouse controls to a Nav object struct NavInputControl : public InputEventHandler { NavInputControl(Nav * nav, double vscale = 0.125, double tscale = 2.) : mNav(nav), mVScale(vscale), mTScale(tscale) {} virtual ~NavInputControl() {} void nav(Nav * v){ mNav=v; } virtual bool onKeyDown(const Keyboard& k){ double vs = nav().velScale(); double a = mTScale * vs; // rotational speed: degrees per update double v = mVScale * vs; // speed: units per update if(k.alt()) v *= 10; switch(k.key()){ case '`': nav().halt().home(); return false; case 's': nav().halt(); return false; case Key::Up: nav().spinR(-a); return false; case Key::Down: nav().spinR( a); return false; case Key::Right: nav().spinU( a); return false; case Key::Left: nav().spinU(-a); return false; case 'q': nav().spinF( a); return false; case 'z': nav().spinF(-a); return false; case 'a': nav().moveR(-v); return false; case 'd': nav().moveR( v); return false; case 'e': nav().moveU( v); return false; case 'c': nav().moveU(-v); return false; case 'x': nav().moveF(-v); return false; case 'w': nav().moveF( v); return false; default:; } return true; } virtual bool onKeyUp(const Keyboard& k) { switch (k.key()) { case Key::Up: case Key::Down: nav().spinR(0); return false; case Key::Right: case Key::Left: nav().spinU(0); return false; case 'q': case 'z': nav().spinF(0); return false; case 'a': case 'd': nav().moveR(0); return false; case 'e': case 'c': nav().moveU(0); return false; case 'x': case 'w': nav().moveF(0); return false; default:; } return true; } virtual bool onMouseDrag(const Mouse& m){ if(m.left()){ nav().turnU(m.dx() * 0.2); nav().turnR(m.dy() * 0.2); } else if(m.right()){ nav().turnF(m.dx() * 0.2); //incBehind(m.dy()*0.005); } return false; } Nav& nav(){ return *mNav; } double vscale() { return mVScale; } NavInputControl& vscale(double v) { mVScale=v; return *this; } double tscale() { return mTScale; } NavInputControl& tscale(double v) { mTScale=v; return *this; } protected: Nav * mNav; double mVScale, mTScale; }; struct NavInputControlCosm : public NavInputControl { NavInputControlCosm(Nav * nav, double vscale = 0.125, double tscale = 2.): NavInputControl(nav, vscale, tscale){} virtual ~NavInputControlCosm() {} virtual bool onKeyDown(const Keyboard& k){ double vs = nav().velScale(); double a = mTScale * vs; // rotational speed: degrees per update double v = mVScale * vs; // speed: units per update switch(k.key()){ case '`': nav().halt().home(); return false; case 'w': nav().spinR(-a); return false; case 'x': nav().spinR( a); return false; case Key::Right: nav().spinU( a); return false; case Key::Left: nav().spinU(-a); return false; case 'a': nav().spinF( a); return false; case 'd': nav().spinF(-a); return false; case ',': nav().moveR(-v); return false; case '.': nav().moveR( v); return false; case '\'': nav().moveU( v); return false; case '/': nav().moveU(-v); return false; case Key::Up: nav().moveF( v); return false; case Key::Down: nav().moveF(-v); return false; default:; } return true; } virtual bool onKeyUp(const Keyboard& k) { switch (k.key()) { case 'w': case 'x': nav().spinR(0); return false; case Key::Right: case Key::Left: nav().spinU(0); return false; case 'a': case 'd': nav().spinF(0); return false; case ',': case '.': nav().moveR(0); return false; case '\'': case '/': nav().moveU(0); return false; case Key::Up: case Key::Down: nav().moveF(0); return false; default:; } return true; } virtual bool onMouseDrag(const Mouse& m){ return true; } }; } // al:: #endif <|endoftext|>
<commit_before>/* This file is part of Zanshin Todo. Copyright 2008-2010 Kevin Ottens <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "actionlisteditorpage.h" #include <KDE/Akonadi/ItemCreateJob> #include <KDE/Akonadi/ItemDeleteJob> #include <KDE/KConfigGroup> #include <kdescendantsproxymodel.h> #include <kmodelindexproxymapper.h> #include <QtCore/QTimer> #include <QtGui/QHeaderView> #include <QtGui/QSortFilterProxyModel> #include <QtGui/QVBoxLayout> #include "actionlistdelegate.h" #include "todomodel.h" #include "todotreeview.h" class GroupLabellingProxyModel : public QSortFilterProxyModel { public: GroupLabellingProxyModel(QObject *parent = 0) : QSortFilterProxyModel(parent) { setDynamicSortFilter(true); } QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const { if (role!=Qt::DisplayRole || index.column()!=0) { return QSortFilterProxyModel::data(index, role); } else { int type = index.data(TodoModel::ItemTypeRole).toInt(); if (type!=TodoModel::ProjectTodo && type!=TodoModel::Category) { return QSortFilterProxyModel::data(index, role); } else { QString display = QSortFilterProxyModel::data(index, role).toString(); QModelIndex currentIndex = index.parent(); type = currentIndex.data(TodoModel::ItemTypeRole).toInt(); while (type==TodoModel::ProjectTodo || type==TodoModel::Category) { display = currentIndex.data(role).toString() + ": " + display; currentIndex = currentIndex.parent(); type = currentIndex.data(TodoModel::ItemTypeRole).toInt(); } return display; } } } }; class GroupSortingProxyModel : public QSortFilterProxyModel { public: GroupSortingProxyModel(QObject *parent = 0) : QSortFilterProxyModel(parent) { setDynamicSortFilter(true); setFilterCaseSensitivity(Qt::CaseInsensitive); } bool lessThan(const QModelIndex &left, const QModelIndex &right) const { int leftType = left.data(TodoModel::ItemTypeRole).toInt(); int rightType = right.data(TodoModel::ItemTypeRole).toInt(); return leftType==TodoModel::Inbox || (leftType==TodoModel::CategoryRoot && rightType!=TodoModel::Inbox) || (leftType==TodoModel::Collection && rightType!=TodoModel::Inbox) || (leftType==TodoModel::Category && rightType==TodoModel::StandardTodo) || (leftType==TodoModel::ProjectTodo && rightType==TodoModel::StandardTodo) || QSortFilterProxyModel::lessThan(left, right); } }; class TypeFilterProxyModel : public QSortFilterProxyModel { public: TypeFilterProxyModel(GroupSortingProxyModel *sorting, QObject *parent = 0) : QSortFilterProxyModel(parent), m_sorting(sorting) { setDynamicSortFilter(true); setFilterCaseSensitivity(Qt::CaseInsensitive); } bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const { QModelIndex sourceChild = sourceModel()->index(sourceRow, 0, sourceParent); int type = sourceChild.data(TodoModel::ItemTypeRole).toInt(); QSize sizeHint = sourceChild.data(Qt::SizeHintRole).toSize(); return type!=TodoModel::Collection && type!=TodoModel::CategoryRoot && !sizeHint.isNull(); // SelectionProxyModel uses the null size for items we shouldn't display } void sort(int column, Qt::SortOrder order = Qt::AscendingOrder) { m_sorting->sort(column, order); } private: GroupSortingProxyModel *m_sorting; }; class ActionListEditorView : public TodoTreeView { public: ActionListEditorView(QWidget *parent = 0) : TodoTreeView(parent) { } protected: virtual QModelIndex moveCursor(CursorAction cursorAction, Qt::KeyboardModifiers modifiers) { QModelIndex index = currentIndex(); if (index.isValid() && modifiers==Qt::NoModifier) { QModelIndex newIndex; int newColumn = index.column(); switch (cursorAction) { case MoveLeft: do { newColumn--; } while (isColumnHidden(newColumn) && newColumn>=0); break; case MoveRight: do { newColumn++; } while (isColumnHidden(newColumn) && newColumn<header()->count()); break; default: return Akonadi::EntityTreeView::moveCursor(cursorAction, modifiers); } newIndex = index.sibling(index.row(), newColumn); if (newIndex.isValid()) { return newIndex; } } return Akonadi::EntityTreeView::moveCursor(cursorAction, modifiers); } }; class ActionListEditorModel : public KDescendantsProxyModel { public: ActionListEditorModel(QObject *parent = 0) : KDescendantsProxyModel(parent) { } virtual bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) { if (!sourceModel()) { return QAbstractProxyModel::dropMimeData(data, action, row, column, parent); } QModelIndex sourceParent = mapToSource(parent); return sourceModel()->dropMimeData(data, action, row, column, sourceParent); } }; ActionListEditorPage::ActionListEditorPage(QAbstractItemModel *model, ModelStack *models, Zanshin::ApplicationMode mode, QWidget *parent) : QWidget(parent), m_mode(mode) { setLayout(new QVBoxLayout(this)); layout()->setContentsMargins(0, 0, 0, 0); m_treeView = new ActionListEditorView(this); GroupLabellingProxyModel *labelling = new GroupLabellingProxyModel(this); labelling->setSourceModel(model); GroupSortingProxyModel *sorting = new GroupSortingProxyModel(this); sorting->setSourceModel(labelling); ActionListEditorModel *descendants = new ActionListEditorModel(this); descendants->setSourceModel(sorting); TypeFilterProxyModel *filter = new TypeFilterProxyModel(sorting, this); filter->setSourceModel(descendants); m_treeView->setModel(filter); m_treeView->setItemDelegate(new ActionListDelegate(models, m_treeView)); m_treeView->header()->setSortIndicatorShown(true); m_treeView->setSortingEnabled(true); m_treeView->sortByColumn(0, Qt::AscendingOrder); m_treeView->setSelectionMode(QAbstractItemView::ExtendedSelection); m_treeView->setItemsExpandable(false); m_treeView->setRootIsDecorated(false); m_treeView->setEditTriggers(m_treeView->editTriggers() | QAbstractItemView::DoubleClicked); connect(m_treeView->model(), SIGNAL(modelReset()), m_treeView, SLOT(expandAll())); connect(m_treeView->model(), SIGNAL(layoutChanged()), m_treeView, SLOT(expandAll())); connect(m_treeView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), m_treeView, SLOT(expandAll())); layout()->addWidget(m_treeView); QTimer::singleShot(0, this, SLOT(onAutoHideColumns())); connect(m_treeView->header(), SIGNAL(sectionResized(int, int, int)), this, SLOT(onColumnsGeometryChanged())); } QItemSelectionModel *ActionListEditorPage::selectionModel() const { return m_treeView->selectionModel(); } void ActionListEditorPage::saveColumnsState(KConfigGroup &config, const QString &key) const { config.writeEntry(key+"/Normal", m_normalStateCache.toBase64()); config.writeEntry(key+"/NoCollection", m_noCollectionStateCache.toBase64()); } void ActionListEditorPage::restoreColumnsState(const KConfigGroup &config, const QString &key) { if (config.hasKey(key+"/Normal")) { m_normalStateCache = QByteArray::fromBase64(config.readEntry(key+"/Normal", QByteArray())); } if (config.hasKey(key+"/NoCollection")) { m_noCollectionStateCache = QByteArray::fromBase64(config.readEntry(key+"/NoCollection", QByteArray())); } if (!m_treeView->isColumnHidden(4)) { m_treeView->header()->restoreState(m_normalStateCache); } else { m_treeView->header()->restoreState(m_noCollectionStateCache); } } void ActionListEditorPage::addNewTodo(const QString &summary) { if (summary.isEmpty()) return; QModelIndex current = m_treeView->selectionModel()->currentIndex(); if (!current.isValid()) { kWarning() << "Oops, nothing selected in the list!"; return; } int type = current.data(TodoModel::ItemTypeRole).toInt(); while (current.isValid() && type==TodoModel::StandardTodo) { current = current.parent(); type = current.data(TodoModel::ItemTypeRole).toInt(); } Akonadi::Collection collection; QString parentUid; QString category; switch (type) { case TodoModel::StandardTodo: kFatal() << "Can't possibly happen!"; break; case TodoModel::ProjectTodo: parentUid = current.data(TodoModel::UidRole).toString(); collection = current.data(Akonadi::EntityTreeModel::ParentCollectionRole).value<Akonadi::Collection>(); break; case TodoModel::Collection: collection = current.data(Akonadi::EntityTreeModel::CollectionRole).value<Akonadi::Collection>(); break; case TodoModel::Category: category = current.data(Qt::EditRole).toString(); // fallthrough case TodoModel::Inbox: case TodoModel::CategoryRoot: collection = m_defaultCollection; break; } KCalCore::Todo::Ptr todo(new KCalCore::Todo); todo->setSummary(summary); if (!parentUid.isEmpty()) { todo->setRelatedTo(parentUid); } if (!category.isEmpty()) { todo->setCategories(category); } Akonadi::Item item; item.setMimeType("application/x-vnd.akonadi.calendar.todo"); item.setPayload<KCalCore::Todo::Ptr>(todo); new Akonadi::ItemCreateJob(item, collection); } void ActionListEditorPage::removeCurrentTodo() { QModelIndex current = m_treeView->selectionModel()->currentIndex(); int type = current.data(TodoModel::ItemTypeRole).toInt(); if (!current.isValid() || type!=TodoModel::StandardTodo) { return; } Akonadi::Item item = current.data(Akonadi::EntityTreeModel::ItemRole).value<Akonadi::Item>(); if (!item.isValid()) { return; } new Akonadi::ItemDeleteJob(item, this); } Zanshin::ApplicationMode ActionListEditorPage::mode() { return m_mode; } void ActionListEditorPage::onAutoHideColumns() { switch (m_mode) { case Zanshin::ProjectMode: hideColumn(1); break; case Zanshin::CategoriesMode: hideColumn(2); break; } } void ActionListEditorPage::hideColumn(int column) { if (!m_treeView->isColumnHidden(column)) { m_treeView->hideColumn(column); } } void ActionListEditorPage::setCollectionColumnHidden(bool hidden) { QByteArray state = hidden ? m_noCollectionStateCache : m_normalStateCache; if (!state.isEmpty()) { m_treeView->header()->restoreState(state); } else { m_treeView->setColumnHidden(4, hidden); } } void ActionListEditorPage::onColumnsGeometryChanged() { if (!m_treeView->isColumnHidden(4)) { m_normalStateCache = m_treeView->header()->saveState(); } else { m_noCollectionStateCache = m_treeView->header()->saveState(); } } void ActionListEditorPage::setDefaultCollection(const Akonadi::Collection &collection) { m_defaultCollection = collection; } <commit_msg>Make sure standard todo always come first in the list<commit_after>/* This file is part of Zanshin Todo. Copyright 2008-2010 Kevin Ottens <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "actionlisteditorpage.h" #include <KDE/Akonadi/ItemCreateJob> #include <KDE/Akonadi/ItemDeleteJob> #include <KDE/KConfigGroup> #include <kdescendantsproxymodel.h> #include <kmodelindexproxymapper.h> #include <QtCore/QTimer> #include <QtGui/QHeaderView> #include <QtGui/QSortFilterProxyModel> #include <QtGui/QVBoxLayout> #include "actionlistdelegate.h" #include "todomodel.h" #include "todotreeview.h" class GroupLabellingProxyModel : public QSortFilterProxyModel { public: GroupLabellingProxyModel(QObject *parent = 0) : QSortFilterProxyModel(parent) { setDynamicSortFilter(true); } QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const { if (role!=Qt::DisplayRole || index.column()!=0) { return QSortFilterProxyModel::data(index, role); } else { int type = index.data(TodoModel::ItemTypeRole).toInt(); if (type!=TodoModel::ProjectTodo && type!=TodoModel::Category) { return QSortFilterProxyModel::data(index, role); } else { QString display = QSortFilterProxyModel::data(index, role).toString(); QModelIndex currentIndex = index.parent(); type = currentIndex.data(TodoModel::ItemTypeRole).toInt(); while (type==TodoModel::ProjectTodo || type==TodoModel::Category) { display = currentIndex.data(role).toString() + ": " + display; currentIndex = currentIndex.parent(); type = currentIndex.data(TodoModel::ItemTypeRole).toInt(); } return display; } } } }; class GroupSortingProxyModel : public QSortFilterProxyModel { public: GroupSortingProxyModel(QObject *parent = 0) : QSortFilterProxyModel(parent) { setDynamicSortFilter(true); setFilterCaseSensitivity(Qt::CaseInsensitive); } bool lessThan(const QModelIndex &left, const QModelIndex &right) const { int leftType = left.data(TodoModel::ItemTypeRole).toInt(); int rightType = right.data(TodoModel::ItemTypeRole).toInt(); return leftType==TodoModel::Inbox || (leftType==TodoModel::CategoryRoot && rightType!=TodoModel::Inbox) || (leftType==TodoModel::Collection && rightType!=TodoModel::Inbox) || (leftType==TodoModel::Category && rightType==TodoModel::StandardTodo) || (leftType==TodoModel::StandardTodo && rightType!=TodoModel::StandardTodo) || (leftType==TodoModel::ProjectTodo && rightType==TodoModel::Collection) || (leftType == rightType && QSortFilterProxyModel::lessThan(left, right)); } }; class TypeFilterProxyModel : public QSortFilterProxyModel { public: TypeFilterProxyModel(GroupSortingProxyModel *sorting, QObject *parent = 0) : QSortFilterProxyModel(parent), m_sorting(sorting) { setDynamicSortFilter(true); setFilterCaseSensitivity(Qt::CaseInsensitive); } bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const { QModelIndex sourceChild = sourceModel()->index(sourceRow, 0, sourceParent); int type = sourceChild.data(TodoModel::ItemTypeRole).toInt(); QSize sizeHint = sourceChild.data(Qt::SizeHintRole).toSize(); return type!=TodoModel::Collection && type!=TodoModel::CategoryRoot && !sizeHint.isNull(); // SelectionProxyModel uses the null size for items we shouldn't display } void sort(int column, Qt::SortOrder order = Qt::AscendingOrder) { m_sorting->sort(column, order); } private: GroupSortingProxyModel *m_sorting; }; class ActionListEditorView : public TodoTreeView { public: ActionListEditorView(QWidget *parent = 0) : TodoTreeView(parent) { } protected: virtual QModelIndex moveCursor(CursorAction cursorAction, Qt::KeyboardModifiers modifiers) { QModelIndex index = currentIndex(); if (index.isValid() && modifiers==Qt::NoModifier) { QModelIndex newIndex; int newColumn = index.column(); switch (cursorAction) { case MoveLeft: do { newColumn--; } while (isColumnHidden(newColumn) && newColumn>=0); break; case MoveRight: do { newColumn++; } while (isColumnHidden(newColumn) && newColumn<header()->count()); break; default: return Akonadi::EntityTreeView::moveCursor(cursorAction, modifiers); } newIndex = index.sibling(index.row(), newColumn); if (newIndex.isValid()) { return newIndex; } } return Akonadi::EntityTreeView::moveCursor(cursorAction, modifiers); } }; class ActionListEditorModel : public KDescendantsProxyModel { public: ActionListEditorModel(QObject *parent = 0) : KDescendantsProxyModel(parent) { } virtual bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) { if (!sourceModel()) { return QAbstractProxyModel::dropMimeData(data, action, row, column, parent); } QModelIndex sourceParent = mapToSource(parent); return sourceModel()->dropMimeData(data, action, row, column, sourceParent); } }; ActionListEditorPage::ActionListEditorPage(QAbstractItemModel *model, ModelStack *models, Zanshin::ApplicationMode mode, QWidget *parent) : QWidget(parent), m_mode(mode) { setLayout(new QVBoxLayout(this)); layout()->setContentsMargins(0, 0, 0, 0); m_treeView = new ActionListEditorView(this); GroupLabellingProxyModel *labelling = new GroupLabellingProxyModel(this); labelling->setSourceModel(model); GroupSortingProxyModel *sorting = new GroupSortingProxyModel(this); sorting->setSourceModel(labelling); ActionListEditorModel *descendants = new ActionListEditorModel(this); descendants->setSourceModel(sorting); TypeFilterProxyModel *filter = new TypeFilterProxyModel(sorting, this); filter->setSourceModel(descendants); m_treeView->setModel(filter); m_treeView->setItemDelegate(new ActionListDelegate(models, m_treeView)); m_treeView->header()->setSortIndicatorShown(true); m_treeView->setSortingEnabled(true); m_treeView->sortByColumn(0, Qt::AscendingOrder); m_treeView->setSelectionMode(QAbstractItemView::ExtendedSelection); m_treeView->setItemsExpandable(false); m_treeView->setRootIsDecorated(false); m_treeView->setEditTriggers(m_treeView->editTriggers() | QAbstractItemView::DoubleClicked); connect(m_treeView->model(), SIGNAL(modelReset()), m_treeView, SLOT(expandAll())); connect(m_treeView->model(), SIGNAL(layoutChanged()), m_treeView, SLOT(expandAll())); connect(m_treeView->model(), SIGNAL(rowsInserted(QModelIndex, int, int)), m_treeView, SLOT(expandAll())); layout()->addWidget(m_treeView); QTimer::singleShot(0, this, SLOT(onAutoHideColumns())); connect(m_treeView->header(), SIGNAL(sectionResized(int, int, int)), this, SLOT(onColumnsGeometryChanged())); } QItemSelectionModel *ActionListEditorPage::selectionModel() const { return m_treeView->selectionModel(); } void ActionListEditorPage::saveColumnsState(KConfigGroup &config, const QString &key) const { config.writeEntry(key+"/Normal", m_normalStateCache.toBase64()); config.writeEntry(key+"/NoCollection", m_noCollectionStateCache.toBase64()); } void ActionListEditorPage::restoreColumnsState(const KConfigGroup &config, const QString &key) { if (config.hasKey(key+"/Normal")) { m_normalStateCache = QByteArray::fromBase64(config.readEntry(key+"/Normal", QByteArray())); } if (config.hasKey(key+"/NoCollection")) { m_noCollectionStateCache = QByteArray::fromBase64(config.readEntry(key+"/NoCollection", QByteArray())); } if (!m_treeView->isColumnHidden(4)) { m_treeView->header()->restoreState(m_normalStateCache); } else { m_treeView->header()->restoreState(m_noCollectionStateCache); } } void ActionListEditorPage::addNewTodo(const QString &summary) { if (summary.isEmpty()) return; QModelIndex current = m_treeView->selectionModel()->currentIndex(); if (!current.isValid()) { kWarning() << "Oops, nothing selected in the list!"; return; } int type = current.data(TodoModel::ItemTypeRole).toInt(); while (current.isValid() && type==TodoModel::StandardTodo) { current = current.parent(); type = current.data(TodoModel::ItemTypeRole).toInt(); } Akonadi::Collection collection; QString parentUid; QString category; switch (type) { case TodoModel::StandardTodo: kFatal() << "Can't possibly happen!"; break; case TodoModel::ProjectTodo: parentUid = current.data(TodoModel::UidRole).toString(); collection = current.data(Akonadi::EntityTreeModel::ParentCollectionRole).value<Akonadi::Collection>(); break; case TodoModel::Collection: collection = current.data(Akonadi::EntityTreeModel::CollectionRole).value<Akonadi::Collection>(); break; case TodoModel::Category: category = current.data(Qt::EditRole).toString(); // fallthrough case TodoModel::Inbox: case TodoModel::CategoryRoot: collection = m_defaultCollection; break; } KCalCore::Todo::Ptr todo(new KCalCore::Todo); todo->setSummary(summary); if (!parentUid.isEmpty()) { todo->setRelatedTo(parentUid); } if (!category.isEmpty()) { todo->setCategories(category); } Akonadi::Item item; item.setMimeType("application/x-vnd.akonadi.calendar.todo"); item.setPayload<KCalCore::Todo::Ptr>(todo); new Akonadi::ItemCreateJob(item, collection); } void ActionListEditorPage::removeCurrentTodo() { QModelIndex current = m_treeView->selectionModel()->currentIndex(); int type = current.data(TodoModel::ItemTypeRole).toInt(); if (!current.isValid() || type!=TodoModel::StandardTodo) { return; } Akonadi::Item item = current.data(Akonadi::EntityTreeModel::ItemRole).value<Akonadi::Item>(); if (!item.isValid()) { return; } new Akonadi::ItemDeleteJob(item, this); } Zanshin::ApplicationMode ActionListEditorPage::mode() { return m_mode; } void ActionListEditorPage::onAutoHideColumns() { switch (m_mode) { case Zanshin::ProjectMode: hideColumn(1); break; case Zanshin::CategoriesMode: hideColumn(2); break; } } void ActionListEditorPage::hideColumn(int column) { if (!m_treeView->isColumnHidden(column)) { m_treeView->hideColumn(column); } } void ActionListEditorPage::setCollectionColumnHidden(bool hidden) { QByteArray state = hidden ? m_noCollectionStateCache : m_normalStateCache; if (!state.isEmpty()) { m_treeView->header()->restoreState(state); } else { m_treeView->setColumnHidden(4, hidden); } } void ActionListEditorPage::onColumnsGeometryChanged() { if (!m_treeView->isColumnHidden(4)) { m_normalStateCache = m_treeView->header()->saveState(); } else { m_noCollectionStateCache = m_treeView->header()->saveState(); } } void ActionListEditorPage::setDefaultCollection(const Akonadi::Collection &collection) { m_defaultCollection = collection; } <|endoftext|>
<commit_before>#include<iostream> int main() { using std::cin; using std::cout; using std::endl; int i = 0, n = 0; cout<<"How many numbers would you like to have on your list?"<<endl; cin>>n; int *list = new int [n]; cout<<"Please enter the integers."<<endl; for(i = 0; i < n; i++) { cin>>list[i]; } cout<<"The numbers you have added are "; for(i = 0; i < n; i++) { cout<<*(list + i)<<" "; } cout<<"."<<endl; delete [] list; return 0; } <commit_msg>Code Update<commit_after>#include <iostream> int main() { using std::cin; using std::cout; using std::endl; int i = 0, n = 0; cout<<"How many numbers would you like to have on your list?"<<endl; cin>>n; int *list = new int [n]; cout<<"Please enter the integers."<<endl; for(i = 0; i < n; i++) { cin>>list[i]; } cout<<"The numbers you have added are "; for(i = 0; i < n; i++) { cout<<*(list + i)<<" "; } cout<<"."<<endl; delete [] list; return 0; }<|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "geocodingtab.h" #include "placepresenter.h" #include <QTreeWidget> #include <QLineEdit> #include <QString> #include <QLabel> #include <QVBoxLayout> #include <QHBoxLayout> #include <QPushButton> #include <QMessageBox> #include <QDialogButtonBox> #include <qgeoaddress.h> GeoCodingInputDialog::GeoCodingInputDialog(QString &obloc, QGeoAddress &address, QWidget *parent) : QDialog(parent), m_oblocStr(obloc), m_address(address) { setWindowTitle(tr("Geocoding Parameters")); QLabel *obloclbl = new QLabel(tr("OneBox-Search:")); m_obloc = new QLineEdit(m_oblocStr); m_obloc->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed); QLabel *addressSearchlbl = new QLabel(tr("Search by address (Leave OneBox empty):")); QLabel *countrylbl = new QLabel(tr("Country:")); m_country = new QLineEdit(address.country()); m_country->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); QLabel *statelbl = new QLabel(tr("State:")); m_state = new QLineEdit(address.state()); m_state->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); QLabel *citylbl = new QLabel(tr("City:")); m_city = new QLineEdit(address.city()); m_city->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); QLabel *ziplbl = new QLabel(tr("Zip:")); m_zip = new QLineEdit(address.postCode()); m_zip->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); QLabel *streetlbl = new QLabel(tr("Street:")); m_street = new QLineEdit(address.street()); m_street->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); QHBoxLayout *firstrow = new QHBoxLayout; firstrow->setSpacing(2); firstrow->setContentsMargins(2, 1, 2, 1); firstrow->addWidget(m_obloc); QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel,Qt::Horizontal); connect(buttonBox,SIGNAL(accepted()),this,SLOT(accept())); connect(buttonBox,SIGNAL(rejected()),this,SLOT(reject())); QGridLayout *gridLayout = new QGridLayout ; gridLayout->setSizeConstraint(QLayout::SetMinimumSize); gridLayout->setSpacing(2); gridLayout->setContentsMargins(2, 1, 2, 1); gridLayout->addWidget(streetlbl, 1, 0); gridLayout->addWidget(m_street, 2, 0,1,2); gridLayout->addWidget(ziplbl, 3, 0); gridLayout->addWidget(citylbl, 3, 1); gridLayout->addWidget(m_zip, 4, 0); gridLayout->addWidget(m_city, 4, 1); gridLayout->addWidget(statelbl, 5, 0); gridLayout->addWidget(countrylbl, 5, 1); gridLayout->addWidget(m_state, 6, 0); gridLayout->addWidget(m_country, 6, 1); QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->setSizeConstraint(QLayout::SetFixedSize); mainLayout->setSpacing(2); mainLayout->setContentsMargins(2, 1, 2, 1); mainLayout->addWidget(obloclbl); mainLayout->addLayout(firstrow); mainLayout->addWidget(addressSearchlbl); mainLayout->addLayout(gridLayout); mainLayout->addWidget(buttonBox); setLayout(mainLayout); } void GeoCodingInputDialog::accept() { m_oblocStr = m_obloc->text(); m_address.setCountry(m_country->text()); m_address.setState(m_state->text()); m_address.setCity(m_city->text()); m_address.setPostCode(m_zip->text()); m_address.setStreet(m_street->text()); QDialog::accept(); } GeocodingTab::GeocodingTab(QWidget *parent) : QWidget(parent), m_searchManager(NULL) { m_oblocStr="Deutschland, Mnchen"; m_requestBtn = new QPushButton(tr("Search By Address")); m_requestBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); m_requestBtn->setDisabled(true); QObject::connect(m_requestBtn, SIGNAL(clicked(bool)), this, SLOT(on_btnRequest_clicked())); m_resultTree = new QTreeWidget(); QStringList labels; labels << tr("Elements") << tr("Value"); m_resultTree->setHeaderLabels(labels); m_resultTree->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); m_resultTree->setColumnWidth(0, 240); QHBoxLayout *firstrow = new QHBoxLayout; firstrow->setSpacing(2); firstrow->setContentsMargins(2, 1, 2, 1); firstrow->addWidget(m_requestBtn); QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->setSpacing(2); mainLayout->setContentsMargins(2, 1, 2, 1); mainLayout->addLayout(firstrow); mainLayout->addWidget(m_resultTree); setLayout(mainLayout); } GeocodingTab::~GeocodingTab() { } void GeocodingTab::initialize(QGeoSearchManager *searchManager) { m_resultTree->clear(); m_searchManager = searchManager; if (m_searchManager) { QObject::connect(m_searchManager, SIGNAL(finished(QGeoSearchReply*)), this, SLOT(replyFinished(QGeoSearchReply*))); QObject::connect(m_searchManager, SIGNAL(error(QGeoSearchReply*, QGeoSearchReply::Error, QString)), this, SLOT(resultsError(QGeoSearchReply*, QGeoSearchReply::Error, QString))); if (m_searchManager->supportsGeocoding()) m_requestBtn->setDisabled(false); } else m_requestBtn->setDisabled(true); } void GeocodingTab::on_btnRequest_clicked() { if (m_searchManager) { GeoCodingInputDialog dlg(m_oblocStr,m_address,this); if(dlg.exec()==QDialog::Accepted) { m_resultTree->clear(); QTreeWidgetItem* top = new QTreeWidgetItem(m_resultTree); top->setText(0, tr("Geocode")); top->setText(1, tr("Requesting data")); if (!m_oblocStr.isEmpty()) { m_searchManager->search(m_oblocStr, QGeoSearchManager::SearchGeocode); } else { m_searchManager->geocode(m_address); } } } else { QMessageBox::warning(this, tr("Geocoding"), tr("No search manager available.")); } } void GeocodingTab::replyFinished(QGeoSearchReply* reply) { if (!isHidden() && reply->error() == QGeoSearchReply::NoError) { PlacePresenter presenter(m_resultTree, reply); presenter.show(); reply->deleteLater(); } } void GeocodingTab::resultsError(QGeoSearchReply* reply, QGeoSearchReply::Error errorCode, QString errorString) { Q_UNUSED(errorCode) if (!isHidden()) { QTreeWidgetItem* errorResultItem = new QTreeWidgetItem(m_resultTree); errorResultItem->setText(0, tr("Error")); errorResultItem->setText(1, errorString); reply->deleteLater(); } } <commit_msg>Fixes: MOBILITY-1431 GeoServiceDemo UI issues on Maemo5<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "geocodingtab.h" #include "placepresenter.h" #include <QTreeWidget> #include <QLineEdit> #include <QString> #include <QLabel> #include <QVBoxLayout> #include <QHBoxLayout> #include <QPushButton> #include <QMessageBox> #include <QDialogButtonBox> #include <qgeoaddress.h> GeoCodingInputDialog::GeoCodingInputDialog(QString &obloc, QGeoAddress &address, QWidget *parent) : QDialog(parent), m_oblocStr(obloc), m_address(address) { setWindowTitle(tr("Geocoding Parameters")); QLabel *obloclbl = new QLabel(tr("OneBox-Search:")); m_obloc = new QLineEdit(m_oblocStr); m_obloc->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed); QLabel *addressSearchlbl = new QLabel(tr("Search by address (Leave OneBox empty):")); QLabel *countrylbl = new QLabel(tr("Country:")); m_country = new QLineEdit(address.country()); m_country->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); QLabel *statelbl = new QLabel(tr("State:")); m_state = new QLineEdit(address.state()); m_state->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); QLabel *citylbl = new QLabel(tr("City:")); m_city = new QLineEdit(address.city()); m_city->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); QLabel *ziplbl = new QLabel(tr("Zip:")); m_zip = new QLineEdit(address.postCode()); m_zip->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); QLabel *streetlbl = new QLabel(tr("Street:")); m_street = new QLineEdit(address.street()); m_street->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); QHBoxLayout *firstrow = new QHBoxLayout; firstrow->setSpacing(2); firstrow->setContentsMargins(2, 1, 2, 1); firstrow->addWidget(m_obloc); QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel,Qt::Horizontal); connect(buttonBox,SIGNAL(accepted()),this,SLOT(accept())); connect(buttonBox,SIGNAL(rejected()),this,SLOT(reject())); QGridLayout *gridLayout = new QGridLayout ; gridLayout->setSizeConstraint(QLayout::SetMinimumSize); gridLayout->setSpacing(2); gridLayout->setContentsMargins(2, 1, 2, 1); #if defined(Q_WS_MAEMO_5) || defined(Q_WS_MAEMO_6) gridLayout->addWidget(streetlbl, 1, 0); gridLayout->addWidget(m_street, 1, 1,1,3); gridLayout->addWidget(ziplbl, 2, 0); gridLayout->addWidget(citylbl, 2, 2); gridLayout->addWidget(m_zip, 2, 1); gridLayout->addWidget(m_city, 2, 3); gridLayout->addWidget(statelbl, 3, 0); gridLayout->addWidget(countrylbl, 3, 2); gridLayout->addWidget(m_state, 3, 1); gridLayout->addWidget(m_country, 3, 3); #else gridLayout->addWidget(streetlbl, 1, 0); gridLayout->addWidget(m_street, 2, 0,1,2); gridLayout->addWidget(ziplbl, 3, 0); gridLayout->addWidget(citylbl, 3, 1); gridLayout->addWidget(m_zip, 4, 0); gridLayout->addWidget(m_city, 4, 1); gridLayout->addWidget(statelbl, 5, 0); gridLayout->addWidget(countrylbl, 5, 1); gridLayout->addWidget(m_state, 6, 0); gridLayout->addWidget(m_country, 6, 1); #endif QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->setSizeConstraint(QLayout::SetFixedSize); mainLayout->setSpacing(2); mainLayout->setContentsMargins(2, 1, 2, 1); mainLayout->addWidget(obloclbl); mainLayout->addLayout(firstrow); mainLayout->addWidget(addressSearchlbl); mainLayout->addLayout(gridLayout); mainLayout->addWidget(buttonBox); setLayout(mainLayout); } void GeoCodingInputDialog::accept() { m_oblocStr = m_obloc->text(); m_address.setCountry(m_country->text()); m_address.setState(m_state->text()); m_address.setCity(m_city->text()); m_address.setPostCode(m_zip->text()); m_address.setStreet(m_street->text()); QDialog::accept(); } GeocodingTab::GeocodingTab(QWidget *parent) : QWidget(parent), m_searchManager(NULL) { m_oblocStr="Deutschland, Mnchen"; m_requestBtn = new QPushButton(tr("Search By Address")); m_requestBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); m_requestBtn->setDisabled(true); QObject::connect(m_requestBtn, SIGNAL(clicked(bool)), this, SLOT(on_btnRequest_clicked())); m_resultTree = new QTreeWidget(); QStringList labels; labels << tr("Elements") << tr("Value"); m_resultTree->setHeaderLabels(labels); m_resultTree->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); m_resultTree->setColumnWidth(0, 240); QHBoxLayout *firstrow = new QHBoxLayout; firstrow->setSpacing(2); firstrow->setContentsMargins(2, 1, 2, 1); firstrow->addWidget(m_requestBtn); QVBoxLayout *mainLayout = new QVBoxLayout; mainLayout->setSpacing(2); mainLayout->setContentsMargins(2, 1, 2, 1); mainLayout->addLayout(firstrow); mainLayout->addWidget(m_resultTree); setLayout(mainLayout); } GeocodingTab::~GeocodingTab() { } void GeocodingTab::initialize(QGeoSearchManager *searchManager) { m_resultTree->clear(); m_searchManager = searchManager; if (m_searchManager) { QObject::connect(m_searchManager, SIGNAL(finished(QGeoSearchReply*)), this, SLOT(replyFinished(QGeoSearchReply*))); QObject::connect(m_searchManager, SIGNAL(error(QGeoSearchReply*, QGeoSearchReply::Error, QString)), this, SLOT(resultsError(QGeoSearchReply*, QGeoSearchReply::Error, QString))); if (m_searchManager->supportsGeocoding()) m_requestBtn->setDisabled(false); } else m_requestBtn->setDisabled(true); } void GeocodingTab::on_btnRequest_clicked() { if (m_searchManager) { GeoCodingInputDialog dlg(m_oblocStr,m_address,this); if(dlg.exec()==QDialog::Accepted) { m_resultTree->clear(); QTreeWidgetItem* top = new QTreeWidgetItem(m_resultTree); top->setText(0, tr("Geocode")); top->setText(1, tr("Requesting data")); if (!m_oblocStr.isEmpty()) { m_searchManager->search(m_oblocStr, QGeoSearchManager::SearchGeocode); } else { m_searchManager->geocode(m_address); } } } else { QMessageBox::warning(this, tr("Geocoding"), tr("No search manager available.")); } } void GeocodingTab::replyFinished(QGeoSearchReply* reply) { if (!isHidden() && reply->error() == QGeoSearchReply::NoError) { PlacePresenter presenter(m_resultTree, reply); presenter.show(); reply->deleteLater(); } } void GeocodingTab::resultsError(QGeoSearchReply* reply, QGeoSearchReply::Error errorCode, QString errorString) { Q_UNUSED(errorCode) if (!isHidden()) { QTreeWidgetItem* errorResultItem = new QTreeWidgetItem(m_resultTree); errorResultItem->setText(0, tr("Error")); errorResultItem->setText(1, errorString); reply->deleteLater(); } } <|endoftext|>
<commit_before>/* * people_det.cpp * * Created on: Oct 20, 2015 * Author: Tzutalin */ #include <string.h> #include <jni.h> #include <android/log.h> #include <string> #include <stdio.h> #include <vector> #include <opencv2/opencv.hpp> #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <dlib/image_processing/frontal_face_detector.h> #include <dlib/image_processing/render_face_detections.h> #include <dlib/opencv/cv_image.h> #include <dlib/image_loader/load_image.h> #define LOG_TAG "People_Det-JNI" #define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE,LOG_TAG, __VA_ARGS__) #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG, __VA_ARGS__) #define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG, __VA_ARGS__) #define LOGW(...) __android_log_print(ANDROID_LOG_WARN,LOG_TAG, __VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG, __VA_ARGS__) class OpencvHOGDetctor { public: OpencvHOGDetctor() { } inline int det(std::string path) { LOGD("det path %s", path.c_str()); cv::Mat src_img = cv::imread(path, 1); if (src_img.empty()) return 0; cv::HOGDescriptor hog; hog.setSVMDetector(cv::HOGDescriptor::getDefaultPeopleDetector()); std::vector<cv::Rect> found, found_filtered; hog.detectMultiScale(src_img, found, 0, cv::Size(8, 8), cv::Size(32, 32), 1.05, 2); size_t i, j; for (i = 0; i < found.size(); i++) { cv::Rect r = found[i]; for (j = 0; j < found.size(); j++) if (j != i && (r & found[j]) == r) break; if (j == found.size()) found_filtered.push_back(r); } for (i = 0; i < found_filtered.size(); i++) { cv::Rect r = found_filtered[i]; r.x += cvRound(r.width * 0.1); r.width = cvRound(r.width * 0.8); r.y += cvRound(r.height * 0.06); r.height = cvRound(r.height * 0.9); cv::rectangle(src_img, r.tl(), r.br(), cv::Scalar(0, 255, 0), 2); } mResultMat = src_img; //cv::imwrite(path, mResultMat); LOGD("det ends"); mRets = found_filtered; return found_filtered.size(); } inline cv::Mat& getResultMat() { return mResultMat; } inline std::vector<cv::Rect> getResult() { return mRets; } private: cv::Mat mResultMat; std::vector<cv::Rect> mRets; }; class DLibHOGFaceDetector { public: DLibHOGFaceDetector() { } inline int det(std::string path) { dlib::frontal_face_detector detector = dlib::get_frontal_face_detector(); dlib::array2d<dlib::rgb_pixel> img; load_image(img, path); //dlib::pyramid_up(img); mRets = detector(img); LOGD("Dlib HOG face det size : %d", mRets.size()); // Draw on the input for test int i = 0; cv::Mat src_img = cv::imread(path, 1); for (i = 0; i < mRets.size(); i++) { dlib::rectangle dlibrect = mRets[i]; cv::Rect r(dlibrect.left(), dlibrect.top(), dlibrect.width(), dlibrect.height()); r.x += cvRound(r.width * 0.1); r.width = cvRound(r.width * 0.8); r.y += cvRound(r.height * 0.06); r.height = cvRound(r.height * 0.9); cv::rectangle(src_img, r.tl(), r.br(), cv::Scalar(0, 255, 0), 2); } //cv::imwrite(path, src_img); return mRets.size(); } inline std::vector<dlib::rectangle> getResult() { return mRets; } private: std::string mModel; std::vector<dlib::rectangle> mRets; }; OpencvHOGDetctor* mOpencvHOGDetctor = NULL; DLibHOGFaceDetector* mDlibFaceDetector = NULL; #ifdef __cplusplus extern "C" { #endif struct VisionDetRetOffsets { jfieldID label; jfieldID confidence; jfieldID left; jfieldID top; jfieldID right; jfieldID bottom; } gVisionDetRetOffsets; // ======================================================== // JNI Mapping Methods // ======================================================== jint JNIEXPORT JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { LOGE("JNI On Load"); JNIEnv* env = NULL; jint result = -1; if (vm->GetEnv((void**) &env, JNI_VERSION_1_6) != JNI_OK) { LOGE("GetEnv failed!"); return result; } return JNI_VERSION_1_6; } void JNIEXPORT JNICALL Java_com_tzutalin_dlib_PeopleDet_jniNativeClassInit(JNIEnv *_env, jclass _this) { jclass detRetClass = _env->FindClass("com/tzutalin/dlib/VisionDetRet"); gVisionDetRetOffsets.label = _env->GetFieldID(detRetClass, "mLabel", "java/lang/String"); gVisionDetRetOffsets.confidence = _env->GetFieldID(detRetClass, "mConfidence", "F"); gVisionDetRetOffsets.left = _env->GetFieldID(detRetClass, "mLeft", "I"); gVisionDetRetOffsets.top = _env->GetFieldID(detRetClass, "mTop", "I"); gVisionDetRetOffsets.right = _env->GetFieldID(detRetClass, "mRight", "I"); gVisionDetRetOffsets.bottom = _env->GetFieldID(detRetClass, "mBottom", "I"); LOGD("JniNativeClassIni Success"); } jint JNIEXPORT JNICALL Java_com_tzutalin_dlib_PeopleDet_jniOpencvHOGDetect( JNIEnv* env, jobject thiz, jstring imgPath) { LOGD("com_tzutalin_dlib_PeopleDet jniOpencvHOGDetect"); const char *img_path = env->GetStringUTFChars(imgPath, 0); if(mOpencvHOGDetctor == NULL) mOpencvHOGDetctor = new OpencvHOGDetctor(); int nums = mOpencvHOGDetctor->det(std::string(img_path)); env->ReleaseStringUTFChars(imgPath, img_path); return nums; } jint JNIEXPORT JNICALL Java_com_tzutalin_dlib_PeopleDet_jniGetOpecvHOGRet(JNIEnv* env, jobject thiz, jobject detRet, jint index) { if (mOpencvHOGDetctor) { cv::Rect rect = mOpencvHOGDetctor->getResult()[index]; env->SetIntField(detRet, gVisionDetRetOffsets.left, rect.x); env->SetIntField(detRet, gVisionDetRetOffsets.top, rect.y); env->SetIntField(detRet, gVisionDetRetOffsets.right, rect.x + rect.width); env->SetIntField(detRet, gVisionDetRetOffsets.bottom, rect.y + rect.height); env->SetFloatField(detRet, gVisionDetRetOffsets.confidence, 0); jstring jstr=(jstring)(env->NewStringUTF("person")); env->SetObjectField(detRet, gVisionDetRetOffsets.label, (jobject)jstr); return 0; } return -1; } jint JNIEXPORT JNICALL Java_com_tzutalin_dlib_PeopleDet_jniDLibHOGDetect( JNIEnv* env, jobject thiz, jstring imgPath, jobject detRet) { LOGD("com_tzutalin_dlib_PeopleDet jniDLibHOGDetect"); const char *img_path = env->GetStringUTFChars(imgPath, 0); if(mDlibFaceDetector == NULL) mDlibFaceDetector = new DLibHOGFaceDetector(); int size = mDlibFaceDetector->det(std::string(img_path)); env->ReleaseStringUTFChars(imgPath, img_path); return size; } jint JNIEXPORT JNICALL Java_com_tzutalin_dlib_PeopleDet_jniGetDLibRet(JNIEnv* env, jobject thiz, jobject detRet, jint index) { if (mDlibFaceDetector) { dlib::rectangle rect = mDlibFaceDetector->getResult()[index]; env->SetIntField(detRet, gVisionDetRetOffsets.left, rect.left()); env->SetIntField(detRet, gVisionDetRetOffsets.top, rect.top()); env->SetIntField(detRet, gVisionDetRetOffsets.right, rect.right()); env->SetIntField(detRet, gVisionDetRetOffsets.bottom, rect.bottom()); env->SetFloatField(detRet, gVisionDetRetOffsets.confidence, 0); jstring jstr=(jstring)(env->NewStringUTF("face")); env->SetObjectField(detRet, gVisionDetRetOffsets.label, (jobject)jstr); return 0; } return -1; } jint JNIEXPORT JNICALL Java_com_tzutalin_dlib_PeopleDet_jniInit(JNIEnv* env, jobject thiz) { if(mDlibFaceDetector == NULL) mDlibFaceDetector = new DLibHOGFaceDetector(); if (mOpencvHOGDetctor == NULL) mOpencvHOGDetctor = new OpencvHOGDetctor(); return 0; } jint JNIEXPORT JNICALL Java_com_tzutalin_dlib_PeopleDet_jniDeInit(JNIEnv* env, jobject thiz) { if(mDlibFaceDetector) delete mDlibFaceDetector; if (mOpencvHOGDetctor) delete mOpencvHOGDetctor; return 0; } #ifdef __cplusplus } #endif <commit_msg>DLib Facedetection will read image from openCV<commit_after>/* * people_det.cpp * * Created on: Oct 20, 2015 * Author: Tzutalin */ #include <string.h> #include <jni.h> #include <android/log.h> #include <string> #include <stdio.h> #include <vector> #include <opencv2/opencv.hpp> #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <dlib/image_processing/frontal_face_detector.h> #include <dlib/image_processing/render_face_detections.h> #include <dlib/opencv/cv_image.h> #include <dlib/image_loader/load_image.h> #define LOG_TAG "People_Det-JNI" #define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE,LOG_TAG, __VA_ARGS__) #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG, __VA_ARGS__) #define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG, __VA_ARGS__) #define LOGW(...) __android_log_print(ANDROID_LOG_WARN,LOG_TAG, __VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG, __VA_ARGS__) class OpencvHOGDetctor { public: OpencvHOGDetctor() { } inline int det(std::string path) { LOGD("det path %s", path.c_str()); cv::Mat src_img = cv::imread(path, 1); if (src_img.empty()) return 0; cv::HOGDescriptor hog; hog.setSVMDetector(cv::HOGDescriptor::getDefaultPeopleDetector()); std::vector<cv::Rect> found, found_filtered; hog.detectMultiScale(src_img, found, 0, cv::Size(8, 8), cv::Size(32, 32), 1.05, 2); size_t i, j; for (i = 0; i < found.size(); i++) { cv::Rect r = found[i]; for (j = 0; j < found.size(); j++) if (j != i && (r & found[j]) == r) break; if (j == found.size()) found_filtered.push_back(r); } for (i = 0; i < found_filtered.size(); i++) { cv::Rect r = found_filtered[i]; r.x += cvRound(r.width * 0.1); r.width = cvRound(r.width * 0.8); r.y += cvRound(r.height * 0.06); r.height = cvRound(r.height * 0.9); cv::rectangle(src_img, r.tl(), r.br(), cv::Scalar(0, 255, 0), 2); } mResultMat = src_img; //cv::imwrite(path, mResultMat); LOGD("det ends"); mRets = found_filtered; return found_filtered.size(); } inline cv::Mat& getResultMat() { return mResultMat; } inline std::vector<cv::Rect> getResult() { return mRets; } private: cv::Mat mResultMat; std::vector<cv::Rect> mRets; }; class DLibHOGFaceDetector { public: DLibHOGFaceDetector() { } inline int det(std::string path) { dlib::frontal_face_detector detector = dlib::get_frontal_face_detector(); cv::Mat src_img = cv::imread(path, 1); dlib::cv_image<dlib::bgr_pixel> img(src_img); mRets = detector(img); LOGD("Dlib HOG face det size : %d", mRets.size()); /* // Draw on the input for test int i = 0; for (i = 0; i < mRets.size(); i++) { dlib::rectangle dlibrect = mRets[i]; cv::Rect r(dlibrect.left(), dlibrect.top(), dlibrect.width(), dlibrect.height()); r.x += cvRound(r.width * 0.1); r.width = cvRound(r.width * 0.8); r.y += cvRound(r.height * 0.06); r.height = cvRound(r.height * 0.9); cv::rectangle(src_img, r.tl(), r.br(), cv::Scalar(0, 255, 0), 2); } cv::imwrite(path, src_img); */ return mRets.size(); } inline std::vector<dlib::rectangle> getResult() { return mRets; } private: std::string mModel; std::vector<dlib::rectangle> mRets; }; OpencvHOGDetctor* mOpencvHOGDetctor = NULL; DLibHOGFaceDetector* mDlibFaceDetector = NULL; #ifdef __cplusplus extern "C" { #endif struct VisionDetRetOffsets { jfieldID label; jfieldID confidence; jfieldID left; jfieldID top; jfieldID right; jfieldID bottom; } gVisionDetRetOffsets; // ======================================================== // JNI Mapping Methods // ======================================================== jint JNIEXPORT JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { LOGE("JNI On Load"); JNIEnv* env = NULL; jint result = -1; if (vm->GetEnv((void**) &env, JNI_VERSION_1_6) != JNI_OK) { LOGE("GetEnv failed!"); return result; } return JNI_VERSION_1_6; } void JNIEXPORT JNICALL Java_com_tzutalin_dlib_PeopleDet_jniNativeClassInit(JNIEnv *_env, jclass _this) { jclass detRetClass = _env->FindClass("com/tzutalin/dlib/VisionDetRet"); gVisionDetRetOffsets.label = _env->GetFieldID(detRetClass, "mLabel", "java/lang/String"); gVisionDetRetOffsets.confidence = _env->GetFieldID(detRetClass, "mConfidence", "F"); gVisionDetRetOffsets.left = _env->GetFieldID(detRetClass, "mLeft", "I"); gVisionDetRetOffsets.top = _env->GetFieldID(detRetClass, "mTop", "I"); gVisionDetRetOffsets.right = _env->GetFieldID(detRetClass, "mRight", "I"); gVisionDetRetOffsets.bottom = _env->GetFieldID(detRetClass, "mBottom", "I"); LOGD("JniNativeClassIni Success"); } jint JNIEXPORT JNICALL Java_com_tzutalin_dlib_PeopleDet_jniOpencvHOGDetect( JNIEnv* env, jobject thiz, jstring imgPath) { LOGD("com_tzutalin_dlib_PeopleDet jniOpencvHOGDetect"); const char *img_path = env->GetStringUTFChars(imgPath, 0); if(mOpencvHOGDetctor == NULL) mOpencvHOGDetctor = new OpencvHOGDetctor(); int nums = mOpencvHOGDetctor->det(std::string(img_path)); env->ReleaseStringUTFChars(imgPath, img_path); return nums; } jint JNIEXPORT JNICALL Java_com_tzutalin_dlib_PeopleDet_jniGetOpecvHOGRet(JNIEnv* env, jobject thiz, jobject detRet, jint index) { if (mOpencvHOGDetctor) { cv::Rect rect = mOpencvHOGDetctor->getResult()[index]; env->SetIntField(detRet, gVisionDetRetOffsets.left, rect.x); env->SetIntField(detRet, gVisionDetRetOffsets.top, rect.y); env->SetIntField(detRet, gVisionDetRetOffsets.right, rect.x + rect.width); env->SetIntField(detRet, gVisionDetRetOffsets.bottom, rect.y + rect.height); env->SetFloatField(detRet, gVisionDetRetOffsets.confidence, 0); jstring jstr=(jstring)(env->NewStringUTF("person")); env->SetObjectField(detRet, gVisionDetRetOffsets.label, (jobject)jstr); return 0; } return -1; } jint JNIEXPORT JNICALL Java_com_tzutalin_dlib_PeopleDet_jniDLibHOGDetect( JNIEnv* env, jobject thiz, jstring imgPath, jobject detRet) { LOGD("com_tzutalin_dlib_PeopleDet jniDLibHOGDetect"); const char *img_path = env->GetStringUTFChars(imgPath, 0); if(mDlibFaceDetector == NULL) mDlibFaceDetector = new DLibHOGFaceDetector(); int size = mDlibFaceDetector->det(std::string(img_path)); env->ReleaseStringUTFChars(imgPath, img_path); return size; } jint JNIEXPORT JNICALL Java_com_tzutalin_dlib_PeopleDet_jniGetDLibRet(JNIEnv* env, jobject thiz, jobject detRet, jint index) { if (mDlibFaceDetector) { dlib::rectangle rect = mDlibFaceDetector->getResult()[index]; env->SetIntField(detRet, gVisionDetRetOffsets.left, rect.left()); env->SetIntField(detRet, gVisionDetRetOffsets.top, rect.top()); env->SetIntField(detRet, gVisionDetRetOffsets.right, rect.right()); env->SetIntField(detRet, gVisionDetRetOffsets.bottom, rect.bottom()); env->SetFloatField(detRet, gVisionDetRetOffsets.confidence, 0); jstring jstr=(jstring)(env->NewStringUTF("face")); env->SetObjectField(detRet, gVisionDetRetOffsets.label, (jobject)jstr); return 0; } return -1; } jint JNIEXPORT JNICALL Java_com_tzutalin_dlib_PeopleDet_jniInit(JNIEnv* env, jobject thiz) { if(mDlibFaceDetector == NULL) mDlibFaceDetector = new DLibHOGFaceDetector(); if (mOpencvHOGDetctor == NULL) mOpencvHOGDetctor = new OpencvHOGDetctor(); return 0; } jint JNIEXPORT JNICALL Java_com_tzutalin_dlib_PeopleDet_jniDeInit(JNIEnv* env, jobject thiz) { if(mDlibFaceDetector) delete mDlibFaceDetector; if (mOpencvHOGDetctor) delete mOpencvHOGDetctor; return 0; } #ifdef __cplusplus } #endif <|endoftext|>
<commit_before>/*! \file helpers.hpp \brief Internal helper functionality \ingroup Internal */ /* Copyright (c) 2013, Randolph Voorhies, Shane Grant 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 cereal 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 RANDOLPH VOORHIES OR SHANE GRANT BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CEREAL_DETAILS_HELPERS_HPP_ #define CEREAL_DETAILS_HELPERS_HPP_ #include <type_traits> #include <cstdint> #include <utility> namespace cereal { //! The size type used by cereal /*! To ensure compatability between 32, 64, etc bit machines, we need to use * a fixed size type instead of size_t, which may vary from machine to * machine. */ typedef uint64_t size_type; // forward decls class BinaryOutputArchive; class BinaryInputArchive; // ###################################################################### namespace detail { struct NameValuePairCore {}; } //! For holding name value pairs /*! This pairs a name (some string) with some value such that an archive can potentially take advantage of the pairing. In serialization functions, NameValuePairs are usually created like so: @code{.cpp} struct MyStruct { int a, b, c, d, e; template<class Archive> void serialize(Archive & archive) { archive( CEREAL_NVP(a), CEREAL_NVP(b), CEREAL_NVP(c), CEREAL_NVP(d), CEREAL_NVP(e) ); } }; @endcode Alternatively, you can give you data members custom names like so: @code{.cpp} struct MyStruct { int a, b, my_embarrassing_variable_name, d, e; template<class Archive> void serialize(Archive & archive) { archive( CEREAL_NVP(a), CEREAL_NVP(b), cereal::make_nvp("var", my_embarrassing_variable_name) ); CEREAL_NVP(d), CEREAL_NVP(e) ); } }; @endcode There is a slight amount of overhead to creating NameValuePairs, so there is a third method which will elide the names when they are not needed by the Archive: @code{.cpp} struct MyStruct { int a, b; template<class Archive> void serialize(Archive & archive) { archive( cereal::make_nvp<Archive>(a), cereal::make_nvp<Archive>(b) ); } }; @endcode This third method is generally only used when providing generic type support. Users writing their own serialize functions will normally explicitly control whether they want to use NVPs or not. @internal */ template <class T> class NameValuePair : detail::NameValuePairCore { private: // If we get passed an RValue, we'll just make a local copy if it here // otherwise, we store a reference typedef typename std::decay<T>::type DT; typedef typename std::conditional<std::is_rvalue_reference<T>::value, DT, typename std::add_lvalue_reference<DT>::type>::type Type; // prevent nested nvps static_assert( !std::is_base_of<detail::NameValuePairCore, T>::value, "Cannot pair a name to a NameValuePair" ); public: //! Constructs a new NameValuePair /*! @param n The name of the pair @param v The value to pair. Ideally this should be an l-value reference so that the value can be both loaded and saved to. If you pass an r-value reference, the NameValuePair will store a copy of it instead of a reference. Thus you should only pass r-values in cases where this makes sense, such as the result of some size() call. In either case, any constness will be stripped away @internal */ NameValuePair( char const * n, T && v ) : name(n), value(const_cast<Type>(v)) {} char const * name; Type value; }; //! A specialization of make_nvp<> that simply forwards the value for binary archives /*! @relates NameValuePair @internal */ template<class Archive, class T> inline typename std::enable_if<std::is_same<Archive, ::cereal::BinaryInputArchive>::value || std::is_same<Archive, ::cereal::BinaryOutputArchive>::value, T && >::type make_nvp( const char *, T && value ) { return std::forward<T>(value); } //! A specialization of make_nvp<> that actually creates an nvp for non-binary archives /*! @relates NameValuePair @internal */ template<class Archive, class T> inline typename std::enable_if<!std::is_same<Archive, ::cereal::BinaryInputArchive>::value && !std::is_same<Archive, ::cereal::BinaryOutputArchive>::value, NameValuePair<T> >::type make_nvp( const char * name, T && value) { return {name, std::forward<T>(value)}; } //! Convenience for creating a templated NVP /*! For use in inteneral generic typing functions which have an Archive type declared @internal */ #define _CEREAL_NVP(name, value) ::cereal::make_nvp<Archive>(name, value) // ###################################################################### //! A wrapper around data that can be serialized in a binary fashion /*! This class is used to demarcate data that can safely be serialized as a binary chunk of data. Individual archives can then choose how best represent this during serialization. @internal */ template <class T> struct BinaryData { //! Internally store the pointer as a void *, keeping const if created with //! a const pointer typedef typename std::conditional<std::is_const<typename std::remove_pointer<T>::type>::value, const void *, void *>::type PT; BinaryData( T && d, uint64_t s ) : data(d), size(s) {} PT data; //!< pointer to beginning of data uint64_t size; //!< size in bytes }; // ###################################################################### namespace detail { // base classes for type checking struct OutputArchiveBase {}; struct InputArchiveBase {}; // forward decls for polymorphic support template <class Archive, class T> struct polymorphic_serialization_support; struct adl_tag; // used during saving pointers static const int32_t msb_32bit = 0x80000000; static const int32_t msb2_32bit = 0x40000000; } // ###################################################################### //! A wrapper around size metadata /*! This class provides a way for archives to have more flexibility over how they choose to serialize size metadata for containers. For some archive types, the size may be implicitly encoded in the output (e.g. JSON) and not need an explicit entry. Specializing serialize or load/save for your archive and SizeTags allows you to choose what happens. @internal */ template <class T> class SizeTag { private: // If we get passed an RValue, we'll just make a local copy if it here // otherwise, we store a reference typedef typename std::decay<T>::type DT; typedef typename std::conditional<std::is_rvalue_reference<T>::value, DT, typename std::add_lvalue_reference<DT>::type>::type Type; public: SizeTag( T && sz ) : size(const_cast<Type>(sz)) {} Type size; }; // ###################################################################### //! A wrapper around a key and value for serializing data into maps. /*! This class just provides a grouping of keys and values into a struct for human readable archives. For example, XML archives will use this wrapper to write maps like so: @code{.xml} <mymap> <item0> <key>MyFirstKey</key> <value>MyFirstValue</value> </item0> <item1> <key>MySecondKey</key> <value>MySecondValue</value> </item1> </mymap> @endcode \sa make_map_item @internal */ template <class Key, class Value> struct MapItem { typedef typename std::decay<Key>::type DecayKey; typedef typename std::conditional< std::is_rvalue_reference<Key>::value, DecayKey, typename std::add_lvalue_reference<DecayKey>::type>::type KeyType; typedef typename std::decay<Value>::type DecayValue; typedef typename std::conditional< std::is_rvalue_reference<Value>::value, DecayValue, typename std::add_lvalue_reference<DecayValue>::type>::type ValueType; //! Construct a MapItem from a key and a value /*! @internal */ MapItem( Key && key, Value && value ) : key(const_cast<KeyType>(key)), value(const_cast<ValueType>(value)) {} KeyType key; ValueType value; //! Serialize the MapItem with the NVPs "key" and "value" template <class Archive> inline void serialize(Archive & archive) { archive( make_nvp<Archive>("key", key), make_nvp<Archive>("value", value) ); } }; //! Create a MapItem so that human readable archives will group keys and values together /*! @internal @relates MapItem */ template <class KeyType, class ValueType> inline MapItem<KeyType, ValueType> make_map_item(KeyType && key, ValueType && value) { return {std::forward<KeyType>(key), std::forward<ValueType>(value)}; } } // namespace cereal #endif // CEREAL_DETAILS_HELPERS_HPP_ <commit_msg>Fixes #27<commit_after>/*! \file helpers.hpp \brief Internal helper functionality \ingroup Internal */ /* Copyright (c) 2013, Randolph Voorhies, Shane Grant 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 cereal 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 RANDOLPH VOORHIES OR SHANE GRANT BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CEREAL_DETAILS_HELPERS_HPP_ #define CEREAL_DETAILS_HELPERS_HPP_ #include <type_traits> #include <cstdint> #include <utility> namespace cereal { //! The size type used by cereal /*! To ensure compatability between 32, 64, etc bit machines, we need to use * a fixed size type instead of size_t, which may vary from machine to * machine. */ typedef uint64_t size_type; // forward decls class BinaryOutputArchive; class BinaryInputArchive; // ###################################################################### namespace detail { struct NameValuePairCore {}; } //! For holding name value pairs /*! This pairs a name (some string) with some value such that an archive can potentially take advantage of the pairing. In serialization functions, NameValuePairs are usually created like so: @code{.cpp} struct MyStruct { int a, b, c, d, e; template<class Archive> void serialize(Archive & archive) { archive( CEREAL_NVP(a), CEREAL_NVP(b), CEREAL_NVP(c), CEREAL_NVP(d), CEREAL_NVP(e) ); } }; @endcode Alternatively, you can give you data members custom names like so: @code{.cpp} struct MyStruct { int a, b, my_embarrassing_variable_name, d, e; template<class Archive> void serialize(Archive & archive) { archive( CEREAL_NVP(a), CEREAL_NVP(b), cereal::make_nvp("var", my_embarrassing_variable_name) ); CEREAL_NVP(d), CEREAL_NVP(e) ); } }; @endcode There is a slight amount of overhead to creating NameValuePairs, so there is a third method which will elide the names when they are not needed by the Archive: @code{.cpp} struct MyStruct { int a, b; template<class Archive> void serialize(Archive & archive) { archive( cereal::make_nvp<Archive>(a), cereal::make_nvp<Archive>(b) ); } }; @endcode This third method is generally only used when providing generic type support. Users writing their own serialize functions will normally explicitly control whether they want to use NVPs or not. @internal */ template <class T> class NameValuePair : detail::NameValuePairCore { private: // If we get passed an RValue, we'll just make a local copy if it here // otherwise, we store a reference. If we were passed an array, don't // decay the type - keep it as an array, and then proceed as normal // with the RValue business typedef typename std::conditional<std::is_array<typename std::remove_reference<T>::type>::value, typename std::remove_cv<T>::type, typename std::decay<T>::type>::type DT; typedef typename std::conditional<std::is_rvalue_reference<T>::value, DT, typename std::add_lvalue_reference<DT>::type>::type Type; // prevent nested nvps static_assert( !std::is_base_of<detail::NameValuePairCore, T>::value, "Cannot pair a name to a NameValuePair" ); public: //! Constructs a new NameValuePair /*! @param n The name of the pair @param v The value to pair. Ideally this should be an l-value reference so that the value can be both loaded and saved to. If you pass an r-value reference, the NameValuePair will store a copy of it instead of a reference. Thus you should only pass r-values in cases where this makes sense, such as the result of some size() call. In either case, any constness will be stripped away @internal */ NameValuePair( char const * n, T && v ) : name(n), value(const_cast<Type>(v)) {} char const * name; Type value; }; //! A specialization of make_nvp<> that simply forwards the value for binary archives /*! @relates NameValuePair @internal */ template<class Archive, class T> inline typename std::enable_if<std::is_same<Archive, ::cereal::BinaryInputArchive>::value || std::is_same<Archive, ::cereal::BinaryOutputArchive>::value, T && >::type make_nvp( const char *, T && value ) { return std::forward<T>(value); } //! A specialization of make_nvp<> that actually creates an nvp for non-binary archives /*! @relates NameValuePair @internal */ template<class Archive, class T> inline typename std::enable_if<!std::is_same<Archive, ::cereal::BinaryInputArchive>::value && !std::is_same<Archive, ::cereal::BinaryOutputArchive>::value, NameValuePair<T> >::type make_nvp( const char * name, T && value) { return {name, std::forward<T>(value)}; } //! Convenience for creating a templated NVP /*! For use in inteneral generic typing functions which have an Archive type declared @internal */ #define _CEREAL_NVP(name, value) ::cereal::make_nvp<Archive>(name, value) // ###################################################################### //! A wrapper around data that can be serialized in a binary fashion /*! This class is used to demarcate data that can safely be serialized as a binary chunk of data. Individual archives can then choose how best represent this during serialization. @internal */ template <class T> struct BinaryData { //! Internally store the pointer as a void *, keeping const if created with //! a const pointer typedef typename std::conditional<std::is_const<typename std::remove_pointer<T>::type>::value, const void *, void *>::type PT; BinaryData( T && d, uint64_t s ) : data(d), size(s) {} PT data; //!< pointer to beginning of data uint64_t size; //!< size in bytes }; // ###################################################################### namespace detail { // base classes for type checking struct OutputArchiveBase {}; struct InputArchiveBase {}; // forward decls for polymorphic support template <class Archive, class T> struct polymorphic_serialization_support; struct adl_tag; // used during saving pointers static const int32_t msb_32bit = 0x80000000; static const int32_t msb2_32bit = 0x40000000; } // ###################################################################### //! A wrapper around size metadata /*! This class provides a way for archives to have more flexibility over how they choose to serialize size metadata for containers. For some archive types, the size may be implicitly encoded in the output (e.g. JSON) and not need an explicit entry. Specializing serialize or load/save for your archive and SizeTags allows you to choose what happens. @internal */ template <class T> class SizeTag { private: // If we get passed an RValue, we'll just make a local copy if it here // otherwise, we store a reference typedef typename std::decay<T>::type DT; typedef typename std::conditional<std::is_rvalue_reference<T>::value, DT, typename std::add_lvalue_reference<DT>::type>::type Type; public: SizeTag( T && sz ) : size(const_cast<Type>(sz)) {} Type size; }; // ###################################################################### //! A wrapper around a key and value for serializing data into maps. /*! This class just provides a grouping of keys and values into a struct for human readable archives. For example, XML archives will use this wrapper to write maps like so: @code{.xml} <mymap> <item0> <key>MyFirstKey</key> <value>MyFirstValue</value> </item0> <item1> <key>MySecondKey</key> <value>MySecondValue</value> </item1> </mymap> @endcode \sa make_map_item @internal */ template <class Key, class Value> struct MapItem { typedef typename std::decay<Key>::type DecayKey; typedef typename std::conditional< std::is_rvalue_reference<Key>::value, DecayKey, typename std::add_lvalue_reference<DecayKey>::type>::type KeyType; typedef typename std::decay<Value>::type DecayValue; typedef typename std::conditional< std::is_rvalue_reference<Value>::value, DecayValue, typename std::add_lvalue_reference<DecayValue>::type>::type ValueType; //! Construct a MapItem from a key and a value /*! @internal */ MapItem( Key && key, Value && value ) : key(const_cast<KeyType>(key)), value(const_cast<ValueType>(value)) {} KeyType key; ValueType value; //! Serialize the MapItem with the NVPs "key" and "value" template <class Archive> inline void serialize(Archive & archive) { archive( make_nvp<Archive>("key", key), make_nvp<Archive>("value", value) ); } }; //! Create a MapItem so that human readable archives will group keys and values together /*! @internal @relates MapItem */ template <class KeyType, class ValueType> inline MapItem<KeyType, ValueType> make_map_item(KeyType && key, ValueType && value) { return {std::forward<KeyType>(key), std::forward<ValueType>(value)}; } } // namespace cereal #endif // CEREAL_DETAILS_HELPERS_HPP_ <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file type_relations.cc * \brief A set of utilities and common functionality * for type relations. */ #include "./type_relations.h" #include <tvm/arith/analyzer.h> #include <tvm/relay/attrs/transform.h> #include <tvm/relay/expr.h> #include <tvm/relay/op.h> #include <tvm/tir/op.h> #include <numeric> namespace tvm { namespace relay { bool IdentityRel(const Array<Type>& types, int num_inputs, const Attrs& attrs, const TypeReporter& reporter) { for (size_t i = 1; i < types.size(); ++i) { reporter->Assign(types[i], types[0]); } return true; } bool EqualCheck(const IndexExpr& lhs, const IndexExpr& rhs) { IndexExpr diff = lhs - rhs; if (const int64_t* pdiff = tir::as_const_int(diff)) { return pdiff[0] == 0; } // symbolic tvm::arith::Analyzer ana; diff = ana.Simplify(diff); if (const int64_t* pdiff = tir::as_const_int(diff)) { return pdiff[0] == 0; } return false; } bool EqualConstInt(const IndexExpr& lhs, int64_t value) { if (const int64_t* pvalue = tir::as_const_int(lhs)) { return pvalue[0] == value; } return false; } TensorType ConcreteBroadcast(const TensorType& t1, const TensorType& t2, DataType output_dtype) { std::vector<IndexExpr> oshape; size_t ndim1 = t1->shape.size(); size_t ndim2 = t2->shape.size(); size_t i = 1; for (; i <= std::min(ndim1, ndim2); ++i) { IndexExpr s1 = t1->shape[ndim1 - i]; IndexExpr s2 = t2->shape[ndim2 - i]; if (EqualConstInt(s1, 1)) { oshape.push_back(s2); } else if (EqualConstInt(s2, 1)) { oshape.push_back(s1); } else if (s1.as<AnyNode>()) { // s1 == 1 || s1 == s2 oshape.push_back(s2); } else if (s2.as<AnyNode>()) { // s2 == 1 || s2 == s1 oshape.push_back(s1); } else if (EqualCheck(s1, s2)) { oshape.push_back(s1); } else { throw CompileError(ErrorBuilder() << "Incompatible broadcast type " << t1 << " and " << t2); } } size_t max_ndim = std::max(ndim1, ndim2); auto& rshape = (ndim1 > ndim2) ? t1->shape : t2->shape; for (; i <= max_ndim; ++i) { oshape.push_back(rshape[max_ndim - i]); } return TensorType(Array<IndexExpr>(oshape.rbegin(), oshape.rend()), output_dtype); } bool BroadcastRel(const Array<Type>& types, int num_inputs, const Attrs& attrs, const TypeReporter& reporter) { ICHECK_EQ(types.size(), 3); // DLOG(INFO) << "In1:" << types[0] << ",In2:" << types[1] // << ",Out:" << types[2] << std::endl; if (auto* t0 = types[0].as<TensorTypeNode>()) { if (auto* t1 = types[1].as<TensorTypeNode>()) { if (t0->dtype != t1->dtype) { reporter->GetDiagCtx().Emit(Diagnostic::Error(t0->span) << "data types " << t0->dtype << " and " << t1->dtype << "do not match in BroadcastRel"); } reporter->Assign( types[2], ConcreteBroadcast(GetRef<TensorType>(t0), GetRef<TensorType>(t1), t0->dtype)); return true; } } return false; } bool BroadcastCompRel(const Array<Type>& types, int num_inputs, const Attrs& attrs, const TypeReporter& reporter) { ICHECK_EQ(types.size(), 3); // DLOG(INFO) << "In1:" << types[0] << ",In2:" << types[1] // << ",Out:" << types[2] << std::endl; if (auto* t0 = types[0].as<TensorTypeNode>()) { if (auto* t1 = types[1].as<TensorTypeNode>()) { if (t0->dtype != t1->dtype) { reporter->GetDiagCtx().Emit(Diagnostic::Error(t0->span) << "data types " << t0->dtype << " and " << t1->dtype << "do not match in BroadcastCompRel"); } reporter->Assign(types[2], ConcreteBroadcast(GetRef<TensorType>(t0), GetRef<TensorType>(t1), DataType::Bool())); return true; } } return false; } bool IdentityCompRel(const Array<Type>& types, int num_inputs, const Attrs& attrs, const TypeReporter& reporter) { if (auto* t0 = types[0].as<TensorTypeNode>()) { Type out_type = TensorType(GetRef<TensorType>(t0)->shape, DataType::Bool()); reporter->Assign(types[1], out_type); return true; } return false; } Array<IndexExpr> RankShape(const Array<IndexExpr>& shape) { if (shape.size() == 0) { return {}; } else { return {tvm::Integer(shape.size())}; } } bool ShapeOfRel(const Array<Type>& types, int num_inputs, const Attrs& attrs, const TypeReporter& reporter) { ICHECK_EQ(num_inputs, 1); auto tt = types[0].as<TensorTypeNode>(); if (tt == nullptr) { return false; } const auto* param = attrs.as<ShapeOfAttrs>(); ICHECK(param != nullptr); auto rank_shape = RankShape(tt->shape); reporter->Assign(types[1], TensorType(rank_shape, param->dtype)); return true; } } // namespace relay } // namespace tvm <commit_msg>Add one extra space to improve diagnostic messages (#10268)<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file type_relations.cc * \brief A set of utilities and common functionality * for type relations. */ #include "./type_relations.h" #include <tvm/arith/analyzer.h> #include <tvm/relay/attrs/transform.h> #include <tvm/relay/expr.h> #include <tvm/relay/op.h> #include <tvm/tir/op.h> #include <numeric> namespace tvm { namespace relay { bool IdentityRel(const Array<Type>& types, int num_inputs, const Attrs& attrs, const TypeReporter& reporter) { for (size_t i = 1; i < types.size(); ++i) { reporter->Assign(types[i], types[0]); } return true; } bool EqualCheck(const IndexExpr& lhs, const IndexExpr& rhs) { IndexExpr diff = lhs - rhs; if (const int64_t* pdiff = tir::as_const_int(diff)) { return pdiff[0] == 0; } // symbolic tvm::arith::Analyzer ana; diff = ana.Simplify(diff); if (const int64_t* pdiff = tir::as_const_int(diff)) { return pdiff[0] == 0; } return false; } bool EqualConstInt(const IndexExpr& lhs, int64_t value) { if (const int64_t* pvalue = tir::as_const_int(lhs)) { return pvalue[0] == value; } return false; } TensorType ConcreteBroadcast(const TensorType& t1, const TensorType& t2, DataType output_dtype) { std::vector<IndexExpr> oshape; size_t ndim1 = t1->shape.size(); size_t ndim2 = t2->shape.size(); size_t i = 1; for (; i <= std::min(ndim1, ndim2); ++i) { IndexExpr s1 = t1->shape[ndim1 - i]; IndexExpr s2 = t2->shape[ndim2 - i]; if (EqualConstInt(s1, 1)) { oshape.push_back(s2); } else if (EqualConstInt(s2, 1)) { oshape.push_back(s1); } else if (s1.as<AnyNode>()) { // s1 == 1 || s1 == s2 oshape.push_back(s2); } else if (s2.as<AnyNode>()) { // s2 == 1 || s2 == s1 oshape.push_back(s1); } else if (EqualCheck(s1, s2)) { oshape.push_back(s1); } else { throw CompileError(ErrorBuilder() << "Incompatible broadcast type " << t1 << " and " << t2); } } size_t max_ndim = std::max(ndim1, ndim2); auto& rshape = (ndim1 > ndim2) ? t1->shape : t2->shape; for (; i <= max_ndim; ++i) { oshape.push_back(rshape[max_ndim - i]); } return TensorType(Array<IndexExpr>(oshape.rbegin(), oshape.rend()), output_dtype); } bool BroadcastRel(const Array<Type>& types, int num_inputs, const Attrs& attrs, const TypeReporter& reporter) { ICHECK_EQ(types.size(), 3); // DLOG(INFO) << "In1:" << types[0] << ",In2:" << types[1] // << ",Out:" << types[2] << std::endl; if (auto* t0 = types[0].as<TensorTypeNode>()) { if (auto* t1 = types[1].as<TensorTypeNode>()) { if (t0->dtype != t1->dtype) { reporter->GetDiagCtx().Emit(Diagnostic::Error(t0->span) << "data types " << t0->dtype << " and " << t1->dtype << " do not match in BroadcastRel"); } reporter->Assign( types[2], ConcreteBroadcast(GetRef<TensorType>(t0), GetRef<TensorType>(t1), t0->dtype)); return true; } } return false; } bool BroadcastCompRel(const Array<Type>& types, int num_inputs, const Attrs& attrs, const TypeReporter& reporter) { ICHECK_EQ(types.size(), 3); // DLOG(INFO) << "In1:" << types[0] << ",In2:" << types[1] // << ",Out:" << types[2] << std::endl; if (auto* t0 = types[0].as<TensorTypeNode>()) { if (auto* t1 = types[1].as<TensorTypeNode>()) { if (t0->dtype != t1->dtype) { reporter->GetDiagCtx().Emit(Diagnostic::Error(t0->span) << "data types " << t0->dtype << " and " << t1->dtype << " do not match in BroadcastCompRel"); } reporter->Assign(types[2], ConcreteBroadcast(GetRef<TensorType>(t0), GetRef<TensorType>(t1), DataType::Bool())); return true; } } return false; } bool IdentityCompRel(const Array<Type>& types, int num_inputs, const Attrs& attrs, const TypeReporter& reporter) { if (auto* t0 = types[0].as<TensorTypeNode>()) { Type out_type = TensorType(GetRef<TensorType>(t0)->shape, DataType::Bool()); reporter->Assign(types[1], out_type); return true; } return false; } Array<IndexExpr> RankShape(const Array<IndexExpr>& shape) { if (shape.size() == 0) { return {}; } else { return {tvm::Integer(shape.size())}; } } bool ShapeOfRel(const Array<Type>& types, int num_inputs, const Attrs& attrs, const TypeReporter& reporter) { ICHECK_EQ(num_inputs, 1); auto tt = types[0].as<TensorTypeNode>(); if (tt == nullptr) { return false; } const auto* param = attrs.as<ShapeOfAttrs>(); ICHECK(param != nullptr); auto rank_shape = RankShape(tt->shape); reporter->Assign(types[1], TensorType(rank_shape, param->dtype)); return true; } } // namespace relay } // namespace tvm <|endoftext|>
<commit_before>// Copyright 2016 Google Inc. All rights reserved // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // +build ignore // This command will dump the contents of a kati stamp file into a more portable // format for use by other tools. For now, it just exports the files read. // Later, this will be expanded to include the Glob and Shell commands, but // those require a more complicated output format. #include <stdio.h> #include <string> #include "io.h" #include "log.h" #include "strutil.h" int main(int argc, char* argv[]) { if (argc == 1) { fprintf(stderr, "Usage: ckati_stamp_dump <stamp>\n"); return 1; } FILE *fp = fopen(argv[1], "rb"); if(!fp) PERROR("fopen"); ScopedFile sfp(fp); double gen_time; size_t r = fread(&gen_time, sizeof(gen_time), 1, fp); if (r != 1) ERROR("Incomplete stamp file"); int num_files = LoadInt(fp); if (num_files < 0) ERROR("Incomplete stamp file"); for (int i = 0; i < num_files; i++) { string s; if (!LoadString(fp, s)) ERROR("Incomplete stamp file"); printf("%s\n", s.c_str()); } return 0; } <commit_msg>Fix typo in regen_dump.cc<commit_after>// Copyright 2016 Google Inc. All rights reserved // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // +build ignore // This command will dump the contents of a kati stamp file into a more portable // format for use by other tools. For now, it just exports the files read. // Later, this will be expanded to include the Glob and Shell commands, but // those require a more complicated output format. #include <stdio.h> #include <string> #include "io.h" #include "log.h" #include "strutil.h" int main(int argc, char* argv[]) { if (argc == 1) { fprintf(stderr, "Usage: ckati_stamp_dump <stamp>\n"); return 1; } FILE *fp = fopen(argv[1], "rb"); if(!fp) PERROR("fopen"); ScopedFile sfp(fp); double gen_time; size_t r = fread(&gen_time, sizeof(gen_time), 1, fp); if (r != 1) ERROR("Incomplete stamp file"); int num_files = LoadInt(fp); if (num_files < 0) ERROR("Incomplete stamp file"); for (int i = 0; i < num_files; i++) { string s; if (!LoadString(fp, &s)) ERROR("Incomplete stamp file"); printf("%s\n", s.c_str()); } return 0; } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2014 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_ICU_SHAPER_HPP #define MAPNIK_ICU_SHAPER_HPP // mapnik #include <mapnik/text/text_properties.hpp> #include <mapnik/text/text_line.hpp> #include <mapnik/text/face.hpp> #include <mapnik/debug.hpp> // stl #include <list> // icu #include <unicode/unistr.h> #include <unicode/ushape.h> #include <unicode/schriter.h> namespace mapnik { struct icu_shaper { static void shape_text(text_line & line, text_itemizer & itemizer, std::map<unsigned,double> & width_map, face_manager_freetype & font_manager, double scale_factor ) { unsigned start = line.first_char(); unsigned end = line.last_char(); size_t length = end - start; if (!length) return; line.reserve(length); std::list<text_item> const& list = itemizer.itemize(start, end); mapnik::value_unicode_string const& text = itemizer.text(); UErrorCode err = U_ZERO_ERROR; mapnik::value_unicode_string shaped; mapnik::value_unicode_string reordered; unsigned char_index = 0; for (auto const& text_item : list) { face_set_ptr face_set = font_manager.get_face_set(text_item.format->face_name, text_item.format->fontset); double size = text_item.format->text_size * scale_factor; face_set->set_unscaled_character_sizes(); for (auto const& face : *face_set) { UBiDi *bidi = ubidi_openSized(length, 0, &err); ubidi_setPara(bidi, text.getBuffer() + start, length, UBIDI_DEFAULT_LTR, 0, &err); ubidi_writeReordered(bidi, reordered.getBuffer(length), length, UBIDI_DO_MIRRORING, &err); ubidi_close(bidi); reordered.releaseBuffer(length); int32_t num_char = u_shapeArabic(reordered.getBuffer(), length, shaped.getBuffer(length), length, U_SHAPE_LETTERS_SHAPE | U_SHAPE_LENGTH_FIXED_SPACES_NEAR | U_SHAPE_TEXT_DIRECTION_VISUAL_LTR, &err); if (num_char < 0) { MAPNIK_LOG_ERROR(icu_shaper) << " u_shapeArabic returned negative num_char " << num_char; } std::size_t num_chars = static_cast<std::size_t>(num_char); shaped.releaseBuffer(length); bool shaped_status = true; if (U_SUCCESS(err) && (num_chars == length)) { U_NAMESPACE_QUALIFIER StringCharacterIterator iter(shaped); for (iter.setToStart(); iter.hasNext();) { UChar ch = iter.nextPostInc(); glyph_info tmp; tmp.glyph_index = FT_Get_Char_Index(face->get_face(), ch); tmp.offset.clear(); if (tmp.glyph_index == 0) { shaped_status = false; break; } if (face->glyph_dimensions(tmp)) { tmp.char_index = char_index; tmp.face = face; tmp.format = text_item.format; tmp.scale_multiplier = size / face->get_face()->units_per_EM; width_map[char_index++] += tmp.advance(); line.add_glyph(tmp, scale_factor); } } } if (!shaped_status) continue; line.update_max_char_height(face->get_char_height(size)); return; } } } }; } //namespace mapnik #endif // MAPNIK_ICU_SHAPER_HPP <commit_msg>itemizer should be const in icu_shaper<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2014 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_ICU_SHAPER_HPP #define MAPNIK_ICU_SHAPER_HPP // mapnik #include <mapnik/text/text_properties.hpp> #include <mapnik/text/text_line.hpp> #include <mapnik/text/face.hpp> #include <mapnik/debug.hpp> // stl #include <list> // icu #include <unicode/unistr.h> #include <unicode/ushape.h> #include <unicode/schriter.h> namespace mapnik { struct icu_shaper { static void shape_text(text_line & line, text_itemizer const& itemizer, std::map<unsigned,double> & width_map, face_manager_freetype & font_manager, double scale_factor ) { unsigned start = line.first_char(); unsigned end = line.last_char(); size_t length = end - start; if (!length) return; line.reserve(length); std::list<text_item> const& list = itemizer.itemize(start, end); mapnik::value_unicode_string const& text = itemizer.text(); UErrorCode err = U_ZERO_ERROR; mapnik::value_unicode_string shaped; mapnik::value_unicode_string reordered; unsigned char_index = 0; for (auto const& text_item : list) { face_set_ptr face_set = font_manager.get_face_set(text_item.format->face_name, text_item.format->fontset); double size = text_item.format->text_size * scale_factor; face_set->set_unscaled_character_sizes(); for (auto const& face : *face_set) { UBiDi *bidi = ubidi_openSized(length, 0, &err); ubidi_setPara(bidi, text.getBuffer() + start, length, UBIDI_DEFAULT_LTR, 0, &err); ubidi_writeReordered(bidi, reordered.getBuffer(length), length, UBIDI_DO_MIRRORING, &err); ubidi_close(bidi); reordered.releaseBuffer(length); int32_t num_char = u_shapeArabic(reordered.getBuffer(), length, shaped.getBuffer(length), length, U_SHAPE_LETTERS_SHAPE | U_SHAPE_LENGTH_FIXED_SPACES_NEAR | U_SHAPE_TEXT_DIRECTION_VISUAL_LTR, &err); if (num_char < 0) { MAPNIK_LOG_ERROR(icu_shaper) << " u_shapeArabic returned negative num_char " << num_char; } std::size_t num_chars = static_cast<std::size_t>(num_char); shaped.releaseBuffer(length); bool shaped_status = true; if (U_SUCCESS(err) && (num_chars == length)) { U_NAMESPACE_QUALIFIER StringCharacterIterator iter(shaped); for (iter.setToStart(); iter.hasNext();) { UChar ch = iter.nextPostInc(); glyph_info tmp; tmp.glyph_index = FT_Get_Char_Index(face->get_face(), ch); tmp.offset.clear(); if (tmp.glyph_index == 0) { shaped_status = false; break; } if (face->glyph_dimensions(tmp)) { tmp.char_index = char_index; tmp.face = face; tmp.format = text_item.format; tmp.scale_multiplier = size / face->get_face()->units_per_EM; width_map[char_index++] += tmp.advance(); line.add_glyph(tmp, scale_factor); } } } if (!shaped_status) continue; line.update_max_char_height(face->get_char_height(size)); return; } } } }; } //namespace mapnik #endif // MAPNIK_ICU_SHAPER_HPP <|endoftext|>
<commit_before>#pragma once #include "dedisp.h" #include <cstdlib> #include <vector> #include <string> #include <cstring> #include <sstream> #include <stdexcept> #include <data_types/timeseries.hpp> #include <data_types/filterbank.hpp> #include <utils/exceptions.hpp> class Dedisperser { private: dedisp_plan plan; Filterbank& filterbank; unsigned int num_gpus; std::vector<float> dm_list; std::vector<dedisp_bool> killmask; public: Dedisperser(Filterbank& filterbank, unsigned int num_gpus=1) :filterbank(filterbank), num_gpus(num_gpus) { killmask.resize(filterbank.get_nchans(),1); dedisp_error error = dedisp_create_plan_multi(&plan, filterbank.get_nchans(), filterbank.get_tsamp(), filterbank.get_fch1(), filterbank.get_foff(), num_gpus); ErrorChecker::check_dedisp_error(error,"create_plan_multi"); } virtual ~Dedisperser() { if( plan ) { dedisp_destroy_plan(plan); } } void set_dm_list(float* dm_list_ptr, unsigned int ndms) { dm_list.resize(ndms); std::copy(dm_list_ptr, dm_list_ptr+ndms, dm_list.begin()); dedisp_error error = dedisp_set_dm_list(plan,&dm_list[0],dm_list.size()); ErrorChecker::check_dedisp_error(error,"set_dm_list"); } void set_dm_list(std::vector<float> dm_list_vec) { dm_list.resize(dm_list_vec.size()); std::copy(dm_list_vec.begin(), dm_list_vec.end(), dm_list.begin()); dedisp_error error = dedisp_set_dm_list(plan,&dm_list[0],dm_list.size()); ErrorChecker::check_dedisp_error(error,"set_dm_list"); } std::vector<float> get_dm_list(void){ return dm_list; } void generate_dm_list(float dm_start, float dm_end, float width, float tolerance) { dedisp_error error = dedisp_generate_dm_list(plan, dm_start, dm_end, width, tolerance); ErrorChecker::check_dedisp_error(error,"generate_dm_list"); dm_list.resize(dedisp_get_dm_count(plan)); const float* plan_dm_list = dedisp_get_dm_list(plan); std::copy(plan_dm_list,plan_dm_list+dm_list.size(),dm_list.begin()); } void set_killmask(std::vector<int> killmask_in) { killmask.swap(killmask_in); dedisp_error error = dedisp_set_killmask(plan,&killmask[0]); ErrorChecker::check_dedisp_error(error,"set_killmask"); } void set_killmask(std::string filename) { std::ifstream infile; std::string str; killmask.clear(); infile.open(filename.c_str(),std::ifstream::in | std::ifstream::binary); ErrorChecker::check_file_error(infile,filename); int ii=0; while(!infile.eof()&&ii<filterbank.get_nchans()){ std::getline(infile, str); killmask.push_back(std::atoi(str.c_str())); ii++; } if (killmask.size() != filterbank.get_nchans()){ std::cerr << "WARNING: killmask is not the same size as nchans" << std::endl; std::cerr << killmask.size() <<" != " << filterbank.get_nchans() << std::endl; killmask.resize(filterbank.get_nchans(),1); } else { dedisp_error error = dedisp_set_killmask(plan,&killmask[0]); ErrorChecker::check_dedisp_error(error,"set_killmask"); } } void dedisperse(DispersionTrials<float>& trials, std::size_t start_sample, std::size_t nsamps, std::size_t gulp) { std::vector<float> temp_buffer; std::size_t max_delay = dedisp_get_max_delay(plan); std::cout << "Max DM delay: " << max_delay << std::endl; if (gulp < 2 * max_delay) { gulp = 2 * max_delay; std::cerr << "WARNING: Gulp size < 2 x maximum DM delay, adjusting gulp size to " << gulp << " bytes"<< std::endl; } if ((start_sample + nsamps) > filterbank.get_nsamps()) { nsamps = filterbank.get_nsamps() - start_sample; std::cerr << "WARNING: Number of sample requested exceeds input filterbank length " << "revising to " << nsamps << " samples" << std::endl; } // Calculated the total number of output samples expected std::size_t total_out_nsamps = nsamps - max_delay; std::cout << "Total Dedisp output samples: " << total_out_nsamps << std::endl; // Create a complete trials object to contain all trials at full length //std::cout << "DM list size " << dm_list.size() << std::endl; //std::cout << "Trials pre size " << trials.get_data().size() << std::endl; //std::cout << "Count " << trials.get_count() << " nsamps " << trials.get_nsamps() << std::endl; trials.resize(total_out_nsamps, dm_list); //std::cout << "Trials post size " << trials.get_data().size() << std::endl; //std::cout << "Count " << trials.get_count() << " nsamps " << trials.get_nsamps() << std::endl; while (start_sample < total_out_nsamps) { std::cout << "Dedispersing samples " << start_sample << " to " << start_sample + gulp << " of " << total_out_nsamps << std::endl; // Load a block of data from the filterbank std::size_t loaded_samples = filterbank.load_gulp(start_sample, gulp); // Calculate the expected number of output samples from a dedisp call std::size_t dedisp_samples = loaded_samples - max_delay; //std::cout << "Dedisp output samples from block: " << dedisp_samples << std::endl; // Calculate the actual number of samples to memcpy std::size_t nsamps_to_copy; if (dedisp_samples + start_sample > total_out_nsamps){ nsamps_to_copy = total_out_nsamps - start_sample; } else { nsamps_to_copy = dedisp_samples; } // Resize the temporary buffer to handle the output of the next dedisp call temp_buffer.resize(gulp * dm_list.size()); // Run Dedisp with output into the temporary buffer //std::cout << "Calling Dedisp" << std::endl; dedisp_error error = dedisp_execute(plan, loaded_samples, filterbank.get_data(), //This pointer gets set in the filterband.load_gulp method filterbank.get_nbits(), reinterpret_cast<unsigned char*>(temp_buffer.data()), 32, // Float output (unsigned) 0); ErrorChecker::check_dedisp_error(error,"execute"); // Get a pointer to the final trials data std::vector<float> const& data = trials.get_data(); std::cout << "Trials total size: " << data.size() * sizeof(float) << " bytes" << std::endl; float* ptr = reinterpret_cast<float*>(trials.get_data_ptr()); // Loop over the trials and for each take the data from the temporary buffer // and memcpy it into the correct location in the final trials object std::cout << "Performing transpose/merge of Dedisp output samples" << std::endl; for (std::size_t trial_idx = 0; trial_idx < dm_list.size(); ++trial_idx) { // Calculate destination offset for trails pointer //std::cout << "Trial IDx " << trial_idx << std::endl; std::size_t offset = total_out_nsamps * trial_idx + start_sample; //std::cout << "Offset " << offset << std::endl; //std::cout << "Temp offset " << dedisp_samples * trial_idx << std::endl; //std::cout << "Trials size " << trials.get_data().size() << std::endl; //std::cout << "Temp size " << temp_buffer.size() << std::endl; //std::cout << "nsamps to copy " << nsamps_to_copy << std::endl; //std::cout << "Dest offset: " << offset * sizeof(float) // << " size: " << sizeof(float) * trials.get_count() * trials.get_nsamps() // << " remaining: " << sizeof(float) * trials.get_count() * trials.get_nsamps() - offset * sizeof(float) // << " to_copy: " << sizeof(float) * nsamps_to_copy << std::endl; std::memcpy( reinterpret_cast<char*>(ptr + offset), reinterpret_cast<char*>(temp_buffer.data() + dedisp_samples * trial_idx), sizeof(float) * nsamps_to_copy); } // Update the start_sample based on the number of samples output by dedisp start_sample += dedisp_samples; //std::cout << "Updating start sample to " << start_sample << std::endl; } } }; <commit_msg>fixed zero read size loop bug<commit_after>#pragma once #include "dedisp.h" #include <cstdlib> #include <vector> #include <string> #include <cstring> #include <sstream> #include <stdexcept> #include <data_types/timeseries.hpp> #include <data_types/filterbank.hpp> #include <utils/exceptions.hpp> class Dedisperser { private: dedisp_plan plan; Filterbank& filterbank; unsigned int num_gpus; std::vector<float> dm_list; std::vector<dedisp_bool> killmask; public: Dedisperser(Filterbank& filterbank, unsigned int num_gpus=1) :filterbank(filterbank), num_gpus(num_gpus) { killmask.resize(filterbank.get_nchans(),1); dedisp_error error = dedisp_create_plan_multi(&plan, filterbank.get_nchans(), filterbank.get_tsamp(), filterbank.get_fch1(), filterbank.get_foff(), num_gpus); ErrorChecker::check_dedisp_error(error,"create_plan_multi"); } virtual ~Dedisperser() { if( plan ) { dedisp_destroy_plan(plan); } } void set_dm_list(float* dm_list_ptr, unsigned int ndms) { dm_list.resize(ndms); std::copy(dm_list_ptr, dm_list_ptr+ndms, dm_list.begin()); dedisp_error error = dedisp_set_dm_list(plan,&dm_list[0],dm_list.size()); ErrorChecker::check_dedisp_error(error,"set_dm_list"); } void set_dm_list(std::vector<float> dm_list_vec) { dm_list.resize(dm_list_vec.size()); std::copy(dm_list_vec.begin(), dm_list_vec.end(), dm_list.begin()); dedisp_error error = dedisp_set_dm_list(plan,&dm_list[0],dm_list.size()); ErrorChecker::check_dedisp_error(error,"set_dm_list"); } std::vector<float> get_dm_list(void){ return dm_list; } void generate_dm_list(float dm_start, float dm_end, float width, float tolerance) { dedisp_error error = dedisp_generate_dm_list(plan, dm_start, dm_end, width, tolerance); ErrorChecker::check_dedisp_error(error,"generate_dm_list"); dm_list.resize(dedisp_get_dm_count(plan)); const float* plan_dm_list = dedisp_get_dm_list(plan); std::copy(plan_dm_list,plan_dm_list+dm_list.size(),dm_list.begin()); } void set_killmask(std::vector<int> killmask_in) { killmask.swap(killmask_in); dedisp_error error = dedisp_set_killmask(plan,&killmask[0]); ErrorChecker::check_dedisp_error(error,"set_killmask"); } void set_killmask(std::string filename) { std::ifstream infile; std::string str; killmask.clear(); infile.open(filename.c_str(),std::ifstream::in | std::ifstream::binary); ErrorChecker::check_file_error(infile,filename); int ii=0; while(!infile.eof()&&ii<filterbank.get_nchans()){ std::getline(infile, str); killmask.push_back(std::atoi(str.c_str())); ii++; } if (killmask.size() != filterbank.get_nchans()){ std::cerr << "WARNING: killmask is not the same size as nchans" << std::endl; std::cerr << killmask.size() <<" != " << filterbank.get_nchans() << std::endl; killmask.resize(filterbank.get_nchans(),1); } else { dedisp_error error = dedisp_set_killmask(plan,&killmask[0]); ErrorChecker::check_dedisp_error(error,"set_killmask"); } } void dedisperse(DispersionTrials<float>& trials, std::size_t start_sample, std::size_t nsamps, std::size_t gulp) { std::vector<float> temp_buffer; std::size_t max_delay = dedisp_get_max_delay(plan); std::cout << "Max DM delay: " << max_delay << std::endl; if (gulp < 2 * max_delay) { gulp = 2 * max_delay; std::cerr << "WARNING: Gulp size < 2 x maximum DM delay, adjusting gulp size to " << gulp << " bytes"<< std::endl; } if ((start_sample + nsamps) > filterbank.get_nsamps()) { nsamps = filterbank.get_nsamps() - start_sample; std::cerr << "WARNING: Number of sample requested exceeds input filterbank length " << "revising to " << nsamps << " samples" << std::endl; } // Calculated the total number of output samples expected std::size_t total_out_nsamps = nsamps - max_delay; std::cout << "Total Dedisp output samples: " << total_out_nsamps << std::endl; // Create a complete trials object to contain all trials at full length //std::cout << "DM list size " << dm_list.size() << std::endl; //std::cout << "Trials pre size " << trials.get_data().size() << std::endl; //std::cout << "Count " << trials.get_count() << " nsamps " << trials.get_nsamps() << std::endl; trials.resize(total_out_nsamps, dm_list); //std::cout << "Trials post size " << trials.get_data().size() << std::endl; //std::cout << "Count " << trials.get_count() << " nsamps " << trials.get_nsamps() << std::endl; while (start_sample < total_out_nsamps) { std::cout << "Dedispersing samples " << start_sample << " to " << start_sample + gulp << " of " << total_out_nsamps << std::endl; // Load a block of data from the filterbank std::size_t loaded_samples = filterbank.load_gulp(start_sample, gulp); if (loaded_samples == 0) { throw std::runtime_error("Failure on reading data during dedispersion, 0 bytes read."); } // Calculate the expected number of output samples from a dedisp call std::size_t dedisp_samples = loaded_samples - max_delay; //std::cout << "Dedisp output samples from block: " << dedisp_samples << std::endl; // Calculate the actual number of samples to memcpy std::size_t nsamps_to_copy; if (dedisp_samples + start_sample > total_out_nsamps){ nsamps_to_copy = total_out_nsamps - start_sample; } else { nsamps_to_copy = dedisp_samples; } // Resize the temporary buffer to handle the output of the next dedisp call temp_buffer.resize(gulp * dm_list.size()); // Run Dedisp with output into the temporary buffer //std::cout << "Calling Dedisp" << std::endl; dedisp_error error = dedisp_execute(plan, loaded_samples, filterbank.get_data(), //This pointer gets set in the filterband.load_gulp method filterbank.get_nbits(), reinterpret_cast<unsigned char*>(temp_buffer.data()), 32, // Float output (unsigned) 0); ErrorChecker::check_dedisp_error(error,"execute"); // Get a pointer to the final trials data std::vector<float> const& data = trials.get_data(); std::cout << "Trials total size: " << data.size() * sizeof(float) << " bytes" << std::endl; float* ptr = reinterpret_cast<float*>(trials.get_data_ptr()); // Loop over the trials and for each take the data from the temporary buffer // and memcpy it into the correct location in the final trials object std::cout << "Performing transpose/merge of Dedisp output samples" << std::endl; for (std::size_t trial_idx = 0; trial_idx < dm_list.size(); ++trial_idx) { // Calculate destination offset for trails pointer //std::cout << "Trial IDx " << trial_idx << std::endl; std::size_t offset = total_out_nsamps * trial_idx + start_sample; //std::cout << "Offset " << offset << std::endl; //std::cout << "Temp offset " << dedisp_samples * trial_idx << std::endl; //std::cout << "Trials size " << trials.get_data().size() << std::endl; //std::cout << "Temp size " << temp_buffer.size() << std::endl; //std::cout << "nsamps to copy " << nsamps_to_copy << std::endl; //std::cout << "Dest offset: " << offset * sizeof(float) // << " size: " << sizeof(float) * trials.get_count() * trials.get_nsamps() // << " remaining: " << sizeof(float) * trials.get_count() * trials.get_nsamps() - offset * sizeof(float) // << " to_copy: " << sizeof(float) * nsamps_to_copy << std::endl; std::memcpy( reinterpret_cast<char*>(ptr + offset), reinterpret_cast<char*>(temp_buffer.data() + dedisp_samples * trial_idx), sizeof(float) * nsamps_to_copy); } // Update the start_sample based on the number of samples output by dedisp start_sample += dedisp_samples; //std::cout << "Updating start sample to " << start_sample << std::endl; } } }; <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (c) 2016, Johan Mabille and Sylvain Corlay * * * * Distributed under the terms of the BSD 3-Clause License. * * * * The full license is in the file LICENSE, distributed with this software. * ****************************************************************************/ #ifndef XTENSOR_CONFIG_HPP #define XTENSOR_CONFIG_HPP #define XTENSOR_VERSION_MAJOR 0 #define XTENSOR_VERSION_MINOR 8 #define XTENSOR_VERSION_PATCH 4 // DETECT 3.6 <= clang < 3.8 for compiler bug workaround. #ifdef __clang__ #if __clang_major__ == 3 && __clang_minor__ < 8 #define X_OLD_CLANG #include <initializer_list> #include <vector> #endif #endif #ifndef DEFAULT_DATA_CONTAINER #define DEFAULT_DATA_CONTAINER(T, A) uvector<T, A> #endif #ifndef DEFAULT_SHAPE_CONTAINER #define DEFAULT_SHAPE_CONTAINER(T, EA, SA) \ std::vector<typename DEFAULT_DATA_CONTAINER(T, EA)::size_type, SA> #endif #ifndef DEFAULT_LAYOUT #define DEFAULT_LAYOUT layout_type::row_major #endif #endif <commit_msg>Release 0.9.0<commit_after>/*************************************************************************** * Copyright (c) 2016, Johan Mabille and Sylvain Corlay * * * * Distributed under the terms of the BSD 3-Clause License. * * * * The full license is in the file LICENSE, distributed with this software. * ****************************************************************************/ #ifndef XTENSOR_CONFIG_HPP #define XTENSOR_CONFIG_HPP #define XTENSOR_VERSION_MAJOR 0 #define XTENSOR_VERSION_MINOR 9 #define XTENSOR_VERSION_PATCH 0 // DETECT 3.6 <= clang < 3.8 for compiler bug workaround. #ifdef __clang__ #if __clang_major__ == 3 && __clang_minor__ < 8 #define X_OLD_CLANG #include <initializer_list> #include <vector> #endif #endif #ifndef DEFAULT_DATA_CONTAINER #define DEFAULT_DATA_CONTAINER(T, A) uvector<T, A> #endif #ifndef DEFAULT_SHAPE_CONTAINER #define DEFAULT_SHAPE_CONTAINER(T, EA, SA) \ std::vector<typename DEFAULT_DATA_CONTAINER(T, EA)::size_type, SA> #endif #ifndef DEFAULT_LAYOUT #define DEFAULT_LAYOUT layout_type::row_major #endif #endif <|endoftext|>
<commit_before>#include "triangular.hpp" #include "../segments/types.hpp" #include "../vertices/types.hpp" //////////////////////////// // Triangle, cartesian 2D // //////////////////////////// unsigned int TriangularCartesian2D_Domain::num_vertices() { TriangularCartesian2D_VertexRange_t vertex_range = viennagrid::elements<viennagrid::vertex_tag>(domain); return vertex_range.size(); } void TriangularCartesian2D_Domain::add_vertex(PointCartesian2D vertex) { viennagrid::create_element<TriangularCartesian2D_Vertex_t>(domain, vertex.get_point()); } TriangularCartesian2D_Domain_t & TriangularCartesian2D_Domain::get_domain() { return domain; } PointCartesian2D TriangularCartesian2D_Domain::get_vertex(unsigned int index) { // TODO: domain.find_by_id(index); TriangularCartesian2D_VertexRange_t vertices = viennagrid::elements<viennagrid::vertex_tag>(domain); return PointCartesian2D(viennagrid::point(domain, vertices[index]), index); } //////////////////////////// // Triangle, cartesian 3D // //////////////////////////// unsigned int TriangularCartesian3D_Domain::num_vertices() { TriangularCartesian3D_VertexRange_t vertex_range = viennagrid::elements<viennagrid::vertex_tag>(domain); return vertex_range.size(); } void TriangularCartesian3D_Domain::add_vertex(PointCartesian3D vertex) { viennagrid::create_element<TriangularCartesian3D_Vertex_t>(domain, vertex.get_point()); unsigned int point_id = num_vertices++; TriangularCartesian3D_VertexRange_t vertex_range = viennagrid::elements<viennagrid::vertex_tag>(domain); PointCartesian3D_t &point = viennagrid::point(domain, vertex_range[point_id]); vertices.append<PointCartesian3D>(PointCartesian3D(&point, point_id)); } TriangularCartesian3D_Domain_t & TriangularCartesian3D_Domain::get_domain() { return domain; } PointCartesian3D TriangularCartesian3D_Domain::get_vertex(unsigned int index) { // TODO: domain.find_by_id(index); TriangularCartesian3D_VertexRange_t vertices = viennagrid::elements<viennagrid::vertex_tag>(domain); return PointCartesian3D(viennagrid::point(domain, vertices[index]), index); } //////////////////////////////// // Triangle, cylindrical (3D) // //////////////////////////////// unsigned int TriangularCylindrical3D_Domain::num_vertices() { TriangularCylindrical3D_VertexRange_t vertex_range = viennagrid::elements<viennagrid::vertex_tag>(domain); return vertex_range.size(); } void TriangularCylindrical3D_Domain::add_vertex(PointCylindrical3D vertex) { viennagrid::create_element<TriangularCylindrical3D_Vertex_t>(domain, vertex.get_point()); unsigned int point_id = num_vertices++; TriangularCylindrical3D_VertexRange_t vertex_range = viennagrid::elements<viennagrid::vertex_tag>(domain); PointCylindrical_t &point = viennagrid::point(domain, vertex_range[point_id]); vertices.append<PointCylindrical3D>(PointCylindrical3D(point, point_id)); } TriangularCylindrical3D_Domain_t & TriangularCylindrical3D_Domain::get_domain() { return domain; } PointCylindrical3D TriangularCylindrical3D_Domain::get_vertex(unsigned int index) { // TODO: domain.find_by_id(index); TriangularCylindrical3D_VertexRange_t vertices = viennagrid::elements<viennagrid::vertex_tag>(domain); return PointCylindrical3D(viennagrid::point(domain, vertices[index]), index); } ////////////////////////// // Triangle, polar (2D) // ////////////////////////// unsigned int TriangularPolar2D_Domain::num_vertices() { TriangularPolar2D_VertexRange_t vertex_range = viennagrid::elements<viennagrid::vertex_tag>(domain); return vertex_range.size(); } void TriangularPolar2D_Domain::add_vertex(PointPolar2D vertex) { viennagrid::create_element<TriangularPolar2D_Vertex_t>(domain, vertex.get_point()); unsigned int point_id = num_vertices++; TriangularPolar2D_VertexRange_t vertex_range = viennagrid::elements<viennagrid::vertex_tag>(domain); PointPolar_t &point = viennagrid::point(domain, vertex_range[point_id]); vertices.append<PointPolar2D>(PointPolar2D(point, point_id)); } TriangularPolar2D_Domain_t & TriangularPolar2D_Domain::get_domain() { return domain; } PointPolar2D TriangularPolar2D_Domain::get_vertex(unsigned int index) { // TODO: domain.find_by_id(index); TriangularPolar2D_VertexRange_t vertices = viennagrid::elements<viennagrid::vertex_tag>(domain); return PointPolar2D(viennagrid::point(domain, vertices[index]), index); } ////////////////////////////// // Triangle, spherical (3D) // ////////////////////////////// unsigned int TriangularSpherical3D_Domain::num_vertices() { TriangularSpherical3D_VertexRange_t vertex_range = viennagrid::elements<viennagrid::vertex_tag>(domain); return vertex_range.size(); } void TriangularSpherical3D_Domain::add_vertex(PointSpherical3D vertex) { viennagrid::create_element<TriangularSpherical3D_Vertex_t>(domain, vertex.get_point()); unsigned int point_id = num_vertices++; TriangularSpherical3D_VertexRange_t vertex_range = viennagrid::elements<viennagrid::vertex_tag>(domain); PointSpherical_t &point = viennagrid::point(domain, vertex_range[point_id]); vertices.append<PointSpherical3D>(PointSpherical3D(point, point_id)); } TriangularSpherical3D_Domain_t & TriangularSpherical3D_Domain::get_domain() { return domain; } PointSpherical3D TriangularSpherical3D_Domain::get_vertex(unsigned int index) { // TODO: domain.find_by_id(index); TriangularSpherical3D_VertexRange_t vertices = viennagrid::elements<viennagrid::vertex_tag>(domain); return PointSpherical3D(viennagrid::point(domain, vertices[index]), index); } <commit_msg>Fix 'Domain.add_vertex' after removing old attributes and methods.<commit_after>#include "triangular.hpp" #include "../segments/types.hpp" #include "../vertices/types.hpp" //////////////////////////// // Triangle, cartesian 2D // //////////////////////////// unsigned int TriangularCartesian2D_Domain::num_vertices() { TriangularCartesian2D_VertexRange_t vertex_range = viennagrid::elements<viennagrid::vertex_tag>(domain); return vertex_range.size(); } void TriangularCartesian2D_Domain::add_vertex(PointCartesian2D vertex) { viennagrid::create_element<TriangularCartesian2D_Vertex_t>(domain, vertex.get_point()); } TriangularCartesian2D_Domain_t & TriangularCartesian2D_Domain::get_domain() { return domain; } PointCartesian2D TriangularCartesian2D_Domain::get_vertex(unsigned int index) { // TODO: domain.find_by_id(index); TriangularCartesian2D_VertexRange_t vertices = viennagrid::elements<viennagrid::vertex_tag>(domain); return PointCartesian2D(viennagrid::point(domain, vertices[index]), index); } //////////////////////////// // Triangle, cartesian 3D // //////////////////////////// unsigned int TriangularCartesian3D_Domain::num_vertices() { TriangularCartesian3D_VertexRange_t vertex_range = viennagrid::elements<viennagrid::vertex_tag>(domain); return vertex_range.size(); } void TriangularCartesian3D_Domain::add_vertex(PointCartesian3D vertex) { viennagrid::create_element<TriangularCartesian3D_Vertex_t>(domain, vertex.get_point()); } TriangularCartesian3D_Domain_t & TriangularCartesian3D_Domain::get_domain() { return domain; } PointCartesian3D TriangularCartesian3D_Domain::get_vertex(unsigned int index) { // TODO: domain.find_by_id(index); TriangularCartesian3D_VertexRange_t vertices = viennagrid::elements<viennagrid::vertex_tag>(domain); return PointCartesian3D(viennagrid::point(domain, vertices[index]), index); } //////////////////////////////// // Triangle, cylindrical (3D) // //////////////////////////////// unsigned int TriangularCylindrical3D_Domain::num_vertices() { TriangularCylindrical3D_VertexRange_t vertex_range = viennagrid::elements<viennagrid::vertex_tag>(domain); return vertex_range.size(); } void TriangularCylindrical3D_Domain::add_vertex(PointCylindrical3D vertex) { viennagrid::create_element<TriangularCylindrical3D_Vertex_t>(domain, vertex.get_point()); } TriangularCylindrical3D_Domain_t & TriangularCylindrical3D_Domain::get_domain() { return domain; } PointCylindrical3D TriangularCylindrical3D_Domain::get_vertex(unsigned int index) { // TODO: domain.find_by_id(index); TriangularCylindrical3D_VertexRange_t vertices = viennagrid::elements<viennagrid::vertex_tag>(domain); return PointCylindrical3D(viennagrid::point(domain, vertices[index]), index); } ////////////////////////// // Triangle, polar (2D) // ////////////////////////// unsigned int TriangularPolar2D_Domain::num_vertices() { TriangularPolar2D_VertexRange_t vertex_range = viennagrid::elements<viennagrid::vertex_tag>(domain); return vertex_range.size(); } void TriangularPolar2D_Domain::add_vertex(PointPolar2D vertex) { viennagrid::create_element<TriangularPolar2D_Vertex_t>(domain, vertex.get_point()); } TriangularPolar2D_Domain_t & TriangularPolar2D_Domain::get_domain() { return domain; } PointPolar2D TriangularPolar2D_Domain::get_vertex(unsigned int index) { // TODO: domain.find_by_id(index); TriangularPolar2D_VertexRange_t vertices = viennagrid::elements<viennagrid::vertex_tag>(domain); return PointPolar2D(viennagrid::point(domain, vertices[index]), index); } ////////////////////////////// // Triangle, spherical (3D) // ////////////////////////////// unsigned int TriangularSpherical3D_Domain::num_vertices() { TriangularSpherical3D_VertexRange_t vertex_range = viennagrid::elements<viennagrid::vertex_tag>(domain); return vertex_range.size(); } void TriangularSpherical3D_Domain::add_vertex(PointSpherical3D vertex) { viennagrid::create_element<TriangularSpherical3D_Vertex_t>(domain, vertex.get_point()); } TriangularSpherical3D_Domain_t & TriangularSpherical3D_Domain::get_domain() { return domain; } PointSpherical3D TriangularSpherical3D_Domain::get_vertex(unsigned int index) { // TODO: domain.find_by_id(index); TriangularSpherical3D_VertexRange_t vertices = viennagrid::elements<viennagrid::vertex_tag>(domain); return PointSpherical3D(viennagrid::point(domain, vertices[index]), index); } <|endoftext|>
<commit_before>/* * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <osquery/filesystem.h> #include "osquery/remote/transports/tls.h" namespace http = boost::network::http; namespace osquery { const std::string kTLSCiphers = "ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:" "DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5"; const std::string kTLSUserAgentBase = "osquery/"; /// TLS server hostname. CLI_FLAG(string, tls_hostname, "", "TLS/HTTPS hostname for Config, Logger, and Enroll plugins"); /// Path to optional TLS server/CA certificate(s), used for pinning. CLI_FLAG(string, tls_server_certs, "", "Optional path to a TLS server PEM certificate(s) bundle"); /// Path to optional TLS client certificate, used for enrollment/requests. CLI_FLAG(string, tls_client_cert, "", "Optional path to a TLS client-auth PEM certificate"); /// Path to optional TLS client secret key, used for enrollment/requests. CLI_FLAG(string, tls_client_key, "", "Optional path to a TLS client-auth PEM private key"); #if defined(DEBUG) HIDDEN_FLAG(bool, tls_allow_unsafe, false, "Allow TLS server certificate trust failures"); #endif HIDDEN_FLAG(bool, tls_dump, false, "Print remote requests and responses"); /// Undocumented feature to override TLS endpoints. HIDDEN_FLAG(bool, tls_node_api, false, "Use node key as TLS endpoints"); DECLARE_bool(verbose); TLSTransport::TLSTransport() : verify_peer_(true) { if (FLAGS_tls_server_certs.size() > 0) { server_certificate_file_ = FLAGS_tls_server_certs; } if (FLAGS_tls_client_cert.size() > 0 && FLAGS_tls_client_key.size() > 0) { client_certificate_file_ = FLAGS_tls_client_cert; client_private_key_file_ = FLAGS_tls_client_key; } } void TLSTransport::decorateRequest(http::client::request& r) { r << boost::network::header("Connection", "close"); r << boost::network::header("Content-Type", serializer_->getContentType()); r << boost::network::header("Accept", serializer_->getContentType()); r << boost::network::header("Host", FLAGS_tls_hostname); r << boost::network::header("User-Agent", kTLSUserAgentBase + kVersion); } http::client TLSTransport::getClient() { http::client::options options; options.follow_redirects(true).always_verify_peer(verify_peer_).timeout(16); std::string ciphers = kTLSCiphers; // Some Ubuntu 12.04 clients exhaust their cipher suites without SHA. #if defined(HAS_SSL_TXT_TLSV1_2) && !defined(UBUNTU_PRECISE) && !defined(DARWIN) // Otherwise we prefer GCM and SHA256+ ciphers += ":!CBC:!SHA"; #endif #if defined(DEBUG) // Configuration may allow unsafe TLS testing if compiled as a debug target. if (FLAGS_tls_allow_unsafe) { options.always_verify_peer(false); } #endif options.openssl_ciphers(ciphers); options.openssl_options(SSL_OP_NO_SSLv3 | SSL_OP_NO_SSLv2 | SSL_OP_ALL); if (server_certificate_file_.size() > 0) { if (!osquery::isReadable(server_certificate_file_).ok()) { LOG(WARNING) << "Cannot read TLS server certificate(s): " << server_certificate_file_; } else { // There is a non-default server certificate set. options.openssl_verify_path(server_certificate_file_); options.openssl_certificate(server_certificate_file_); } } if (client_certificate_file_.size() > 0) { if (!osquery::isReadable(client_certificate_file_).ok()) { LOG(WARNING) << "Cannot read TLS client certificate: " << client_certificate_file_; } else if (!osquery::isReadable(client_private_key_file_).ok()) { LOG(WARNING) << "Cannot read TLS client private key: " << client_private_key_file_; } else { options.openssl_certificate_file(client_certificate_file_); options.openssl_private_key_file(client_private_key_file_); } } // 'Optionally', though all TLS plugins should set a hostname, supply an SNI // hostname. This will reveal the requested domain. if (options_.count("hostname")) { #if BOOST_NETLIB_VERSION_MINOR >= 12 // Boost cpp-netlib will only support SNI in versions >= 0.12 options.openssl_sni_hostname(options_.get<std::string>("hostname")); #endif } http::client client(options); return client; } inline bool tlsFailure(const std::string& what) { if (what.find("Error") == 0 || what.find("refused") != std::string::npos) { return false; } return true; } Status TLSTransport::sendRequest() { if (destination_.find("https://") == std::string::npos) { return Status(1, "Cannot create TLS request for non-HTTPS protocol URI"); } auto client = getClient(); http::client::request r(destination_); decorateRequest(r); VLOG(1) << "TLS/HTTPS GET request to URI: " << destination_; try { response_ = client.get(r); const auto& response_body = body(response_); if (FLAGS_verbose && FLAGS_tls_dump) { fprintf(stdout, "%s\n", std::string(response_body).c_str()); } response_status_ = serializer_->deserialize(response_body, response_params_); } catch (const std::exception& e) { return Status((tlsFailure(e.what())) ? 2 : 1, std::string("Request error: ") + e.what()); } return response_status_; } Status TLSTransport::sendRequest(const std::string& params, bool compress) { if (destination_.find("https://") == std::string::npos) { return Status(1, "Cannot create TLS request for non-HTTPS protocol URI"); } auto client = getClient(); http::client::request r(destination_); decorateRequest(r); if (compress) { // Later, when posting/putting, the data will be optionally compressed. r << boost::network::header("Content-Encoding", "gzip"); } // Allow request calls to override the default HTTP POST verb. HTTPVerb verb = HTTP_POST; if (options_.count("verb") > 0) { verb = (HTTPVerb)options_.get<int>("verb", HTTP_POST); } VLOG(1) << "TLS/HTTPS " << ((verb == HTTP_POST) ? "POST" : "PUT") << " request to URI: " << destination_; if (FLAGS_verbose && FLAGS_tls_dump) { fprintf(stdout, "%s\n", params.c_str()); } try { if (verb == HTTP_POST) { response_ = client.post(r, (compress) ? compressString(params) : params); } else { response_ = client.put(r, (compress) ? compressString(params) : params); } const auto& response_body = body(response_); if (FLAGS_verbose && FLAGS_tls_dump) { fprintf(stdout, "%s\n", std::string(response_body).c_str()); } response_status_ = serializer_->deserialize(response_body, response_params_); } catch (const std::exception& e) { return Status((tlsFailure(e.what())) ? 2 : 1, std::string("Request error: ") + e.what()); } return response_status_; } } <commit_msg>Remove OpenSSL and cpp-netlib old version exceptions (#2413)<commit_after>/* * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <osquery/core.h> #include <osquery/filesystem.h> #include "osquery/remote/transports/tls.h" namespace http = boost::network::http; namespace osquery { const std::string kTLSCiphers = "ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:" "DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5"; const std::string kTLSUserAgentBase = "osquery/"; /// TLS server hostname. CLI_FLAG(string, tls_hostname, "", "TLS/HTTPS hostname for Config, Logger, and Enroll plugins"); /// Path to optional TLS server/CA certificate(s), used for pinning. CLI_FLAG(string, tls_server_certs, "", "Optional path to a TLS server PEM certificate(s) bundle"); /// Path to optional TLS client certificate, used for enrollment/requests. CLI_FLAG(string, tls_client_cert, "", "Optional path to a TLS client-auth PEM certificate"); /// Path to optional TLS client secret key, used for enrollment/requests. CLI_FLAG(string, tls_client_key, "", "Optional path to a TLS client-auth PEM private key"); #if defined(DEBUG) HIDDEN_FLAG(bool, tls_allow_unsafe, false, "Allow TLS server certificate trust failures"); #endif HIDDEN_FLAG(bool, tls_dump, false, "Print remote requests and responses"); /// Undocumented feature to override TLS endpoints. HIDDEN_FLAG(bool, tls_node_api, false, "Use node key as TLS endpoints"); DECLARE_bool(verbose); TLSTransport::TLSTransport() : verify_peer_(true) { if (FLAGS_tls_server_certs.size() > 0) { server_certificate_file_ = FLAGS_tls_server_certs; } if (FLAGS_tls_client_cert.size() > 0 && FLAGS_tls_client_key.size() > 0) { client_certificate_file_ = FLAGS_tls_client_cert; client_private_key_file_ = FLAGS_tls_client_key; } } void TLSTransport::decorateRequest(http::client::request& r) { r << boost::network::header("Connection", "close"); r << boost::network::header("Content-Type", serializer_->getContentType()); r << boost::network::header("Accept", serializer_->getContentType()); r << boost::network::header("Host", FLAGS_tls_hostname); r << boost::network::header("User-Agent", kTLSUserAgentBase + kVersion); } http::client TLSTransport::getClient() { http::client::options options; options.follow_redirects(true).always_verify_peer(verify_peer_).timeout(16); std::string ciphers = kTLSCiphers; if (!isPlatform(PlatformType::TYPE_OSX)) { // Otherwise we prefer GCM and SHA256+ ciphers += ":!CBC:!SHA"; } #if defined(DEBUG) // Configuration may allow unsafe TLS testing if compiled as a debug target. if (FLAGS_tls_allow_unsafe) { options.always_verify_peer(false); } #endif options.openssl_ciphers(ciphers); options.openssl_options(SSL_OP_NO_SSLv3 | SSL_OP_NO_SSLv2 | SSL_OP_ALL); if (server_certificate_file_.size() > 0) { if (!osquery::isReadable(server_certificate_file_).ok()) { LOG(WARNING) << "Cannot read TLS server certificate(s): " << server_certificate_file_; } else { // There is a non-default server certificate set. options.openssl_verify_path(server_certificate_file_); options.openssl_certificate(server_certificate_file_); } } if (client_certificate_file_.size() > 0) { if (!osquery::isReadable(client_certificate_file_).ok()) { LOG(WARNING) << "Cannot read TLS client certificate: " << client_certificate_file_; } else if (!osquery::isReadable(client_private_key_file_).ok()) { LOG(WARNING) << "Cannot read TLS client private key: " << client_private_key_file_; } else { options.openssl_certificate_file(client_certificate_file_); options.openssl_private_key_file(client_private_key_file_); } } // 'Optionally', though all TLS plugins should set a hostname, supply an SNI // hostname. This will reveal the requested domain. if (options_.count("hostname")) { // Boost cpp-netlib will only support SNI in versions >= 0.12 options.openssl_sni_hostname(options_.get<std::string>("hostname")); } http::client client(options); return client; } inline bool tlsFailure(const std::string& what) { if (what.find("Error") == 0 || what.find("refused") != std::string::npos) { return false; } return true; } Status TLSTransport::sendRequest() { if (destination_.find("https://") == std::string::npos) { return Status(1, "Cannot create TLS request for non-HTTPS protocol URI"); } auto client = getClient(); http::client::request r(destination_); decorateRequest(r); VLOG(1) << "TLS/HTTPS GET request to URI: " << destination_; try { response_ = client.get(r); const auto& response_body = body(response_); if (FLAGS_verbose && FLAGS_tls_dump) { fprintf(stdout, "%s\n", std::string(response_body).c_str()); } response_status_ = serializer_->deserialize(response_body, response_params_); } catch (const std::exception& e) { return Status((tlsFailure(e.what())) ? 2 : 1, std::string("Request error: ") + e.what()); } return response_status_; } Status TLSTransport::sendRequest(const std::string& params, bool compress) { if (destination_.find("https://") == std::string::npos) { return Status(1, "Cannot create TLS request for non-HTTPS protocol URI"); } auto client = getClient(); http::client::request r(destination_); decorateRequest(r); if (compress) { // Later, when posting/putting, the data will be optionally compressed. r << boost::network::header("Content-Encoding", "gzip"); } // Allow request calls to override the default HTTP POST verb. HTTPVerb verb = HTTP_POST; if (options_.count("verb") > 0) { verb = (HTTPVerb)options_.get<int>("verb", HTTP_POST); } VLOG(1) << "TLS/HTTPS " << ((verb == HTTP_POST) ? "POST" : "PUT") << " request to URI: " << destination_; if (FLAGS_verbose && FLAGS_tls_dump) { fprintf(stdout, "%s\n", params.c_str()); } try { if (verb == HTTP_POST) { response_ = client.post(r, (compress) ? compressString(params) : params); } else { response_ = client.put(r, (compress) ? compressString(params) : params); } const auto& response_body = body(response_); if (FLAGS_verbose && FLAGS_tls_dump) { fprintf(stdout, "%s\n", std::string(response_body).c_str()); } response_status_ = serializer_->deserialize(response_body, response_params_); } catch (const std::exception& e) { return Status((tlsFailure(e.what())) ? 2 : 1, std::string("Request error: ") + e.what()); } return response_status_; } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: register.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2003-12-01 18:09:29 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_ #include <com/sun/star/registry/XRegistryKey.hpp> #endif #ifndef _COM_SUN_STAR_REGISTRY_INVALIDREGISTRYEXCEPTION_HPP_ #include <com/sun/star/registry/InvalidRegistryException.hpp> #endif #ifndef _CPPUHELPER_FACTORY_HXX_ #include <cppuhelper/factory.hxx> #endif #include "xfactory.hxx" using namespace ::com::sun::star; extern "C" { void SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv ) { *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; } void * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey ) { void * pRet = 0; ::rtl::OUString aImplName( ::rtl::OUString::createFromAscii( pImplName ) ); uno::Reference< lang::XSingleServiceFactory > xFactory; if ( pServiceManager && aImplName.equals( OStorageFactory::impl_staticGetImplementationName() ) ) { xFactory= ::cppu::createOneInstanceFactory( reinterpret_cast< lang::XMultiServiceFactory*>( pServiceManager ), OStorageFactory::impl_staticGetImplementationName(), OStorageFactory::impl_staticCreateSelfInstance, OStorageFactory::impl_staticGetSupportedServiceNames() ); } if ( xFactory.is() ) { xFactory->acquire(); pRet = xFactory.get(); } return pRet; } sal_Bool SAL_CALL component_writeInfo( void * pServiceManager, void * pRegistryKey ) { if (pRegistryKey) { try { uno::Reference< registry::XRegistryKey > xKey( reinterpret_cast< registry::XRegistryKey* >( pRegistryKey ) ); uno::Reference< registry::XRegistryKey > xNewKey; xNewKey = xKey->createKey( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("/") ) + OStorageFactory::impl_staticGetImplementationName() + ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "/UNO/SERVICES") ) ); const uno::Sequence< ::rtl::OUString > &rServices = OStorageFactory::impl_staticGetSupportedServiceNames(); for( sal_Int32 ind = 0; ind < rServices.getLength(); ind++ ) xNewKey->createKey( rServices.getConstArray()[ind] ); return sal_True; } catch (registry::InvalidRegistryException &) { OSL_ENSURE( sal_False, "### InvalidRegistryException!" ); } } return sal_False; } } // extern "C" <commit_msg>INTEGRATION: CWS mav09 (1.3.42); FILE MERGED 2004/05/13 15:10:03 mav 1.3.42.1: #112768# remove dangerous references<commit_after>/************************************************************************* * * $RCSfile: register.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: kz $ $Date: 2004-10-04 21:08: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): _______________________________________ * * ************************************************************************/ #ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_ #include <com/sun/star/registry/XRegistryKey.hpp> #endif #ifndef _COM_SUN_STAR_REGISTRY_INVALIDREGISTRYEXCEPTION_HPP_ #include <com/sun/star/registry/InvalidRegistryException.hpp> #endif #ifndef _CPPUHELPER_FACTORY_HXX_ #include <cppuhelper/factory.hxx> #endif #include "xfactory.hxx" using namespace ::com::sun::star; extern "C" { void SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv ) { *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; } void * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey ) { void * pRet = 0; ::rtl::OUString aImplName( ::rtl::OUString::createFromAscii( pImplName ) ); uno::Reference< lang::XSingleServiceFactory > xFactory; if ( pServiceManager && aImplName.equals( OStorageFactory::impl_staticGetImplementationName() ) ) { xFactory= ::cppu::createOneInstanceFactory( reinterpret_cast< lang::XMultiServiceFactory*>( pServiceManager ), OStorageFactory::impl_staticGetImplementationName(), OStorageFactory::impl_staticCreateSelfInstance, OStorageFactory::impl_staticGetSupportedServiceNames() ); } if ( xFactory.is() ) { xFactory->acquire(); pRet = xFactory.get(); } return pRet; } sal_Bool SAL_CALL component_writeInfo( void * pServiceManager, void * pRegistryKey ) { if (pRegistryKey) { try { uno::Reference< registry::XRegistryKey > xKey( reinterpret_cast< registry::XRegistryKey* >( pRegistryKey ) ); uno::Reference< registry::XRegistryKey > xNewKey; xNewKey = xKey->createKey( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("/") ) + OStorageFactory::impl_staticGetImplementationName() + ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "/UNO/SERVICES") ) ); const uno::Sequence< ::rtl::OUString > aServices = OStorageFactory::impl_staticGetSupportedServiceNames(); for( sal_Int32 ind = 0; ind < aServices.getLength(); ind++ ) xNewKey->createKey( aServices.getConstArray()[ind] ); return sal_True; } catch (registry::InvalidRegistryException &) { OSL_ENSURE( sal_False, "### InvalidRegistryException!" ); } } return sal_False; } } // extern "C" <|endoftext|>
<commit_before>#include "BACharacter.h" #include "BAMap.h" #include "BAGlobal.h" BAPlayer::BAPlayer(BACharacterData data){ charData = data; // init ships ships = NULL; numberOfShips = charData.sShips + charData.mShips + charData.lShips; ships = new BAShip[numberOfShips]; // small ships for(size_t i = 0; i < charData.sShips; i++) ships[i] = BAShipMake(1); // medium ships for(size_t i = 0; i < charData.mShips; i++) ships[i+charData.sShips] = BAShipMake(2); // big ships for(size_t i = 0; i < charData.lShips; i++) ships[i+charData.sShips+charData.mShips] = BAShipMake(3); // create water map for(size_t j = 0; j < GAME_BOARD_SIZE_HEIGHT; j++){ for(size_t i = 0; i < GAME_BOARD_SIZE_WIDTH; i++){ //Water playerBoard[j][i] = BAMapTileTypeWater0; } } // random mountains byte mountainsCount = random(3,6); ABPoint lastMountainPos = ABPointMake(-1, -1); for(byte i = 0; i < mountainsCount ; i++){ ABPoint mountainPos; do{ mountainPos.x = random(0, GAME_BOARD_SIZE_WIDTH); mountainPos.y = random(0, GAME_BOARD_SIZE_HEIGHT); } while(pointIsEqualToPoint(mountainPos, lastMountainPos)); lastMountainPos = mountainPos; playerBoard[mountainPos.y][mountainPos.x] = BAMapTileTypeMountain; } } BAPlayer::~BAPlayer(){ delete ships; ships = NULL; } BACharacterData BAPlayer::getCharacterData(){ return charData; } BAShip BAPlayer::shipAtIndex(byte idx){ return ships[idx]; } void BAPlayer::updateShipAtIndex(byte idx, BAShip newShip){ ships[idx].remainingLength = newShip.remainingLength; ships[idx].horizontal = newShip.horizontal; } byte BAPlayer:: numberOfRemainingShips(){ byte nr = 0; for(int i = 0; i<numberOfShips ;i++) if(!isShipDestroyed(ships[i])) nr++; return nr; } <commit_msg>update ship position when update ship<commit_after>#include "BACharacter.h" #include "BAMap.h" #include "BAGlobal.h" BAPlayer::BAPlayer(BACharacterData data){ charData = data; // init ships ships = NULL; numberOfShips = charData.sShips + charData.mShips + charData.lShips; ships = new BAShip[numberOfShips]; // small ships for(size_t i = 0; i < charData.sShips; i++) ships[i] = BAShipMake(1); // medium ships for(size_t i = 0; i < charData.mShips; i++) ships[i+charData.sShips] = BAShipMake(2); // big ships for(size_t i = 0; i < charData.lShips; i++) ships[i+charData.sShips+charData.mShips] = BAShipMake(3); // create water map for(size_t j = 0; j < GAME_BOARD_SIZE_HEIGHT; j++){ for(size_t i = 0; i < GAME_BOARD_SIZE_WIDTH; i++){ //Water playerBoard[j][i] = BAMapTileTypeWater0; } } // random mountains byte mountainsCount = random(3,6); ABPoint lastMountainPos = ABPointMake(-1, -1); for(byte i = 0; i < mountainsCount ; i++){ ABPoint mountainPos; do{ mountainPos.x = random(0, GAME_BOARD_SIZE_WIDTH); mountainPos.y = random(0, GAME_BOARD_SIZE_HEIGHT); } while(pointIsEqualToPoint(mountainPos, lastMountainPos)); lastMountainPos = mountainPos; playerBoard[mountainPos.y][mountainPos.x] = BAMapTileTypeMountain; } } BAPlayer::~BAPlayer(){ delete ships; ships = NULL; } BACharacterData BAPlayer::getCharacterData(){ return charData; } BAShip BAPlayer::shipAtIndex(byte idx){ return ships[idx]; } void BAPlayer::updateShipAtIndex(byte idx, BAShip newShip){ ships[idx].remainingLength = newShip.remainingLength; ships[idx].horizontal = newShip.horizontal; ships[idx].position = newShip.position; } byte BAPlayer:: numberOfRemainingShips(){ byte nr = 0; for(int i = 0; i<numberOfShips ;i++) if(!isShipDestroyed(ships[i])) nr++; return nr; } <|endoftext|>
<commit_before>// Port of // third_party/nxp/rt1176-sdk/middleware/wireless/ethermind/port/pal/mcux/bluetooth/BT_storage_pl.c // to use Dev Board Micro's filesystem APIs. #include "libs/base/filesystem.h" extern "C" { #include "third_party/nxp/rt1176-sdk/middleware/wireless/ethermind/port/pal/mcux/bluetooth/BT_storage_pl.h" static lfs_file_t *fp[STORAGE_NUM_TYPES]; static lfs_file_t lfs_file[STORAGE_NUM_TYPES]; /* Storage File Name array */ static UCHAR *fn[STORAGE_NUM_TYPES] = { (UCHAR *)"btps.db", #ifdef STORAGE_RETENTION_SUPPORT (UCHAR *)"btrn.db", #endif /* STORAGE_RETENTION_SUPPORT */ }; /* Storage Signature Key array */ static UCHAR ssign[STORAGE_NUM_TYPES][STORAGE_SKEY_SIZE] = { {'E', 'T', 'H', 'E', 'R', 'M', 'I', 'N', 'D', 'P', 'S'}}; API_RESULT storage_open_pl(UCHAR type, UCHAR mode) { if (NULL != fp[type]) { coralmicro::filesystem::Close(fp[type]); fp[type] = NULL; } bool open; if (mode == STORAGE_OPEN_MODE_WRITE) { open = coralmicro::filesystem::Open(&lfs_file[type], (char *)fn[type], true); } else { open = coralmicro::filesystem::Open(&lfs_file[type], (char *)fn[type]); } if (!open) { return API_FAILURE; } fp[type] = &lfs_file[type]; return API_SUCCESS; } API_RESULT storage_close_pl(UCHAR type, UCHAR mode) { if (NULL != fp[type]) { coralmicro::filesystem::Close(fp[type]); fp[type] = NULL; } return API_SUCCESS; } INT16 storage_write_pl(UCHAR type, void *buffer, UINT16 size) { INT16 nbytes; nbytes = 0; if (NULL != fp[type]) { nbytes = (INT16)coralmicro::filesystem::Write(fp[type], buffer, size); } return nbytes; } INT16 storage_read_pl(UCHAR type, void *buffer, UINT16 size) { INT16 nbytes = 0; if (NULL != fp[type]) { nbytes = (INT16)coralmicro::filesystem::Read(fp[type], buffer, size); } return nbytes; } INT16 storage_write_signature_pl(UCHAR type) { INT16 nbytes = 0; if (NULL != fp[type]) { nbytes = (INT16)coralmicro::filesystem::Write(fp[type], ssign[type], STORAGE_SKEY_SIZE); } return nbytes; } INT16 storage_read_signature_pl(UCHAR type) { INT16 nbytes = 0; UCHAR sign[STORAGE_SKEY_SIZE]; if (NULL != fp[type]) { nbytes = coralmicro::filesystem::Read(fp[type], sign, STORAGE_SKEY_SIZE); if (BT_mem_cmp(ssign[type], sign, STORAGE_SKEY_SIZE)) { return -1; } } return nbytes; } void storage_bt_init_pl(void) { for (unsigned int i = 0; i < STORAGE_NUM_TYPES; ++i) { fp[i] = NULL; } } } // extern "C" <commit_msg>Use LFS API directly in BT_storage_pl.cc<commit_after>// Port of // third_party/nxp/rt1176-sdk/middleware/wireless/ethermind/port/pal/mcux/bluetooth/BT_storage_pl.c #include "libs/base/filesystem.h" /* * Copyright (C) 2013. Mindtree Ltd. * All rights reserved. */ using coralmicro::filesystem::Lfs; extern "C" { #include "third_party/nxp/rt1176-sdk/middleware/wireless/ethermind/port/pal/mcux/bluetooth/BT_storage_pl.h" /* Storage File Handle array */ static lfs_file_t* fp[STORAGE_NUM_TYPES]; static lfs_file_t lfs_file[STORAGE_NUM_TYPES]; /* Storage File Name array */ static UCHAR* fn[STORAGE_NUM_TYPES] = { (UCHAR*)"btps.db", #ifdef STORAGE_RETENTION_SUPPORT (UCHAR*)"btrn.db", #endif /* STORAGE_RETENTION_SUPPORT */ }; /* Storage Signature Key array */ static UCHAR ssign[STORAGE_NUM_TYPES][STORAGE_SKEY_SIZE] = { {'E', 'T', 'H', 'E', 'R', 'M', 'I', 'N', 'D', 'P', 'S'}}; API_RESULT storage_open_pl(UCHAR type, UCHAR mode) { if (NULL != fp[type]) { (void)lfs_file_close(Lfs(), fp[type]); fp[type] = NULL; } /* Set the file access mode */ int rw = (int)((STORAGE_OPEN_MODE_WRITE == mode) ? (LFS_O_WRONLY | LFS_O_CREAT) : LFS_O_RDONLY); int err = lfs_file_open(Lfs(), &lfs_file[type], (CHAR*)fn[type], rw); if (err < 0) { return API_FAILURE; } fp[type] = &lfs_file[type]; return API_SUCCESS; } API_RESULT storage_close_pl(UCHAR type, UCHAR mode) { BT_IGNORE_UNUSED_PARAM(mode); if (NULL != fp[type]) { (void)lfs_file_close(Lfs(), fp[type]); fp[type] = NULL; } return API_SUCCESS; } INT16 storage_write_pl(UCHAR type, void* buffer, UINT16 size) { INT16 nbytes = 0; if (NULL != fp[type]) { nbytes = (INT16)lfs_file_write(Lfs(), fp[type], buffer, size); } return nbytes; } INT16 storage_read_pl(UCHAR type, void* buffer, UINT16 size) { INT16 nbytes = 0; if (NULL != fp[type]) { nbytes = (INT16)lfs_file_read(Lfs(), fp[type], buffer, size); } return nbytes; } INT16 storage_write_signature_pl(UCHAR type) { INT16 nbytes = 0; if (NULL != fp[type]) { nbytes = (INT16)lfs_file_write(Lfs(), fp[type], ssign[type], STORAGE_SKEY_SIZE); } return nbytes; } INT16 storage_read_signature_pl(UCHAR type) { INT16 nbytes = 0; UCHAR sign[STORAGE_SKEY_SIZE]; if (NULL != fp[type]) { nbytes = lfs_file_read(Lfs(), fp[type], sign, STORAGE_SKEY_SIZE); if (BT_mem_cmp(ssign[type], sign, STORAGE_SKEY_SIZE)) { return -1; } } return nbytes; } void storage_bt_init_pl() { for (UCHAR i = 0; i < STORAGE_NUM_TYPES; i++) { fp[i] = NULL; } } void storage_bt_shutdown_pl() { for (UCHAR i = 0; i < STORAGE_NUM_TYPES; i++) { if (NULL != fp[i]) { lfs_file_close(Lfs(), fp[i]); fp[i] = NULL; } } } } // extern "C" <|endoftext|>
<commit_before>// $Id$ /* Copyright (c) 2007-2009, Trustees of The Leland Stanford Junior 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 the Stanford University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "booksim.hpp" #include <iostream> #include <cassert> #include "allocator.hpp" ///////////////////////////////////////////////////////////////////////// //Allocator types #include "maxsize.hpp" #include "pim.hpp" #include "islip.hpp" #include "loa.hpp" #include "wavefront.hpp" #include "fair_wavefront.hpp" #include "prio_wavefront.hpp" #include "selalloc.hpp" #include "separable_input_first.hpp" #include "separable_output_first.hpp" // ///////////////////////////////////////////////////////////////////////// //================================================== // Allocator base class //================================================== Allocator::Allocator( Module *parent, const string& name, int inputs, int outputs ) : Module( parent, name ), _inputs( inputs ), _outputs( outputs ) { _inmatch.resize(_inputs, -1); _outmatch.resize(_outputs, -1); } void Allocator::Clear( ) { _inmatch.assign(_inputs, -1); _outmatch.assign(_outputs, -1); } void Allocator::AddRequest( int in, int out, int label, int in_pri, int out_pri ) { assert( ( in >= 0 ) && ( in < _inputs ) ); assert( ( out >= 0 ) && ( out < _outputs ) ); assert( label >= 0 ); } int Allocator::OutputAssigned( int in ) const { assert( ( in >= 0 ) && ( in < _inputs ) ); return _inmatch[in]; } int Allocator::InputAssigned( int out ) const { assert( ( out >= 0 ) && ( out < _outputs ) ); return _outmatch[out]; } //================================================== // DenseAllocator //================================================== DenseAllocator::DenseAllocator( Module *parent, const string& name, int inputs, int outputs ) : Allocator( parent, name, inputs, outputs ) { _request.resize(_inputs); for ( int i = 0; i < _inputs; ++i ) { _request[i].resize(_outputs); for ( int j = 0; j < _outputs; ++j ) { _request[i][j].label = -1; } } } void DenseAllocator::Clear( ) { for ( int i = 0; i < _inputs; ++i ) { for ( int j = 0; j < _outputs; ++j ) { _request[i][j].label = -1; } } Allocator::Clear(); } int DenseAllocator::ReadRequest( int in, int out ) const { assert( ( in >= 0 ) && ( in < _inputs ) ); assert( ( out >= 0 ) && ( out < _outputs ) ); return _request[in][out].label; } bool DenseAllocator::ReadRequest( sRequest &req, int in, int out ) const { assert( ( in >= 0 ) && ( in < _inputs ) ); assert( ( out >= 0 ) && ( out < _outputs ) ); req = _request[in][out]; return ( req.label != -1 ); } void DenseAllocator::AddRequest( int in, int out, int label, int in_pri, int out_pri ) { Allocator::AddRequest(in, out, label, in_pri, out_pri); if((_request[in][out].label == -1) || (_request[in][out].in_pri < in_pri)) { _request[in][out].label = label; _request[in][out].in_pri = in_pri; _request[in][out].out_pri = out_pri; } } void DenseAllocator::RemoveRequest( int in, int out, int label ) { assert( ( in >= 0 ) && ( in < _inputs ) ); assert( ( out >= 0 ) && ( out < _outputs ) ); _request[in][out].label = -1; } void DenseAllocator::PrintRequests( ostream * os ) const { if(!os) os = &cout; *os << "Requests = [ "; for ( int i = 0; i < _inputs; ++i ) { *os << "[ "; for ( int j = 0; j < _outputs; ++j ) { *os << ( _request[i][j].label != -1 ) << " "; } *os << "] "; } *os << "]." << endl; } //================================================== // SparseAllocator //================================================== SparseAllocator::SparseAllocator( Module *parent, const string& name, int inputs, int outputs ) : Allocator( parent, name, inputs, outputs ) { _in_req.resize(_inputs); _out_req.resize(_outputs); } void SparseAllocator::Clear( ) { for ( int i = 0; i < _inputs; ++i ) { _in_req[i].clear( ); } for ( int j = 0; j < _outputs; ++j ) { _out_req[j].clear( ); } _in_occ.clear( ); _out_occ.clear( ); Allocator::Clear(); } int SparseAllocator::ReadRequest( int in, int out ) const { sRequest r; if ( ! ReadRequest( r, in, out ) ) { r.label = -1; } return r.label; } bool SparseAllocator::ReadRequest( sRequest &req, int in, int out ) const { bool found; assert( ( in >= 0 ) && ( in < _inputs ) ); assert( ( out >= 0 ) && ( out < _outputs ) ); map<int, sRequest>::const_iterator match = _in_req[in].find(out); if ( match != _in_req[in].end( ) ) { req = match->second; found = true; } else { found = false; } return found; } void SparseAllocator::AddRequest( int in, int out, int label, int in_pri, int out_pri ) { Allocator::AddRequest(in, out, label, in_pri, out_pri); // insert into occupied inputs set if // input is currently empty if ( _in_req[in].empty( ) ) { _in_occ.insert(in); } // similarly for the output if ( _out_req[out].empty( ) ) { _out_occ.insert(out); } sRequest req; req.port = out; req.label = label; req.in_pri = in_pri; req.out_pri = out_pri; // insert input request in order of it's output map<int, sRequest>::iterator insert_point = _in_req[in].find(out); if(insert_point == _in_req[in].end()) { _in_req[in][out] = req; } else if(insert_point->second.in_pri < in_pri) { insert_point->second = req; } req.port = in; req.label = label; insert_point = _out_req[out].find(in); if(insert_point == _out_req[out].end()) { _out_req[out][in] = req; } else if(insert_point->second.in_pri < in_pri) { insert_point->second = req; } } void SparseAllocator::RemoveRequest( int in, int out, int label ) { assert( ( in >= 0 ) && ( in < _inputs ) ); assert( ( out >= 0 ) && ( out < _outputs ) ); // insert input request in order of it's output map<int, sRequest>::iterator erase_point = _in_req[in].find(out); assert( erase_point != _in_req[in].end( ) ); _in_req[in].erase( erase_point ); // remove from occupied inputs list if // input is now empty if ( _in_req[in].empty( ) ) { _in_occ.erase(in); } // similarly for the output erase_point = _out_req[out].find(in); assert( erase_point != _out_req[out].end( ) ); _out_req[out].erase( erase_point ); if ( _out_req[out].empty( ) ) { _out_occ.erase(out); } } void SparseAllocator::PrintRequests( ostream * os ) const { map<int, sRequest>::const_iterator iter; if(!os) os = &cout; *os << "Input requests = [ "; for ( int input = 0; input < _inputs; ++input ) { *os << input << " -> [ "; for ( iter = _in_req[input].begin( ); iter != _in_req[input].end( ); iter++ ) { *os << iter->second.port << " "; } *os << "] "; } *os << "], output requests = [ "; for ( int output = 0; output < _outputs; ++output ) { *os << output << " -> "; *os << "[ "; for ( iter = _out_req[output].begin( ); iter != _out_req[output].end( ); iter++ ) { *os << iter->second.port << " "; } *os << "] "; } *os << "]." << endl; } //================================================== // Global allocator allocation function //================================================== Allocator *Allocator::NewAllocator( Module *parent, const string& name, const string &alloc_type, int inputs, int outputs, int iters, const string &arb_type ) { Allocator *a = 0; if ( alloc_type == "max_size" ) { a = new MaxSizeMatch( parent, name, inputs, outputs ); } else if ( alloc_type == "pim" ) { a = new PIM( parent, name, inputs, outputs, iters ); } else if ( alloc_type == "islip" ) { a = new iSLIP_Sparse( parent, name, inputs, outputs, iters ); } else if ( alloc_type == "loa" ) { a = new LOA( parent, name, inputs, outputs ); } else if ( alloc_type == "wavefront" ) { a = new Wavefront( parent, name, inputs, outputs ); } else if ( alloc_type == "fair_wavefront" ) { a = new FairWavefront( parent, name, inputs, outputs ); } else if ( alloc_type == "prio_wavefront" ) { a = new PrioWavefront( parent, name, inputs, outputs ); } else if ( alloc_type == "select" ) { a = new SelAlloc( parent, name, inputs, outputs, iters ); } else if (alloc_type == "separable_input_first") { a = new SeparableInputFirstAllocator( parent, name, inputs, outputs, arb_type ); } else if (alloc_type == "separable_output_first") { a = new SeparableOutputFirstAllocator( parent, name, inputs, outputs, arb_type ); } //================================================== // Insert new allocators here, add another else if //================================================== return a; } <commit_msg>simplify request removal for sparse allocator<commit_after>// $Id$ /* Copyright (c) 2007-2009, Trustees of The Leland Stanford Junior 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 the Stanford University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "booksim.hpp" #include <iostream> #include <cassert> #include "allocator.hpp" ///////////////////////////////////////////////////////////////////////// //Allocator types #include "maxsize.hpp" #include "pim.hpp" #include "islip.hpp" #include "loa.hpp" #include "wavefront.hpp" #include "fair_wavefront.hpp" #include "prio_wavefront.hpp" #include "selalloc.hpp" #include "separable_input_first.hpp" #include "separable_output_first.hpp" // ///////////////////////////////////////////////////////////////////////// //================================================== // Allocator base class //================================================== Allocator::Allocator( Module *parent, const string& name, int inputs, int outputs ) : Module( parent, name ), _inputs( inputs ), _outputs( outputs ) { _inmatch.resize(_inputs, -1); _outmatch.resize(_outputs, -1); } void Allocator::Clear( ) { _inmatch.assign(_inputs, -1); _outmatch.assign(_outputs, -1); } void Allocator::AddRequest( int in, int out, int label, int in_pri, int out_pri ) { assert( ( in >= 0 ) && ( in < _inputs ) ); assert( ( out >= 0 ) && ( out < _outputs ) ); assert( label >= 0 ); } int Allocator::OutputAssigned( int in ) const { assert( ( in >= 0 ) && ( in < _inputs ) ); return _inmatch[in]; } int Allocator::InputAssigned( int out ) const { assert( ( out >= 0 ) && ( out < _outputs ) ); return _outmatch[out]; } //================================================== // DenseAllocator //================================================== DenseAllocator::DenseAllocator( Module *parent, const string& name, int inputs, int outputs ) : Allocator( parent, name, inputs, outputs ) { _request.resize(_inputs); for ( int i = 0; i < _inputs; ++i ) { _request[i].resize(_outputs); for ( int j = 0; j < _outputs; ++j ) { _request[i][j].label = -1; } } } void DenseAllocator::Clear( ) { for ( int i = 0; i < _inputs; ++i ) { for ( int j = 0; j < _outputs; ++j ) { _request[i][j].label = -1; } } Allocator::Clear(); } int DenseAllocator::ReadRequest( int in, int out ) const { assert( ( in >= 0 ) && ( in < _inputs ) ); assert( ( out >= 0 ) && ( out < _outputs ) ); return _request[in][out].label; } bool DenseAllocator::ReadRequest( sRequest &req, int in, int out ) const { assert( ( in >= 0 ) && ( in < _inputs ) ); assert( ( out >= 0 ) && ( out < _outputs ) ); req = _request[in][out]; return ( req.label != -1 ); } void DenseAllocator::AddRequest( int in, int out, int label, int in_pri, int out_pri ) { Allocator::AddRequest(in, out, label, in_pri, out_pri); if((_request[in][out].label == -1) || (_request[in][out].in_pri < in_pri)) { _request[in][out].label = label; _request[in][out].in_pri = in_pri; _request[in][out].out_pri = out_pri; } } void DenseAllocator::RemoveRequest( int in, int out, int label ) { assert( ( in >= 0 ) && ( in < _inputs ) ); assert( ( out >= 0 ) && ( out < _outputs ) ); _request[in][out].label = -1; } void DenseAllocator::PrintRequests( ostream * os ) const { if(!os) os = &cout; *os << "Requests = [ "; for ( int i = 0; i < _inputs; ++i ) { *os << "[ "; for ( int j = 0; j < _outputs; ++j ) { *os << ( _request[i][j].label != -1 ) << " "; } *os << "] "; } *os << "]." << endl; } //================================================== // SparseAllocator //================================================== SparseAllocator::SparseAllocator( Module *parent, const string& name, int inputs, int outputs ) : Allocator( parent, name, inputs, outputs ) { _in_req.resize(_inputs); _out_req.resize(_outputs); } void SparseAllocator::Clear( ) { for ( int i = 0; i < _inputs; ++i ) { _in_req[i].clear( ); } for ( int j = 0; j < _outputs; ++j ) { _out_req[j].clear( ); } _in_occ.clear( ); _out_occ.clear( ); Allocator::Clear(); } int SparseAllocator::ReadRequest( int in, int out ) const { sRequest r; if ( ! ReadRequest( r, in, out ) ) { r.label = -1; } return r.label; } bool SparseAllocator::ReadRequest( sRequest &req, int in, int out ) const { bool found; assert( ( in >= 0 ) && ( in < _inputs ) ); assert( ( out >= 0 ) && ( out < _outputs ) ); map<int, sRequest>::const_iterator match = _in_req[in].find(out); if ( match != _in_req[in].end( ) ) { req = match->second; found = true; } else { found = false; } return found; } void SparseAllocator::AddRequest( int in, int out, int label, int in_pri, int out_pri ) { Allocator::AddRequest(in, out, label, in_pri, out_pri); // insert into occupied inputs set if // input is currently empty if ( _in_req[in].empty( ) ) { _in_occ.insert(in); } // similarly for the output if ( _out_req[out].empty( ) ) { _out_occ.insert(out); } sRequest req; req.port = out; req.label = label; req.in_pri = in_pri; req.out_pri = out_pri; _in_req[in][out] = req; req.port = in; req.label = label; _out_req[out][in] = req; } void SparseAllocator::RemoveRequest( int in, int out, int label ) { assert( ( in >= 0 ) && ( in < _inputs ) ); assert( ( out >= 0 ) && ( out < _outputs ) ); assert( _in_req[in].count( out ) > 0 ); _in_req[in].erase( out ); // remove from occupied inputs list if // input is now empty if ( _in_req[in].empty( ) ) { _in_occ.erase(in); } // similarly for the output assert( _out_req[out].count( out ) > 0 ); _out_req[out].erase( out ); if ( _out_req[out].empty( ) ) { _out_occ.erase(out); } } void SparseAllocator::PrintRequests( ostream * os ) const { map<int, sRequest>::const_iterator iter; if(!os) os = &cout; *os << "Input requests = [ "; for ( int input = 0; input < _inputs; ++input ) { *os << input << " -> [ "; for ( iter = _in_req[input].begin( ); iter != _in_req[input].end( ); iter++ ) { *os << iter->second.port << " "; } *os << "] "; } *os << "], output requests = [ "; for ( int output = 0; output < _outputs; ++output ) { *os << output << " -> "; *os << "[ "; for ( iter = _out_req[output].begin( ); iter != _out_req[output].end( ); iter++ ) { *os << iter->second.port << " "; } *os << "] "; } *os << "]." << endl; } //================================================== // Global allocator allocation function //================================================== Allocator *Allocator::NewAllocator( Module *parent, const string& name, const string &alloc_type, int inputs, int outputs, int iters, const string &arb_type ) { Allocator *a = 0; if ( alloc_type == "max_size" ) { a = new MaxSizeMatch( parent, name, inputs, outputs ); } else if ( alloc_type == "pim" ) { a = new PIM( parent, name, inputs, outputs, iters ); } else if ( alloc_type == "islip" ) { a = new iSLIP_Sparse( parent, name, inputs, outputs, iters ); } else if ( alloc_type == "loa" ) { a = new LOA( parent, name, inputs, outputs ); } else if ( alloc_type == "wavefront" ) { a = new Wavefront( parent, name, inputs, outputs ); } else if ( alloc_type == "fair_wavefront" ) { a = new FairWavefront( parent, name, inputs, outputs ); } else if ( alloc_type == "prio_wavefront" ) { a = new PrioWavefront( parent, name, inputs, outputs ); } else if ( alloc_type == "select" ) { a = new SelAlloc( parent, name, inputs, outputs, iters ); } else if (alloc_type == "separable_input_first") { a = new SeparableInputFirstAllocator( parent, name, inputs, outputs, arb_type ); } else if (alloc_type == "separable_output_first") { a = new SeparableOutputFirstAllocator( parent, name, inputs, outputs, arb_type ); } //================================================== // Insert new allocators here, add another else if //================================================== return a; } <|endoftext|>
<commit_before>void lego() { // macro to visualize the lego plots generated by gAlive->RunLego gROOT->Reset(); TFile *file = new TFile("galice.root"); Float_t theta = 10; Float_t phi = 170; Int_t ncont = 50; TCanvas *cgcm2 = new TCanvas("cgcm2","gcm2",200,100,600,400); cgcm2->SetTheta(theta); cgcm2->SetPhi(phi); TH2F *hgcm2 = (TH2F*)file->Get("hgcm2"); hgcm2->SetFillColor(2); hgcm2->SetMaximum(1); hgcm2->SetContour(ncont); hgcm2->SetMaximum(50); hgcm2->Draw("lego2sphe"); TCanvas *cabso = new TCanvas("cabso","abso",100,50,600,400); cabso->SetTheta(theta); cabso->SetPhi(phi); TH2F *habso = (TH2F*)file->Get("habso"); habso->SetFillColor(2); habso->SetMaximum(1); habso->SetContour(ncont); habso->SetMaximum(1); habso->Draw("lego2sphe"); TCanvas *cradl = new TCanvas("cradl","radl",10,10,600,400); cradl->SetTheta(theta); cradl->SetPhi(phi); TH2F *hradl = (TH2F*)file->Get("hradl"); hradl->SetFillColor(2); hradl->SetMaximum(1); hradl->SetContour(ncont); hradl->SetMaximum(5); hradl->Draw("lego2sphe"); TCanvas *cetar = new TCanvas("cetar","etar",10,10,600,400); cetar->SetTheta(theta); cetar->SetPhi(phi); TH2F *hetar = (TH2F*)file->Get("hetar"); hetar->SetFillColor(2); hetar->SetMaximum(1); hetar->SetContour(ncont); hetar->SetMaximum(5); hetar->Draw("lego2sphe"); } <commit_msg>Pseudorapidity histogram removed.<commit_after>void lego() { // macro to visualize the lego plots generated by gAlive->RunLego gROOT->Reset(); TFile *file = new TFile("galice.root"); Float_t theta = 10; Float_t phi = 170; Int_t ncont = 50; TCanvas *cgcm2 = new TCanvas("cgcm2","gcm2",200,100,600,400); cgcm2->SetTheta(theta); cgcm2->SetPhi(phi); TH2F *hgcm2 = (TH2F*)file->Get("hgcm2"); hgcm2->SetFillColor(2); hgcm2->SetMaximum(1); hgcm2->SetContour(ncont); hgcm2->SetMaximum(50); hgcm2->Draw("lego2sphe"); TCanvas *cabso = new TCanvas("cabso","abso",100,50,600,400); cabso->SetTheta(theta); cabso->SetPhi(phi); TH2F *habso = (TH2F*)file->Get("habso"); habso->SetFillColor(2); habso->SetMaximum(1); habso->SetContour(ncont); habso->SetMaximum(1); habso->Draw("lego2sphe"); TCanvas *cradl = new TCanvas("cradl","radl",10,10,600,400); cradl->SetTheta(theta); cradl->SetPhi(phi); TH2F *hradl = (TH2F*)file->Get("hradl"); hradl->SetFillColor(2); hradl->SetMaximum(1); hradl->SetContour(ncont); hradl->SetMaximum(5); hradl->Draw("lego2sphe"); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: BGroups.cxx,v $ * * $Revision: 1.13 $ * * last change: $Author: obo $ $Date: 2006-09-17 02:06:47 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_connectivity.hxx" #ifndef _CONNECTIVITY_ADABAS_GROUPS_HXX_ #include "adabas/BGroups.hxx" #endif #ifndef _CONNECTIVITY_ADABAS_GROUP_HXX_ #include "adabas/BGroup.hxx" #endif #ifndef _CONNECTIVITY_ADABAS_TABLE_HXX_ #include "adabas/BTable.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_XROW_HPP_ #include <com/sun/star/sdbc/XRow.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_ #include <com/sun/star/sdbc/XResultSet.hpp> #endif #ifndef _CONNECTIVITY_SDBCX_IREFRESHABLE_HXX_ #include "sdbcx/IRefreshable.hxx" #endif #ifndef _COMPHELPER_TYPES_HXX_ #include <comphelper/types.hxx> #endif using namespace ::comphelper; using namespace connectivity; using namespace connectivity::adabas; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; // using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; typedef connectivity::sdbcx::OCollection OCollection_TYPE; // ------------------------------------------------------------------------- sdbcx::ObjectType OGroups::createObject(const ::rtl::OUString& _rName) { return new OAdabasGroup(m_pConnection,_rName); } // ------------------------------------------------------------------------- void OGroups::impl_refresh() throw(RuntimeException) { m_pParent->refreshGroups(); } // ------------------------------------------------------------------------- Reference< XPropertySet > OGroups::createDescriptor() { // OAdabasGroup* pNew = return new OAdabasGroup(m_pConnection); } // ------------------------------------------------------------------------- // XAppend sdbcx::ObjectType OGroups::appendObject( const ::rtl::OUString& _rForName, const Reference< XPropertySet >& /*descriptor*/ ) { ::rtl::OUString aSql = ::rtl::OUString::createFromAscii("CREATE USERGROUP "); ::rtl::OUString aQuote = m_pConnection->getMetaData()->getIdentifierQuoteString( ); aSql = aSql + aQuote + _rForName + aQuote; Reference< XStatement > xStmt = m_pConnection->createStatement( ); xStmt->execute(aSql); ::comphelper::disposeComponent(xStmt); return createObject( _rForName ); } // ------------------------------------------------------------------------- // XDrop void OGroups::dropObject(sal_Int32 /*_nPos*/,const ::rtl::OUString _sElementName) { ::rtl::OUString aSql = ::rtl::OUString::createFromAscii("DROP USERGROUP "); ::rtl::OUString aQuote = m_pConnection->getMetaData()->getIdentifierQuoteString( ); aSql = aSql + aQuote + _sElementName + aQuote; Reference< XStatement > xStmt = m_pConnection->createStatement( ); xStmt->execute(aSql); ::comphelper::disposeComponent(xStmt); } // ------------------------------------------------------------------------- <commit_msg>INTEGRATION: CWS changefileheader (1.13.216); FILE MERGED 2008/04/01 19:56:13 thb 1.13.216.4: #i85898# Stripping all external header guards, now manually fixing misspelled ones and other compile-time breakage 2008/04/01 15:08:34 thb 1.13.216.3: #i85898# Stripping all external header guards 2008/04/01 10:52:47 thb 1.13.216.2: #i85898# Stripping all external header guards 2008/03/28 15:23:23 rt 1.13.216.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: BGroups.cxx,v $ * $Revision: 1.14 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_connectivity.hxx" #include "adabas/BGroups.hxx" #include "adabas/BGroup.hxx" #include "adabas/BTable.hxx" #include <com/sun/star/sdbc/XRow.hpp> #include <com/sun/star/sdbc/XResultSet.hpp> #include <comphelper/types.hxx> using namespace ::comphelper; using namespace connectivity; using namespace connectivity::adabas; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; // using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; typedef connectivity::sdbcx::OCollection OCollection_TYPE; // ------------------------------------------------------------------------- sdbcx::ObjectType OGroups::createObject(const ::rtl::OUString& _rName) { return new OAdabasGroup(m_pConnection,_rName); } // ------------------------------------------------------------------------- void OGroups::impl_refresh() throw(RuntimeException) { m_pParent->refreshGroups(); } // ------------------------------------------------------------------------- Reference< XPropertySet > OGroups::createDescriptor() { // OAdabasGroup* pNew = return new OAdabasGroup(m_pConnection); } // ------------------------------------------------------------------------- // XAppend sdbcx::ObjectType OGroups::appendObject( const ::rtl::OUString& _rForName, const Reference< XPropertySet >& /*descriptor*/ ) { ::rtl::OUString aSql = ::rtl::OUString::createFromAscii("CREATE USERGROUP "); ::rtl::OUString aQuote = m_pConnection->getMetaData()->getIdentifierQuoteString( ); aSql = aSql + aQuote + _rForName + aQuote; Reference< XStatement > xStmt = m_pConnection->createStatement( ); xStmt->execute(aSql); ::comphelper::disposeComponent(xStmt); return createObject( _rForName ); } // ------------------------------------------------------------------------- // XDrop void OGroups::dropObject(sal_Int32 /*_nPos*/,const ::rtl::OUString _sElementName) { ::rtl::OUString aSql = ::rtl::OUString::createFromAscii("DROP USERGROUP "); ::rtl::OUString aQuote = m_pConnection->getMetaData()->getIdentifierQuoteString( ); aSql = aSql + aQuote + _sElementName + aQuote; Reference< XStatement > xStmt = m_pConnection->createStatement( ); xStmt->execute(aSql); ::comphelper::disposeComponent(xStmt); } // ------------------------------------------------------------------------- <|endoftext|>
<commit_before>// Copyright 2013 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 "content/browser/android/in_process/synchronous_compositor_impl.h" #include "base/auto_reset.h" #include "base/bind.h" #include "base/lazy_instance.h" #include "base/message_loop/message_loop.h" #include "cc/input/input_handler.h" #include "content/browser/android/in_process/synchronous_compositor_external_begin_frame_source.h" #include "content/browser/android/in_process/synchronous_compositor_factory_impl.h" #include "content/browser/android/in_process/synchronous_compositor_registry.h" #include "content/browser/android/in_process/synchronous_input_event_filter.h" #include "content/browser/renderer_host/render_widget_host_view_android.h" #include "content/common/input/did_overscroll_params.h" #include "content/common/input_messages.h" #include "content/public/browser/android/synchronous_compositor_client.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "ui/gl/gl_surface.h" namespace content { namespace { int GetInProcessRendererId() { content::RenderProcessHost::iterator it = content::RenderProcessHost::AllHostsIterator(); if (it.IsAtEnd()) { // There should always be one RPH in single process mode. NOTREACHED(); return 0; } int id = it.GetCurrentValue()->GetID(); it.Advance(); DCHECK(it.IsAtEnd()); // Not multiprocess compatible. return id; } base::LazyInstance<SynchronousCompositorFactoryImpl>::Leaky g_factory = LAZY_INSTANCE_INITIALIZER; } // namespace DEFINE_WEB_CONTENTS_USER_DATA_KEY(SynchronousCompositorImpl); // static SynchronousCompositorImpl* SynchronousCompositorImpl::FromID(int process_id, int routing_id) { if (g_factory == nullptr) return nullptr; RenderViewHost* rvh = RenderViewHost::FromID(process_id, routing_id); if (!rvh) return nullptr; WebContents* contents = WebContents::FromRenderViewHost(rvh); if (!contents) return nullptr; return FromWebContents(contents); } SynchronousCompositorImpl* SynchronousCompositorImpl::FromRoutingID( int routing_id) { return FromID(GetInProcessRendererId(), routing_id); } SynchronousCompositorImpl::SynchronousCompositorImpl(WebContents* contents) : compositor_client_(nullptr), output_surface_(nullptr), begin_frame_source_(nullptr), contents_(contents), routing_id_(contents->GetRoutingID()), input_handler_(nullptr), registered_with_client_(false), is_active_(true), renderer_needs_begin_frames_(false), weak_ptr_factory_(this) { DCHECK(contents); DCHECK_NE(routing_id_, MSG_ROUTING_NONE); } SynchronousCompositorImpl::~SynchronousCompositorImpl() { DCHECK(!output_surface_); DCHECK(!begin_frame_source_); DCHECK(!input_handler_); } void SynchronousCompositorImpl::SetClient( SynchronousCompositorClient* compositor_client) { DCHECK(CalledOnValidThread()); DCHECK_IMPLIES(compositor_client, !compositor_client_); DCHECK_IMPLIES(!compositor_client, compositor_client_); if (!compositor_client) { SynchronousCompositorRegistry::GetInstance()->UnregisterCompositor( routing_id_, this); } compositor_client_ = compositor_client; // SetClient is essentially the constructor and destructor of // SynchronousCompositorImpl. if (compositor_client_) { SynchronousCompositorRegistry::GetInstance()->RegisterCompositor( routing_id_, this); } } void SynchronousCompositorImpl::RegisterWithClient() { DCHECK(CalledOnValidThread()); DCHECK(compositor_client_); DCHECK(output_surface_); DCHECK(input_handler_); DCHECK(!registered_with_client_); registered_with_client_ = true; compositor_client_->DidInitializeCompositor(this); output_surface_->SetTreeActivationCallback( base::Bind(&SynchronousCompositorImpl::DidActivatePendingTree, weak_ptr_factory_.GetWeakPtr())); // Setting the delegate causes UpdateRootLayerState immediately so do it // after setting the client. input_handler_->SetRootLayerScrollOffsetDelegate(this); } // static void SynchronousCompositor::SetGpuService( scoped_refptr<gpu::InProcessCommandBuffer::Service> service) { g_factory.Get().SetDeferredGpuService(service); } // static void SynchronousCompositor::SetRecordFullDocument(bool record_full_document) { g_factory.Get().SetRecordFullDocument(record_full_document); } void SynchronousCompositorImpl::DidInitializeRendererObjects( SynchronousCompositorOutputSurface* output_surface, SynchronousCompositorExternalBeginFrameSource* begin_frame_source, cc::InputHandler* input_handler) { DCHECK(!output_surface_); DCHECK(!begin_frame_source_); DCHECK(output_surface); DCHECK(begin_frame_source); DCHECK(compositor_client_); DCHECK(input_handler); output_surface_ = output_surface; begin_frame_source_ = begin_frame_source; input_handler_ = input_handler; output_surface_->SetCompositor(this); begin_frame_source_->SetCompositor(this); } void SynchronousCompositorImpl::DidDestroyRendererObjects() { DCHECK(output_surface_); DCHECK(begin_frame_source_); DCHECK(compositor_client_); if (registered_with_client_) { input_handler_->SetRootLayerScrollOffsetDelegate(nullptr); output_surface_->SetTreeActivationCallback(base::Closure()); compositor_client_->DidDestroyCompositor(this); registered_with_client_ = false; } begin_frame_source_->SetCompositor(nullptr); output_surface_->SetCompositor(nullptr); input_handler_ = nullptr; begin_frame_source_ = nullptr; output_surface_ = nullptr; } scoped_ptr<cc::CompositorFrame> SynchronousCompositorImpl::DemandDrawHw( gfx::Size surface_size, const gfx::Transform& transform, gfx::Rect viewport, gfx::Rect clip, gfx::Rect viewport_rect_for_tile_priority, const gfx::Transform& transform_for_tile_priority) { DCHECK(CalledOnValidThread()); DCHECK(output_surface_); DCHECK(compositor_client_); DCHECK(begin_frame_source_); scoped_ptr<cc::CompositorFrame> frame = output_surface_->DemandDrawHw(surface_size, transform, viewport, clip, viewport_rect_for_tile_priority, transform_for_tile_priority); if (frame.get()) UpdateFrameMetaData(frame->metadata); return frame.Pass(); } void SynchronousCompositorImpl::ReturnResources( const cc::CompositorFrameAck& frame_ack) { DCHECK(CalledOnValidThread()); output_surface_->ReturnResources(frame_ack); } bool SynchronousCompositorImpl::DemandDrawSw(SkCanvas* canvas) { DCHECK(CalledOnValidThread()); DCHECK(output_surface_); DCHECK(compositor_client_); DCHECK(begin_frame_source_); scoped_ptr<cc::CompositorFrame> frame = output_surface_->DemandDrawSw(canvas); if (frame.get()) UpdateFrameMetaData(frame->metadata); return !!frame.get(); } void SynchronousCompositorImpl::UpdateFrameMetaData( const cc::CompositorFrameMetadata& frame_metadata) { RenderWidgetHostViewAndroid* rwhv = static_cast<RenderWidgetHostViewAndroid*>( contents_->GetRenderWidgetHostView()); if (rwhv) rwhv->SynchronousFrameMetadata(frame_metadata); DeliverMessages(); } void SynchronousCompositorImpl::SetMemoryPolicy(size_t bytes_limit) { DCHECK(CalledOnValidThread()); DCHECK(output_surface_); size_t current_bytes_limit = output_surface_->GetMemoryPolicy(); output_surface_->SetMemoryPolicy(bytes_limit); if (bytes_limit && !current_bytes_limit) { g_factory.Get().CompositorInitializedHardwareDraw(); } else if (!bytes_limit && current_bytes_limit) { g_factory.Get().CompositorReleasedHardwareDraw(); } } void SynchronousCompositorImpl::PostInvalidate() { DCHECK(CalledOnValidThread()); DCHECK(compositor_client_); if (registered_with_client_) compositor_client_->PostInvalidate(); } void SynchronousCompositorImpl::DidChangeRootLayerScrollOffset() { if (input_handler_) input_handler_->OnRootLayerDelegatedScrollOffsetChanged(); } void SynchronousCompositorImpl::SetIsActive(bool is_active) { TRACE_EVENT1("cc", "SynchronousCompositorImpl::SetIsActive", "is_active", is_active); is_active_ = is_active; UpdateNeedsBeginFrames(); } void SynchronousCompositorImpl::OnNeedsBeginFramesChange( bool needs_begin_frames) { renderer_needs_begin_frames_ = needs_begin_frames; UpdateNeedsBeginFrames(); } void SynchronousCompositorImpl::BeginFrame(const cc::BeginFrameArgs& args) { if (!registered_with_client_) { RegisterWithClient(); DCHECK(registered_with_client_); } if (begin_frame_source_) begin_frame_source_->BeginFrame(args); } void SynchronousCompositorImpl::UpdateNeedsBeginFrames() { RenderWidgetHostViewAndroid* rwhv = static_cast<RenderWidgetHostViewAndroid*>( contents_->GetRenderWidgetHostView()); if (rwhv) rwhv->OnSetNeedsBeginFrames(is_active_ && renderer_needs_begin_frames_); } void SynchronousCompositorImpl::DidOverscroll( const DidOverscrollParams& params) { DCHECK(compositor_client_); if (registered_with_client_) { compositor_client_->DidOverscroll(params.accumulated_overscroll, params.latest_overscroll_delta, params.current_fling_velocity); } } void SynchronousCompositorImpl::DidStopFlinging() { // It's important that the fling-end notification follow the same path as it // takes on other platforms (using an IPC). This ensures consistent // bookkeeping at all stages of the input pipeline. contents_->GetRenderProcessHost()->OnMessageReceived( InputHostMsg_DidStopFlinging(routing_id_)); } InputEventAckState SynchronousCompositorImpl::HandleInputEvent( const blink::WebInputEvent& input_event) { DCHECK(CalledOnValidThread()); return g_factory.Get().synchronous_input_event_filter()->HandleInputEvent( contents_->GetRoutingID(), input_event); } void SynchronousCompositorImpl::DeliverMessages() { ScopedVector<IPC::Message> messages; output_surface_->GetMessagesToDeliver(&messages); RenderProcessHost* rph = contents_->GetRenderProcessHost(); for (ScopedVector<IPC::Message>::const_iterator i = messages.begin(); i != messages.end(); ++i) { rph->OnMessageReceived(**i); } } void SynchronousCompositorImpl::DidActivatePendingTree() { DCHECK(compositor_client_); if (registered_with_client_) compositor_client_->DidUpdateContent(); DeliverMessages(); } gfx::ScrollOffset SynchronousCompositorImpl::GetTotalScrollOffset() { DCHECK(CalledOnValidThread()); DCHECK(compositor_client_); if (!registered_with_client_) return gfx::ScrollOffset(); // TODO(miletus): Make GetTotalRootLayerScrollOffset return // ScrollOffset. crbug.com/414283. return gfx::ScrollOffset( compositor_client_->GetTotalRootLayerScrollOffset()); } bool SynchronousCompositorImpl::IsExternalFlingActive() const { DCHECK(CalledOnValidThread()); DCHECK(compositor_client_); if (!registered_with_client_) return false; return compositor_client_->IsExternalFlingActive(); } void SynchronousCompositorImpl::UpdateRootLayerState( const gfx::ScrollOffset& total_scroll_offset, const gfx::ScrollOffset& max_scroll_offset, const gfx::SizeF& scrollable_size, float page_scale_factor, float min_page_scale_factor, float max_page_scale_factor) { DCHECK(CalledOnValidThread()); DCHECK(compositor_client_); if (registered_with_client_) { // TODO(miletus): Pass in ScrollOffset. crbug.com/414283. compositor_client_->UpdateRootLayerState( gfx::ScrollOffsetToVector2dF(total_scroll_offset), gfx::ScrollOffsetToVector2dF(max_scroll_offset), scrollable_size, page_scale_factor, min_page_scale_factor, max_page_scale_factor); } } // Not using base::NonThreadSafe as we want to enforce a more exacting threading // requirement: SynchronousCompositorImpl() must only be used on the UI thread. bool SynchronousCompositorImpl::CalledOnValidThread() const { return BrowserThread::CurrentlyOn(BrowserThread::UI); } // static void SynchronousCompositor::SetClientForWebContents( WebContents* contents, SynchronousCompositorClient* client) { DCHECK(contents); if (client) { g_factory.Get(); // Ensure it's initialized. SynchronousCompositorImpl::CreateForWebContents(contents); } SynchronousCompositorImpl* instance = SynchronousCompositorImpl::FromWebContents(contents); DCHECK(instance); instance->SetClient(client); } } // namespace content <commit_msg>Fix crash in sync compositor registration<commit_after>// Copyright 2013 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 "content/browser/android/in_process/synchronous_compositor_impl.h" #include "base/auto_reset.h" #include "base/bind.h" #include "base/lazy_instance.h" #include "base/message_loop/message_loop.h" #include "cc/input/input_handler.h" #include "content/browser/android/in_process/synchronous_compositor_external_begin_frame_source.h" #include "content/browser/android/in_process/synchronous_compositor_factory_impl.h" #include "content/browser/android/in_process/synchronous_compositor_registry.h" #include "content/browser/android/in_process/synchronous_input_event_filter.h" #include "content/browser/renderer_host/render_widget_host_view_android.h" #include "content/common/input/did_overscroll_params.h" #include "content/common/input_messages.h" #include "content/public/browser/android/synchronous_compositor_client.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "ui/gl/gl_surface.h" namespace content { namespace { int GetInProcessRendererId() { content::RenderProcessHost::iterator it = content::RenderProcessHost::AllHostsIterator(); if (it.IsAtEnd()) { // There should always be one RPH in single process mode. NOTREACHED(); return 0; } int id = it.GetCurrentValue()->GetID(); it.Advance(); DCHECK(it.IsAtEnd()); // Not multiprocess compatible. return id; } base::LazyInstance<SynchronousCompositorFactoryImpl>::Leaky g_factory = LAZY_INSTANCE_INITIALIZER; } // namespace DEFINE_WEB_CONTENTS_USER_DATA_KEY(SynchronousCompositorImpl); // static SynchronousCompositorImpl* SynchronousCompositorImpl::FromID(int process_id, int routing_id) { if (g_factory == nullptr) return nullptr; RenderViewHost* rvh = RenderViewHost::FromID(process_id, routing_id); if (!rvh) return nullptr; WebContents* contents = WebContents::FromRenderViewHost(rvh); if (!contents) return nullptr; return FromWebContents(contents); } SynchronousCompositorImpl* SynchronousCompositorImpl::FromRoutingID( int routing_id) { return FromID(GetInProcessRendererId(), routing_id); } SynchronousCompositorImpl::SynchronousCompositorImpl(WebContents* contents) : compositor_client_(nullptr), output_surface_(nullptr), begin_frame_source_(nullptr), contents_(contents), routing_id_(contents->GetRoutingID()), input_handler_(nullptr), registered_with_client_(false), is_active_(true), renderer_needs_begin_frames_(false), weak_ptr_factory_(this) { DCHECK(contents); DCHECK_NE(routing_id_, MSG_ROUTING_NONE); } SynchronousCompositorImpl::~SynchronousCompositorImpl() { DCHECK(!output_surface_); DCHECK(!begin_frame_source_); DCHECK(!input_handler_); } void SynchronousCompositorImpl::SetClient( SynchronousCompositorClient* compositor_client) { DCHECK(CalledOnValidThread()); DCHECK_IMPLIES(compositor_client, !compositor_client_); DCHECK_IMPLIES(!compositor_client, compositor_client_); if (!compositor_client) { SynchronousCompositorRegistry::GetInstance()->UnregisterCompositor( routing_id_, this); } compositor_client_ = compositor_client; // SetClient is essentially the constructor and destructor of // SynchronousCompositorImpl. if (compositor_client_) { SynchronousCompositorRegistry::GetInstance()->RegisterCompositor( routing_id_, this); } } void SynchronousCompositorImpl::RegisterWithClient() { DCHECK(CalledOnValidThread()); DCHECK(compositor_client_); DCHECK(output_surface_); DCHECK(input_handler_); DCHECK(!registered_with_client_); registered_with_client_ = true; compositor_client_->DidInitializeCompositor(this); output_surface_->SetTreeActivationCallback( base::Bind(&SynchronousCompositorImpl::DidActivatePendingTree, weak_ptr_factory_.GetWeakPtr())); // Setting the delegate causes UpdateRootLayerState immediately so do it // after setting the client. input_handler_->SetRootLayerScrollOffsetDelegate(this); } // static void SynchronousCompositor::SetGpuService( scoped_refptr<gpu::InProcessCommandBuffer::Service> service) { g_factory.Get().SetDeferredGpuService(service); } // static void SynchronousCompositor::SetRecordFullDocument(bool record_full_document) { g_factory.Get().SetRecordFullDocument(record_full_document); } void SynchronousCompositorImpl::DidInitializeRendererObjects( SynchronousCompositorOutputSurface* output_surface, SynchronousCompositorExternalBeginFrameSource* begin_frame_source, cc::InputHandler* input_handler) { DCHECK(!output_surface_); DCHECK(!begin_frame_source_); DCHECK(output_surface); DCHECK(begin_frame_source); DCHECK(compositor_client_); DCHECK(input_handler); output_surface_ = output_surface; begin_frame_source_ = begin_frame_source; input_handler_ = input_handler; output_surface_->SetCompositor(this); begin_frame_source_->SetCompositor(this); } void SynchronousCompositorImpl::DidDestroyRendererObjects() { DCHECK(output_surface_); DCHECK(begin_frame_source_); DCHECK(compositor_client_); if (registered_with_client_) { input_handler_->SetRootLayerScrollOffsetDelegate(nullptr); output_surface_->SetTreeActivationCallback(base::Closure()); compositor_client_->DidDestroyCompositor(this); registered_with_client_ = false; } begin_frame_source_->SetCompositor(nullptr); output_surface_->SetCompositor(nullptr); input_handler_ = nullptr; begin_frame_source_ = nullptr; output_surface_ = nullptr; } scoped_ptr<cc::CompositorFrame> SynchronousCompositorImpl::DemandDrawHw( gfx::Size surface_size, const gfx::Transform& transform, gfx::Rect viewport, gfx::Rect clip, gfx::Rect viewport_rect_for_tile_priority, const gfx::Transform& transform_for_tile_priority) { DCHECK(CalledOnValidThread()); DCHECK(output_surface_); DCHECK(compositor_client_); DCHECK(begin_frame_source_); scoped_ptr<cc::CompositorFrame> frame = output_surface_->DemandDrawHw(surface_size, transform, viewport, clip, viewport_rect_for_tile_priority, transform_for_tile_priority); if (frame.get()) UpdateFrameMetaData(frame->metadata); return frame.Pass(); } void SynchronousCompositorImpl::ReturnResources( const cc::CompositorFrameAck& frame_ack) { DCHECK(CalledOnValidThread()); output_surface_->ReturnResources(frame_ack); } bool SynchronousCompositorImpl::DemandDrawSw(SkCanvas* canvas) { DCHECK(CalledOnValidThread()); DCHECK(output_surface_); DCHECK(compositor_client_); DCHECK(begin_frame_source_); scoped_ptr<cc::CompositorFrame> frame = output_surface_->DemandDrawSw(canvas); if (frame.get()) UpdateFrameMetaData(frame->metadata); return !!frame.get(); } void SynchronousCompositorImpl::UpdateFrameMetaData( const cc::CompositorFrameMetadata& frame_metadata) { RenderWidgetHostViewAndroid* rwhv = static_cast<RenderWidgetHostViewAndroid*>( contents_->GetRenderWidgetHostView()); if (rwhv) rwhv->SynchronousFrameMetadata(frame_metadata); DeliverMessages(); } void SynchronousCompositorImpl::SetMemoryPolicy(size_t bytes_limit) { DCHECK(CalledOnValidThread()); DCHECK(output_surface_); size_t current_bytes_limit = output_surface_->GetMemoryPolicy(); output_surface_->SetMemoryPolicy(bytes_limit); if (bytes_limit && !current_bytes_limit) { g_factory.Get().CompositorInitializedHardwareDraw(); } else if (!bytes_limit && current_bytes_limit) { g_factory.Get().CompositorReleasedHardwareDraw(); } } void SynchronousCompositorImpl::PostInvalidate() { DCHECK(CalledOnValidThread()); DCHECK(compositor_client_); if (registered_with_client_) compositor_client_->PostInvalidate(); } void SynchronousCompositorImpl::DidChangeRootLayerScrollOffset() { if (input_handler_) input_handler_->OnRootLayerDelegatedScrollOffsetChanged(); } void SynchronousCompositorImpl::SetIsActive(bool is_active) { TRACE_EVENT1("cc", "SynchronousCompositorImpl::SetIsActive", "is_active", is_active); is_active_ = is_active; UpdateNeedsBeginFrames(); } void SynchronousCompositorImpl::OnNeedsBeginFramesChange( bool needs_begin_frames) { renderer_needs_begin_frames_ = needs_begin_frames; UpdateNeedsBeginFrames(); } void SynchronousCompositorImpl::BeginFrame(const cc::BeginFrameArgs& args) { if (!registered_with_client_ && is_active_ && renderer_needs_begin_frames_) { // Make sure this is a BeginFrame that renderer side explicitly requested. // Otherwise it is possible renderer objects not initialized. RegisterWithClient(); DCHECK(registered_with_client_); } if (begin_frame_source_) begin_frame_source_->BeginFrame(args); } void SynchronousCompositorImpl::UpdateNeedsBeginFrames() { RenderWidgetHostViewAndroid* rwhv = static_cast<RenderWidgetHostViewAndroid*>( contents_->GetRenderWidgetHostView()); if (rwhv) rwhv->OnSetNeedsBeginFrames(is_active_ && renderer_needs_begin_frames_); } void SynchronousCompositorImpl::DidOverscroll( const DidOverscrollParams& params) { DCHECK(compositor_client_); if (registered_with_client_) { compositor_client_->DidOverscroll(params.accumulated_overscroll, params.latest_overscroll_delta, params.current_fling_velocity); } } void SynchronousCompositorImpl::DidStopFlinging() { // It's important that the fling-end notification follow the same path as it // takes on other platforms (using an IPC). This ensures consistent // bookkeeping at all stages of the input pipeline. contents_->GetRenderProcessHost()->OnMessageReceived( InputHostMsg_DidStopFlinging(routing_id_)); } InputEventAckState SynchronousCompositorImpl::HandleInputEvent( const blink::WebInputEvent& input_event) { DCHECK(CalledOnValidThread()); return g_factory.Get().synchronous_input_event_filter()->HandleInputEvent( contents_->GetRoutingID(), input_event); } void SynchronousCompositorImpl::DeliverMessages() { ScopedVector<IPC::Message> messages; output_surface_->GetMessagesToDeliver(&messages); RenderProcessHost* rph = contents_->GetRenderProcessHost(); for (ScopedVector<IPC::Message>::const_iterator i = messages.begin(); i != messages.end(); ++i) { rph->OnMessageReceived(**i); } } void SynchronousCompositorImpl::DidActivatePendingTree() { DCHECK(compositor_client_); if (registered_with_client_) compositor_client_->DidUpdateContent(); DeliverMessages(); } gfx::ScrollOffset SynchronousCompositorImpl::GetTotalScrollOffset() { DCHECK(CalledOnValidThread()); DCHECK(compositor_client_); if (!registered_with_client_) return gfx::ScrollOffset(); // TODO(miletus): Make GetTotalRootLayerScrollOffset return // ScrollOffset. crbug.com/414283. return gfx::ScrollOffset( compositor_client_->GetTotalRootLayerScrollOffset()); } bool SynchronousCompositorImpl::IsExternalFlingActive() const { DCHECK(CalledOnValidThread()); DCHECK(compositor_client_); if (!registered_with_client_) return false; return compositor_client_->IsExternalFlingActive(); } void SynchronousCompositorImpl::UpdateRootLayerState( const gfx::ScrollOffset& total_scroll_offset, const gfx::ScrollOffset& max_scroll_offset, const gfx::SizeF& scrollable_size, float page_scale_factor, float min_page_scale_factor, float max_page_scale_factor) { DCHECK(CalledOnValidThread()); DCHECK(compositor_client_); if (registered_with_client_) { // TODO(miletus): Pass in ScrollOffset. crbug.com/414283. compositor_client_->UpdateRootLayerState( gfx::ScrollOffsetToVector2dF(total_scroll_offset), gfx::ScrollOffsetToVector2dF(max_scroll_offset), scrollable_size, page_scale_factor, min_page_scale_factor, max_page_scale_factor); } } // Not using base::NonThreadSafe as we want to enforce a more exacting threading // requirement: SynchronousCompositorImpl() must only be used on the UI thread. bool SynchronousCompositorImpl::CalledOnValidThread() const { return BrowserThread::CurrentlyOn(BrowserThread::UI); } // static void SynchronousCompositor::SetClientForWebContents( WebContents* contents, SynchronousCompositorClient* client) { DCHECK(contents); if (client) { g_factory.Get(); // Ensure it's initialized. SynchronousCompositorImpl::CreateForWebContents(contents); } SynchronousCompositorImpl* instance = SynchronousCompositorImpl::FromWebContents(contents); DCHECK(instance); instance->SetClient(client); } } // namespace content <|endoftext|>
<commit_before>/** * @file * @brief Implementation of object with set of particles at pixel * @copyright Copyright (c) 2017-2019 CERN and the Allpix Squared authors. * This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md". * In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an * Intergovernmental Organization or submit itself to any jurisdiction. */ #include "PixelCharge.hpp" #include <set> #include "exceptions.h" using namespace allpix; PixelCharge::PixelCharge(Pixel pixel, unsigned int charge, std::vector<const PropagatedCharge*> propagated_charges) : pixel_(std::move(pixel)), charge_(charge) { // Unique set of MC particles std::set<TRef> unique_particles; // Store all propagated charges and their MC particles for(auto& propagated_charge : propagated_charges) { propagated_charges_.push_back(const_cast<PropagatedCharge*>(propagated_charge)); // NOLINT unique_particles.insert(propagated_charge->mc_particle_); } // Store the MC particle references for(auto& mc_particle : unique_particles) { mc_particles_.push_back(mc_particle); } // No pulse provided, set full charge in first bin: pulse_.addCharge(charge, 0); } // WARNING PixelCharge always returns a positive "collected" charge... PixelCharge::PixelCharge(Pixel pixel, Pulse pulse, std::vector<const PropagatedCharge*> propagated_charges) : PixelCharge(std::move(pixel), static_cast<unsigned int>(std::abs(pulse.getCharge())), std::move(propagated_charges)) { pulse_ = std::move(pulse); } const Pixel& PixelCharge::getPixel() const { return pixel_; } Pixel::Index PixelCharge::getIndex() const { return getPixel().getIndex(); } unsigned int PixelCharge::getCharge() const { return charge_; } const Pulse& PixelCharge::getPulse() const { return pulse_; } /** * @throws MissingReferenceException If the pointed object is not in scope * * Objects are stored as vector of TRef and can only be accessed if pointed objects are in scope */ std::vector<const PropagatedCharge*> PixelCharge::getPropagatedCharges() const { // FIXME: This is not very efficient unfortunately std::vector<const PropagatedCharge*> propagated_charges; for(auto& propagated_charge : propagated_charges_) { if(!propagated_charge.IsValid() || propagated_charge.GetObject() == nullptr) { throw MissingReferenceException(typeid(*this), typeid(PropagatedCharge)); } propagated_charges.emplace_back(dynamic_cast<PropagatedCharge*>(propagated_charge.GetObject())); } return propagated_charges; } /** * @throws MissingReferenceException If the pointed object is not in scope * * MCParticles can only be fetched if the full history of objects are in scope and stored */ std::vector<const MCParticle*> PixelCharge::getMCParticles() const { std::vector<const MCParticle*> mc_particles; for(auto& mc_particle : mc_particles_) { if(!mc_particle.IsValid() || mc_particle.GetObject() == nullptr) { throw MissingReferenceException(typeid(*this), typeid(MCParticle)); } mc_particles.emplace_back(dynamic_cast<MCParticle*>(mc_particle.GetObject())); } // Return as a vector of mc particles return mc_particles; } void PixelCharge::print(std::ostream& out) const { auto local_center_location = pixel_.getLocalCenter(); auto global_center_location = pixel_.getGlobalCenter(); auto pixel_size = pixel_.getSize(); out << "--- Pixel charge information\n"; out << "Local Position: (" << local_center_location.X() << ", " << local_center_location.Y() << ", " << local_center_location.Z() << ") mm\n" << "Global Position: (" << global_center_location.X() << ", " << global_center_location.Y() << ", " << global_center_location.Z() << ") mm\n" << "\nCharge: " << charge_ << " ke" << "\nSize: " << pixel_size.X() << ' ' << pixel_size.Y() << '\n'; } <commit_msg>Remove the empty line between PixelCharge printed data<commit_after>/** * @file * @brief Implementation of object with set of particles at pixel * @copyright Copyright (c) 2017-2019 CERN and the Allpix Squared authors. * This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md". * In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an * Intergovernmental Organization or submit itself to any jurisdiction. */ #include "PixelCharge.hpp" #include <set> #include "exceptions.h" using namespace allpix; PixelCharge::PixelCharge(Pixel pixel, unsigned int charge, std::vector<const PropagatedCharge*> propagated_charges) : pixel_(std::move(pixel)), charge_(charge) { // Unique set of MC particles std::set<TRef> unique_particles; // Store all propagated charges and their MC particles for(auto& propagated_charge : propagated_charges) { propagated_charges_.push_back(const_cast<PropagatedCharge*>(propagated_charge)); // NOLINT unique_particles.insert(propagated_charge->mc_particle_); } // Store the MC particle references for(auto& mc_particle : unique_particles) { mc_particles_.push_back(mc_particle); } // No pulse provided, set full charge in first bin: pulse_.addCharge(charge, 0); } // WARNING PixelCharge always returns a positive "collected" charge... PixelCharge::PixelCharge(Pixel pixel, Pulse pulse, std::vector<const PropagatedCharge*> propagated_charges) : PixelCharge(std::move(pixel), static_cast<unsigned int>(std::abs(pulse.getCharge())), std::move(propagated_charges)) { pulse_ = std::move(pulse); } const Pixel& PixelCharge::getPixel() const { return pixel_; } Pixel::Index PixelCharge::getIndex() const { return getPixel().getIndex(); } unsigned int PixelCharge::getCharge() const { return charge_; } const Pulse& PixelCharge::getPulse() const { return pulse_; } /** * @throws MissingReferenceException If the pointed object is not in scope * * Objects are stored as vector of TRef and can only be accessed if pointed objects are in scope */ std::vector<const PropagatedCharge*> PixelCharge::getPropagatedCharges() const { // FIXME: This is not very efficient unfortunately std::vector<const PropagatedCharge*> propagated_charges; for(auto& propagated_charge : propagated_charges_) { if(!propagated_charge.IsValid() || propagated_charge.GetObject() == nullptr) { throw MissingReferenceException(typeid(*this), typeid(PropagatedCharge)); } propagated_charges.emplace_back(dynamic_cast<PropagatedCharge*>(propagated_charge.GetObject())); } return propagated_charges; } /** * @throws MissingReferenceException If the pointed object is not in scope * * MCParticles can only be fetched if the full history of objects are in scope and stored */ std::vector<const MCParticle*> PixelCharge::getMCParticles() const { std::vector<const MCParticle*> mc_particles; for(auto& mc_particle : mc_particles_) { if(!mc_particle.IsValid() || mc_particle.GetObject() == nullptr) { throw MissingReferenceException(typeid(*this), typeid(MCParticle)); } mc_particles.emplace_back(dynamic_cast<MCParticle*>(mc_particle.GetObject())); } // Return as a vector of mc particles return mc_particles; } void PixelCharge::print(std::ostream& out) const { auto local_center_location = pixel_.getLocalCenter(); auto global_center_location = pixel_.getGlobalCenter(); auto pixel_size = pixel_.getSize(); out << "--- Pixel charge information\n"; out << "Local Position: (" << local_center_location.X() << ", " << local_center_location.Y() << ", " << local_center_location.Z() << ") mm\n" << "Global Position: (" << global_center_location.X() << ", " << global_center_location.Y() << ", " << global_center_location.Z() << ") mm\n" << "Charge: " << charge_ << " ke\n" << "Size: " << pixel_size.X() << ' ' << pixel_size.Y() << '\n'; } <|endoftext|>