text stringlengths 54 60.6k |
|---|
<commit_before>#include "entity_description.h"
#include "entity_system/entity.h"
#include "../components/name_component.h"
#include "../components/gun_component.h"
#include "../components/damage_component.h"
#include "../components/container_component.h"
#include "../components/item_component.h"
#include "../detail/inventory_utils.h"
#include "../detail/inventory_slot.h"
#include "../detail/inventory_slot_id.h"
#include "log.h"
#include "stream.h"
textual_description description_of_entity(augs::entity_id id) {
return description_by_entity_name(id->get<components::name>().id);
}
std::wstring describe_properties(augs::entity_id id) {
std::wostringstream result;
auto* gun = id->find<components::gun>();
auto* damage = id->find<components::damage>();
auto* container = id->find<components::container>();
auto* item = id->find<components::item>();
if (item) {
if (item->categories_for_slot_compatibility != 0)
result << L"[color=vsblue]" << describe_item_compatibility_categories(item->categories_for_slot_compatibility) << L"[/color]\n";
result << "Occupies: [color=vscyan]" << format_space_units(calculate_space_occupied_with_children(id)) << " [/color]";
if (item->charges > 1)
result << "[color=vsdarkgray](" << format_space_units(item->space_occupied_per_charge) << L" each)[/color]";
result << L"\n";
}
if (gun) {
result << L"Muzzle velocity: [color=vscyan]" << (gun->muzzle_velocity.first + gun->muzzle_velocity.second) / 2
<< L"[/color]\nDamage multiplier: [color=vscyan]" << std::fixed << std::setprecision(1) << gun->damage_multiplier << L"[/color]\n";
}
if (damage) {
result << L"Base damage: [color=vscyan]" << damage->amount << L"[/color]\n";
if (damage->constrain_distance)
result << L"Max distance: [color=vscyan]" << damage->max_distance << L"[/color]\n";
if (damage->constrain_lifetime)
result << L"Max lifetime: [color=vscyan]" << damage->max_lifetime_ms << L" ms[/color]\n";
}
if (id.has(slot_function::ITEM_DEPOSIT)) {
auto depo = id[slot_function::ITEM_DEPOSIT];
auto children_space = format_space_units(depo->calculate_free_space_with_children());
auto with_parents_space = format_space_units(depo.calculate_free_space_with_parent_containers());
result << L"Deposit space: [color=vsgreen]" << format_space_units(depo.calculate_free_space_with_parent_containers()) << L"[/color]/";
if (children_space != with_parents_space)
result << L"[color=vsyellow]" << format_space_units(depo->calculate_free_space_with_children()) << L"[/color]/";
result << L"[color=vscyan]" << format_space_units(depo->space_available) << L"[/color]\n";
}
std::wstring out;
if (id.has(sub_entity_name::BULLET_ROUND_DEFINITION)) {
out = result.str() + describe_properties(id[sub_entity_name::BULLET_ROUND_DEFINITION]);
return out;
}
else {
out = result.str();
return out.substr(0, out.length() - 1);
}
}
std::wstring describe_slot(inventory_slot_id id) {
auto text = describe_slot_function(id.type);
auto catcolor = id->for_categorized_items_only ? L"violet" : L"vsblue";
return text.name + L"\n[color=vslightgray]Allows: [/color][color=" + catcolor + L"]" + describe_item_compatibility_categories(id->category_allowed) + L"[/color][color=vsdarkgray]\n" +
text.details + L"[/color]";
}<commit_msg>space occupied if empty<commit_after>#include "entity_description.h"
#include "entity_system/entity.h"
#include "../components/name_component.h"
#include "../components/gun_component.h"
#include "../components/damage_component.h"
#include "../components/container_component.h"
#include "../components/item_component.h"
#include "../detail/inventory_utils.h"
#include "../detail/inventory_slot.h"
#include "../detail/inventory_slot_id.h"
#include "log.h"
#include "stream.h"
textual_description description_of_entity(augs::entity_id id) {
return description_by_entity_name(id->get<components::name>().id);
}
std::wstring describe_properties(augs::entity_id id) {
std::wostringstream result;
auto* gun = id->find<components::gun>();
auto* damage = id->find<components::damage>();
auto* container = id->find<components::container>();
auto* item = id->find<components::item>();
if (item) {
if (item->categories_for_slot_compatibility != 0)
result << L"[color=vsblue]" << describe_item_compatibility_categories(item->categories_for_slot_compatibility) << L"[/color]\n";
auto total_occupied = format_space_units(calculate_space_occupied_with_children(id));
auto per_charge = format_space_units(item->space_occupied_per_charge);
result << "Occupies: [color=vscyan]" << total_occupied << " [/color]";
if (item->charges > 1)
result << "[color=vsdarkgray](" << per_charge << L" each)[/color]";
else if(container && total_occupied != per_charge)
result << "[color=vsdarkgray](" << per_charge << L" if empty)[/color]";
result << L"\n";
}
if (gun) {
result << L"Muzzle velocity: [color=vscyan]" << (gun->muzzle_velocity.first + gun->muzzle_velocity.second) / 2
<< L"[/color]\nDamage multiplier: [color=vscyan]" << std::fixed << std::setprecision(1) << gun->damage_multiplier << L"[/color]\n";
}
if (damage) {
result << L"Base damage: [color=vscyan]" << damage->amount << L"[/color]\n";
if (damage->constrain_distance)
result << L"Max distance: [color=vscyan]" << damage->max_distance << L"[/color]\n";
if (damage->constrain_lifetime)
result << L"Max lifetime: [color=vscyan]" << damage->max_lifetime_ms << L" ms[/color]\n";
}
if (id.has(slot_function::ITEM_DEPOSIT)) {
auto depo = id[slot_function::ITEM_DEPOSIT];
auto children_space = format_space_units(depo->calculate_free_space_with_children());
auto with_parents_space = format_space_units(depo.calculate_free_space_with_parent_containers());
result << L"Deposit space: [color=vsgreen]" << format_space_units(depo.calculate_free_space_with_parent_containers()) << L"[/color]/";
if (children_space != with_parents_space)
result << L"[color=vsyellow]" << format_space_units(depo->calculate_free_space_with_children()) << L"[/color]/";
result << L"[color=vscyan]" << format_space_units(depo->space_available) << L"[/color]\n";
}
std::wstring out;
if (id.has(sub_entity_name::BULLET_ROUND_DEFINITION)) {
out = result.str() + describe_properties(id[sub_entity_name::BULLET_ROUND_DEFINITION]);
return out;
}
else {
out = result.str();
return out.substr(0, out.length() - 1);
}
}
std::wstring describe_slot(inventory_slot_id id) {
auto text = describe_slot_function(id.type);
auto catcolor = id->for_categorized_items_only ? L"violet" : L"vsblue";
return text.name + L"\n[color=vslightgray]Allows: [/color][color=" + catcolor + L"]" + describe_item_compatibility_categories(id->category_allowed) + L"[/color][color=vsdarkgray]\n" +
text.details + L"[/color]";
}<|endoftext|> |
<commit_before>// Copyright (c) 2018 Google LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "source/val/validate.h"
#include <algorithm>
#include "source/opcode.h"
#include "source/spirv_target_env.h"
#include "source/val/instruction.h"
#include "source/val/validation_state.h"
namespace spvtools {
namespace val {
namespace {
spv_result_t ValidateEntryPoint(ValidationState_t& _, const Instruction* inst) {
const auto entry_point_id = inst->GetOperandAs<uint32_t>(1);
auto entry_point = _.FindDef(entry_point_id);
if (!entry_point || SpvOpFunction != entry_point->opcode()) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< "OpEntryPoint Entry Point <id> '" << _.getIdName(entry_point_id)
<< "' is not a function.";
}
// don't check kernel function signatures
const SpvExecutionModel execution_model =
inst->GetOperandAs<SpvExecutionModel>(0);
if (execution_model != SpvExecutionModelKernel) {
// TODO: Check the entry point signature is void main(void), may be subject
// to change
const auto entry_point_type_id = entry_point->GetOperandAs<uint32_t>(3);
const auto entry_point_type = _.FindDef(entry_point_type_id);
if (!entry_point_type || 3 != entry_point_type->words().size()) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< "OpEntryPoint Entry Point <id> '" << _.getIdName(entry_point_id)
<< "'s function parameter count is not zero.";
}
}
auto return_type = _.FindDef(entry_point->type_id());
if (!return_type || SpvOpTypeVoid != return_type->opcode()) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< "OpEntryPoint Entry Point <id> '" << _.getIdName(entry_point_id)
<< "'s function return type is not void.";
}
const auto* execution_modes = _.GetExecutionModes(entry_point_id);
if (_.HasCapability(SpvCapabilityShader)) {
switch (execution_model) {
case SpvExecutionModelFragment:
if (execution_modes &&
execution_modes->count(SpvExecutionModeOriginUpperLeft) &&
execution_modes->count(SpvExecutionModeOriginLowerLeft)) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Fragment execution model entry points can only specify "
"one of OriginUpperLeft or OriginLowerLeft execution "
"modes.";
}
if (!execution_modes ||
(!execution_modes->count(SpvExecutionModeOriginUpperLeft) &&
!execution_modes->count(SpvExecutionModeOriginLowerLeft))) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Fragment execution model entry points require either an "
"OriginUpperLeft or OriginLowerLeft execution mode.";
}
if (execution_modes &&
1 < std::count_if(execution_modes->begin(), execution_modes->end(),
[](const SpvExecutionMode& mode) {
switch (mode) {
case SpvExecutionModeDepthGreater:
case SpvExecutionModeDepthLess:
case SpvExecutionModeDepthUnchanged:
return true;
default:
return false;
}
})) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Fragment execution model entry points can specify at most "
"one of DepthGreater, DepthLess or DepthUnchanged "
"execution modes.";
}
break;
case SpvExecutionModelTessellationControl:
case SpvExecutionModelTessellationEvaluation:
if (execution_modes &&
1 < std::count_if(execution_modes->begin(), execution_modes->end(),
[](const SpvExecutionMode& mode) {
switch (mode) {
case SpvExecutionModeSpacingEqual:
case SpvExecutionModeSpacingFractionalEven:
case SpvExecutionModeSpacingFractionalOdd:
return true;
default:
return false;
}
})) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Tessellation execution model entry points can specify at "
"most one of SpacingEqual, SpacingFractionalOdd or "
"SpacingFractionalEven execution modes.";
}
if (execution_modes &&
1 < std::count_if(execution_modes->begin(), execution_modes->end(),
[](const SpvExecutionMode& mode) {
switch (mode) {
case SpvExecutionModeTriangles:
case SpvExecutionModeQuads:
case SpvExecutionModeIsolines:
return true;
default:
return false;
}
})) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Tessellation execution model entry points can specify at "
"most one of Triangles, Quads or Isolines execution modes.";
}
if (execution_modes &&
1 < std::count_if(execution_modes->begin(), execution_modes->end(),
[](const SpvExecutionMode& mode) {
switch (mode) {
case SpvExecutionModeVertexOrderCw:
case SpvExecutionModeVertexOrderCcw:
return true;
default:
return false;
}
})) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Tessellation execution model entry points can specify at "
"most one of VertexOrderCw or VertexOrderCcw execution "
"modes.";
}
break;
case SpvExecutionModelGeometry:
if (!execution_modes ||
1 != std::count_if(execution_modes->begin(), execution_modes->end(),
[](const SpvExecutionMode& mode) {
switch (mode) {
case SpvExecutionModeInputPoints:
case SpvExecutionModeInputLines:
case SpvExecutionModeInputLinesAdjacency:
case SpvExecutionModeTriangles:
case SpvExecutionModeInputTrianglesAdjacency:
return true;
default:
return false;
}
})) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Geometry execution model entry points must specify "
"exactly one of InputPoints, InputLines, "
"InputLinesAdjacency, Triangles or InputTrianglesAdjacency "
"execution modes.";
}
if (!execution_modes ||
1 != std::count_if(execution_modes->begin(), execution_modes->end(),
[](const SpvExecutionMode& mode) {
switch (mode) {
case SpvExecutionModeOutputPoints:
case SpvExecutionModeOutputLineStrip:
case SpvExecutionModeOutputTriangleStrip:
return true;
default:
return false;
}
})) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Geometry execution model entry points must specify "
"exactly one of OutputPoints, OutputLineStrip or "
"OutputTriangleStrip execution modes.";
}
break;
default:
break;
}
}
if (spvIsVulkanEnv(_.context()->target_env)) {
switch (execution_model) {
case SpvExecutionModelGLCompute:
if (!execution_modes ||
!execution_modes->count(SpvExecutionModeLocalSize)) {
bool ok = false;
for (auto& i : _.ordered_instructions()) {
if (i.opcode() == SpvOpDecorate) {
if (i.operands().size() > 2) {
if (i.GetOperandAs<SpvDecoration>(1) == SpvDecorationBuiltIn &&
i.GetOperandAs<SpvBuiltIn>(2) == SpvBuiltInWorkgroupSize) {
ok = true;
break;
}
}
}
}
if (!ok) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "In the Vulkan environment, GLCompute execution model "
"entry points require either the LocalSize execution "
"mode or an object decorated with WorkgroupSize must be "
"specified.";
}
}
break;
default:
break;
}
}
return SPV_SUCCESS;
}
spv_result_t ValidateExecutionMode(ValidationState_t& _,
const Instruction* inst) {
const auto entry_point_id = inst->GetOperandAs<uint32_t>(0);
const auto found = std::find(_.entry_points().cbegin(),
_.entry_points().cend(), entry_point_id);
if (found == _.entry_points().cend()) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< "OpExecutionMode Entry Point <id> '"
<< _.getIdName(entry_point_id)
<< "' is not the Entry Point "
"operand of an OpEntryPoint.";
}
const auto mode = inst->GetOperandAs<SpvExecutionMode>(1);
const auto* models = _.GetExecutionModels(entry_point_id);
switch (mode) {
case SpvExecutionModeInvocations:
case SpvExecutionModeInputPoints:
case SpvExecutionModeInputLines:
case SpvExecutionModeInputLinesAdjacency:
case SpvExecutionModeInputTrianglesAdjacency:
case SpvExecutionModeOutputLineStrip:
case SpvExecutionModeOutputTriangleStrip:
if (!std::all_of(models->begin(), models->end(),
[](const SpvExecutionModel& model) {
return model == SpvExecutionModelGeometry;
})) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Execution mode can only be used with the Geometry execution "
"model.";
}
break;
case SpvExecutionModeOutputPoints:
if (!std::all_of(models->begin(), models->end(),
[&_](const SpvExecutionModel& model) {
switch (model) {
case SpvExecutionModelGeometry:
return true;
case SpvExecutionModelMeshNV:
return _.HasCapability(SpvCapabilityMeshShadingNV);
default:
return false;
}
})) {
if (_.HasCapability(SpvCapabilityMeshShadingNV)) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Execution mode can only be used with the Geometry or "
"MeshNV execution model.";
} else {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Execution mode can only be used with the Geometry "
"execution "
"model.";
}
}
break;
case SpvExecutionModeSpacingEqual:
case SpvExecutionModeSpacingFractionalEven:
case SpvExecutionModeSpacingFractionalOdd:
case SpvExecutionModeVertexOrderCw:
case SpvExecutionModeVertexOrderCcw:
case SpvExecutionModePointMode:
case SpvExecutionModeQuads:
case SpvExecutionModeIsolines:
if (!std::all_of(
models->begin(), models->end(),
[](const SpvExecutionModel& model) {
return (model == SpvExecutionModelTessellationControl) ||
(model == SpvExecutionModelTessellationEvaluation);
})) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Execution mode can only be used with a tessellation "
"execution model.";
}
break;
case SpvExecutionModeTriangles:
if (!std::all_of(models->begin(), models->end(),
[](const SpvExecutionModel& model) {
switch (model) {
case SpvExecutionModelGeometry:
case SpvExecutionModelTessellationControl:
case SpvExecutionModelTessellationEvaluation:
return true;
default:
return false;
}
})) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Execution mode can only be used with a Geometry or "
"tessellation execution model.";
}
break;
case SpvExecutionModeOutputVertices:
if (!std::all_of(models->begin(), models->end(),
[&_](const SpvExecutionModel& model) {
switch (model) {
case SpvExecutionModelGeometry:
case SpvExecutionModelTessellationControl:
case SpvExecutionModelTessellationEvaluation:
return true;
case SpvExecutionModelMeshNV:
return _.HasCapability(SpvCapabilityMeshShadingNV);
default:
return false;
}
})) {
if (_.HasCapability(SpvCapabilityMeshShadingNV)) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Execution mode can only be used with a Geometry, "
"tessellation or MeshNV execution model.";
} else {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Execution mode can only be used with a Geometry or "
"tessellation execution model.";
}
}
break;
case SpvExecutionModePixelCenterInteger:
case SpvExecutionModeOriginUpperLeft:
case SpvExecutionModeOriginLowerLeft:
case SpvExecutionModeEarlyFragmentTests:
case SpvExecutionModeDepthReplacing:
case SpvExecutionModeDepthGreater:
case SpvExecutionModeDepthLess:
case SpvExecutionModeDepthUnchanged:
if (!std::all_of(models->begin(), models->end(),
[](const SpvExecutionModel& model) {
return model == SpvExecutionModelFragment;
})) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Execution mode can only be used with the Fragment execution "
"model.";
}
break;
case SpvExecutionModeLocalSizeHint:
case SpvExecutionModeVecTypeHint:
case SpvExecutionModeContractionOff:
case SpvExecutionModeLocalSizeHintId:
if (!std::all_of(models->begin(), models->end(),
[](const SpvExecutionModel& model) {
return model == SpvExecutionModelKernel;
})) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Execution mode can only be used with the Kernel execution "
"model.";
}
break;
case SpvExecutionModeLocalSize:
case SpvExecutionModeLocalSizeId:
if (!std::all_of(models->begin(), models->end(),
[&_](const SpvExecutionModel& model) {
switch (model) {
case SpvExecutionModelKernel:
case SpvExecutionModelGLCompute:
return true;
case SpvExecutionModelTaskNV:
case SpvExecutionModelMeshNV:
return _.HasCapability(SpvCapabilityMeshShadingNV);
default:
return false;
}
})) {
if (_.HasCapability(SpvCapabilityMeshShadingNV)) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Execution mode can only be used with a Kernel, GLCompute, "
"MeshNV, or TaskNV execution model.";
} else {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Execution mode can only be used with a Kernel or "
"GLCompute "
"execution model.";
}
}
default:
break;
}
if (spvIsVulkanEnv(_.context()->target_env)) {
if (mode == SpvExecutionModeOriginLowerLeft) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "In the Vulkan environment, the OriginLowerLeft execution mode "
"must not be used.";
}
if (mode == SpvExecutionModePixelCenterInteger) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "In the Vulkan environment, the PixelCenterInteger execution "
"mode must not be used.";
}
}
if (spvIsWebGPUEnv(_.context()->target_env)) {
if (mode != SpvExecutionModeOriginUpperLeft &&
mode != SpvExecutionModeDepthReplacing &&
mode != SpvExecutionModeDepthGreater &&
mode != SpvExecutionModeDepthLess &&
mode != SpvExecutionModeDepthUnchanged &&
mode != SpvExecutionModeLocalSize &&
mode != SpvExecutionModeLocalSizeHint) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Execution mode must be one of OriginUpperLeft, "
"DepthReplacing, DepthGreater, DepthLess, DepthUnchanged, "
"LocalSize, or LocalSizeHint for WebGPU environment.";
}
}
return SPV_SUCCESS;
}
} // namespace
spv_result_t ModeSettingPass(ValidationState_t& _, const Instruction* inst) {
switch (inst->opcode()) {
case SpvOpEntryPoint:
if (auto error = ValidateEntryPoint(_, inst)) return error;
break;
case SpvOpExecutionMode:
case SpvOpExecutionModeId:
if (auto error = ValidateExecutionMode(_, inst)) return error;
break;
default:
break;
}
return SPV_SUCCESS;
}
} // namespace val
} // namespace spvtools
<commit_msg>Remove stale comment (#2542)<commit_after>// Copyright (c) 2018 Google LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "source/val/validate.h"
#include <algorithm>
#include "source/opcode.h"
#include "source/spirv_target_env.h"
#include "source/val/instruction.h"
#include "source/val/validation_state.h"
namespace spvtools {
namespace val {
namespace {
spv_result_t ValidateEntryPoint(ValidationState_t& _, const Instruction* inst) {
const auto entry_point_id = inst->GetOperandAs<uint32_t>(1);
auto entry_point = _.FindDef(entry_point_id);
if (!entry_point || SpvOpFunction != entry_point->opcode()) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< "OpEntryPoint Entry Point <id> '" << _.getIdName(entry_point_id)
<< "' is not a function.";
}
// Only check the shader execution models
const SpvExecutionModel execution_model =
inst->GetOperandAs<SpvExecutionModel>(0);
if (execution_model != SpvExecutionModelKernel) {
const auto entry_point_type_id = entry_point->GetOperandAs<uint32_t>(3);
const auto entry_point_type = _.FindDef(entry_point_type_id);
if (!entry_point_type || 3 != entry_point_type->words().size()) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< "OpEntryPoint Entry Point <id> '" << _.getIdName(entry_point_id)
<< "'s function parameter count is not zero.";
}
}
auto return_type = _.FindDef(entry_point->type_id());
if (!return_type || SpvOpTypeVoid != return_type->opcode()) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< "OpEntryPoint Entry Point <id> '" << _.getIdName(entry_point_id)
<< "'s function return type is not void.";
}
const auto* execution_modes = _.GetExecutionModes(entry_point_id);
if (_.HasCapability(SpvCapabilityShader)) {
switch (execution_model) {
case SpvExecutionModelFragment:
if (execution_modes &&
execution_modes->count(SpvExecutionModeOriginUpperLeft) &&
execution_modes->count(SpvExecutionModeOriginLowerLeft)) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Fragment execution model entry points can only specify "
"one of OriginUpperLeft or OriginLowerLeft execution "
"modes.";
}
if (!execution_modes ||
(!execution_modes->count(SpvExecutionModeOriginUpperLeft) &&
!execution_modes->count(SpvExecutionModeOriginLowerLeft))) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Fragment execution model entry points require either an "
"OriginUpperLeft or OriginLowerLeft execution mode.";
}
if (execution_modes &&
1 < std::count_if(execution_modes->begin(), execution_modes->end(),
[](const SpvExecutionMode& mode) {
switch (mode) {
case SpvExecutionModeDepthGreater:
case SpvExecutionModeDepthLess:
case SpvExecutionModeDepthUnchanged:
return true;
default:
return false;
}
})) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Fragment execution model entry points can specify at most "
"one of DepthGreater, DepthLess or DepthUnchanged "
"execution modes.";
}
break;
case SpvExecutionModelTessellationControl:
case SpvExecutionModelTessellationEvaluation:
if (execution_modes &&
1 < std::count_if(execution_modes->begin(), execution_modes->end(),
[](const SpvExecutionMode& mode) {
switch (mode) {
case SpvExecutionModeSpacingEqual:
case SpvExecutionModeSpacingFractionalEven:
case SpvExecutionModeSpacingFractionalOdd:
return true;
default:
return false;
}
})) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Tessellation execution model entry points can specify at "
"most one of SpacingEqual, SpacingFractionalOdd or "
"SpacingFractionalEven execution modes.";
}
if (execution_modes &&
1 < std::count_if(execution_modes->begin(), execution_modes->end(),
[](const SpvExecutionMode& mode) {
switch (mode) {
case SpvExecutionModeTriangles:
case SpvExecutionModeQuads:
case SpvExecutionModeIsolines:
return true;
default:
return false;
}
})) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Tessellation execution model entry points can specify at "
"most one of Triangles, Quads or Isolines execution modes.";
}
if (execution_modes &&
1 < std::count_if(execution_modes->begin(), execution_modes->end(),
[](const SpvExecutionMode& mode) {
switch (mode) {
case SpvExecutionModeVertexOrderCw:
case SpvExecutionModeVertexOrderCcw:
return true;
default:
return false;
}
})) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Tessellation execution model entry points can specify at "
"most one of VertexOrderCw or VertexOrderCcw execution "
"modes.";
}
break;
case SpvExecutionModelGeometry:
if (!execution_modes ||
1 != std::count_if(execution_modes->begin(), execution_modes->end(),
[](const SpvExecutionMode& mode) {
switch (mode) {
case SpvExecutionModeInputPoints:
case SpvExecutionModeInputLines:
case SpvExecutionModeInputLinesAdjacency:
case SpvExecutionModeTriangles:
case SpvExecutionModeInputTrianglesAdjacency:
return true;
default:
return false;
}
})) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Geometry execution model entry points must specify "
"exactly one of InputPoints, InputLines, "
"InputLinesAdjacency, Triangles or InputTrianglesAdjacency "
"execution modes.";
}
if (!execution_modes ||
1 != std::count_if(execution_modes->begin(), execution_modes->end(),
[](const SpvExecutionMode& mode) {
switch (mode) {
case SpvExecutionModeOutputPoints:
case SpvExecutionModeOutputLineStrip:
case SpvExecutionModeOutputTriangleStrip:
return true;
default:
return false;
}
})) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Geometry execution model entry points must specify "
"exactly one of OutputPoints, OutputLineStrip or "
"OutputTriangleStrip execution modes.";
}
break;
default:
break;
}
}
if (spvIsVulkanEnv(_.context()->target_env)) {
switch (execution_model) {
case SpvExecutionModelGLCompute:
if (!execution_modes ||
!execution_modes->count(SpvExecutionModeLocalSize)) {
bool ok = false;
for (auto& i : _.ordered_instructions()) {
if (i.opcode() == SpvOpDecorate) {
if (i.operands().size() > 2) {
if (i.GetOperandAs<SpvDecoration>(1) == SpvDecorationBuiltIn &&
i.GetOperandAs<SpvBuiltIn>(2) == SpvBuiltInWorkgroupSize) {
ok = true;
break;
}
}
}
}
if (!ok) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "In the Vulkan environment, GLCompute execution model "
"entry points require either the LocalSize execution "
"mode or an object decorated with WorkgroupSize must be "
"specified.";
}
}
break;
default:
break;
}
}
return SPV_SUCCESS;
}
spv_result_t ValidateExecutionMode(ValidationState_t& _,
const Instruction* inst) {
const auto entry_point_id = inst->GetOperandAs<uint32_t>(0);
const auto found = std::find(_.entry_points().cbegin(),
_.entry_points().cend(), entry_point_id);
if (found == _.entry_points().cend()) {
return _.diag(SPV_ERROR_INVALID_ID, inst)
<< "OpExecutionMode Entry Point <id> '"
<< _.getIdName(entry_point_id)
<< "' is not the Entry Point "
"operand of an OpEntryPoint.";
}
const auto mode = inst->GetOperandAs<SpvExecutionMode>(1);
const auto* models = _.GetExecutionModels(entry_point_id);
switch (mode) {
case SpvExecutionModeInvocations:
case SpvExecutionModeInputPoints:
case SpvExecutionModeInputLines:
case SpvExecutionModeInputLinesAdjacency:
case SpvExecutionModeInputTrianglesAdjacency:
case SpvExecutionModeOutputLineStrip:
case SpvExecutionModeOutputTriangleStrip:
if (!std::all_of(models->begin(), models->end(),
[](const SpvExecutionModel& model) {
return model == SpvExecutionModelGeometry;
})) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Execution mode can only be used with the Geometry execution "
"model.";
}
break;
case SpvExecutionModeOutputPoints:
if (!std::all_of(models->begin(), models->end(),
[&_](const SpvExecutionModel& model) {
switch (model) {
case SpvExecutionModelGeometry:
return true;
case SpvExecutionModelMeshNV:
return _.HasCapability(SpvCapabilityMeshShadingNV);
default:
return false;
}
})) {
if (_.HasCapability(SpvCapabilityMeshShadingNV)) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Execution mode can only be used with the Geometry or "
"MeshNV execution model.";
} else {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Execution mode can only be used with the Geometry "
"execution "
"model.";
}
}
break;
case SpvExecutionModeSpacingEqual:
case SpvExecutionModeSpacingFractionalEven:
case SpvExecutionModeSpacingFractionalOdd:
case SpvExecutionModeVertexOrderCw:
case SpvExecutionModeVertexOrderCcw:
case SpvExecutionModePointMode:
case SpvExecutionModeQuads:
case SpvExecutionModeIsolines:
if (!std::all_of(
models->begin(), models->end(),
[](const SpvExecutionModel& model) {
return (model == SpvExecutionModelTessellationControl) ||
(model == SpvExecutionModelTessellationEvaluation);
})) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Execution mode can only be used with a tessellation "
"execution model.";
}
break;
case SpvExecutionModeTriangles:
if (!std::all_of(models->begin(), models->end(),
[](const SpvExecutionModel& model) {
switch (model) {
case SpvExecutionModelGeometry:
case SpvExecutionModelTessellationControl:
case SpvExecutionModelTessellationEvaluation:
return true;
default:
return false;
}
})) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Execution mode can only be used with a Geometry or "
"tessellation execution model.";
}
break;
case SpvExecutionModeOutputVertices:
if (!std::all_of(models->begin(), models->end(),
[&_](const SpvExecutionModel& model) {
switch (model) {
case SpvExecutionModelGeometry:
case SpvExecutionModelTessellationControl:
case SpvExecutionModelTessellationEvaluation:
return true;
case SpvExecutionModelMeshNV:
return _.HasCapability(SpvCapabilityMeshShadingNV);
default:
return false;
}
})) {
if (_.HasCapability(SpvCapabilityMeshShadingNV)) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Execution mode can only be used with a Geometry, "
"tessellation or MeshNV execution model.";
} else {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Execution mode can only be used with a Geometry or "
"tessellation execution model.";
}
}
break;
case SpvExecutionModePixelCenterInteger:
case SpvExecutionModeOriginUpperLeft:
case SpvExecutionModeOriginLowerLeft:
case SpvExecutionModeEarlyFragmentTests:
case SpvExecutionModeDepthReplacing:
case SpvExecutionModeDepthGreater:
case SpvExecutionModeDepthLess:
case SpvExecutionModeDepthUnchanged:
if (!std::all_of(models->begin(), models->end(),
[](const SpvExecutionModel& model) {
return model == SpvExecutionModelFragment;
})) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Execution mode can only be used with the Fragment execution "
"model.";
}
break;
case SpvExecutionModeLocalSizeHint:
case SpvExecutionModeVecTypeHint:
case SpvExecutionModeContractionOff:
case SpvExecutionModeLocalSizeHintId:
if (!std::all_of(models->begin(), models->end(),
[](const SpvExecutionModel& model) {
return model == SpvExecutionModelKernel;
})) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Execution mode can only be used with the Kernel execution "
"model.";
}
break;
case SpvExecutionModeLocalSize:
case SpvExecutionModeLocalSizeId:
if (!std::all_of(models->begin(), models->end(),
[&_](const SpvExecutionModel& model) {
switch (model) {
case SpvExecutionModelKernel:
case SpvExecutionModelGLCompute:
return true;
case SpvExecutionModelTaskNV:
case SpvExecutionModelMeshNV:
return _.HasCapability(SpvCapabilityMeshShadingNV);
default:
return false;
}
})) {
if (_.HasCapability(SpvCapabilityMeshShadingNV)) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Execution mode can only be used with a Kernel, GLCompute, "
"MeshNV, or TaskNV execution model.";
} else {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Execution mode can only be used with a Kernel or "
"GLCompute "
"execution model.";
}
}
default:
break;
}
if (spvIsVulkanEnv(_.context()->target_env)) {
if (mode == SpvExecutionModeOriginLowerLeft) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "In the Vulkan environment, the OriginLowerLeft execution mode "
"must not be used.";
}
if (mode == SpvExecutionModePixelCenterInteger) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "In the Vulkan environment, the PixelCenterInteger execution "
"mode must not be used.";
}
}
if (spvIsWebGPUEnv(_.context()->target_env)) {
if (mode != SpvExecutionModeOriginUpperLeft &&
mode != SpvExecutionModeDepthReplacing &&
mode != SpvExecutionModeDepthGreater &&
mode != SpvExecutionModeDepthLess &&
mode != SpvExecutionModeDepthUnchanged &&
mode != SpvExecutionModeLocalSize &&
mode != SpvExecutionModeLocalSizeHint) {
return _.diag(SPV_ERROR_INVALID_DATA, inst)
<< "Execution mode must be one of OriginUpperLeft, "
"DepthReplacing, DepthGreater, DepthLess, DepthUnchanged, "
"LocalSize, or LocalSizeHint for WebGPU environment.";
}
}
return SPV_SUCCESS;
}
} // namespace
spv_result_t ModeSettingPass(ValidationState_t& _, const Instruction* inst) {
switch (inst->opcode()) {
case SpvOpEntryPoint:
if (auto error = ValidateEntryPoint(_, inst)) return error;
break;
case SpvOpExecutionMode:
case SpvOpExecutionModeId:
if (auto error = ValidateExecutionMode(_, inst)) return error;
break;
default:
break;
}
return SPV_SUCCESS;
}
} // namespace val
} // namespace spvtools
<|endoftext|> |
<commit_before>//!
//! @file PyDockWidget.cpp
//! @author Björn Eriksson <bjorn.eriksson@liu.se>
//! @date 2010-09-21
//!
//! @brief Contains a derived QDockWidget class that contain a Python console
//!
//$Id$
#include "PyDockWidget.h"
#include "PythonQt.h"
#include "PythonQt_QtAll.h"
#include "gui/PythonQtScriptingConsole.h"
#include "PythonQtConversion.h"
#include "../PyWrapperClasses.h"
//! Create a dock for the Python console
//! Constructor
PyDockWidget::PyDockWidget(MainWindow *pMainWindow, QWidget * parent)
: QDockWidget(tr("Python Console"), parent)
{
PythonQt::init(PythonQt::RedirectStdOut);
PythonQt_QtAll::init();
PythonQt::self()->registerCPPClass("MainWindow", "","", PythonQtCreateObject<PyHopsanClassWrapper>);
PythonQt::self()->registerCPPClass("GUIObject", "","", PythonQtCreateObject<PyGUIObjectClassWrapper>);
PythonQt::self()->registerCPPClass("GUIPort", "","", PythonQtCreateObject<PyGUIPortClassWrapper>);
PythonQtObjectPtr mainContext = PythonQt::self()->getMainModule();
mainContext.addObject("hopsan", pMainWindow);
// pyTestClass *test = new pyTestClass();
// mainContext.addObject("test", test);
mpPyConsole = new PythonQtScriptingConsole(NULL, mainContext);
mpPyConsole->consoleMessage("There is an object called hopsan that allow you to interact with Hopsan.");
mpPyConsole->appendCommandPrompt();
mpScriptFileLineEdit = new QLineEdit();
//mpScriptFileLineEdit->setAlignment(Qt::AlignVCenter | Qt::AlignLeft);
//mpStartTimeLineEdit->setValidator(new QDoubleValidator(-999.0, 999.0, 6, mpStartTimeLineEdit));
QPushButton *pPyCustomButton = new QPushButton();
pPyCustomButton->setText("Run .py-file");
pPyCustomButton->connect(pPyCustomButton,SIGNAL(clicked()), this, SLOT(runPyScript()));
QHBoxLayout *pScriptFileLayout = new QHBoxLayout();
pScriptFileLayout->addWidget(mpScriptFileLineEdit);
pScriptFileLayout->addWidget(pPyCustomButton);
QVBoxLayout *pPyLayout = new QVBoxLayout();
pPyLayout->addWidget(mpPyConsole);
pPyLayout->setContentsMargins(4,4,4,4);
pPyLayout->addLayout(pScriptFileLayout);
PyWidget *pPyWidget = new PyWidget();
pPyWidget->setLayout(pPyLayout);
setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
setWidget(pPyWidget);//->setWidget(mpPythonConsole);
}
void PyDockWidget::saveSettingsToDomElement(QDomElement &rDomElement)
{
QDomElement lastscript = appendDomElement(rDomElement, "lastscript");
lastscript.setAttribute("file", mpScriptFileLineEdit->text());
}
void PyDockWidget::loadSettingsFromDomElement(QDomElement &rDomElement)
{
QDomElement lastscript = rDomElement.firstChildElement("lastscript");
QString filename = lastscript.attribute("file");
if(!(filename.isEmpty()))
mpScriptFileLineEdit->setText(filename);
}
void PyDockWidget::runPyScript()
{
PythonQtObjectPtr mainContext = PythonQt::self()->getMainModule();
QString command = QString("execfile('").append(mpScriptFileLineEdit->text()).append("')");
mainContext.evalScript(command);
mpPyConsole->appendCommandPrompt();
}
void PyDockWidget::runPyScript(QString path)
{
PythonQtObjectPtr mainContext = PythonQt::self()->getMainModule();
QString command = QString("execfile('").append(path).append("')");
mainContext.evalScript(command);
mpPyConsole->appendCommandPrompt();
}
PyWidget::PyWidget(QWidget *parent)
: QWidget(parent)
{
//Nothing to do...
}
//! @brief Reimplementation of QWidget::sizeHint(), used to reduce the size of the plot widget when docked
QSize PyWidget::sizeHint() const
{
QSize size = QWidget::sizeHint();
//Set very small height. A minimum apperantly stops at resonable size.
size.rheight() = 1; //pixels
return size;
}
<commit_msg>Added minor check<commit_after>//!
//! @file PyDockWidget.cpp
//! @author Björn Eriksson <bjorn.eriksson@liu.se>
//! @date 2010-09-21
//!
//! @brief Contains a derived QDockWidget class that contain a Python console
//!
//$Id$
#include "PyDockWidget.h"
#include "PythonQt.h"
#include "PythonQt_QtAll.h"
#include "gui/PythonQtScriptingConsole.h"
#include "PythonQtConversion.h"
#include "../PyWrapperClasses.h"
//! Create a dock for the Python console
//! Constructor
PyDockWidget::PyDockWidget(MainWindow *pMainWindow, QWidget * parent)
: QDockWidget(tr("Python Console"), parent)
{
PythonQt::init(PythonQt::RedirectStdOut);
PythonQt_QtAll::init();
PythonQt::self()->registerCPPClass("MainWindow", "","", PythonQtCreateObject<PyHopsanClassWrapper>);
PythonQt::self()->registerCPPClass("GUIObject", "","", PythonQtCreateObject<PyGUIObjectClassWrapper>);
PythonQt::self()->registerCPPClass("GUIPort", "","", PythonQtCreateObject<PyGUIPortClassWrapper>);
PythonQtObjectPtr mainContext = PythonQt::self()->getMainModule();
mainContext.addObject("hopsan", pMainWindow);
// pyTestClass *test = new pyTestClass();
// mainContext.addObject("test", test);
mpPyConsole = new PythonQtScriptingConsole(NULL, mainContext);
mpPyConsole->consoleMessage("There is an object called hopsan that allow you to interact with Hopsan.");
mpPyConsole->appendCommandPrompt();
mpScriptFileLineEdit = new QLineEdit();
//mpScriptFileLineEdit->setAlignment(Qt::AlignVCenter | Qt::AlignLeft);
//mpStartTimeLineEdit->setValidator(new QDoubleValidator(-999.0, 999.0, 6, mpStartTimeLineEdit));
QPushButton *pPyCustomButton = new QPushButton();
pPyCustomButton->setText("Run .py-file");
pPyCustomButton->connect(pPyCustomButton,SIGNAL(clicked()), this, SLOT(runPyScript()));
QHBoxLayout *pScriptFileLayout = new QHBoxLayout();
pScriptFileLayout->addWidget(mpScriptFileLineEdit);
pScriptFileLayout->addWidget(pPyCustomButton);
QVBoxLayout *pPyLayout = new QVBoxLayout();
pPyLayout->addWidget(mpPyConsole);
pPyLayout->setContentsMargins(4,4,4,4);
pPyLayout->addLayout(pScriptFileLayout);
PyWidget *pPyWidget = new PyWidget();
pPyWidget->setLayout(pPyLayout);
setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea | Qt::BottomDockWidgetArea);
setWidget(pPyWidget);//->setWidget(mpPythonConsole);
}
void PyDockWidget::saveSettingsToDomElement(QDomElement &rDomElement)
{
QDomElement lastscript = appendDomElement(rDomElement, "lastscript");
lastscript.setAttribute("file", mpScriptFileLineEdit->text());
}
void PyDockWidget::loadSettingsFromDomElement(QDomElement &rDomElement)
{
QDomElement lastscript = rDomElement.firstChildElement("lastscript");
QString filename = lastscript.attribute("file");
if(!(filename.isEmpty()))
mpScriptFileLineEdit->setText(filename);
}
void PyDockWidget::runPyScript()
{
PythonQtObjectPtr mainContext = PythonQt::self()->getMainModule();
QString command = QString("execfile('").append(mpScriptFileLineEdit->text()).append("')");
mainContext.evalScript(command);
mpPyConsole->appendCommandPrompt();
}
void PyDockWidget::runPyScript(QString path)
{
if(path.isEmpty()) return;
PythonQtObjectPtr mainContext = PythonQt::self()->getMainModule();
QString command = QString("execfile('").append(path).append("')");
mainContext.evalScript(command);
mpPyConsole->appendCommandPrompt();
}
PyWidget::PyWidget(QWidget *parent)
: QWidget(parent)
{
//Nothing to do...
}
//! @brief Reimplementation of QWidget::sizeHint(), used to reduce the size of the plot widget when docked
QSize PyWidget::sizeHint() const
{
QSize size = QWidget::sizeHint();
//Set very small height. A minimum apperantly stops at resonable size.
size.rheight() = 1; //pixels
return size;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2019-2022, Hossein Moein
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 Hossein Moein and/or the DataFrame 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 Hossein Moein 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 <DataFrame/DataFrame.h> // Main DataFrame header
#include <DataFrame/DataFrameFinancialVisitors.h> // Financial algorithms
#include <DataFrame/DataFrameMLVisitors.h> // Machine-learning algorithms
#include <DataFrame/DataFrameStatsVisitors.h> // Statistical algorithms
#include <DataFrame/Utils/DateTime.h> // Cool and handy date-time object
#include <iostream>
// -----------------------------------------------------------------------------
// DataFrame library is entirely under hmdf name-space
//
using namespace hmdf;
// A DataFrame with ulong index type
//
using ULDataFrame = StdDataFrame<unsigned long>;
// A DataFrame with string index type
//
using StrDataFrame = StdDataFrame<std::string>;
// A DataFrame with DateTime index type
//
using DTDataFrame = StdDataFrame<DateTime>;
// This is just some arbitrary type to show how any type could be in DataFrame
//
struct MyData {
int i { 10 };
double d { 5.5 };
std::string s { "Boo" };
MyData() = default;
};
// -----------------------------------------------------------------------------
// The main purpose of this file is to introduce the basic operations of DataFrame.
// For more advanced operations and a complete list of features with code samples, see documentation at:
// https://htmlpreview.github.io/?https://github.com/hosseinmoein/DataFrame/blob/master/docs/HTML/DataFrame.html
//
int main(int, char *[]) {
std::vector<unsigned long> idx_col1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
std::vector<MyData> mydata_col (10);
std::vector<int> int_col1 = { 1, 2, -3, -4, 5, 6, 7, 8, 9, -10 };
std::vector<double> dbl_col1 = { 0.01, 0.02, 0.03, 0.03, 0.05, 0.06, 0.03, 0.08, 0.09, 0.03 };
ULDataFrame ul_df1;
// One way to load data into the DataFrame is one column at a time.
// A DataFram column could be at most as long as its index column. So, you must load the index
// first before loading any column
//
// Once you load a column or index, the data is moved to DataFrame. The original vectors are now empty.
// There are other ways of loading data without the move
//
ul_df1.load_index(std::move(idx_col1));
ul_df1.load_column<double>("dbl_col", std::move(dbl_col1));
ul_df1.load_column<MyData>("my_data_col", std::move(mydata_col));
ul_df1.load_column<int>("integers", std::move(int_col1));
std::vector<unsigned long> idx_col2 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
std::vector<std::string> str_col1 = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };
std::vector<std::string> str_col2 =
{ "Azadi", "Hello", " World", "!", "Hype", "cubic spline", "Foo", "Silverado", "Arash", "Pardis" };
std::vector<double> dbl_col2 = { 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0};
ULDataFrame ul_df2;
// Also, you can load data into a DataFrame all at once
//
ul_df2.load_data(std::move(idx_col2),
std::make_pair("string col", str_col1),
std::make_pair("Cool Column", str_col2),
std::make_pair("numbers", dbl_col2));
StrDataFrame ibm_df;
// Also, you can load data into a DataFrame from a file, suporting a few different formats.
// If the file cannot be found, an exception will be thrown.
// If the DataFrame root directory is your current directory when running this, it should work fine.
//
ibm_df.read("data/IBM.csv", io_format::csv2);
// To access a column, you must know its name (or index) and its type
//
auto &str_col_ref = ul_df2.get_column<std::string>("string col");
const auto &close_const_ref = ibm_df.get_column<double>("IBM_Close");
const auto &index_vec = ibm_df.get_index();
// In case of a "standard" DataFrame (not a view), the columns are returned
// as a reference to a std::vector of type of that column.
//
std::cout << ul_df2.get_column<std::string>("Cool Column")[1]
<< ul_df2.get_column<std::string>("Cool Column")[2]
<< ul_df2.get_column<std::string>("Cool Column")[3]
<< std::endl;
for (auto citer : str_col_ref)
std::cout << citer << ", ";
std::cout << std::endl;
for (std::size_t i = 0; i < str_col_ref.size(); ++i)
std::cout << str_col_ref[i] << ", ";
std::cout << std::endl;
std::cout << "There are " << close_const_ref.size() << " IBM close prices" << std::endl;
std::cout << "There are " << index_vec.size() << " IBM indices" << std::endl;
// You can write the data to a file or stdout in a few formats
// You must specify all the column types, but only once
// When writing to a file, the file name/path must be create-able.
//
ul_df2.write<std::ostream, std::string, double>(std::cout, io_format::csv2);
ibm_df.write<double, long>("/tmp/test.json", io_format::json);
// You can convert a DataFrame to a string and from a string back into a DataFrame.
// This could be used to transmit a DataFrame from one place to another
// or store a DataFrame in databases, caches, …
//
const std::string str_ibm = ibm_df.to_string<double, long>();
StrDataFrame ibm_df_2;
// Since we convert from native type to string and back, if you have
// floating point numbers with long precisions, you may run into precision mismatches.
// to_string() has a precision parameter you can adjust. The defualt is 12
// which is a relatively high precision.
//
ibm_df_2.from_string(str_ibm.c_str());
// std::cout << str_ibm << std::endl;
using ul_idx_t = ULDataFrame::IndexType; // This is just unsigned long
// You can sort by one or multiple columns You must specify all the column types, but only once
// Sort first by the index column in ascending order then by "string col" column in descending order
//
ul_df2.sort<ul_idx_t, std::string, double, std::string>(DF_INDEX_COL_NAME, sort_spec::ascen,
"string col", sort_spec::desce);
// You could get another DataFrame by selecting on one or multiple columns
// You must specify all the column types, but only once
//
auto functor =
[](const std::string &, const double &val)-> bool { return (val > 150.0); };
auto above_150_df =
ibm_df.get_data_by_sel<double, decltype(functor), double, long>("IBM_Close", functor);
// Or, you could choose to get a view. See docs for views
//
auto above_150_view =
ibm_df.get_view_by_sel<double, decltype(functor), double, long>("IBM_Close", functor);
// You can get another DataFrame by group-bying on one or multiple columns
// You must specify only the type(s) of column(s), you are group-bying
//
// Group-by column dbl_col, and I am specifying how to summarize the index
// column and each of the other columns
//
auto gb_df =
ul_df1.groupby1<double>("dbl_col",
LastVisitor<ul_idx_t, ul_idx_t>(),
std::make_tuple("integers", "sum_int", SumVisitor<int>()),
std::make_tuple("my_data_col", "last_my_data", LastVisitor<MyData>()));
// You can run statistical, financial, ML, … algorithms on one or multiple
// columns by using visitors. You must specify the column(s) type(s)
//
StdVisitor<double, std::string> ibm_stdev;
ibm_df.visit<double>("IBM_Close", ibm_stdev);
std::cout << "Standard deviation of IBM close prices: " << ibm_stdev.get_result()
<< std::endl;
// Now Let’s declare two DataFrames with index type of DateTime
// which is a handy object for date/time manipulations.
//
DTDataFrame dt_ibm;
DTDataFrame dt_aapl;
// Let’s read the AAPL and IBM market data from their files.
// The data for these two stocks start and end at different dates.
// But there is overlapping data between them
//
dt_ibm.read("data/DT_IBM.csv", io_format::csv2);
dt_aapl.read("data/DT_AAPL.csv", io_format::csv2);
// Now we join the AAPL and IBM DataFrames using their indices and applying inner-join policy
//
DTDataFrame aapl_ibm = dt_ibm.join_by_index<DTDataFrame, double, long>(dt_aapl, join_policy::inner_join);
// Now we calculate the Pearson correlation coefficient between AAPL and IBM close prices
//
CorrVisitor<double, DateTime> aapl_ibm_corrl;
std::cout << "Correlation between AAPL and IBM close prices: "
<< aapl_ibm.visit<double, double>("AAPL_Close", "IBM_Close", aapl_ibm_corrl).get_result()
<< std::endl;
using dt_idx_t = DTDataFrame::IndexType; // This is just DateTime
// Appel data are daily. Let’s create 10-day OHLC (plus mean, std, total volume) for close prices.
//
DTDataFrame aapl_ohlc =
dt_aapl.bucketize(bucket_type::by_count,
10,
LastVisitor<dt_idx_t, dt_idx_t>(),
std::make_tuple("AAPL_Close", "Open", FirstVisitor<double, dt_idx_t>()),
std::make_tuple("AAPL_Close", "High", MaxVisitor<double, dt_idx_t>()),
std::make_tuple("AAPL_Close", "Low", MinVisitor<double, dt_idx_t>()),
std::make_tuple("AAPL_Close", "Close", LastVisitor<double, dt_idx_t>()),
std::make_tuple("AAPL_Close", "Mean", MeanVisitor<double, dt_idx_t>()),
std::make_tuple("AAPL_Close", "Std", StdVisitor<double, dt_idx_t>()),
std::make_tuple("AAPL_Volume", "Volume", SumVisitor<long, dt_idx_t>()));
// Now, let's get a view of a random sample of appel data.
// We randomley sample 35% of the data
//
auto random_view =
dt_aapl.get_view_by_rand<double, long>(random_policy::frac_rows_no_seed, 0.35);
return (0);
}
// -----------------------------------------------------------------------------
// Local Variables:
// mode:C++
// tab-width:4
// c-basic-offset:4
// End:
<commit_msg>:pencil: Fixed typos in hello_world.cc<commit_after>/*
Copyright (c) 2019-2022, Hossein Moein
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 Hossein Moein and/or the DataFrame 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 Hossein Moein 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 <DataFrame/DataFrame.h> // Main DataFrame header
#include <DataFrame/DataFrameFinancialVisitors.h> // Financial algorithms
#include <DataFrame/DataFrameMLVisitors.h> // Machine-learning algorithms
#include <DataFrame/DataFrameStatsVisitors.h> // Statistical algorithms
#include <DataFrame/Utils/DateTime.h> // Cool and handy date-time object
#include <iostream>
// -----------------------------------------------------------------------------
// DataFrame library is entirely under hmdf name-space
//
using namespace hmdf;
// A DataFrame with ulong index type
//
using ULDataFrame = StdDataFrame<unsigned long>;
// A DataFrame with string index type
//
using StrDataFrame = StdDataFrame<std::string>;
// A DataFrame with DateTime index type
//
using DTDataFrame = StdDataFrame<DateTime>;
// This is just some arbitrary type to show how any type could be in DataFrame
//
struct MyData {
int i { 10 };
double d { 5.5 };
std::string s { "Boo" };
MyData() = default;
};
// -----------------------------------------------------------------------------
// The main purpose of this file is to introduce the basic operations of DataFrame.
// For more advanced operations and a complete list of features with code samples, see documentation at:
// https://htmlpreview.github.io/?https://github.com/hosseinmoein/DataFrame/blob/master/docs/HTML/DataFrame.html
//
int main(int, char *[]) {
std::vector<unsigned long> idx_col1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
std::vector<MyData> mydata_col (10);
std::vector<int> int_col1 = { 1, 2, -3, -4, 5, 6, 7, 8, 9, -10 };
std::vector<double> dbl_col1 = { 0.01, 0.02, 0.03, 0.03, 0.05, 0.06, 0.03, 0.08, 0.09, 0.03 };
ULDataFrame ul_df1;
// One way to load data into the DataFrame is one column at a time.
// A DataFrame column could be at most as long as its index column. So, you must load the index
// first before loading any column
//
// Once you load a column or index, the data is moved to DataFrame. The original vectors are now empty.
// There are other ways of loading data without the move
//
ul_df1.load_index(std::move(idx_col1));
ul_df1.load_column<double>("dbl_col", std::move(dbl_col1));
ul_df1.load_column<MyData>("my_data_col", std::move(mydata_col));
ul_df1.load_column<int>("integers", std::move(int_col1));
std::vector<unsigned long> idx_col2 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
std::vector<std::string> str_col1 = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };
std::vector<std::string> str_col2 =
{ "Azadi", "Hello", " World", "!", "Hype", "cubic spline", "Foo", "Silverado", "Arash", "Pardis" };
std::vector<double> dbl_col2 = { 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0};
ULDataFrame ul_df2;
// Also, you can load data into a DataFrame all at once
//
ul_df2.load_data(std::move(idx_col2),
std::make_pair("string col", str_col1),
std::make_pair("Cool Column", str_col2),
std::make_pair("numbers", dbl_col2));
StrDataFrame ibm_df;
// Also, you can load data into a DataFrame from a file, supporting a few different formats.
// If the file cannot be found, an exception will be thrown.
// If the DataFrame root directory is your current directory when running this, it should work fine.
//
ibm_df.read("data/IBM.csv", io_format::csv2);
// To access a column, you must know its name (or index) and its type
//
auto &str_col_ref = ul_df2.get_column<std::string>("string col");
const auto &close_const_ref = ibm_df.get_column<double>("IBM_Close");
const auto &index_vec = ibm_df.get_index();
// In case of a "standard" DataFrame (not a view), the columns are returned
// as a reference to a std::vector of type of that column.
//
std::cout << ul_df2.get_column<std::string>("Cool Column")[1]
<< ul_df2.get_column<std::string>("Cool Column")[2]
<< ul_df2.get_column<std::string>("Cool Column")[3]
<< std::endl;
for (auto citer : str_col_ref)
std::cout << citer << ", ";
std::cout << std::endl;
for (std::size_t i = 0; i < str_col_ref.size(); ++i)
std::cout << str_col_ref[i] << ", ";
std::cout << std::endl;
std::cout << "There are " << close_const_ref.size() << " IBM close prices" << std::endl;
std::cout << "There are " << index_vec.size() << " IBM indices" << std::endl;
// You can write the data to a file or stdout in a few formats
// You must specify all the column types, but only once
// When writing to a file, the file name/path must be create-able.
//
ul_df2.write<std::ostream, std::string, double>(std::cout, io_format::csv2);
ibm_df.write<double, long>("/tmp/test.json", io_format::json);
// You can convert a DataFrame to a string and from a string back into a DataFrame.
// This could be used to transmit a DataFrame from one place to another
// or store a DataFrame in databases, caches, …
//
const std::string str_ibm = ibm_df.to_string<double, long>();
StrDataFrame ibm_df_2;
// Since we convert from native type to string and back, if you have
// floating point numbers with long precisions, you may run into precision mismatches.
// to_string() has a precision parameter you can adjust. The default is 12
// which is a relatively high precision.
//
ibm_df_2.from_string(str_ibm.c_str());
// std::cout << str_ibm << std::endl;
using ul_idx_t = ULDataFrame::IndexType; // This is just unsigned long
// You can sort by one or multiple columns. You must specify all the column types, but only once
// Sort first by the index column in ascending order then by "string col" column in descending order
//
ul_df2.sort<ul_idx_t, std::string, double, std::string>(DF_INDEX_COL_NAME, sort_spec::ascen,
"string col", sort_spec::desce);
// You could get another DataFrame by selecting on one or multiple columns
// You must specify all the column types, but only once
//
auto functor =
[](const std::string &, const double &val)-> bool { return (val > 150.0); };
auto above_150_df =
ibm_df.get_data_by_sel<double, decltype(functor), double, long>("IBM_Close", functor);
// Or, you could choose to get a view. See docs for views
//
auto above_150_view =
ibm_df.get_view_by_sel<double, decltype(functor), double, long>("IBM_Close", functor);
// You can get another DataFrame by group-bying on one or multiple columns
// You must specify only the type(s) of column(s), you are group-bying
//
// Group-by column dbl_col, and I am specifying how to summarize the index
// column and each of the other columns
//
auto gb_df =
ul_df1.groupby1<double>("dbl_col",
LastVisitor<ul_idx_t, ul_idx_t>(),
std::make_tuple("integers", "sum_int", SumVisitor<int>()),
std::make_tuple("my_data_col", "last_my_data", LastVisitor<MyData>()));
// You can run statistical, financial, ML, … algorithms on one or multiple
// columns by using visitors. You must specify the column(s) type(s)
//
StdVisitor<double, std::string> ibm_stdev;
ibm_df.visit<double>("IBM_Close", ibm_stdev);
std::cout << "Standard deviation of IBM close prices: " << ibm_stdev.get_result()
<< std::endl;
// Now, let’s declare two DataFrames with index type of DateTime
// which is a handy object for date/time manipulations.
//
DTDataFrame dt_ibm;
DTDataFrame dt_aapl;
// Let’s read the AAPL and IBM market data from their files.
// The data for these two stocks start and end at different dates.
// But there is overlapping data between them
//
dt_ibm.read("data/DT_IBM.csv", io_format::csv2);
dt_aapl.read("data/DT_AAPL.csv", io_format::csv2);
// Now we join the AAPL and IBM DataFrames using their indices and applying inner-join policy
//
DTDataFrame aapl_ibm = dt_ibm.join_by_index<DTDataFrame, double, long>(dt_aapl, join_policy::inner_join);
// Now we calculate the Pearson correlation coefficient between AAPL and IBM close prices
//
CorrVisitor<double, DateTime> aapl_ibm_corrl;
std::cout << "Correlation between AAPL and IBM close prices: "
<< aapl_ibm.visit<double, double>("AAPL_Close", "IBM_Close", aapl_ibm_corrl).get_result()
<< std::endl;
using dt_idx_t = DTDataFrame::IndexType; // This is just DateTime
// Appel data are daily. Let’s create 10-day OHLC (plus mean, std, total volume) for close prices.
//
DTDataFrame aapl_ohlc =
dt_aapl.bucketize(bucket_type::by_count,
10,
LastVisitor<dt_idx_t, dt_idx_t>(),
std::make_tuple("AAPL_Close", "Open", FirstVisitor<double, dt_idx_t>()),
std::make_tuple("AAPL_Close", "High", MaxVisitor<double, dt_idx_t>()),
std::make_tuple("AAPL_Close", "Low", MinVisitor<double, dt_idx_t>()),
std::make_tuple("AAPL_Close", "Close", LastVisitor<double, dt_idx_t>()),
std::make_tuple("AAPL_Close", "Mean", MeanVisitor<double, dt_idx_t>()),
std::make_tuple("AAPL_Close", "Std", StdVisitor<double, dt_idx_t>()),
std::make_tuple("AAPL_Volume", "Volume", SumVisitor<long, dt_idx_t>()));
// Now, let's get a view of a random sample of appel data.
// We randomly sample 35% of the data
//
auto random_view =
dt_aapl.get_view_by_rand<double, long>(random_policy::frac_rows_no_seed, 0.35);
return (0);
}
// -----------------------------------------------------------------------------
// Local Variables:
// mode:C++
// tab-width:4
// c-basic-offset:4
// End:
<|endoftext|> |
<commit_before>/*************************************************************************
*
* 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: refvaluecomponent.hxx,v $
* $Revision: 1.10 $
*
* 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 EFORMS2_FORMS_SOURCE_COMPONENT_REFVALUECOMPONENT_HXX
#define EFORMS2_FORMS_SOURCE_COMPONENT_REFVALUECOMPONENT_HXX
#include "FormComponent.hxx"
/** === begin UNO includes === **/
/** === end UNO includes === **/
//........................................................................
namespace frm
{
//........................................................................
enum CheckState { STATE_NOCHECK = 0, STATE_CHECK = 1, STATE_DONTKNOW = 2 };
//====================================================================
//= OReferenceValueComponent
//====================================================================
/** a OBoundControlModel which features the exchange of a reference value
*/
class OReferenceValueComponent : public OBoundControlModel
{
private:
// <properties>
::rtl::OUString m_sReferenceValue; // the reference value to use for data exchange
::rtl::OUString m_sNoCheckReferenceValue; // the reference value to be exchanged when the control is not checked
CheckState m_eDefaultChecked; // the default check state
// </properties>
sal_Bool m_bSupportSecondRefValue; // do we support the SecondaryRefValue property?
/** type how we should transfer our selection to external value bindings
*/
enum ValueExchangeType
{
eString,
eBoolean
};
ValueExchangeType m_eValueExchangeType;
protected:
const ::rtl::OUString& getReferenceValue() const { return m_sReferenceValue; }
void setReferenceValue( const ::rtl::OUString& _rRefValue );
const ::rtl::OUString& getNoCheckReferenceValue() const { return m_sNoCheckReferenceValue; }
CheckState getDefaultChecked() const { return m_eDefaultChecked; }
void setDefaultChecked( CheckState _eChecked ) { m_eDefaultChecked = _eChecked; }
protected:
OReferenceValueComponent(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory,
const ::rtl::OUString& _rUnoControlModelTypeName,
const ::rtl::OUString& _rDefault,
sal_Bool _bSupportNoCheckRefValue = sal_False
);
DECLARE_DEFAULT_CLONE_CTOR( OReferenceValueComponent )
DECLARE_DEFAULT_DTOR( OReferenceValueComponent );
// OPropertySet and friends
virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle) const;
virtual void SAL_CALL setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue )
throw (::com::sun::star::uno::Exception);
virtual sal_Bool SAL_CALL convertFastPropertyValue(
::com::sun::star::uno::Any& _rConvertedValue, ::com::sun::star::uno::Any& _rOldValue, sal_Int32 _nHandle, const ::com::sun::star::uno::Any& _rValue )
throw (::com::sun::star::lang::IllegalArgumentException);
virtual void describeFixedProperties(
::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rProps
) const;
using ::cppu::OPropertySetHelper::getFastPropertyValue;
// OBoundControlModel overridables
virtual void onConnectedExternalValue( );
virtual sal_Bool approveValueBinding( const ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XValueBinding >& _rxBinding );
virtual ::com::sun::star::uno::Any
translateExternalValueToControlValue( ) const;
virtual ::com::sun::star::uno::Any
translateControlValueToExternalValue( ) const;
virtual ::com::sun::star::uno::Any
translateControlValueToValidatableValue( ) const;
virtual ::com::sun::star::uno::Any
getDefaultForReset() const;
private:
/** calculates the data type we need to use to exchange values with external bindings
*/
void calcValueExchangeType();
};
//........................................................................
} // namespace frm
//........................................................................
#endif // EFORMS2_FORMS_SOURCE_COMPONENT_REFVALUECOMPONENT_HXX
<commit_msg>INTEGRATION: CWS dba30d (1.10.10); FILE MERGED 2008/05/27 12:28:03 fs 1.10.10.1: #i89657# refactoring, so that our binding's getValue is only called when our mutex is not locked<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: refvaluecomponent.hxx,v $
* $Revision: 1.11 $
*
* 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 EFORMS2_FORMS_SOURCE_COMPONENT_REFVALUECOMPONENT_HXX
#define EFORMS2_FORMS_SOURCE_COMPONENT_REFVALUECOMPONENT_HXX
#include "FormComponent.hxx"
/** === begin UNO includes === **/
/** === end UNO includes === **/
//........................................................................
namespace frm
{
//........................................................................
enum CheckState { STATE_NOCHECK = 0, STATE_CHECK = 1, STATE_DONTKNOW = 2 };
//====================================================================
//= OReferenceValueComponent
//====================================================================
/** a OBoundControlModel which features the exchange of a reference value
*/
class OReferenceValueComponent : public OBoundControlModel
{
private:
// <properties>
::rtl::OUString m_sReferenceValue; // the reference value to use for data exchange
::rtl::OUString m_sNoCheckReferenceValue; // the reference value to be exchanged when the control is not checked
CheckState m_eDefaultChecked; // the default check state
// </properties>
sal_Bool m_bSupportSecondRefValue; // do we support the SecondaryRefValue property?
protected:
const ::rtl::OUString& getReferenceValue() const { return m_sReferenceValue; }
void setReferenceValue( const ::rtl::OUString& _rRefValue );
const ::rtl::OUString& getNoCheckReferenceValue() const { return m_sNoCheckReferenceValue; }
CheckState getDefaultChecked() const { return m_eDefaultChecked; }
void setDefaultChecked( CheckState _eChecked ) { m_eDefaultChecked = _eChecked; }
protected:
OReferenceValueComponent(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory,
const ::rtl::OUString& _rUnoControlModelTypeName,
const ::rtl::OUString& _rDefault,
sal_Bool _bSupportNoCheckRefValue = sal_False
);
DECLARE_DEFAULT_CLONE_CTOR( OReferenceValueComponent )
DECLARE_DEFAULT_DTOR( OReferenceValueComponent );
// OPropertySet and friends
virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle) const;
virtual void SAL_CALL setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue )
throw (::com::sun::star::uno::Exception);
virtual sal_Bool SAL_CALL convertFastPropertyValue(
::com::sun::star::uno::Any& _rConvertedValue, ::com::sun::star::uno::Any& _rOldValue, sal_Int32 _nHandle, const ::com::sun::star::uno::Any& _rValue )
throw (::com::sun::star::lang::IllegalArgumentException);
virtual void describeFixedProperties(
::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rProps
) const;
using ::cppu::OPropertySetHelper::getFastPropertyValue;
// OBoundControlModel overridables
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type >
getSupportedBindingTypes();
virtual ::com::sun::star::uno::Any
translateExternalValueToControlValue( const ::com::sun::star::uno::Any& _rExternalValue ) const;
virtual ::com::sun::star::uno::Any
translateControlValueToExternalValue( ) const;
virtual ::com::sun::star::uno::Any
translateControlValueToValidatableValue( ) const;
virtual ::com::sun::star::uno::Any
getDefaultForReset() const;
};
//........................................................................
} // namespace frm
//........................................................................
#endif // EFORMS2_FORMS_SOURCE_COMPONENT_REFVALUECOMPONENT_HXX
<|endoftext|> |
<commit_before>/**
* SDL widgets example for Guichan.
*
* @author Kevin Lynx
* @author Olof Naessn
*/
// Include all necessary headers.
#include <guichan.hpp>
#include <guichan/hge.hpp>
#include <hge.h>
/*
* Common stuff we need
*/
HGE *hge = NULL;
bool running = false;
/*
* Guichan HGE stuff we need
*/
HGEInput *input; // Input driver
HGEGraphics *graphics; // Graphics driver
HGEImageLoader *imageLoader; // For loading images
HGEImageFont *font; // For displaying a font
/*
* Guichan stuff we need
*/
gcn::Gui *gui; // A Gui object - binds it all together
/*
* All of the default widgets
*/
gcn::Container *top; // A top container
gcn::Label* label; // A label
gcn::Icon* icon; // An icon (image)
gcn::Button* button; // A button
gcn::TextField* textField; // One-line text field
gcn::TextBox* textBox; // Multi-line text box
gcn::ScrollArea* textBoxScrollArea; // Scroll area for the text box
gcn::ListBox* listBox; // A list box
gcn::DropDown* dropDown; // Drop down
gcn::CheckBox* checkBox1; // Two checkboxes
gcn::CheckBox* checkBox2;
gcn::RadioButton* radioButton1; // Three radio buttons
gcn::RadioButton* radioButton2;
gcn::RadioButton* radioButton3;
gcn::Slider* slider; // A slider
gcn::Image *image; // An image for the icon
gcn::Window *window;
gcn::Image *darkbitsImage;
gcn::Icon* darkbitsIcon;
gcn::ScrollArea* nestedScrollArea;
gcn::Container* nestedContainer;
gcn::Slider* nestedSlider;
/*
* Forward declations
*/
void init();
void halt();
bool frameFunc();
/*
* List boxes and dropdowns needs an instance of a listmodel
* to know what elements they have.
*/
class DemoListModel : public gcn::ListModel
{
public:
int getNumberOfElements()
{
return 5;
}
std::string getElementAt(int i)
{
switch(i)
{
case 0:
return std::string("zero");
case 1:
return std::string("one");
case 2:
return std::string("two");
case 3:
return std::string("three");
case 4:
return std::string("four");
default: // Just to keep warnings away
return std::string("");
}
}
};
DemoListModel demoListModel;
void initWidgets()
{
/*
* Create all the widgets
*/
label = new gcn::Label("Label");
image = gcn::Image::load("gui-chan.png");
icon = new gcn::Icon(image);
button = new gcn::Button("Button");
textField = new gcn::TextField("Text field");
textBox = new gcn::TextBox("Multiline\nText box");
textBoxScrollArea = new gcn::ScrollArea(textBox);
textBoxScrollArea->setWidth(200);
textBoxScrollArea->setHeight(100);
textBoxScrollArea->setBorderSize(1);
listBox = new gcn::ListBox(&demoListModel);
listBox->setBorderSize(1);
dropDown = new gcn::DropDown(&demoListModel);
checkBox1 = new gcn::CheckBox("Checkbox 1");
checkBox2 = new gcn::CheckBox("Checkbox 2");
radioButton1 = new gcn::RadioButton("RadioButton 1", "radiogroup", true);
radioButton2 = new gcn::RadioButton("RadioButton 2", "radiogroup");
radioButton3 = new gcn::RadioButton("RadioButton 3", "radiogroup");
slider = new gcn::Slider(0, 10);
slider->setSize(100, 10);
window = new gcn::Window("I am a window Drag me");
window->setBaseColor(gcn::Color(255, 150, 200, 190));
darkbitsImage = gcn::Image::load("darkbitslogo_by_haiko.bmp");
darkbitsIcon = new gcn::Icon(darkbitsImage);
window->add(darkbitsIcon);
window->resizeToContent();
nestedSlider = new gcn::Slider(0, 10);
nestedSlider->setSize(100, 10);
nestedContainer = new gcn::Container();
nestedContainer->setSize(400, 200);
nestedContainer->add(nestedSlider, 50, 70);
nestedScrollArea = new gcn::ScrollArea(nestedContainer);
nestedScrollArea->setSize(180, 90);
nestedScrollArea->setBorderSize(1);
/*
* Add them to the top container
*/
top->add(label, 10, 10);
top->add(icon, 10, 30);
top->add(button, 200, 10);
top->add(textField, 300, 10);
top->add(textBoxScrollArea, 200, 50);
top->add(listBox, 200, 200);
top->add(dropDown, 500, 10);
top->add(checkBox1, 500, 130);
top->add(checkBox2, 500, 150);
top->add(radioButton1, 500, 200);
top->add(radioButton2, 500, 220);
top->add(radioButton3, 500, 240);
top->add(slider, 500, 300);
top->add(window, 100, 350);
top->add(nestedScrollArea, 440, 350);
}
/**
* Initializes the application
*/
void init()
{
imageLoader = new gcn::HGEImageLoader();
// The ImageLoader in use is static and must be set to be
// able to load images
Image::setImageLoader(imageLoader);
graphics = new gcn::HGEGraphics();
input = new gcn::HGEInput();
/*
* Last but not least it's time to initialize and create the gui
* with Guichan stuff.
*/
top = new gcn::Container();
top->setDimension(gcn::Rectangle(0, 0, 640, 480));
gui = new gcn::Gui();
// Set gui to use the HGEGraphics object.
gui->setGraphics(graphics);
// Set gui to use the HGEInput object
gui->setInput(input);
// Set the top container
gui->setTop(top);
// Load the HGE image font.
font = new gcn::HGEImageFont("font2.fnt");
// The global font is static and must be set.
gcn::Widget::setGlobalFont(font);
initWidgets();
}
void halt()
{
/*
* Destroy Guichan stuff
*/
delete font;
delete gui;
/*
* Widgets
*/
delete label;
delete icon;
delete button;
delete textField;
delete textBox;
delete textBoxScrollArea;
delete listBox;
delete dropDown;
delete checkBox1;
delete checkBox2;
delete radioButton1;
delete radioButton2;
delete radioButton3;
delete slider;
delete window;
delete darkbitsIcon;
delete darkbitsImage;
delete nestedScrollArea;
delete nestedContainer;
delete nestedSlider;
/*
* Destroy Guichan HGE stuff
*/
delete nput;
delete graphics;
delete imageLoader;
}
bool frameFunc()
{
if (hge->Input_GetKeyState(HGEK_ESCAPE) || running)
{
return true;
}
// Let the gui perform it's logic (like handle input)
gui->logic();
// Begin rendering
hge->Gfx_BeginScene();
hge->Gfx_Clear( 0 );
// Draw the gui
gui->draw();
// End rendering
hge->Gfx_EndScene();
return false;
}
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
hge = hgeCreate(HGE_VERSION);
hge->System_SetState(HGE_FRAMEFUNC, frameFunc);
hge->System_SetState(HGE_TITLE, "Guichan with HGE Demo : Created By Kevin Lynx 2007-03-16");
hge->System_SetState(HGE_SCREENWIDTH, 640);
hge->System_SetState(HGE_SCREENHEIGHT, 480);
hge->System_SetState(HGE_WINDOWED, true);
hge->System_SetState(HGE_HIDEMOUSE, false);
hge->System_SetState(HGE_USESOUND, false);
#ifdef _DEBUG
hge->System_SetState(HGE_LOGFILE, "log.txt");
#endif
try
{
if (hge->System_Initiate())
{
init();
hge->System_Start();
}
else
{
MessageBox(NULL, hge->System_GetErrorMessage(), "Error", MB_OK | MB_ICONERROR | MB_SYSTEMMODAL);
}
halt();
hge->System_Shutdown();
hge->Release();
return 0;
}
/*
* Catch all Guichan exceptions
*/
catch (gcn::Exception e)
{
MessageBox(NULL, hge->System_GetErrorMessage(), e.getMessage().c_str(), MB_OK | MB_ICONERROR | MB_SYSTEMMODAL);
return 1;
}
/*
* Catch all Std exceptions
*/
catch (std::exception e)
{
MessageBox(NULL, hge->System_GetErrorMessage(), e.what().c_str(), MB_OK | MB_ICONERROR | MB_SYSTEMMODAL);
return 1;
}
/*
* Catch all Unknown exceptions
*/
catch (...)
{
MessageBox(NULL, hge->System_GetErrorMessage(), "Unknown exception", MB_OK | MB_ICONERROR | MB_SYSTEMMODAL);
return 1;
}
}
<commit_msg>A copy paste error in a comment has been fixed.<commit_after>/**
* HGE widgets example for Guichan.
*
* @author Kevin Lynx
* @author Olof Naessn
*/
// Include all necessary headers.
#include <guichan.hpp>
#include <guichan/hge.hpp>
#include <hge.h>
/*
* Common stuff we need
*/
HGE *hge = NULL;
bool running = false;
/*
* Guichan HGE stuff we need
*/
HGEInput *input; // Input driver
HGEGraphics *graphics; // Graphics driver
HGEImageLoader *imageLoader; // For loading images
HGEImageFont *font; // For displaying a font
/*
* Guichan stuff we need
*/
gcn::Gui *gui; // A Gui object - binds it all together
/*
* All of the default widgets
*/
gcn::Container *top; // A top container
gcn::Label* label; // A label
gcn::Icon* icon; // An icon (image)
gcn::Button* button; // A button
gcn::TextField* textField; // One-line text field
gcn::TextBox* textBox; // Multi-line text box
gcn::ScrollArea* textBoxScrollArea; // Scroll area for the text box
gcn::ListBox* listBox; // A list box
gcn::DropDown* dropDown; // Drop down
gcn::CheckBox* checkBox1; // Two checkboxes
gcn::CheckBox* checkBox2;
gcn::RadioButton* radioButton1; // Three radio buttons
gcn::RadioButton* radioButton2;
gcn::RadioButton* radioButton3;
gcn::Slider* slider; // A slider
gcn::Image *image; // An image for the icon
gcn::Window *window;
gcn::Image *darkbitsImage;
gcn::Icon* darkbitsIcon;
gcn::ScrollArea* nestedScrollArea;
gcn::Container* nestedContainer;
gcn::Slider* nestedSlider;
/*
* Forward declations
*/
void init();
void halt();
bool frameFunc();
/*
* List boxes and dropdowns needs an instance of a listmodel
* to know what elements they have.
*/
class DemoListModel : public gcn::ListModel
{
public:
int getNumberOfElements()
{
return 5;
}
std::string getElementAt(int i)
{
switch(i)
{
case 0:
return std::string("zero");
case 1:
return std::string("one");
case 2:
return std::string("two");
case 3:
return std::string("three");
case 4:
return std::string("four");
default: // Just to keep warnings away
return std::string("");
}
}
};
DemoListModel demoListModel;
void initWidgets()
{
/*
* Create all the widgets
*/
label = new gcn::Label("Label");
image = gcn::Image::load("gui-chan.png");
icon = new gcn::Icon(image);
button = new gcn::Button("Button");
textField = new gcn::TextField("Text field");
textBox = new gcn::TextBox("Multiline\nText box");
textBoxScrollArea = new gcn::ScrollArea(textBox);
textBoxScrollArea->setWidth(200);
textBoxScrollArea->setHeight(100);
textBoxScrollArea->setBorderSize(1);
listBox = new gcn::ListBox(&demoListModel);
listBox->setBorderSize(1);
dropDown = new gcn::DropDown(&demoListModel);
checkBox1 = new gcn::CheckBox("Checkbox 1");
checkBox2 = new gcn::CheckBox("Checkbox 2");
radioButton1 = new gcn::RadioButton("RadioButton 1", "radiogroup", true);
radioButton2 = new gcn::RadioButton("RadioButton 2", "radiogroup");
radioButton3 = new gcn::RadioButton("RadioButton 3", "radiogroup");
slider = new gcn::Slider(0, 10);
slider->setSize(100, 10);
window = new gcn::Window("I am a window Drag me");
window->setBaseColor(gcn::Color(255, 150, 200, 190));
darkbitsImage = gcn::Image::load("darkbitslogo_by_haiko.bmp");
darkbitsIcon = new gcn::Icon(darkbitsImage);
window->add(darkbitsIcon);
window->resizeToContent();
nestedSlider = new gcn::Slider(0, 10);
nestedSlider->setSize(100, 10);
nestedContainer = new gcn::Container();
nestedContainer->setSize(400, 200);
nestedContainer->add(nestedSlider, 50, 70);
nestedScrollArea = new gcn::ScrollArea(nestedContainer);
nestedScrollArea->setSize(180, 90);
nestedScrollArea->setBorderSize(1);
/*
* Add them to the top container
*/
top->add(label, 10, 10);
top->add(icon, 10, 30);
top->add(button, 200, 10);
top->add(textField, 300, 10);
top->add(textBoxScrollArea, 200, 50);
top->add(listBox, 200, 200);
top->add(dropDown, 500, 10);
top->add(checkBox1, 500, 130);
top->add(checkBox2, 500, 150);
top->add(radioButton1, 500, 200);
top->add(radioButton2, 500, 220);
top->add(radioButton3, 500, 240);
top->add(slider, 500, 300);
top->add(window, 100, 350);
top->add(nestedScrollArea, 440, 350);
}
/**
* Initializes the application
*/
void init()
{
imageLoader = new gcn::HGEImageLoader();
// The ImageLoader in use is static and must be set to be
// able to load images
Image::setImageLoader(imageLoader);
graphics = new gcn::HGEGraphics();
input = new gcn::HGEInput();
/*
* Last but not least it's time to initialize and create the gui
* with Guichan stuff.
*/
top = new gcn::Container();
top->setDimension(gcn::Rectangle(0, 0, 640, 480));
gui = new gcn::Gui();
// Set gui to use the HGEGraphics object.
gui->setGraphics(graphics);
// Set gui to use the HGEInput object
gui->setInput(input);
// Set the top container
gui->setTop(top);
// Load the HGE image font.
font = new gcn::HGEImageFont("font2.fnt");
// The global font is static and must be set.
gcn::Widget::setGlobalFont(font);
initWidgets();
}
void halt()
{
/*
* Destroy Guichan stuff
*/
delete font;
delete gui;
/*
* Widgets
*/
delete label;
delete icon;
delete button;
delete textField;
delete textBox;
delete textBoxScrollArea;
delete listBox;
delete dropDown;
delete checkBox1;
delete checkBox2;
delete radioButton1;
delete radioButton2;
delete radioButton3;
delete slider;
delete window;
delete darkbitsIcon;
delete darkbitsImage;
delete nestedScrollArea;
delete nestedContainer;
delete nestedSlider;
/*
* Destroy Guichan HGE stuff
*/
delete nput;
delete graphics;
delete imageLoader;
}
bool frameFunc()
{
if (hge->Input_GetKeyState(HGEK_ESCAPE) || running)
{
return true;
}
// Let the gui perform it's logic (like handle input)
gui->logic();
// Begin rendering
hge->Gfx_BeginScene();
hge->Gfx_Clear( 0 );
// Draw the gui
gui->draw();
// End rendering
hge->Gfx_EndScene();
return false;
}
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
hge = hgeCreate(HGE_VERSION);
hge->System_SetState(HGE_FRAMEFUNC, frameFunc);
hge->System_SetState(HGE_TITLE, "Guichan with HGE Demo : Created By Kevin Lynx 2007-03-16");
hge->System_SetState(HGE_SCREENWIDTH, 640);
hge->System_SetState(HGE_SCREENHEIGHT, 480);
hge->System_SetState(HGE_WINDOWED, true);
hge->System_SetState(HGE_HIDEMOUSE, false);
hge->System_SetState(HGE_USESOUND, false);
#ifdef _DEBUG
hge->System_SetState(HGE_LOGFILE, "log.txt");
#endif
try
{
if (hge->System_Initiate())
{
init();
hge->System_Start();
}
else
{
MessageBox(NULL, hge->System_GetErrorMessage(), "Error", MB_OK | MB_ICONERROR | MB_SYSTEMMODAL);
}
halt();
hge->System_Shutdown();
hge->Release();
return 0;
}
/*
* Catch all Guichan exceptions
*/
catch (gcn::Exception e)
{
MessageBox(NULL, hge->System_GetErrorMessage(), e.getMessage().c_str(), MB_OK | MB_ICONERROR | MB_SYSTEMMODAL);
return 1;
}
/*
* Catch all Std exceptions
*/
catch (std::exception e)
{
MessageBox(NULL, hge->System_GetErrorMessage(), e.what().c_str(), MB_OK | MB_ICONERROR | MB_SYSTEMMODAL);
return 1;
}
/*
* Catch all Unknown exceptions
*/
catch (...)
{
MessageBox(NULL, hge->System_GetErrorMessage(), "Unknown exception", MB_OK | MB_ICONERROR | MB_SYSTEMMODAL);
return 1;
}
}
<|endoftext|> |
<commit_before>#include <algorithm>
#include <cassert>
#include <fstream>
#include <iostream>
#include <sys/time.h>
const int NX=1024, NY= 1024, N_TIME=1024;
const int X_MASK = NX-1, Y_MASK = NY-1;
const int NS=1;
const int NT=64;
const int NG=NT/NS/2; // 32
const int NTO=NX/NT; // 16
const int NF=NX/NT*NG; // 16*32 = 512
using namespace std;
double dens[NY][NX];
double dens_next[NY][NX];
double dens_std[NY][NX];
double dens_pitch[NY][NX];
double second()
{
struct timeval tm;
double t ;
static int base_sec = 0,base_usec = 0;
gettimeofday(&tm, NULL);
if(base_sec == 0 && base_usec == 0)
{
base_sec = tm.tv_sec;
base_usec = tm.tv_usec;
t = 0.0;
} else {
t = (double) (tm.tv_sec-base_sec) +
((double) (tm.tv_usec-base_usec))/1.0e6 ;
}
return t ;
}
void init() {
for (int y=0;y<NY; ++y) {
for (int x=0; x<NX; ++x) {
int p1=x, p2=y, fac=1, sum=0;
int pat[4] = {0,1,2,-3};
while(p1!=0 || p2!=0) {
sum += fac * pat[(p1&1)*2+(p2&1)];
fac *= 2;p1>>=1; p2>>=1;
}
dens[y][x]=sum;
}
}
}
void dump(const char *fn) {
ofstream ofs(fn);
for (int y=0;y<NY; ++y) {
for (int x=0; x<NX; ++x) {
ofs << x << " " << y << " " << dens[y][x] << endl;
}
ofs << endl;
}
}
#define dens_at(y,x) dens[(y)&Y_MASK][(x)&X_MASK]
void proceed(){
for (int y=0;y<NY; ++y) {
for (int x=0; x<NX; ++x) {
dens_next[y][x]=0.5*dens[y][x]+
0.125*((dens_at(y,x-1)+dens_at(y,x+1))
+(dens_at(y-1,x)+dens_at(y+1,x)));
}
}
swap(dens, dens_next);
}
double pad[NT+2*NS][NT+2*NS];
double yslabs[NTO][NTO][NF][NT][2] = {0};
double xslabs[NTO][NTO][NF][NT][2] = {0};
double sticks[NTO][NTO][NT][4] = {0};
double pads[NTO][NTO][NT+2*NS][NT+2*NS] = {0};
#define dens_at_pitch(y,x) pad[(y)][(x)]
void proceed_region
( double yslab[NF][NT][2],
double xslab[NF][NT][2],
double stick[NF][4],
double yslab_next[NF][NT][2],
double xslab_next[NF][NT][2],
double stick_next[NF][4]
) {
for(int t=0; t<NF; ++t){
for (int i=0;i<NT;++i) {
pad[i][NT] = yslab[t][i][0];
pad[i][NT+1] = yslab[t][i][1];
pad[NT][i] = xslab[t][i][0];
pad[NT+1][i] = xslab[t][i][1];
}
pad[NT][NT]=stick[t][0];
pad[NT][NT+1]=stick[t][1];
pad[NT+1][NT]=stick[t][2];
pad[NT+1][NT+1]=stick[t][3];
for(int y=1;y<=NT;++y) {
for(int x=1;x<=NT;++x) {
pad[y-1][x-1] =
0.5*dens_at_pitch(y,x);
0.125*((dens_at_pitch(y,x-1)+dens_at_pitch(y,x+1))
+(dens_at_pitch(y-1,x)+dens_at_pitch(y+1,x)));
}
}
for (int i=0;i<NT;++i) {
yslab_next[t][i][0] = pad[i][0] ;
yslab_next[t][i][1] = pad[i][1] ;
xslab_next[t][i][0] = pad[0][i] ;
xslab_next[t][i][1] = pad[1][i] ;
}
stick[t][0] = pad[0][0];
stick[t][1] = pad[0][1];
stick[t][2] = pad[1][0];
stick[t][3] = pad[1][1];
}
}
void compute_pitch() {
for (int large_t=0; large_t < N_TIME/NF; ++large_t) {
for (int tile_y=0;tile_y<NTO; ++tile_y) {
for (int tile_x=0;tile_x<NTO; ++tile_x) {
proceed_region(yslabs[tile_y][tile_x], xslabs[tile_y][tile_x], sticks[tile_y][tile_x],
yslabs[tile_y][tile_x], xslabs[tile_y][tile_x], sticks[tile_y][tile_x]);
}
}
}
}
int main(){
cout << "yslabs " << (NTO)*(NTO)*(NF)*(NT)*(2) << endl;
cout << "xslabs " << (NTO)*(NTO)*(NF)*(NT)*(2) << endl;
cout << "sticks " << (NTO)*(NTO)*(NT)*(4) << endl;
cout << "pads " << (NTO)*(NTO)*(NT+2*NS)*(NT+2*NS) << endl;
init();
double wct0 = second();
for(int t=0; t<N_TIME; ++t){
proceed();
}
double wct1 = second();
double flops = double(NX*NY)*N_TIME*6.0/(wct1-wct0);
cerr << flops << " FLOP/s" << endl;
dump("test.txt");
wct0 = second();
compute_pitch();
wct1 = second();
flops = double(NX*NY)*N_TIME*6.0/(wct1-wct0);
cerr << flops << " FLOP/s" << endl;
flops = double(N_TIME/NF)*NTO*NTO*NF*NT*NT*6.0/(wct1-wct0);
cerr << flops << " FLOP/s" << endl;
}
<commit_msg>debug output<commit_after>#include <algorithm>
#include <cassert>
#include <fstream>
#include <iostream>
#include <sys/time.h>
//const int NX=1024, NY= 1024, N_TIME=1024;
const int NX=512, NY= 512, N_TIME=512;
const int X_MASK = NX-1, Y_MASK = NY-1;
const int NS=1;
const int NT=64;
const int T_MASK = NT-1;
const int NG=NT/NS/2; // 32
const int NTO=NX/NT; // 16
const int NF=NX/NT*NG; // 16*32 = 512
using namespace std;
double dens[NY][NX];
double dens_next[NY][NX];
double dens_std[NY][NX];
double dens_pitch[NY][NX];
double second()
{
struct timeval tm;
double t ;
static int base_sec = 0,base_usec = 0;
gettimeofday(&tm, NULL);
if(base_sec == 0 && base_usec == 0)
{
base_sec = tm.tv_sec;
base_usec = tm.tv_usec;
t = 0.0;
} else {
t = (double) (tm.tv_sec-base_sec) +
((double) (tm.tv_usec-base_usec))/1.0e6 ;
}
return t ;
}
void init() {
for (int y=0;y<NY; ++y) {
for (int x=0; x<NX; ++x) {
int p1=x, p2=y, fac=1, sum=0;
int pat[4] = {0,1,2,-3};
while(p1!=0 || p2!=0) {
sum += fac * pat[(p1&1)*2+(p2&1)];
fac *= 2;p1>>=1; p2>>=1;
}
dens[y][x]=sum;
}
}
}
void dump(const char *fn) {
ofstream ofs(fn);
for (int y=0;y<NY; ++y) {
for (int x=0; x<NX; ++x) {
ofs << x << " " << y << " " << dens[y][x] << endl;
}
ofs << endl;
}
}
#define dens_at(y,x) dens[(y)&Y_MASK][(x)&X_MASK]
void proceed(){
for (int y=0;y<NY; ++y) {
for (int x=0; x<NX; ++x) {
dens_next[y][x]=0.5*dens[y][x]+
0.125*((dens_at(y,x-1)+dens_at(y,x+1))
+(dens_at(y-1,x)+dens_at(y+1,x)));
}
}
swap(dens, dens_next);
}
double pad[NT+2*NS][NT+2*NS];
double yslabs[NTO][NTO][NF][NT][2] = {0};
double xslabs[NTO][NTO][NF][NT][2] = {0};
double sticks[NTO][NTO][NT][4] = {0};
double pads[NTO][NTO][NT][NT] = {0};
#define dens_at_pitch(y,x) pad[(y)][(x)]
void proceed_region
( double yslab[NF][NT][2],
double xslab[NF][NT][2],
double stick[NF][4],
double pad_input[NT][NT],
double yslab_next[NF][NT][2],
double xslab_next[NF][NT][2],
double stick_next[NF][4],
double pad_next[NT][NT]
) {
for(int y=0;y<NT;++y) {
for(int x=0;x<NT;++x) {
pad[y][x] = pad_input[y][x];
}
}
for(int t=0; t<NF; ++t){
for (int i=0;i<NT;++i) {
pad[i][NT] = yslab[t][i][0];
pad[i][NT+1] = yslab[t][i][1];
pad[NT][i] = xslab[t][i][0];
pad[NT+1][i] = xslab[t][i][1];
}
pad[NT][NT]=stick[t][0];
pad[NT][NT+1]=stick[t][1];
pad[NT+1][NT]=stick[t][2];
pad[NT+1][NT+1]=stick[t][3];
for(int y=1;y<=NT;++y) {
for(int x=1;x<=NT;++x) {
pad[y-1][x-1] =
0.5*dens_at_pitch(y,x);
0.125*((dens_at_pitch(y,x-1)+dens_at_pitch(y,x+1))
+(dens_at_pitch(y-1,x)+dens_at_pitch(y+1,x)));
}
}
for (int i=0;i<NT;++i) {
yslab_next[t][i][0] = pad[i][0] ;
yslab_next[t][i][1] = pad[i][1] ;
xslab_next[t][i][0] = pad[0][i] ;
xslab_next[t][i][1] = pad[1][i] ;
}
stick_next[t][0] = pad[0][0];
stick_next[t][1] = pad[0][1];
stick_next[t][2] = pad[1][0];
stick_next[t][3] = pad[1][1];
}
for(int y=0;y<NT;++y) {
for(int x=0;x<NT;++x) {
pad_next[y][x] = pad[y][x];
}
}
}
void compute_pitch() {
for (int large_t=0; large_t < N_TIME/NF; ++large_t) {
for (int y5=NTO;y5>=0; --y5) {
for (int x5=NTO;x5>=0; --x5) {
int x4=(x5-1) & NTO;
int y4=(y5-1) & NTO;
proceed_region(yslabs[y5][x5], xslabs[y5][x5], sticks[y5][x5],pads[y5][x5],
yslabs[y4][x5], xslabs[y5][x4], sticks[y4][x4],pads[y5][x5]);
}
}
}
}
int main(){
cout << "yslabs " << (NTO)*(NTO)*(NF)*(NT)*(2) << endl;
cout << "xslabs " << (NTO)*(NTO)*(NF)*(NT)*(2) << endl;
cout << "sticks " << (NTO)*(NTO)*(NT)*(4) << endl;
cout << "pads " << (NTO)*(NTO)*(NT+2*NS)*(NT+2*NS) << endl;
init();
double wct0 = second();
for(int t=0; t<N_TIME; ++t){
proceed();
}
double wct1 = second();
double flops = double(NX*NY)*N_TIME*6.0/(wct1-wct0);
cerr << flops << " FLOP/s" << endl;
dump("test.txt");
init();
for (int y=0;y<NY; ++y) {
for (int x=0; x<NX; ++x) {
pads[y/NT][x/NT][y&T_MASK][x&T_MASK] = dens[y][x];
}
}
wct0 = second();
compute_pitch();
wct1 = second();
flops = double(NX*NY)*N_TIME*6.0/(wct1-wct0);
cerr << flops << " FLOP/s" << endl;
flops = double(N_TIME/NF)*NTO*NTO*NF*NT*NT*6.0/(wct1-wct0);
cerr << flops << " FLOP/s" << endl;
init();
for (int y=0;y<NY; ++y) {
for (int x=0; x<NX; ++x) {
dens[y][x] = pads[y/NT][x/NT][y&T_MASK][x&T_MASK];
}
}
dump("test-pitch.txt");
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <sstream>
#include <Jatta.h>
using namespace Jatta;
/** @brief Loads a shader from a vertex file and a fragment file.
* @param vertexFile The file name of the vertex shader.
* @param fragmentFile The file name of the fragment shader.
* @return The compile program.
*/
Jatta::OpenGL::Program LoadShader(const String& vertexFile, const String& fragmentFile)
{
// Create the shaders
OpenGL::Shader vertexShader, fragmentShader;
vertexShader.Create(Jatta::OpenGL::GL::VERTEX_SHADER);
fragmentShader.Create(Jatta::OpenGL::GL::FRAGMENT_SHADER);
// Load the contents of the files
String vertexSource, fragmentSource;
if (!Jatta::File::GetText(vertexFile, &vertexSource))
{
std::ostringstream ss;
ss << "Failed to load vertex shader \"" << vertexFile << "\"!";
throw std::runtime_error(ss.str().c_str());
}
vertexShader.Source(vertexSource);
if (!Jatta::File::GetText(fragmentFile, &fragmentSource))
{
std::ostringstream ss;
ss << "Failed to load fragment shader \"" << fragmentFile << "\"!";
throw std::runtime_error(ss.str().c_str());
}
fragmentShader.Source(fragmentSource);
// Compile the vertex shader
vertexShader.Compile();
if (!vertexShader.GetCompileStatus())
{
std::ostringstream ss;
ss << "Failed to compile vertex shader \"" << vertexFile << "\":\n";
ss << vertexShader.GetInfoLog();
throw std::runtime_error(ss.str().c_str());
}
// Compile the vertex shader
fragmentShader.Compile();
if (!fragmentShader.GetCompileStatus())
{
std::ostringstream ss;
ss << "Failed to compile fragment shader \"" << fragmentFile << "\":\n";
ss << fragmentShader.GetInfoLog();
throw std::runtime_error(ss.str().c_str());
}
// Create the program
OpenGL::Program program;
program.Create();
// Setup the attributes
program.BindAttribLocation(OpenGL::POSITION1, "vertPosition");
program.BindAttribLocation(OpenGL::TEXCOORD1, "vertTexCoord");
// Link the program
program.AttachShader(vertexShader);
program.AttachShader(fragmentShader);
program.Link();
if (!program.GetLinkStatus())
{
std::ostringstream ss;
ss << "Failed to link program (vert: \"" << vertexFile << "\", frag: \"" << fragmentFile << "\"):\n";
ss << program.GetInfoLog();
throw std::runtime_error(ss.str().c_str());
}
program.Validate();
if (!program.GetValidateStatus())
{
std::ostringstream ss;
ss << "Failed to validate program (vert: \"" << vertexFile << "\", frag: \"" << fragmentFile << "\"):\n";
ss << program.GetInfoLog();
throw std::runtime_error(ss.str().c_str());
}
return program;
}
/** @brief Creates a 2D box with coordinates from (0, 0) to (1, 1).
* @return The vertex array object.
*/
OpenGL::VertexArray MakeBox()
{
// Setup the buffer data
Float2 boxPositions[] = { Float2(0, 0), Float2(0, 1), Float2(1, 1), Float2(1, 0) };
Float2 boxTexCoords[] = { Float2(0, 0), Float2(0, 1), Float2(1, 1), Float2(1, 0) };
// Create the vertex array object
OpenGL::VertexArray vertexArray;
vertexArray.Create();
vertexArray.Bind();
// Setup the position buffer and attach it to the vertex array
OpenGL::Buffer buffer1;
buffer1.Create(OpenGL::GL::ARRAY_BUFFER);
buffer1.Bind();
buffer1.Data(4 * sizeof(Float2), boxPositions, OpenGL::GL::STATIC_DRAW);
vertexArray.AttribPointer(OpenGL::POSITION1, 2, OpenGL::GL::FLOAT, false, 0, 0);
vertexArray.EnableAttribArray(OpenGL::POSITION1);
// Setup the texcoord buffer and attach it to the vertex array
OpenGL::Buffer buffer2;
buffer2.Create(OpenGL::GL::ARRAY_BUFFER);
buffer2.Bind();
buffer2.Data(4 * sizeof(Float2), boxTexCoords, OpenGL::GL::STATIC_DRAW);
vertexArray.AttribPointer(OpenGL::TEXCOORD1, 2, OpenGL::GL::FLOAT, false, 0, 0);
vertexArray.EnableAttribArray(OpenGL::TEXCOORD1);
// All done
vertexArray.Unbind();
return vertexArray;
}
int main()
{
Jatta::Matrix wee;
wee[1][2] = 5;
std::cout << wee << std::endl;
try
{
// Setup the window
WindowStyle style;
style.title = "Jatta Window";
style.width = 640;
style.height = 480;
style.backgroundColor = Colors::black;
style.resizable = false;
Window window;
window.Create(style);
window.SetTitle("こんにちわ");
// Create the OpenGL context
OpenGL::Context context;
context.Create(&window);
OpenGL::Program program = LoadShader("Resources/screen.vert", "Resources/screen.frag");
Image image;
image.LoadPng("Resources/sky.png");
OpenGL::Texture texture;
texture.Create(OpenGL::GL::TEXTURE_2D);
texture.Bind();
texture.SetTextureWrapS(OpenGL::GL::REPEAT);
texture.SetTextureWrapT(OpenGL::GL::REPEAT);
texture.SetMinFilter(OpenGL::GL::LINEAR);
texture.SetMagFilter(OpenGL::GL::LINEAR);
texture.Image2D(0, OpenGL::GL::RGBA, image.GetWidth(), image.GetHeight(), 0, OpenGL::GL::RGBA, OpenGL::GL::UNSIGNED_BYTE, image.GetData());
texture.Unbind();
OpenGL::VertexArray box = MakeBox();
context.ClearColor(Colors::red);
while (window.IsOpen())
{
Window::Update();
context.Viewport(0, 0, window.GetWidth(), window.GetHeight());
context.Clear(OpenGL::GL::COLOR_BUFFER_BIT | OpenGL::GL::DEPTH_BUFFER_BIT);
program.Bind();
OpenGL::Program::UniformMatrix4f(program.GetUniformLocation("orthoMatrix"), false, Matrix::MakeOrtho(0, 1, 1, 0));
OpenGL::Program::UniformMatrix4f(program.GetUniformLocation("modelMatrix"), false, Matrix::Identity());
OpenGL::Program::Uniform1i(program.GetUniformLocation("texture"), 0);
OpenGL::ClearErrors();
OpenGL::Texture::Active(0);
texture.Bind();
box.Bind();
box.DrawArrays(OpenGL::GL::QUADS, 0, 4);
box.Unbind();
program.Unbind();
context.SwapBuffers();
}
}
catch (std::exception& e)
{
std::cout << e.what() << std::endl;
}
}
<commit_msg>Fixed image example.<commit_after>#include <iostream>
#include <sstream>
#include <Jatta.h>
using namespace Jatta;
/** @brief Loads a shader from a vertex file and a fragment file.
* @param vertexFile The file name of the vertex shader.
* @param fragmentFile The file name of the fragment shader.
* @return The compile program.
*/
Jatta::OpenGL::Program LoadShader(const String& vertexFile, const String& fragmentFile)
{
// Create the shaders
OpenGL::Shader vertexShader, fragmentShader;
vertexShader.Create(Jatta::OpenGL::GL::VERTEX_SHADER);
fragmentShader.Create(Jatta::OpenGL::GL::FRAGMENT_SHADER);
// Load the contents of the files
String vertexSource, fragmentSource;
if (!Jatta::File::GetText(vertexFile, &vertexSource))
{
std::ostringstream ss;
ss << "Failed to load vertex shader \"" << vertexFile << "\"!";
throw std::runtime_error(ss.str().c_str());
}
vertexShader.Source(vertexSource);
if (!Jatta::File::GetText(fragmentFile, &fragmentSource))
{
std::ostringstream ss;
ss << "Failed to load fragment shader \"" << fragmentFile << "\"!";
throw std::runtime_error(ss.str().c_str());
}
fragmentShader.Source(fragmentSource);
// Compile the vertex shader
vertexShader.Compile();
if (!vertexShader.GetCompileStatus())
{
std::ostringstream ss;
ss << "Failed to compile vertex shader \"" << vertexFile << "\":\n";
ss << vertexShader.GetInfoLog();
throw std::runtime_error(ss.str().c_str());
}
// Compile the vertex shader
fragmentShader.Compile();
if (!fragmentShader.GetCompileStatus())
{
std::ostringstream ss;
ss << "Failed to compile fragment shader \"" << fragmentFile << "\":\n";
ss << fragmentShader.GetInfoLog();
throw std::runtime_error(ss.str().c_str());
}
// Create the program
OpenGL::Program program;
program.Create();
// Setup the attributes
program.BindAttribLocation(OpenGL::POSITION1, "vertPosition");
program.BindAttribLocation(OpenGL::TEXCOORD1, "vertTexCoord");
// Link the program
program.AttachShader(vertexShader);
program.AttachShader(fragmentShader);
program.Link();
if (!program.GetLinkStatus())
{
std::ostringstream ss;
ss << "Failed to link program (vert: \"" << vertexFile << "\", frag: \"" << fragmentFile << "\"):\n";
ss << program.GetInfoLog();
throw std::runtime_error(ss.str().c_str());
}
program.Validate();
if (!program.GetValidateStatus())
{
std::ostringstream ss;
ss << "Failed to validate program (vert: \"" << vertexFile << "\", frag: \"" << fragmentFile << "\"):\n";
ss << program.GetInfoLog();
throw std::runtime_error(ss.str().c_str());
}
return program;
}
/** @brief Creates a 2D box with coordinates from (0, 0) to (1, 1).
* @return The vertex array object.
*/
OpenGL::VertexArray MakeBox()
{
// Setup the buffer data
Float2 boxPositions[] = { Float2(0, 0), Float2(0, 1), Float2(1, 1), Float2(1, 0) };
Float2 boxTexCoords[] = { Float2(0, 0), Float2(0, 1), Float2(1, 1), Float2(1, 0) };
// Create the vertex array object
OpenGL::VertexArray vertexArray;
vertexArray.Create();
vertexArray.Bind();
// Setup the position buffer and attach it to the vertex array
OpenGL::Buffer buffer1;
buffer1.Create(OpenGL::GL::ARRAY_BUFFER);
buffer1.Bind();
buffer1.Data(4 * sizeof(Float2), boxPositions, OpenGL::GL::STATIC_DRAW);
vertexArray.AttribPointer(OpenGL::POSITION1, 2, OpenGL::GL::FLOAT, false, 0, 0);
vertexArray.EnableAttribArray(OpenGL::POSITION1);
// Setup the texcoord buffer and attach it to the vertex array
OpenGL::Buffer buffer2;
buffer2.Create(OpenGL::GL::ARRAY_BUFFER);
buffer2.Bind();
buffer2.Data(4 * sizeof(Float2), boxTexCoords, OpenGL::GL::STATIC_DRAW);
vertexArray.AttribPointer(OpenGL::TEXCOORD1, 2, OpenGL::GL::FLOAT, false, 0, 0);
vertexArray.EnableAttribArray(OpenGL::TEXCOORD1);
// All done
vertexArray.Unbind();
return vertexArray;
}
int main()
{
Jatta::Matrix wee;
wee[1][2] = 5;
std::cout << wee << std::endl;
try
{
// Setup the window
WindowStyle style;
style.title = "Jatta Window";
style.width = 640;
style.height = 480;
style.backgroundColor = Colors::black;
style.resizable = false;
Window window;
window.Create(style);
window.SetTitle("こんにちわ");
// Create the OpenGL context
OpenGL::Context context;
context.Create(&window);
OpenGL::Program program = LoadShader("Resources/screen.vert", "Resources/screen.frag");
Image image;
image.Load("Resources/sky.png");
OpenGL::Texture texture;
texture.Create(OpenGL::GL::TEXTURE_2D);
texture.Bind();
texture.SetTextureWrapS(OpenGL::GL::REPEAT);
texture.SetTextureWrapT(OpenGL::GL::REPEAT);
texture.SetMinFilter(OpenGL::GL::LINEAR);
texture.SetMagFilter(OpenGL::GL::LINEAR);
texture.Image2D(0, OpenGL::GL::RGBA, image.GetWidth(), image.GetHeight(), 0, OpenGL::GL::RGBA, OpenGL::GL::UNSIGNED_BYTE, image.GetData());
texture.Unbind();
OpenGL::VertexArray box = MakeBox();
context.ClearColor(Colors::red);
while (window.IsOpen())
{
Window::Update();
context.Viewport(0, 0, window.GetWidth(), window.GetHeight());
context.Clear(OpenGL::GL::COLOR_BUFFER_BIT | OpenGL::GL::DEPTH_BUFFER_BIT);
program.Bind();
OpenGL::Program::UniformMatrix4f(program.GetUniformLocation("orthoMatrix"), false, Matrix::MakeOrtho(0, 1, 1, 0));
OpenGL::Program::UniformMatrix4f(program.GetUniformLocation("modelMatrix"), false, Matrix::Identity());
OpenGL::Program::Uniform1i(program.GetUniformLocation("texture"), 0);
OpenGL::ClearErrors();
OpenGL::Texture::Active(0);
texture.Bind();
box.Bind();
box.DrawArrays(OpenGL::GL::QUADS, 0, 4);
box.Unbind();
program.Unbind();
context.SwapBuffers();
}
}
catch (std::exception& e)
{
std::cout << e.what() << std::endl;
}
}
<|endoftext|> |
<commit_before>//===- lib/ReaderWriter/PECOFF/ReaderImportHeader.cpp ---------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file \brief This file provides a way to read an import library member in a
/// .lib file.
///
/// Archive Files in Windows
/// ========================
///
/// In Windows, archive files with .lib file extension serve two different
/// purposes.
///
/// - For static linking: An archive file in this use case contains multiple
/// regular .obj files and is used for static linking. This is the same
/// usage as .a file in Unix.
///
/// - For dynamic linking: An archive file in this use case contains pseudo
/// .obj files to describe exported symbols of a DLL. Each pseudo .obj file
/// in an archive has a name of an exported symbol and a DLL filename from
/// which the symbol can be imported. When you link a DLL on Windows, you
/// pass the name of the .lib file for the DLL instead of the DLL filename
/// itself. That is the Windows way of linking against a shared library.
///
/// This file contains a function to handle the pseudo object file.
///
/// Windows Loader and Import Address Table
/// =======================================
///
/// Windows supports a GOT-like mechanism for DLLs. The executable using DLLs
/// contains a list of DLL names and list of symbols that need to be resolved by
/// the loader. Windows loader maps the executable and all the DLLs to memory,
/// resolves the symbols referencing items in DLLs, and updates the import
/// address table (IAT) in memory. The IAT is an array of pointers to all of the
/// data or functions in DLL referenced by the executable. You cannot access
/// items in DLLs directly. They have to be accessed through an extra level of
/// indirection.
///
/// So, if you want to access an item in DLL, you have to go through a
/// pointer. How do you actually do that? You need a symbol for a pointer in the
/// IAT. For each symbol defined in a DLL, a symbol with "__imp_" prefix is
/// exported from the DLL for an IAT entry. For example, if you have a global
/// variable "foo" in a DLL, a pointer to the variable is available as
/// "_imp__foo". The IAT is an array of _imp__ symbols.
///
/// Is this OK? That's not that complicated. Because items in a DLL are not
/// directly accessible, you need to access through a pointer, and the pointer
/// is available as a symbol with _imp__ prefix.
///
/// Note 1: Although you can write code with _imp__ prefix, today's compiler and
/// linker let you write code as if there's no extra level of indirection.
/// That's why you haven't seen lots of _imp__ in your code. A variable or a
/// function declared with "dllimport" attribute is treated as an item in a DLL,
/// and the compiler automatically mangles its name and inserts the extra level
/// of indirection when accessing the item. Here are some examples:
///
/// __declspec(dllimport) int var_in_dll;
/// var_in_dll = 3; // is equivalent to *_imp__var_in_dll = 3;
///
/// __declspec(dllimport) int fn_in_dll(void);
/// fn_in_dll(); // is equivalent to (*_imp__fn_in_dll)();
///
/// It's just the compiler rewrites code for you so that you don't need to
/// handle the indirection youself.
///
/// Note 2: __declspec(dllimport) is mandatory for data but optional for
/// function. For a function, the linker creates a jump table with the original
/// symbol name, so that the function is accessible without _imp__ prefix. The
/// same function in a DLL can be called through two different symbols if it's
/// not dllimport'ed.
///
/// (*_imp__fn)()
/// fn()
///
/// The above functions do the same thing. fn's content is a JMP instruction to
/// branch to the address pointed by _imp__fn. The latter may be a little bit
/// slower than the former because it will execute the extra JMP instruction, but
/// that's usually negligible.
///
/// If a function is dllimport'ed, which is usually done in a header file,
/// mangled name will be used at compile time so the jump table will not be
/// used.
///
/// Because there's no way to hide the indirection for data access at link time,
/// data has to be accessed through dllimport'ed symbols or explicit _imp__
/// prefix.
///
/// Idata Sections in the Pseudo Object File
/// ========================================
///
/// The object file created by cl.exe has several sections whose name starts
/// with ".idata$" followed by a number. The contents of the sections seem the
/// fragments of a complete ".idata" section. These sections has relocations for
/// the data referenced from the idata secton. Generally, the linker discards
/// "$" and all characters that follow from the section name and merges their
/// contents to one section. So, it looks like if everything would work fine,
/// the idata section would naturally be constructed without having any special
/// code for doing that.
///
/// However, the LLD linker cannot do that. An idata section constructed in that
/// way was never be in valid format. We don't know the reason yet. Our
/// assumption on the idata fragment could simply be wrong, or the LLD linker is
/// not powerful enough to do the job. Meanwhile, we construct the idata section
/// ourselves. All the "idata$" sections in the pseudo object file are currently
/// ignored.
///
/// Creating Atoms for the Import Address Table
/// ===========================================
///
/// The function in this file reads a pseudo object file and creates at most two
/// atoms. One is a shared library atom for _imp__ symbol. The another is a
/// defined atom for the JMP instruction if the symbol is for a function.
///
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "ReaderImportHeader"
#include "Atoms.h"
#include "lld/Core/File.h"
#include "lld/Core/Error.h"
#include "lld/Core/SharedLibraryAtom.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/Object/COFF.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/COFF.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Memory.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/system_error.h"
#include <map>
#include <vector>
#include <cstring>
using namespace lld;
using namespace llvm;
namespace lld {
namespace coff {
namespace {
/// The defined atom for jump table.
class FuncAtom : public COFFLinkerInternalAtom {
public:
FuncAtom(const File &file, StringRef symbolName)
: COFFLinkerInternalAtom(file, std::vector<uint8_t>(rawContent),
symbolName) {}
virtual uint64_t ordinal() const { return 0; }
virtual Scope scope() const { return scopeGlobal; }
virtual ContentType contentType() const { return typeCode; }
virtual Alignment alignment() const { return Alignment(1); }
virtual ContentPermissions permissions() const { return permR_X; }
private:
static std::vector<uint8_t> rawContent;
};
// MSVC doesn't seem to like C++11 initializer list, so initialize the
// vector from an array.
namespace {
uint8_t FuncAtomContent[] = {
0xff, 0x25, 0x00, 0x00, 0x00, 0x00, // jmp *0x0
0x90, 0x90 // nop; nop
};
} // anonymous namespace
std::vector<uint8_t> FuncAtom::rawContent(
FuncAtomContent, FuncAtomContent + sizeof(FuncAtomContent));
class FileImportLibrary : public File {
public:
FileImportLibrary(const LinkingContext &context,
std::unique_ptr<MemoryBuffer> mb,
error_code &ec)
: File(mb->getBufferIdentifier(), kindSharedLibrary), _context(context) {
const char *buf = mb->getBufferStart();
const char *end = mb->getBufferEnd();
// The size of the string that follows the header.
uint32_t dataSize = *reinterpret_cast<const support::ulittle32_t *>(
buf + offsetof(COFF::ImportHeader, SizeOfData));
// Check if the total size is valid.
if (end - buf != sizeof(COFF::ImportHeader) + dataSize) {
ec = make_error_code(NativeReaderError::unknown_file_format);
return;
}
uint16_t hint = *reinterpret_cast<const support::ulittle16_t *>(
buf + offsetof(COFF::ImportHeader, OrdinalHint));
StringRef symbolName(buf + sizeof(COFF::ImportHeader));
StringRef dllName(buf + sizeof(COFF::ImportHeader) + symbolName.size() + 1);
// TypeInfo is a bitfield. The least significant 2 bits are import
// type, followed by 3 bit import name type.
uint16_t typeInfo = *reinterpret_cast<const support::ulittle16_t *>(
buf + offsetof(COFF::ImportHeader, TypeInfo));
int type = typeInfo & 0x3;
int nameType = (typeInfo >> 2) & 0x7;
// Symbol name used by the linker may be different from the symbol name used
// by the loader. The latter may lack symbol decorations, or may not even
// have name if it's imported by ordinal.
StringRef importName = symbolNameToImportName(symbolName, nameType);
const COFFSharedLibraryAtom *dataAtom = addSharedLibraryAtom(
hint, symbolName, importName, dllName);
if (type == llvm::COFF::IMPORT_CODE)
addDefinedAtom(symbolName, dllName, dataAtom);
ec = error_code::success();
}
virtual const atom_collection<DefinedAtom> &defined() const {
return _definedAtoms;
}
virtual const atom_collection<UndefinedAtom> &undefined() const {
return _noUndefinedAtoms;
}
virtual const atom_collection<SharedLibraryAtom> &sharedLibrary() const {
return _sharedLibraryAtoms;
}
virtual const atom_collection<AbsoluteAtom> &absolute() const {
return _noAbsoluteAtoms;
}
virtual const LinkingContext &getLinkingContext() const { return _context; }
private:
const COFFSharedLibraryAtom *
addSharedLibraryAtom(uint16_t hint, StringRef symbolName,
StringRef importName, StringRef dllName) {
auto *atom = new (_alloc) COFFSharedLibraryAtom(
*this, hint, symbolName, importName, dllName);
_sharedLibraryAtoms._atoms.push_back(atom);
return atom;
}
void addDefinedAtom(StringRef symbolName, StringRef dllName,
const COFFSharedLibraryAtom *dataAtom) {
auto *atom = new (_alloc) FuncAtom(*this, symbolName);
// The first two byte of the atom is JMP instruction.
atom->addReference(std::unique_ptr<COFFReference>(
new COFFReference(dataAtom, 2, llvm::COFF::IMAGE_REL_I386_DIR32)));
_definedAtoms._atoms.push_back(atom);
}
atom_collection_vector<DefinedAtom> _definedAtoms;
atom_collection_vector<SharedLibraryAtom> _sharedLibraryAtoms;
const LinkingContext &_context;
mutable llvm::BumpPtrAllocator _alloc;
// Does the same thing as StringRef::ltrim() but removes at most one
// character.
StringRef ltrim1(StringRef str, const char *chars) const {
if (!str.empty() && strchr(chars, str[0]))
return str.substr(1);
return str;
}
// Convert the given symbol name to the import symbol name exported by the
// DLL.
StringRef symbolNameToImportName(StringRef symbolName, int nameType) const {
StringRef ret;
switch (nameType) {
case llvm::COFF::IMPORT_ORDINAL:
// The import is by ordinal. No symbol name will be used to identify the
// item in the DLL. Only its ordinal will be used.
return "";
case llvm::COFF::IMPORT_NAME:
// The import name in this case is identical to the symbol name.
return symbolName;
case llvm::COFF::IMPORT_NAME_NOPREFIX:
// The import name is the symbol name without leading ?, @ or _.
ret = ltrim1(symbolName, "?@_");
break;
case llvm::COFF::IMPORT_NAME_UNDECORATE:
// Similar to NOPREFIX, but we also need to truncate at the first @.
ret = ltrim1(symbolName, "?@_");
ret = ret.substr(0, ret.find('@'));
break;
}
std::string *str = new (_alloc) std::string(ret);
return *str;
}
};
} // end anonymous namespace
error_code parseCOFFImportLibrary(const LinkingContext &targetInfo,
std::unique_ptr<MemoryBuffer> &mb,
std::vector<std::unique_ptr<File>> &result) {
// Check the file magic.
const char *buf = mb->getBufferStart();
const char *end = mb->getBufferEnd();
// Error if the file is too small or does not start with the magic.
if (end - buf < static_cast<ptrdiff_t>(sizeof(COFF::ImportHeader)) ||
memcmp(buf, "\0\0\xFF\xFF", 4))
return make_error_code(NativeReaderError::unknown_file_format);
error_code ec;
auto file = std::unique_ptr<File>(
new FileImportLibrary(targetInfo, std::move(mb), ec));
if (ec)
return ec;
result.push_back(std::move(file));
return error_code::success();
}
} // end namespace coff
} // end namespace lld
<commit_msg>[PECOFF] Remove unnecessary static member.<commit_after>//===- lib/ReaderWriter/PECOFF/ReaderImportHeader.cpp ---------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file \brief This file provides a way to read an import library member in a
/// .lib file.
///
/// Archive Files in Windows
/// ========================
///
/// In Windows, archive files with .lib file extension serve two different
/// purposes.
///
/// - For static linking: An archive file in this use case contains multiple
/// regular .obj files and is used for static linking. This is the same
/// usage as .a file in Unix.
///
/// - For dynamic linking: An archive file in this use case contains pseudo
/// .obj files to describe exported symbols of a DLL. Each pseudo .obj file
/// in an archive has a name of an exported symbol and a DLL filename from
/// which the symbol can be imported. When you link a DLL on Windows, you
/// pass the name of the .lib file for the DLL instead of the DLL filename
/// itself. That is the Windows way of linking against a shared library.
///
/// This file contains a function to handle the pseudo object file.
///
/// Windows Loader and Import Address Table
/// =======================================
///
/// Windows supports a GOT-like mechanism for DLLs. The executable using DLLs
/// contains a list of DLL names and list of symbols that need to be resolved by
/// the loader. Windows loader maps the executable and all the DLLs to memory,
/// resolves the symbols referencing items in DLLs, and updates the import
/// address table (IAT) in memory. The IAT is an array of pointers to all of the
/// data or functions in DLL referenced by the executable. You cannot access
/// items in DLLs directly. They have to be accessed through an extra level of
/// indirection.
///
/// So, if you want to access an item in DLL, you have to go through a
/// pointer. How do you actually do that? You need a symbol for a pointer in the
/// IAT. For each symbol defined in a DLL, a symbol with "__imp_" prefix is
/// exported from the DLL for an IAT entry. For example, if you have a global
/// variable "foo" in a DLL, a pointer to the variable is available as
/// "_imp__foo". The IAT is an array of _imp__ symbols.
///
/// Is this OK? That's not that complicated. Because items in a DLL are not
/// directly accessible, you need to access through a pointer, and the pointer
/// is available as a symbol with _imp__ prefix.
///
/// Note 1: Although you can write code with _imp__ prefix, today's compiler and
/// linker let you write code as if there's no extra level of indirection.
/// That's why you haven't seen lots of _imp__ in your code. A variable or a
/// function declared with "dllimport" attribute is treated as an item in a DLL,
/// and the compiler automatically mangles its name and inserts the extra level
/// of indirection when accessing the item. Here are some examples:
///
/// __declspec(dllimport) int var_in_dll;
/// var_in_dll = 3; // is equivalent to *_imp__var_in_dll = 3;
///
/// __declspec(dllimport) int fn_in_dll(void);
/// fn_in_dll(); // is equivalent to (*_imp__fn_in_dll)();
///
/// It's just the compiler rewrites code for you so that you don't need to
/// handle the indirection youself.
///
/// Note 2: __declspec(dllimport) is mandatory for data but optional for
/// function. For a function, the linker creates a jump table with the original
/// symbol name, so that the function is accessible without _imp__ prefix. The
/// same function in a DLL can be called through two different symbols if it's
/// not dllimport'ed.
///
/// (*_imp__fn)()
/// fn()
///
/// The above functions do the same thing. fn's content is a JMP instruction to
/// branch to the address pointed by _imp__fn. The latter may be a little bit
/// slower than the former because it will execute the extra JMP instruction, but
/// that's usually negligible.
///
/// If a function is dllimport'ed, which is usually done in a header file,
/// mangled name will be used at compile time so the jump table will not be
/// used.
///
/// Because there's no way to hide the indirection for data access at link time,
/// data has to be accessed through dllimport'ed symbols or explicit _imp__
/// prefix.
///
/// Idata Sections in the Pseudo Object File
/// ========================================
///
/// The object file created by cl.exe has several sections whose name starts
/// with ".idata$" followed by a number. The contents of the sections seem the
/// fragments of a complete ".idata" section. These sections has relocations for
/// the data referenced from the idata secton. Generally, the linker discards
/// "$" and all characters that follow from the section name and merges their
/// contents to one section. So, it looks like if everything would work fine,
/// the idata section would naturally be constructed without having any special
/// code for doing that.
///
/// However, the LLD linker cannot do that. An idata section constructed in that
/// way was never be in valid format. We don't know the reason yet. Our
/// assumption on the idata fragment could simply be wrong, or the LLD linker is
/// not powerful enough to do the job. Meanwhile, we construct the idata section
/// ourselves. All the "idata$" sections in the pseudo object file are currently
/// ignored.
///
/// Creating Atoms for the Import Address Table
/// ===========================================
///
/// The function in this file reads a pseudo object file and creates at most two
/// atoms. One is a shared library atom for _imp__ symbol. The another is a
/// defined atom for the JMP instruction if the symbol is for a function.
///
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "ReaderImportHeader"
#include "Atoms.h"
#include "lld/Core/File.h"
#include "lld/Core/Error.h"
#include "lld/Core/SharedLibraryAtom.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/Object/COFF.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/COFF.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Memory.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/system_error.h"
#include <map>
#include <vector>
#include <cstring>
using namespace lld;
using namespace llvm;
namespace lld {
namespace coff {
namespace {
uint8_t FuncAtomContent[] = {
0xff, 0x25, 0x00, 0x00, 0x00, 0x00, // jmp *0x0
0x90, 0x90 // nop; nop
};
/// The defined atom for jump table.
class FuncAtom : public COFFLinkerInternalAtom {
public:
FuncAtom(const File &file, StringRef symbolName)
: COFFLinkerInternalAtom(
file,
std::vector<uint8_t>(FuncAtomContent,
FuncAtomContent + sizeof(FuncAtomContent)),
symbolName) {}
virtual uint64_t ordinal() const { return 0; }
virtual Scope scope() const { return scopeGlobal; }
virtual ContentType contentType() const { return typeCode; }
virtual Alignment alignment() const { return Alignment(1); }
virtual ContentPermissions permissions() const { return permR_X; }
};
class FileImportLibrary : public File {
public:
FileImportLibrary(const LinkingContext &context,
std::unique_ptr<MemoryBuffer> mb,
error_code &ec)
: File(mb->getBufferIdentifier(), kindSharedLibrary), _context(context) {
const char *buf = mb->getBufferStart();
const char *end = mb->getBufferEnd();
// The size of the string that follows the header.
uint32_t dataSize = *reinterpret_cast<const support::ulittle32_t *>(
buf + offsetof(COFF::ImportHeader, SizeOfData));
// Check if the total size is valid.
if (end - buf != sizeof(COFF::ImportHeader) + dataSize) {
ec = make_error_code(NativeReaderError::unknown_file_format);
return;
}
uint16_t hint = *reinterpret_cast<const support::ulittle16_t *>(
buf + offsetof(COFF::ImportHeader, OrdinalHint));
StringRef symbolName(buf + sizeof(COFF::ImportHeader));
StringRef dllName(buf + sizeof(COFF::ImportHeader) + symbolName.size() + 1);
// TypeInfo is a bitfield. The least significant 2 bits are import
// type, followed by 3 bit import name type.
uint16_t typeInfo = *reinterpret_cast<const support::ulittle16_t *>(
buf + offsetof(COFF::ImportHeader, TypeInfo));
int type = typeInfo & 0x3;
int nameType = (typeInfo >> 2) & 0x7;
// Symbol name used by the linker may be different from the symbol name used
// by the loader. The latter may lack symbol decorations, or may not even
// have name if it's imported by ordinal.
StringRef importName = symbolNameToImportName(symbolName, nameType);
const COFFSharedLibraryAtom *dataAtom = addSharedLibraryAtom(
hint, symbolName, importName, dllName);
if (type == llvm::COFF::IMPORT_CODE)
addDefinedAtom(symbolName, dllName, dataAtom);
ec = error_code::success();
}
virtual const atom_collection<DefinedAtom> &defined() const {
return _definedAtoms;
}
virtual const atom_collection<UndefinedAtom> &undefined() const {
return _noUndefinedAtoms;
}
virtual const atom_collection<SharedLibraryAtom> &sharedLibrary() const {
return _sharedLibraryAtoms;
}
virtual const atom_collection<AbsoluteAtom> &absolute() const {
return _noAbsoluteAtoms;
}
virtual const LinkingContext &getLinkingContext() const { return _context; }
private:
const COFFSharedLibraryAtom *
addSharedLibraryAtom(uint16_t hint, StringRef symbolName,
StringRef importName, StringRef dllName) {
auto *atom = new (_alloc) COFFSharedLibraryAtom(
*this, hint, symbolName, importName, dllName);
_sharedLibraryAtoms._atoms.push_back(atom);
return atom;
}
void addDefinedAtom(StringRef symbolName, StringRef dllName,
const COFFSharedLibraryAtom *dataAtom) {
auto *atom = new (_alloc) FuncAtom(*this, symbolName);
// The first two byte of the atom is JMP instruction.
atom->addReference(std::unique_ptr<COFFReference>(
new COFFReference(dataAtom, 2, llvm::COFF::IMAGE_REL_I386_DIR32)));
_definedAtoms._atoms.push_back(atom);
}
atom_collection_vector<DefinedAtom> _definedAtoms;
atom_collection_vector<SharedLibraryAtom> _sharedLibraryAtoms;
const LinkingContext &_context;
mutable llvm::BumpPtrAllocator _alloc;
// Does the same thing as StringRef::ltrim() but removes at most one
// character.
StringRef ltrim1(StringRef str, const char *chars) const {
if (!str.empty() && strchr(chars, str[0]))
return str.substr(1);
return str;
}
// Convert the given symbol name to the import symbol name exported by the
// DLL.
StringRef symbolNameToImportName(StringRef symbolName, int nameType) const {
StringRef ret;
switch (nameType) {
case llvm::COFF::IMPORT_ORDINAL:
// The import is by ordinal. No symbol name will be used to identify the
// item in the DLL. Only its ordinal will be used.
return "";
case llvm::COFF::IMPORT_NAME:
// The import name in this case is identical to the symbol name.
return symbolName;
case llvm::COFF::IMPORT_NAME_NOPREFIX:
// The import name is the symbol name without leading ?, @ or _.
ret = ltrim1(symbolName, "?@_");
break;
case llvm::COFF::IMPORT_NAME_UNDECORATE:
// Similar to NOPREFIX, but we also need to truncate at the first @.
ret = ltrim1(symbolName, "?@_");
ret = ret.substr(0, ret.find('@'));
break;
}
std::string *str = new (_alloc) std::string(ret);
return *str;
}
};
} // end anonymous namespace
error_code parseCOFFImportLibrary(const LinkingContext &targetInfo,
std::unique_ptr<MemoryBuffer> &mb,
std::vector<std::unique_ptr<File>> &result) {
// Check the file magic.
const char *buf = mb->getBufferStart();
const char *end = mb->getBufferEnd();
// Error if the file is too small or does not start with the magic.
if (end - buf < static_cast<ptrdiff_t>(sizeof(COFF::ImportHeader)) ||
memcmp(buf, "\0\0\xFF\xFF", 4))
return make_error_code(NativeReaderError::unknown_file_format);
error_code ec;
auto file = std::unique_ptr<File>(
new FileImportLibrary(targetInfo, std::move(mb), ec));
if (ec)
return ec;
result.push_back(std::move(file));
return error_code::success();
}
} // end namespace coff
} // end namespace lld
<|endoftext|> |
<commit_before>//===- TraceValues.cpp - Value Tracing for debugging -------------*- C++ -*--=//
//
// Support for inserting LLVM code to print values at basic block and function
// exits.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Instrumentation.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/iMemory.h"
#include "llvm/iTerminators.h"
#include "llvm/iOther.h"
#include "llvm/Module.h"
#include "llvm/Pass.h"
#include "llvm/Assembly/Writer.h"
#include "Support/CommandLine.h"
#include "Support/StringExtras.h"
#include <algorithm>
#include <sstream>
using std::vector;
using std::string;
static cl::opt<bool>
DisablePtrHashing("tracedisablehashdisable", cl::Hidden,
cl::desc("Disable pointer hashing"));
static cl::list<string>
TraceFuncNames("tracefunc", cl::desc("trace only specific functions"),
cl::value_desc("function"), cl::Hidden);
static void TraceValuesAtBBExit(BasicBlock *BB,
Function *Printf, Function* HashPtrToSeqNum,
vector<Instruction*> *valuesStoredInFunction);
// We trace a particular function if no functions to trace were specified
// or if the function is in the specified list.
//
inline static bool
TraceThisFunction(Function &F)
{
if (TraceFuncNames.empty()) return true;
return std::find(TraceFuncNames.begin(), TraceFuncNames.end(), F.getName())
!= TraceFuncNames.end();
}
namespace {
struct ExternalFuncs {
Function *PrintfFunc, *HashPtrFunc, *ReleasePtrFunc;
Function *RecordPtrFunc, *PushOnEntryFunc, *ReleaseOnReturnFunc;
void doInitialization(Module &M); // Add prototypes for external functions
};
class InsertTraceCode : public FunctionPass {
protected:
ExternalFuncs externalFuncs;
public:
// Add a prototype for runtime functions not already in the program.
//
bool doInitialization(Module &M);
//--------------------------------------------------------------------------
// Function InsertCodeToTraceValues
//
// Inserts tracing code for all live values at basic block and/or function
// exits as specified by `traceBasicBlockExits' and `traceFunctionExits'.
//
bool doit(Function *M);
virtual void handleBasicBlock(BasicBlock *BB, vector<Instruction*> &VI) = 0;
// runOnFunction - This method does the work.
//
bool runOnFunction(Function &F);
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
}
};
struct FunctionTracer : public InsertTraceCode {
// Ignore basic blocks here...
virtual void handleBasicBlock(BasicBlock *BB, vector<Instruction*> &VI) {}
};
struct BasicBlockTracer : public InsertTraceCode {
// Trace basic blocks here...
virtual void handleBasicBlock(BasicBlock *BB, vector<Instruction*> &VI) {
TraceValuesAtBBExit(BB, externalFuncs.PrintfFunc,
externalFuncs.HashPtrFunc, &VI);
}
};
// Register the passes...
RegisterOpt<FunctionTracer> X("tracem","Insert Function trace code only");
RegisterOpt<BasicBlockTracer> Y("trace","Insert BB and Function trace code");
} // end anonymous namespace
Pass *createTraceValuesPassForFunction() { // Just trace functions
return new FunctionTracer();
}
Pass *createTraceValuesPassForBasicBlocks() { // Trace BB's and functions
return new BasicBlockTracer();
}
// Add a prototype for external functions used by the tracing code.
//
void ExternalFuncs::doInitialization(Module &M) {
const Type *SBP = PointerType::get(Type::SByteTy);
const FunctionType *MTy =
FunctionType::get(Type::IntTy, vector<const Type*>(1, SBP), true);
PrintfFunc = M.getOrInsertFunction("printf", MTy);
// uint (sbyte*)
const FunctionType *hashFuncTy =
FunctionType::get(Type::UIntTy, vector<const Type*>(1, SBP), false);
HashPtrFunc = M.getOrInsertFunction("HashPointerToSeqNum", hashFuncTy);
// void (sbyte*)
const FunctionType *voidSBPFuncTy =
FunctionType::get(Type::VoidTy, vector<const Type*>(1, SBP), false);
ReleasePtrFunc = M.getOrInsertFunction("ReleasePointerSeqNum", voidSBPFuncTy);
RecordPtrFunc = M.getOrInsertFunction("RecordPointer", voidSBPFuncTy);
const FunctionType *voidvoidFuncTy =
FunctionType::get(Type::VoidTy, vector<const Type*>(), false);
PushOnEntryFunc = M.getOrInsertFunction("PushPointerSet", voidvoidFuncTy);
ReleaseOnReturnFunc = M.getOrInsertFunction("ReleasePointersPopSet",
voidvoidFuncTy);
}
// Add a prototype for external functions used by the tracing code.
//
bool InsertTraceCode::doInitialization(Module &M) {
externalFuncs.doInitialization(M);
return false;
}
static inline GlobalVariable *getStringRef(Module *M, const string &str) {
// Create a constant internal string reference...
Constant *Init = ConstantArray::get(str);
// Create the global variable and record it in the module
// The GV will be renamed to a unique name if needed.
GlobalVariable *GV = new GlobalVariable(Init->getType(), true, true, Init,
"trstr");
M->getGlobalList().push_back(GV);
return GV;
}
//
// Check if this instruction has any uses outside its basic block,
// or if it used by either a Call or Return instruction.
//
static inline bool LiveAtBBExit(const Instruction* I) {
const BasicBlock *BB = I->getParent();
for (Value::use_const_iterator U = I->use_begin(); U != I->use_end(); ++U)
if (const Instruction *UI = dyn_cast<Instruction>(*U))
if (UI->getParent() != BB || isa<ReturnInst>(UI))
return true;
return false;
}
static inline bool TraceThisOpCode(unsigned opCode) {
// Explicitly test for opCodes *not* to trace so that any new opcodes will
// be traced by default (VoidTy's are already excluded)
//
return (opCode < Instruction::OtherOpsBegin &&
opCode != Instruction::Alloca &&
opCode != Instruction::PHINode &&
opCode != Instruction::Cast);
}
static bool ShouldTraceValue(const Instruction *I) {
return
I->getType() != Type::VoidTy && LiveAtBBExit(I) &&
TraceThisOpCode(I->getOpcode());
}
static string getPrintfCodeFor(const Value *V) {
if (V == 0) return "";
if (V->getType()->isFloatingPoint())
return "%g";
else if (V->getType() == Type::LabelTy)
return "0x%p";
else if (isa<PointerType>(V->getType()))
return DisablePtrHashing ? "0x%p" : "%d";
else if (V->getType()->isIntegral())
return "%d";
assert(0 && "Illegal value to print out...");
return "";
}
static void InsertPrintInst(Value *V, BasicBlock *BB, Instruction *InsertBefore,
string Message,
Function *Printf, Function* HashPtrToSeqNum) {
// Escape Message by replacing all % characters with %% chars.
string Tmp;
std::swap(Tmp, Message);
string::iterator I = std::find(Tmp.begin(), Tmp.end(), '%');
while (I != Tmp.end()) {
Message.append(Tmp.begin(), I);
Message += "%%";
++I; // Make sure to erase the % as well...
Tmp.erase(Tmp.begin(), I);
I = std::find(Tmp.begin(), Tmp.end(), '%');
}
Message += Tmp;
Module *Mod = BB->getParent()->getParent();
// Turn the marker string into a global variable...
GlobalVariable *fmtVal = getStringRef(Mod, Message+getPrintfCodeFor(V)+"\n");
// Turn the format string into an sbyte *
Instruction *GEP =
new GetElementPtrInst(fmtVal,
vector<Value*>(2,ConstantSInt::get(Type::LongTy, 0)),
"trstrp", InsertBefore);
// Insert a call to the hash function if this is a pointer value
if (V && isa<PointerType>(V->getType()) && !DisablePtrHashing) {
const Type *SBP = PointerType::get(Type::SByteTy);
if (V->getType() != SBP) // Cast pointer to be sbyte*
V = new CastInst(V, SBP, "Hash_cast", InsertBefore);
vector<Value*> HashArgs(1, V);
V = new CallInst(HashPtrToSeqNum, HashArgs, "ptrSeqNum", InsertBefore);
}
// Insert the first print instruction to print the string flag:
vector<Value*> PrintArgs;
PrintArgs.push_back(GEP);
if (V) PrintArgs.push_back(V);
new CallInst(Printf, PrintArgs, "trace", InsertBefore);
}
static void InsertVerbosePrintInst(Value *V, BasicBlock *BB,
Instruction *InsertBefore,
const string &Message, Function *Printf,
Function* HashPtrToSeqNum) {
std::ostringstream OutStr;
if (V) WriteAsOperand(OutStr, V);
InsertPrintInst(V, BB, InsertBefore, Message+OutStr.str()+" = ",
Printf, HashPtrToSeqNum);
}
static void
InsertReleaseInst(Value *V, BasicBlock *BB,
Instruction *InsertBefore,
Function* ReleasePtrFunc) {
const Type *SBP = PointerType::get(Type::SByteTy);
if (V->getType() != SBP) // Cast pointer to be sbyte*
V = new CastInst(V, SBP, "RPSN_cast", InsertBefore);
vector<Value*> releaseArgs(1, V);
new CallInst(ReleasePtrFunc, releaseArgs, "", InsertBefore);
}
static void
InsertRecordInst(Value *V, BasicBlock *BB,
Instruction *InsertBefore,
Function* RecordPtrFunc) {
const Type *SBP = PointerType::get(Type::SByteTy);
if (V->getType() != SBP) // Cast pointer to be sbyte*
V = new CastInst(V, SBP, "RP_cast", InsertBefore);
vector<Value*> releaseArgs(1, V);
new CallInst(RecordPtrFunc, releaseArgs, "", InsertBefore);
}
// Look for alloca and free instructions. These are the ptrs to release.
// Release the free'd pointers immediately. Record the alloca'd pointers
// to be released on return from the current function.
//
static void
ReleasePtrSeqNumbers(BasicBlock *BB,
ExternalFuncs& externalFuncs) {
for (BasicBlock::iterator II=BB->begin(), IE = BB->end(); II != IE; ++II)
if (FreeInst *FI = dyn_cast<FreeInst>(&*II))
InsertReleaseInst(FI->getOperand(0), BB, FI,externalFuncs.ReleasePtrFunc);
else if (AllocaInst *AI = dyn_cast<AllocaInst>(&*II))
InsertRecordInst(AI, BB, AI->getNext(), externalFuncs.RecordPtrFunc);
}
// Insert print instructions at the end of basic block BB for each value
// computed in BB that is live at the end of BB,
// or that is stored to memory in BB.
// If the value is stored to memory, we load it back before printing it
// We also return all such loaded values in the vector valuesStoredInFunction
// for printing at the exit from the function. (Note that in each invocation
// of the function, this will only get the last value stored for each static
// store instruction).
//
static void TraceValuesAtBBExit(BasicBlock *BB,
Function *Printf, Function* HashPtrToSeqNum,
vector<Instruction*> *valuesStoredInFunction) {
// Get an iterator to point to the insertion location, which is
// just before the terminator instruction.
//
TerminatorInst *InsertPos = BB->getTerminator();
std::ostringstream OutStr;
WriteAsOperand(OutStr, BB, false);
InsertPrintInst(0, BB, InsertPos, "LEAVING BB:" + OutStr.str(),
Printf, HashPtrToSeqNum);
// Insert a print instruction for each instruction preceding InsertPos.
// The print instructions must go before InsertPos, so we use the
// instruction *preceding* InsertPos to check when to terminate the loop.
//
for (BasicBlock::iterator II = BB->begin(); &*II != InsertPos; ++II) {
if (StoreInst *SI = dyn_cast<StoreInst>(&*II)) {
assert(valuesStoredInFunction &&
"Should not be printing a store instruction at function exit");
LoadInst *LI = new LoadInst(SI->getPointerOperand(), "reload." +
SI->getPointerOperand()->getName(),
InsertPos);
valuesStoredInFunction->push_back(LI);
}
if (ShouldTraceValue(II))
InsertVerbosePrintInst(II, BB, InsertPos, " ", Printf, HashPtrToSeqNum);
}
}
static inline void InsertCodeToShowFunctionEntry(Function &F, Function *Printf,
Function* HashPtrToSeqNum){
// Get an iterator to point to the insertion location
BasicBlock &BB = F.getEntryNode();
Instruction *InsertPos = BB.begin();
std::ostringstream OutStr;
WriteAsOperand(OutStr, &F);
InsertPrintInst(0, &BB, InsertPos, "ENTERING FUNCTION: " + OutStr.str(),
Printf, HashPtrToSeqNum);
// Now print all the incoming arguments
unsigned ArgNo = 0;
for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I, ++ArgNo){
InsertVerbosePrintInst(I, &BB, InsertPos,
" Arg #" + utostr(ArgNo) + ": ", Printf,
HashPtrToSeqNum);
}
}
static inline void InsertCodeToShowFunctionExit(BasicBlock *BB,
Function *Printf,
Function* HashPtrToSeqNum) {
// Get an iterator to point to the insertion location
ReturnInst *Ret = cast<ReturnInst>(BB->getTerminator());
std::ostringstream OutStr;
WriteAsOperand(OutStr, BB->getParent(), true);
InsertPrintInst(0, BB, Ret, "LEAVING FUNCTION: " + OutStr.str(),
Printf, HashPtrToSeqNum);
// print the return value, if any
if (BB->getParent()->getReturnType() != Type::VoidTy)
InsertPrintInst(Ret->getReturnValue(), BB, Ret, " Returning: ",
Printf, HashPtrToSeqNum);
}
bool InsertTraceCode::runOnFunction(Function &F) {
if (!TraceThisFunction(F))
return false;
vector<Instruction*> valuesStoredInFunction;
vector<BasicBlock*> exitBlocks;
// Insert code to trace values at function entry
InsertCodeToShowFunctionEntry(F, externalFuncs.PrintfFunc,
externalFuncs.HashPtrFunc);
// Push a pointer set for recording alloca'd pointers at entry.
if (!DisablePtrHashing)
new CallInst(externalFuncs.PushOnEntryFunc, vector<Value*>(), "",
F.getEntryNode().begin());
for (Function::iterator BB = F.begin(); BB != F.end(); ++BB) {
if (isa<ReturnInst>(BB->getTerminator()))
exitBlocks.push_back(BB); // record this as an exit block
// Insert trace code if this basic block is interesting...
handleBasicBlock(BB, valuesStoredInFunction);
if (!DisablePtrHashing) // release seq. numbers on free/ret
ReleasePtrSeqNumbers(BB, externalFuncs);
}
for (unsigned i=0; i != exitBlocks.size(); ++i)
{
// Insert code to trace values at function exit
InsertCodeToShowFunctionExit(exitBlocks[i], externalFuncs.PrintfFunc,
externalFuncs.HashPtrFunc);
// Release all recorded pointers before RETURN. Do this LAST!
if (!DisablePtrHashing)
new CallInst(externalFuncs.ReleaseOnReturnFunc, vector<Value*>(), "",
exitBlocks[i]->getTerminator());
}
return true;
}
<commit_msg>Make help message more clear<commit_after>//===- TraceValues.cpp - Value Tracing for debugging -------------*- C++ -*--=//
//
// Support for inserting LLVM code to print values at basic block and function
// exits.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Instrumentation.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/iMemory.h"
#include "llvm/iTerminators.h"
#include "llvm/iOther.h"
#include "llvm/Module.h"
#include "llvm/Pass.h"
#include "llvm/Assembly/Writer.h"
#include "Support/CommandLine.h"
#include "Support/StringExtras.h"
#include <algorithm>
#include <sstream>
using std::vector;
using std::string;
static cl::opt<bool>
DisablePtrHashing("tracedisablehashdisable", cl::Hidden,
cl::desc("Disable pointer hashing in the -trace or -tracem "
"passes"));
static cl::list<string>
TraceFuncNames("tracefunc", cl::desc("Only trace specific functions in the "
"-trace or -tracem passes"),
cl::value_desc("function"), cl::Hidden);
static void TraceValuesAtBBExit(BasicBlock *BB,
Function *Printf, Function* HashPtrToSeqNum,
vector<Instruction*> *valuesStoredInFunction);
// We trace a particular function if no functions to trace were specified
// or if the function is in the specified list.
//
inline static bool
TraceThisFunction(Function &F)
{
if (TraceFuncNames.empty()) return true;
return std::find(TraceFuncNames.begin(), TraceFuncNames.end(), F.getName())
!= TraceFuncNames.end();
}
namespace {
struct ExternalFuncs {
Function *PrintfFunc, *HashPtrFunc, *ReleasePtrFunc;
Function *RecordPtrFunc, *PushOnEntryFunc, *ReleaseOnReturnFunc;
void doInitialization(Module &M); // Add prototypes for external functions
};
class InsertTraceCode : public FunctionPass {
protected:
ExternalFuncs externalFuncs;
public:
// Add a prototype for runtime functions not already in the program.
//
bool doInitialization(Module &M);
//--------------------------------------------------------------------------
// Function InsertCodeToTraceValues
//
// Inserts tracing code for all live values at basic block and/or function
// exits as specified by `traceBasicBlockExits' and `traceFunctionExits'.
//
bool doit(Function *M);
virtual void handleBasicBlock(BasicBlock *BB, vector<Instruction*> &VI) = 0;
// runOnFunction - This method does the work.
//
bool runOnFunction(Function &F);
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
}
};
struct FunctionTracer : public InsertTraceCode {
// Ignore basic blocks here...
virtual void handleBasicBlock(BasicBlock *BB, vector<Instruction*> &VI) {}
};
struct BasicBlockTracer : public InsertTraceCode {
// Trace basic blocks here...
virtual void handleBasicBlock(BasicBlock *BB, vector<Instruction*> &VI) {
TraceValuesAtBBExit(BB, externalFuncs.PrintfFunc,
externalFuncs.HashPtrFunc, &VI);
}
};
// Register the passes...
RegisterOpt<FunctionTracer> X("tracem","Insert Function trace code only");
RegisterOpt<BasicBlockTracer> Y("trace","Insert BB and Function trace code");
} // end anonymous namespace
Pass *createTraceValuesPassForFunction() { // Just trace functions
return new FunctionTracer();
}
Pass *createTraceValuesPassForBasicBlocks() { // Trace BB's and functions
return new BasicBlockTracer();
}
// Add a prototype for external functions used by the tracing code.
//
void ExternalFuncs::doInitialization(Module &M) {
const Type *SBP = PointerType::get(Type::SByteTy);
const FunctionType *MTy =
FunctionType::get(Type::IntTy, vector<const Type*>(1, SBP), true);
PrintfFunc = M.getOrInsertFunction("printf", MTy);
// uint (sbyte*)
const FunctionType *hashFuncTy =
FunctionType::get(Type::UIntTy, vector<const Type*>(1, SBP), false);
HashPtrFunc = M.getOrInsertFunction("HashPointerToSeqNum", hashFuncTy);
// void (sbyte*)
const FunctionType *voidSBPFuncTy =
FunctionType::get(Type::VoidTy, vector<const Type*>(1, SBP), false);
ReleasePtrFunc = M.getOrInsertFunction("ReleasePointerSeqNum", voidSBPFuncTy);
RecordPtrFunc = M.getOrInsertFunction("RecordPointer", voidSBPFuncTy);
const FunctionType *voidvoidFuncTy =
FunctionType::get(Type::VoidTy, vector<const Type*>(), false);
PushOnEntryFunc = M.getOrInsertFunction("PushPointerSet", voidvoidFuncTy);
ReleaseOnReturnFunc = M.getOrInsertFunction("ReleasePointersPopSet",
voidvoidFuncTy);
}
// Add a prototype for external functions used by the tracing code.
//
bool InsertTraceCode::doInitialization(Module &M) {
externalFuncs.doInitialization(M);
return false;
}
static inline GlobalVariable *getStringRef(Module *M, const string &str) {
// Create a constant internal string reference...
Constant *Init = ConstantArray::get(str);
// Create the global variable and record it in the module
// The GV will be renamed to a unique name if needed.
GlobalVariable *GV = new GlobalVariable(Init->getType(), true, true, Init,
"trstr");
M->getGlobalList().push_back(GV);
return GV;
}
//
// Check if this instruction has any uses outside its basic block,
// or if it used by either a Call or Return instruction.
//
static inline bool LiveAtBBExit(const Instruction* I) {
const BasicBlock *BB = I->getParent();
for (Value::use_const_iterator U = I->use_begin(); U != I->use_end(); ++U)
if (const Instruction *UI = dyn_cast<Instruction>(*U))
if (UI->getParent() != BB || isa<ReturnInst>(UI))
return true;
return false;
}
static inline bool TraceThisOpCode(unsigned opCode) {
// Explicitly test for opCodes *not* to trace so that any new opcodes will
// be traced by default (VoidTy's are already excluded)
//
return (opCode < Instruction::OtherOpsBegin &&
opCode != Instruction::Alloca &&
opCode != Instruction::PHINode &&
opCode != Instruction::Cast);
}
static bool ShouldTraceValue(const Instruction *I) {
return
I->getType() != Type::VoidTy && LiveAtBBExit(I) &&
TraceThisOpCode(I->getOpcode());
}
static string getPrintfCodeFor(const Value *V) {
if (V == 0) return "";
if (V->getType()->isFloatingPoint())
return "%g";
else if (V->getType() == Type::LabelTy)
return "0x%p";
else if (isa<PointerType>(V->getType()))
return DisablePtrHashing ? "0x%p" : "%d";
else if (V->getType()->isIntegral())
return "%d";
assert(0 && "Illegal value to print out...");
return "";
}
static void InsertPrintInst(Value *V, BasicBlock *BB, Instruction *InsertBefore,
string Message,
Function *Printf, Function* HashPtrToSeqNum) {
// Escape Message by replacing all % characters with %% chars.
string Tmp;
std::swap(Tmp, Message);
string::iterator I = std::find(Tmp.begin(), Tmp.end(), '%');
while (I != Tmp.end()) {
Message.append(Tmp.begin(), I);
Message += "%%";
++I; // Make sure to erase the % as well...
Tmp.erase(Tmp.begin(), I);
I = std::find(Tmp.begin(), Tmp.end(), '%');
}
Message += Tmp;
Module *Mod = BB->getParent()->getParent();
// Turn the marker string into a global variable...
GlobalVariable *fmtVal = getStringRef(Mod, Message+getPrintfCodeFor(V)+"\n");
// Turn the format string into an sbyte *
Instruction *GEP =
new GetElementPtrInst(fmtVal,
vector<Value*>(2,ConstantSInt::get(Type::LongTy, 0)),
"trstrp", InsertBefore);
// Insert a call to the hash function if this is a pointer value
if (V && isa<PointerType>(V->getType()) && !DisablePtrHashing) {
const Type *SBP = PointerType::get(Type::SByteTy);
if (V->getType() != SBP) // Cast pointer to be sbyte*
V = new CastInst(V, SBP, "Hash_cast", InsertBefore);
vector<Value*> HashArgs(1, V);
V = new CallInst(HashPtrToSeqNum, HashArgs, "ptrSeqNum", InsertBefore);
}
// Insert the first print instruction to print the string flag:
vector<Value*> PrintArgs;
PrintArgs.push_back(GEP);
if (V) PrintArgs.push_back(V);
new CallInst(Printf, PrintArgs, "trace", InsertBefore);
}
static void InsertVerbosePrintInst(Value *V, BasicBlock *BB,
Instruction *InsertBefore,
const string &Message, Function *Printf,
Function* HashPtrToSeqNum) {
std::ostringstream OutStr;
if (V) WriteAsOperand(OutStr, V);
InsertPrintInst(V, BB, InsertBefore, Message+OutStr.str()+" = ",
Printf, HashPtrToSeqNum);
}
static void
InsertReleaseInst(Value *V, BasicBlock *BB,
Instruction *InsertBefore,
Function* ReleasePtrFunc) {
const Type *SBP = PointerType::get(Type::SByteTy);
if (V->getType() != SBP) // Cast pointer to be sbyte*
V = new CastInst(V, SBP, "RPSN_cast", InsertBefore);
vector<Value*> releaseArgs(1, V);
new CallInst(ReleasePtrFunc, releaseArgs, "", InsertBefore);
}
static void
InsertRecordInst(Value *V, BasicBlock *BB,
Instruction *InsertBefore,
Function* RecordPtrFunc) {
const Type *SBP = PointerType::get(Type::SByteTy);
if (V->getType() != SBP) // Cast pointer to be sbyte*
V = new CastInst(V, SBP, "RP_cast", InsertBefore);
vector<Value*> releaseArgs(1, V);
new CallInst(RecordPtrFunc, releaseArgs, "", InsertBefore);
}
// Look for alloca and free instructions. These are the ptrs to release.
// Release the free'd pointers immediately. Record the alloca'd pointers
// to be released on return from the current function.
//
static void
ReleasePtrSeqNumbers(BasicBlock *BB,
ExternalFuncs& externalFuncs) {
for (BasicBlock::iterator II=BB->begin(), IE = BB->end(); II != IE; ++II)
if (FreeInst *FI = dyn_cast<FreeInst>(&*II))
InsertReleaseInst(FI->getOperand(0), BB, FI,externalFuncs.ReleasePtrFunc);
else if (AllocaInst *AI = dyn_cast<AllocaInst>(&*II))
InsertRecordInst(AI, BB, AI->getNext(), externalFuncs.RecordPtrFunc);
}
// Insert print instructions at the end of basic block BB for each value
// computed in BB that is live at the end of BB,
// or that is stored to memory in BB.
// If the value is stored to memory, we load it back before printing it
// We also return all such loaded values in the vector valuesStoredInFunction
// for printing at the exit from the function. (Note that in each invocation
// of the function, this will only get the last value stored for each static
// store instruction).
//
static void TraceValuesAtBBExit(BasicBlock *BB,
Function *Printf, Function* HashPtrToSeqNum,
vector<Instruction*> *valuesStoredInFunction) {
// Get an iterator to point to the insertion location, which is
// just before the terminator instruction.
//
TerminatorInst *InsertPos = BB->getTerminator();
std::ostringstream OutStr;
WriteAsOperand(OutStr, BB, false);
InsertPrintInst(0, BB, InsertPos, "LEAVING BB:" + OutStr.str(),
Printf, HashPtrToSeqNum);
// Insert a print instruction for each instruction preceding InsertPos.
// The print instructions must go before InsertPos, so we use the
// instruction *preceding* InsertPos to check when to terminate the loop.
//
for (BasicBlock::iterator II = BB->begin(); &*II != InsertPos; ++II) {
if (StoreInst *SI = dyn_cast<StoreInst>(&*II)) {
assert(valuesStoredInFunction &&
"Should not be printing a store instruction at function exit");
LoadInst *LI = new LoadInst(SI->getPointerOperand(), "reload." +
SI->getPointerOperand()->getName(),
InsertPos);
valuesStoredInFunction->push_back(LI);
}
if (ShouldTraceValue(II))
InsertVerbosePrintInst(II, BB, InsertPos, " ", Printf, HashPtrToSeqNum);
}
}
static inline void InsertCodeToShowFunctionEntry(Function &F, Function *Printf,
Function* HashPtrToSeqNum){
// Get an iterator to point to the insertion location
BasicBlock &BB = F.getEntryNode();
Instruction *InsertPos = BB.begin();
std::ostringstream OutStr;
WriteAsOperand(OutStr, &F);
InsertPrintInst(0, &BB, InsertPos, "ENTERING FUNCTION: " + OutStr.str(),
Printf, HashPtrToSeqNum);
// Now print all the incoming arguments
unsigned ArgNo = 0;
for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I, ++ArgNo){
InsertVerbosePrintInst(I, &BB, InsertPos,
" Arg #" + utostr(ArgNo) + ": ", Printf,
HashPtrToSeqNum);
}
}
static inline void InsertCodeToShowFunctionExit(BasicBlock *BB,
Function *Printf,
Function* HashPtrToSeqNum) {
// Get an iterator to point to the insertion location
ReturnInst *Ret = cast<ReturnInst>(BB->getTerminator());
std::ostringstream OutStr;
WriteAsOperand(OutStr, BB->getParent(), true);
InsertPrintInst(0, BB, Ret, "LEAVING FUNCTION: " + OutStr.str(),
Printf, HashPtrToSeqNum);
// print the return value, if any
if (BB->getParent()->getReturnType() != Type::VoidTy)
InsertPrintInst(Ret->getReturnValue(), BB, Ret, " Returning: ",
Printf, HashPtrToSeqNum);
}
bool InsertTraceCode::runOnFunction(Function &F) {
if (!TraceThisFunction(F))
return false;
vector<Instruction*> valuesStoredInFunction;
vector<BasicBlock*> exitBlocks;
// Insert code to trace values at function entry
InsertCodeToShowFunctionEntry(F, externalFuncs.PrintfFunc,
externalFuncs.HashPtrFunc);
// Push a pointer set for recording alloca'd pointers at entry.
if (!DisablePtrHashing)
new CallInst(externalFuncs.PushOnEntryFunc, vector<Value*>(), "",
F.getEntryNode().begin());
for (Function::iterator BB = F.begin(); BB != F.end(); ++BB) {
if (isa<ReturnInst>(BB->getTerminator()))
exitBlocks.push_back(BB); // record this as an exit block
// Insert trace code if this basic block is interesting...
handleBasicBlock(BB, valuesStoredInFunction);
if (!DisablePtrHashing) // release seq. numbers on free/ret
ReleasePtrSeqNumbers(BB, externalFuncs);
}
for (unsigned i=0; i != exitBlocks.size(); ++i)
{
// Insert code to trace values at function exit
InsertCodeToShowFunctionExit(exitBlocks[i], externalFuncs.PrintfFunc,
externalFuncs.HashPtrFunc);
// Release all recorded pointers before RETURN. Do this LAST!
if (!DisablePtrHashing)
new CallInst(externalFuncs.ReleaseOnReturnFunc, vector<Value*>(), "",
exitBlocks[i]->getTerminator());
}
return true;
}
<|endoftext|> |
<commit_before>
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "Test.h"
#include "SkPathMeasure.h"
static void test_small_segment3(skiatest::Reporter* reporter) {
#ifdef SK_SCALAR_IS_FLOAT
SkPath path;
const SkPoint pts[] = {
{ 0, 0 },
{ 100000000000.0f, 100000000000.0f }, { 0, 0 }, { 10, 10 },
{ 10, 10 }, { 0, 0 }, { 10, 10 }
};
path.moveTo(pts[0]);
for (size_t i = 1; i < SK_ARRAY_COUNT(pts); i += 2) {
path.cubicTo(pts[i], pts[i + 1], pts[i + 2]);
}
SkPathMeasure meas(path, false);
meas.getLength();
#endif
}
static void test_small_segment2(skiatest::Reporter* reporter) {
#ifdef SK_SCALAR_IS_FLOAT
SkPath path;
const SkPoint pts[] = {
{ 0, 0 },
{ 100000000000.0f, 100000000000.0f }, { 0, 0 },
{ 10, 10 }, { 0, 0 },
};
path.moveTo(pts[0]);
for (size_t i = 1; i < SK_ARRAY_COUNT(pts); i += 2) {
path.quadTo(pts[i], pts[i + 1]);
}
SkPathMeasure meas(path, false);
meas.getLength();
#endif
}
static void test_small_segment(skiatest::Reporter* reporter) {
#ifdef SK_SCALAR_IS_FLOAT
SkPath path;
const SkPoint pts[] = {
{ 100000, 100000},
// big jump between these points, makes a big segment
{ SkFloatToScalar(1.0005f), SkFloatToScalar(0.9999f) },
// tiny (non-zero) jump between these points
{ SK_Scalar1, SK_Scalar1 },
};
path.moveTo(pts[0]);
for (size_t i = 1; i < SK_ARRAY_COUNT(pts); ++i) {
path.lineTo(pts[i]);
}
SkPathMeasure meas(path, false);
/* this would assert (before a fix) because we added a segment with
the same length as the prev segment, due to the follow (bad) pattern
d = distance(pts[0], pts[1]);
distance += d;
seg->fDistance = distance;
SkASSERT(d > 0); // TRUE
SkASSERT(seg->fDistance > prevSeg->fDistance); // FALSE
This 2nd assert failes because (distance += d) didn't affect distance
because distance >>> d.
*/
meas.getLength();
#endif
}
static void TestPathMeasure(skiatest::Reporter* reporter) {
SkPath path;
path.moveTo(0, 0);
path.lineTo(SK_Scalar1, 0);
path.lineTo(SK_Scalar1, SK_Scalar1);
path.lineTo(0, SK_Scalar1);
SkPathMeasure meas(path, true);
SkScalar length = meas.getLength();
SkASSERT(length == SK_Scalar1*4);
path.reset();
path.moveTo(0, 0);
path.lineTo(SK_Scalar1*3, SK_Scalar1*4);
meas.setPath(&path, false);
length = meas.getLength();
REPORTER_ASSERT(reporter, length == SK_Scalar1*5);
path.reset();
path.addCircle(0, 0, SK_Scalar1);
meas.setPath(&path, true);
length = meas.getLength();
// SkDebugf("circle arc-length = %g\n", length);
// Test the behavior following a close not followed by a move.
path.reset();
path.lineTo(SK_Scalar1, 0);
path.lineTo(SK_Scalar1, SK_Scalar1);
path.lineTo(0, SK_Scalar1);
path.close();
path.lineTo(-SK_Scalar1, 0);
meas.setPath(&path, false);
length = meas.getLength();
REPORTER_ASSERT(reporter, length == SK_Scalar1 * 4);
meas.nextContour();
length = meas.getLength();
REPORTER_ASSERT(reporter, length == SK_Scalar1);
SkPoint position;
SkVector tangent;
REPORTER_ASSERT(reporter, meas.getPosTan(SK_ScalarHalf, &position, &tangent));
REPORTER_ASSERT(reporter,
SkScalarNearlyEqual(position.fX,
-SK_ScalarHalf,
SkFloatToScalar(0.0001f)));
REPORTER_ASSERT(reporter, position.fY == 0);
REPORTER_ASSERT(reporter, tangent.fX == -SK_Scalar1);
REPORTER_ASSERT(reporter, tangent.fY == 0);
// Test degenerate paths
path.reset();
path.moveTo(0, 0);
path.lineTo(0, 0);
path.lineTo(SK_Scalar1, 0);
path.quadTo(SK_Scalar1, 0, SK_Scalar1, 0);
path.quadTo(SK_Scalar1, SK_Scalar1, SK_Scalar1, SK_Scalar1 * 2);
path.cubicTo(SK_Scalar1, SK_Scalar1 * 2,
SK_Scalar1, SK_Scalar1 * 2,
SK_Scalar1, SK_Scalar1 * 2);
path.cubicTo(SK_Scalar1*2, SK_Scalar1 * 2,
SK_Scalar1*3, SK_Scalar1 * 2,
SK_Scalar1*4, SK_Scalar1 * 2);
meas.setPath(&path, false);
length = meas.getLength();
REPORTER_ASSERT(reporter, length == SK_Scalar1 * 6);
REPORTER_ASSERT(reporter, meas.getPosTan(SK_ScalarHalf, &position, &tangent));
REPORTER_ASSERT(reporter,
SkScalarNearlyEqual(position.fX,
SK_ScalarHalf,
SkFloatToScalar(0.0001f)));
REPORTER_ASSERT(reporter, position.fY == 0);
REPORTER_ASSERT(reporter, tangent.fX == SK_Scalar1);
REPORTER_ASSERT(reporter, tangent.fY == 0);
REPORTER_ASSERT(reporter, meas.getPosTan(SkFloatToScalar(2.5f), &position, &tangent));
REPORTER_ASSERT(reporter,
SkScalarNearlyEqual(position.fX, SK_Scalar1, SkFloatToScalar(0.0001f)));
REPORTER_ASSERT(reporter,
SkScalarNearlyEqual(position.fY, SkFloatToScalar(1.5f)));
REPORTER_ASSERT(reporter, tangent.fX == 0);
REPORTER_ASSERT(reporter, tangent.fY == SK_Scalar1);
REPORTER_ASSERT(reporter, meas.getPosTan(SkFloatToScalar(4.5f), &position, &tangent));
REPORTER_ASSERT(reporter,
SkScalarNearlyEqual(position.fX,
SkFloatToScalar(2.5f),
SkFloatToScalar(0.0001f)));
REPORTER_ASSERT(reporter,
SkScalarNearlyEqual(position.fY,
SkFloatToScalar(2.0f),
SkFloatToScalar(0.0001f)));
REPORTER_ASSERT(reporter, tangent.fX == SK_Scalar1);
REPORTER_ASSERT(reporter, tangent.fY == 0);
path.reset();
path.moveTo(0, 0);
path.lineTo(SK_Scalar1, 0);
path.moveTo(SK_Scalar1, SK_Scalar1);
path.moveTo(SK_Scalar1 * 2, SK_Scalar1 * 2);
path.lineTo(SK_Scalar1, SK_Scalar1 * 2);
meas.setPath(&path, false);
length = meas.getLength();
REPORTER_ASSERT(reporter, length == SK_Scalar1);
REPORTER_ASSERT(reporter, meas.getPosTan(SK_ScalarHalf, &position, &tangent));
REPORTER_ASSERT(reporter,
SkScalarNearlyEqual(position.fX,
SK_ScalarHalf,
SkFloatToScalar(0.0001f)));
REPORTER_ASSERT(reporter, position.fY == 0);
REPORTER_ASSERT(reporter, tangent.fX == SK_Scalar1);
REPORTER_ASSERT(reporter, tangent.fY == 0);
meas.nextContour();
length = meas.getLength();
REPORTER_ASSERT(reporter, length == SK_Scalar1);
REPORTER_ASSERT(reporter, meas.getPosTan(SK_ScalarHalf, &position, &tangent));
REPORTER_ASSERT(reporter,
SkScalarNearlyEqual(position.fX,
SkFloatToScalar(1.5f),
SkFloatToScalar(0.0001f)));
REPORTER_ASSERT(reporter,
SkScalarNearlyEqual(position.fY,
SkFloatToScalar(2.0f),
SkFloatToScalar(0.0001f)));
REPORTER_ASSERT(reporter, tangent.fX == -SK_Scalar1);
REPORTER_ASSERT(reporter, tangent.fY == 0);
test_small_segment(reporter);
test_small_segment2(reporter);
test_small_segment3(reporter);
}
#include "TestClassDef.h"
DEFINE_TESTCLASS("PathMeasure", PathMeasureTestClass, TestPathMeasure)
<commit_msg>Fix test_small_segments3 path measure test. Review URL: https://codereview.appspot.com/6601050<commit_after>
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "Test.h"
#include "SkPathMeasure.h"
static void test_small_segment3(skiatest::Reporter* reporter) {
#ifdef SK_SCALAR_IS_FLOAT
SkPath path;
const SkPoint pts[] = {
{ 0, 0 },
{ 100000000000.0f, 100000000000.0f }, { 0, 0 }, { 10, 10 },
{ 10, 10 }, { 0, 0 }, { 10, 10 }
};
path.moveTo(pts[0]);
for (size_t i = 1; i < SK_ARRAY_COUNT(pts); i += 3) {
path.cubicTo(pts[i], pts[i + 1], pts[i + 2]);
}
SkPathMeasure meas(path, false);
meas.getLength();
#endif
}
static void test_small_segment2(skiatest::Reporter* reporter) {
#ifdef SK_SCALAR_IS_FLOAT
SkPath path;
const SkPoint pts[] = {
{ 0, 0 },
{ 100000000000.0f, 100000000000.0f }, { 0, 0 },
{ 10, 10 }, { 0, 0 },
};
path.moveTo(pts[0]);
for (size_t i = 1; i < SK_ARRAY_COUNT(pts); i += 2) {
path.quadTo(pts[i], pts[i + 1]);
}
SkPathMeasure meas(path, false);
meas.getLength();
#endif
}
static void test_small_segment(skiatest::Reporter* reporter) {
#ifdef SK_SCALAR_IS_FLOAT
SkPath path;
const SkPoint pts[] = {
{ 100000, 100000},
// big jump between these points, makes a big segment
{ SkFloatToScalar(1.0005f), SkFloatToScalar(0.9999f) },
// tiny (non-zero) jump between these points
{ SK_Scalar1, SK_Scalar1 },
};
path.moveTo(pts[0]);
for (size_t i = 1; i < SK_ARRAY_COUNT(pts); ++i) {
path.lineTo(pts[i]);
}
SkPathMeasure meas(path, false);
/* this would assert (before a fix) because we added a segment with
the same length as the prev segment, due to the follow (bad) pattern
d = distance(pts[0], pts[1]);
distance += d;
seg->fDistance = distance;
SkASSERT(d > 0); // TRUE
SkASSERT(seg->fDistance > prevSeg->fDistance); // FALSE
This 2nd assert failes because (distance += d) didn't affect distance
because distance >>> d.
*/
meas.getLength();
#endif
}
static void TestPathMeasure(skiatest::Reporter* reporter) {
SkPath path;
path.moveTo(0, 0);
path.lineTo(SK_Scalar1, 0);
path.lineTo(SK_Scalar1, SK_Scalar1);
path.lineTo(0, SK_Scalar1);
SkPathMeasure meas(path, true);
SkScalar length = meas.getLength();
SkASSERT(length == SK_Scalar1*4);
path.reset();
path.moveTo(0, 0);
path.lineTo(SK_Scalar1*3, SK_Scalar1*4);
meas.setPath(&path, false);
length = meas.getLength();
REPORTER_ASSERT(reporter, length == SK_Scalar1*5);
path.reset();
path.addCircle(0, 0, SK_Scalar1);
meas.setPath(&path, true);
length = meas.getLength();
// SkDebugf("circle arc-length = %g\n", length);
// Test the behavior following a close not followed by a move.
path.reset();
path.lineTo(SK_Scalar1, 0);
path.lineTo(SK_Scalar1, SK_Scalar1);
path.lineTo(0, SK_Scalar1);
path.close();
path.lineTo(-SK_Scalar1, 0);
meas.setPath(&path, false);
length = meas.getLength();
REPORTER_ASSERT(reporter, length == SK_Scalar1 * 4);
meas.nextContour();
length = meas.getLength();
REPORTER_ASSERT(reporter, length == SK_Scalar1);
SkPoint position;
SkVector tangent;
REPORTER_ASSERT(reporter, meas.getPosTan(SK_ScalarHalf, &position, &tangent));
REPORTER_ASSERT(reporter,
SkScalarNearlyEqual(position.fX,
-SK_ScalarHalf,
SkFloatToScalar(0.0001f)));
REPORTER_ASSERT(reporter, position.fY == 0);
REPORTER_ASSERT(reporter, tangent.fX == -SK_Scalar1);
REPORTER_ASSERT(reporter, tangent.fY == 0);
// Test degenerate paths
path.reset();
path.moveTo(0, 0);
path.lineTo(0, 0);
path.lineTo(SK_Scalar1, 0);
path.quadTo(SK_Scalar1, 0, SK_Scalar1, 0);
path.quadTo(SK_Scalar1, SK_Scalar1, SK_Scalar1, SK_Scalar1 * 2);
path.cubicTo(SK_Scalar1, SK_Scalar1 * 2,
SK_Scalar1, SK_Scalar1 * 2,
SK_Scalar1, SK_Scalar1 * 2);
path.cubicTo(SK_Scalar1*2, SK_Scalar1 * 2,
SK_Scalar1*3, SK_Scalar1 * 2,
SK_Scalar1*4, SK_Scalar1 * 2);
meas.setPath(&path, false);
length = meas.getLength();
REPORTER_ASSERT(reporter, length == SK_Scalar1 * 6);
REPORTER_ASSERT(reporter, meas.getPosTan(SK_ScalarHalf, &position, &tangent));
REPORTER_ASSERT(reporter,
SkScalarNearlyEqual(position.fX,
SK_ScalarHalf,
SkFloatToScalar(0.0001f)));
REPORTER_ASSERT(reporter, position.fY == 0);
REPORTER_ASSERT(reporter, tangent.fX == SK_Scalar1);
REPORTER_ASSERT(reporter, tangent.fY == 0);
REPORTER_ASSERT(reporter, meas.getPosTan(SkFloatToScalar(2.5f), &position, &tangent));
REPORTER_ASSERT(reporter,
SkScalarNearlyEqual(position.fX, SK_Scalar1, SkFloatToScalar(0.0001f)));
REPORTER_ASSERT(reporter,
SkScalarNearlyEqual(position.fY, SkFloatToScalar(1.5f)));
REPORTER_ASSERT(reporter, tangent.fX == 0);
REPORTER_ASSERT(reporter, tangent.fY == SK_Scalar1);
REPORTER_ASSERT(reporter, meas.getPosTan(SkFloatToScalar(4.5f), &position, &tangent));
REPORTER_ASSERT(reporter,
SkScalarNearlyEqual(position.fX,
SkFloatToScalar(2.5f),
SkFloatToScalar(0.0001f)));
REPORTER_ASSERT(reporter,
SkScalarNearlyEqual(position.fY,
SkFloatToScalar(2.0f),
SkFloatToScalar(0.0001f)));
REPORTER_ASSERT(reporter, tangent.fX == SK_Scalar1);
REPORTER_ASSERT(reporter, tangent.fY == 0);
path.reset();
path.moveTo(0, 0);
path.lineTo(SK_Scalar1, 0);
path.moveTo(SK_Scalar1, SK_Scalar1);
path.moveTo(SK_Scalar1 * 2, SK_Scalar1 * 2);
path.lineTo(SK_Scalar1, SK_Scalar1 * 2);
meas.setPath(&path, false);
length = meas.getLength();
REPORTER_ASSERT(reporter, length == SK_Scalar1);
REPORTER_ASSERT(reporter, meas.getPosTan(SK_ScalarHalf, &position, &tangent));
REPORTER_ASSERT(reporter,
SkScalarNearlyEqual(position.fX,
SK_ScalarHalf,
SkFloatToScalar(0.0001f)));
REPORTER_ASSERT(reporter, position.fY == 0);
REPORTER_ASSERT(reporter, tangent.fX == SK_Scalar1);
REPORTER_ASSERT(reporter, tangent.fY == 0);
meas.nextContour();
length = meas.getLength();
REPORTER_ASSERT(reporter, length == SK_Scalar1);
REPORTER_ASSERT(reporter, meas.getPosTan(SK_ScalarHalf, &position, &tangent));
REPORTER_ASSERT(reporter,
SkScalarNearlyEqual(position.fX,
SkFloatToScalar(1.5f),
SkFloatToScalar(0.0001f)));
REPORTER_ASSERT(reporter,
SkScalarNearlyEqual(position.fY,
SkFloatToScalar(2.0f),
SkFloatToScalar(0.0001f)));
REPORTER_ASSERT(reporter, tangent.fX == -SK_Scalar1);
REPORTER_ASSERT(reporter, tangent.fY == 0);
test_small_segment(reporter);
test_small_segment2(reporter);
test_small_segment3(reporter);
}
#include "TestClassDef.h"
DEFINE_TESTCLASS("PathMeasure", PathMeasureTestClass, TestPathMeasure)
<|endoftext|> |
<commit_before>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include <cctype>
#include <algorithm>
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/optional.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/identify_client.hpp"
#include "libtorrent/fingerprint.hpp"
namespace
{
using namespace libtorrent;
int decode_digit(char c)
{
if (std::isdigit(c)) return c - '0';
return unsigned(c) - 'A' + 10;
}
// takes a peer id and returns a valid boost::optional
// object if the peer id matched the azureus style encoding
// the returned fingerprint contains information about the
// client's id
boost::optional<fingerprint> parse_az_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (id[0] != '-' || !std::isprint(id[1]) || (id[2] < '0')
|| (id[3] < '0') || (id[4] < '0')
|| (id[5] < '0') || (id[6] < '0')
|| id[7] != '-')
return boost::optional<fingerprint>();
ret.name[0] = id[1];
ret.name[1] = id[2];
ret.major_version = decode_digit(id[3]);
ret.minor_version = decode_digit(id[4]);
ret.revision_version = decode_digit(id[5]);
ret.tag_version = decode_digit(id[6]);
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a shadow-style
// identification
boost::optional<fingerprint> parse_shadow_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (!std::isalnum(id[0]))
return boost::optional<fingerprint>();
if (std::equal(id.begin()+4, id.begin()+6, "--"))
{
if ((id[1] < '0') || (id[2] < '0')
|| (id[3] < '0'))
return boost::optional<fingerprint>();
ret.major_version = decode_digit(id[1]);
ret.minor_version = decode_digit(id[2]);
ret.revision_version = decode_digit(id[3]);
}
else
{
if (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127)
return boost::optional<fingerprint>();
ret.major_version = id[1];
ret.minor_version = id[2];
ret.revision_version = id[3];
}
ret.name[0] = id[0];
ret.name[1] = 0;
ret.tag_version = 0;
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a mainline-style
// identification
boost::optional<fingerprint> parse_mainline_style(const peer_id& id)
{
char ids[21];
std::copy(id.begin(), id.end(), ids);
ids[20] = 0;
fingerprint ret("..", 0, 0, 0, 0);
ret.name[1] = 0;
ret.tag_version = 0;
if (sscanf(ids, "%c%d-%d-%d--", &ret.name[0], &ret.major_version, &ret.minor_version
, &ret.revision_version) != 4
|| !std::isprint(ret.name[0]))
return boost::optional<fingerprint>();
return boost::optional<fingerprint>(ret);
}
typedef std::pair<char const*, char const*> map_entry;
// only support BitTorrentSpecification
// must be ordered alphabetically
map_entry name_map[] =
{
map_entry("A", "ABC")
, map_entry("AR", "Arctic Torrent")
, map_entry("AX", "BitPump")
, map_entry("AZ", "Azureus")
, map_entry("BB", "BitBuddy")
, map_entry("BC", "BitComet")
, map_entry("BF", "Bitflu")
, map_entry("BG", "btgdaemon")
, map_entry("BS", "BTSlave")
, map_entry("BX", "BittorrentX")
, map_entry("CD", "Enhanced CTorrent")
, map_entry("CT", "CTorrent")
, map_entry("DE", "Deluge")
, map_entry("ES", "electric sheep")
, map_entry("HL", "Halite")
, map_entry("KT", "KTorrent")
, map_entry("LK", "Linkage")
, map_entry("LP", "lphant")
, map_entry("LT", "libtorrent")
, map_entry("M", "Mainline")
, map_entry("ML", "MLDonkey")
, map_entry("MO", "Mono Torrent")
, map_entry("MP", "MooPolice")
, map_entry("MT", "Moonlight Torrent")
, map_entry("O", "Osprey Permaseed")
, map_entry("QT", "Qt 4")
, map_entry("R", "Tribler")
, map_entry("S", "Shadow")
, map_entry("SB", "Swiftbit")
, map_entry("SN", "ShareNet")
, map_entry("SS", "SwarmScope")
, map_entry("SZ", "Shareaza")
, map_entry("T", "BitTornado")
, map_entry("TN", "Torrent.NET")
, map_entry("TR", "Transmission")
, map_entry("TS", "TorrentStorm")
, map_entry("U", "UPnP")
, map_entry("UL", "uLeecher")
, map_entry("UT", "MicroTorrent")
, map_entry("XT", "XanTorrent")
, map_entry("XX", "Xtorrent")
, map_entry("ZT", "ZipTorrent")
, map_entry("lt", "libTorrent (libtorrent.rakshasa.no/)")
, map_entry("pX", "pHoeniX")
, map_entry("qB", "qBittorrent")
};
bool compare_first_string(map_entry const& lhs, map_entry const& rhs)
{
return lhs.first[0] < rhs.first[0]
|| ((lhs.first[0] == rhs.first[0]) && (lhs.first[1] < rhs.first[1]));
}
std::string lookup(fingerprint const& f)
{
std::stringstream identity;
const int size = sizeof(name_map)/sizeof(name_map[0]);
map_entry* i =
std::lower_bound(name_map, name_map + size
, map_entry(f.name, ""), &compare_first_string);
#ifndef NDEBUG
for (int i = 1; i < size; ++i)
{
assert(compare_first_string(name_map[i-1]
, name_map[i]));
}
#endif
if (i < name_map + size && std::equal(f.name, f.name + 2, i->first))
identity << i->second;
else
{
identity << f.name[0];
if (f.name[1] != 0) identity << f.name[1];
}
identity << " " << (int)f.major_version
<< "." << (int)f.minor_version
<< "." << (int)f.revision_version;
if (f.name[1] != 0)
identity << "." << (int)f.tag_version;
return identity.str();
}
bool find_string(unsigned char const* id, char const* search)
{
return std::equal(search, search + std::strlen(search), id);
}
}
namespace libtorrent
{
boost::optional<fingerprint> client_fingerprint(peer_id const& p)
{
// look for azureus style id
boost::optional<fingerprint> f;
f = parse_az_style(p);
if (f) return f;
// look for shadow style id
f = parse_shadow_style(p);
if (f) return f;
// look for mainline style id
f = parse_mainline_style(p);
if (f) return f;
return f;
}
std::string identify_client(peer_id const& p)
{
peer_id::const_iterator PID = p.begin();
boost::optional<fingerprint> f;
if (p.is_all_zeros()) return "Unknown";
// ----------------------
// non standard encodings
// ----------------------
if (find_string(PID, "Deadman Walking-")) return "Deadman";
if (find_string(PID + 5, "Azureus")) return "Azureus 2.0.3.2";
if (find_string(PID, "DansClient")) return "XanTorrent";
if (find_string(PID + 4, "btfans")) return "SimpleBT";
if (find_string(PID, "PRC.P---")) return "Bittorrent Plus! II";
if (find_string(PID, "P87.P---")) return "Bittorrent Plus!";
if (find_string(PID, "S587Plus")) return "Bittorrent Plus!";
if (find_string(PID, "martini")) return "Martini Man";
if (find_string(PID, "Plus---")) return "Bittorrent Plus";
if (find_string(PID, "turbobt")) return "TurboBT";
if (find_string(PID, "a00---0")) return "Swarmy";
if (find_string(PID, "a02---0")) return "Swarmy";
if (find_string(PID, "T00---0")) return "Teeweety";
if (find_string(PID, "BTDWV-")) return "Deadman Walking";
if (find_string(PID + 2, "BS")) return "BitSpirit";
if (find_string(PID, "btuga")) return "BTugaXP";
if (find_string(PID, "oernu")) return "BTugaXP";
if (find_string(PID, "Mbrst")) return "Burst!";
if (find_string(PID, "Plus")) return "Plus!";
if (find_string(PID, "-Qt-")) return "Qt";
if (find_string(PID, "exbc")) return "BitComet";
if (find_string(PID, "-G3")) return "G3 Torrent";
if (find_string(PID, "XBT")) return "XBT";
if (find_string(PID, "OP")) return "Opera";
if (find_string(PID, "-BOW") && PID[7] == '-')
return "Bits on Wheels " + std::string(PID + 4, PID + 7);
if (find_string(PID, "eX"))
{
std::string user(PID + 2, PID + 14);
return std::string("eXeem ('") + user.c_str() + "')";
}
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\x97"))
return "Experimental 3.2.1b2";
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Experimental 3.1";
// look for azureus style id
f = parse_az_style(p);
if (f) return lookup(*f);
// look for shadow style id
f = parse_shadow_style(p);
if (f) return lookup(*f);
// look for mainline style id
f = parse_mainline_style(p);
if (f) return lookup(*f);
if (std::equal(PID, PID + 12, "\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Generic";
std::string unknown("Unknown [");
for (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)
{
unknown += std::isprint(*i)?*i:'.';
}
unknown += "]";
return unknown;
}
}
<commit_msg>added BitRocket to known clients<commit_after>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#include <cctype>
#include <algorithm>
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/optional.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/identify_client.hpp"
#include "libtorrent/fingerprint.hpp"
namespace
{
using namespace libtorrent;
int decode_digit(char c)
{
if (std::isdigit(c)) return c - '0';
return unsigned(c) - 'A' + 10;
}
// takes a peer id and returns a valid boost::optional
// object if the peer id matched the azureus style encoding
// the returned fingerprint contains information about the
// client's id
boost::optional<fingerprint> parse_az_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (id[0] != '-' || !std::isprint(id[1]) || (id[2] < '0')
|| (id[3] < '0') || (id[4] < '0')
|| (id[5] < '0') || (id[6] < '0')
|| id[7] != '-')
return boost::optional<fingerprint>();
ret.name[0] = id[1];
ret.name[1] = id[2];
ret.major_version = decode_digit(id[3]);
ret.minor_version = decode_digit(id[4]);
ret.revision_version = decode_digit(id[5]);
ret.tag_version = decode_digit(id[6]);
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a shadow-style
// identification
boost::optional<fingerprint> parse_shadow_style(const peer_id& id)
{
fingerprint ret("..", 0, 0, 0, 0);
if (!std::isalnum(id[0]))
return boost::optional<fingerprint>();
if (std::equal(id.begin()+4, id.begin()+6, "--"))
{
if ((id[1] < '0') || (id[2] < '0')
|| (id[3] < '0'))
return boost::optional<fingerprint>();
ret.major_version = decode_digit(id[1]);
ret.minor_version = decode_digit(id[2]);
ret.revision_version = decode_digit(id[3]);
}
else
{
if (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127)
return boost::optional<fingerprint>();
ret.major_version = id[1];
ret.minor_version = id[2];
ret.revision_version = id[3];
}
ret.name[0] = id[0];
ret.name[1] = 0;
ret.tag_version = 0;
return boost::optional<fingerprint>(ret);
}
// checks if a peer id can possibly contain a mainline-style
// identification
boost::optional<fingerprint> parse_mainline_style(const peer_id& id)
{
char ids[21];
std::copy(id.begin(), id.end(), ids);
ids[20] = 0;
fingerprint ret("..", 0, 0, 0, 0);
ret.name[1] = 0;
ret.tag_version = 0;
if (sscanf(ids, "%c%d-%d-%d--", &ret.name[0], &ret.major_version, &ret.minor_version
, &ret.revision_version) != 4
|| !std::isprint(ret.name[0]))
return boost::optional<fingerprint>();
return boost::optional<fingerprint>(ret);
}
typedef std::pair<char const*, char const*> map_entry;
// only support BitTorrentSpecification
// must be ordered alphabetically
map_entry name_map[] =
{
map_entry("A", "ABC")
, map_entry("AR", "Arctic Torrent")
, map_entry("AX", "BitPump")
, map_entry("AZ", "Azureus")
, map_entry("BB", "BitBuddy")
, map_entry("BC", "BitComet")
, map_entry("BF", "Bitflu")
, map_entry("BG", "btgdaemon")
, map_entry("BR", "BitRocket")
, map_entry("BS", "BTSlave")
, map_entry("BX", "BittorrentX")
, map_entry("CD", "Enhanced CTorrent")
, map_entry("CT", "CTorrent")
, map_entry("DE", "Deluge")
, map_entry("ES", "electric sheep")
, map_entry("HL", "Halite")
, map_entry("KT", "KTorrent")
, map_entry("LK", "Linkage")
, map_entry("LP", "lphant")
, map_entry("LT", "libtorrent")
, map_entry("M", "Mainline")
, map_entry("ML", "MLDonkey")
, map_entry("MO", "Mono Torrent")
, map_entry("MP", "MooPolice")
, map_entry("MT", "Moonlight Torrent")
, map_entry("O", "Osprey Permaseed")
, map_entry("QT", "Qt 4")
, map_entry("R", "Tribler")
, map_entry("S", "Shadow")
, map_entry("SB", "Swiftbit")
, map_entry("SN", "ShareNet")
, map_entry("SS", "SwarmScope")
, map_entry("SZ", "Shareaza")
, map_entry("T", "BitTornado")
, map_entry("TN", "Torrent.NET")
, map_entry("TR", "Transmission")
, map_entry("TS", "TorrentStorm")
, map_entry("U", "UPnP")
, map_entry("UL", "uLeecher")
, map_entry("UT", "MicroTorrent")
, map_entry("XT", "XanTorrent")
, map_entry("XX", "Xtorrent")
, map_entry("ZT", "ZipTorrent")
, map_entry("lt", "libTorrent (libtorrent.rakshasa.no/)")
, map_entry("pX", "pHoeniX")
, map_entry("qB", "qBittorrent")
};
bool compare_first_string(map_entry const& lhs, map_entry const& rhs)
{
return lhs.first[0] < rhs.first[0]
|| ((lhs.first[0] == rhs.first[0]) && (lhs.first[1] < rhs.first[1]));
}
std::string lookup(fingerprint const& f)
{
std::stringstream identity;
const int size = sizeof(name_map)/sizeof(name_map[0]);
map_entry* i =
std::lower_bound(name_map, name_map + size
, map_entry(f.name, ""), &compare_first_string);
#ifndef NDEBUG
for (int i = 1; i < size; ++i)
{
assert(compare_first_string(name_map[i-1]
, name_map[i]));
}
#endif
if (i < name_map + size && std::equal(f.name, f.name + 2, i->first))
identity << i->second;
else
{
identity << f.name[0];
if (f.name[1] != 0) identity << f.name[1];
}
identity << " " << (int)f.major_version
<< "." << (int)f.minor_version
<< "." << (int)f.revision_version;
if (f.name[1] != 0)
identity << "." << (int)f.tag_version;
return identity.str();
}
bool find_string(unsigned char const* id, char const* search)
{
return std::equal(search, search + std::strlen(search), id);
}
}
namespace libtorrent
{
boost::optional<fingerprint> client_fingerprint(peer_id const& p)
{
// look for azureus style id
boost::optional<fingerprint> f;
f = parse_az_style(p);
if (f) return f;
// look for shadow style id
f = parse_shadow_style(p);
if (f) return f;
// look for mainline style id
f = parse_mainline_style(p);
if (f) return f;
return f;
}
std::string identify_client(peer_id const& p)
{
peer_id::const_iterator PID = p.begin();
boost::optional<fingerprint> f;
if (p.is_all_zeros()) return "Unknown";
// ----------------------
// non standard encodings
// ----------------------
if (find_string(PID, "Deadman Walking-")) return "Deadman";
if (find_string(PID + 5, "Azureus")) return "Azureus 2.0.3.2";
if (find_string(PID, "DansClient")) return "XanTorrent";
if (find_string(PID + 4, "btfans")) return "SimpleBT";
if (find_string(PID, "PRC.P---")) return "Bittorrent Plus! II";
if (find_string(PID, "P87.P---")) return "Bittorrent Plus!";
if (find_string(PID, "S587Plus")) return "Bittorrent Plus!";
if (find_string(PID, "martini")) return "Martini Man";
if (find_string(PID, "Plus---")) return "Bittorrent Plus";
if (find_string(PID, "turbobt")) return "TurboBT";
if (find_string(PID, "a00---0")) return "Swarmy";
if (find_string(PID, "a02---0")) return "Swarmy";
if (find_string(PID, "T00---0")) return "Teeweety";
if (find_string(PID, "BTDWV-")) return "Deadman Walking";
if (find_string(PID + 2, "BS")) return "BitSpirit";
if (find_string(PID, "btuga")) return "BTugaXP";
if (find_string(PID, "oernu")) return "BTugaXP";
if (find_string(PID, "Mbrst")) return "Burst!";
if (find_string(PID, "Plus")) return "Plus!";
if (find_string(PID, "-Qt-")) return "Qt";
if (find_string(PID, "exbc")) return "BitComet";
if (find_string(PID, "-G3")) return "G3 Torrent";
if (find_string(PID, "XBT")) return "XBT";
if (find_string(PID, "OP")) return "Opera";
if (find_string(PID, "-BOW") && PID[7] == '-')
return "Bits on Wheels " + std::string(PID + 4, PID + 7);
if (find_string(PID, "eX"))
{
std::string user(PID + 2, PID + 14);
return std::string("eXeem ('") + user.c_str() + "')";
}
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\x97"))
return "Experimental 3.2.1b2";
if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Experimental 3.1";
// look for azureus style id
f = parse_az_style(p);
if (f) return lookup(*f);
// look for shadow style id
f = parse_shadow_style(p);
if (f) return lookup(*f);
// look for mainline style id
f = parse_mainline_style(p);
if (f) return lookup(*f);
if (std::equal(PID, PID + 12, "\0\0\0\0\0\0\0\0\0\0\0\0"))
return "Generic";
std::string unknown("Unknown [");
for (peer_id::const_iterator i = p.begin(); i != p.end(); ++i)
{
unknown += std::isprint(*i)?*i:'.';
}
unknown += "]";
return unknown;
}
}
<|endoftext|> |
<commit_before>
#include "registerAddr.hpp"
#include "Gpu.hpp"
#include "OpenGLWindow.hpp"
#include "Memory.hpp"
#include "GpuControl.hpp"
Gpu::Gpu(Memory *memory) :
_clock(0),
_window(nullptr),
_memory(memory)
{
}
Gpu::~Gpu()
{
}
#define TILES0_ADDR 0x8000 // Go to 0x8FFF / 0->255
#define TILES1_ADDR 0x8800 // Go to 0x97FF / -128->127
#define TILE_W 8 // bits
#define TILE_H 8
#define BYTE_SIZE 8 // byte size 0000 0000 ;)
#define MAP_W 32
#define MAP0_ADDR 0x9800 // 32*32 tile
#define MAP1_ADDR 0x9C00 // 32*32 tile
#include <iostream>
std::string Gpu::toString()
{
t_gpuControl gpuC = (t_gpuControl){_memory->read_byte(REGISTER_LCDC)};
char buf[32];
std::string s;
sprintf(buf, "[%d, %d, %d, %d, %d, %d, %d, %d]",
gpuC.background ,
gpuC.sprite ,
gpuC.sprite_size ,
gpuC.tile_map ,
gpuC.tile_set ,
gpuC.window ,
gpuC.wtile_map ,
gpuC.display
);
s = std::string(buf);
return (s);
}
unsigned int gbColors[4] = {0x00FFFFFF, 0x00C0C0C0, 0x00606060, 0x00000000};
unsigned int Gpu::scanPixel(uint8_t line, unsigned int x)
{
t_gpuControl gpuC = (t_gpuControl){_memory->read_byte(REGISTER_LCDC)};
uint8_t scy = _memory->read_byte(REGISTER_SCY);
uint8_t scx = _memory->read_byte(REGISTER_SCX);
unsigned int tileMapAddr = gpuC.tile_map ? MAP1_ADDR : MAP0_ADDR;
unsigned int tileSetAddr = gpuC.tile_set ? TILES1_ADDR : TILES0_ADDR;
unsigned int tileId = _memory->read_byte(
tileMapAddr
+ (((line / TILE_W) + scy) * MAP_W)
+ (x / TILE_W) + scx); // TODO: use scroll X / Y here
unsigned int tileAddr = tileSetAddr + tileId * TILE_H * 2;
unsigned int sy = line % TILE_W;
unsigned int sx = x % TILE_W;
unsigned int rsx = BYTE_SIZE - sx - 1;
uint8_t sdata1 = _memory->read_byte(tileAddr + (sy * 2));
uint8_t sdata2 = _memory->read_byte(tileAddr + (sy * 2) + 1);
unsigned int colorId = ((sdata1 >> rsx) & 1) | (((sdata2 >> rsx) & 1) << 1);
return gbColors[colorId & 3];
}
void Gpu::scanActLine()
{
uint16_t addrLine;
unsigned int pixel;
uint8_t line = _memory->read_byte(REGISTER_LY);
for (int x = 0 ; x < WIN_WIDTH ; ++x) {
addrLine = line * WIN_WIDTH + x;
pixel = scanPixel(line, x);
_window->drawPixel(addrLine, pixel);
}
}
#include "interrupt.hpp"
void Gpu::step()
{
uint8_t line = _memory->read_byte(REGISTER_LY);
t_gpuMode mode = readGpuMode();
t_gpuStat gpuStat = {_memory->read_byte(REGISTER_STAT)};
switch (mode)
{
case OAM_READ:
if (_clock >= 80)
{
_clock = 0;
writeGpuMode(VRAM_READ);
if (gpuStat.interupt_oam)
_memory->write_byte(REGISTER_IF, _memory->read_byte(REGISTER_IF) | INTER_LCDC);
}
break ;
case VRAM_READ:
if (_clock >= 172)
{
_clock = 0;
writeGpuMode(HBLANK);
scanActLine();
}
break ;
case HBLANK:
if (_clock >= 204)
{
_clock = 0;
_memory->write_byte(REGISTER_LY, ++line);
if (line == 143)
{
writeGpuMode(VBLANK);
_window->renderLater();
_memory->write_byte(REGISTER_IF, _memory->read_byte(REGISTER_IF) | INTER_VBLANK);
}
else
{
writeGpuMode(OAM_READ);
}
if (gpuStat.interupt_hblank)
_memory->write_byte(REGISTER_IF, _memory->read_byte(REGISTER_IF) | INTER_LCDC);
}
break ;
case VBLANK:
if (_clock >= 456)
{
_clock = 0;
_memory->write_byte(REGISTER_LY, ++line);
if (line > 153)
{
writeGpuMode(OAM_READ);
_memory->write_byte(REGISTER_LY, 0);
}
if (gpuStat.interupt_vblank)
_memory->write_byte(REGISTER_IF, _memory->read_byte(REGISTER_IF) | INTER_LCDC);
}
break ;
default:
break ;
}
// Check LYC
gpuStat = {_memory->read_byte(REGISTER_STAT)};
gpuStat.coincidence = (uint8_t)(_memory->read_byte(REGISTER_LY) == _memory->read_byte(REGISTER_LYC));
_memory->write_byte(REGISTER_STAT, gpuStat.stat);
if (gpuStat.interupt_coincid && gpuStat.coincidence)
_memory->write_byte(REGISTER_IF, _memory->read_byte(REGISTER_IF) | INTER_LCDC);
}
void Gpu::init()
{
writeGpuMode(OAM_READ);
_clock = 0;
// TODO remove when bios is
std::cout << "set GPU to end, remove me when bios is" << std::endl;
writeGpuMode(VBLANK);
_clock = 455;
_window = OpenGLWindow::Instance();
_window->initialize();
}
void Gpu::accClock(unsigned int clock)
{
_clock += clock;
}
t_gpuMode Gpu::readGpuMode()
{
return static_cast<t_gpuMode>(_memory->read_byte(REGISTER_STAT) & 0x3);
}
void Gpu::writeGpuMode(t_gpuMode mode)
{
uint8_t stat = _memory->read_byte(REGISTER_STAT);
_memory->write_byte(REGISTER_STAT, (stat & 0xFC ) | mode);
}
t_sprite Gpu::findSprite(uint8_t line, uint8_t x, unsigned int spriteHeight)
{
t_sprite *displaySprite = nullptr;
t_sprite tmp;
for (int addr = 0xfe00 ; addr <= 0xfe9f ; addr += 4)
{
tmp.y_pos = _memory->read_byte(addr);// - 16;
tmp.x_pos = _memory->read_byte(addr + 1);// - 8;
tmp.tile_nbr = _memory->read_byte(addr + 2);
tmp.options = _memory->read_byte(addr + 3);
if (tmp.y_pos <= line && line <= (tmp.y_pos + spriteHeight))
{
if (tmp.x_pos <= x && x <= (tmp.x_pos + TILE_W))
{
if (!displaySprite || displaySprite->x_pos > tmp.x_pos)
*displaySprite = tmp;
}
}
}
return *displaySprite;
}
unsigned int Gpu::findSpritePixel(t_sprite sprite, uint8_t line, uint8_t x, uint8_t spriteHeight)
{
if (spriteHeight == 16)
sprite.tile_nbr >>= 1;
x = sprite.x_flip ? TILE_W - (x - sprite.x_pos) : x - sprite.x_pos;
line = sprite.y_flip ? spriteHeight + line - sprite.y_pos : line - sprite.y_pos;
unsigned int tileAddr = (TILES0_ADDR + (sprite.tile_nbr * 16));
unsigned int start = tileAddr + line;
uint8_t sdata1 = _memory->read_byte(start * 2);
uint8_t sdata2 = _memory->read_byte(start * 2 + 1);
unsigned int rx = TILE_W - x;
unsigned int colorId = ((sdata1 >> rx) & 1) | (((sdata2 >> rx) & 1) << 1);
return colorId;
}
unsigned int Gpu::scanSprite(uint8_t line, uint8_t x, unsigned int pixel)
{
t_gpuControl gpuC = (t_gpuControl){_memory->read_byte(REGISTER_LCDC)};
unsigned int spritePixel = 0xFFFFFF;
if (gpuC.sprite)
{
uint8_t spriteHeight = gpuC.sprite_size ? 16 : 8;
t_sprite sprite = findSprite(line, x, spriteHeight);
unsigned int colorId = findSpritePixel(sprite, line, x, spriteHeight);
uint8_t pal = sprite.pal == 0 ? _memory->read_byte(REGISTER_OBP0) :_memory->read_byte(REGISTER_OBP1);
spritePixel = pal >> (2 * colorId) & 0x03;
if (sprite.bckgrd_prio == 1 || pixel == 0)
return spritePixel;
}
return pixel;
}
<commit_msg>change reset gpu clock<commit_after>
#include "registerAddr.hpp"
#include "Gpu.hpp"
#include "OpenGLWindow.hpp"
#include "Memory.hpp"
#include "GpuControl.hpp"
Gpu::Gpu(Memory *memory) :
_clock(0),
_window(nullptr),
_memory(memory)
{
}
Gpu::~Gpu()
{
}
#define TILES0_ADDR 0x8000 // Go to 0x8FFF / 0->255
#define TILES1_ADDR 0x8800 // Go to 0x97FF / -128->127
#define TILE_W 8 // bits
#define TILE_H 8
#define BYTE_SIZE 8 // byte size 0000 0000 ;)
#define MAP_W 32
#define MAP0_ADDR 0x9800 // 32*32 tile
#define MAP1_ADDR 0x9C00 // 32*32 tile
#include <iostream>
std::string Gpu::toString()
{
t_gpuControl gpuC = (t_gpuControl){_memory->read_byte(REGISTER_LCDC)};
char buf[32];
std::string s;
sprintf(buf, "[%d, %d, %d, %d, %d, %d, %d, %d]",
gpuC.background ,
gpuC.sprite ,
gpuC.sprite_size ,
gpuC.tile_map ,
gpuC.tile_set ,
gpuC.window ,
gpuC.wtile_map ,
gpuC.display
);
s = std::string(buf);
return (s);
}
unsigned int gbColors[4] = {0x00FFFFFF, 0x00C0C0C0, 0x00606060, 0x00000000};
unsigned int Gpu::scanPixel(uint8_t line, unsigned int x)
{
t_gpuControl gpuC = (t_gpuControl){_memory->read_byte(REGISTER_LCDC)};
uint8_t scy = _memory->read_byte(REGISTER_SCY);
uint8_t scx = _memory->read_byte(REGISTER_SCX);
unsigned int tileMapAddr = gpuC.tile_map ? MAP1_ADDR : MAP0_ADDR;
unsigned int tileSetAddr = gpuC.tile_set ? TILES1_ADDR : TILES0_ADDR;
unsigned int tileId = _memory->read_byte(
tileMapAddr
+ (((line / TILE_W) + scy) * MAP_W)
+ (x / TILE_W) + scx); // TODO: use scroll X / Y here
unsigned int tileAddr = tileSetAddr + tileId * TILE_H * 2;
unsigned int sy = line % TILE_W;
unsigned int sx = x % TILE_W;
unsigned int rsx = BYTE_SIZE - sx - 1;
uint8_t sdata1 = _memory->read_byte(tileAddr + (sy * 2));
uint8_t sdata2 = _memory->read_byte(tileAddr + (sy * 2) + 1);
unsigned int colorId = ((sdata1 >> rsx) & 1) | (((sdata2 >> rsx) & 1) << 1);
return gbColors[colorId & 3];
}
void Gpu::scanActLine()
{
uint16_t addrLine;
unsigned int pixel;
uint8_t line = _memory->read_byte(REGISTER_LY);
for (int x = 0 ; x < WIN_WIDTH ; ++x) {
addrLine = line * WIN_WIDTH + x;
pixel = scanPixel(line, x);
_window->drawPixel(addrLine, pixel);
}
}
#include "interrupt.hpp"
void Gpu::step()
{
uint8_t line = _memory->read_byte(REGISTER_LY);
t_gpuMode mode = readGpuMode();
t_gpuStat gpuStat = {_memory->read_byte(REGISTER_STAT)};
switch (mode)
{
case OAM_READ:
if (_clock >= 80)
{
_clock -= 80;
writeGpuMode(VRAM_READ);
if (gpuStat.interupt_oam)
_memory->write_byte(REGISTER_IF, _memory->read_byte(REGISTER_IF) | INTER_LCDC);
}
break ;
case VRAM_READ:
if (_clock >= 172)
{
_clock -= 172;
writeGpuMode(HBLANK);
scanActLine();
}
break ;
case HBLANK:
if (_clock >= 204)
{
_clock -= 204;
_memory->write_byte(REGISTER_LY, ++line);
if (line == 143)
{
writeGpuMode(VBLANK);
_window->renderLater();
_memory->write_byte(REGISTER_IF, _memory->read_byte(REGISTER_IF) | INTER_VBLANK);
}
else
{
writeGpuMode(OAM_READ);
}
if (gpuStat.interupt_hblank)
_memory->write_byte(REGISTER_IF, _memory->read_byte(REGISTER_IF) | INTER_LCDC);
}
break ;
case VBLANK:
if (_clock >= 456)
{
_clock -= 456;
_memory->write_byte(REGISTER_LY, ++line);
if (line > 153)
{
writeGpuMode(OAM_READ);
_memory->write_byte(REGISTER_LY, 0);
}
if (gpuStat.interupt_vblank)
_memory->write_byte(REGISTER_IF, _memory->read_byte(REGISTER_IF) | INTER_LCDC);
}
break ;
default:
break ;
}
// Check LYC
gpuStat = {_memory->read_byte(REGISTER_STAT)};
gpuStat.coincidence = (uint8_t)(_memory->read_byte(REGISTER_LY) == _memory->read_byte(REGISTER_LYC));
_memory->write_byte(REGISTER_STAT, gpuStat.stat);
if (gpuStat.interupt_coincid && gpuStat.coincidence)
_memory->write_byte(REGISTER_IF, _memory->read_byte(REGISTER_IF) | INTER_LCDC);
}
void Gpu::init()
{
writeGpuMode(OAM_READ);
_clock = 0;
// TODO remove when bios is
std::cout << "set GPU to end, remove me when bios is" << std::endl;
writeGpuMode(VBLANK);
_clock = 455;
_window = OpenGLWindow::Instance();
_window->initialize();
}
void Gpu::accClock(unsigned int clock)
{
_clock += clock;
}
t_gpuMode Gpu::readGpuMode()
{
return static_cast<t_gpuMode>(_memory->read_byte(REGISTER_STAT) & 0x3);
}
void Gpu::writeGpuMode(t_gpuMode mode)
{
uint8_t stat = _memory->read_byte(REGISTER_STAT);
_memory->write_byte(REGISTER_STAT, (stat & 0xFC ) | mode);
}
t_sprite Gpu::findSprite(uint8_t line, uint8_t x, unsigned int spriteHeight)
{
t_sprite *displaySprite = nullptr;
t_sprite tmp;
for (int addr = 0xfe00 ; addr <= 0xfe9f ; addr += 4)
{
tmp.y_pos = _memory->read_byte(addr);// - 16;
tmp.x_pos = _memory->read_byte(addr + 1);// - 8;
tmp.tile_nbr = _memory->read_byte(addr + 2);
tmp.options = _memory->read_byte(addr + 3);
if (tmp.y_pos <= line && line <= (tmp.y_pos + spriteHeight))
{
if (tmp.x_pos <= x && x <= (tmp.x_pos + TILE_W))
{
if (!displaySprite || displaySprite->x_pos > tmp.x_pos)
*displaySprite = tmp;
}
}
}
return *displaySprite;
}
unsigned int Gpu::findSpritePixel(t_sprite sprite, uint8_t line, uint8_t x, uint8_t spriteHeight)
{
if (spriteHeight == 16)
sprite.tile_nbr >>= 1;
x = sprite.x_flip ? TILE_W - (x - sprite.x_pos) : x - sprite.x_pos;
line = sprite.y_flip ? spriteHeight + line - sprite.y_pos : line - sprite.y_pos;
unsigned int tileAddr = (TILES0_ADDR + (sprite.tile_nbr * 16));
unsigned int start = tileAddr + line;
uint8_t sdata1 = _memory->read_byte(start * 2);
uint8_t sdata2 = _memory->read_byte(start * 2 + 1);
unsigned int rx = TILE_W - x;
unsigned int colorId = ((sdata1 >> rx) & 1) | (((sdata2 >> rx) & 1) << 1);
return colorId;
}
unsigned int Gpu::scanSprite(uint8_t line, uint8_t x, unsigned int pixel)
{
t_gpuControl gpuC = (t_gpuControl){_memory->read_byte(REGISTER_LCDC)};
unsigned int spritePixel = 0xFFFFFF;
if (gpuC.sprite)
{
uint8_t spriteHeight = gpuC.sprite_size ? 16 : 8;
t_sprite sprite = findSprite(line, x, spriteHeight);
unsigned int colorId = findSpritePixel(sprite, line, x, spriteHeight);
uint8_t pal = sprite.pal == 0 ? _memory->read_byte(REGISTER_OBP0) :_memory->read_byte(REGISTER_OBP1);
spritePixel = pal >> (2 * colorId) & 0x03;
if (sprite.bckgrd_prio == 1 || pixel == 0)
return spritePixel;
}
return pixel;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: loaddispatcher.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: kz $ $Date: 2004-01-28 14:29:18 $
*
* 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): _______________________________________
*
*
************************************************************************/
//_______________________________________________
// my own includes
#ifndef __FRAMEWORK_DISPATCH_LOADDISPATCHER_HXX_
#include <dispatch/loaddispatcher.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_
#include <threadhelp/readguard.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_
#include <threadhelp/writeguard.hxx>
#endif
//_______________________________________________
// interface includes
#ifndef _COM_SUN_STAR_FRAME_DISPATCHRESULTSTATE_HPP_
#include <com/sun/star/frame/DispatchResultState.hpp>
#endif
//_______________________________________________
// includes of other projects
//_______________________________________________
// namespace
namespace framework{
namespace css = ::com::sun::star;
//_______________________________________________
// declarations
/*-----------------------------------------------
20.08.2003 09:52
-----------------------------------------------*/
LoadDispatcher::LoadDispatcher(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR ,
const css::uno::Reference< css::frame::XFrame >& xOwnerFrame ,
const ::rtl::OUString sTargetName ,
sal_Int32 nSearchFlags)
: ThreadHelpBase( )
, m_xSMGR (xSMGR )
, m_aLoader (xSMGR )
, m_xOwnerFrame (xOwnerFrame )
, m_sTarget (sTargetName )
, m_nSearchFlags(nSearchFlags)
{
}
/*-----------------------------------------------
20.08.2003 09:12
-----------------------------------------------*/
LoadDispatcher::~LoadDispatcher()
{
m_xSMGR.clear();
}
/*-----------------------------------------------
20.08.2003 09:58
-----------------------------------------------*/
void SAL_CALL LoadDispatcher::dispatchWithNotification(const css::util::URL& aURL ,
const css::uno::Sequence< css::beans::PropertyValue >& lArguments,
const css::uno::Reference< css::frame::XDispatchResultListener >& xListener )
throw(css::uno::RuntimeException)
{
// Attention: May be nobody outside hold such temp. dispatch object alive (because
// the container in which we resists isnt implemented threadsafe but updated by a timer
// and clear our reference ...) we should hold us self alive!
css::uno::Reference< css::uno::XInterface > xThis(static_cast< css::frame::XNotifyingDispatch* >(this), css::uno::UNO_QUERY);
// SAFE -> ----------------------------------
ReadGuard aReadLock(m_aLock);
// We are the only client of this load env object ... but
// may a dispatch request before is still in progress (?!).
// Then we should wait a little bit and block this new request.
// In case we run into the timeout, we should reject this new request
// and return "FAILED" as result. Otherwhise we can start this new operation.
if (!m_aLoader.waitWhileLoading(2000)) // => 2 sec.
{
if (xListener.is())
xListener->dispatchFinished(
css::frame::DispatchResultEvent(xThis, css::frame::DispatchResultState::DONTKNOW, css::uno::Any())); // DONTKNOW? ... not realy started ... not realy failed :-)
}
css::uno::Reference< css::frame::XFrame > xBaseFrame(m_xOwnerFrame.get(), css::uno::UNO_QUERY);
if (!xBaseFrame.is())
{
if (xListener.is())
xListener->dispatchFinished(
css::frame::DispatchResultEvent(xThis, css::frame::DispatchResultState::FAILURE, css::uno::Any()));
}
// OK ... now the internal loader seems to be useable for new requests
// and our owner frame seems to be valid for such operations.
// Initialize it with all new but needed properties and start the loading.
try
{
m_aLoader.initializeLoading(aURL.Complete, lArguments, xBaseFrame, m_sTarget, m_nSearchFlags, (LoadEnv::EFeature)(LoadEnv::E_ALLOW_CONTENTHANDLER | LoadEnv::E_WORK_WITH_UI));
m_aLoader.startLoading();
}
catch(const LoadEnvException&)
{
if (xListener.is())
xListener->dispatchFinished(
css::frame::DispatchResultEvent(xThis, css::frame::DispatchResultState::FAILURE, css::uno::Any()));
}
/*TODO implement listener support inside LoadEnv member ... */
// But dont wait for the results here.
// In case loading will be synchronous, the listener will be notified immediatly.
// In case it will be asynchronous such event will occure next time.
// But we block further requests on THIS dispatch object, till our internal
// used loader isnt still in progress any longer.
aReadLock.unlock();
// <- SAFE ----------------------------------
}
/*-----------------------------------------------
20.08.2003 09:16
-----------------------------------------------*/
void SAL_CALL LoadDispatcher::dispatch(const css::util::URL& aURL ,
const css::uno::Sequence< css::beans::PropertyValue >& lArguments)
throw(css::uno::RuntimeException)
{
dispatchWithNotification(aURL, lArguments, css::uno::Reference< css::frame::XDispatchResultListener >());
}
/*-----------------------------------------------
20.08.2003 10:48
-----------------------------------------------*/
void SAL_CALL LoadDispatcher::addStatusListener(const css::uno::Reference< css::frame::XStatusListener >& xListener,
const css::util::URL& aURL )
throw(css::uno::RuntimeException)
{
}
/*-----------------------------------------------
20.08.2003 10:49
-----------------------------------------------*/
void SAL_CALL LoadDispatcher::removeStatusListener(const css::uno::Reference< css::frame::XStatusListener >& xListener,
const css::util::URL& aURL )
throw(css::uno::RuntimeException)
{
}
} // namespace framework
<commit_msg>INTEGRATION: CWS mbaqfixes (1.2.24); FILE MERGED 2004/02/27 08:52:41 as 1.2.24.1: #115454# notify listener everytimes<commit_after>/*************************************************************************
*
* $RCSfile: loaddispatcher.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2004-03-08 16:16:39 $
*
* 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): _______________________________________
*
*
************************************************************************/
//_______________________________________________
// my own includes
#ifndef __FRAMEWORK_DISPATCH_LOADDISPATCHER_HXX_
#include <dispatch/loaddispatcher.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_
#include <threadhelp/readguard.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_
#include <threadhelp/writeguard.hxx>
#endif
//_______________________________________________
// interface includes
#ifndef _COM_SUN_STAR_FRAME_DISPATCHRESULTSTATE_HPP_
#include <com/sun/star/frame/DispatchResultState.hpp>
#endif
//_______________________________________________
// includes of other projects
//_______________________________________________
// namespace
namespace framework{
namespace css = ::com::sun::star;
//_______________________________________________
// declarations
/*-----------------------------------------------
20.08.2003 09:52
-----------------------------------------------*/
LoadDispatcher::LoadDispatcher(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR ,
const css::uno::Reference< css::frame::XFrame >& xOwnerFrame ,
const ::rtl::OUString sTargetName ,
sal_Int32 nSearchFlags)
: ThreadHelpBase( )
, m_xSMGR (xSMGR )
, m_aLoader (xSMGR )
, m_xOwnerFrame (xOwnerFrame )
, m_sTarget (sTargetName )
, m_nSearchFlags(nSearchFlags)
{
}
/*-----------------------------------------------
20.08.2003 09:12
-----------------------------------------------*/
LoadDispatcher::~LoadDispatcher()
{
m_xSMGR.clear();
}
/*-----------------------------------------------
20.08.2003 09:58
-----------------------------------------------*/
void SAL_CALL LoadDispatcher::dispatchWithNotification(const css::util::URL& aURL ,
const css::uno::Sequence< css::beans::PropertyValue >& lArguments,
const css::uno::Reference< css::frame::XDispatchResultListener >& xListener )
throw(css::uno::RuntimeException)
{
// Attention: May be nobody outside hold such temp. dispatch object alive (because
// the container in which we resists isnt implemented threadsafe but updated by a timer
// and clear our reference ...) we should hold us self alive!
css::uno::Reference< css::uno::XInterface > xThis(static_cast< css::frame::XNotifyingDispatch* >(this), css::uno::UNO_QUERY);
// SAFE -> ----------------------------------
ReadGuard aReadLock(m_aLock);
// We are the only client of this load env object ... but
// may a dispatch request before is still in progress (?!).
// Then we should wait a little bit and block this new request.
// In case we run into the timeout, we should reject this new request
// and return "FAILED" as result. Otherwhise we can start this new operation.
if (!m_aLoader.waitWhileLoading(2000)) // => 2 sec.
{
if (xListener.is())
xListener->dispatchFinished(
css::frame::DispatchResultEvent(xThis, css::frame::DispatchResultState::DONTKNOW, css::uno::Any())); // DONTKNOW? ... not realy started ... not realy failed :-)
}
css::uno::Reference< css::frame::XFrame > xBaseFrame(m_xOwnerFrame.get(), css::uno::UNO_QUERY);
if (!xBaseFrame.is())
{
if (xListener.is())
xListener->dispatchFinished(
css::frame::DispatchResultEvent(xThis, css::frame::DispatchResultState::FAILURE, css::uno::Any()));
}
// OK ... now the internal loader seems to be useable for new requests
// and our owner frame seems to be valid for such operations.
// Initialize it with all new but needed properties and start the loading.
css::uno::Reference< css::lang::XComponent > xComponent;
try
{
m_aLoader.initializeLoading(aURL.Complete, lArguments, xBaseFrame, m_sTarget, m_nSearchFlags, (LoadEnv::EFeature)(LoadEnv::E_ALLOW_CONTENTHANDLER | LoadEnv::E_WORK_WITH_UI));
m_aLoader.startLoading();
m_aLoader.waitWhileLoading(); // wait for ever!
xComponent = m_aLoader.getTargetComponent();
// TODO thinking about asynchronous operations and listener support
}
catch(const LoadEnvException&)
{ xComponent.clear(); }
if (xListener.is())
{
if (xComponent.is())
xListener->dispatchFinished(
css::frame::DispatchResultEvent(xThis, css::frame::DispatchResultState::SUCCESS, css::uno::Any()));
else
xListener->dispatchFinished(
css::frame::DispatchResultEvent(xThis, css::frame::DispatchResultState::FAILURE, css::uno::Any()));
}
aReadLock.unlock();
// <- SAFE ----------------------------------
}
/*-----------------------------------------------
20.08.2003 09:16
-----------------------------------------------*/
void SAL_CALL LoadDispatcher::dispatch(const css::util::URL& aURL ,
const css::uno::Sequence< css::beans::PropertyValue >& lArguments)
throw(css::uno::RuntimeException)
{
dispatchWithNotification(aURL, lArguments, css::uno::Reference< css::frame::XDispatchResultListener >());
}
/*-----------------------------------------------
20.08.2003 10:48
-----------------------------------------------*/
void SAL_CALL LoadDispatcher::addStatusListener(const css::uno::Reference< css::frame::XStatusListener >& xListener,
const css::util::URL& aURL )
throw(css::uno::RuntimeException)
{
}
/*-----------------------------------------------
20.08.2003 10:49
-----------------------------------------------*/
void SAL_CALL LoadDispatcher::removeStatusListener(const css::uno::Reference< css::frame::XStatusListener >& xListener,
const css::util::URL& aURL )
throw(css::uno::RuntimeException)
{
}
} // namespace framework
<|endoftext|> |
<commit_before>/*
* nbody.cc
*/
#include <sys/types.h>
#include <sys/time.h>
#include "def.h"
void simulate_a_step(particle ** particles, int n_particles, t_real dt)
{
int t0, t1, t2, t3, t4;
space * tree;
t0 = current_real_time_milli();
#if BUILD_TREE_PARALLEL
// tree = build_tree(particles, n_particles);
tree = build_tree_bottomup(particles, n_particles);
#else
tree = generate_tree(particles, n_particles);
#endif
t1 = current_real_time_milli();
mass_momentum mm = tree->set_mass_and_cg();
t2 = current_real_time_milli();
set_accels(particles, n_particles, tree);
t3 = current_real_time_milli();
move_particles(particles, n_particles, dt);
t4 = current_real_time_milli();
printf(" Tree nodes: %d\n"
#if BUILD_TREE_PARALLEL
" GenTree (pll): %d msec\n"
#else
" GenTree (seq): %d msec\n"
#endif /* BUILD_TREE_PARALLEL */
" SetMass: %d msec\n" \
" CompForces: %d msec\n" \
" Leapfrog: %d msec\n" \
" TotalElapsed: %d msec\n",
mm.n_nodes, t1 - t0, t2 - t1, t3 - t2, t4 - t3, t4 - t0);
}
void dump_particles (particle **, int);
void nbody_main (int n_particles, int n_steps, t_real dt, int dump_p)
{
particle ** particles = generate_particles(n_particles);
if (dump_p) dump_particles(particles, n_particles);
for (int i = 0; i < n_steps; i++)
simulate_a_step(particles, n_particles, dt);
if (dump_p) dump_particles(particles, n_particles);
}
int main (int argc, char ** argv)
{
if (argc != 3) {
printf ("usage: %s N STEPS\n", argv[0]);
exit(1);
}
int n_particles = atoi(argv[1]);
int n_steps = atoi(argv[2]);
int dump_p = 0;
t_real dt = 0.1;
printf("Start with N=%d, STEPS=%d\n", n_particles, n_steps);
int t0 = current_real_time_milli();
nbody_main(n_particles, n_steps, dt, dump_p);
int t1 = current_real_time_milli();
printf("Finish in %d msec\n", t1 - t0);
return 0;
}
<commit_msg>add bottomup tree build<commit_after>/*
* nbody.cc
*/
#include <sys/types.h>
#include <sys/time.h>
#include "def.h"
void simulate_a_step(particle ** particles, int n_particles, t_real dt)
{
int t0, t1, t2, t3, t4;
space * tree;
t0 = current_real_time_milli();
#if BUILD_TREE_PARALLEL
tree = build_tree(particles, n_particles);
// tree = build_tree_bottomup(particles, n_particles);
#else
tree = generate_tree(particles, n_particles);
#endif
t1 = current_real_time_milli();
mass_momentum mm = tree->set_mass_and_cg();
t2 = current_real_time_milli();
set_accels(particles, n_particles, tree);
t3 = current_real_time_milli();
move_particles(particles, n_particles, dt);
t4 = current_real_time_milli();
printf(" Tree nodes: %d\n"
#if BUILD_TREE_PARALLEL
" GenTree (pll): %d msec\n"
#else
" GenTree (seq): %d msec\n"
#endif /* BUILD_TREE_PARALLEL */
" SetMass: %d msec\n" \
" CompForces: %d msec\n" \
" Leapfrog: %d msec\n" \
" TotalElapsed: %d msec\n",
mm.n_nodes, t1 - t0, t2 - t1, t3 - t2, t4 - t3, t4 - t0);
}
void dump_particles (particle **, int);
void nbody_main (int n_particles, int n_steps, t_real dt, int dump_p)
{
particle ** particles = generate_particles(n_particles);
if (dump_p) dump_particles(particles, n_particles);
for (int i = 0; i < n_steps; i++)
simulate_a_step(particles, n_particles, dt);
if (dump_p) dump_particles(particles, n_particles);
}
int main (int argc, char ** argv)
{
if (argc != 3) {
printf ("usage: %s N STEPS\n", argv[0]);
exit(1);
}
int n_particles = atoi(argv[1]);
int n_steps = atoi(argv[2]);
int dump_p = 0;
t_real dt = 0.1;
printf("Start with N=%d, STEPS=%d\n", n_particles, n_steps);
int t0 = current_real_time_milli();
nbody_main(n_particles, n_steps, dt, dump_p);
int t1 = current_real_time_milli();
printf("Finish in %d msec\n", t1 - t0);
return 0;
}
<|endoftext|> |
<commit_before>/* ****************************************************************
*
* Copyright 2018 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 <media/FileOutputDataSource.h>
namespace media {
namespace stream {
FileOutputDataSource::FileOutputDataSource(const std::string& dataPath)
: OutputDataSource(), mDataPath(dataPath)
{
}
FileOutputDataSource::FileOutputDataSource(unsigned short channels, unsigned int sampleRate, int pcmFormat, const std::string& dataPath)
: OutputDataSource(channels, sampleRate, pcmFormat), mDataPath(dataPath)
{
}
FileOutputDataSource::FileOutputDataSource(const FileOutputDataSource& source) : OutputDataSource(source)
{
}
FileOutputDataSource& FileOutputDataSource::operator=(const FileOutputDataSource& source)
{
OutputDataSource::operator=(source);
return *this;
}
bool FileOutputDataSource::open()
{
mFp = fopen(mDataPath.c_str(), "w+");
return isPrepare();
}
void FileOutputDataSource::close()
{
fclose(mFp);
mFp = nullptr;
}
bool FileOutputDataSource::isPrepare()
{
return (mFp != nullptr);
}
size_t FileOutputDataSource::write(unsigned char* buf, size_t size)
{
return fwrite(buf, sizeof(unsigned char), size, mFp);
}
FileOutputDataSource::~FileOutputDataSource()
{
}
} // namespace stream
} // namespace media
<commit_msg>media : add logic for reopen case<commit_after>/* ****************************************************************
*
* Copyright 2018 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 <media/FileOutputDataSource.h>
namespace media {
namespace stream {
FileOutputDataSource::FileOutputDataSource(const std::string& dataPath)
: OutputDataSource(), mDataPath(dataPath), mFp(nullptr)
{
}
FileOutputDataSource::FileOutputDataSource(unsigned short channels, unsigned int sampleRate, int pcmFormat, const std::string& dataPath)
: OutputDataSource(channels, sampleRate, pcmFormat), mDataPath(dataPath), mFp(nullptr)
{
}
FileOutputDataSource::FileOutputDataSource(const FileOutputDataSource& source) : OutputDataSource(source)
{
}
FileOutputDataSource& FileOutputDataSource::operator=(const FileOutputDataSource& source)
{
OutputDataSource::operator=(source);
return *this;
}
bool FileOutputDataSource::open()
{
if (!mFp) {
mFp = fopen(mDataPath.c_str(), "w+");
return true;
}
medvdbg("file is already open\n");
return false;
}
void FileOutputDataSource::close()
{
fclose(mFp);
mFp = nullptr;
}
bool FileOutputDataSource::isPrepare()
{
return (mFp != nullptr);
}
size_t FileOutputDataSource::write(unsigned char* buf, size_t size)
{
return fwrite(buf, sizeof(unsigned char), size, mFp);
}
FileOutputDataSource::~FileOutputDataSource()
{
}
} // namespace stream
} // namespace media
<|endoftext|> |
<commit_before>#include "toml.hpp"
#include <iostream>
#include <iomanip>
struct json_serializer
{
void operator()(toml::boolean v)
{
std::cout << "{\"type\":\"bool\",\"value\":\"" << toml::value(v) << "\"}";
return ;
}
void operator()(toml::integer v)
{
std::cout << "{\"type\":\"integer\",\"value\":\"" << toml::value(v) << "\"}";
return ;
}
void operator()(toml::floating v)
{
std::cout << "{\"type\":\"float\",\"value\":\"" << toml::value(v) << "\"}";
return ;
}
void operator()(const toml::string& v)
{
// since toml11 automatically convert string to multiline string that is
// valid only in TOML, we need to format the string to make it valid in
// JSON.
std::cout << "{\"type\":\"string\",\"value\":\""
<< this->escape_string(v.str) << "\"}";
return ;
}
void operator()(const toml::local_time& v)
{
std::cout << "{\"type\":\"local_time\",\"value\":\"" << toml::value(v) << "\"}";
return ;
}
void operator()(const toml::local_date& v)
{
std::cout << "{\"type\":\"local_date\",\"value\":\"" << toml::value(v) << "\"}";
return ;
}
void operator()(const toml::local_datetime& v)
{
std::cout << "{\"type\":\"local_datetime\",\"value\":\"" << toml::value(v) << "\"}";
return ;
}
void operator()(const toml::offset_datetime& v)
{
std::cout << "{\"type\":\"datetime\",\"value\":\"" << toml::value(v) << "\"}";
return ;
}
void operator()(const toml::array& v)
{
if(!v.empty() && v.front().is_table())
{
std::cout << '[';
bool is_first = true;
for(const auto& elem : v)
{
if(!is_first) {std::cout << ", ";}
is_first = false;
toml::visit(*this, elem);
}
std::cout << ']';
}
else
{
std::cout << "{\"type\":\"array\",\"value\":[";
bool is_first = true;
for(const auto& elem : v)
{
if(!is_first) {std::cout << ", ";}
is_first = false;
toml::visit(*this, elem);
}
std::cout << "]}";
}
return ;
}
void operator()(const toml::table& v)
{
std::cout << '{';
bool is_first = true;
for(const auto& elem : v)
{
if(!is_first) {std::cout << ", ";}
is_first = false;
std::cout << toml::format(toml::string(elem.first),
std::numeric_limits<std::size_t>::max());
std::cout << ':';
toml::visit(*this, elem.second);
}
std::cout << '}';
return ;
}
std::string escape_string(const std::string& s) const
{
std::string retval;
for(const char c : s)
{
switch(c)
{
case '\\': {retval += "\\\\"; break;}
case '\"': {retval += "\\\""; break;}
case '\b': {retval += "\\b"; break;}
case '\t': {retval += "\\t"; break;}
case '\f': {retval += "\\f"; break;}
case '\n': {retval += "\\n"; break;}
case '\r': {retval += "\\r"; break;}
default : {retval += c; break;}
}
}
return retval;
}
};
int main()
{
try
{
std::vector<char> buf;
std::cin.peek();
while(!std::cin.eof())
{
buf.push_back(std::cin.get());
std::cin.peek();
}
std::string bufstr(buf.begin(), buf.end());
std::istringstream ss(bufstr);
const auto data = toml::parse(ss);
std::cout << std::setprecision(std::numeric_limits<double>::max_digits10);
toml::visit(json_serializer(), data);
return 0;
}
catch(const toml::syntax_error& err)
{
std::cout << "what(): " << err.what() << std::endl;
return 1;
}
}
<commit_msg>fix: enable to deduce what basic_value to be used<commit_after>#include "toml.hpp"
#include <iostream>
#include <iomanip>
struct json_serializer
{
void operator()(toml::boolean v)
{
std::cout << "{\"type\":\"bool\",\"value\":\"" << toml::value(v) << "\"}";
return ;
}
void operator()(toml::integer v)
{
std::cout << "{\"type\":\"integer\",\"value\":\"" << toml::value(v) << "\"}";
return ;
}
void operator()(toml::floating v)
{
std::cout << "{\"type\":\"float\",\"value\":\"" << toml::value(v) << "\"}";
return ;
}
void operator()(const toml::string& v)
{
// since toml11 automatically convert string to multiline string that is
// valid only in TOML, we need to format the string to make it valid in
// JSON.
std::cout << "{\"type\":\"string\",\"value\":\""
<< this->escape_string(v.str) << "\"}";
return ;
}
void operator()(const toml::local_time& v)
{
std::cout << "{\"type\":\"local_time\",\"value\":\"" << toml::value(v) << "\"}";
return ;
}
void operator()(const toml::local_date& v)
{
std::cout << "{\"type\":\"local_date\",\"value\":\"" << toml::value(v) << "\"}";
return ;
}
void operator()(const toml::local_datetime& v)
{
std::cout << "{\"type\":\"local_datetime\",\"value\":\"" << toml::value(v) << "\"}";
return ;
}
void operator()(const toml::offset_datetime& v)
{
std::cout << "{\"type\":\"datetime\",\"value\":\"" << toml::value(v) << "\"}";
return ;
}
void operator()(const toml::array& v)
{
if(!v.empty() && v.front().is_table())
{
std::cout << '[';
bool is_first = true;
for(const auto& elem : v)
{
if(!is_first) {std::cout << ", ";}
is_first = false;
toml::visit(*this, elem);
}
std::cout << ']';
}
else
{
std::cout << "{\"type\":\"array\",\"value\":[";
bool is_first = true;
for(const auto& elem : v)
{
if(!is_first) {std::cout << ", ";}
is_first = false;
toml::visit(*this, elem);
}
std::cout << "]}";
}
return ;
}
void operator()(const toml::table& v)
{
std::cout << '{';
bool is_first = true;
for(const auto& elem : v)
{
if(!is_first) {std::cout << ", ";}
is_first = false;
std::cout << toml::format(toml::value(elem.first),
std::numeric_limits<std::size_t>::max());
std::cout << ':';
toml::visit(*this, elem.second);
}
std::cout << '}';
return ;
}
std::string escape_string(const std::string& s) const
{
std::string retval;
for(const char c : s)
{
switch(c)
{
case '\\': {retval += "\\\\"; break;}
case '\"': {retval += "\\\""; break;}
case '\b': {retval += "\\b"; break;}
case '\t': {retval += "\\t"; break;}
case '\f': {retval += "\\f"; break;}
case '\n': {retval += "\\n"; break;}
case '\r': {retval += "\\r"; break;}
default : {retval += c; break;}
}
}
return retval;
}
};
int main()
{
try
{
std::vector<char> buf;
std::cin.peek();
while(!std::cin.eof())
{
buf.push_back(std::cin.get());
std::cin.peek();
}
std::string bufstr(buf.begin(), buf.end());
std::istringstream ss(bufstr);
const auto data = toml::parse(ss);
std::cout << std::setprecision(std::numeric_limits<double>::max_digits10);
toml::visit(json_serializer(), data);
return 0;
}
catch(const toml::syntax_error& err)
{
std::cout << "what(): " << err.what() << std::endl;
return 1;
}
}
<|endoftext|> |
<commit_before>// Scintilla source code edit control
/** @file LexDMIS.cxx
** Lexer for DMIS.
**/
// Copyright 1998-2005 by Neil Hodgson <neilh@scintilla.org>
// Copyright 2013-2014 by Andreas Tscharner <andy@vis.ethz.ch>
// The License.txt file describes the conditions under which this software may be distributed.
#include <cstdlib>
#include <cassert>
#include <cstring>
#include <cctype>
#include "ILexer.h"
#include "SciLexer.h"
#include "Scintilla.h"
#include "LexerModule.h"
#include "LexAccessor.h"
#include "StyleContext.h"
#include "CharacterSet.h"
#include "WordList.h"
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
static const char *const DMISWordListDesc[] = {
"DMIS Major Words",
"DMIS Minor Words",
"Unsupported DMIS Major Words",
"Unsupported DMIS Minor Words",
"Keywords for code folding start",
"Corresponding keywords for code folding end",
0
};
class LexerDMIS : public ILexer
{
private:
char *m_wordListSets;
WordList m_majorWords;
WordList m_minorWords;
WordList m_unsupportedMajor;
WordList m_unsupportedMinor;
WordList m_codeFoldingStart;
WordList m_codeFoldingEnd;
char * SCI_METHOD UpperCase(char *item);
void SCI_METHOD InitWordListSets(void);
public:
LexerDMIS(void);
virtual ~LexerDMIS(void);
int SCI_METHOD Version() const {
return lvOriginal;
}
void SCI_METHOD Release() {
delete this;
}
const char * SCI_METHOD PropertyNames() {
return NULL;
}
int SCI_METHOD PropertyType(const char *) {
return -1;
}
const char * SCI_METHOD DescribeProperty(const char *) {
return NULL;
}
int SCI_METHOD PropertySet(const char *, const char *) {
return -1;
}
int SCI_METHOD WordListSet(int n, const char *wl);
void * SCI_METHOD PrivateCall(int, void *) {
return NULL;
}
static ILexer *LexerFactoryDMIS() {
return new LexerDMIS;
}
const char * SCI_METHOD DescribeWordListSets();
void SCI_METHOD Lex(unsigned int startPos, int lengthDoc, int initStyle, IDocument *pAccess);
void SCI_METHOD Fold(unsigned int startPos, int lengthDoc, int initStyle, IDocument *pAccess);
};
char * SCI_METHOD LexerDMIS::UpperCase(char *item)
{
char *itemStart;
itemStart = item;
while (item && *item) {
*item = toupper(*item);
item++;
};
return itemStart;
}
void SCI_METHOD LexerDMIS::InitWordListSets(void)
{
size_t totalLen = 0;
for (int i=0; DMISWordListDesc[i]; i++) {
totalLen += strlen(DMISWordListDesc[i]);
totalLen++;
};
totalLen++;
this->m_wordListSets = new char[totalLen];
memset(this->m_wordListSets, 0, totalLen);
for (int i=0; DMISWordListDesc[i]; i++) {
strcat(this->m_wordListSets, DMISWordListDesc[i]);
strcat(this->m_wordListSets, "\n");
};
}
LexerDMIS::LexerDMIS(void) {
this->InitWordListSets();
this->m_majorWords.Clear();
this->m_minorWords.Clear();
this->m_unsupportedMajor.Clear();
this->m_unsupportedMinor.Clear();
this->m_codeFoldingStart.Clear();
this->m_codeFoldingEnd.Clear();
}
LexerDMIS::~LexerDMIS(void) {
delete[] this->m_wordListSets;
}
int SCI_METHOD LexerDMIS::WordListSet(int n, const char *wl)
{
switch (n) {
case 0:
this->m_majorWords.Clear();
this->m_majorWords.Set(wl);
break;
case 1:
this->m_minorWords.Clear();
this->m_minorWords.Set(wl);
break;
case 2:
this->m_unsupportedMajor.Clear();
this->m_unsupportedMajor.Set(wl);
break;
case 3:
this->m_unsupportedMinor.Clear();
this->m_unsupportedMinor.Set(wl);
break;
case 4:
this->m_codeFoldingStart.Clear();
this->m_codeFoldingStart.Set(wl);
break;
case 5:
this->m_codeFoldingEnd.Clear();
this->m_codeFoldingEnd.Set(wl);
break;
default:
return -1;
break;
}
return 0;
}
const char * SCI_METHOD LexerDMIS::DescribeWordListSets()
{
return this->m_wordListSets;
}
void SCI_METHOD LexerDMIS::Lex(unsigned int startPos, int lengthDoc, int initStyle, IDocument *pAccess)
{
const unsigned int MAX_STR_LEN = 100;
LexAccessor styler(pAccess);
StyleContext scCTX(startPos, lengthDoc, initStyle, styler);
CharacterSet setDMISNumber(CharacterSet::setDigits, ".-+eE");
CharacterSet setDMISWordStart(CharacterSet::setAlpha, "-234", 0x80, true);
CharacterSet setDMISWord(CharacterSet::setAlpha);
bool isIFLine = false;
for (; scCTX.More(); scCTX.Forward()) {
if (scCTX.atLineEnd) {
isIFLine = false;
};
switch (scCTX.state) {
case SCE_DMIS_DEFAULT:
if (scCTX.Match('$', '$')) {
scCTX.SetState(SCE_DMIS_COMMENT);
scCTX.Forward();
};
if (scCTX.Match('\'')) {
scCTX.SetState(SCE_DMIS_STRING);
};
if (IsADigit(scCTX.ch) || ((scCTX.Match('-') || scCTX.Match('+')) && IsADigit(scCTX.chNext))) {
scCTX.SetState(SCE_DMIS_NUMBER);
break;
};
if (setDMISWordStart.Contains(scCTX.ch)) {
scCTX.SetState(SCE_DMIS_KEYWORD);
};
if (scCTX.Match('(') && (!isIFLine)) {
scCTX.SetState(SCE_DMIS_LABEL);
};
break;
case SCE_DMIS_COMMENT:
if (scCTX.atLineEnd) {
scCTX.SetState(SCE_DMIS_DEFAULT);
};
break;
case SCE_DMIS_STRING:
if (scCTX.Match('\'')) {
scCTX.SetState(SCE_DMIS_DEFAULT);
};
break;
case SCE_DMIS_NUMBER:
if (!setDMISNumber.Contains(scCTX.ch)) {
scCTX.SetState(SCE_DMIS_DEFAULT);
};
break;
case SCE_DMIS_KEYWORD:
if (!setDMISWord.Contains(scCTX.ch)) {
char tmpStr[MAX_STR_LEN];
memset(tmpStr, 0, MAX_STR_LEN*sizeof(char));
scCTX.GetCurrent(tmpStr, (MAX_STR_LEN-1));
strncpy(tmpStr, this->UpperCase(tmpStr), (MAX_STR_LEN-1));
if (this->m_minorWords.InList(tmpStr)) {
scCTX.ChangeState(SCE_DMIS_MINORWORD);
};
if (this->m_majorWords.InList(tmpStr)) {
isIFLine = (strcmp(tmpStr, "IF") == 0);
scCTX.ChangeState(SCE_DMIS_MAJORWORD);
};
if (this->m_unsupportedMajor.InList(tmpStr)) {
scCTX.ChangeState(SCE_DMIS_UNSUPPORTED_MAJOR);
};
if (this->m_unsupportedMinor.InList(tmpStr)) {
scCTX.ChangeState(SCE_DMIS_UNSUPPORTED_MINOR);
};
if (scCTX.Match('(') && (isIFLine)) {
scCTX.SetState(SCE_DMIS_LABEL);
} else {
scCTX.SetState(SCE_DMIS_DEFAULT);
};
};
break;
case SCE_DMIS_LABEL:
if (scCTX.Match(')')) {
scCTX.SetState(SCE_DMIS_DEFAULT);
};
break;
};
};
scCTX.Complete();
}
void SCI_METHOD LexerDMIS::Fold(unsigned int startPos, int lengthDoc, int, IDocument *pAccess)
{
const int MAX_STR_LEN = 100;
LexAccessor styler(pAccess);
unsigned int endPos = startPos + lengthDoc;
char chNext = styler[startPos];
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
int strPos = 0;
bool foldWordPossible = false;
CharacterSet setDMISFoldWord(CharacterSet::setAlpha);
char *tmpStr;
tmpStr = new char[MAX_STR_LEN];
memset(tmpStr, 0, MAX_STR_LEN*sizeof(char));
for (unsigned int i=startPos; i<endPos; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i+1);
bool atEOL = ((ch == '\r' && chNext != '\n') || (ch == '\n'));
if (strPos >= (MAX_STR_LEN-1)) {
strPos = MAX_STR_LEN-1;
};
int style = styler.StyleAt(i);
bool noFoldPos = ((style == SCE_DMIS_COMMENT) || (style == SCE_DMIS_STRING));
if (foldWordPossible) {
if (setDMISFoldWord.Contains(ch)) {
tmpStr[strPos++] = ch;
} else {
tmpStr = this->UpperCase(tmpStr);
if (this->m_codeFoldingStart.InList(tmpStr) && (!noFoldPos)) {
levelCurrent++;
};
if (this->m_codeFoldingEnd.InList(tmpStr) && (!noFoldPos)) {
levelCurrent--;
};
memset(tmpStr, 0, MAX_STR_LEN*sizeof(char));
strPos = 0;
foldWordPossible = false;
};
} else {
if (setDMISFoldWord.Contains(ch)) {
tmpStr[strPos++] = ch;
foldWordPossible = true;
};
};
if (atEOL || (i == (endPos-1))) {
int lev = levelPrev;
if (levelCurrent > levelPrev) {
lev |= SC_FOLDLEVELHEADERFLAG;
};
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
};
lineCurrent++;
levelPrev = levelCurrent;
};
};
delete[] tmpStr;
}
LexerModule lmDMIS(SCLEX_DMIS, LexerDMIS::LexerFactoryDMIS, "DMIS", DMISWordListDesc);
<commit_msg>Add missing not sign to fix DMIS label highlighting<commit_after>// Scintilla source code edit control
/** @file LexDMIS.cxx
** Lexer for DMIS.
**/
// Copyright 1998-2005 by Neil Hodgson <neilh@scintilla.org>
// Copyright 2013-2014 by Andreas Tscharner <andy@vis.ethz.ch>
// The License.txt file describes the conditions under which this software may be distributed.
#include <cstdlib>
#include <cassert>
#include <cstring>
#include <cctype>
#include "ILexer.h"
#include "SciLexer.h"
#include "Scintilla.h"
#include "LexerModule.h"
#include "LexAccessor.h"
#include "StyleContext.h"
#include "CharacterSet.h"
#include "WordList.h"
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
static const char *const DMISWordListDesc[] = {
"DMIS Major Words",
"DMIS Minor Words",
"Unsupported DMIS Major Words",
"Unsupported DMIS Minor Words",
"Keywords for code folding start",
"Corresponding keywords for code folding end",
0
};
class LexerDMIS : public ILexer
{
private:
char *m_wordListSets;
WordList m_majorWords;
WordList m_minorWords;
WordList m_unsupportedMajor;
WordList m_unsupportedMinor;
WordList m_codeFoldingStart;
WordList m_codeFoldingEnd;
char * SCI_METHOD UpperCase(char *item);
void SCI_METHOD InitWordListSets(void);
public:
LexerDMIS(void);
virtual ~LexerDMIS(void);
int SCI_METHOD Version() const {
return lvOriginal;
}
void SCI_METHOD Release() {
delete this;
}
const char * SCI_METHOD PropertyNames() {
return NULL;
}
int SCI_METHOD PropertyType(const char *) {
return -1;
}
const char * SCI_METHOD DescribeProperty(const char *) {
return NULL;
}
int SCI_METHOD PropertySet(const char *, const char *) {
return -1;
}
int SCI_METHOD WordListSet(int n, const char *wl);
void * SCI_METHOD PrivateCall(int, void *) {
return NULL;
}
static ILexer *LexerFactoryDMIS() {
return new LexerDMIS;
}
const char * SCI_METHOD DescribeWordListSets();
void SCI_METHOD Lex(unsigned int startPos, int lengthDoc, int initStyle, IDocument *pAccess);
void SCI_METHOD Fold(unsigned int startPos, int lengthDoc, int initStyle, IDocument *pAccess);
};
char * SCI_METHOD LexerDMIS::UpperCase(char *item)
{
char *itemStart;
itemStart = item;
while (item && *item) {
*item = toupper(*item);
item++;
};
return itemStart;
}
void SCI_METHOD LexerDMIS::InitWordListSets(void)
{
size_t totalLen = 0;
for (int i=0; DMISWordListDesc[i]; i++) {
totalLen += strlen(DMISWordListDesc[i]);
totalLen++;
};
totalLen++;
this->m_wordListSets = new char[totalLen];
memset(this->m_wordListSets, 0, totalLen);
for (int i=0; DMISWordListDesc[i]; i++) {
strcat(this->m_wordListSets, DMISWordListDesc[i]);
strcat(this->m_wordListSets, "\n");
};
}
LexerDMIS::LexerDMIS(void) {
this->InitWordListSets();
this->m_majorWords.Clear();
this->m_minorWords.Clear();
this->m_unsupportedMajor.Clear();
this->m_unsupportedMinor.Clear();
this->m_codeFoldingStart.Clear();
this->m_codeFoldingEnd.Clear();
}
LexerDMIS::~LexerDMIS(void) {
delete[] this->m_wordListSets;
}
int SCI_METHOD LexerDMIS::WordListSet(int n, const char *wl)
{
switch (n) {
case 0:
this->m_majorWords.Clear();
this->m_majorWords.Set(wl);
break;
case 1:
this->m_minorWords.Clear();
this->m_minorWords.Set(wl);
break;
case 2:
this->m_unsupportedMajor.Clear();
this->m_unsupportedMajor.Set(wl);
break;
case 3:
this->m_unsupportedMinor.Clear();
this->m_unsupportedMinor.Set(wl);
break;
case 4:
this->m_codeFoldingStart.Clear();
this->m_codeFoldingStart.Set(wl);
break;
case 5:
this->m_codeFoldingEnd.Clear();
this->m_codeFoldingEnd.Set(wl);
break;
default:
return -1;
break;
}
return 0;
}
const char * SCI_METHOD LexerDMIS::DescribeWordListSets()
{
return this->m_wordListSets;
}
void SCI_METHOD LexerDMIS::Lex(unsigned int startPos, int lengthDoc, int initStyle, IDocument *pAccess)
{
const unsigned int MAX_STR_LEN = 100;
LexAccessor styler(pAccess);
StyleContext scCTX(startPos, lengthDoc, initStyle, styler);
CharacterSet setDMISNumber(CharacterSet::setDigits, ".-+eE");
CharacterSet setDMISWordStart(CharacterSet::setAlpha, "-234", 0x80, true);
CharacterSet setDMISWord(CharacterSet::setAlpha);
bool isIFLine = false;
for (; scCTX.More(); scCTX.Forward()) {
if (scCTX.atLineEnd) {
isIFLine = false;
};
switch (scCTX.state) {
case SCE_DMIS_DEFAULT:
if (scCTX.Match('$', '$')) {
scCTX.SetState(SCE_DMIS_COMMENT);
scCTX.Forward();
};
if (scCTX.Match('\'')) {
scCTX.SetState(SCE_DMIS_STRING);
};
if (IsADigit(scCTX.ch) || ((scCTX.Match('-') || scCTX.Match('+')) && IsADigit(scCTX.chNext))) {
scCTX.SetState(SCE_DMIS_NUMBER);
break;
};
if (setDMISWordStart.Contains(scCTX.ch)) {
scCTX.SetState(SCE_DMIS_KEYWORD);
};
if (scCTX.Match('(') && (!isIFLine)) {
scCTX.SetState(SCE_DMIS_LABEL);
};
break;
case SCE_DMIS_COMMENT:
if (scCTX.atLineEnd) {
scCTX.SetState(SCE_DMIS_DEFAULT);
};
break;
case SCE_DMIS_STRING:
if (scCTX.Match('\'')) {
scCTX.SetState(SCE_DMIS_DEFAULT);
};
break;
case SCE_DMIS_NUMBER:
if (!setDMISNumber.Contains(scCTX.ch)) {
scCTX.SetState(SCE_DMIS_DEFAULT);
};
break;
case SCE_DMIS_KEYWORD:
if (!setDMISWord.Contains(scCTX.ch)) {
char tmpStr[MAX_STR_LEN];
memset(tmpStr, 0, MAX_STR_LEN*sizeof(char));
scCTX.GetCurrent(tmpStr, (MAX_STR_LEN-1));
strncpy(tmpStr, this->UpperCase(tmpStr), (MAX_STR_LEN-1));
if (this->m_minorWords.InList(tmpStr)) {
scCTX.ChangeState(SCE_DMIS_MINORWORD);
};
if (this->m_majorWords.InList(tmpStr)) {
isIFLine = (strcmp(tmpStr, "IF") == 0);
scCTX.ChangeState(SCE_DMIS_MAJORWORD);
};
if (this->m_unsupportedMajor.InList(tmpStr)) {
scCTX.ChangeState(SCE_DMIS_UNSUPPORTED_MAJOR);
};
if (this->m_unsupportedMinor.InList(tmpStr)) {
scCTX.ChangeState(SCE_DMIS_UNSUPPORTED_MINOR);
};
if (scCTX.Match('(') && (!isIFLine)) {
scCTX.SetState(SCE_DMIS_LABEL);
} else {
scCTX.SetState(SCE_DMIS_DEFAULT);
};
};
break;
case SCE_DMIS_LABEL:
if (scCTX.Match(')')) {
scCTX.SetState(SCE_DMIS_DEFAULT);
};
break;
};
};
scCTX.Complete();
}
void SCI_METHOD LexerDMIS::Fold(unsigned int startPos, int lengthDoc, int, IDocument *pAccess)
{
const int MAX_STR_LEN = 100;
LexAccessor styler(pAccess);
unsigned int endPos = startPos + lengthDoc;
char chNext = styler[startPos];
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
int strPos = 0;
bool foldWordPossible = false;
CharacterSet setDMISFoldWord(CharacterSet::setAlpha);
char *tmpStr;
tmpStr = new char[MAX_STR_LEN];
memset(tmpStr, 0, MAX_STR_LEN*sizeof(char));
for (unsigned int i=startPos; i<endPos; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i+1);
bool atEOL = ((ch == '\r' && chNext != '\n') || (ch == '\n'));
if (strPos >= (MAX_STR_LEN-1)) {
strPos = MAX_STR_LEN-1;
};
int style = styler.StyleAt(i);
bool noFoldPos = ((style == SCE_DMIS_COMMENT) || (style == SCE_DMIS_STRING));
if (foldWordPossible) {
if (setDMISFoldWord.Contains(ch)) {
tmpStr[strPos++] = ch;
} else {
tmpStr = this->UpperCase(tmpStr);
if (this->m_codeFoldingStart.InList(tmpStr) && (!noFoldPos)) {
levelCurrent++;
};
if (this->m_codeFoldingEnd.InList(tmpStr) && (!noFoldPos)) {
levelCurrent--;
};
memset(tmpStr, 0, MAX_STR_LEN*sizeof(char));
strPos = 0;
foldWordPossible = false;
};
} else {
if (setDMISFoldWord.Contains(ch)) {
tmpStr[strPos++] = ch;
foldWordPossible = true;
};
};
if (atEOL || (i == (endPos-1))) {
int lev = levelPrev;
if (levelCurrent > levelPrev) {
lev |= SC_FOLDLEVELHEADERFLAG;
};
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
};
lineCurrent++;
levelPrev = levelCurrent;
};
};
delete[] tmpStr;
}
LexerModule lmDMIS(SCLEX_DMIS, LexerDMIS::LexerFactoryDMIS, "DMIS", DMISWordListDesc);
<|endoftext|> |
<commit_before>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <iostream>
#include <sstream>
#include <assert.h>
#include <zorba/zorba.h>
#include <zorba/external_module.h>
#include <zorba/iterator.h>
#include <zorba/item_sequence.h>
#include <zorba/function.h>
#include <zorba/serialization_callback.h>
#include <zorba/store_manager.h>
#include <zorba/zorba_exception.h>
#include <zorba/internal/unique_ptr.h>
using namespace zorba;
bool
execution_plan_example_1(Zorba* aZorba)
{
// the stringstream used for query materialization
std::stringstream lExecutionPlan;
// materialize a compiled query to a binary format
{
XQuery_t lQuery = aZorba->compileQuery("1+2");
lQuery->saveExecutionPlan(lExecutionPlan);
std::cout << lQuery << std::endl;
}
// read a compiled query from an input stream
// and execute it
{
XQuery_t lQuery = aZorba->createQuery();
lQuery->loadExecutionPlan(lExecutionPlan);
std::cout << lQuery << std::endl;
}
return true;
}
class MySerializableExternalFunction : public NonContextualExternalFunction
{
protected:
const ExternalModule* theModule;
public:
MySerializableExternalFunction(const ExternalModule* aModule)
: theModule(aModule) {}
virtual String
getURI() const { return theModule->getURI(); }
virtual String
getLocalName() const { return "bar1"; }
virtual ItemSequence_t
evaluate(const ExternalFunction::Arguments_t& args) const
{
iv_t vec;
for(int i = 0; i < 2; ++i) {
Item lItem;
Iterator_t iter = args[i]->getIterator();
iter->open();
while(iter->next(lItem)) {
vec.push_back(lItem);
}
iter->close();
}
// transfer ownership of the IteratorBackedItemSequence to Zorba (using a unique_ptr)
return ItemSequence_t(new IteratorBackedItemSequence(vec));
}
private:
typedef std::vector<Item> iv_t;
typedef iv_t::iterator ii_t;
class IteratorBackedItemSequence : public ItemSequence {
class InternalIterator : public Iterator
{
private:
IteratorBackedItemSequence *theItemSequence;
ii_t m_i;
ii_t m_end;
bool is_open;
public:
InternalIterator(IteratorBackedItemSequence *item_sequence) : theItemSequence(item_sequence), is_open(false)
{
}
virtual void open()
{
m_i = theItemSequence->m_vec.begin();
m_end = theItemSequence->m_vec.end();
is_open = true;
}
virtual void close()
{
is_open = false;
}
virtual bool isOpen() const
{
return is_open;
}
bool next(Item& val)
{
assert(is_open);
if (m_i == m_end) {
return false;
}
val = *m_i;
++m_i;
return true;
}
};
public:
IteratorBackedItemSequence(iv_t& vec)
: m_vec(vec)
{ }
Iterator_t getIterator() {return new InternalIterator(this);}
private:
iv_t m_vec;
};
};
class MySerializableExternalModule : public ExternalModule
{
protected:
MySerializableExternalFunction* bar1;
public:
MySerializableExternalModule()
: bar1(0) {}
virtual ~MySerializableExternalModule()
{
delete bar1;
}
virtual String
getURI() const { return "urn:foo"; }
virtual ExternalFunction*
getExternalFunction(const String& aLocalname)
{
if (aLocalname == "bar1") {
if (!bar1) {
bar1 = new MySerializableExternalFunction(this);
}
return bar1;
}
return 0;
}
};
class MySerializationCallback : public SerializationCallback
{
protected:
ExternalModule* theModule;
public:
MySerializationCallback(ExternalModule* aModule)
: theModule(aModule) {}
ExternalModule*
getExternalModule(const String& aURI) const { return theModule; }
};
bool
execution_plan_example_2(Zorba* aZorba)
{
// the stringstream used for query materialization
std::stringstream lExecutionPlan;
MySerializableExternalModule lModule;
{
// materialize a compiled query to a binary format
StaticContext_t sctx = aZorba->createStaticContext();
sctx->registerModule(&lModule);
std::ostringstream lText;
lText << "declare namespace foo=\"urn:foo\";" << std::endl
<< "declare function foo:bar1($a1, $a2) external;" << std::endl
<< "foo:bar1((1,2,3), (4,5,6))" << std::endl;
XQuery_t lQuery = aZorba->compileQuery(lText.str(), sctx);
lQuery->saveExecutionPlan(lExecutionPlan);
std::cout << lQuery << std::endl;
}
// read a compiled query from an input stream
// and execute it
{
MySerializationCallback lCallback(&lModule);
XQuery_t lQuery = aZorba->createQuery();
lQuery->loadExecutionPlan(lExecutionPlan, &lCallback);
std::cout << lQuery << std::endl;
}
return true;
}
bool
execution_plan_example_3(Zorba* aZorba)
{
// the stringstream used for query materialization
std::stringstream lExecutionPlan;
{
MySerializableExternalModule lModule;
// materialize a compiled query to a binary format
StaticContext_t sctx = aZorba->createStaticContext();
sctx->registerModule(&lModule);
std::ostringstream lText;
lText << "declare namespace foo=\"urn:foo\";" << std::endl
<< "declare function foo:bar1($a1, $a2) external;" << std::endl
<< "foo:bar1((1,2,3), (4,5,6))" << std::endl;
XQuery_t lQuery = aZorba->compileQuery(lText.str(), sctx);
lQuery->saveExecutionPlan(lExecutionPlan);
std::cout << lQuery << std::endl;
}
// read a compiled query from an input stream
// but forgot to register a SerializationCallback
try {
XQuery_t lQuery = aZorba->createQuery();
lQuery->loadExecutionPlan(lExecutionPlan);
std::cout << lQuery << std::endl;
} catch (ZorbaException &e) {
std::cerr << e << std::endl;
return true;
}
return false;
}
int
execution_plans(int argc, char* argv[])
{
void* lStore = zorba::StoreManager::getStore();
Zorba *lZorba = Zorba::getInstance(lStore);
bool res = false;
std::cout << "executing example 1" << std::endl;
res = execution_plan_example_1(lZorba);
if (!res) return 1;
std::cout << std::endl;
std::cout << "executing example 2" << std::endl;
res = execution_plan_example_2(lZorba);
if (!res) return 2;
std::cout << std::endl;
std::cout << "executing example 3" << std::endl;
res = execution_plan_example_3(lZorba);
if (!res) return 3;
std::cout << std::endl;
lZorba->shutdown();
zorba::StoreManager::shutdownStore(lStore);
return 0;
}
<commit_msg>Added test<commit_after>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <iostream>
#include <sstream>
#include <assert.h>
#include <zorba/zorba.h>
#include <zorba/external_module.h>
#include <zorba/iterator.h>
#include <zorba/item_sequence.h>
#include <zorba/function.h>
#include <zorba/serialization_callback.h>
#include <zorba/store_manager.h>
#include <zorba/zorba_exception.h>
#include <zorba/internal/unique_ptr.h>
using namespace zorba;
bool
execution_plan_example_1(Zorba* aZorba)
{
// the stringstream used for query materialization
std::stringstream lExecutionPlan;
// materialize a compiled query to a binary format
{
XQuery_t lQuery = aZorba->compileQuery("1+2");
lQuery->saveExecutionPlan(lExecutionPlan);
std::cout << lQuery << std::endl;
}
// read a compiled query from an input stream
// and execute it
{
XQuery_t lQuery = aZorba->createQuery();
lQuery->loadExecutionPlan(lExecutionPlan);
std::cout << lQuery << std::endl;
}
return true;
}
class MySerializableExternalFunction : public NonContextualExternalFunction
{
protected:
const ExternalModule* theModule;
public:
MySerializableExternalFunction(const ExternalModule* aModule)
: theModule(aModule) {}
virtual String
getURI() const { return theModule->getURI(); }
virtual String
getLocalName() const { return "bar1"; }
virtual ItemSequence_t
evaluate(const ExternalFunction::Arguments_t& args) const
{
iv_t vec;
for(int i = 0; i < 2; ++i) {
Item lItem;
Iterator_t iter = args[i]->getIterator();
iter->open();
while(iter->next(lItem)) {
vec.push_back(lItem);
}
iter->close();
}
// transfer ownership of the IteratorBackedItemSequence to Zorba (using a unique_ptr)
return ItemSequence_t(new IteratorBackedItemSequence(vec));
}
private:
typedef std::vector<Item> iv_t;
typedef iv_t::iterator ii_t;
class IteratorBackedItemSequence : public ItemSequence {
class InternalIterator : public Iterator
{
private:
IteratorBackedItemSequence *theItemSequence;
ii_t m_i;
ii_t m_end;
bool is_open;
public:
InternalIterator(IteratorBackedItemSequence *item_sequence) : theItemSequence(item_sequence), is_open(false)
{
}
virtual void open()
{
m_i = theItemSequence->m_vec.begin();
m_end = theItemSequence->m_vec.end();
is_open = true;
}
virtual void close()
{
is_open = false;
}
virtual bool isOpen() const
{
return is_open;
}
bool next(Item& val)
{
assert(is_open);
if (m_i == m_end) {
return false;
}
val = *m_i;
++m_i;
return true;
}
};
public:
IteratorBackedItemSequence(iv_t& vec)
: m_vec(vec)
{ }
Iterator_t getIterator() {return new InternalIterator(this);}
private:
iv_t m_vec;
};
};
class MySerializableExternalModule : public ExternalModule
{
protected:
MySerializableExternalFunction* bar1;
public:
MySerializableExternalModule()
: bar1(0) {}
virtual ~MySerializableExternalModule()
{
delete bar1;
}
virtual String
getURI() const { return "urn:foo"; }
virtual ExternalFunction*
getExternalFunction(const String& aLocalname)
{
if (aLocalname == "bar1") {
if (!bar1) {
bar1 = new MySerializableExternalFunction(this);
}
return bar1;
}
return 0;
}
};
class MySerializationCallback : public SerializationCallback
{
protected:
ExternalModule* theModule;
public:
MySerializationCallback(ExternalModule* aModule)
: theModule(aModule) {}
ExternalModule*
getExternalModule(const String& aURI) const { return theModule; }
};
bool
execution_plan_example_2(Zorba* aZorba)
{
// the stringstream used for query materialization
std::stringstream lExecutionPlan;
MySerializableExternalModule lModule;
{
// materialize a compiled query to a binary format
StaticContext_t sctx = aZorba->createStaticContext();
sctx->registerModule(&lModule);
std::ostringstream lText;
lText << "declare namespace foo=\"urn:foo\";" << std::endl
<< "declare function foo:bar1($a1, $a2) external;" << std::endl
<< "foo:bar1((1,2,3), (4,5,6))" << std::endl;
XQuery_t lQuery = aZorba->compileQuery(lText.str(), sctx);
lQuery->saveExecutionPlan(lExecutionPlan);
std::cout << lQuery << std::endl;
}
// read a compiled query from an input stream
// and execute it
{
MySerializationCallback lCallback(&lModule);
XQuery_t lQuery = aZorba->createQuery();
lQuery->loadExecutionPlan(lExecutionPlan, &lCallback);
std::cout << lQuery << std::endl;
}
return true;
}
bool
execution_plan_example_3(Zorba* aZorba)
{
// the stringstream used for query materialization
std::stringstream lExecutionPlan;
{
MySerializableExternalModule lModule;
// materialize a compiled query to a binary format
StaticContext_t sctx = aZorba->createStaticContext();
sctx->registerModule(&lModule);
std::ostringstream lText;
lText << "declare namespace foo=\"urn:foo\";" << std::endl
<< "declare function foo:bar1($a1, $a2) external;" << std::endl
<< "foo:bar1((1,2,3), (4,5,6))" << std::endl;
XQuery_t lQuery = aZorba->compileQuery(lText.str(), sctx);
lQuery->saveExecutionPlan(lExecutionPlan);
std::cout << lQuery << std::endl;
}
// read a compiled query from an input stream
// but forgot to register a SerializationCallback
try {
XQuery_t lQuery = aZorba->createQuery();
lQuery->loadExecutionPlan(lExecutionPlan);
std::cout << lQuery << std::endl;
} catch (ZorbaException &e) {
std::cerr << e << std::endl;
return true;
}
return false;
}
bool
execution_plan_example_4(Zorba* aZorba)
{
StaticContext_t lContext = aZorba->createStaticContext();
Zorba_CompilerHints_t lHints;
std::stringstream lPredeclaredModules;
lPredeclaredModules
<< "import module namespace libjn = "
<< "'http://jsoniq.org/function-library';"
<< std::endl;
lContext->loadProlog(lPredeclaredModules.str(), lHints);
std::vector<zorba::String> lDefaultNS;
lDefaultNS.push_back("http://jsoniq.org/functions");
lContext->setDefaultFunctionNamespaces(lDefaultNS);
// the stringstream used for query materialization
std::stringstream lExecutionPlan;
// materialize a compiled query to a binary format
{
XQuery_t lQuery = aZorba->compileQuery("jn:encode-for-roundtrip(xs:dateTime('2014-05-21T00:00:01'))", lContext);
lQuery->saveExecutionPlan(lExecutionPlan);
std::cout << lQuery << std::endl;
}
// read a compiled query from an input stream
// and execute it
{
XQuery_t lQuery = aZorba->createQuery();
lQuery->loadExecutionPlan(lExecutionPlan);
std::cout << lQuery << std::endl;
}
return true;
}
int
execution_plans(int argc, char* argv[])
{
void* lStore = zorba::StoreManager::getStore();
Zorba *lZorba = Zorba::getInstance(lStore);
bool res = false;
std::cout << "executing example 1" << std::endl;
res = execution_plan_example_1(lZorba);
if (!res) return 1;
std::cout << std::endl;
std::cout << "executing example 2" << std::endl;
res = execution_plan_example_2(lZorba);
if (!res) return 2;
std::cout << std::endl;
std::cout << "executing example 3" << std::endl;
res = execution_plan_example_3(lZorba);
if (!res) return 3;
std::cout << std::endl;
std::cout << "executing example 4" << std::endl;
res = execution_plan_example_4(lZorba);
if (!res) return 4;
std::cout << std::endl;
lZorba->shutdown();
zorba::StoreManager::shutdownStore(lStore);
return 0;
}
<|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 "gfx/canvas_skia.h"
#include <cairo/cairo.h>
#include <gtk/gtk.h>
#include <pango/pango.h>
#include <pango/pangocairo.h>
#include "base/logging.h"
#include "base/utf_string_conversions.h"
#include "gfx/font.h"
#include "gfx/gtk_util.h"
#include "gfx/rect.h"
namespace {
const gunichar kAcceleratorChar = '&';
// Font settings that we initialize once and then use when drawing text in
// DrawStringInt().
static cairo_font_options_t* cairo_font_options = NULL;
// Update |cairo_font_options| based on GtkSettings, allocating it if needed.
static void UpdateCairoFontOptions() {
if (!cairo_font_options)
cairo_font_options = cairo_font_options_create();
GtkSettings* gtk_settings = gtk_settings_get_default();
gint antialias = 0;
gint hinting = 0;
gchar* hint_style = NULL;
gchar* rgba_style = NULL;
g_object_get(gtk_settings,
"gtk-xft-antialias", &antialias,
"gtk-xft-hinting", &hinting,
"gtk-xft-hintstyle", &hint_style,
"gtk-xft-rgba", &rgba_style,
NULL);
// g_object_get() doesn't tell us whether the properties were present or not,
// but if they aren't (because gnome-settings-daemon isn't running), we'll get
// NULL values for the strings.
if (hint_style && rgba_style) {
if (!antialias) {
cairo_font_options_set_antialias(cairo_font_options,
CAIRO_ANTIALIAS_NONE);
} else if (strcmp(rgba_style, "none") == 0) {
cairo_font_options_set_antialias(cairo_font_options,
CAIRO_ANTIALIAS_GRAY);
} else {
cairo_font_options_set_antialias(cairo_font_options,
CAIRO_ANTIALIAS_SUBPIXEL);
cairo_subpixel_order_t cairo_subpixel_order =
CAIRO_SUBPIXEL_ORDER_DEFAULT;
if (strcmp(rgba_style, "rgb") == 0) {
cairo_subpixel_order = CAIRO_SUBPIXEL_ORDER_RGB;
} else if (strcmp(rgba_style, "bgr") == 0) {
cairo_subpixel_order = CAIRO_SUBPIXEL_ORDER_BGR;
} else if (strcmp(rgba_style, "vrgb") == 0) {
cairo_subpixel_order = CAIRO_SUBPIXEL_ORDER_VRGB;
} else if (strcmp(rgba_style, "vbgr") == 0) {
cairo_subpixel_order = CAIRO_SUBPIXEL_ORDER_VBGR;
}
cairo_font_options_set_subpixel_order(cairo_font_options,
cairo_subpixel_order);
}
cairo_hint_style_t cairo_hint_style = CAIRO_HINT_STYLE_DEFAULT;
if (hinting == 0 || strcmp(hint_style, "hintnone") == 0) {
cairo_hint_style = CAIRO_HINT_STYLE_NONE;
} else if (strcmp(hint_style, "hintslight") == 0) {
cairo_hint_style = CAIRO_HINT_STYLE_SLIGHT;
} else if (strcmp(hint_style, "hintmedium") == 0) {
cairo_hint_style = CAIRO_HINT_STYLE_MEDIUM;
} else if (strcmp(hint_style, "hintfull") == 0) {
cairo_hint_style = CAIRO_HINT_STYLE_FULL;
}
cairo_font_options_set_hint_style(cairo_font_options, cairo_hint_style);
}
if (hint_style)
g_free(hint_style);
if (rgba_style)
g_free(rgba_style);
}
} // namespace
namespace gfx {
CanvasSkia::CanvasSkia(int width, int height, bool is_opaque)
: skia::PlatformCanvas(width, height, is_opaque) {
}
CanvasSkia::CanvasSkia() : skia::PlatformCanvas() {
}
CanvasSkia::~CanvasSkia() {
}
// Pass a width > 0 to force wrapping and elliding.
static void SetupPangoLayout(PangoLayout* layout,
const std::wstring& text,
const gfx::Font& font,
int width,
int flags) {
if (!cairo_font_options)
UpdateCairoFontOptions();
// This needs to be done early on; it has no effect when called just before
// pango_cairo_show_layout().
pango_cairo_context_set_font_options(
pango_layout_get_context(layout), cairo_font_options);
// Callers of DrawStringInt handle RTL layout themselves, so tell pango to not
// scope out RTL characters.
pango_layout_set_auto_dir(layout, FALSE);
if (width > 0)
pango_layout_set_width(layout, width * PANGO_SCALE);
if (flags & Canvas::NO_ELLIPSIS) {
pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_NONE);
} else {
pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_END);
}
if (flags & Canvas::TEXT_ALIGN_CENTER) {
pango_layout_set_alignment(layout, PANGO_ALIGN_CENTER);
} else if (flags & Canvas::TEXT_ALIGN_RIGHT) {
pango_layout_set_alignment(layout, PANGO_ALIGN_RIGHT);
}
if (flags & Canvas::MULTI_LINE) {
pango_layout_set_wrap(layout,
(flags & Canvas::CHARACTER_BREAK) ?
PANGO_WRAP_WORD_CHAR : PANGO_WRAP_WORD);
}
// Set the resolution to match that used by Gtk. If we don't set the
// resolution and the resolution differs from the default, Gtk and Chrome end
// up drawing at different sizes.
double resolution = gfx::GetPangoResolution();
if (resolution > 0) {
pango_cairo_context_set_resolution(pango_layout_get_context(layout),
resolution);
}
PangoFontDescription* desc = gfx::Font::PangoFontFromGfxFont(font);
pango_layout_set_font_description(layout, desc);
pango_font_description_free(desc);
// Set text and accelerator character if needed.
std::string utf8 = WideToUTF8(text);
if (flags & gfx::Canvas::HIDE_PREFIX) {
// Escape the text string to be used as markup.
gchar* escaped_text = g_markup_escape_text(utf8.c_str(), utf8.size());
pango_layout_set_markup_with_accel(layout,
escaped_text,
strlen(escaped_text),
kAcceleratorChar, NULL);
g_free(escaped_text);
} else {
pango_layout_set_text(layout, utf8.data(), utf8.size());
}
}
// static
void CanvasSkia::SizeStringInt(const std::wstring& text,
const gfx::Font& font,
int* width, int* height, int flags) {
int org_width = *width;
cairo_surface_t* surface =
cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 0, 0);
cairo_t* cr = cairo_create(surface);
PangoLayout* layout = pango_cairo_create_layout(cr);
SetupPangoLayout(layout, text, font, *width, flags);
pango_layout_get_pixel_size(layout, width, height);
if (org_width > 0 && flags & Canvas::MULTI_LINE &&
pango_layout_is_wrapped(layout)) {
// The text wrapped. There seems to be a bug in Pango when this happens
// such that the width returned from pango_layout_get_pixel_size is too
// small. Using the width from pango_layout_get_pixel_size in this case
// results in wrapping across more lines, which requires a bigger height.
// As a workaround we use the original width, which is not necessarily
// exactly correct, but isn't wrong by much.
//
// It looks like Pango uses the size of whitespace in calculating wrapping
// but doesn't include the size of the whitespace when the extents are
// asked for. See the loop in pango-layout.c process_item that determines
// where to wrap.
*width = org_width;
}
g_object_unref(layout);
cairo_destroy(cr);
cairo_surface_destroy(surface);
}
void CanvasSkia::DrawStringInt(const std::wstring& text,
const gfx::Font& font,
const SkColor& color,
int x, int y, int w, int h,
int flags) {
if (w <= 0 || h <= 0)
return;
cairo_t* cr = beginPlatformPaint();
PangoLayout* layout = pango_cairo_create_layout(cr);
SetupPangoLayout(layout, text, font, w, flags);
pango_layout_set_height(layout, h * PANGO_SCALE);
cairo_save(cr);
cairo_set_source_rgba(cr,
SkColorGetR(color) / 255.0,
SkColorGetG(color) / 255.0,
SkColorGetB(color) / 255.0,
SkColorGetA(color) / 255.0);
int width, height;
pango_layout_get_pixel_size(layout, &width, &height);
cairo_rectangle(cr, x, y, w, h);
cairo_clip(cr);
if (flags & Canvas::TEXT_VALIGN_TOP) {
// Cairo should draw from the top left corner already.
} else if (flags & Canvas::TEXT_VALIGN_BOTTOM) {
y += (h - height);
} else {
// Vertically centered.
y += ((h - height) / 2);
}
cairo_move_to(cr, x, y);
pango_cairo_show_layout(cr, layout);
if (font.style() & gfx::Font::UNDERLINED) {
double underline_y =
static_cast<double>(y) + height + font.underline_position();
cairo_set_line_width(cr, font.underline_thickness());
cairo_move_to(cr, x, underline_y);
cairo_line_to(cr, x + width, underline_y);
cairo_stroke(cr);
}
cairo_restore(cr);
g_object_unref(layout);
// NOTE: beginPlatformPaint returned its surface, we shouldn't destroy it.
}
void CanvasSkia::DrawGdkPixbuf(GdkPixbuf* pixbuf, int x, int y) {
if (!pixbuf) {
NOTREACHED();
return;
}
cairo_t* cr = beginPlatformPaint();
gdk_cairo_set_source_pixbuf(cr, pixbuf, x, y);
cairo_paint(cr);
}
} // namespace gfx
<commit_msg>Fixes bug in showing accelerators where on views/gtk where we would incorrectly show the ampersand character in some situations, and in others show the underline when we shouldn't have.<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 "gfx/canvas_skia.h"
#include <cairo/cairo.h>
#include <gtk/gtk.h>
#include <pango/pango.h>
#include <pango/pangocairo.h>
#include "base/logging.h"
#include "base/utf_string_conversions.h"
#include "gfx/font.h"
#include "gfx/gtk_util.h"
#include "gfx/rect.h"
namespace {
const gunichar kAcceleratorChar = '&';
// Font settings that we initialize once and then use when drawing text in
// DrawStringInt().
static cairo_font_options_t* cairo_font_options = NULL;
// Update |cairo_font_options| based on GtkSettings, allocating it if needed.
static void UpdateCairoFontOptions() {
if (!cairo_font_options)
cairo_font_options = cairo_font_options_create();
GtkSettings* gtk_settings = gtk_settings_get_default();
gint antialias = 0;
gint hinting = 0;
gchar* hint_style = NULL;
gchar* rgba_style = NULL;
g_object_get(gtk_settings,
"gtk-xft-antialias", &antialias,
"gtk-xft-hinting", &hinting,
"gtk-xft-hintstyle", &hint_style,
"gtk-xft-rgba", &rgba_style,
NULL);
// g_object_get() doesn't tell us whether the properties were present or not,
// but if they aren't (because gnome-settings-daemon isn't running), we'll get
// NULL values for the strings.
if (hint_style && rgba_style) {
if (!antialias) {
cairo_font_options_set_antialias(cairo_font_options,
CAIRO_ANTIALIAS_NONE);
} else if (strcmp(rgba_style, "none") == 0) {
cairo_font_options_set_antialias(cairo_font_options,
CAIRO_ANTIALIAS_GRAY);
} else {
cairo_font_options_set_antialias(cairo_font_options,
CAIRO_ANTIALIAS_SUBPIXEL);
cairo_subpixel_order_t cairo_subpixel_order =
CAIRO_SUBPIXEL_ORDER_DEFAULT;
if (strcmp(rgba_style, "rgb") == 0) {
cairo_subpixel_order = CAIRO_SUBPIXEL_ORDER_RGB;
} else if (strcmp(rgba_style, "bgr") == 0) {
cairo_subpixel_order = CAIRO_SUBPIXEL_ORDER_BGR;
} else if (strcmp(rgba_style, "vrgb") == 0) {
cairo_subpixel_order = CAIRO_SUBPIXEL_ORDER_VRGB;
} else if (strcmp(rgba_style, "vbgr") == 0) {
cairo_subpixel_order = CAIRO_SUBPIXEL_ORDER_VBGR;
}
cairo_font_options_set_subpixel_order(cairo_font_options,
cairo_subpixel_order);
}
cairo_hint_style_t cairo_hint_style = CAIRO_HINT_STYLE_DEFAULT;
if (hinting == 0 || strcmp(hint_style, "hintnone") == 0) {
cairo_hint_style = CAIRO_HINT_STYLE_NONE;
} else if (strcmp(hint_style, "hintslight") == 0) {
cairo_hint_style = CAIRO_HINT_STYLE_SLIGHT;
} else if (strcmp(hint_style, "hintmedium") == 0) {
cairo_hint_style = CAIRO_HINT_STYLE_MEDIUM;
} else if (strcmp(hint_style, "hintfull") == 0) {
cairo_hint_style = CAIRO_HINT_STYLE_FULL;
}
cairo_font_options_set_hint_style(cairo_font_options, cairo_hint_style);
}
if (hint_style)
g_free(hint_style);
if (rgba_style)
g_free(rgba_style);
}
// TODO(sky): this is a copy of the one in gtk_util. It needs to be moved to a
// common place.
// Common implementation of ConvertAcceleratorsFromWindowsStyle() and
// RemoveWindowsStyleAccelerators().
// Replaces all ampersands (as used in our grd files to indicate mnemonics)
// to |target|. Similarly any underscores get replaced with two underscores as
// is needed by pango.
std::string ConvertAmperstandsTo(const std::string& label,
const std::string& target) {
std::string ret;
ret.reserve(label.length() * 2);
for (size_t i = 0; i < label.length(); ++i) {
if ('_' == label[i]) {
ret.push_back('_');
ret.push_back('_');
} else if ('&' == label[i]) {
if (i + 1 < label.length() && '&' == label[i + 1]) {
ret.push_back('&');
++i;
} else {
ret.append(target);
}
} else {
ret.push_back(label[i]);
}
}
return ret;
}
} // namespace
namespace gfx {
CanvasSkia::CanvasSkia(int width, int height, bool is_opaque)
: skia::PlatformCanvas(width, height, is_opaque) {
}
CanvasSkia::CanvasSkia() : skia::PlatformCanvas() {
}
CanvasSkia::~CanvasSkia() {
}
// Pass a width > 0 to force wrapping and elliding.
static void SetupPangoLayout(PangoLayout* layout,
const std::wstring& text,
const gfx::Font& font,
int width,
int flags) {
if (!cairo_font_options)
UpdateCairoFontOptions();
// This needs to be done early on; it has no effect when called just before
// pango_cairo_show_layout().
pango_cairo_context_set_font_options(
pango_layout_get_context(layout), cairo_font_options);
// Callers of DrawStringInt handle RTL layout themselves, so tell pango to not
// scope out RTL characters.
pango_layout_set_auto_dir(layout, FALSE);
if (width > 0)
pango_layout_set_width(layout, width * PANGO_SCALE);
if (flags & Canvas::NO_ELLIPSIS) {
pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_NONE);
} else {
pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_END);
}
if (flags & Canvas::TEXT_ALIGN_CENTER) {
pango_layout_set_alignment(layout, PANGO_ALIGN_CENTER);
} else if (flags & Canvas::TEXT_ALIGN_RIGHT) {
pango_layout_set_alignment(layout, PANGO_ALIGN_RIGHT);
}
if (flags & Canvas::MULTI_LINE) {
pango_layout_set_wrap(layout,
(flags & Canvas::CHARACTER_BREAK) ?
PANGO_WRAP_WORD_CHAR : PANGO_WRAP_WORD);
}
// Set the resolution to match that used by Gtk. If we don't set the
// resolution and the resolution differs from the default, Gtk and Chrome end
// up drawing at different sizes.
double resolution = gfx::GetPangoResolution();
if (resolution > 0) {
pango_cairo_context_set_resolution(pango_layout_get_context(layout),
resolution);
}
PangoFontDescription* desc = gfx::Font::PangoFontFromGfxFont(font);
pango_layout_set_font_description(layout, desc);
pango_font_description_free(desc);
// Set text and accelerator character if needed.
std::string utf8 = WideToUTF8(text);
if (flags & gfx::Canvas::SHOW_PREFIX) {
// Escape the text string to be used as markup.
gchar* escaped_text = g_markup_escape_text(utf8.c_str(), utf8.size());
pango_layout_set_markup_with_accel(layout,
escaped_text,
strlen(escaped_text),
kAcceleratorChar, NULL);
g_free(escaped_text);
} else if (flags & gfx::Canvas::HIDE_PREFIX) {
// Remove the ampersand character.
utf8 = ConvertAmperstandsTo(utf8, "");
pango_layout_set_text(layout, utf8.data(), utf8.size());
} else {
pango_layout_set_text(layout, utf8.data(), utf8.size());
}
}
// static
void CanvasSkia::SizeStringInt(const std::wstring& text,
const gfx::Font& font,
int* width, int* height, int flags) {
int org_width = *width;
cairo_surface_t* surface =
cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 0, 0);
cairo_t* cr = cairo_create(surface);
PangoLayout* layout = pango_cairo_create_layout(cr);
SetupPangoLayout(layout, text, font, *width, flags);
pango_layout_get_pixel_size(layout, width, height);
if (org_width > 0 && flags & Canvas::MULTI_LINE &&
pango_layout_is_wrapped(layout)) {
// The text wrapped. There seems to be a bug in Pango when this happens
// such that the width returned from pango_layout_get_pixel_size is too
// small. Using the width from pango_layout_get_pixel_size in this case
// results in wrapping across more lines, which requires a bigger height.
// As a workaround we use the original width, which is not necessarily
// exactly correct, but isn't wrong by much.
//
// It looks like Pango uses the size of whitespace in calculating wrapping
// but doesn't include the size of the whitespace when the extents are
// asked for. See the loop in pango-layout.c process_item that determines
// where to wrap.
*width = org_width;
}
g_object_unref(layout);
cairo_destroy(cr);
cairo_surface_destroy(surface);
}
void CanvasSkia::DrawStringInt(const std::wstring& text,
const gfx::Font& font,
const SkColor& color,
int x, int y, int w, int h,
int flags) {
if (w <= 0 || h <= 0)
return;
cairo_t* cr = beginPlatformPaint();
PangoLayout* layout = pango_cairo_create_layout(cr);
SetupPangoLayout(layout, text, font, w, flags);
pango_layout_set_height(layout, h * PANGO_SCALE);
cairo_save(cr);
cairo_set_source_rgba(cr,
SkColorGetR(color) / 255.0,
SkColorGetG(color) / 255.0,
SkColorGetB(color) / 255.0,
SkColorGetA(color) / 255.0);
int width, height;
pango_layout_get_pixel_size(layout, &width, &height);
cairo_rectangle(cr, x, y, w, h);
cairo_clip(cr);
if (flags & Canvas::TEXT_VALIGN_TOP) {
// Cairo should draw from the top left corner already.
} else if (flags & Canvas::TEXT_VALIGN_BOTTOM) {
y += (h - height);
} else {
// Vertically centered.
y += ((h - height) / 2);
}
cairo_move_to(cr, x, y);
pango_cairo_show_layout(cr, layout);
if (font.style() & gfx::Font::UNDERLINED) {
double underline_y =
static_cast<double>(y) + height + font.underline_position();
cairo_set_line_width(cr, font.underline_thickness());
cairo_move_to(cr, x, underline_y);
cairo_line_to(cr, x + width, underline_y);
cairo_stroke(cr);
}
cairo_restore(cr);
g_object_unref(layout);
// NOTE: beginPlatformPaint returned its surface, we shouldn't destroy it.
}
void CanvasSkia::DrawGdkPixbuf(GdkPixbuf* pixbuf, int x, int y) {
if (!pixbuf) {
NOTREACHED();
return;
}
cairo_t* cr = beginPlatformPaint();
gdk_cairo_set_source_pixbuf(cr, pixbuf, x, y);
cairo_paint(cr);
}
} // namespace gfx
<|endoftext|> |
<commit_before>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2015 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#ifndef CAF_SCHEDULER_PROFILED_COORDINATOR_HPP
#define CAF_SCHEDULER_PROFILED_COORDINATOR_HPP
#include "caf/config.hpp"
#if defined(CAF_MACOS) || defined(CAF_IOS)
#include <mach/mach.h>
#else
#include <sys/resource.h>
#endif // CAF_MACOS
#include <cmath>
#include <mutex>
#include <chrono>
#include <vector>
#include <fstream>
#include <iomanip>
#include <unordered_map>
#include "caf/policy/profiled.hpp"
#include "caf/policy/work_stealing.hpp"
#include "caf/detail/logging.hpp"
namespace caf {
namespace scheduler {
/// A coordinator which keeps fine-grained profiling state about its workers
/// and their jobs.
template <class Policy = policy::profiled<policy::work_stealing>>
class profiled_coordinator : public coordinator<Policy> {
public:
using super = coordinator<Policy>;
using clock_type = std::chrono::high_resolution_clock;
using usec = std::chrono::microseconds;
using msec = std::chrono::milliseconds;
class measurement {
public:
# if defined(CAF_MACOS) || defined(CAF_IOS)
static usec to_usec(const ::time_value_t& tv) {
return std::chrono::seconds(tv.seconds) + usec(tv.microseconds);
}
# else
static usec to_usec(const ::timeval& tv) {
return std::chrono::seconds(tv.tv_sec) + usec(tv.tv_usec);
}
# endif // CAF_MACOS
static measurement take() {
auto now = clock_type::now().time_since_epoch();
measurement m;
m.runtime = std::chrono::duration_cast<usec>(now);
# if defined(CAF_MACOS) || defined(CAF_IOS)
auto tself = ::mach_thread_self();
::thread_basic_info info;
auto count = THREAD_BASIC_INFO_COUNT;
auto result = ::thread_info(tself, THREAD_BASIC_INFO,
reinterpret_cast<thread_info_t>(&info),
&count);
if (result == KERN_SUCCESS && (info.flags & TH_FLAGS_IDLE) == 0) {
m.usr = to_usec(info.user_time);
m.sys = to_usec(info.system_time);
}
::mach_port_deallocate(mach_task_self(), tself);
# else
::rusage ru;
::getrusage(RUSAGE_THREAD, &ru);
m.usr = to_usec(ru.ru_utime);
m.sys = to_usec(ru.ru_stime);
m.mem = ru.ru_maxrss;
# endif // CAF_MACOS
return m;
}
measurement& operator+=(const measurement& other) {
runtime += other.runtime;
usr += other.usr;
sys += other.sys;
mem += other.mem;
return *this;
}
measurement& operator-=(const measurement& other) {
runtime -= other.runtime;
usr -= other.usr;
sys -= other.sys;
mem -= other.mem;
return *this;
}
friend measurement operator+(const measurement& x, const measurement& y) {
measurement tmp(x);
tmp += y;
return tmp;
}
friend measurement operator-(const measurement& x, const measurement& y) {
measurement tmp(x);
tmp -= y;
return tmp;
}
friend std::ostream& operator<<(std::ostream& out, const measurement& m) {
using std::setw;
out << setw(15) << m.runtime.count()
<< setw(15) << m.usr.count()
<< setw(15) << m.sys.count()
<< m.mem;
return out;
}
usec runtime = usec::zero();
usec usr = usec::zero();
usec sys = usec::zero();
long mem = 0;
};
struct worker_state {
actor_id current;
measurement job;
measurement worker;
clock_type::duration last_flush = clock_type::duration::zero();
};
profiled_coordinator(const std::string& filename,
msec res = msec{1000},
size_t nw = std::max(std::thread::hardware_concurrency(),
4u),
size_t mt = std::numeric_limits<size_t>::max())
: super{nw, mt},
file_{filename},
resolution_{res},
system_start_{std::chrono::system_clock::now()},
clock_start_{clock_type::now().time_since_epoch()} {
if (! file_) {
throw std::runtime_error{"failed to open CAF profiler file"};
}
}
void initialize() override {
super::initialize();
worker_states_.resize(this->num_workers());
using std::setw;
file_.flags(std::ios::left);
file_ << setw(21) << "clock" // UNIX timestamp in microseconds
<< setw(10) << "type" // "actor" or "worker"
<< setw(10) << "id" // ID of the above
<< setw(15) << "time" // duration of this sample (cumulative)
<< setw(15) << "usr" // time spent in user mode (cumulative)
<< setw(15) << "sys" // time spent in kernel model (cumulative)
<< "mem" // used memory (cumulative)
<< '\n';
}
void stop() override {
CAF_LOG_TRACE("");
super::stop();
auto now = clock_type::now().time_since_epoch();
auto wallclock = system_start_ + (now - clock_start_);
for (size_t i = 0; i < worker_states_.size(); ++i) {
record(wallclock, "worker", i, worker_states_[i].worker);
}
}
void start_measuring(size_t worker, actor_id job) {
auto& w = worker_states_[worker];
w.current = job;
w.job = measurement::take();
}
void stop_measuring(size_t worker, actor_id job) {
auto m = measurement::take();
auto& w = worker_states_[worker];
CAF_ASSERT(job == w.current);
auto delta = m - w.job;
// It's not possible that the wallclock timer is less than actual CPU time
// spent. Due to resolution mismatches of the C++ high-resolution clock and
// the system timers, this may appear to be the case sometimes. We "fix"
// this by adjusting the wallclock to the sum of user and system time, so
// that utilization never exceeds 100%.
if (delta.runtime < delta.usr + delta.sys) {
delta.runtime = delta.usr + delta.sys;
}
w.worker += delta;
report(job, delta);
if (m.runtime - w.last_flush >= resolution_) {
w.last_flush = m.runtime;
auto wallclock = system_start_ + (m.runtime - clock_start_);
std::lock_guard<std::mutex> file_guard{file_mtx_};
record(wallclock, "worker", worker, w.worker);
w.worker = {};
}
}
void remove_job(actor_id job) {
std::lock_guard<std::mutex> job_guard{job_mtx_};
auto j = jobs_.find(job);
if (j != jobs_.end()) {
if (job != 0) {
auto now = clock_type::now().time_since_epoch();
auto wallclock = system_start_ + (now - clock_start_);
std::lock_guard<std::mutex> file_guard{file_mtx_};
record(wallclock, "actor", job, j->second);
}
jobs_.erase(j);
}
}
template <class Time, class Label>
void record(Time t, Label label, size_t id, const measurement& m) {
using std::setw;
file_ << setw(21) << t.time_since_epoch().count()
<< setw(10) << label
<< setw(10) << id
<< m
<< '\n';
}
void report(const actor_id& job, const measurement& m) {
std::lock_guard<std::mutex> job_guard{job_mtx_};
jobs_[job] += m;
if (m.runtime - last_flush_ >= resolution_) {
last_flush_ = m.runtime;
auto now = clock_type::now().time_since_epoch();
auto wallclock = system_start_ + (now - clock_start_);
std::lock_guard<std::mutex> file_guard{file_mtx_};
for (auto& j : jobs_) {
record(wallclock, "actor", j.first, j.second);
j.second = {};
}
}
}
std::mutex job_mtx_;
std::mutex file_mtx_;
std::ofstream file_;
msec resolution_;
std::chrono::system_clock::time_point system_start_;
clock_type::duration clock_start_;
std::vector<worker_state> worker_states_;
std::unordered_map<actor_id, measurement> jobs_;
clock_type::duration last_flush_ = clock_type::duration::zero();
};
} // namespace scheduler
} // namespace caf
#endif // CAF_SCHEDULER_PROFILED_COORDINATOR_HPP
<commit_msg>profiled_coordianator works on windows<commit_after>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2015 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#ifndef CAF_SCHEDULER_PROFILED_COORDINATOR_HPP
#define CAF_SCHEDULER_PROFILED_COORDINATOR_HPP
#include "caf/config.hpp"
#if defined(CAF_MACOS) || defined(CAF_IOS)
#include <mach/mach.h>
#elif defined(CAF_WINDOWS)
#include <Windows.h>
#include <Psapi.h>
#else
#include <sys/resource.h>
#endif
#include <cmath>
#include <mutex>
#include <chrono>
#include <vector>
#include <fstream>
#include <iomanip>
#include <unordered_map>
#include "caf/policy/profiled.hpp"
#include "caf/policy/work_stealing.hpp"
#include "caf/detail/logging.hpp"
namespace caf {
namespace scheduler {
/// A coordinator which keeps fine-grained profiling state about its workers
/// and their jobs.
template <class Policy = policy::profiled<policy::work_stealing>>
class profiled_coordinator : public coordinator<Policy> {
public:
using super = coordinator<Policy>;
using clock_type = std::chrono::high_resolution_clock;
using usec = std::chrono::microseconds;
using msec = std::chrono::milliseconds;
class measurement {
public:
# if defined(CAF_MACOS) || defined(CAF_IOS)
static usec to_usec(const ::time_value_t& tv) {
return std::chrono::seconds(tv.seconds) + usec(tv.microseconds);
}
# elif defined(CAF_WINDOWS)
static usec to_usec(FILETIME const& ft) {
ULARGE_INTEGER time;
time.LowPart = ft.dwLowDateTime;
time.HighPart = ft.dwHighDateTime;
return std::chrono::seconds(time.QuadPart / 10000000) + usec((time.QuadPart % 10000000) / 10);
}
# else
static usec to_usec(const ::timeval& tv) {
return std::chrono::seconds(tv.tv_sec) + usec(tv.tv_usec);
}
# endif
static measurement take() {
auto now = clock_type::now().time_since_epoch();
measurement m;
m.runtime = std::chrono::duration_cast<usec>(now);
# if defined(CAF_MACOS) || defined(CAF_IOS)
auto tself = ::mach_thread_self();
::thread_basic_info info;
auto count = THREAD_BASIC_INFO_COUNT;
auto result = ::thread_info(tself, THREAD_BASIC_INFO,
reinterpret_cast<thread_info_t>(&info),
&count);
if (result == KERN_SUCCESS && (info.flags & TH_FLAGS_IDLE) == 0) {
m.usr = to_usec(info.user_time);
m.sys = to_usec(info.system_time);
}
::mach_port_deallocate(mach_task_self(), tself);
# elif defined(CAF_WINDOWS)
FILETIME creation_time, exit_time, kernel_time, user_time;
PROCESS_MEMORY_COUNTERS pmc;
GetProcessTimes(GetCurrentProcess(), &creation_time, &exit_time,
&kernel_time, &user_time));
GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc));
m.mem = pmc.PeakWorkingSetSize / 1024;
m.usr = to_usec(user_time);
m.sys = to_usec(kernel_time);
# else
::rusage ru;
::getrusage(RUSAGE_THREAD, &ru);
m.usr = to_usec(ru.ru_utime);
m.sys = to_usec(ru.ru_stime);
m.mem = ru.ru_maxrss;
# endif
return m;
}
measurement& operator+=(const measurement& other) {
runtime += other.runtime;
usr += other.usr;
sys += other.sys;
mem += other.mem;
return *this;
}
measurement& operator-=(const measurement& other) {
runtime -= other.runtime;
usr -= other.usr;
sys -= other.sys;
mem -= other.mem;
return *this;
}
friend measurement operator+(const measurement& x, const measurement& y) {
measurement tmp(x);
tmp += y;
return tmp;
}
friend measurement operator-(const measurement& x, const measurement& y) {
measurement tmp(x);
tmp -= y;
return tmp;
}
friend std::ostream& operator<<(std::ostream& out, const measurement& m) {
using std::setw;
out << setw(15) << m.runtime.count()
<< setw(15) << m.usr.count()
<< setw(15) << m.sys.count()
<< m.mem;
return out;
}
usec runtime = usec::zero();
usec usr = usec::zero();
usec sys = usec::zero();
long mem = 0;
};
struct worker_state {
actor_id current;
measurement job;
measurement worker;
clock_type::duration last_flush = clock_type::duration::zero();
};
profiled_coordinator(const std::string& filename,
msec res = msec{1000},
size_t nw = std::max(std::thread::hardware_concurrency(),
4u),
size_t mt = std::numeric_limits<size_t>::max())
: super{nw, mt},
file_{filename},
resolution_{res},
system_start_{std::chrono::system_clock::now()},
clock_start_{clock_type::now().time_since_epoch()} {
if (! file_) {
throw std::runtime_error{"failed to open CAF profiler file"};
}
}
void initialize() override {
super::initialize();
worker_states_.resize(this->num_workers());
using std::setw;
file_.flags(std::ios::left);
file_ << setw(21) << "clock" // UNIX timestamp in microseconds
<< setw(10) << "type" // "actor" or "worker"
<< setw(10) << "id" // ID of the above
<< setw(15) << "time" // duration of this sample (cumulative)
<< setw(15) << "usr" // time spent in user mode (cumulative)
<< setw(15) << "sys" // time spent in kernel model (cumulative)
<< "mem" // used memory (cumulative)
<< '\n';
}
void stop() override {
CAF_LOG_TRACE("");
super::stop();
auto now = clock_type::now().time_since_epoch();
auto wallclock = system_start_ + (now - clock_start_);
for (size_t i = 0; i < worker_states_.size(); ++i) {
record(wallclock, "worker", i, worker_states_[i].worker);
}
}
void start_measuring(size_t worker, actor_id job) {
auto& w = worker_states_[worker];
w.current = job;
w.job = measurement::take();
}
void stop_measuring(size_t worker, actor_id job) {
auto m = measurement::take();
auto& w = worker_states_[worker];
CAF_ASSERT(job == w.current);
auto delta = m - w.job;
// It's not possible that the wallclock timer is less than actual CPU time
// spent. Due to resolution mismatches of the C++ high-resolution clock and
// the system timers, this may appear to be the case sometimes. We "fix"
// this by adjusting the wallclock to the sum of user and system time, so
// that utilization never exceeds 100%.
if (delta.runtime < delta.usr + delta.sys) {
delta.runtime = delta.usr + delta.sys;
}
w.worker += delta;
report(job, delta);
if (m.runtime - w.last_flush >= resolution_) {
w.last_flush = m.runtime;
auto wallclock = system_start_ + (m.runtime - clock_start_);
std::lock_guard<std::mutex> file_guard{file_mtx_};
record(wallclock, "worker", worker, w.worker);
w.worker = {};
}
}
void remove_job(actor_id job) {
std::lock_guard<std::mutex> job_guard{job_mtx_};
auto j = jobs_.find(job);
if (j != jobs_.end()) {
if (job != 0) {
auto now = clock_type::now().time_since_epoch();
auto wallclock = system_start_ + (now - clock_start_);
std::lock_guard<std::mutex> file_guard{file_mtx_};
record(wallclock, "actor", job, j->second);
}
jobs_.erase(j);
}
}
template <class Time, class Label>
void record(Time t, Label label, size_t id, const measurement& m) {
using std::setw;
file_ << setw(21) << t.time_since_epoch().count()
<< setw(10) << label
<< setw(10) << id
<< m
<< '\n';
}
void report(const actor_id& job, const measurement& m) {
std::lock_guard<std::mutex> job_guard{job_mtx_};
jobs_[job] += m;
if (m.runtime - last_flush_ >= resolution_) {
last_flush_ = m.runtime;
auto now = clock_type::now().time_since_epoch();
auto wallclock = system_start_ + (now - clock_start_);
std::lock_guard<std::mutex> file_guard{file_mtx_};
for (auto& j : jobs_) {
record(wallclock, "actor", j.first, j.second);
j.second = {};
}
}
}
std::mutex job_mtx_;
std::mutex file_mtx_;
std::ofstream file_;
msec resolution_;
std::chrono::system_clock::time_point system_start_;
clock_type::duration clock_start_;
std::vector<worker_state> worker_states_;
std::unordered_map<actor_id, measurement> jobs_;
clock_type::duration last_flush_ = clock_type::duration::zero();
};
} // namespace scheduler
} // namespace caf
#endif // CAF_SCHEDULER_PROFILED_COORDINATOR_HPP
<|endoftext|> |
<commit_before>/*
** Author(s):
** - Herve Cuche <hcuche@aldebaran-robotics.com>
**
** Copyright (C) 2012 Aldebaran Robotics
*/
#include <iostream>
#include <cstring>
#include <map>
#include <stdint.h>
#include <event2/util.h>
#include <event2/event.h>
#include <event2/buffer.h>
#include <event2/bufferevent.h>
#include <boost/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include "src/transport_socket_p.hpp"
#include "src/transport_socket_libevent_p.hpp"
#include "src/network_thread.hpp"
#include "src/message_p.hpp"
#include "src/buffer_p.hpp"
#include "src/session_p.hpp"
#include <qi/log.hpp>
#include <qimessaging/session.hpp>
#include <qimessaging/message.hpp>
#include <qimessaging/datastream.hpp>
#include <qimessaging/buffer.hpp>
#define MAX_LINE 16384
namespace qi
{
static void readcb(struct bufferevent *bev,
void *context)
{
TransportSocketLibEvent *tc = static_cast<TransportSocketLibEvent*>(context);
tc->readcb(bev, context);
}
static void writecb(struct bufferevent* bev,
void* context)
{
TransportSocketLibEvent *tc = static_cast<TransportSocketLibEvent*>(context);
tc->writecb(bev, context);
}
static void eventcb(struct bufferevent *bev,
short error,
void *context)
{
TransportSocketLibEvent *tc = static_cast<TransportSocketLibEvent*>(context);
tc->eventcb(bev, error, context);
}
void TransportSocketLibEvent::readcb(struct bufferevent *bev,
void *QI_UNUSED(context))
{
struct evbuffer *input = bufferevent_get_input(bev);
while (true)
{
if (msg == NULL)
{
msg = new qi::Message();
readHdr = true;
}
if (readHdr)
{
if (evbuffer_get_length(input) < sizeof(MessagePrivate::MessageHeader))
return;
evbuffer_remove(input,
msg->_p->getHeader(),
sizeof(MessagePrivate::MessageHeader));
readHdr = false;
}
if (evbuffer_get_length(input) <
static_cast<MessagePrivate::MessageHeader*>(msg->_p->getHeader())->size)
return;
/* we have to let the Buffer know we are going to push some data inside */
qi::Buffer buf;
buf.reserve(static_cast<MessagePrivate::MessageHeader*>(msg->_p->getHeader())->size);
msg->setBuffer(buf);
evbuffer_remove(input,
buf.data(),
buf.size());
assert(msg->isValid());
{
boost::mutex::scoped_lock l(mtx);
msgSend[msg->id()] = msg;
cond.notify_all();
}
if (tcd)
tcd->onSocketReadyRead(self, msg->id());
msg = NULL;
}
}
void TransportSocketLibEvent::writecb(struct bufferevent *QI_UNUSED(bev),
void *QI_UNUSED(context))
{
if (tcd)
tcd->onSocketWriteDone(self);
}
void TransportSocketLibEvent::eventcb(struct bufferevent *bev,
short events,
void *QI_UNUSED(context))
{
if (events & BEV_EVENT_CONNECTED)
{
connected = true;
if (tcd)
tcd->onSocketConnected(self);
}
#ifdef WIN32
/* On windows, BEV_EVENT_EOF doesn't pop on service kill
** but BEV_EVENT_READING and BEV_EVENT_ERROR suggest an error while reading.
** For a better fix, need to find out how to make libevent pop the proper error. (pr)
*/
else if ((events & BEV_EVENT_READING) && (events & BEV_EVENT_ERROR))
#else
else if (events & BEV_EVENT_EOF)
#endif
{
bufferevent_free(bev);
bev = 0;
connected = false;
//for waitForId
cond.notify_all();
if (tcd)
tcd->onSocketDisconnected(self);
// connection has been closed, do any clean up here
}
else if (events & BEV_EVENT_ERROR)
{
bufferevent_free(bev);
bev = 0;
connected = false;
//for waitForId
cond.notify_all();
if (tcd)
tcd->onSocketConnectionError(self);
// check errno to see what error occurred
qiLogError("qimessaging.TransportSocketLibevent") << "Cannot connect" << std::endl;
}
else if (events & BEV_EVENT_TIMEOUT)
{
// must be a timeout event handle, handle it
qiLogError("qimessaging.TransportSocketLibevent") << "must be a timeout event handle, handle it" << std::endl;
}
}
TransportSocketLibEvent::TransportSocketLibEvent(TransportSocket *socket)
: TransportSocketPrivate(socket)
, bev(NULL)
, fd(-1)
{
}
TransportSocketLibEvent::TransportSocketLibEvent(TransportSocket *socket, int fileDesc, void *data)
: TransportSocketPrivate(socket)
, bev(NULL)
, fd(fileDesc)
{
struct event_base *base = static_cast<event_base *>(data);
bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);
bufferevent_setcb(bev, ::qi::readcb, ::qi::writecb, ::qi::eventcb, this);
bufferevent_setwatermark(bev, EV_WRITE, 0, MAX_LINE);
bufferevent_enable(bev, EV_READ|EV_WRITE);
connected = true;
}
TransportSocketLibEvent::~TransportSocketLibEvent()
{
if (isConnected())
disconnect();
}
void TransportSocketLibEvent::onBufferSent(const void *QI_UNUSED(data),
size_t QI_UNUSED(datalen),
void *buffer)
{
Buffer *b = static_cast<Buffer *>(buffer);
delete b;
}
void TransportSocketLibEvent::onMessageSent(const void *QI_UNUSED(data),
size_t QI_UNUSED(datalen),
void *msg)
{
Message *m = static_cast<Message *>(msg);
delete m;
}
bool TransportSocketLibEvent::connect(qi::Session *session,
const qi::Url &url)
{
const std::string &address = url.host();
unsigned short port = url.port();
if (!isConnected())
{
bev = bufferevent_socket_new(session->_p->_networkThread->getEventBase(), -1, BEV_OPT_CLOSE_ON_FREE);
bufferevent_setcb(bev, ::qi::readcb, ::qi::writecb, ::qi::eventcb, this);
bufferevent_setwatermark(bev, EV_WRITE, 0, MAX_LINE);
bufferevent_enable(bev, EV_READ|EV_WRITE);
int result = bufferevent_socket_connect_hostname(bev, NULL, AF_INET, address.c_str(), port);
if (result == 0)
{
connected = true;
return true;
}
}
else
{
qiLogError("qimessaging.TransportSocketLibevent") << "socket is already connected.";
}
return false;
}
void TransportSocketLibEvent::disconnect()
{
if (isConnected())
{
bufferevent_free(bev);
bev = NULL;
connected = false;
}
else
{
qiLogError("qimessaging.TransportSocketLibevent") << "socket is not connected.";
}
}
bool TransportSocketLibEvent::send(const qi::Message &msg)
{
if (!isConnected())
{
qiLogError("qimessaging.TransportSocketLibevent") << "socket is not connected.";
return false;
}
qi::Message *m = new qi::Message();
*m = msg;
m->_p->complete();
assert(m->isValid());
struct evbuffer *evb = bufferevent_get_output(bev);
// m might be deleted.
qi::Buffer *b = new qi::Buffer(m->buffer());
if (evbuffer_add_reference(evb,
m->_p->getHeader(),
sizeof(qi::MessagePrivate::MessageHeader),
qi::TransportSocketLibEvent::onMessageSent,
static_cast<void *>(m)) != 0)
{
return false;
}
if (b->size() &&
evbuffer_add_reference(evb,
b->data(),
b->size(),
qi::TransportSocketLibEvent::onBufferSent,
static_cast<void *>(b)) != 0)
{
return false;
}
if (bufferevent_write_buffer(bev, evb) != 0)
{
return false;
}
return true;
}
}
<commit_msg>fix connection error on windows by resolving ourself before calling socket_connect<commit_after>/*
** Author(s):
** - Herve Cuche <hcuche@aldebaran-robotics.com>
**
** Copyright (C) 2012 Aldebaran Robotics
*/
#include <iostream>
#include <cstring>
#include <map>
#include <stdint.h>
#include <event2/util.h>
#include <event2/event.h>
#include <event2/buffer.h>
#include <event2/bufferevent.h>
#include <boost/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include "src/transport_socket_p.hpp"
#include "src/transport_socket_libevent_p.hpp"
#include "src/network_thread.hpp"
#include "src/message_p.hpp"
#include "src/buffer_p.hpp"
#include "src/session_p.hpp"
#include <qi/log.hpp>
#include <qimessaging/session.hpp>
#include <qimessaging/message.hpp>
#include <qimessaging/datastream.hpp>
#include <qimessaging/buffer.hpp>
#define MAX_LINE 16384
namespace qi
{
static void readcb(struct bufferevent *bev,
void *context)
{
TransportSocketLibEvent *tc = static_cast<TransportSocketLibEvent*>(context);
tc->readcb(bev, context);
}
static void writecb(struct bufferevent* bev,
void* context)
{
TransportSocketLibEvent *tc = static_cast<TransportSocketLibEvent*>(context);
tc->writecb(bev, context);
}
static void eventcb(struct bufferevent *bev,
short error,
void *context)
{
TransportSocketLibEvent *tc = static_cast<TransportSocketLibEvent*>(context);
tc->eventcb(bev, error, context);
}
void TransportSocketLibEvent::readcb(struct bufferevent *bev,
void *QI_UNUSED(context))
{
struct evbuffer *input = bufferevent_get_input(bev);
while (true)
{
if (msg == NULL)
{
msg = new qi::Message();
readHdr = true;
}
if (readHdr)
{
if (evbuffer_get_length(input) < sizeof(MessagePrivate::MessageHeader))
return;
evbuffer_remove(input,
msg->_p->getHeader(),
sizeof(MessagePrivate::MessageHeader));
readHdr = false;
}
if (evbuffer_get_length(input) <
static_cast<MessagePrivate::MessageHeader*>(msg->_p->getHeader())->size)
return;
/* we have to let the Buffer know we are going to push some data inside */
qi::Buffer buf;
buf.reserve(static_cast<MessagePrivate::MessageHeader*>(msg->_p->getHeader())->size);
msg->setBuffer(buf);
evbuffer_remove(input,
buf.data(),
buf.size());
assert(msg->isValid());
{
boost::mutex::scoped_lock l(mtx);
msgSend[msg->id()] = msg;
cond.notify_all();
}
if (tcd)
tcd->onSocketReadyRead(self, msg->id());
msg = NULL;
}
}
void TransportSocketLibEvent::writecb(struct bufferevent *QI_UNUSED(bev),
void *QI_UNUSED(context))
{
if (tcd)
tcd->onSocketWriteDone(self);
}
void TransportSocketLibEvent::eventcb(struct bufferevent *bev,
short events,
void *QI_UNUSED(context))
{
if (events & BEV_EVENT_CONNECTED)
{
connected = true;
if (tcd)
tcd->onSocketConnected(self);
}
#ifdef WIN32
/* On windows, BEV_EVENT_EOF doesn't pop on service kill
** but BEV_EVENT_READING and BEV_EVENT_ERROR suggest an error while reading.
** For a better fix, need to find out how to make libevent pop the proper error. (pr)
*/
else if ((events & BEV_EVENT_READING) && (events & BEV_EVENT_ERROR))
#else
else if (events & BEV_EVENT_EOF)
#endif
{
bufferevent_free(bev);
bev = 0;
connected = false;
//for waitForId
cond.notify_all();
if (tcd)
tcd->onSocketDisconnected(self);
// connection has been closed, do any clean up here
}
else if (events & BEV_EVENT_ERROR)
{
bufferevent_free(bev);
bev = 0;
connected = false;
//for waitForId
cond.notify_all();
if (tcd)
tcd->onSocketConnectionError(self);
// check errno to see what error occurred
qiLogError("qimessaging.TransportSocketLibevent") << "Cannot connect" << std::endl;
}
else if (events & BEV_EVENT_TIMEOUT)
{
// must be a timeout event handle, handle it
qiLogError("qimessaging.TransportSocketLibevent") << "must be a timeout event handle, handle it" << std::endl;
}
}
TransportSocketLibEvent::TransportSocketLibEvent(TransportSocket *socket)
: TransportSocketPrivate(socket)
, bev(NULL)
, fd(-1)
{
}
TransportSocketLibEvent::TransportSocketLibEvent(TransportSocket *socket, int fileDesc, void *data)
: TransportSocketPrivate(socket)
, bev(NULL)
, fd(fileDesc)
{
struct event_base *base = static_cast<event_base *>(data);
bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);
bufferevent_setcb(bev, ::qi::readcb, ::qi::writecb, ::qi::eventcb, this);
bufferevent_setwatermark(bev, EV_WRITE, 0, MAX_LINE);
bufferevent_enable(bev, EV_READ|EV_WRITE);
connected = true;
}
TransportSocketLibEvent::~TransportSocketLibEvent()
{
if (isConnected())
disconnect();
}
void TransportSocketLibEvent::onBufferSent(const void *QI_UNUSED(data),
size_t QI_UNUSED(datalen),
void *buffer)
{
Buffer *b = static_cast<Buffer *>(buffer);
delete b;
}
void TransportSocketLibEvent::onMessageSent(const void *QI_UNUSED(data),
size_t QI_UNUSED(datalen),
void *msg)
{
Message *m = static_cast<Message *>(msg);
delete m;
}
bool TransportSocketLibEvent::connect(qi::Session *session,
const qi::Url &url)
{
const std::string &address = url.host();
unsigned short port = url.port();
struct evutil_addrinfo *ai=NULL;
int err;
struct evutil_addrinfo hint;
char portbuf[10];
if (!isConnected())
{
bev = bufferevent_socket_new(session->_p->_networkThread->getEventBase(), -1, BEV_OPT_CLOSE_ON_FREE);
bufferevent_setcb(bev, ::qi::readcb, ::qi::writecb, ::qi::eventcb, this);
bufferevent_setwatermark(bev, EV_WRITE, 0, MAX_LINE);
bufferevent_enable(bev, EV_READ|EV_WRITE);
evutil_snprintf(portbuf, sizeof(portbuf), "%d", url.port());
memset(&hint, 0, sizeof(hint));
hint.ai_family = AF_INET;
hint.ai_protocol = IPPROTO_TCP;
hint.ai_socktype = SOCK_STREAM;
err = evutil_getaddrinfo(address.c_str(), portbuf, &hint, &ai);
if (err != 0)
{
qiLogError("qimessaging.TransportSocketLibEvent", "Cannot resolve dns");
return (false);
}
int result = bufferevent_socket_connect(bev, ai->ai_addr, ai->ai_addrlen);
if (result == 0)
{
connected = true;
return true;
}
return false;
}
else
{
qiLogError("qimessaging.TransportSocketLibevent") << "socket is already connected.";
}
return false;
}
void TransportSocketLibEvent::disconnect()
{
if (isConnected())
{
bufferevent_free(bev);
bev = NULL;
connected = false;
}
else
{
qiLogError("qimessaging.TransportSocketLibevent") << "socket is not connected.";
}
}
bool TransportSocketLibEvent::send(const qi::Message &msg)
{
if (!isConnected())
{
qiLogError("qimessaging.TransportSocketLibevent") << "socket is not connected.";
return false;
}
qi::Message *m = new qi::Message();
*m = msg;
m->_p->complete();
assert(m->isValid());
struct evbuffer *evb = bufferevent_get_output(bev);
// m might be deleted.
qi::Buffer *b = new qi::Buffer(m->buffer());
if (evbuffer_add_reference(evb,
m->_p->getHeader(),
sizeof(qi::MessagePrivate::MessageHeader),
qi::TransportSocketLibEvent::onMessageSent,
static_cast<void *>(m)) != 0)
{
return false;
}
if (b->size() &&
evbuffer_add_reference(evb,
b->data(),
b->size(),
qi::TransportSocketLibEvent::onBufferSent,
static_cast<void *>(b)) != 0)
{
return false;
}
if (bufferevent_write_buffer(bev, evb) != 0)
{
return false;
}
return true;
}
}
<|endoftext|> |
<commit_before>#include "JsonFile.hpp"
#include "Common/toJson.hpp"
using json = nlohmann::json;
namespace But
{
namespace Log
{
namespace Destination
{
void JsonFile::toStreamFormat(std::ostream& os, Backend::Entry const& entry)
{
auto tab = Common::toJson(entry);
os << tab << "\n";
}
void JsonFile::toStreamFormat(std::ostream& os, Field::FormattedString const& str, Backend::Entry const& entry)
{
auto tab = json::array();
tab.push_back( Common::toJsonField( Backend::FieldInfo{str} ) );
Common::toJson(tab, entry);
os << tab << "\n";
}
}
}
}
<commit_msg>implementation moved to new helper<commit_after>#include "JsonFile.hpp"
#include "Common/toJsonStream.hpp"
namespace But
{
namespace Log
{
namespace Destination
{
void JsonFile::toStreamFormat(std::ostream& os, Backend::Entry const& entry)
{
Common::toJsonStream(os, entry);
os << endline();
}
void JsonFile::toStreamFormat(std::ostream& os, Field::FormattedString const& str, Backend::Entry const& entry)
{
Common::toJsonStream(os, str, entry);
os << endline();
}
}
}
}
<|endoftext|> |
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2014, Robert Bosch LLC.
* 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 Robert Bosch 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 "modules/perception/traffic_light/util/color_space.h"
#include <cassert>
#include <cstdint>
#include "modules/common/log.h"
namespace apollo {
namespace perception {
namespace traffic_light {
#ifdef __USE_AVX__
template <bool align>
SIMD_INLINE void YuvSeperateAvx2(uint8_t *y, __m256i *y0, __m256i *y1,
__m256i *u0, __m256i *v0) {
DCHECK_NOTNULL(y0);
DCHECK_NOTNULL(y1);
DCHECK_NOTNULL(u0);
DCHECK_NOTNULL(v0);
__m256i yuv_m256[4];
if (align) {
yuv_m256[0] = Load<true>(reinterpret_cast<__m256i *>(y));
yuv_m256[1] = Load<true>(reinterpret_cast<__m256i *>(y) + 1);
yuv_m256[2] = Load<true>(reinterpret_cast<__m256i *>(y) + 2);
yuv_m256[3] = Load<true>(reinterpret_cast<__m256i *>(y) + 3);
} else {
yuv_m256[0] = Load<false>(reinterpret_cast<__m256i *>(y));
yuv_m256[1] = Load<false>(reinterpret_cast<__m256i *>(y) + 1);
yuv_m256[2] = Load<false>(reinterpret_cast<__m256i *>(y) + 2);
yuv_m256[3] = Load<false>(reinterpret_cast<__m256i *>(y) + 3);
}
*y0 =
_mm256_or_si256(_mm256_permute4x64_epi64(
_mm256_shuffle_epi8(yuv_m256[0], Y_SHUFFLE0), 0xD8),
_mm256_permute4x64_epi64(
_mm256_shuffle_epi8(yuv_m256[1], Y_SHUFFLE1), 0xD8));
*y1 =
_mm256_or_si256(_mm256_permute4x64_epi64(
_mm256_shuffle_epi8(yuv_m256[2], Y_SHUFFLE0), 0xD8),
_mm256_permute4x64_epi64(
_mm256_shuffle_epi8(yuv_m256[3], Y_SHUFFLE1), 0xD8));
*u0 = _mm256_permutevar8x32_epi32(
_mm256_or_si256(
_mm256_or_si256(_mm256_shuffle_epi8(yuv_m256[0], U_SHUFFLE0),
_mm256_shuffle_epi8(yuv_m256[1], U_SHUFFLE1)),
_mm256_or_si256(_mm256_shuffle_epi8(yuv_m256[2], U_SHUFFLE2),
_mm256_shuffle_epi8(yuv_m256[3], U_SHUFFLE3))),
U_SHUFFLE4);
*v0 = _mm256_permutevar8x32_epi32(
_mm256_or_si256(
_mm256_or_si256(_mm256_shuffle_epi8(yuv_m256[0], V_SHUFFLE0),
_mm256_shuffle_epi8(yuv_m256[1], V_SHUFFLE1)),
_mm256_or_si256(_mm256_shuffle_epi8(yuv_m256[2], V_SHUFFLE2),
_mm256_shuffle_epi8(yuv_m256[3], V_SHUFFLE3))),
U_SHUFFLE4);
}
template <bool align>
void Yuv2rgbAvx2(__m256i y0, __m256i u0, __m256i v0, uint8_t *rgb) {
__m256i r0 = YuvToRed(y0, v0);
__m256i g0 = YuvToGreen(y0, u0, v0);
__m256i b0 = YuvToBlue(y0, u0);
Store<align>(reinterpret_cast<__m256i *>(rgb) + 0,
InterleaveBgr<0>(r0, g0, b0));
Store<align>(reinterpret_cast<__m256i *>(rgb) + 1,
InterleaveBgr<1>(r0, g0, b0));
Store<align>(reinterpret_cast<__m256i *>(rgb) + 2,
InterleaveBgr<2>(r0, g0, b0));
}
template <bool align>
void Yuv2rgbAvx2(uint8_t *yuv, uint8_t *rgb) {
__m256i y0, y1, u0, v0;
YuvSeperateAvx2<align>(yuv, &y0, &y1, &u0, &v0);
__m256i u0_u0 = _mm256_permute4x64_epi64(u0, 0xD8);
__m256i v0_v0 = _mm256_permute4x64_epi64(v0, 0xD8);
Yuv2rgbAvx2<align>(y0, _mm256_unpacklo_epi8(u0_u0, u0_u0),
_mm256_unpacklo_epi8(v0_v0, v0_v0), rgb);
Yuv2rgbAvx2<align>(y1, _mm256_unpackhi_epi8(u0_u0, u0_u0),
_mm256_unpackhi_epi8(v0_v0, v0_v0),
rgb + 3 * sizeof(__m256i));
}
void Yuyv2rgb(unsigned char *YUV, unsigned char *RGB, int NumPixels) {
bool align = Aligned(YUV) & Aligned(RGB);
uint8_t *yuv_offset = YUV;
uint8_t *rgb_offset = RGB;
if (align) {
for (int i = 0; i < NumPixels; i = i + (2 * sizeof(__m256i)),
yuv_offset += 4 * sizeof(__m256i),
rgb_offset += 6 * sizeof(__m256i)) {
Yuv2rgbAvx2<true>(yuv_offset, rgb_offset);
}
} else {
for (int i = 0; i < NumPixels; i = i + (2 * sizeof(__m256i)),
yuv_offset += 4 * sizeof(__m256i),
rgb_offset += 6 * sizeof(__m256i)) {
Yuv2rgbAvx2<false>(yuv_offset, rgb_offset);
}
}
}
#else
unsigned char CLIPVALUE(int val) {
// Old method (if)
val = val < 0 ? 0 : val;
return val > 255 ? 255 : val;
// New method (array)
// return uchar_clipping_table[val + clipping_table_offset];
}
void YUV2RGB(const unsigned char y, const unsigned char u,
const unsigned char v, unsigned char* r, unsigned char* g,
unsigned char* b) {
const int y2 = static_cast<int>(y);
const int u2 = static_cast<int>(u) - 128;
const int v2 = static_cast<int>(v) - 128;
double r2 = y2 + (1.4065 * v2);
double g2 = y2 - (0.3455 * u2) - (0.7169 * v2);
double b2 = y2 + (2.041 * u2);
*r = CLIPVALUE(r2);
*g = CLIPVALUE(g2);
*b = CLIPVALUE(b2);
}
void Yuyv2rgb(unsigned char* YUV, unsigned char* RGB, int NumPixels) {
for (int i = 0, int j = 0; i < (NumPixels << 1); i += 4, j += 6) {
unsigned char u = (unsigned char)YUV[i + 0];
unsigned char y0 = (unsigned char)YUV[i + 1];
unsigned char v = (unsigned char)YUV[i + 2];
unsigned char y1 = (unsigned char)YUV[i + 3];
unsigned char r, g, b;
YUV2RGB(y0, u, v, &r, &g, &b);
RGB[j + 0] = r;
RGB[j + 1] = g;
RGB[j + 2] = b;
YUV2RGB(y1, u, v, &r, &g, &b);
RGB[j + 3] = r;
RGB[j + 4] = g;
RGB[j + 5] = b;
}
}
#endif
} // namespace traffic_light
} // namespace perception
} // namespace apollo
<commit_msg>Update color_space.cc<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2014, Robert Bosch LLC.
* 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 Robert Bosch 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 "modules/perception/traffic_light/util/color_space.h"
#include <cassert>
#include <cstdint>
#include "modules/common/log.h"
namespace apollo {
namespace perception {
namespace traffic_light {
#ifdef __USE_AVX__
template <bool align>
SIMD_INLINE void YuvSeperateAvx2(uint8_t *y, __m256i *y0, __m256i *y1,
__m256i *u0, __m256i *v0) {
DCHECK_NOTNULL(y0);
DCHECK_NOTNULL(y1);
DCHECK_NOTNULL(u0);
DCHECK_NOTNULL(v0);
__m256i yuv_m256[4];
if (align) {
yuv_m256[0] = Load<true>(reinterpret_cast<__m256i *>(y));
yuv_m256[1] = Load<true>(reinterpret_cast<__m256i *>(y) + 1);
yuv_m256[2] = Load<true>(reinterpret_cast<__m256i *>(y) + 2);
yuv_m256[3] = Load<true>(reinterpret_cast<__m256i *>(y) + 3);
} else {
yuv_m256[0] = Load<false>(reinterpret_cast<__m256i *>(y));
yuv_m256[1] = Load<false>(reinterpret_cast<__m256i *>(y) + 1);
yuv_m256[2] = Load<false>(reinterpret_cast<__m256i *>(y) + 2);
yuv_m256[3] = Load<false>(reinterpret_cast<__m256i *>(y) + 3);
}
*y0 =
_mm256_or_si256(_mm256_permute4x64_epi64(
_mm256_shuffle_epi8(yuv_m256[0], Y_SHUFFLE0), 0xD8),
_mm256_permute4x64_epi64(
_mm256_shuffle_epi8(yuv_m256[1], Y_SHUFFLE1), 0xD8));
*y1 =
_mm256_or_si256(_mm256_permute4x64_epi64(
_mm256_shuffle_epi8(yuv_m256[2], Y_SHUFFLE0), 0xD8),
_mm256_permute4x64_epi64(
_mm256_shuffle_epi8(yuv_m256[3], Y_SHUFFLE1), 0xD8));
*u0 = _mm256_permutevar8x32_epi32(
_mm256_or_si256(
_mm256_or_si256(_mm256_shuffle_epi8(yuv_m256[0], U_SHUFFLE0),
_mm256_shuffle_epi8(yuv_m256[1], U_SHUFFLE1)),
_mm256_or_si256(_mm256_shuffle_epi8(yuv_m256[2], U_SHUFFLE2),
_mm256_shuffle_epi8(yuv_m256[3], U_SHUFFLE3))),
U_SHUFFLE4);
*v0 = _mm256_permutevar8x32_epi32(
_mm256_or_si256(
_mm256_or_si256(_mm256_shuffle_epi8(yuv_m256[0], V_SHUFFLE0),
_mm256_shuffle_epi8(yuv_m256[1], V_SHUFFLE1)),
_mm256_or_si256(_mm256_shuffle_epi8(yuv_m256[2], V_SHUFFLE2),
_mm256_shuffle_epi8(yuv_m256[3], V_SHUFFLE3))),
U_SHUFFLE4);
}
template <bool align>
void Yuv2rgbAvx2(__m256i y0, __m256i u0, __m256i v0, uint8_t *rgb) {
__m256i r0 = YuvToRed(y0, v0);
__m256i g0 = YuvToGreen(y0, u0, v0);
__m256i b0 = YuvToBlue(y0, u0);
Store<align>(reinterpret_cast<__m256i *>(rgb) + 0,
InterleaveBgr<0>(r0, g0, b0));
Store<align>(reinterpret_cast<__m256i *>(rgb) + 1,
InterleaveBgr<1>(r0, g0, b0));
Store<align>(reinterpret_cast<__m256i *>(rgb) + 2,
InterleaveBgr<2>(r0, g0, b0));
}
template <bool align>
void Yuv2rgbAvx2(uint8_t *yuv, uint8_t *rgb) {
__m256i y0, y1, u0, v0;
YuvSeperateAvx2<align>(yuv, &y0, &y1, &u0, &v0);
__m256i u0_u0 = _mm256_permute4x64_epi64(u0, 0xD8);
__m256i v0_v0 = _mm256_permute4x64_epi64(v0, 0xD8);
Yuv2rgbAvx2<align>(y0, _mm256_unpacklo_epi8(u0_u0, u0_u0),
_mm256_unpacklo_epi8(v0_v0, v0_v0), rgb);
Yuv2rgbAvx2<align>(y1, _mm256_unpackhi_epi8(u0_u0, u0_u0),
_mm256_unpackhi_epi8(v0_v0, v0_v0),
rgb + 3 * sizeof(__m256i));
}
void Yuyv2rgb(unsigned char *YUV, unsigned char *RGB, int NumPixels) {
bool align = Aligned(YUV) & Aligned(RGB);
uint8_t *yuv_offset = YUV;
uint8_t *rgb_offset = RGB;
if (align) {
for (int i = 0; i < NumPixels; i = i + (2 * sizeof(__m256i)),
yuv_offset += 4 * sizeof(__m256i),
rgb_offset += 6 * sizeof(__m256i)) {
Yuv2rgbAvx2<true>(yuv_offset, rgb_offset);
}
} else {
for (int i = 0; i < NumPixels; i = i + (2 * sizeof(__m256i)),
yuv_offset += 4 * sizeof(__m256i),
rgb_offset += 6 * sizeof(__m256i)) {
Yuv2rgbAvx2<false>(yuv_offset, rgb_offset);
}
}
}
#else
unsigned char CLIPVALUE(int val) {
// Old method (if)
val = val < 0 ? 0 : val;
return val > 255 ? 255 : val;
// New method (array)
// return uchar_clipping_table[val + clipping_table_offset];
}
void YUV2RGB(const unsigned char y, const unsigned char u,
const unsigned char v, unsigned char* r, unsigned char* g,
unsigned char* b) {
const int y2 = static_cast<int>(y);
const int u2 = static_cast<int>(u) - 128;
const int v2 = static_cast<int>(v) - 128;
double r2 = y2 + (1.4065 * v2);
double g2 = y2 - (0.3455 * u2) - (0.7169 * v2);
double b2 = y2 + (2.041 * u2);
*r = CLIPVALUE(r2);
*g = CLIPVALUE(g2);
*b = CLIPVALUE(b2);
}
void Yuyv2rgb(unsigned char* YUV, unsigned char* RGB, int NumPixels) {
for (int i = 0, j = 0; i < (NumPixels << 1); i += 4, j += 6) {
unsigned char u = (unsigned char)YUV[i + 0];
unsigned char y0 = (unsigned char)YUV[i + 1];
unsigned char v = (unsigned char)YUV[i + 2];
unsigned char y1 = (unsigned char)YUV[i + 3];
unsigned char r, g, b;
YUV2RGB(y0, u, v, &r, &g, &b);
RGB[j + 0] = r;
RGB[j + 1] = g;
RGB[j + 2] = b;
YUV2RGB(y1, u, v, &r, &g, &b);
RGB[j + 3] = r;
RGB[j + 4] = g;
RGB[j + 5] = b;
}
}
#endif
} // namespace traffic_light
} // namespace perception
} // namespace apollo
<|endoftext|> |
<commit_before>/***************************************
CountMatrix_main.cpp
2013 - Kyle Hernandez
Juenger Laboratory
Section of Integrative Biology
The University of Texas at Austin
kmhernan84@gmail.com
Unlicensed, <http://unlicense.org/>
***************************************/
#include "CountMatrix.h"
using namespace std;
// Define parameter checking macro as used in bedtools
#define PARAMETER_CHECK(param, paramLen, actualLen) (strncmp(argv[i], param, min(actualLen, paramLen))== 0) && (actualLen == paramLen)
// function prototypes
void countMatrix_help(void);
int countMatrix_main(int argc, char* argv[]) {
// configuration variables
bool showHelp = false;
// I/O files
string indir;
string out;
// parm flags
bool haveInput = false;
bool haveOut = false;
if (argc <= 1) showHelp = true;
for(int i = 1; i < argc; i++) {
int parameterLength = (int)strlen(argv[i]);
if((PARAMETER_CHECK("-h", 2, parameterLength)) ||
(PARAMETER_CHECK("--help", 6, parameterLength))) {
showHelp = true;
}
}
if(showHelp) countMatrix_help();
// parse command line
for (int i = 1; i < argc; i++) {
int parameterLength = (int)strlen(argv[i]);
if(PARAMETER_CHECK("-i", 2, parameterLength)) {
if ((i+1) < argc) {
haveInput = true;
indir = argv[i + 1];
i++;
}
}
else if (PARAMETER_CHECK("-o", 2, parameterLength)) {
if ((i+1) < argc) {
haveOut = true;
out = argv[i + 1];
i++;
}
}
else {
cerr << "*****ERROR: Unrecognized parameter: " << argv[i] << endl;
showHelp = true;
}
}
// Check required elements
if (!haveInput) {
cerr << "*****ERROR: Need -i input directory of GMCounts files." << endl;
showHelp = true;
}
else if (!haveOut) {
cerr << "*****ERROR: Need -o output expression matrix file." << endl;
showHelp = true;
}
if (!showHelp) {
TagSeqCountMatrix *ts = new TagSeqCountMatrix(indir, out);
delete ts;
}
else {
countMatrix_help();
}
return 0;
}
void countMatrix_help(void)
{
cout << endl;
cout << "TagSeqTools CountMatrix: Create expression count matrix by merging " << endl;
cout << " count files created with GMCounts into one file." << endl;
cout << "Kyle Hernandez, 2013. UNLICENSED <www.unlicense.org>" << endl;
cout << endl;
cout << "USAGE:TagSeqTools CountMatrix -i <in-directory> -o <output.tab>" << endl;
cout << endl;
cout << "Required Arguments:" << endl;
cout << "Input either a directory with files:\n" << endl;
cout << " -i " << "Input parent directory of all the GMCount files you " << endl;
cout << " want to combine.\n" << endl;
cout << "Or provide a tab-delimited file with the following columns:" << endl;
cout << " 1. path - path to a single GMCounts file." << endl;
cout << " 2. output column id - the name used to the column representing this file in the matrix" << endl;
cout << " -o " << "Output expression matrix file" << endl;
cout << endl;
cout << "Optional Arguments:" << endl;
cout << " -h " << "Print this message and exit" << endl;
cout << endl;
exit(1);
}
<commit_msg>fixing help output<commit_after>/***************************************
CountMatrix_main.cpp
2013 - Kyle Hernandez
Juenger Laboratory
Section of Integrative Biology
The University of Texas at Austin
kmhernan84@gmail.com
Unlicensed, <http://unlicense.org/>
***************************************/
#include "CountMatrix.h"
using namespace std;
// Define parameter checking macro as used in bedtools
#define PARAMETER_CHECK(param, paramLen, actualLen) (strncmp(argv[i], param, min(actualLen, paramLen))== 0) && (actualLen == paramLen)
// function prototypes
void countMatrix_help(void);
int countMatrix_main(int argc, char* argv[]) {
// configuration variables
bool showHelp = false;
// I/O files
string indir;
string out;
// parm flags
bool haveInput = false;
bool haveOut = false;
if (argc <= 1) showHelp = true;
for(int i = 1; i < argc; i++) {
int parameterLength = (int)strlen(argv[i]);
if((PARAMETER_CHECK("-h", 2, parameterLength)) ||
(PARAMETER_CHECK("--help", 6, parameterLength))) {
showHelp = true;
}
}
if(showHelp) countMatrix_help();
// parse command line
for (int i = 1; i < argc; i++) {
int parameterLength = (int)strlen(argv[i]);
if(PARAMETER_CHECK("-i", 2, parameterLength)) {
if ((i+1) < argc) {
haveInput = true;
indir = argv[i + 1];
i++;
}
}
else if (PARAMETER_CHECK("-o", 2, parameterLength)) {
if ((i+1) < argc) {
haveOut = true;
out = argv[i + 1];
i++;
}
}
else {
cerr << "*****ERROR: Unrecognized parameter: " << argv[i] << endl;
showHelp = true;
}
}
// Check required elements
if (!haveInput) {
cerr << "*****ERROR: Need -i input directory of GMCounts files." << endl;
showHelp = true;
}
else if (!haveOut) {
cerr << "*****ERROR: Need -o output expression matrix file." << endl;
showHelp = true;
}
if (!showHelp) {
TagSeqCountMatrix *ts = new TagSeqCountMatrix(indir, out);
delete ts;
}
else {
countMatrix_help();
}
return 0;
}
void countMatrix_help(void)
{
cout << endl;
cout << "TagSeqTools CountMatrix: Create expression count matrix by merging " << endl;
cout << " count files created with GMCounts into one file." << endl;
cout << "Kyle Hernandez, 2013. UNLICENSED <www.unlicense.org>" << endl;
cout << endl;
cout << "USAGE:TagSeqTools CountMatrix -i <in-directory> -o <output.tab>" << endl;
cout << endl;
cout << "Required Arguments:" << endl;
cout << "Input either a directory with files:\n" << endl;
cout << " -i " << "Input parent directory of all the GMCount files you " << endl;
cout << " " << "want to combine.\n" << endl;
cout << " -o " << "Output expression matrix file" << endl;
cout << endl;
cout << "Optional Arguments:" << endl;
cout << " -h " << "Print this message and exit" << endl;
cout << endl;
exit(1);
}
<|endoftext|> |
<commit_before>#include "ConfusionMatrix.hpp"
/**
*
*/
ConfusionMatrix::ConfusionMatrix() {
a_ = 0;
b_ = 0;
c_ = 0;
d_ = 0;
}
/**
*
*/
ConfusionMatrix::~ConfusionMatrix() {}
/**
* each ruby hash are pairs of {read_id => clust_id}
*/
ConfusionMatrix::ConfusionMatrix(Rice::Hash c1_hsh, Rice::Hash c2_hsh) {
a_ = 0;
b_ = 0;
c_ = 0;
d_ = 0;
populate_vect(c1_hsh, clust_1_);
populate_vect(c2_hsh, clust_2_);
//
int max_clust_1 = 0;
for(int i = 0; i < (int)clust_1_.size(); i++) {
if(clust_1_[i] > max_clust_1) {
max_clust_1 = clust_1_[i];
}
}
int max_clust_2 = 0;
for(int i = 0; i < (int)clust_2_.size(); i++) {
if(clust_2_[i] > max_clust_2) {
max_clust_2 = clust_2_[i];
}
}
// set up clust_id => [id_1, id_2, ...]
clust_map_1_.resize(max_clust_1+1);
clust_map_2_.resize(max_clust_2+1);
//
for(int i = 0; i < (int)clust_1_.size(); i++) {
clust_map_1_[clust_1_[i]].push_back(i);
}
for(int i = 0; i < (int)clust_2_.size(); i++) {
clust_map_2_[clust_2_[i]].push_back(i);
}
//
compute_confusion_matrix();
}
/**
* given a ruby hash, populate a vector of read_id as index, cluster_id as value
*/
void ConfusionMatrix::populate_vect(Rice::Hash &hsh,
std::vector<int> &clust_v) {
int len = hsh.size();
clust_v.resize(len);
//
Rice::Hash::iterator it = hsh.begin();
Rice::Hash::iterator it_end = hsh.end();
int i = 0;
for(; it != it_end; ++it) {
Rice::Hash::Entry en(*it);
int x = FIX2INT(en.key);
int y = FIX2INT(en.value.value());
clust_v[x] = y;
i++;
}
}
/**
* compute confusion matrix entries a, b, c, and d
*/
void ConfusionMatrix::compute_confusion_matrix() {
std::pair<int,int> v1 = int_and_diff(clust_1_, clust_map_2_);
std::pair<int,int> v2 = int_and_diff(clust_2_, clust_map_1_);
//
int n = (int)clust_1_.size();
a_ = v1.first;
c_ = v1.second;
d_ = v2.first;
b_ = ((n*(n-1))/2) - (a_+c_+d_);
}
/**
* return Rand index: (a+b)/(a+b+c+d)
*/
double ConfusionMatrix::get_rand_index() {
return (double)(a_+b_)/(double)(a_+b_+c_+d_);
}
/**
* return Jaccard index: a/(a+c+d)
*/
double ConfusionMatrix::get_jaccard_index() {
return (double)(a_)/(double)(a_+c_+d_);
}
/**
* returns Fowlkes-Mallows (FM) index: a/sqrt((a+c)*(a+d))
*/
double ConfusionMatrix::get_fm_index() {
double d1 = (double)(a_+c_);
double d2 = (double)(a_+d_);
return (double)a_/sqrt(d1*d2);
}
/**
* get counts of: <intersection, difference> between the vector of
* cluster assignments (A) and cluster assignment groupings (B)
*/
std::pair<int,int> ConfusionMatrix::int_and_diff(std::vector<int> clust_v,
std::vector<std::vector<int>> clust_map) {
//
int intsect = 0;
int diff = 0;
for(int i = 0; i < (int)clust_map.size(); i++) {
//
std::vector<int> vs = clust_map[i];
int len = (int) vs.size();
for(int i = 0; i < len; i++) {
int val_i = vs[i];
for(int j = 0; j < len; j++) {
if(i < j) {
int val_j = vs[j];
bool t1 = clust_v[val_i] == clust_v[val_j];
if(t1) { intsect++; }
else { diff++; }
}
}
}
}
//
return std::pair<int,int>(intsect, diff);
}
<commit_msg>added temp cout statement<commit_after>#include "ConfusionMatrix.hpp"
/**
*
*/
ConfusionMatrix::ConfusionMatrix() {
a_ = 0;
b_ = 0;
c_ = 0;
d_ = 0;
}
/**
*
*/
ConfusionMatrix::~ConfusionMatrix() {}
/**
* each ruby hash are pairs of {read_id => clust_id}
*/
ConfusionMatrix::ConfusionMatrix(Rice::Hash c1_hsh, Rice::Hash c2_hsh) {
a_ = 0;
b_ = 0;
c_ = 0;
d_ = 0;
populate_vect(c1_hsh, clust_1_);
populate_vect(c2_hsh, clust_2_);
//
int max_clust_1 = 0;
for(int i = 0; i < (int)clust_1_.size(); i++) {
if(clust_1_[i] > max_clust_1) {
max_clust_1 = clust_1_[i];
}
}
int max_clust_2 = 0;
for(int i = 0; i < (int)clust_2_.size(); i++) {
if(clust_2_[i] > max_clust_2) {
max_clust_2 = clust_2_[i];
}
}
// set up clust_id => [id_1, id_2, ...]
clust_map_1_.resize(max_clust_1+1);
clust_map_2_.resize(max_clust_2+1);
//
for(int i = 0; i < (int)clust_1_.size(); i++) {
clust_map_1_[clust_1_[i]].push_back(i);
}
for(int i = 0; i < (int)clust_2_.size(); i++) {
clust_map_2_[clust_2_[i]].push_back(i);
}
//
compute_confusion_matrix();
}
/**
* given a ruby hash, populate a vector of read_id as index, cluster_id as value
*/
void ConfusionMatrix::populate_vect(Rice::Hash &hsh,
std::vector<int> &clust_v) {
int len = hsh.size();
clust_v.resize(len);
//
Rice::Hash::iterator it = hsh.begin();
Rice::Hash::iterator it_end = hsh.end();
int i = 0;
for(; it != it_end; ++it) {
Rice::Hash::Entry en(*it);
int x = FIX2INT(en.key);
int y = FIX2INT(en.value.value());
clust_v[x] = y;
i++;
}
}
/**
* compute confusion matrix entries a, b, c, and d
*/
void ConfusionMatrix::compute_confusion_matrix() {
std::pair<int,int> v1 = int_and_diff(clust_1_, clust_map_2_);
std::pair<int,int> v2 = int_and_diff(clust_2_, clust_map_1_);
//
int n = (int)clust_1_.size();
a_ = v1.first;
c_ = v1.second;
d_ = v2.first;
b_ = ((n*(n-1))/2) - (a_+c_+d_);
std::cout<<a_<<"\t"<<b_<<"\t"<<c_<<"\t"<<d_<<std::endl;
}
/**
* return Rand index: (a+b)/(a+b+c+d)
*/
double ConfusionMatrix::get_rand_index() {
return (double)(a_+b_)/(double)(a_+b_+c_+d_);
}
/**
* return Jaccard index: a/(a+c+d)
*/
double ConfusionMatrix::get_jaccard_index() {
return (double)(a_)/(double)(a_+c_+d_);
}
/**
* returns Fowlkes-Mallows (FM) index: a/sqrt((a+c)*(a+d))
*/
double ConfusionMatrix::get_fm_index() {
double d1 = (double)(a_+c_);
double d2 = (double)(a_+d_);
return (double)a_/sqrt(d1*d2);
}
/**
* get counts of: <intersection, difference> between the vector of
* cluster assignments (A) and cluster assignment groupings (B)
*/
std::pair<int,int> ConfusionMatrix::int_and_diff(std::vector<int> clust_v,
std::vector<std::vector<int>> clust_map) {
//
int intsect = 0;
int diff = 0;
for(int i = 0; i < (int)clust_map.size(); i++) {
//
std::vector<int> vs = clust_map[i];
int len = (int) vs.size();
for(int i = 0; i < len; i++) {
int val_i = vs[i];
for(int j = 0; j < len; j++) {
if(i < j) {
int val_j = vs[j];
bool t1 = clust_v[val_i] == clust_v[val_j];
if(t1) { intsect++; }
else { diff++; }
}
}
}
}
//
return std::pair<int,int>(intsect, diff);
}
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/lattice/behavior/feasible_region.h"
#include <cmath>
#include "glog/logging.h"
#include "modules/planning/common/planning_gflags.h"
namespace apollo {
namespace planning {
FeasibleRegion::FeasibleRegion(const std::array<double, 3>& init_s,
const double speed_limit) {
Setup(init_s, speed_limit);
}
void FeasibleRegion::Setup(const std::array<double, 3>& init_s,
const double speed_limit) {
init_s_ = init_s;
speed_limit_ = speed_limit;
double v = init_s[1];
CHECK(v >= 0.0);
const double max_deceleration = -FLAGS_longitudinal_acceleration_lower_bound;
t_at_zero_speed_ = v / max_deceleration;
s_at_zero_speed_ = init_s[0] + v * v / (2.0 * max_deceleration);
double delta_v = std::abs(v - speed_limit);
if (v < speed_limit) {
t_at_speed_limit_ = delta_v / FLAGS_longitudinal_acceleration_upper_bound;
s_at_speed_limit_ = init_s_[0] + v * t_at_speed_limit_ +
0.5 * FLAGS_longitudinal_acceleration_upper_bound *
t_at_speed_limit_ * t_at_speed_limit_;
} else {
t_at_speed_limit_ = 0.0;
s_at_speed_limit_ = init_s_[0];
}
}
double FeasibleRegion::SUpper(const double t) const {
CHECK(t >= 0.0);
if (init_s_[1] < speed_limit_) {
if (t < t_at_speed_limit_) {
return init_s_[0] + init_s_[1] * t +
0.5 * FLAGS_longitudinal_acceleration_upper_bound * t * t;
} else {
return s_at_speed_limit_ + speed_limit_ * (t - t_at_speed_limit_);
}
} else {
return init_s_[0] + init_s_[1] * t;
}
}
double FeasibleRegion::SLower(const double t) const {
if (t < t_at_zero_speed_) {
return init_s_[0] + init_s_[1] * t +
0.5 * FLAGS_longitudinal_acceleration_lower_bound * t * t;
}
return s_at_zero_speed_;
}
double FeasibleRegion::VUpper(const double t) const {
return std::max(
init_s_[1],
std::min(init_s_[1] + FLAGS_longitudinal_acceleration_upper_bound * t,
speed_limit_));
}
double FeasibleRegion::VLower(const double t) const {
return t < t_at_zero_speed_
? init_s_[1] + FLAGS_longitudinal_acceleration_lower_bound * t
: 0.0;
}
double FeasibleRegion::TLower(const double s) const {
CHECK(s >= init_s_[0]);
if (init_s_[1] < speed_limit_) {
if (s < s_at_speed_limit_) {
double delta =
init_s_[1] * init_s_[1] -
2.0 * FLAGS_longitudinal_acceleration_upper_bound * (init_s_[0] - s);
return (std::sqrt(delta) - init_s_[1]) /
FLAGS_longitudinal_acceleration_upper_bound;
} else {
return t_at_speed_limit_ + (s - s_at_speed_limit_) / speed_limit_;
}
} else {
return (s - init_s_[0]) / init_s_[1];
}
}
} // namespace planning
} // namespace apollo
<commit_msg>Planning: fix lattice feasible region<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/**
* @file
**/
#include "modules/planning/lattice/behavior/feasible_region.h"
#include <cmath>
#include "glog/logging.h"
#include "modules/planning/common/planning_gflags.h"
namespace apollo {
namespace planning {
FeasibleRegion::FeasibleRegion(const std::array<double, 3>& init_s,
const double speed_limit) {
Setup(init_s, speed_limit);
}
void FeasibleRegion::Setup(const std::array<double, 3>& init_s,
const double speed_limit) {
init_s_ = init_s;
speed_limit_ = speed_limit;
double v = init_s[1];
CHECK(v >= 0.0);
const double max_deceleration = -FLAGS_longitudinal_acceleration_lower_bound;
t_at_zero_speed_ = v / max_deceleration;
s_at_zero_speed_ = init_s[0] + v * v / (2.0 * max_deceleration);
double delta_v = speed_limit - v;
if (delta_v < 0.0) {
t_at_speed_limit_ = delta_v / FLAGS_longitudinal_acceleration_lower_bound;
s_at_speed_limit_ = init_s_[0] + v * t_at_speed_limit_ +
0.5 * FLAGS_longitudinal_acceleration_lower_bound *
t_at_speed_limit_ * t_at_speed_limit_;
} else {
t_at_speed_limit_ = delta_v / FLAGS_longitudinal_acceleration_upper_bound;
s_at_speed_limit_ = init_s_[0] + v * t_at_speed_limit_ +
0.5 * FLAGS_longitudinal_acceleration_upper_bound *
t_at_speed_limit_ * t_at_speed_limit_;
}
}
double FeasibleRegion::SUpper(const double t) const {
CHECK(t >= 0.0);
if (init_s_[1] < speed_limit_) {
if (t < t_at_speed_limit_) {
return init_s_[0] + init_s_[1] * t +
0.5 * FLAGS_longitudinal_acceleration_upper_bound * t * t;
} else {
return s_at_speed_limit_ + speed_limit_ * (t - t_at_speed_limit_);
}
} else {
return init_s_[0] + init_s_[1] * t;
}
}
double FeasibleRegion::SLower(const double t) const {
if (t < t_at_zero_speed_) {
return init_s_[0] + init_s_[1] * t +
0.5 * FLAGS_longitudinal_acceleration_lower_bound * t * t;
}
return s_at_zero_speed_;
}
double FeasibleRegion::VUpper(const double t) const {
return std::max(
init_s_[1],
std::min(init_s_[1] + FLAGS_longitudinal_acceleration_upper_bound * t,
speed_limit_));
}
double FeasibleRegion::VLower(const double t) const {
return t < t_at_zero_speed_
? init_s_[1] + FLAGS_longitudinal_acceleration_lower_bound * t
: 0.0;
}
double FeasibleRegion::TLower(const double s) const {
CHECK(s >= init_s_[0]);
if (init_s_[1] < speed_limit_) {
if (s < s_at_speed_limit_) {
double delta =
init_s_[1] * init_s_[1] -
2.0 * FLAGS_longitudinal_acceleration_upper_bound * (init_s_[0] - s);
return (std::sqrt(delta) - init_s_[1]) /
FLAGS_longitudinal_acceleration_upper_bound;
} else {
return t_at_speed_limit_ + (s - s_at_speed_limit_) / speed_limit_;
}
} else {
return (s - init_s_[0]) / init_s_[1];
}
}
} // namespace planning
} // namespace apollo
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2020, John Haddon. 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 John Haddon nor the names of
// any other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "GafferScene/PrimitiveSampler.h"
#include "GafferScene/SceneAlgo.h"
#include "Gaffer/Private/IECorePreview/ParallelAlgo.h"
#include "IECoreScene/MeshAlgo.h"
#include "IECoreScene/MeshPrimitive.h"
#include "IECoreScene/PrimitiveEvaluator.h"
#include "tbb/parallel_for.h"
using namespace std;
using namespace tbb;
using namespace Imath;
using namespace IECore;
using namespace IECoreScene;
using namespace Gaffer;
using namespace GafferScene;
//////////////////////////////////////////////////////////////////////////
// Internal utilities
//////////////////////////////////////////////////////////////////////////
namespace
{
using OutputVariableFunction = std::function<void ( size_t, const PrimitiveEvaluator::Result & )>;
M44f matrix( const M44f &transform, GeometricData::Interpretation interpretation )
{
switch( interpretation )
{
case GeometricData::Point :
return transform;
case GeometricData::Vector : {
// Don't apply translation to vectors.
M44f x = transform;
x[3][0] = x[3][1] = x[3][2] = 0.0f;
return x;
}
case GeometricData::Normal : {
// Use the transpose of the inverse
// for transforming normals. Also,
// don't apply translation.
M44f x = transform;
x[3][0] = x[3][1] = x[3][2] = 0.0f;
x = x.inverse();
x.transpose();
return x;
}
default :
return M44f();
}
}
OutputVariableFunction addPrimitiveVariable( Primitive *outputPrimitive, const std::string &name, const PrimitiveVariable &sourceVariable, PrimitiveVariable::Interpolation outputInterpolation, const M44f &transform )
{
const size_t size = outputPrimitive->variableSize( outputInterpolation );
switch( sourceVariable.data->typeId() )
{
case V3fVectorDataTypeId : {
V3fVectorDataPtr data = new V3fVectorData;
data->writable().resize( size, V3f( 0 ) );
const GeometricData::Interpretation interpretation = static_cast<const V3fVectorData *>( sourceVariable.data.get() )->getInterpretation();
data->setInterpretation( interpretation );
outputPrimitive->variables[name] = PrimitiveVariable( outputInterpolation, data );
V3f *d = data->writable().data();
const M44f m = matrix( transform, interpretation );
return [d, &sourceVariable, m ] ( size_t index, const PrimitiveEvaluator::Result &result ) {
d[index] = result.vectorPrimVar( sourceVariable ) * m;
};
}
case V2fVectorDataTypeId : {
V2fVectorDataPtr data = new V2fVectorData;
data->writable().resize( size, V2f( 0 ) );
data->setInterpretation( static_cast<const V2fVectorData *>( sourceVariable.data.get() )->getInterpretation() );
outputPrimitive->variables[name] = PrimitiveVariable( outputInterpolation, data );
V2f *d = data->writable().data();
return [d, &sourceVariable] ( size_t index, const PrimitiveEvaluator::Result &result ) {
d[index] = result.vec2PrimVar( sourceVariable );
};
}
case Color3fVectorDataTypeId : {
Color3fVectorDataPtr data = new Color3fVectorData;
data->writable().resize( size, Color3f( 0 ) );
outputPrimitive->variables[name] = PrimitiveVariable( outputInterpolation, data );
Color3f *d = data->writable().data();
return [d, &sourceVariable] ( size_t index, const PrimitiveEvaluator::Result &result ) {
d[index] = result.colorPrimVar( sourceVariable );
};
}
case FloatVectorDataTypeId : {
FloatVectorDataPtr data = new FloatVectorData;
data->writable().resize( size, 0 );
outputPrimitive->variables[name] = PrimitiveVariable( outputInterpolation, data );
float *d = data->writable().data();
return [d, &sourceVariable] ( size_t index, const PrimitiveEvaluator::Result &result ) {
d[index] = result.floatPrimVar( sourceVariable );
};
}
case IntVectorDataTypeId : {
IntVectorDataPtr data = new IntVectorData;
data->writable().resize( size, 0 );
outputPrimitive->variables[name] = PrimitiveVariable( outputInterpolation, data );
int *d = data->writable().data();
return [d, &sourceVariable] ( size_t index, const PrimitiveEvaluator::Result &result ) {
d[index] = result.intPrimVar( sourceVariable );
};
}
default :
// Unsupported type
return OutputVariableFunction();
};
}
} // namespace
//////////////////////////////////////////////////////////////////////////
// Sampler
//////////////////////////////////////////////////////////////////////////
GAFFER_GRAPHCOMPONENT_DEFINE_TYPE( PrimitiveSampler );
size_t PrimitiveSampler::g_firstPlugIndex = 0;
PrimitiveSampler::PrimitiveSampler( const std::string &name )
: Deformer( name )
{
storeIndexOfNextChild( g_firstPlugIndex );
addChild( new ScenePlug( "source" ) );
addChild( new StringPlug( "sourceLocation" ) );
addChild( new StringPlug( "primitiveVariables" ) );
addChild( new StringPlug( "prefix" ) );
addChild( new StringPlug( "status" ) );
}
PrimitiveSampler::~PrimitiveSampler()
{
}
ScenePlug *PrimitiveSampler::sourcePlug()
{
return getChild<ScenePlug>( g_firstPlugIndex );
}
const ScenePlug *PrimitiveSampler::sourcePlug() const
{
return getChild<ScenePlug>( g_firstPlugIndex );
}
Gaffer::StringPlug *PrimitiveSampler::sourceLocationPlug()
{
return getChild<StringPlug>( g_firstPlugIndex + 1 );
}
const Gaffer::StringPlug *PrimitiveSampler::sourceLocationPlug() const
{
return getChild<StringPlug>( g_firstPlugIndex + 1 );
}
Gaffer::StringPlug *PrimitiveSampler::primitiveVariablesPlug()
{
return getChild<StringPlug>( g_firstPlugIndex + 2 );
}
const Gaffer::StringPlug *PrimitiveSampler::primitiveVariablesPlug() const
{
return getChild<StringPlug>( g_firstPlugIndex + 2 );
}
Gaffer::StringPlug *PrimitiveSampler::prefixPlug()
{
return getChild<StringPlug>( g_firstPlugIndex + 3 );
}
const Gaffer::StringPlug *PrimitiveSampler::prefixPlug() const
{
return getChild<StringPlug>( g_firstPlugIndex + 3 );
}
Gaffer::StringPlug *PrimitiveSampler::statusPlug()
{
return getChild<StringPlug>( g_firstPlugIndex + 4 );
}
const Gaffer::StringPlug *PrimitiveSampler::statusPlug() const
{
return getChild<StringPlug>( g_firstPlugIndex + 4 );
}
bool PrimitiveSampler::affectsProcessedObject( const Gaffer::Plug *input ) const
{
return
Deformer::affectsProcessedObject( input ) ||
input == sourcePlug() ||
input == sourceLocationPlug() ||
input == primitiveVariablesPlug() ||
input == prefixPlug() ||
input == statusPlug() ||
input == sourcePlug()->objectPlug() ||
input == inPlug()->transformPlug() ||
input == sourcePlug()->transformPlug() ||
affectsSamplingFunction( input )
;
}
void PrimitiveSampler::hashProcessedObject( const ScenePath &path, const Gaffer::Context *context, IECore::MurmurHash &h ) const
{
PrimitiveSampler::Deformer::hashProcessedObject( path, context, h );
const string sourceLocation = sourceLocationPlug()->getValue();
const string primitiveVariables = primitiveVariablesPlug()->getValue();
const string status = statusPlug()->getValue();
if( sourceLocation.empty() || ( primitiveVariables.empty() && status.empty() ) )
{
return;
}
ScenePlug::ScenePath sourcePath;
ScenePlug::stringToPath( sourceLocation, sourcePath );
if( !SceneAlgo::exists( sourcePlug(), sourcePath ) )
{
return;
}
h.append( sourcePlug()->objectHash( sourcePath ) );
h.append( primitiveVariables );
prefixPlug()->hash( h );
h.append( status );
h.append( inPlug()->fullTransformHash( path ) );
h.append( sourcePlug()->fullTransformHash( sourcePath ) );
hashSamplingFunction( h );
}
IECore::ConstObjectPtr PrimitiveSampler::computeProcessedObject( const ScenePath &path, const Gaffer::Context *context, const IECore::Object *inputObject ) const
{
const Primitive *inputPrimitive = runTimeCast<const Primitive>( inputObject );
if( !inputPrimitive )
{
return inputObject;
}
const string sourceLocation = sourceLocationPlug()->getValue();
const string primitiveVariables = primitiveVariablesPlug()->getValue();
const string status = statusPlug()->getValue();
if( sourceLocation.empty() || ( primitiveVariables.empty() && status.empty() ) )
{
return inputObject;
}
PrimitiveVariable::Interpolation outputInterpolation = PrimitiveVariable::Invalid;
SamplingFunction samplingFunction = computeSamplingFunction( inputPrimitive, outputInterpolation );
if( !samplingFunction || outputInterpolation == PrimitiveVariable::Invalid )
{
return inputObject;
}
ScenePlug::ScenePath sourcePath;
ScenePlug::stringToPath( sourceLocation, sourcePath );
if( !SceneAlgo::exists( sourcePlug(), sourcePath ) )
{
return inputObject;
}
ConstObjectPtr sourceObject = sourcePlug()->object( sourcePath );
const Primitive *sourcePrimitive = runTimeCast<const Primitive>( sourceObject.get() );
if( !sourcePrimitive )
{
return inputObject;
}
ConstPrimitivePtr preprocessedSourcePrimitive = sourcePrimitive;
if( auto mesh = runTimeCast<const MeshPrimitive>( preprocessedSourcePrimitive.get() ) )
{
preprocessedSourcePrimitive = MeshAlgo::triangulate( mesh );
}
PrimitiveEvaluatorPtr evaluator = PrimitiveEvaluator::create( preprocessedSourcePrimitive );
if( !evaluator )
{
return inputObject;
}
PrimitivePtr outputPrimitive = inputPrimitive->copy();
const size_t size = outputPrimitive->variableSize( outputInterpolation );
const string prefix = prefixPlug()->getValue();
const M44f transform = inPlug()->fullTransform( path );
const M44f sourceTransform = sourcePlug()->fullTransform( sourcePath );
const M44f primitiveVariableTransform = sourceTransform * transform.inverse();
vector<OutputVariableFunction> outputVariables;
for( auto &p : preprocessedSourcePrimitive->variables )
{
if( !StringAlgo::matchMultiple( p.first, primitiveVariables ) )
{
continue;
}
if( auto o = addPrimitiveVariable( outputPrimitive.get(), prefix + p.first, p.second, outputInterpolation, primitiveVariableTransform ) )
{
outputVariables.push_back( o );
}
}
BoolVectorDataPtr statusData;
if( !status.empty() )
{
statusData = new BoolVectorData();
statusData->writable().resize( size, false );
outputPrimitive->variables[status] = PrimitiveVariable( outputInterpolation, statusData );
}
const M44f samplingTransform = transform * sourceTransform.inverse();
auto rangeSampler = [&]( const blocked_range<size_t> &r ) {
PrimitiveEvaluator::ResultPtr evaluatorResult = evaluator->createResult();
for( size_t i = r.begin(); i != r.end(); ++i )
{
Canceller::check( context->canceller() );
if( samplingFunction( *evaluator, i, samplingTransform, *evaluatorResult ) )
{
for( const auto &o : outputVariables )
{
o( i, *evaluatorResult );
}
if( statusData )
{
statusData->writable()[i] = true;
}
}
}
};
/// \todo We should be implementing `ComputeNode::computeCachePolicy()` instead
/// of doing our own isolation here, and we might even prefer the `TaskCollaboration`
/// that would provide. But we might also be filtered to only affect a single
/// object in an entire scene, and it seems that changing cache policy for
/// `outPlug()->objectPlug()` might give unwanted overhead for the pass-through
/// computations (particulary if we used `TaskCollaboration`). We might be able to
/// deal with this in ObjectProcessor by performing the non-pass-through computations
/// on an internal plug with a custom policy. But we leave that for another time.
IECorePreview::ParallelAlgo::isolate(
[&] () {
tbb::task_group_context taskGroupContext( tbb::task_group_context::isolated );
parallel_for( blocked_range<size_t>( 0, size ), rangeSampler, taskGroupContext );
}
);
return outputPrimitive;
}
bool PrimitiveSampler::adjustBounds() const
{
return
Deformer::adjustBounds() &&
prefixPlug()->getValue().empty() &&
StringAlgo::matchMultiple( "P", primitiveVariablesPlug()->getValue() )
;
}
bool PrimitiveSampler::affectsSamplingFunction( const Gaffer::Plug *input ) const
{
return false;
}
void PrimitiveSampler::hashSamplingFunction( IECore::MurmurHash &h ) const
{
}
<commit_msg>PrimitiveSampler : Remove redundant namespacing<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2020, John Haddon. 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 John Haddon nor the names of
// any other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "GafferScene/PrimitiveSampler.h"
#include "GafferScene/SceneAlgo.h"
#include "Gaffer/Private/IECorePreview/ParallelAlgo.h"
#include "IECoreScene/MeshAlgo.h"
#include "IECoreScene/MeshPrimitive.h"
#include "IECoreScene/PrimitiveEvaluator.h"
#include "tbb/parallel_for.h"
using namespace std;
using namespace tbb;
using namespace Imath;
using namespace IECore;
using namespace IECoreScene;
using namespace Gaffer;
using namespace GafferScene;
//////////////////////////////////////////////////////////////////////////
// Internal utilities
//////////////////////////////////////////////////////////////////////////
namespace
{
using OutputVariableFunction = std::function<void ( size_t, const PrimitiveEvaluator::Result & )>;
M44f matrix( const M44f &transform, GeometricData::Interpretation interpretation )
{
switch( interpretation )
{
case GeometricData::Point :
return transform;
case GeometricData::Vector : {
// Don't apply translation to vectors.
M44f x = transform;
x[3][0] = x[3][1] = x[3][2] = 0.0f;
return x;
}
case GeometricData::Normal : {
// Use the transpose of the inverse
// for transforming normals. Also,
// don't apply translation.
M44f x = transform;
x[3][0] = x[3][1] = x[3][2] = 0.0f;
x = x.inverse();
x.transpose();
return x;
}
default :
return M44f();
}
}
OutputVariableFunction addPrimitiveVariable( Primitive *outputPrimitive, const std::string &name, const PrimitiveVariable &sourceVariable, PrimitiveVariable::Interpolation outputInterpolation, const M44f &transform )
{
const size_t size = outputPrimitive->variableSize( outputInterpolation );
switch( sourceVariable.data->typeId() )
{
case V3fVectorDataTypeId : {
V3fVectorDataPtr data = new V3fVectorData;
data->writable().resize( size, V3f( 0 ) );
const GeometricData::Interpretation interpretation = static_cast<const V3fVectorData *>( sourceVariable.data.get() )->getInterpretation();
data->setInterpretation( interpretation );
outputPrimitive->variables[name] = PrimitiveVariable( outputInterpolation, data );
V3f *d = data->writable().data();
const M44f m = matrix( transform, interpretation );
return [d, &sourceVariable, m ] ( size_t index, const PrimitiveEvaluator::Result &result ) {
d[index] = result.vectorPrimVar( sourceVariable ) * m;
};
}
case V2fVectorDataTypeId : {
V2fVectorDataPtr data = new V2fVectorData;
data->writable().resize( size, V2f( 0 ) );
data->setInterpretation( static_cast<const V2fVectorData *>( sourceVariable.data.get() )->getInterpretation() );
outputPrimitive->variables[name] = PrimitiveVariable( outputInterpolation, data );
V2f *d = data->writable().data();
return [d, &sourceVariable] ( size_t index, const PrimitiveEvaluator::Result &result ) {
d[index] = result.vec2PrimVar( sourceVariable );
};
}
case Color3fVectorDataTypeId : {
Color3fVectorDataPtr data = new Color3fVectorData;
data->writable().resize( size, Color3f( 0 ) );
outputPrimitive->variables[name] = PrimitiveVariable( outputInterpolation, data );
Color3f *d = data->writable().data();
return [d, &sourceVariable] ( size_t index, const PrimitiveEvaluator::Result &result ) {
d[index] = result.colorPrimVar( sourceVariable );
};
}
case FloatVectorDataTypeId : {
FloatVectorDataPtr data = new FloatVectorData;
data->writable().resize( size, 0 );
outputPrimitive->variables[name] = PrimitiveVariable( outputInterpolation, data );
float *d = data->writable().data();
return [d, &sourceVariable] ( size_t index, const PrimitiveEvaluator::Result &result ) {
d[index] = result.floatPrimVar( sourceVariable );
};
}
case IntVectorDataTypeId : {
IntVectorDataPtr data = new IntVectorData;
data->writable().resize( size, 0 );
outputPrimitive->variables[name] = PrimitiveVariable( outputInterpolation, data );
int *d = data->writable().data();
return [d, &sourceVariable] ( size_t index, const PrimitiveEvaluator::Result &result ) {
d[index] = result.intPrimVar( sourceVariable );
};
}
default :
// Unsupported type
return OutputVariableFunction();
};
}
} // namespace
//////////////////////////////////////////////////////////////////////////
// Sampler
//////////////////////////////////////////////////////////////////////////
GAFFER_GRAPHCOMPONENT_DEFINE_TYPE( PrimitiveSampler );
size_t PrimitiveSampler::g_firstPlugIndex = 0;
PrimitiveSampler::PrimitiveSampler( const std::string &name )
: Deformer( name )
{
storeIndexOfNextChild( g_firstPlugIndex );
addChild( new ScenePlug( "source" ) );
addChild( new StringPlug( "sourceLocation" ) );
addChild( new StringPlug( "primitiveVariables" ) );
addChild( new StringPlug( "prefix" ) );
addChild( new StringPlug( "status" ) );
}
PrimitiveSampler::~PrimitiveSampler()
{
}
ScenePlug *PrimitiveSampler::sourcePlug()
{
return getChild<ScenePlug>( g_firstPlugIndex );
}
const ScenePlug *PrimitiveSampler::sourcePlug() const
{
return getChild<ScenePlug>( g_firstPlugIndex );
}
Gaffer::StringPlug *PrimitiveSampler::sourceLocationPlug()
{
return getChild<StringPlug>( g_firstPlugIndex + 1 );
}
const Gaffer::StringPlug *PrimitiveSampler::sourceLocationPlug() const
{
return getChild<StringPlug>( g_firstPlugIndex + 1 );
}
Gaffer::StringPlug *PrimitiveSampler::primitiveVariablesPlug()
{
return getChild<StringPlug>( g_firstPlugIndex + 2 );
}
const Gaffer::StringPlug *PrimitiveSampler::primitiveVariablesPlug() const
{
return getChild<StringPlug>( g_firstPlugIndex + 2 );
}
Gaffer::StringPlug *PrimitiveSampler::prefixPlug()
{
return getChild<StringPlug>( g_firstPlugIndex + 3 );
}
const Gaffer::StringPlug *PrimitiveSampler::prefixPlug() const
{
return getChild<StringPlug>( g_firstPlugIndex + 3 );
}
Gaffer::StringPlug *PrimitiveSampler::statusPlug()
{
return getChild<StringPlug>( g_firstPlugIndex + 4 );
}
const Gaffer::StringPlug *PrimitiveSampler::statusPlug() const
{
return getChild<StringPlug>( g_firstPlugIndex + 4 );
}
bool PrimitiveSampler::affectsProcessedObject( const Gaffer::Plug *input ) const
{
return
Deformer::affectsProcessedObject( input ) ||
input == sourcePlug() ||
input == sourceLocationPlug() ||
input == primitiveVariablesPlug() ||
input == prefixPlug() ||
input == statusPlug() ||
input == sourcePlug()->objectPlug() ||
input == inPlug()->transformPlug() ||
input == sourcePlug()->transformPlug() ||
affectsSamplingFunction( input )
;
}
void PrimitiveSampler::hashProcessedObject( const ScenePath &path, const Gaffer::Context *context, IECore::MurmurHash &h ) const
{
Deformer::hashProcessedObject( path, context, h );
const string sourceLocation = sourceLocationPlug()->getValue();
const string primitiveVariables = primitiveVariablesPlug()->getValue();
const string status = statusPlug()->getValue();
if( sourceLocation.empty() || ( primitiveVariables.empty() && status.empty() ) )
{
return;
}
ScenePlug::ScenePath sourcePath;
ScenePlug::stringToPath( sourceLocation, sourcePath );
if( !SceneAlgo::exists( sourcePlug(), sourcePath ) )
{
return;
}
h.append( sourcePlug()->objectHash( sourcePath ) );
h.append( primitiveVariables );
prefixPlug()->hash( h );
h.append( status );
h.append( inPlug()->fullTransformHash( path ) );
h.append( sourcePlug()->fullTransformHash( sourcePath ) );
hashSamplingFunction( h );
}
IECore::ConstObjectPtr PrimitiveSampler::computeProcessedObject( const ScenePath &path, const Gaffer::Context *context, const IECore::Object *inputObject ) const
{
const Primitive *inputPrimitive = runTimeCast<const Primitive>( inputObject );
if( !inputPrimitive )
{
return inputObject;
}
const string sourceLocation = sourceLocationPlug()->getValue();
const string primitiveVariables = primitiveVariablesPlug()->getValue();
const string status = statusPlug()->getValue();
if( sourceLocation.empty() || ( primitiveVariables.empty() && status.empty() ) )
{
return inputObject;
}
PrimitiveVariable::Interpolation outputInterpolation = PrimitiveVariable::Invalid;
SamplingFunction samplingFunction = computeSamplingFunction( inputPrimitive, outputInterpolation );
if( !samplingFunction || outputInterpolation == PrimitiveVariable::Invalid )
{
return inputObject;
}
ScenePlug::ScenePath sourcePath;
ScenePlug::stringToPath( sourceLocation, sourcePath );
if( !SceneAlgo::exists( sourcePlug(), sourcePath ) )
{
return inputObject;
}
ConstObjectPtr sourceObject = sourcePlug()->object( sourcePath );
const Primitive *sourcePrimitive = runTimeCast<const Primitive>( sourceObject.get() );
if( !sourcePrimitive )
{
return inputObject;
}
ConstPrimitivePtr preprocessedSourcePrimitive = sourcePrimitive;
if( auto mesh = runTimeCast<const MeshPrimitive>( preprocessedSourcePrimitive.get() ) )
{
preprocessedSourcePrimitive = MeshAlgo::triangulate( mesh );
}
PrimitiveEvaluatorPtr evaluator = PrimitiveEvaluator::create( preprocessedSourcePrimitive );
if( !evaluator )
{
return inputObject;
}
PrimitivePtr outputPrimitive = inputPrimitive->copy();
const size_t size = outputPrimitive->variableSize( outputInterpolation );
const string prefix = prefixPlug()->getValue();
const M44f transform = inPlug()->fullTransform( path );
const M44f sourceTransform = sourcePlug()->fullTransform( sourcePath );
const M44f primitiveVariableTransform = sourceTransform * transform.inverse();
vector<OutputVariableFunction> outputVariables;
for( auto &p : preprocessedSourcePrimitive->variables )
{
if( !StringAlgo::matchMultiple( p.first, primitiveVariables ) )
{
continue;
}
if( auto o = addPrimitiveVariable( outputPrimitive.get(), prefix + p.first, p.second, outputInterpolation, primitiveVariableTransform ) )
{
outputVariables.push_back( o );
}
}
BoolVectorDataPtr statusData;
if( !status.empty() )
{
statusData = new BoolVectorData();
statusData->writable().resize( size, false );
outputPrimitive->variables[status] = PrimitiveVariable( outputInterpolation, statusData );
}
const M44f samplingTransform = transform * sourceTransform.inverse();
auto rangeSampler = [&]( const blocked_range<size_t> &r ) {
PrimitiveEvaluator::ResultPtr evaluatorResult = evaluator->createResult();
for( size_t i = r.begin(); i != r.end(); ++i )
{
Canceller::check( context->canceller() );
if( samplingFunction( *evaluator, i, samplingTransform, *evaluatorResult ) )
{
for( const auto &o : outputVariables )
{
o( i, *evaluatorResult );
}
if( statusData )
{
statusData->writable()[i] = true;
}
}
}
};
/// \todo We should be implementing `ComputeNode::computeCachePolicy()` instead
/// of doing our own isolation here, and we might even prefer the `TaskCollaboration`
/// that would provide. But we might also be filtered to only affect a single
/// object in an entire scene, and it seems that changing cache policy for
/// `outPlug()->objectPlug()` might give unwanted overhead for the pass-through
/// computations (particulary if we used `TaskCollaboration`). We might be able to
/// deal with this in ObjectProcessor by performing the non-pass-through computations
/// on an internal plug with a custom policy. But we leave that for another time.
IECorePreview::ParallelAlgo::isolate(
[&] () {
tbb::task_group_context taskGroupContext( tbb::task_group_context::isolated );
parallel_for( blocked_range<size_t>( 0, size ), rangeSampler, taskGroupContext );
}
);
return outputPrimitive;
}
bool PrimitiveSampler::adjustBounds() const
{
return
Deformer::adjustBounds() &&
prefixPlug()->getValue().empty() &&
StringAlgo::matchMultiple( "P", primitiveVariablesPlug()->getValue() )
;
}
bool PrimitiveSampler::affectsSamplingFunction( const Gaffer::Plug *input ) const
{
return false;
}
void PrimitiveSampler::hashSamplingFunction( IECore::MurmurHash &h ) const
{
}
<|endoftext|> |
<commit_before>// Copyright (c) 2019 by Robert Bosch GmbH. 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.
#pragma once
#include "iceoryx_utils/cxx/optional.hpp"
#include "iceoryx_utils/cxx/vector.hpp"
#include "iceoryx_utils/platform/acl.hpp"
#include <cstdint>
#include <functional>
#include <iostream>
#include <memory>
namespace iox
{
namespace posix
{
/// @brief abstraction class for the management of access control lists (ACLs).
///
/// ACLs allow to define fine-grained access rights for files. In addition to the standard access rights, which can only
/// distinguish between user/group/others, ACLs can be used to give specific access rights to named users and groups.
/// ACL is part of the posix specification. The AccessController class is used to store ACL permission entries and
/// provides a way to write those entries to a file. A permission entry can be seen as a combination of an access
/// Category, a Permission and an optional name (used to identify specific users and groups.)
class AccessController
{
public:
using string_t = std::string;
/// @brief maximum number of permission entries the AccessController can store
static constexpr int32_t MaxNumOfPermissions = 20;
/// @brief identifier for a permission entry (user, group, others, ...)
#if defined(QNX) || defined(QNX__) || defined(__QNX__)
enum class Category : std::underlying_type(acl_tag_t)
#else
enum class Category : acl_tag_t
#endif
{
USER = ACL_USER_OBJ,
/// a specific user must be identified by a name
SPECIFIC_USER = ACL_USER,
GROUP = ACL_GROUP_OBJ,
/// a specific group must be identified by a name
SPECIFIC_GROUP = ACL_GROUP,
OTHERS = ACL_OTHER,
};
/// @brief access right for a permission entry
#if defined(QNX) || defined(QNX__) || defined(__QNX__)
enum class Permission : std::underlying_type(acl_perm_t)
#else
enum class Permission : acl_perm_t
#endif
{
READ = ACL_READ,
WRITE = ACL_WRITE,
READWRITE = Permission::READ | Permission::WRITE,
NONE = 0
};
/// @brief define and store a specific permission entry to be used by writePermissionsToFile.
/// @param[f_id] id of the user or group. For Category::SPECIFIC_USER or Category::SPECIFIC_GROUP the id is
/// required. Otherwise writing the permission entry to a file will fail. For the default user/group/others
/// categories the id is ignored and can therefore be left empty. Do not forget to add permissions of the standard
/// user/group/others categories before writing to a file.
/// @param[f_permission] Permissions which should be applied to the category.
/// @param[f_id] The group or user id - depending on the category. For Category::USER, Category::GROUP and
/// Category::OTHER the f_id is not required for everything else a valid group or user id is mandatory.
bool addPermissionEntry(const Category f_category, const Permission f_permission, const unsigned int f_id = -1u);
/// @brief just like addPermissionEntry(Category, Permission, int) but using a name instead of an id.
bool addPermissionEntry(const Category f_category, const Permission f_permission, const string_t& f_name);
/// @brief Write permission entries stored by the AccessController to a file identified by a file descriptor.
/// @param[f_fileDescriptor] identifier for a file (can be regular file, shared memory file, message queue file...
/// everything is a file).
/// @return true if succesful. If false, you can assume that the file has not been touched at all.
bool writePermissionsToFile(const int f_fileDescriptor) const;
private:
using smartAclPointer_t = std::unique_ptr<std::remove_pointer<acl_t>::type, std::function<void(acl_t)>>;
struct PermissionEntry
{
unsigned int m_category;
Permission m_permission;
unsigned int m_id;
};
cxx::vector<PermissionEntry, MaxNumOfPermissions> m_permissions;
smartAclPointer_t createACL(const int f_numEntries) const;
bool createACLEntry(const acl_t f_ACL, const PermissionEntry& f_entry) const;
bool addAclPermission(acl_permset_t f_permset, acl_perm_t f_perm) const;
bool m_useACLMask{false};
};
} // namespace posix
} // namespace iox
<commit_msg>iox-#70 fix QNX build<commit_after>// Copyright (c) 2019 by Robert Bosch GmbH. 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.
#pragma once
#include "iceoryx_utils/cxx/optional.hpp"
#include "iceoryx_utils/cxx/vector.hpp"
#include "iceoryx_utils/platform/acl.hpp"
#include <cstdint>
#include <functional>
#include <iostream>
#include <memory>
#include <type_traits>
namespace iox
{
namespace posix
{
/// @brief abstraction class for the management of access control lists (ACLs).
///
/// ACLs allow to define fine-grained access rights for files. In addition to the standard access rights, which can only
/// distinguish between user/group/others, ACLs can be used to give specific access rights to named users and groups.
/// ACL is part of the posix specification. The AccessController class is used to store ACL permission entries and
/// provides a way to write those entries to a file. A permission entry can be seen as a combination of an access
/// Category, a Permission and an optional name (used to identify specific users and groups.)
class AccessController
{
public:
using string_t = std::string;
/// @brief maximum number of permission entries the AccessController can store
static constexpr int32_t MaxNumOfPermissions = 20;
/// @brief identifier for a permission entry (user, group, others, ...)
#if defined(QNX) || defined(QNX__) || defined(__QNX__)
enum class Category : std::underlying_type<acl_tag_t>::type
#else
enum class Category : acl_tag_t
#endif
{
USER = ACL_USER_OBJ,
/// a specific user must be identified by a name
SPECIFIC_USER = ACL_USER,
GROUP = ACL_GROUP_OBJ,
/// a specific group must be identified by a name
SPECIFIC_GROUP = ACL_GROUP,
OTHERS = ACL_OTHER,
};
/// @brief access right for a permission entry
#if defined(QNX) || defined(QNX__) || defined(__QNX__)
enum class Permission : std::underlying_type<acl_perm_t>::type
#else
enum class Permission : acl_perm_t
#endif
{
READ = ACL_READ,
WRITE = ACL_WRITE,
READWRITE = Permission::READ | Permission::WRITE,
NONE = 0
};
/// @brief define and store a specific permission entry to be used by writePermissionsToFile.
/// @param[f_id] id of the user or group. For Category::SPECIFIC_USER or Category::SPECIFIC_GROUP the id is
/// required. Otherwise writing the permission entry to a file will fail. For the default user/group/others
/// categories the id is ignored and can therefore be left empty. Do not forget to add permissions of the standard
/// user/group/others categories before writing to a file.
/// @param[f_permission] Permissions which should be applied to the category.
/// @param[f_id] The group or user id - depending on the category. For Category::USER, Category::GROUP and
/// Category::OTHER the f_id is not required for everything else a valid group or user id is mandatory.
bool addPermissionEntry(const Category f_category, const Permission f_permission, const unsigned int f_id = -1u);
/// @brief just like addPermissionEntry(Category, Permission, int) but using a name instead of an id.
bool addPermissionEntry(const Category f_category, const Permission f_permission, const string_t& f_name);
/// @brief Write permission entries stored by the AccessController to a file identified by a file descriptor.
/// @param[f_fileDescriptor] identifier for a file (can be regular file, shared memory file, message queue file...
/// everything is a file).
/// @return true if succesful. If false, you can assume that the file has not been touched at all.
bool writePermissionsToFile(const int f_fileDescriptor) const;
private:
using smartAclPointer_t = std::unique_ptr<std::remove_pointer<acl_t>::type, std::function<void(acl_t)>>;
struct PermissionEntry
{
unsigned int m_category;
Permission m_permission;
unsigned int m_id;
};
cxx::vector<PermissionEntry, MaxNumOfPermissions> m_permissions;
smartAclPointer_t createACL(const int f_numEntries) const;
bool createACLEntry(const acl_t f_ACL, const PermissionEntry& f_entry) const;
bool addAclPermission(acl_permset_t f_permset, acl_perm_t f_perm) const;
bool m_useACLMask{false};
};
} // namespace posix
} // namespace iox
<|endoftext|> |
<commit_before>#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <time.h>
#include <fstream>
#include <stdlib.h>
#include <string.h>
#include <sys/times.h>
using namespace std;
int main(int argc, char ** argv) {
if (argc < 3)
return 0;
ifstream test(argv[2]);
if (test.good())
{
test.close();
cerr << "Output already exists." << endl;
exit(1);
}
if ((argv[3]) && strcmp(argv[3], "-a") == 0)
{
// method 1
struct tms tmsstart, tmsend;
clock_t start, end;
if ((start = times(&tmsstart)) == -1) /* starting values */
cout << "times error" << endl;
char * input = argv[1];
char * output = argv[2];
ifstream infile(input);
ofstream outfile(output);
while (infile.good())
{
char c;
infile.get(c);
if (infile.good())
outfile.put(c);
}
if ((end = times(&tmsend)) == -1)
cout << "times error" << endl;
static long clktck = 0;
if ((clktck = sysconf(_SC_CLK_TCK)) < 0)
cout << "sysconf error" << endl;
cout << "Wall time: " << double(end-start)/clktck << endl;
cout << "User time: " << double(tmsend.tms_utime - tmsstart.tms_utime)
/clktck << endl;
cout << "Syst time: " << double(tmsend.tms_stime - tmsstart.tms_stime)
/clktck << endl;
// method 2
if ((start = times(&tmsstart)) == -1) /* starting values */
cout << "times error" << endl;
char c;
int fd;
int fd2;
int status;
fd = open(argv[1], O_RDONLY);
if (fd == -1)
perror("open");
fd2 = open(argv[2], O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
if (fd2 == -1)
perror("open");
while(read(fd, &c, 1)) {
status = write(fd2, &c, 1);
if (status == -1)
perror("write");
}
status = close(fd);
if (status == -1)
perror("close");
status = close(fd2);
if (status == -1)
perror("close");
if ((end = times(&tmsend)) == -1)
cout << "times error" << endl;
cout << "Wall time: " << double(end-start)/clktck << endl;
cout << "User time: " << double(tmsend.tms_utime - tmsstart.tms_utime)
/clktck << endl;
cout << "Syst time: " << double(tmsend.tms_stime - tmsstart.tms_stime)
/clktck << endl;
}
// method 3
struct tms tmsstart, tmsend;
clock_t start, end;
if ((start = times(&tmsstart)) == -1) /* starting values */
cout << "times error" << endl;
char buf[BUFSIZ];
int n;
int status;
int fd;
int fd2;
fd = open(argv[1], O_RDONLY);
if (fd == -1)
perror("open");
fd2 = open(argv[2], O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
if (fd2 == -1)
perror("open");
while ((n = read(fd, buf, BUFSIZ)) >0) {
status = write(fd2, buf, n);
if (status == -1)
perror("write");
}
status = close(fd);
if (status == -1)
perror("close");
status = close(fd2);
if (status == -1)
perror("close");
if ((end = times(&tmsend)) == -1)
cout << "times error" << endl;
if (argv[3] && strcmp(argv[3], "-a") == 0) {
static long clktck = 0;
if ((clktck = sysconf(_SC_CLK_TCK)) < 0)
cout << "sysconf error" << endl;
cout << "Wall time: " << (double)(end-start)/clktck << endl;
cout << "User time: " << double(tmsend.tms_utime - tmsstart.tms_utime)
/clktck << endl;
cout << "Syst time: " << double(tmsend.tms_stime - tmsstart.tms_stime)
/clktck << endl;
}
}
<commit_msg>allows tags to be anywhere in cp<commit_after>#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <time.h>
#include <fstream>
#include <stdlib.h>
#include <string.h>
#include <sys/times.h>
using namespace std;
int main(int argc, char ** argv) {
if (argc < 3)
return 0;
ifstream test(argv[2]);
if (test.good())
{
test.close();
cerr << "Output already exists." << endl;
exit(1);
}
bool flag = false;
for (int i =1; i<argc; i++)
if (argv[i][0]=='-')
for (int j=1; argv[i][j]!=0; j++)
if (argv[i][j] == 'a')
flag = true;
if ((argv[3]) && flag)
{
// method 1
struct tms tmsstart, tmsend;
clock_t start, end;
if ((start = times(&tmsstart)) == -1) /* starting values */
cout << "times error" << endl;
char * input = argv[1];
char * output = argv[2];
ifstream infile(input);
ofstream outfile(output);
while (infile.good())
{
char c;
infile.get(c);
if (infile.good())
outfile.put(c);
}
if ((end = times(&tmsend)) == -1)
cout << "times error" << endl;
static long clktck = 0;
if ((clktck = sysconf(_SC_CLK_TCK)) < 0)
cout << "sysconf error" << endl;
cout << "Wall time: " << double(end-start)/clktck << endl;
cout << "User time: " << double(tmsend.tms_utime - tmsstart.tms_utime)
/clktck << endl;
cout << "Syst time: " << double(tmsend.tms_stime - tmsstart.tms_stime)
/clktck << endl;
// method 2
if ((start = times(&tmsstart)) == -1) /* starting values */
cout << "times error" << endl;
char c;
int fd;
int fd2;
int status;
fd = open(argv[1], O_RDONLY);
if (fd == -1)
perror("open");
fd2 = open(argv[2], O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
if (fd2 == -1)
perror("open");
while(read(fd, &c, 1)) {
status = write(fd2, &c, 1);
if (status == -1)
perror("write");
}
status = close(fd);
if (status == -1)
perror("close");
status = close(fd2);
if (status == -1)
perror("close");
if ((end = times(&tmsend)) == -1)
cout << "times error" << endl;
cout << "Wall time: " << double(end-start)/clktck << endl;
cout << "User time: " << double(tmsend.tms_utime - tmsstart.tms_utime)
/clktck << endl;
cout << "Syst time: " << double(tmsend.tms_stime - tmsstart.tms_stime)
/clktck << endl;
}
// method 3
struct tms tmsstart, tmsend;
clock_t start, end;
if ((start = times(&tmsstart)) == -1) /* starting values */
cout << "times error" << endl;
char buf[BUFSIZ];
int n;
int status;
int fd;
int fd2;
fd = open(argv[1], O_RDONLY);
if (fd == -1)
perror("open");
fd2 = open(argv[2], O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
if (fd2 == -1)
perror("open");
while ((n = read(fd, buf, BUFSIZ)) >0) {
status = write(fd2, buf, n);
if (status == -1)
perror("write");
}
status = close(fd);
if (status == -1)
perror("close");
status = close(fd2);
if (status == -1)
perror("close");
if ((end = times(&tmsend)) == -1)
cout << "times error" << endl;
if (argv[3] && flag) {
static long clktck = 0;
if ((clktck = sysconf(_SC_CLK_TCK)) < 0)
cout << "sysconf error" << endl;
cout << "Wall time: " << (double)(end-start)/clktck << endl;
cout << "User time: " << double(tmsend.tms_utime - tmsstart.tms_utime)
/clktck << endl;
cout << "Syst time: " << double(tmsend.tms_stime - tmsstart.tms_stime)
/clktck << endl;
}
}
<|endoftext|> |
<commit_before>#include "Intelligence.h"
#include <iostream>
#include <algorithm>
using namespace std;
Intelligence::Intelligence() {
state_ = new BoardState();
}
Intelligence::Intelligence(BoardState * state) {
state_ = state;
}
Intelligence::~Intelligence() {
delete state_;
}
void Intelligence::apply_move(BoardMove move, BoardPlayer player) {
auto state = state_->with_move_applied(move, player);
state_ = new BoardState(state);
}
BoardMove Intelligence::choose_best_move(int time, BoardPlayer player) {
int alpha = MIN_SCORE - 1;
int beta = MAX_SCORE + 1;
int score = 0;
// TODO: Dismiss time for now, just go on for a few rounds.
BoardMove move = choose_best_move(state_, BoardMove(), alpha, beta, 3, player, score);
cout << "iterations " << iteration_count << endl;
cout << "prunes " << prune_count << endl;
return move;
}
BoardMove Intelligence::choose_best_move(BoardState * state, BoardMove move, int alpha, int beta, int time, BoardPlayer player, int& v) {
BoardMove * moves = new BoardMove[MOVE_COUNT];
int move_count = state->available_moves(player, moves, MOVE_COUNT);
BoardMove bestMove;
int bestScore = MIN_SCORE - 1;
for (int i = 0; i < move_count; i++)
{
BoardState * innerState;
innerState = new BoardState(state->with_move_applied(moves[i], player));
int newScore = alpha_beta(innerState, time, MIN_SCORE - 1, MAX_SCORE + 1, OPPONENT(player));
if (newScore > bestScore)
{
bestMove = moves[i];
bestScore = newScore;
}
}
return bestMove;
}
int Intelligence::alpha_beta(BoardState * state, int depth, int alpha, int beta, BoardPlayer player)
{
iteration_count++;
if (depth == 0)
{
return evaluate(state, player);
}
if (player == PLAYER_PLAYER1)
{
int v = MIN_SCORE - 1;
BoardMove * moves = new BoardMove[MOVE_COUNT];
int move_count = state->available_moves(player, moves, MOVE_COUNT);
cout << move_count << endl;
for (int i = 0; i < move_count; i++)
{
BoardState * innerState;
innerState = new BoardState(state->with_move_applied(moves[i], player));
v = max(v, alpha_beta(innerState, depth - 1, alpha, beta, OPPONENT(player)));
alpha = max(alpha, v);
if (beta <= alpha)
{
prune_count++;
break;
}
delete innerState;
innerState = 0;
}
return v;
}
else
{
int v = MAX_SCORE + 1;
BoardMove * moves = new BoardMove[MOVE_COUNT];
int move_count = state->available_moves(player, moves, MOVE_COUNT);
for (int i = 0; i < move_count; i++)
{
BoardState * innerState;
innerState = new BoardState(state->with_move_applied(moves[i], player));
v = min(v, alpha_beta(innerState, depth - 1, alpha, beta, OPPONENT(player)));
beta = min(beta, v);
if (beta <= alpha)
{
prune_count++;
break;
}
delete innerState;
innerState = 0;
}
return v;
}
}
//BoardMove Intelligence::choose_best_move(BoardState * state, BoardMove move, int alpha, int beta, int time, BoardPlayer player, int* j, int* k, int* l, int& v) {
// ++*j;
//
// if (time == 0 || state->is_finished())
// {
// v = evaluate(state, player);
//
// return move;
// }
//
// BoardMove * moves = new BoardMove[MOVE_COUNT];
// int move_count = state->available_moves(player, moves, MOVE_COUNT);
//
// BoardMove bestMove;
//
// if (player == PLAYER_PLAYER1)
// {
// v = MIN_SCORE - 1;
//
// for (int i = 0; i < move_count; i++) {
// BoardState* innerState = new BoardState(state->with_move_applied(moves[i], player));
//
// int nv;
// BoardMove move = choose_best_move(innerState, moves[i], alpha, beta, time - 1, OPPONENT(player), j, k, l, nv);
//
// if (nv > v)
// {
// bestMove = move;
// }
//
// v = max(v, nv);
// alpha = max(alpha, v);
//
// if (beta <= alpha)
// {
// ++*k;
// break;
// }
// }
// }
// else
// {
// v = MAX_SCORE + 1;
//
// for (int i = 0; i < move_count; i++) {
// BoardState* innerState = new BoardState(state->with_move_applied(moves[i], player));
//
// int nv;
// BoardMove move = choose_best_move(innerState, moves[i], alpha, beta, time - 1, OPPONENT(player), j, k, l, nv);
//
// if (nv < v)
// {
// bestMove = move;
// }
//
// v = min(v, nv);
// beta = min(beta, v);
//
// if (beta <= alpha)
// {
// ++*k;
// break;
// }
// }
// }
//
// return bestMove;
//
//
//}
/*BoardMove Intelligence::choose_best_move(BoardState * state, int alpha, int beta, int time, BoardPlayer player, int* j, int* k, int* l, int& v) {
++*j;
BoardMove * moves = new BoardMove[MOVE_COUNT];
int move_count = state->available_moves(player, moves, MOVE_COUNT);
BoardMove bestMove;
int bestScore = MIN_SCORE;
if (player == PLAYER_PLAYER1)
v = MIN_SCORE - 1;
else
v = MAX_SCORE + 1;
for (int i = 0; i < move_count; i++) {
BoardState * innerState;
BoardMove innerMove;
innerState = new BoardState(state->with_move_applied(moves[i], player));
if (time == 0 || innerState->is_finished())
{
int newScore = evaluate(innerState, player);
if (newScore > bestScore)
{
v = newScore;
bestMove = moves[i];
}
}
else
{
int nv;
BoardMove move;
move = choose_best_move(innerState, alpha, beta, time - 1, OPPONENT(player), j, k, l, nv);
if (player == PLAYER_PLAYER1)
{
if (nv > v)
{
bestMove = move;
}
v = max(v, nv);
alpha = max(alpha, v);
}
else
{
if (nv < v)
{
bestMove = move;
}
v = min(v, nv);
beta = max(beta, v);
}
if (beta <= alpha)
{
++*k;
break;
}
}
delete innerState;
}
return bestMove;
}*/
//BoardMove Intelligence::choose_best_move(BoardState * state, int* alpha, int* beta, int time, BoardPlayer player, int* j) {
// int origAlpha = *alpha;
// int origBeta = *beta;
// ++*j;
//
// BoardMove * moves = new BoardMove[MOVE_COUNT];
// int move_count = state->available_moves(player, moves, MOVE_COUNT);
//
// BoardMove bestMove;
// int bestScore = MIN_SCORE;
//
// for (int i = 0; i < move_count; i++) {
// BoardState * innerState;
// BoardMove innerMove;
//
// if (time > 0 && !state->with_move_applied(moves[i], player).is_finished()) {
// innerState = new BoardState(state->with_move_applied(moves[i], player));
//
// if (*beta > *alpha)
// innerMove = choose_best_move(innerState, alpha, beta, time - 1, OPPONENT(player), j);
// }
// else {
// innerState = new BoardState(*state);
// innerMove = moves[i];
// }
//
// int score = evaluate(new BoardState(innerState->with_move_applied(innerMove, player)), player);
//
// if (player == PLAYER_PLAYER1)
// origAlpha = fmax(origAlpha, score);
// else
// origBeta = fmin(origBeta, evaluate(new BoardState(innerState->with_move_applied(innerMove, OPPONENT(player))), OPPONENT(player)));
//
// if (score > bestScore)
// {
// bestMove = moves[i];
// bestScore = score;
// }
//
// delete innerState;
// }
//
// if (player == PLAYER_PLAYER1)
// *beta = origAlpha;
// else
// *alpha = origBeta;
//
// return bestMove;
//}
int Intelligence::evaluate(BoardState * state, BoardPlayer player) {
//neighbourx = new int[]{ 1, 1, 0, -1 };
//neighboury = new int[]{ 1, 0, 1, 1 };
BoardPiece* allPieces = state->pieces();
int score = 0;
if (state->piece_count() < PIECE_COUNT)
{
for (int i = 0; i < PIECE_COUNT; i++) {
if (allPieces[i].player == player)
score += 1;
else
score -= 1;
}
}
for (int i = 0; i < PIECE_COUNT; i++) {
//for each piece
//is piece flipped
if (!allPieces[i].is_face_up)
continue;
bool mypiece = (allPieces[i].player == player);
BoardTile tile = allPieces[i].tile;
#define TRY_OFFSET(ox,oy, idx, oidx); int idx = state->row_length(tile.x, tile.y, (ox), (oy), player) + \
1 + \
state->row_length(tile.x, tile.y, -(ox), -(oy), player); \
int oidx = state->row_length(tile.x, tile.y, (ox), (oy), OPPONENT(player)) + \
1 + \
state->row_length(tile.x, tile.y, -(ox), -(oy), OPPONENT(player)); \
if(idx >= 4) { return MIN_SCORE; } else if (oidx >= 4) { return MAX_SCORE; } else { score += mypiece ? idx : -idx; }
TRY_OFFSET(1, 1, d1, od1);
TRY_OFFSET(1, 0, d2, od2);
TRY_OFFSET(0, 1, d3, od3);
TRY_OFFSET(-1, 1, d4, od4);
#undef TRY_OFFSET
}
return score;
}<commit_msg>Refactor<commit_after>#include "Intelligence.h"
#include <iostream>
#include <algorithm>
using namespace std;
Intelligence::Intelligence() {
state_ = new BoardState();
}
Intelligence::Intelligence(BoardState * state) {
state_ = state;
}
Intelligence::~Intelligence() {
delete state_;
}
void Intelligence::apply_move(BoardMove move, BoardPlayer player) {
auto state = state_->with_move_applied(move, player);
state_ = new BoardState(state);
}
BoardMove Intelligence::choose_best_move(int time, BoardPlayer player) {
BoardMove * moves = new BoardMove[MOVE_COUNT];
int move_count = state_->available_moves(player, moves, MOVE_COUNT);
BoardMove bestMove;
int bestScore = MIN_SCORE - 1;
for (int i = 0; i < move_count; i++)
{
BoardState * innerState;
innerState = new BoardState(state_->with_move_applied(moves[i], player));
int newScore = alpha_beta(innerState, 3, MIN_SCORE - 1, MAX_SCORE + 1, OPPONENT(player));
if (newScore > bestScore)
{
bestMove = moves[i];
bestScore = newScore;
}
}
cout << "iterations " << iteration_count << endl;
cout << "prunes " << prune_count << endl;
return bestMove;
}
BoardMove Intelligence::choose_best_move(BoardState * state, BoardMove move, int alpha, int beta, int time, BoardPlayer player, int& v) {
BoardMove * moves = new BoardMove[MOVE_COUNT];
int move_count = state->available_moves(player, moves, MOVE_COUNT);
BoardMove bestMove;
int bestScore = MIN_SCORE - 1;
for (int i = 0; i < move_count; i++)
{
BoardState * innerState;
innerState = new BoardState(state->with_move_applied(moves[i], player));
int newScore = alpha_beta(innerState, time, MIN_SCORE - 1, MAX_SCORE + 1, OPPONENT(player));
if (newScore > bestScore)
{
bestMove = moves[i];
bestScore = newScore;
}
}
return bestMove;
}
int Intelligence::alpha_beta(BoardState * state, int depth, int alpha, int beta, BoardPlayer player)
{
iteration_count++;
if (depth == 0)
{
return evaluate(state, player);
}
if (player == PLAYER_PLAYER1)
{
int v = MIN_SCORE - 1;
BoardMove * moves = new BoardMove[MOVE_COUNT];
int move_count = state->available_moves(player, moves, MOVE_COUNT);
cout << move_count << endl;
for (int i = 0; i < move_count; i++)
{
BoardState * innerState;
innerState = new BoardState(state->with_move_applied(moves[i], player));
v = max(v, alpha_beta(innerState, depth - 1, alpha, beta, OPPONENT(player)));
alpha = max(alpha, v);
if (beta <= alpha)
{
prune_count++;
break;
}
delete innerState;
innerState = 0;
}
return v;
}
else
{
int v = MAX_SCORE + 1;
BoardMove * moves = new BoardMove[MOVE_COUNT];
int move_count = state->available_moves(player, moves, MOVE_COUNT);
for (int i = 0; i < move_count; i++)
{
BoardState * innerState;
innerState = new BoardState(state->with_move_applied(moves[i], player));
v = min(v, alpha_beta(innerState, depth - 1, alpha, beta, OPPONENT(player)));
beta = min(beta, v);
if (beta <= alpha)
{
prune_count++;
break;
}
delete innerState;
innerState = 0;
}
return v;
}
}
//BoardMove Intelligence::choose_best_move(BoardState * state, BoardMove move, int alpha, int beta, int time, BoardPlayer player, int* j, int* k, int* l, int& v) {
// ++*j;
//
// if (time == 0 || state->is_finished())
// {
// v = evaluate(state, player);
//
// return move;
// }
//
// BoardMove * moves = new BoardMove[MOVE_COUNT];
// int move_count = state->available_moves(player, moves, MOVE_COUNT);
//
// BoardMove bestMove;
//
// if (player == PLAYER_PLAYER1)
// {
// v = MIN_SCORE - 1;
//
// for (int i = 0; i < move_count; i++) {
// BoardState* innerState = new BoardState(state->with_move_applied(moves[i], player));
//
// int nv;
// BoardMove move = choose_best_move(innerState, moves[i], alpha, beta, time - 1, OPPONENT(player), j, k, l, nv);
//
// if (nv > v)
// {
// bestMove = move;
// }
//
// v = max(v, nv);
// alpha = max(alpha, v);
//
// if (beta <= alpha)
// {
// ++*k;
// break;
// }
// }
// }
// else
// {
// v = MAX_SCORE + 1;
//
// for (int i = 0; i < move_count; i++) {
// BoardState* innerState = new BoardState(state->with_move_applied(moves[i], player));
//
// int nv;
// BoardMove move = choose_best_move(innerState, moves[i], alpha, beta, time - 1, OPPONENT(player), j, k, l, nv);
//
// if (nv < v)
// {
// bestMove = move;
// }
//
// v = min(v, nv);
// beta = min(beta, v);
//
// if (beta <= alpha)
// {
// ++*k;
// break;
// }
// }
// }
//
// return bestMove;
//
//
//}
/*BoardMove Intelligence::choose_best_move(BoardState * state, int alpha, int beta, int time, BoardPlayer player, int* j, int* k, int* l, int& v) {
++*j;
BoardMove * moves = new BoardMove[MOVE_COUNT];
int move_count = state->available_moves(player, moves, MOVE_COUNT);
BoardMove bestMove;
int bestScore = MIN_SCORE;
if (player == PLAYER_PLAYER1)
v = MIN_SCORE - 1;
else
v = MAX_SCORE + 1;
for (int i = 0; i < move_count; i++) {
BoardState * innerState;
BoardMove innerMove;
innerState = new BoardState(state->with_move_applied(moves[i], player));
if (time == 0 || innerState->is_finished())
{
int newScore = evaluate(innerState, player);
if (newScore > bestScore)
{
v = newScore;
bestMove = moves[i];
}
}
else
{
int nv;
BoardMove move;
move = choose_best_move(innerState, alpha, beta, time - 1, OPPONENT(player), j, k, l, nv);
if (player == PLAYER_PLAYER1)
{
if (nv > v)
{
bestMove = move;
}
v = max(v, nv);
alpha = max(alpha, v);
}
else
{
if (nv < v)
{
bestMove = move;
}
v = min(v, nv);
beta = max(beta, v);
}
if (beta <= alpha)
{
++*k;
break;
}
}
delete innerState;
}
return bestMove;
}*/
//BoardMove Intelligence::choose_best_move(BoardState * state, int* alpha, int* beta, int time, BoardPlayer player, int* j) {
// int origAlpha = *alpha;
// int origBeta = *beta;
// ++*j;
//
// BoardMove * moves = new BoardMove[MOVE_COUNT];
// int move_count = state->available_moves(player, moves, MOVE_COUNT);
//
// BoardMove bestMove;
// int bestScore = MIN_SCORE;
//
// for (int i = 0; i < move_count; i++) {
// BoardState * innerState;
// BoardMove innerMove;
//
// if (time > 0 && !state->with_move_applied(moves[i], player).is_finished()) {
// innerState = new BoardState(state->with_move_applied(moves[i], player));
//
// if (*beta > *alpha)
// innerMove = choose_best_move(innerState, alpha, beta, time - 1, OPPONENT(player), j);
// }
// else {
// innerState = new BoardState(*state);
// innerMove = moves[i];
// }
//
// int score = evaluate(new BoardState(innerState->with_move_applied(innerMove, player)), player);
//
// if (player == PLAYER_PLAYER1)
// origAlpha = fmax(origAlpha, score);
// else
// origBeta = fmin(origBeta, evaluate(new BoardState(innerState->with_move_applied(innerMove, OPPONENT(player))), OPPONENT(player)));
//
// if (score > bestScore)
// {
// bestMove = moves[i];
// bestScore = score;
// }
//
// delete innerState;
// }
//
// if (player == PLAYER_PLAYER1)
// *beta = origAlpha;
// else
// *alpha = origBeta;
//
// return bestMove;
//}
int Intelligence::evaluate(BoardState * state, BoardPlayer player) {
//neighbourx = new int[]{ 1, 1, 0, -1 };
//neighboury = new int[]{ 1, 0, 1, 1 };
BoardPiece* allPieces = state->pieces();
int score = 0;
if (state->piece_count() < PIECE_COUNT)
{
for (int i = 0; i < PIECE_COUNT; i++) {
if (allPieces[i].player == player)
score += 1;
else
score -= 1;
}
}
for (int i = 0; i < PIECE_COUNT; i++) {
//for each piece
//is piece flipped
if (!allPieces[i].is_face_up)
continue;
bool mypiece = (allPieces[i].player == player);
BoardTile tile = allPieces[i].tile;
#define TRY_OFFSET(ox,oy, idx, oidx); int idx = state->row_length(tile.x, tile.y, (ox), (oy), player) + \
1 + \
state->row_length(tile.x, tile.y, -(ox), -(oy), player); \
int oidx = state->row_length(tile.x, tile.y, (ox), (oy), OPPONENT(player)) + \
1 + \
state->row_length(tile.x, tile.y, -(ox), -(oy), OPPONENT(player)); \
if(idx >= 4) { return MIN_SCORE; } else if (oidx >= 4) { return MAX_SCORE; } else { score += mypiece ? idx : -idx; }
TRY_OFFSET(1, 1, d1, od1);
TRY_OFFSET(1, 0, d2, od2);
TRY_OFFSET(0, 1, d3, od3);
TRY_OFFSET(-1, 1, d4, od4);
#undef TRY_OFFSET
}
return score;
}<|endoftext|> |
<commit_before>#ifndef GENERIC_ANYFUNCTION_HPP
# define GENERIC_ANYFUNCTION_HPP
# pragma once
#include <cassert>
#include <cstdint>
#include <functional>
#include "many.hpp"
#include "some.hpp"
namespace generic
{
namespace
{
template <typename>
struct signature
{
};
//
template <typename>
struct class_ref;
//
template <typename R, typename C, typename ...A>
struct class_ref<R (C::*)(A...)>
{
using type = C&;
};
template <typename R, typename C, typename ...A>
struct class_ref<R (C::*)(A...) const>
{
using type = C const&;
};
template <typename R, typename C, typename ...A>
struct class_ref<R (C::*)(A...) const volatile>
{
using type = C const volatile&;
};
//
template <typename R, typename C, typename ...A>
struct class_ref<R (C::*)(A...) &>
{
using type = C&;
};
template <typename R, typename C, typename ...A>
struct class_ref<R (C::*)(A...) const &>
{
using type = C const&;
};
template <typename R, typename C, typename ...A>
struct class_ref<R (C::*)(A...) const volatile &>
{
using type = C const volatile&;
};
//
template <typename R, typename C, typename ...A>
struct class_ref<R (C::*)(A...) &&>
{
using type = C&&;
};
template <typename R, typename C, typename ...A>
struct class_ref<R (C::*)(A...) const &&>
{
using type = C const&&;
};
template <typename R, typename C, typename ...A>
struct class_ref<R (C::*)(A...) const volatile &&>
{
using type = C const volatile&&;
};
template <typename F>
using class_ref_t = typename class_ref<F>::type;
//
template <typename>
struct remove_cv_seq;
//
template <typename R, typename ...A>
struct remove_cv_seq<R(A...)>
{
using type = R(A...);
};
template <typename R, typename ...A>
struct remove_cv_seq<R(A...) const>
{
using type = R(A...);
};
template <typename R, typename ...A>
struct remove_cv_seq<R(A...) volatile>
{
using type = R(A...);
};
template <typename R, typename ...A>
struct remove_cv_seq<R(A...) const volatile>
{
using type = R(A...);
};
//
template <typename R, typename ...A>
struct remove_cv_seq<R(A...) &>
{
using type = R(A...);
};
template <typename R, typename ...A>
struct remove_cv_seq<R(A...) const &>
{
using type = R(A...);
};
template <typename R, typename ...A>
struct remove_cv_seq<R(A...) volatile &>
{
using type = R(A...);
};
template <typename R, typename ...A>
struct remove_cv_seq<R(A...) const volatile &>
{
using type = R(A...);
};
//
template <typename R, typename ...A>
struct remove_cv_seq<R(A...) &&>
{
using type = R(A...);
};
template <typename R, typename ...A>
struct remove_cv_seq<R(A...) const &&>
{
using type = R(A...);
};
template <typename R, typename ...A>
struct remove_cv_seq<R(A...) volatile &&>
{
using type = R(A...);
};
template <typename R, typename ...A>
struct remove_cv_seq<R(A...) const volatile &&>
{
using type = R(A...);
};
template <typename F>
constexpr inline auto extract_signature(F* const) noexcept
{
return signature<typename remove_cv_seq<F>::type>();
}
template <typename C, typename F>
constexpr inline auto extract_signature(F C::* const) noexcept
{
return signature<typename remove_cv_seq<F>::type>();
}
template <typename F>
constexpr inline auto extract_signature(F const&) noexcept ->
decltype(&F::operator(), extract_signature(&F::operator()))
{
return extract_signature(&F::operator());
}
}
template <typename Any = ::generic::some<4 * sizeof(void*)>>
class any_function
{
using typeid_t = ::std::uintptr_t;
#if defined(__GNUC__)
template <typename T>
static typeid_t type_id() noexcept
{
return typeid_t(type_id<T>);
}
#else
template <typename T>
static typeid_t type_id() noexcept
{
static char const type_id{};
return typeid_t(&type_id);
}
#endif // __GNUC__
void (*f_)(Any const&, void const*, Any&);
Any any_;
#ifndef NDEBUG
typeid_t type_id_;
#endif // NDEBUG
template <typename F, typename R, typename ...A, ::std::size_t ...I>
static ::std::enable_if_t<!::std::is_void<R>{}>
do_invoke(F const& f,
::generic::many<A...> const& t,
Any& r,
::std::index_sequence<I...> const) noexcept(
#if __cplusplus <= 201402L
noexcept(f(::std::get<I>(t)...))
#else
noexcept(::std::invoke(f, ::std::get<I>(t)...))
#endif
)
{
#if __cplusplus <= 201402L
r = f(::std::get<I>(t)...);
#else
r = ::std::invoke(f, ::std::get<I>(t)...);
#endif
}
template <typename F, typename R, typename ...A, ::std::size_t ...I>
static ::std::enable_if_t<::std::is_void<R>{}>
do_invoke(F const& f,
::generic::many<A...> const& t,
Any&,
::std::index_sequence<I...> const) noexcept(
#if __cplusplus <= 201402L
noexcept(f(::std::get<I>(t)...))
#else
noexcept(::std::invoke(f, ::std::get<I>(t)...))
#endif
)
{
#if __cplusplus <= 201402L
f(::std::get<I>(t)...);
#else
::std::invoke(f, ::std::get<I>(t)...);
#endif
}
template <typename F, typename R, typename ...A>
static ::std::enable_if_t<!::std::is_member_function_pointer<F>{}>
invoker(Any const& any,
void const* const v,
Any& r) noexcept(
noexcept(do_invoke<F, R, A...>(::generic::get<F>(any),
*static_cast<::generic::many<A...> const*>(v),
r,
::std::make_index_sequence<sizeof...(A)>())
)
)
{
do_invoke<F, R, A...>(::generic::get<F>(any),
*static_cast<::generic::many<A...> const*>(v),
r,
::std::make_index_sequence<sizeof...(A)>()
);
}
template <typename F, typename R, typename ...A>
static ::std::enable_if_t<::std::is_member_function_pointer<F>{}>
invoker(Any const& any,
void const* const v,
Any& r) noexcept(
noexcept(do_invoke<F, R, A...>(::generic::get<F>(any),
*static_cast<::generic::many<class_ref_t<F>, A...> const*>(v),
r,
::std::make_index_sequence<sizeof...(A) + 1>())
)
)
{
do_invoke<F, R, A...>(::generic::get<F>(any),
*static_cast<::generic::many<class_ref_t<F>, A...> const*>(v),
r,
::std::make_index_sequence<sizeof...(A) + 1>()
);
}
template <typename F, typename R, typename ...A>
::std::enable_if_t<!::std::is_member_function_pointer<F>{}>
assign(signature<R(A...)>) noexcept
{
f_ = invoker<F, R, A...>;
#ifndef NDEBUG
type_id_ = type_id<::generic::many<A...>>();
#endif // NDEBUG
}
template <typename F, typename R, typename ...A>
::std::enable_if_t<::std::is_member_function_pointer<F>{}>
assign(signature<R(A...)>) noexcept
{
f_ = invoker<F, R, A...>;
#ifndef NDEBUG
type_id_ = type_id<::generic::many<class_ref_t<F>, A...>>();
#endif // NDEBUG
}
public:
template <typename T>
struct arg_type
{
using type = ::std::decay_t<T>;
};
template <typename T>
struct arg_type<::std::reference_wrapper<T> >
{
using type = T&;
};
template <typename T>
using arg_type_t = typename arg_type<T>::type;
any_function() = default;
template <typename F,
typename = ::std::enable_if_t<
!::std::is_same<::std::decay_t<F>, any_function>{}
>
>
any_function(F&& f) :
any_(::std::forward<F>(f))
{
assign<F>(extract_signature(::std::forward<F>(f)));
}
any_function(any_function const&) = default;
any_function(any_function&&) = default;
any_function& operator=(any_function const&) = default;
any_function& operator=(any_function&&) = default;
template <typename F,
typename = ::std::enable_if_t<
!::std::is_same<::std::decay_t<F>, any_function>{}
>
>
any_function& operator=(F&& f)
{
assign(::std::forward<F>(f));
return *this;
}
explicit operator bool() const noexcept
{
return bool(any_);
}
bool empty() const noexcept
{
return !*this;
}
template <typename F>
void assign(F&& f)
{
any_ = ::std::forward<F>(f);
assign<F>(extract_signature(::std::forward<F>(f)));
}
template <typename ...A>
auto operator()(A&& ...args) const
{
return invoke(::std::forward<A>(args)...);
}
template <typename ...A>
Any apply(::generic::many<A...> const& m) const
{
#ifndef NDEBUG
assert(type_id<::generic::many<A...> >() == type_id_);
#endif // NDEBUG
Any result;
f_(any_, &m, result);
return result;
}
template <typename ...A>
auto invoke(A&& ...args) const
{
return apply(
::generic::many<arg_type_t<A>...>{::std::forward<A>(args)...}
);
}
};
}
#endif // GENERIC_ANYFUNCTION_HPP
<commit_msg>some fixes<commit_after>#ifndef GENERIC_ANYFUNCTION_HPP
# define GENERIC_ANYFUNCTION_HPP
# pragma once
#include <cassert>
#include <cstdint>
#include <functional>
#include "many.hpp"
#include "some.hpp"
namespace generic
{
namespace
{
template <typename>
struct signature
{
};
//
template <typename>
struct class_ref;
//
template <typename R, typename C, typename ...A>
struct class_ref<R (C::*)(A...)>
{
using type = C&;
};
template <typename R, typename C, typename ...A>
struct class_ref<R (C::*)(A...) const>
{
using type = C const&;
};
template <typename R, typename C, typename ...A>
struct class_ref<R (C::*)(A...) const volatile>
{
using type = C const volatile&;
};
//
template <typename R, typename C, typename ...A>
struct class_ref<R (C::*)(A...) &>
{
using type = C&;
};
template <typename R, typename C, typename ...A>
struct class_ref<R (C::*)(A...) const &>
{
using type = C const&;
};
template <typename R, typename C, typename ...A>
struct class_ref<R (C::*)(A...) const volatile &>
{
using type = C const volatile&;
};
//
template <typename R, typename C, typename ...A>
struct class_ref<R (C::*)(A...) &&>
{
using type = C&&;
};
template <typename R, typename C, typename ...A>
struct class_ref<R (C::*)(A...) const &&>
{
using type = C const&&;
};
template <typename R, typename C, typename ...A>
struct class_ref<R (C::*)(A...) const volatile &&>
{
using type = C const volatile&&;
};
template <typename F>
using class_ref_t = typename class_ref<F>::type;
//
template <typename>
struct remove_cv_seq;
//
template <typename R, typename ...A>
struct remove_cv_seq<R(A...)>
{
using type = R(A...);
};
template <typename R, typename ...A>
struct remove_cv_seq<R(A...) const>
{
using type = R(A...);
};
template <typename R, typename ...A>
struct remove_cv_seq<R(A...) volatile>
{
using type = R(A...);
};
template <typename R, typename ...A>
struct remove_cv_seq<R(A...) const volatile>
{
using type = R(A...);
};
//
template <typename R, typename ...A>
struct remove_cv_seq<R(A...) &>
{
using type = R(A...);
};
template <typename R, typename ...A>
struct remove_cv_seq<R(A...) const &>
{
using type = R(A...);
};
template <typename R, typename ...A>
struct remove_cv_seq<R(A...) volatile &>
{
using type = R(A...);
};
template <typename R, typename ...A>
struct remove_cv_seq<R(A...) const volatile &>
{
using type = R(A...);
};
//
template <typename R, typename ...A>
struct remove_cv_seq<R(A...) &&>
{
using type = R(A...);
};
template <typename R, typename ...A>
struct remove_cv_seq<R(A...) const &&>
{
using type = R(A...);
};
template <typename R, typename ...A>
struct remove_cv_seq<R(A...) volatile &&>
{
using type = R(A...);
};
template <typename R, typename ...A>
struct remove_cv_seq<R(A...) const volatile &&>
{
using type = R(A...);
};
template <typename F>
constexpr inline auto extract_signature(F* const) noexcept
{
return signature<typename remove_cv_seq<F>::type>();
}
template <typename C, typename F>
constexpr inline auto extract_signature(F C::* const) noexcept
{
return signature<typename remove_cv_seq<F>::type>();
}
template <typename F>
constexpr inline auto extract_signature(F const&) noexcept ->
decltype(&F::operator(), extract_signature(&F::operator()))
{
return extract_signature(&F::operator());
}
}
template <typename Any = ::generic::some<4 * sizeof(void*)>>
class any_function
{
using typeid_t = ::std::uintptr_t;
#if defined(__GNUC__)
template <typename T>
static typeid_t type_id() noexcept
{
return typeid_t(type_id<T>);
}
#else
template <typename T>
static typeid_t type_id() noexcept
{
static char const type_id{};
return typeid_t(&type_id);
}
#endif // __GNUC__
void (*f_)(Any const&, void const*, Any&);
Any any_;
#ifndef NDEBUG
typeid_t type_id_;
#endif // NDEBUG
template <typename R, typename ...A, typename F, ::std::size_t ...I>
static ::std::enable_if_t<!::std::is_void<R>{}>
do_invoke(F&& f,
::generic::many<A...> const& t,
Any& r,
::std::index_sequence<I...> const) noexcept(
#if __cplusplus <= 201402L
noexcept(f(::std::get<I>(t)...))
#else
noexcept(::std::invoke(f, ::std::get<I>(t)...))
#endif
)
{
#if __cplusplus <= 201402L
r = f(::std::get<I>(t)...);
#else
r = ::std::invoke(f, ::std::get<I>(t)...);
#endif
}
template <typename R, typename ...A, typename F, ::std::size_t ...I>
static ::std::enable_if_t<::std::is_void<R>{}>
do_invoke(F&& f,
::generic::many<A...> const& t,
Any&,
::std::index_sequence<I...> const) noexcept(
#if __cplusplus <= 201402L
noexcept(f(::std::get<I>(t)...))
#else
noexcept(::std::invoke(f, ::std::get<I>(t)...))
#endif
)
{
#if __cplusplus <= 201402L
f(::std::get<I>(t)...);
#else
::std::invoke(f, ::std::get<I>(t)...);
#endif
}
template <typename F, typename R, typename ...A>
static ::std::enable_if_t<!::std::is_member_function_pointer<F>{}>
invoker(Any const& any,
void const* const v,
Any& r) noexcept(
noexcept(do_invoke<R, A...>(::generic::get<F>(any),
*static_cast<::generic::many<A...> const*>(v),
r,
::std::make_index_sequence<sizeof...(A)>())
)
)
{
do_invoke<R, A...>(::generic::get<F>(any),
*static_cast<::generic::many<A...> const*>(v),
r,
::std::make_index_sequence<sizeof...(A)>()
);
}
template <typename F, typename R, typename ...A>
static ::std::enable_if_t<::std::is_member_function_pointer<F>{}>
invoker(Any const& any,
void const* const v,
Any& r) noexcept(
noexcept(do_invoke<R, A...>(::generic::get<F>(any),
*static_cast<::generic::many<class_ref_t<F>, A...> const*>(v),
r,
::std::make_index_sequence<sizeof...(A) + 1>())
)
)
{
do_invoke<R, A...>(::generic::get<F>(any),
*static_cast<::generic::many<class_ref_t<F>, A...> const*>(v),
r,
::std::make_index_sequence<sizeof...(A) + 1>()
);
}
template <typename F, typename R, typename ...A>
::std::enable_if_t<!::std::is_member_function_pointer<F>{}>
assign(signature<R(A...)>) noexcept
{
f_ = invoker<F, R, A...>;
#ifndef NDEBUG
type_id_ = type_id<::generic::many<A...>>();
#endif // NDEBUG
}
template <typename F, typename R, typename ...A>
::std::enable_if_t<::std::is_member_function_pointer<F>{}>
assign(signature<R(A...)>) noexcept
{
f_ = invoker<F, R, A...>;
#ifndef NDEBUG
type_id_ = type_id<::generic::many<class_ref_t<F>, A...>>();
#endif // NDEBUG
}
public:
template <typename T>
struct arg_type
{
using type = ::std::decay_t<T>;
};
template <typename T>
struct arg_type<::std::reference_wrapper<T> >
{
using type = T&;
};
template <typename T>
using arg_type_t = typename arg_type<T>::type;
any_function() = default;
template <typename F,
typename = ::std::enable_if_t<
!::std::is_same<::std::decay_t<F>, any_function>{}
>
>
any_function(F&& f) :
any_(::std::forward<F>(f))
{
assign<F>(extract_signature(::std::forward<F>(f)));
}
any_function(any_function const&) = default;
any_function(any_function&&) = default;
any_function& operator=(any_function const&) = default;
any_function& operator=(any_function&&) = default;
template <typename F,
typename = ::std::enable_if_t<
!::std::is_same<::std::decay_t<F>, any_function>{}
>
>
any_function& operator=(F&& f)
{
assign(::std::forward<F>(f));
return *this;
}
explicit operator bool() const noexcept
{
return bool(any_);
}
bool empty() const noexcept
{
return !*this;
}
template <typename F>
void assign(F&& f)
{
any_ = ::std::forward<F>(f);
assign<F>(extract_signature(::std::forward<F>(f)));
}
template <typename ...A>
auto operator()(A&& ...args) const
{
return invoke(::std::forward<A>(args)...);
}
template <typename ...A>
Any apply(::generic::many<A...> const& m) const
{
#ifndef NDEBUG
assert(type_id<::generic::many<A...> >() == type_id_);
#endif // NDEBUG
Any result;
f_(any_, &m, result);
return result;
}
template <typename ...A>
auto invoke(A&& ...args) const
{
return apply(
::generic::many<arg_type_t<A>...>{::std::forward<A>(args)...}
);
}
};
}
#endif // GENERIC_ANYFUNCTION_HPP
<|endoftext|> |
<commit_before>#include "Simulation/BFER/Standard/BFER_std.hpp"
#include <thread>
#include <string>
#include <iostream>
#include "Factory/Module/Monitor/BFER/Monitor_BFER.hpp"
#include "Factory/Module/Interleaver/Interleaver.hpp"
#include "BFER_std.hpp"
using namespace aff3ct;
using namespace aff3ct::launcher;
template <typename B, typename R, typename Q>
BFER_std<B,R,Q>
::BFER_std(const int argc, const char **argv, std::ostream &stream)
: Launcher(argc, argv, params, stream)
{
params.set_src(new factory::Source ::parameters("src"));
params.set_crc(new factory::CRC ::parameters("crc"));
params.set_mdm(new factory::Modem ::parameters("mdm"));
params.set_chn(new factory::Channel ::parameters("chn"));
params.set_qnt(new factory::Quantizer ::parameters("qnt"));
params.set_mnt(new factory::Monitor_BFER ::parameters("mnt"));
params.set_ter(new factory::Terminal_BFER::parameters("ter"));
}
template <typename B, typename R, typename Q>
BFER_std<B,R,Q>
::~BFER_std()
{
}
template <typename B, typename R, typename Q>
void BFER_std<B,R,Q>
::get_description_args()
{
Launcher::get_description_args();
params. get_description(this->args);
params.src->get_description(this->args);
params.crc->get_description(this->args);
params.mdm->get_description(this->args);
params.chn->get_description(this->args);
if (std::is_integral<Q>())
params.qnt->get_description(this->args);
params.mnt->get_description(this->args);
params.ter->get_description(this->args);
auto psrc = params.src ->get_prefix();
auto pcrc = params.crc ->get_prefix();
auto penc = params.cdc->enc->get_prefix();
auto ppct = std::string("pct");
auto pmdm = params.mdm ->get_prefix();
auto pchn = params.chn ->get_prefix();
auto pqnt = params.qnt ->get_prefix();
auto pmnt = params.mnt ->get_prefix();
auto pter = params.ter ->get_prefix();
if (this->args.exist({penc+"-info-bits", "K"}) || this->args.exist({ppct+"-info-bits", "K"}))
this->args.erase({psrc+"-info-bits", "K"});
this->args.erase({psrc+"-seed", "S"});
this->args.erase({pcrc+"-info-bits", "K"});
this->args.erase({pcrc+"-fra", "F"});
this->args.erase({pmdm+"-fra-size", "N"});
this->args.erase({pmdm+"-fra", "F"});
this->args.erase({pmdm+"-noise" });
this->args.erase({pchn+"-fra-size", "N"});
this->args.erase({pchn+"-fra", "F"});
this->args.erase({pchn+"-noise" });
this->args.erase({pchn+"-seed", "S"});
this->args.erase({pchn+"-add-users" });
this->args.erase({pchn+"-complex" });
this->args.erase({pqnt+"-size", "N"});
this->args.erase({pqnt+"-fra", "F"});
this->args.erase({pmnt+"-info-bits", "K"});
this->args.erase({pmnt+"-cw-size", "N"});
this->args.erase({pmnt+"-fra", "F"});
this->args.erase({pter+"-info-bits", "K"});
this->args.erase({pter+"-cw-size", "N"});
}
template <typename B, typename R, typename Q>
void BFER_std<B,R,Q>
::store_args()
{
Launcher::store_args();
params.store(this->arg_vals);
params.src->seed = params.local_seed;
params.src->store(this->arg_vals);
auto psrc = params.src->get_prefix();
auto K = this->args.exist({psrc+"-info-bits", "K"}) ? params.src->K : params.cdc->K;
auto N = this->args.exist({psrc+"-info-bits", "K"}) ? params.src->K : params.cdc->N;
auto N_cw = this->args.exist({psrc+"-info-bits", "K"}) ? params.src->K : params.cdc->N_cw;
params.crc->store(this->arg_vals);
params.crc->K = K - params.crc->size;
params.src->K = params.src->K == 0 ? params.crc->K : params.src->K;
params.mdm->N = N;
params.mdm->store(this->arg_vals);
params.chn->N = params.mdm->N_mod;
params.chn->complex = params.mdm->complex;
params.chn->add_users = params.mdm->type == "SCMA";
params.chn->seed = params.local_seed;
params.chn->store(this->arg_vals);
params.qnt->size = params.mdm->N;
if (std::is_integral<Q>())
params.qnt->store(this->arg_vals);
params.mnt->K = params.coded_monitoring ? N_cw : params.src->K;
params.mnt->N = N_cw;
params.mnt->store(this->arg_vals);
params.ter->store(this->arg_vals);
if (!std::is_integral<Q>())
params.qnt->type = "NO";
if (params.coset)
params.cdc->enc->type = "COSET";
else if (params.cdc->enc->type == "COSET")
params.coset = true;
if (params.src->type == "AZCW" || params.cdc->enc->type == "AZCW")
{
params.src ->type = "AZCW";
params.cdc->enc->type = "AZCW";
}
if (params.err_track_revert)
{
params.src->type = "USER";
params.src->path = params.err_track_path + std::string("_$snr.src");
params.cdc->enc->type = "USER";
params.cdc->enc->path = params.err_track_path + std::string("_$snr.enc");
if (params.cdc->itl != nullptr && params.cdc->itl->core->uniform)
{
params.cdc->itl->core->type = "USER";
params.cdc->itl->core->path = params.err_track_path + std::string("_$snr.itl");
}
params.chn->type = "USER";
params.chn->path = params.err_track_path + std::string("_$snr.chn");
}
params.cdc->enc->seed = params.local_seed;
params.crc->n_frames = params.src->n_frames;
params.mdm->n_frames = params.src->n_frames;
params.chn->n_frames = params.src->n_frames;
params.qnt->n_frames = params.src->n_frames;
params.mnt->n_frames = params.src->n_frames;
}
template <typename B, typename R, typename Q>
simulation::Simulation* BFER_std<B,R,Q>
::build_simu()
{
return factory::BFER_std::build<B,R,Q>(params);
}
// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef MULTI_PREC
template class aff3ct::launcher::BFER_std<B_8,R_8,Q_8>;
template class aff3ct::launcher::BFER_std<B_16,R_16,Q_16>;
template class aff3ct::launcher::BFER_std<B_32,R_32,Q_32>;
template class aff3ct::launcher::BFER_std<B_64,R_64,Q_64>;
#else
template class aff3ct::launcher::BFER_std<B,R,Q>;
#endif
// ==================================================================================== explicit template instantiation
<commit_msg>Set the right channel type with error tracker revert<commit_after>#include "Simulation/BFER/Standard/BFER_std.hpp"
#include <thread>
#include <string>
#include <iostream>
#include "Factory/Module/Monitor/BFER/Monitor_BFER.hpp"
#include "Factory/Module/Interleaver/Interleaver.hpp"
#include "BFER_std.hpp"
using namespace aff3ct;
using namespace aff3ct::launcher;
template <typename B, typename R, typename Q>
BFER_std<B,R,Q>
::BFER_std(const int argc, const char **argv, std::ostream &stream)
: Launcher(argc, argv, params, stream)
{
params.set_src(new factory::Source ::parameters("src"));
params.set_crc(new factory::CRC ::parameters("crc"));
params.set_mdm(new factory::Modem ::parameters("mdm"));
params.set_chn(new factory::Channel ::parameters("chn"));
params.set_qnt(new factory::Quantizer ::parameters("qnt"));
params.set_mnt(new factory::Monitor_BFER ::parameters("mnt"));
params.set_ter(new factory::Terminal_BFER::parameters("ter"));
}
template <typename B, typename R, typename Q>
BFER_std<B,R,Q>
::~BFER_std()
{
}
template <typename B, typename R, typename Q>
void BFER_std<B,R,Q>
::get_description_args()
{
Launcher::get_description_args();
params. get_description(this->args);
params.src->get_description(this->args);
params.crc->get_description(this->args);
params.mdm->get_description(this->args);
params.chn->get_description(this->args);
if (std::is_integral<Q>())
params.qnt->get_description(this->args);
params.mnt->get_description(this->args);
params.ter->get_description(this->args);
auto psrc = params.src ->get_prefix();
auto pcrc = params.crc ->get_prefix();
auto penc = params.cdc->enc->get_prefix();
auto ppct = std::string("pct");
auto pmdm = params.mdm ->get_prefix();
auto pchn = params.chn ->get_prefix();
auto pqnt = params.qnt ->get_prefix();
auto pmnt = params.mnt ->get_prefix();
auto pter = params.ter ->get_prefix();
if (this->args.exist({penc+"-info-bits", "K"}) || this->args.exist({ppct+"-info-bits", "K"}))
this->args.erase({psrc+"-info-bits", "K"});
this->args.erase({psrc+"-seed", "S"});
this->args.erase({pcrc+"-info-bits", "K"});
this->args.erase({pcrc+"-fra", "F"});
this->args.erase({pmdm+"-fra-size", "N"});
this->args.erase({pmdm+"-fra", "F"});
this->args.erase({pmdm+"-noise" });
this->args.erase({pchn+"-fra-size", "N"});
this->args.erase({pchn+"-fra", "F"});
this->args.erase({pchn+"-noise" });
this->args.erase({pchn+"-seed", "S"});
this->args.erase({pchn+"-add-users" });
this->args.erase({pchn+"-complex" });
this->args.erase({pqnt+"-size", "N"});
this->args.erase({pqnt+"-fra", "F"});
this->args.erase({pmnt+"-info-bits", "K"});
this->args.erase({pmnt+"-cw-size", "N"});
this->args.erase({pmnt+"-fra", "F"});
this->args.erase({pter+"-info-bits", "K"});
this->args.erase({pter+"-cw-size", "N"});
}
template <typename B, typename R, typename Q>
void BFER_std<B,R,Q>
::store_args()
{
Launcher::store_args();
params.store(this->arg_vals);
params.src->seed = params.local_seed;
params.src->store(this->arg_vals);
auto psrc = params.src->get_prefix();
auto K = this->args.exist({psrc+"-info-bits", "K"}) ? params.src->K : params.cdc->K;
auto N = this->args.exist({psrc+"-info-bits", "K"}) ? params.src->K : params.cdc->N;
auto N_cw = this->args.exist({psrc+"-info-bits", "K"}) ? params.src->K : params.cdc->N_cw;
params.crc->store(this->arg_vals);
params.crc->K = K - params.crc->size;
params.src->K = params.src->K == 0 ? params.crc->K : params.src->K;
params.mdm->N = N;
params.mdm->store(this->arg_vals);
params.chn->N = params.mdm->N_mod;
params.chn->complex = params.mdm->complex;
params.chn->add_users = params.mdm->type == "SCMA";
params.chn->seed = params.local_seed;
params.chn->store(this->arg_vals);
params.qnt->size = params.mdm->N;
if (std::is_integral<Q>())
params.qnt->store(this->arg_vals);
params.mnt->K = params.coded_monitoring ? N_cw : params.src->K;
params.mnt->N = N_cw;
params.mnt->store(this->arg_vals);
params.ter->store(this->arg_vals);
if (!std::is_integral<Q>())
params.qnt->type = "NO";
if (params.coset)
params.cdc->enc->type = "COSET";
else if (params.cdc->enc->type == "COSET")
params.coset = true;
if (params.src->type == "AZCW" || params.cdc->enc->type == "AZCW")
{
params.src ->type = "AZCW";
params.cdc->enc->type = "AZCW";
}
if (params.err_track_revert)
{
params.src->type = "USER";
params.src->path = params.err_track_path + std::string("_$snr.src");
params.cdc->enc->type = "USER";
params.cdc->enc->path = params.err_track_path + std::string("_$snr.enc");
if (params.cdc->itl != nullptr && params.cdc->itl->core->uniform)
{
params.cdc->itl->core->type = "USER";
params.cdc->itl->core->path = params.err_track_path + std::string("_$snr.itl");
}
if (params.chn->type == "USER_ADD" || params.chn->type == "AWGN" || params.chn->type == "RAYLEIGH" || params.chn->type == "RAYLEIGH_USER")
params.chn->type = "USER_ADD";
else if (params.chn->type == "USER" || params.chn->type == "BEC" || params.chn->type == "OPTICAL")
params.chn->type = "USER";
// else params.chn->type == "NO" stays as it is
params.chn->path = params.err_track_path + std::string("_$snr.chn");
}
params.cdc->enc->seed = params.local_seed;
params.crc->n_frames = params.src->n_frames;
params.mdm->n_frames = params.src->n_frames;
params.chn->n_frames = params.src->n_frames;
params.qnt->n_frames = params.src->n_frames;
params.mnt->n_frames = params.src->n_frames;
}
template <typename B, typename R, typename Q>
simulation::Simulation* BFER_std<B,R,Q>
::build_simu()
{
return factory::BFER_std::build<B,R,Q>(params);
}
// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef MULTI_PREC
template class aff3ct::launcher::BFER_std<B_8,R_8,Q_8>;
template class aff3ct::launcher::BFER_std<B_16,R_16,Q_16>;
template class aff3ct::launcher::BFER_std<B_32,R_32,Q_32>;
template class aff3ct::launcher::BFER_std<B_64,R_64,Q_64>;
#else
template class aff3ct::launcher::BFER_std<B,R,Q>;
#endif
// ==================================================================================== explicit template instantiation
<|endoftext|> |
<commit_before>/* Main function definition for vecomp program */
#include <cstdio>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include "../headers/ErrorReporter.hpp"
#include "../headers/FileReader.hpp"
#include "../headers/Parser.hpp"
#include "../headers/main.hpp"
using namespace std;
int main(int argc, char** argv)
{
ErrorReporter* errorReporter = nullptr;
if (argc == 2)
{
#ifdef DEBUG
cout << argc << " " << argv[0] << " " << argv[1] << endl;
#endif
errorReporter = ErrorReporter::getInstance();
FileReader* fileReader = FileReader::getInstance();
errorReporter->setFileReader(fileReader);
fileReader->setErrorReporter(errorReporter);
fileReader->readFile(argv[1]);
Parser parser(fileReader, errorReporter);
parser.parse();
if (errorReporter->getErrors() > 0)
{
errorReporter->endErrorsFile();
}
}
else
{
cerr << "error: se esperaba un nombre de archivo a compilar" << endl;
cerr << "uso: vecomp <archivo>" << endl;
}
int returnValue;
if (errorReporter == nullptr)
{
returnValue = EXIT_FAILURE;
}
else
{
returnValue = errorReporter->getErrors() == 0 ? EXIT_SUCCESS :
EXIT_FAILURE;
}
return returnValue;
}
<commit_msg>added call to ending of errors out<commit_after>/* Main function definition for vecomp program */
#include <cstdio>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include "../headers/ErrorReporter.hpp"
#include "../headers/FileReader.hpp"
#include "../headers/Parser.hpp"
#include "../headers/main.hpp"
using namespace std;
int main(int argc, char** argv)
{
ErrorReporter* errorReporter = nullptr;
if (argc == 2)
{
#ifdef DEBUG
cout << argc << " " << argv[0] << " " << argv[1] << endl;
#endif
errorReporter = ErrorReporter::getInstance();
FileReader* fileReader = FileReader::getInstance();
errorReporter->setFileReader(fileReader);
fileReader->setErrorReporter(errorReporter);
fileReader->readFile(argv[1]);
Parser parser(fileReader, errorReporter);
parser.parse();
}
else
{
cerr << "error: se esperaba un nombre de archivo a compilar" << endl;
cerr << "uso: vecomp <archivo>" << endl;
}
int returnValue;
if (errorReporter == nullptr)
{
returnValue = EXIT_FAILURE;
}
else
{
returnValue = errorReporter->getErrors() == 0 ? EXIT_SUCCESS :
EXIT_FAILURE;
}
return returnValue;
}
<|endoftext|> |
<commit_before>#include "stdsneezy.h"
void TBeing::doFish(const char *direction){
TRoom *rp;
roomDirData *exitp;
if(!(exitp = exitDir(getDirFromChar(direction))) || !direction){
rp=roomp;
} else {
if(!exitp->to_room || !(rp = real_roomp(exitp->to_room))){
rp=roomp;
}
}
if(rp->isUnderwaterSector()){
sendTo("You can't fish underwater!\n\r");
return;
}
if(!rp->isWaterSector()){
sendTo("You can't fish on land!\n\r");
return;
}
if(task){
stopTask();
}
sendTo("You start fishing.\n\r");
start_task(this, NULL, rp, TASK_FISHING, "", 2, inRoom(), 0, 0, 5);
}
TObj *catch_a_fish(TRoom *rp){
TObj *fish=NULL;
int nfresh=17, nmarine=24;
const int freshfishes[]={13800, 13801, 13802, 13803, 13804, 13805, 13806,
13807, 13816, 13817, 13818, 13819, 13820, 13821,
13822, 13823, 13824};
const int marinefishes[]={13808, 13809, 13810, 13811, 13812, 13813, 13814,
13815, 13825, 13826, 13827, 13828, 13829, 13830,
13831, 13832, 13833, 13834, 13835, 13836, 13837,
13838, 13839, 13840};
float weightmod=(((float)(::number(0,100))-50.0)/100.0)+1.0; // plus or minus 30%
vlogf(LOG_PEEL, "weightmod=%f", weightmod);
if(!::number(0,100)){
weightmod=3; // big one
}
if(rp->isOceanSector()){
if(!::number(0,24)){
fish=read_object(12445, VIRTUAL); // some random crap item
} else {
fish=read_object(marinefishes[::number(0,nmarine-1)], VIRTUAL);
fish->setWeight((float)((float)fish->getWeight()*(float)weightmod));
fish->setVolume(fish->getWeight()*200);
}
} else { // if(rp->isRiverSector()){ // river or pond or lake or whatever
fish=read_object(freshfishes[::number(0,nfresh-1)], VIRTUAL);
fish->setWeight(fish->getWeight()*weightmod);
fish->setVolume(fish->getWeight()*200);
}
return fish;
}
int task_fishing(TBeing *ch, cmdTypeT cmd, const char *, int pulse, TRoom *rp, TObj *)
{
TTool *bait=NULL;
TThing *t=NULL, *tpole=NULL;
char buf[256];
TObj *fish=NULL, *pole=NULL;
int baitmax=10000, baitchance=0;
int polemax=50000, polechance=0;
int catchchance=0;
if(ch->utilityTaskCommand(cmd) || ch->nobrainerTaskCommand(cmd))
return FALSE;
// basic tasky safechecking
if (ch->isLinkdead() || (ch->in_room != ch->task->wasInRoom)){
act("You cease fishing.",
FALSE, ch, 0, 0, TO_CHAR);
act("$n stops fishing.",
TRUE, ch, 0, 0, TO_ROOM);
ch->stopTask();
return FALSE; // returning FALSE lets command be interpreted
}
// find our bait here
for(t=ch->stuff;t;t=t->nextThing){
bait=dynamic_cast<TTool *>(t);
if(bait){
if(bait->getToolType() != TOOL_FISHINGBAIT){
bait=NULL;
} else {
break;
}
}
}
if(!bait){
ch->sendTo("You need to have some bait to fish.\n\r");
ch->stopTask();
return FALSE;
}
// find our pole here
if((!(tpole=ch->heldInPrimHand()) && !(tpole = ch->heldInSecHand())) ||
!isname("fishingpole", tpole->name)){
ch->sendTo("You need to hold a fishing pole to fish!\n\r");
ch->stopTask();
return FALSE;
}
if(!(pole=dynamic_cast<TObj *>(tpole))){
vlogf(LOG_BUG, "Hmm got a fishing pole that isn't a TObj");
ch->sendTo("You need to hold a fishing pole to fish!\n\r");
ch->stopTask();
return FALSE;
}
/*
do generic checks here
*/
if(rp && !rp->isWaterSector()){
ch->sendTo("You can't fish on land!\n\r");
ch->stopTask();
return FALSE;
}
if (ch->task && ch->task->timeLeft < 0){
ch->sendTo("You pack up and stop fishing.\n\r");
ch->stopTask();
return FALSE;
}
switch (cmd) {
case CMD_TASK_CONTINUE:
ch->task->calcNextUpdate(pulse, PULSE_MOBACT * 5);
switch (ch->task->timeLeft) {
case 2:
// check for out of bait
bait->addToToolUses(-1);
if (bait->getToolUses() <= 0) {
act("Oops, you're out of bait.",
FALSE, ch, NULL, 0, TO_CHAR);
act("$n looks startled as $e realizes that $e is out of bait.",
FALSE, ch, NULL, 0, TO_ROOM);
ch->stopTask();
delete bait;
return FALSE;
}
sprintf(buf, "You bait %s with $p.", pole->shortDescr);
act(buf, FALSE, ch, bait, 0, TO_CHAR);
sprintf(buf, "$n baits %s with $p.", pole->shortDescr);
act(buf, TRUE, ch, bait, 0, TO_ROOM);
ch->task->timeLeft--;
break;
case 1:
act("You cast your line out.",
FALSE, ch, NULL, 0, TO_CHAR);
act("$n casts $s line out.",
TRUE, ch, NULL, 0, TO_ROOM);
ch->task->timeLeft--;
break;
case 0:
baitchance=(int)(((float)((float)(bait->rentCost()*2)/(float)baitmax))*40);
polechance=(int)(((float)((float)(pole->rentCost()*2)/(float)polemax))*40);
catchchance=::number(1,100);
vlogf(LOG_PEEL, "fishing: baitcost=%i, bait=%i, pole=%i, catch=%i",
bait->rentCost(), baitchance, polechance, catchchance);
if(bSuccess(ch, ch->getSkillValue(SKILL_FISHING), SKILL_FISHING) &&
(catchchance<(baitchance+polechance)) &&
(fish=catch_a_fish(rp))){
*ch += *fish;
act("You reel in $p!",
FALSE, ch, fish, 0, TO_CHAR);
act("$n reels in $p!",
TRUE, ch, fish, 0, TO_ROOM);
} else {
act("You didn't catch anything.",
FALSE, ch, NULL, 0, TO_CHAR);
act("$n doesn't catch anything.",
TRUE, ch, NULL, 0, TO_ROOM);
}
ch->stopTask();
break;
}
break;
case CMD_ABORT:
case CMD_STOP:
act("You cease fishing.",
FALSE, ch, 0, 0, TO_CHAR);
act("$n stops fishing.",
TRUE, ch, 0, 0, TO_ROOM);
ch->stopTask();
break;
case CMD_TASK_FIGHTING:
ch->sendTo("You have not yet mastered the art of fighting while fishing.\n\r");
ch->stopTask();
break;
default:
if (cmd < MAX_CMD_LIST)
warn_busy(ch);
break; // eat the command
}
return TRUE;
}
<commit_msg>descreased chance of catching fish<commit_after>#include "stdsneezy.h"
void TBeing::doFish(const char *direction){
TRoom *rp;
roomDirData *exitp;
if(!(exitp = exitDir(getDirFromChar(direction))) || !direction){
rp=roomp;
} else {
if(!exitp->to_room || !(rp = real_roomp(exitp->to_room))){
rp=roomp;
}
}
if(rp->isUnderwaterSector()){
sendTo("You can't fish underwater!\n\r");
return;
}
if(!rp->isWaterSector()){
sendTo("You can't fish on land!\n\r");
return;
}
if(task){
stopTask();
}
sendTo("You start fishing.\n\r");
start_task(this, NULL, rp, TASK_FISHING, "", 2, inRoom(), 0, 0, 5);
}
TObj *catch_a_fish(TRoom *rp){
TObj *fish=NULL;
int nfresh=17, nmarine=24;
const int freshfishes[]={13800, 13801, 13802, 13803, 13804, 13805, 13806,
13807, 13816, 13817, 13818, 13819, 13820, 13821,
13822, 13823, 13824};
const int marinefishes[]={13808, 13809, 13810, 13811, 13812, 13813, 13814,
13815, 13825, 13826, 13827, 13828, 13829, 13830,
13831, 13832, 13833, 13834, 13835, 13836, 13837,
13838, 13839, 13840};
float weightmod=(((float)(::number(0,100))-50.0)/100.0)+1.0; // plus or minus 30%
vlogf(LOG_PEEL, "weightmod=%f", weightmod);
if(!::number(0,100)){
weightmod=3; // big one
}
if(rp->isOceanSector()){
if(!::number(0,24)){
fish=read_object(12445, VIRTUAL); // some random crap item
} else {
fish=read_object(marinefishes[::number(0,nmarine-1)], VIRTUAL);
fish->setWeight((float)((float)fish->getWeight()*(float)weightmod));
fish->setVolume(fish->getWeight()*200);
}
} else { // if(rp->isRiverSector()){ // river or pond or lake or whatever
fish=read_object(freshfishes[::number(0,nfresh-1)], VIRTUAL);
fish->setWeight(fish->getWeight()*weightmod);
fish->setVolume(fish->getWeight()*200);
}
return fish;
}
int task_fishing(TBeing *ch, cmdTypeT cmd, const char *, int pulse, TRoom *rp, TObj *)
{
TTool *bait=NULL;
TThing *t=NULL, *tpole=NULL;
char buf[256];
TObj *fish=NULL, *pole=NULL;
int baitmax=10000, baitchance=0;
int polemax=50000, polechance=0;
int catchchance=0;
if(ch->utilityTaskCommand(cmd) || ch->nobrainerTaskCommand(cmd))
return FALSE;
// basic tasky safechecking
if (ch->isLinkdead() || (ch->in_room != ch->task->wasInRoom)){
act("You cease fishing.",
FALSE, ch, 0, 0, TO_CHAR);
act("$n stops fishing.",
TRUE, ch, 0, 0, TO_ROOM);
ch->stopTask();
return FALSE; // returning FALSE lets command be interpreted
}
// find our bait here
for(t=ch->stuff;t;t=t->nextThing){
bait=dynamic_cast<TTool *>(t);
if(bait){
if(bait->getToolType() != TOOL_FISHINGBAIT){
bait=NULL;
} else {
break;
}
}
}
if(!bait){
ch->sendTo("You need to have some bait to fish.\n\r");
ch->stopTask();
return FALSE;
}
// find our pole here
if((!(tpole=ch->heldInPrimHand()) && !(tpole = ch->heldInSecHand())) ||
!isname("fishingpole", tpole->name)){
ch->sendTo("You need to hold a fishing pole to fish!\n\r");
ch->stopTask();
return FALSE;
}
if(!(pole=dynamic_cast<TObj *>(tpole))){
vlogf(LOG_BUG, "Hmm got a fishing pole that isn't a TObj");
ch->sendTo("You need to hold a fishing pole to fish!\n\r");
ch->stopTask();
return FALSE;
}
/*
do generic checks here
*/
if(rp && !rp->isWaterSector()){
ch->sendTo("You can't fish on land!\n\r");
ch->stopTask();
return FALSE;
}
if (ch->task && ch->task->timeLeft < 0){
ch->sendTo("You pack up and stop fishing.\n\r");
ch->stopTask();
return FALSE;
}
switch (cmd) {
case CMD_TASK_CONTINUE:
ch->task->calcNextUpdate(pulse, PULSE_MOBACT * 5);
switch (ch->task->timeLeft) {
case 2:
// check for out of bait
bait->addToToolUses(-1);
if (bait->getToolUses() <= 0) {
act("Oops, you're out of bait.",
FALSE, ch, NULL, 0, TO_CHAR);
act("$n looks startled as $e realizes that $e is out of bait.",
FALSE, ch, NULL, 0, TO_ROOM);
ch->stopTask();
delete bait;
return FALSE;
}
sprintf(buf, "You bait %s with $p.", pole->shortDescr);
act(buf, FALSE, ch, bait, 0, TO_CHAR);
sprintf(buf, "$n baits %s with $p.", pole->shortDescr);
act(buf, TRUE, ch, bait, 0, TO_ROOM);
ch->task->timeLeft--;
break;
case 1:
act("You cast your line out.",
FALSE, ch, NULL, 0, TO_CHAR);
act("$n casts $s line out.",
TRUE, ch, NULL, 0, TO_ROOM);
ch->task->timeLeft--;
break;
case 0:
baitchance=(int)(((float)((float)(bait->rentCost()*2)/(float)baitmax))*25);
polechance=(int)(((float)((float)(pole->rentCost()*2)/(float)polemax))*25);
catchchance=::number(1,100);
vlogf(LOG_PEEL, "fishing: baitcost=%i, bait=%i, pole=%i, catch=%i",
bait->rentCost(), baitchance, polechance, catchchance);
if(bSuccess(ch, ch->getSkillValue(SKILL_FISHING), SKILL_FISHING) &&
(catchchance<(baitchance+polechance)) &&
(fish=catch_a_fish(rp))){
*ch += *fish;
act("You reel in $p!",
FALSE, ch, fish, 0, TO_CHAR);
act("$n reels in $p!",
TRUE, ch, fish, 0, TO_ROOM);
} else {
act("You didn't catch anything.",
FALSE, ch, NULL, 0, TO_CHAR);
act("$n doesn't catch anything.",
TRUE, ch, NULL, 0, TO_ROOM);
}
ch->stopTask();
break;
}
break;
case CMD_ABORT:
case CMD_STOP:
act("You cease fishing.",
FALSE, ch, 0, 0, TO_CHAR);
act("$n stops fishing.",
TRUE, ch, 0, 0, TO_ROOM);
ch->stopTask();
break;
case CMD_TASK_FIGHTING:
ch->sendTo("You have not yet mastered the art of fighting while fishing.\n\r");
ch->stopTask();
break;
default:
if (cmd < MAX_CMD_LIST)
warn_busy(ch);
break; // eat the command
}
return TRUE;
}
<|endoftext|> |
<commit_before>
#include "set.h"
#include <gtest/gtest.h>
using std::string;
TEST(SetTests, EmptySetToString) {
Set x;
EXPECT_EQ(string("{}"), x.toString());
}
TEST(SetTests, EmptySetContainsNothing) {
Set x;
EXPECT_EQ(false, x.contains(3));
}
TEST(SetTests, OneElementSet) {
Set x({5});
// Canonical representation is ordered,
// even through object itself is not.
EXPECT_EQ(string("{5}"), x.toString());
}
TEST(SetTests, Singleton5Contains5) {
Set x({5});
EXPECT_EQ(true, x.contains(5));
}
TEST(SetTests, TwoElemInOrder) {
Set x({5,6});
// Canonical representation is ordered,
// even through object itself is not.
EXPECT_EQ(string("{5,6}"), x.toString());
}
TEST(SetTests, TwoElemInOrderContainsEach) {
Set x({5,6});
// Canonical representation is ordered,
// even through object itself is not.
EXPECT_EQ(string("{5,6}"), x.toString());
EXPECT_TRUE(x.contains(5));
EXPECT_TRUE(x.contains(6));
}
TEST(SetTests, TwoElemOutOfOrder) {
Set x({5,4});
// Canonical representation is ordered,
// even through object itself is not.
EXPECT_EQ(string("{4,5}"), x.toString());
}
TEST(SetTests, DuplicateTwoShouldGiveSingletonSet) {
Set x({5,5});
// Canonical representation is ordered,
// even through object itself is not.
EXPECT_EQ(string("{5}"), x.toString());
}
TEST(SetTests, BiggerDuplicateDetection) {
Set x({3,3,4,4,3,3,4,3});
// Canonical representation is ordered,
// even through object itself is not.
EXPECT_EQ(string("{3,4}"), x.toString());
}
TEST(SetTests, BiggerDuplicateDetectionPartDeux) {
Set x({4,4,4,4,3,3,4,3});
// Canonical representation is ordered,
// even through object itself is not.
EXPECT_EQ(string("{3,4}"), x.toString());
}
TEST(SetTests, BiggerDuplicateDetectionPartTres) {
Set x({5,4,4,4,4,4});
// Canonical representation is ordered,
// even through object itself is not.
EXPECT_EQ(string("{4,5}"), x.toString());
}
#if 0
TEST(SetTests, ThreeElemInOrderSet) {
Set x({4,5,6});
// Canonical representation is ordered,
// even through object itself is not.
EXPECT_EQ(string("{4,5,6}"), x.toString());
}
TEST(SetTests, BiggerDuplicateDetectionPartFour) {
Set x({4,4,4,4,3,3,4,3,6});
// Canonical representation is ordered,
// even through object itself is not.
EXPECT_EQ(string("{3,4,6}"), x.toString());
}
TEST(SetTests, SingletonOneToString) {
Set x;
Set y=x.add(1);
EXPECT_EQ(string("{1}"), y.toString());
}
TEST(SetTests, BiggerSet) {
Set x({3,7,4,9});
// Canonical representation is ordered,
// even through object itself is not.
EXPECT_EQ(string("{3,4,7,9}"), x.toString());
}
#endif
<commit_msg>failing three elem test<commit_after>
#include "set.h"
#include <gtest/gtest.h>
using std::string;
TEST(SetTests, EmptySetToString) {
Set x;
EXPECT_EQ(string("{}"), x.toString());
}
TEST(SetTests, EmptySetContainsNothing) {
Set x;
EXPECT_EQ(false, x.contains(3));
}
TEST(SetTests, OneElementSet) {
Set x({5});
// Canonical representation is ordered,
// even through object itself is not.
EXPECT_EQ(string("{5}"), x.toString());
}
TEST(SetTests, Singleton5Contains5) {
Set x({5});
EXPECT_EQ(true, x.contains(5));
}
TEST(SetTests, TwoElemInOrder) {
Set x({5,6});
// Canonical representation is ordered,
// even through object itself is not.
EXPECT_EQ(string("{5,6}"), x.toString());
}
TEST(SetTests, TwoElemInOrderContainsEach) {
Set x({5,6});
// Canonical representation is ordered,
// even through object itself is not.
EXPECT_EQ(string("{5,6}"), x.toString());
EXPECT_TRUE(x.contains(5));
EXPECT_TRUE(x.contains(6));
}
TEST(SetTests, TwoElemOutOfOrder) {
Set x({5,4});
// Canonical representation is ordered,
// even through object itself is not.
EXPECT_EQ(string("{4,5}"), x.toString());
}
TEST(SetTests, DuplicateTwoShouldGiveSingletonSet) {
Set x({5,5});
// Canonical representation is ordered,
// even through object itself is not.
EXPECT_EQ(string("{5}"), x.toString());
}
TEST(SetTests, BiggerDuplicateDetection) {
Set x({3,4,4});
// Canonical representation is ordered,
// even through object itself is not.
EXPECT_EQ(string("{3,4}"), x.toString());
}
TEST(SetTests, ThreeElemInOrderSet) {
Set x({4,5,6});
// Canonical representation is ordered,
// even through object itself is not.
EXPECT_EQ(string("{4,5,6}"), x.toString());
}
#if 0
TEST(SetTests, ThreeElemInOrderSet) {
Set x({4,5,6});
// Canonical representation is ordered,
// even through object itself is not.
EXPECT_EQ(string("{4,5,6}"), x.toString());
}
TEST(SetTests, BiggerDuplicateDetectionPartFour) {
Set x({4,4,4,4,3,3,4,3,6});
// Canonical representation is ordered,
// even through object itself is not.
EXPECT_EQ(string("{3,4,6}"), x.toString());
}
TEST(SetTests, BiggerDuplicateDetection) {
Set x({3,3,4,4,3,3,4,3});
// Canonical representation is ordered,
// even through object itself is not.
EXPECT_EQ(string("{3,4}"), x.toString());
}
TEST(SetTests, BiggerDuplicateDetectionPartDeux) {
Set x({4,4,4,4,3,3,4,3});
// Canonical representation is ordered,
// even through object itself is not.
EXPECT_EQ(string("{3,4}"), x.toString());
}
TEST(SetTests, BiggerDuplicateDetectionPartTres) {
Set x({5,4,4,4,4,4});
// Canonical representation is ordered,
// even through object itself is not.
EXPECT_EQ(string("{4,5}"), x.toString());
}
TEST(SetTests, SingletonOneToString) {
Set x;
Set y=x.add(1);
EXPECT_EQ(string("{1}"), y.toString());
}
TEST(SetTests, BiggerSet) {
Set x({3,7,4,9});
// Canonical representation is ordered,
// even through object itself is not.
EXPECT_EQ(string("{3,4,7,9}"), x.toString());
}
#endif
<|endoftext|> |
<commit_before>// illarionserver - server for the game Illarion
// Copyright 2011 Illarion e.V.
//
// This file is part of illarionserver.
//
// illarionserver is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// illarionserver is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with illarionserver. If not, see <http://www.gnu.org/licenses/>.
#ifndef CONSTANTS_HPP
#define CONSTANTS_HPP
#include <cstdint>
const uint32_t DYNNPC_BASE = 0xFF800000;
const uint32_t NPC_BASE = 0xFF000000;
const uint32_t MONSTER_BASE = 0xFE000000;
const uint32_t MONSTERVIEWRANGE = 11;
#define MAXPOISONVALUE 400
#define MAXMANA 10000
#define MAXHPS 10000
#define MAXFOOD 60000
#define MAXATTRIB 255
#define MAXWEIGHT 30000
#define WAITINGVALIDATION 1
#define BANNED 30
#define BANNEDFORTIME 31
#define DEPOTITEM 321
#define DEPOTSIZE 100
#define BLOCKEDITEM 228
#define FLAG_WARPFIELD 1
#define FLAG_SPECIALITEM 2
#define FLAG_BLOCKPATH 4
#define FLAG_MAKEPASSABLE 8
#define FLAG_MONSTERONFIELD 16
#define FLAG_NPCONFIELD 32
#define FLAG_PLAYERONFIELD 64
// Verwendung siehe Tabelle:
// WERT| tiles | tilesmoditems | flags |
// ----+-------------------+-------------------+--------------------+
// 001 | | |FLAG_WARPFIELD |
// ----+-------------------+-------------------+--------------------+
// 002 | |FLAG_SPECIALITEM |FLAG_SPECIALITEM |
// ----+-------------------+-------------------+--------------------+
// 004 |FLAG_BLOCKPATH |FLAG_BLOCKPATH |FLAG_BLOCKPATH |
// ----+-------------------+-------------------+--------------------+
// 008 | |FLAG_MAKEPASSABLE |FLAG_MAKEPASSABLE |
// ----+-------------------+-------------------+--------------------+
// 016 | | |FLAG_MONSTERONFIELD |
// ----+-------------------+-------------------+--------------------+
// 032 | | |FLAG_NPCONFIELD |
// ----+-------------------+-------------------+--------------------+
// 064 | | |FLAG_PLAYERONFIELD |
// ----+-------------------+-------------------+--------------------+
// 128 | | | |
// ----+-------------------+-------------------+--------------------+
//! das Verzeichnis der Karte, relativ zum DEFAULTMUDDIR
#define MAPDIR "map/"
//! das Verzeichnis der Skripte, relativ zum DEFAULTMUDDIR
#define SCRIPTSDIR "scripts/"
//! Anzahl der maximal sichtbaren Ebenen nach Oben
#define RANGEUP 0x02
//! Anzahl der maximal sichtbaren Ebenen nach Unten
#define RANGEDOWN 0x02
//! Anzahl der Felder zwischen zwei Ebenen
#define LEVELDISTANCE 0x03
//! Typ der maximalen Anzahl von Item in einem Container
#define MAXCOUNTTYPE unsigned char
//! Die maximale Anzahl von Item auf einem Feld
#define MAXITEMS 250 // max 255 da oft als BYTE verwendet
//! die maximale Anzahl von Item am Grtel
#define MAX_BELT_SLOTS 6
//! Die maximale Anzahl von Item direkt am K�per
#define MAX_BODY_ITEMS 12
//! Rucksack
#define BACKPACK 0
//! Kopf
#define HEAD 1
//! Kopf-Flag
#define FLAG_HEAD 1
//! Hals
#define NECK 2
//! Hals-Flag
#define FLAG_NECK 2
//! Brustkorb
#define BREAST 3
//! Brustkorb-Flag
#define FLAG_BREAST 4
//! H�de (fr Handschuhe)
#define HANDS 4
//! H�de-Flag
#define FLAG_HANDS 8
//! Werkzeug / Waffe in der linken Hand
#define LEFT_TOOL 5
//! Werkzeug / Waffe in der rechten Hand
#define RIGHT_TOOL 6
//! Finger der linken Hand
#define FINGER_LEFT_HAND 7
//! Finger der rechten Hand
#define FINGER_RIGHT_HAND 8
//! Finger-Flag
#define FLAG_FINGER 32
//! Beine
#define LEGS 9
//! Beine-Flag
#define FLAG_LEGS 64
//! F�
#define FEET 10
//! F�-Flag
#define FLAG_FEET 128
//! Umhang
#define COAT 11
#define LAST_WEARABLE 11
//! Coat-Flag
#define FLAG_COAT 16
#define MAXSHOWCASES 100
#define MAX_DEPOT_SHOWCASE 9
//! Code fr "kein Feld"
#define NOFIELD 0xFFFF
//-------------- Client to Server ---------------------
//! folgender Wert ist relative x und y Koordinaten eines Items/Bodenplatte/Charakters
#define UID_KOORD 0x01
//! folgender Wert ist Showcasenummer+showcaseposition
#define UID_SHOWC 0x02
//! folgender Wert ist Inventory Position
#define UID_INV 0x03
//! Eine Person wird benutzt
#define UID_PERSON 0x05
#define UID_MAGICWAND 0x06
//-------------- Server to Client ---------------------
#define STILLMOVING 0x09
#define NOMOVE 0x0A
#define NORMALMOVE 0x0B
#define PUSH 0x0C
#define RUNNING 0x0D
//! Grund fr Verbindungsabbruch: Client logt aus
#define NORMALLOGOUT 0x00
//! Grund fr Verbindungsabbruch: zu alter Client
#define OLDCLIENT 0x01
//! Grund fr Verbindungsabbruch: Spieler ist schon online
#define DOUBLEPLAYER 0x02
//! Grund fr Verbindungsabbruch: Falsches Pa�ort
#define WRONGPWD 0x03
//! Grund fr Verbindungsabbruch: Servershutdown
#define SERVERSHUTDOWN 0x04
//! Grund fr Verbindungsabbruch: durch Gamemaster entfernt
#define BYGAMEMASTER 0x05
//! Grund fr Verbindungsabbruch: zum Erstellen eines neuen Player
#define FORCREATE 0x06
//! Grund fr Verbindungsabbruch: kein Platz fr den Player
#define NOPLACE 0x07
//! Grund fr Verbindungsabbruch: angegebener Spieler nicht gefunden
#define NOCHARACTERFOUND 0x08
//! Grund fr Verbindungsabbruch: Spieler wurde erstellt
#define PLAYERCREATED 0x09 // string name
//! Grund fr Verbindungsabbruch: UNSTABLECONNECTION
#define UNSTABLECONNECTION 0x0A // string name
//! Reason for Connection shutdown: player has no account
#define NOACCOUNT 0x0B
//! Grund fr Verbindungsabbruch: no skill package chosen
#define NOSKILLS 0x0C
//! Grund fuer Verbindungsabbruch: Spielerdaten korrupt
#define CORRUPTDATA 0x0D
#endif
<commit_msg>Replace defines with constexpr and const<commit_after>// illarionserver - server for the game Illarion
// Copyright 2011 Illarion e.V.
//
// This file is part of illarionserver.
//
// illarionserver is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// illarionserver is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with illarionserver. If not, see <http://www.gnu.org/licenses/>.
#ifndef CONSTANTS_HPP
#define CONSTANTS_HPP
#include <cstdint>
#include <string>
constexpr uint32_t DYNNPC_BASE = 0xFF800000;
constexpr uint32_t NPC_BASE = 0xFF000000;
constexpr uint32_t MONSTER_BASE = 0xFE000000;
constexpr auto MONSTERVIEWRANGE = 11;
constexpr auto MAXPOISONVALUE = 400;
constexpr auto MAXMANA = 10000;
constexpr auto MAXHPS = 10000;
constexpr auto MAXFOOD = 60000;
constexpr auto MAXATTRIB = 255;
constexpr auto MAXWEIGHT = 30000;
constexpr auto WAITINGVALIDATION = 1;
constexpr auto BANNED = 30;
constexpr auto BANNEDFORTIME = 31;
constexpr auto DEPOTITEM = 321;
constexpr auto DEPOTSIZE = 100;
constexpr auto BLOCKEDITEM = 228;
constexpr auto FLAG_WARPFIELD = 1;
constexpr auto FLAG_SPECIALITEM = 2;
constexpr auto FLAG_BLOCKPATH = 4;
constexpr auto FLAG_MAKEPASSABLE = 8;
constexpr auto FLAG_MONSTERONFIELD = 16;
constexpr auto FLAG_NPCONFIELD = 32;
constexpr auto FLAG_PLAYERONFIELD = 64;
// Verwendung siehe Tabelle:
// WERT| tiles | tilesmoditems | flags |
// ----+-------------------+-------------------+--------------------+
// 001 | | |FLAG_WARPFIELD |
// ----+-------------------+-------------------+--------------------+
// 002 | |FLAG_SPECIALITEM |FLAG_SPECIALITEM |
// ----+-------------------+-------------------+--------------------+
// 004 |FLAG_BLOCKPATH |FLAG_BLOCKPATH |FLAG_BLOCKPATH |
// ----+-------------------+-------------------+--------------------+
// 008 | |FLAG_MAKEPASSABLE |FLAG_MAKEPASSABLE |
// ----+-------------------+-------------------+--------------------+
// 016 | | |FLAG_MONSTERONFIELD |
// ----+-------------------+-------------------+--------------------+
// 032 | | |FLAG_NPCONFIELD |
// ----+-------------------+-------------------+--------------------+
// 064 | | |FLAG_PLAYERONFIELD |
// ----+-------------------+-------------------+--------------------+
// 128 | | | |
// ----+-------------------+-------------------+--------------------+
//! das Verzeichnis der Karte, relativ zum DEFAULTMUDDIR
const std::string MAPDIR("map/");
//! das Verzeichnis der Skripte, relativ zum DEFAULTMUDDIR
const std::string SCRIPTSDIR("scripts/");
//! Anzahl der maximal sichtbaren Ebenen nach Oben
constexpr auto RANGEUP = 0x02;
//! Anzahl der maximal sichtbaren Ebenen nach Unten
constexpr auto RANGEDOWN = 0x02;
//! Anzahl der Felder zwischen zwei Ebenen
constexpr auto LEVELDISTANCE = 0x03;
//! Typ der maximalen Anzahl von Item in einem Container
using MAXCOUNTTYPE = unsigned char;
//! Die maximale Anzahl von Item auf einem Feld
constexpr auto MAXITEMS = 250; // max 255 da oft als BYTE verwendet
//! die maximale Anzahl von Item am Grtel
constexpr auto MAX_BELT_SLOTS = 6;
//! Die maximale Anzahl von Item direkt am K�per
constexpr auto MAX_BODY_ITEMS = 12;
//! Rucksack
constexpr auto BACKPACK = 0;
//! Kopf
constexpr auto HEAD = 1;
//! Kopf-Flag
constexpr auto FLAG_HEAD = 1;
//! Hals
constexpr auto NECK = 2;
//! Hals-Flag
constexpr auto FLAG_NECK = 2;
//! Brustkorb
constexpr auto BREAST = 3;
//! Brustkorb-Flag
constexpr auto FLAG_BREAST = 4;
//! H�de (fr Handschuhe)
constexpr auto HANDS = 4;
//! H�de-Flag
constexpr auto FLAG_HANDS = 8;
//! Werkzeug / Waffe in der linken Hand
constexpr auto LEFT_TOOL = 5;
//! Werkzeug / Waffe in der rechten Hand
constexpr auto RIGHT_TOOL = 6;
//! Finger der linken Hand
constexpr auto FINGER_LEFT_HAND = 7;
//! Finger der rechten Hand
constexpr auto FINGER_RIGHT_HAND = 8;
//! Finger-Flag
constexpr auto FLAG_FINGER = 32;
//! Beine
constexpr auto LEGS = 9;
//! Beine-Flag
constexpr auto FLAG_LEGS = 64;
//! F�
constexpr auto FEET = 10;
//! F�-Flag
constexpr auto FLAG_FEET = 128;
//! Umhang
constexpr auto COAT = 11;
constexpr auto LAST_WEARABLE = 11;
//! Coat-Flag
constexpr auto FLAG_COAT = 16;
constexpr auto MAXSHOWCASES = 100;
constexpr auto MAX_DEPOT_SHOWCASE = 9;
//! Code fr "kein Feld"
constexpr auto NOFIELD = 0xFFFF;
//-------------- Client to Server ---------------------
//! folgender Wert ist relative x und y Koordinaten eines Items/Bodenplatte/Charakters
constexpr auto UID_KOORD = 0x01;
//! folgender Wert ist Showcasenummer+showcaseposition
constexpr auto UID_SHOWC = 0x02;
//! folgender Wert ist Inventory Position
constexpr auto UID_INV = 0x03;
//! Eine Person wird benutzt
constexpr auto UID_PERSON = 0x05;
constexpr auto UID_MAGICWAND = 0x06;
//-------------- Server to Client ---------------------
constexpr auto STILLMOVING = 0x09;
constexpr auto NOMOVE = 0x0A;
constexpr auto NORMALMOVE = 0x0B;
constexpr auto PUSH = 0x0C;
constexpr auto RUNNING = 0x0D;
//! Grund fr Verbindungsabbruch: Client logt aus
constexpr auto NORMALLOGOUT = 0x00;
//! Grund fr Verbindungsabbruch: zu alter Client
constexpr auto OLDCLIENT = 0x01;
//! Grund fr Verbindungsabbruch: Spieler ist schon online
constexpr auto DOUBLEPLAYER = 0x02;
//! Grund fr Verbindungsabbruch: Falsches Pa�ort
constexpr auto WRONGPWD = 0x03;
//! Grund fr Verbindungsabbruch: Servershutdown
constexpr auto SERVERSHUTDOWN = 0x04;
//! Grund fr Verbindungsabbruch: durch Gamemaster entfernt
constexpr auto BYGAMEMASTER = 0x05;
//! Grund fr Verbindungsabbruch: zum Erstellen eines neuen Player
constexpr auto FORCREATE = 0x06;
//! Grund fr Verbindungsabbruch: kein Platz fr den Player
constexpr auto NOPLACE = 0x07;
//! Grund fr Verbindungsabbruch: angegebener Spieler nicht gefunden
constexpr auto NOCHARACTERFOUND = 0x08;
//! Grund fr Verbindungsabbruch: Spieler wurde erstellt
constexpr auto PLAYERCREATED = 0x09; // string name
//! Grund fr Verbindungsabbruch: UNSTABLECONNECTION
constexpr auto UNSTABLECONNECTION = 0x0A; // string name
//! Reason for Connection shutdown: player has no account
constexpr auto NOACCOUNT = 0x0B;
//! Grund fr Verbindungsabbruch: no skill package chosen
constexpr auto NOSKILLS = 0x0C;
//! Grund fuer Verbindungsabbruch: Spielerdaten korrupt
constexpr auto CORRUPTDATA = 0x0D;
#endif
<|endoftext|> |
<commit_before><commit_msg>UnsteadyLinearAdvectionDiffusion<commit_after><|endoftext|> |
<commit_before>// Copyright (C) 2007-2015 CEA/DEN, EDF R&D, OPEN CASCADE
//
// Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
//
// 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
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
#include "OCCViewer_VService.h"
#include <V3d_Viewer.hxx>
#include <V3d_View.hxx>
#include <Aspect_DisplayConnection.hxx>
#include <Basics_OCCTVersion.hxx>
#if OCC_VERSION_LARGE > 0x06070200 // for OCC-6.7.3 and higher version
#include <OpenGl_GraphicDriver.hxx>
#else
#include <Graphic3d.hxx>
#include <Graphic3d_GraphicDriver.hxx>
#endif
#ifdef WIN32
#include <WNT_Window.hxx>
#else
#include <Xw_Window.hxx>
#endif
/*!
Create native view window for CasCade view [ static ]
*/
Handle(Aspect_Window) OCCViewer_VService::CreateWindow( const Handle(V3d_View)& view,
WId winId )
{
Aspect_Handle aWindowHandle = (Aspect_Handle)winId;
#ifdef WIN32
Handle(WNT_Window) viewWindow = new WNT_Window( aWindowHandle );
#else
Handle(Aspect_DisplayConnection) aDispConnection = view->Viewer()->Driver()->GetDisplayConnection();
Handle(Xw_Window) viewWindow = new Xw_Window( aDispConnection, aWindowHandle );
#endif
return viewWindow;
}
/*!
Creates viewer 3d [ static ]
*/
Handle(V3d_Viewer) OCCViewer_VService::CreateViewer( const Standard_ExtString name,
const Standard_CString displayName,
const Standard_CString domain,
const Standard_Real viewSize ,
const V3d_TypeOfOrientation viewProjection,
const Standard_Boolean computedMode,
const Standard_Boolean defaultComputedMode )
{
#if OCC_VERSION_LARGE > 0x06070200 // for OCC-6.7.3 and higher version
static Handle(OpenGl_GraphicDriver) aGraphicDriver;
#else
static Handle(Graphic3d_GraphicDriver) aGraphicDriver;
#endif
if (aGraphicDriver.IsNull())
{
Handle(Aspect_DisplayConnection) aDisplayConnection;
#ifndef WIN32
aDisplayConnection = new Aspect_DisplayConnection( displayName );
#else
aDisplayConnection = new Aspect_DisplayConnection();
#endif
#if OCC_VERSION_LARGE > 0x06070200 // for OCC-6.7.3 and higher version
aGraphicDriver = new OpenGl_GraphicDriver(aDisplayConnection);
#else
aGraphicDriver = Graphic3d::InitGraphicDriver( aDisplayConnection );
#endif
}
return new V3d_Viewer( aGraphicDriver, name, domain, viewSize, viewProjection,
Quantity_NOC_GRAY30, V3d_ZBUFFER, V3d_GOURAUD, V3d_WAIT,
computedMode, defaultComputedMode, V3d_TEX_NONE );
}
<commit_msg>Fix problem of compilation with OCCT dev<commit_after>// Copyright (C) 2007-2015 CEA/DEN, EDF R&D, OPEN CASCADE
//
// Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
//
// 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
//
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
#include "OCCViewer_VService.h"
#include <V3d_Viewer.hxx>
#include <V3d_View.hxx>
#include <Basics_OCCTVersion.hxx>
#if OCC_VERSION_LARGE > 0x06070200 // for OCC-6.7.3 and higher version
#include <OpenGl_GraphicDriver.hxx>
#else
#include <Graphic3d.hxx>
#include <Graphic3d_GraphicDriver.hxx>
#endif
#include <Aspect_DisplayConnection.hxx>
#ifdef WIN32
#include <WNT_Window.hxx>
#else
#include <Xw_Window.hxx>
#endif
/*!
Create native view window for CasCade view [ static ]
*/
Handle(Aspect_Window) OCCViewer_VService::CreateWindow( const Handle(V3d_View)& view,
WId winId )
{
Aspect_Handle aWindowHandle = (Aspect_Handle)winId;
#ifdef WIN32
Handle(WNT_Window) viewWindow = new WNT_Window( aWindowHandle );
#else
Handle(Aspect_DisplayConnection) aDispConnection = view->Viewer()->Driver()->GetDisplayConnection();
Handle(Xw_Window) viewWindow = new Xw_Window( aDispConnection, aWindowHandle );
#endif
return viewWindow;
}
/*!
Creates viewer 3d [ static ]
*/
Handle(V3d_Viewer) OCCViewer_VService::CreateViewer( const Standard_ExtString name,
const Standard_CString displayName,
const Standard_CString domain,
const Standard_Real viewSize ,
const V3d_TypeOfOrientation viewProjection,
const Standard_Boolean computedMode,
const Standard_Boolean defaultComputedMode )
{
#if OCC_VERSION_LARGE > 0x06070200 // for OCC-6.7.3 and higher version
static Handle(OpenGl_GraphicDriver) aGraphicDriver;
#else
static Handle(Graphic3d_GraphicDriver) aGraphicDriver;
#endif
if (aGraphicDriver.IsNull())
{
Handle(Aspect_DisplayConnection) aDisplayConnection;
#ifndef WIN32
aDisplayConnection = new Aspect_DisplayConnection( displayName );
#else
aDisplayConnection = new Aspect_DisplayConnection();
#endif
#if OCC_VERSION_LARGE > 0x06070200 // for OCC-6.7.3 and higher version
aGraphicDriver = new OpenGl_GraphicDriver(aDisplayConnection);
#else
aGraphicDriver = Graphic3d::InitGraphicDriver( aDisplayConnection );
#endif
}
return new V3d_Viewer( aGraphicDriver, name, domain, viewSize, viewProjection,
Quantity_NOC_GRAY30, V3d_ZBUFFER, V3d_GOURAUD, V3d_WAIT,
computedMode, defaultComputedMode, V3d_TEX_NONE );
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
//
// File: ParseUtils.hpp
//
// For more information, please see: http://www.nektar.info/
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description: This file contains various parsing utilities, primarily used
// by SpatialDomains to process input files.
//
//
////////////////////////////////////////////////////////////////////////////////
#ifndef NEKTAR_LIBUTILITIES_PARSEUTILS_HPP
#define NEKTAR_LIBUTILITIES_PARSEUTILS_HPP
#include <LibUtilities/BasicConst/NektarUnivTypeDefs.hpp>
#include <vector>
#include <boost/version.hpp>
#include <LibUtilities/LibUtilitiesDeclspec.h>
#if( BOOST_VERSION / 100 % 1000 >= 36 )
#include <boost/spirit/include/classic_core.hpp>
#include <boost/spirit/include/classic_push_back_actor.hpp>
using namespace boost::spirit::classic;
#else
#include <boost/spirit/core.hpp>
#include <boost/spirit/actor/push_back_actor.hpp>
using namespace boost::spirit;
#endif
namespace Nektar
{
class ParseUtils
{
public:
static bool ParseRealAssignment(const char *const str, std::string &symbol, NekDouble &value)
{
SymbolFunctor symbolFunctor(&symbol);
ValueFunctor valueFunctor(&value);
return parse(str,
// Begin grammar
(
lexeme_d[alpha_p >> *alnum_p][symbolFunctor] >> "=" >> real_p[valueFunctor]
)
,
// End grammar
space_p).full;
}
static bool GenerateSeqVector(const char *const str, std::vector<unsigned int> &vec)
{
// Functors used to parse the sequence.
fctor1 functor1(&vec);
fctor2 functor2(&vec);
return parse(str,
// Begin grammar
(
uint_p[functor1] >> !('-' >> uint_p[functor2]) >>
*(',' >> uint_p[functor1] >> !('-' >> uint_p[functor2]))
)
,
// End grammar
space_p).full;
}
static bool GenerateOrderedVector(const char *const str, std::vector<unsigned int> &vec)
{
// Functors used to parse the sequence.
fctor1 functor1(&vec);
return parse(str,
// Begin grammar
(
uint_p[functor1] >> *(',' >> uint_p[functor1])
)
,
// End grammar
space_p).full;
}
static bool GenerateOrderedVector(const char *const str, std::vector<NekDouble> &vec)
{
// Functors used to parse the sequence.
fctor4 functor4(&vec);
return parse(str,
// Begin grammar
(
real_p[functor4] >> *(',' >> real_p[functor4])
)
,
// End grammar
space_p).full;
}
static bool GenerateUnOrderedVector(const char *const str, std::vector<NekDouble> &vec)
{
// Functors used to parse the sequence.
fctor5 functor5(&vec);
return parse(str,
// Begin grammar
(
real_p[functor5] >> *(',' >> real_p[functor5])
)
,
// End grammar
space_p).full;
}
static bool GenerateOrderedStringVector(const char *const str, std::vector<std::string> &vec)
{
// Functors used to parse the sequence.
fctor3 functor3(&vec);
return parse(str,
// Begin grammar
(
(+(print_p - ','))[functor3] >> *(',' >> (+(print_p - ','))[functor3])
)
,
// End grammar
space_p).full;
}
private:
struct SymbolFunctor
{
SymbolFunctor(std::string *symbol):
m_symbol(symbol)
{
}
void operator()(const char *beg, const char *end) const
{
m_symbol->assign(beg, end-beg);
}
private:
std::string *m_symbol;
};
struct ValueFunctor
{
ValueFunctor(NekDouble *value):
m_value(value)
{
}
void operator()(NekDouble val) const
{
*m_value = val;
}
private:
NekDouble *m_value;
};
struct fctor1
{
fctor1(std::vector<unsigned int> *vec):
m_vector(vec)
{
}
void operator()(unsigned int n) const
{
#ifdef NOTREQUIRED //SJS: I do not think we need this check
if (!m_vector->empty())
{
unsigned int prevElem = m_vector->back();
if (n > prevElem)
{
m_vector->push_back(n);
}
}
else
#endif
{
m_vector->push_back(n);
}
}
private:
std::vector<unsigned int> *m_vector;
fctor1();
};
struct fctor2
{
fctor2(std::vector<unsigned int> *vec):
m_vector(vec)
{
}
void operator()(unsigned int n) const
{
unsigned int prevElem = m_vector->back();
for (unsigned int i=prevElem+1; i<=n; ++i)
{
m_vector->push_back(i);
}
}
private:
std::vector<unsigned int> *m_vector;
};
struct fctor3
{
fctor3(std::vector<std::string> *vec):
m_vector(vec)
{
}
void operator()(char const* first, char const* last) const
{
m_vector->push_back(std::string(first, last));
}
private:
std::vector<std::string> *m_vector;
};
// Probably should template fctor1 if that is possible?
struct fctor4
{
fctor4(std::vector<NekDouble> *vec):
m_vector(vec)
{
}
void operator()(NekDouble n) const
{
if (!m_vector->empty())
{
NekDouble prevElem = m_vector->back();
if (n > prevElem)
{
m_vector->push_back(n);
}
}
else
{
m_vector->push_back(n);
}
}
private:
std::vector<NekDouble> *m_vector;
fctor4();
};
struct fctor5
{
fctor5(std::vector<NekDouble> *vec):
m_vector(vec)
{
}
void operator()(NekDouble n) const
{
m_vector->push_back(n);
}
private:
std::vector<NekDouble> *m_vector;
fctor5();
};
};
}
#endif //NEKTAR_LIBUTILITIES_PARSEUTILS_HPP
<commit_msg>Alignment fix<commit_after>////////////////////////////////////////////////////////////////////////////////
//
// File: ParseUtils.hpp
//
// For more information, please see: http://www.nektar.info/
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description: This file contains various parsing utilities, primarily used
// by SpatialDomains to process input files.
//
//
////////////////////////////////////////////////////////////////////////////////
#ifndef NEKTAR_LIBUTILITIES_PARSEUTILS_HPP
#define NEKTAR_LIBUTILITIES_PARSEUTILS_HPP
#include <LibUtilities/BasicConst/NektarUnivTypeDefs.hpp>
#include <vector>
#include <boost/version.hpp>
#include <LibUtilities/LibUtilitiesDeclspec.h>
#if( BOOST_VERSION / 100 % 1000 >= 36 )
#include <boost/spirit/include/classic_core.hpp>
#include <boost/spirit/include/classic_push_back_actor.hpp>
using namespace boost::spirit::classic;
#else
#include <boost/spirit/core.hpp>
#include <boost/spirit/actor/push_back_actor.hpp>
using namespace boost::spirit;
#endif
namespace Nektar
{
class ParseUtils
{
public:
static bool ParseRealAssignment(const char *const str, std::string &symbol, NekDouble &value)
{
SymbolFunctor symbolFunctor(&symbol);
ValueFunctor valueFunctor(&value);
return parse(str,
// Begin grammar
(
lexeme_d[alpha_p >> *alnum_p][symbolFunctor] >> "=" >> real_p[valueFunctor]
)
,
// End grammar
space_p).full;
}
static bool GenerateSeqVector(const char *const str, std::vector<unsigned int> &vec)
{
// Functors used to parse the sequence.
fctor1 functor1(&vec);
fctor2 functor2(&vec);
return parse(str,
// Begin grammar
(
uint_p[functor1] >> !('-' >> uint_p[functor2]) >>
*(',' >> uint_p[functor1] >> !('-' >> uint_p[functor2]))
)
,
// End grammar
space_p).full;
}
static bool GenerateOrderedVector(const char *const str, std::vector<unsigned int> &vec)
{
// Functors used to parse the sequence.
fctor1 functor1(&vec);
return parse(str,
// Begin grammar
(
uint_p[functor1] >> *(',' >> uint_p[functor1])
)
,
// End grammar
space_p).full;
}
static bool GenerateOrderedVector(const char *const str, std::vector<NekDouble> &vec)
{
// Functors used to parse the sequence.
fctor4 functor4(&vec);
return parse(str,
// Begin grammar
(
real_p[functor4] >> *(',' >> real_p[functor4])
)
,
// End grammar
space_p).full;
}
static bool GenerateUnOrderedVector(const char *const str, std::vector<NekDouble> &vec)
{
// Functors used to parse the sequence.
fctor5 functor5(&vec);
return parse(str,
// Begin grammar
(
real_p[functor5] >> *(',' >> real_p[functor5])
)
,
// End grammar
space_p).full;
}
static bool GenerateOrderedStringVector(const char *const str, std::vector<std::string> &vec)
{
// Functors used to parse the sequence.
fctor3 functor3(&vec);
return parse(str,
// Begin grammar
(
(+(print_p - ','))[functor3] >> *(',' >> (+(print_p - ','))[functor3])
)
,
// End grammar
space_p).full;
}
private:
struct SymbolFunctor
{
SymbolFunctor(std::string *symbol):
m_symbol(symbol)
{
}
void operator()(const char *beg, const char *end) const
{
m_symbol->assign(beg, end-beg);
}
private:
std::string *m_symbol;
};
struct ValueFunctor
{
ValueFunctor(NekDouble *value):
m_value(value)
{
}
void operator()(NekDouble val) const
{
*m_value = val;
}
private:
NekDouble *m_value;
};
struct fctor1
{
fctor1(std::vector<unsigned int> *vec):
m_vector(vec)
{
}
void operator()(unsigned int n) const
{
#ifdef NOTREQUIRED //SJS: I do not think we need this check
if (!m_vector->empty())
{
unsigned int prevElem = m_vector->back();
if (n > prevElem)
{
m_vector->push_back(n);
}
}
else
#endif
{
m_vector->push_back(n);
}
}
private:
std::vector<unsigned int> *m_vector;
fctor1();
};
struct fctor2
{
fctor2(std::vector<unsigned int> *vec):
m_vector(vec)
{
}
void operator()(unsigned int n) const
{
unsigned int prevElem = m_vector->back();
for (unsigned int i=prevElem+1; i<=n; ++i)
{
m_vector->push_back(i);
}
}
private:
std::vector<unsigned int> *m_vector;
};
struct fctor3
{
fctor3(std::vector<std::string> *vec):
m_vector(vec)
{
}
void operator()(char const* first, char const* last) const
{
m_vector->push_back(std::string(first, last));
}
private:
std::vector<std::string> *m_vector;
};
// Probably should template fctor1 if that is possible?
struct fctor4
{
fctor4(std::vector<NekDouble> *vec):
m_vector(vec)
{
}
void operator()(NekDouble n) const
{
if (!m_vector->empty())
{
NekDouble prevElem = m_vector->back();
if (n > prevElem)
{
m_vector->push_back(n);
}
}
else
{
m_vector->push_back(n);
}
}
private:
std::vector<NekDouble> *m_vector;
fctor4();
};
struct fctor5
{
fctor5(std::vector<NekDouble> *vec):
m_vector(vec)
{
}
void operator()(NekDouble n) const
{
m_vector->push_back(n);
}
private:
std::vector<NekDouble> *m_vector;
fctor5();
};
};
}
#endif //NEKTAR_LIBUTILITIES_PARSEUTILS_HPP
<|endoftext|> |
<commit_before>#include <git2.h>
#include <uv.h>
#include <set>
#include <vector>
#include <map>
#include <algorithm>
#include "../include/lock_master.h"
// LockMaster implementation details
// implemented in a separate class to keep LockMaster opaque
class LockMasterImpl {
// STATIC variables / methods
// A map from objects that are locked (or were locked), to information on their mutex
static std::map<const void *, std::pair<uv_mutex_t *, unsigned> > mutexes;
// A mutex used for the mutexes map
static uv_mutex_t mapMutex;
// A libuv key used to store the current thread-specific LockMasterImpl instance
static uv_key_t currentLockMasterKey;
// A libuv async handle used to trigger / debounce mutex cleanup
static uv_async_t cleanupMutexesHandle;
// Cleans up any mutexes that are not currently used
static void CleanupMutexes(uv_async_t *async);
public:
static void Initialize();
// INSTANCE variables / methods
private:
// The set of objects this LockMaster is responsible for locking
std::set<const void *> objectsToLock;
// Mutexes locked by this LockMaster on construction and unlocked on destruction
std::vector<uv_mutex_t *> GetMutexes(int useCountDelta);
void Register();
void Unregister();
void CleanupMutexes();
public:
static LockMasterImpl *CurrentLockMasterImpl() {
return (LockMasterImpl *)uv_key_get(¤tLockMasterKey);
}
LockMasterImpl() {
Register();
Lock(true);
}
~LockMasterImpl() {
Unregister();
Unlock(true);
CleanupMutexes();
}
void ObjectToLock(const void *objectToLock) {
objectsToLock.insert(objectToLock);
}
void Lock(bool acquireMutexes);
void Unlock(bool releaseMutexes);
};
std::map<const void *, std::pair<uv_mutex_t *, unsigned> > LockMasterImpl::mutexes;
uv_mutex_t LockMasterImpl::mapMutex;
uv_key_t LockMasterImpl::currentLockMasterKey;
uv_async_t LockMasterImpl::cleanupMutexesHandle;
void LockMasterImpl::Initialize() {
uv_mutex_init(&mapMutex);
uv_key_create(¤tLockMasterKey);
uv_async_init(uv_default_loop(), &cleanupMutexesHandle, CleanupMutexes);
}
void LockMasterImpl::CleanupMutexes(uv_async_t *async) {
uv_mutex_lock(&mapMutex);
for (auto it = mutexes.begin(); it != mutexes.end(); )
{
uv_mutex_t *mutex = it->second.first;
unsigned use_count = it->second.second;
// if the mutex is only referenced by the mutexes map,
// we can destroy it (because any LockMaster that is using the mutex would
// hold it in its objectMutexes)
if (!use_count) {
uv_mutex_destroy(mutex);
free(mutex);
auto to_erase = it;
it++;
mutexes.erase(to_erase);
} else {
it++;
}
}
uv_mutex_unlock(&mapMutex);
}
void LockMaster::Initialize() {
LockMasterImpl::Initialize();
}
std::vector<uv_mutex_t *> LockMasterImpl::GetMutexes(int useCountDelta) {
std::vector<uv_mutex_t *> objectMutexes;
uv_mutex_lock(&mapMutex);
for (auto object : objectsToLock) {
if(object) {
// ensure we have an initialized mutex for each object
auto mutexIt = mutexes.find(object);
if(mutexIt == mutexes.end()) {
mutexIt = mutexes.insert(
std::make_pair(
object,
std::make_pair((uv_mutex_t *)malloc(sizeof(uv_mutex_t)), 0U)
)
).first;
uv_mutex_init(mutexIt->second.first);
}
objectMutexes.push_back(mutexIt->second.first);
mutexIt->second.second += useCountDelta;
}
}
uv_mutex_unlock(&mapMutex);
return objectMutexes;
}
void LockMasterImpl::Register() {
uv_key_set(¤tLockMasterKey, this);
}
void LockMasterImpl::Unregister() {
uv_key_set(¤tLockMasterKey, NULL);
}
void LockMasterImpl::Lock(bool acquireMutexes) {
std::vector<uv_mutex_t *> objectMutexes = GetMutexes(acquireMutexes * 1);
auto alreadyLocked = objectMutexes.end();
// we will attempt to lock all the mutexes at the same time to avoid deadlocks
// note in most cases we are locking 0 or 1 mutexes. more than 1 implies
// passing objects with different repos/owners in the same call.
std::vector<uv_mutex_t *>::iterator it;
do {
// go through all the mutexes and try to lock them
for(it = objectMutexes.begin(); it != objectMutexes.end(); it++) {
// if we already locked this mutex in a previous pass via uv_mutex_lock,
// we don't need to lock it again
if (it == alreadyLocked) {
continue;
}
// first, try to lock (non-blocking)
bool failure = uv_mutex_trylock(*it);
if(failure) {
// we have failed to lock a mutex... unlock everything we have locked
std::for_each(objectMutexes.begin(), it, uv_mutex_unlock);
if (alreadyLocked > it && alreadyLocked != objectMutexes.end()) {
uv_mutex_unlock(*alreadyLocked);
}
// now do a blocking lock on what we couldn't lock
uv_mutex_lock(*it);
// mark that we have already locked this one
// if there are more mutexes than this one, we will go back to locking everything
alreadyLocked = it;
break;
}
}
} while(it != objectMutexes.end());
}
void LockMasterImpl::Unlock(bool releaseMutexes) {
std::vector<uv_mutex_t *> objectMutexes = GetMutexes(releaseMutexes * -1);
std::for_each(objectMutexes.begin(), objectMutexes.end(), uv_mutex_unlock);
}
void LockMasterImpl::CleanupMutexes() {
// schedule mutex cleanup on the main event loop
// this somewhat delays and debounces cleanup (uv_async_send coalesces calls)
uv_async_send(&cleanupMutexesHandle);
}
// LockMaster
void LockMaster::ConstructorImpl() {
impl = new LockMasterImpl();
}
void LockMaster::DestructorImpl() {
delete impl;
}
void LockMaster::ObjectToLock(const void *objectToLock) {
impl->ObjectToLock(objectToLock);
}
// LockMaster::TemporaryUnlock
void LockMaster::TemporaryUnlock::ConstructorImpl() {
impl = LockMasterImpl::CurrentLockMasterImpl();
impl->Unlock(false);
}
void LockMaster::TemporaryUnlock::DestructorImpl() {
impl->Lock(false);
}
bool LockMaster::enabled = false;
<commit_msg>Use ObjectInfo instead of pair for readability<commit_after>#include <git2.h>
#include <uv.h>
#include <set>
#include <vector>
#include <map>
#include <algorithm>
#include "../include/lock_master.h"
// information about a lockable object
// - the mutex used to lock it and the number of outstanding locks
struct ObjectInfo {
uv_mutex_t *mutex;
unsigned useCount;
ObjectInfo(uv_mutex_t *mutex, unsigned useCount)
: mutex(mutex), useCount(useCount)
{}
};
// LockMaster implementation details
// implemented in a separate class to keep LockMaster opaque
class LockMasterImpl {
// STATIC variables / methods
// A map from objects that are locked (or were locked), to information on their mutex
static std::map<const void *, ObjectInfo> mutexes;
// A mutex used for the mutexes map
static uv_mutex_t mapMutex;
// A libuv key used to store the current thread-specific LockMasterImpl instance
static uv_key_t currentLockMasterKey;
// A libuv async handle used to trigger / debounce mutex cleanup
static uv_async_t cleanupMutexesHandle;
// Cleans up any mutexes that are not currently used
static void CleanupMutexes(uv_async_t *async);
public:
static void Initialize();
// INSTANCE variables / methods
private:
// The set of objects this LockMaster is responsible for locking
std::set<const void *> objectsToLock;
// Mutexes locked by this LockMaster on construction and unlocked on destruction
std::vector<uv_mutex_t *> GetMutexes(int useCountDelta);
void Register();
void Unregister();
void CleanupMutexes();
public:
static LockMasterImpl *CurrentLockMasterImpl() {
return (LockMasterImpl *)uv_key_get(¤tLockMasterKey);
}
LockMasterImpl() {
Register();
Lock(true);
}
~LockMasterImpl() {
Unregister();
Unlock(true);
CleanupMutexes();
}
void ObjectToLock(const void *objectToLock) {
objectsToLock.insert(objectToLock);
}
void Lock(bool acquireMutexes);
void Unlock(bool releaseMutexes);
};
std::map<const void *, ObjectInfo> LockMasterImpl::mutexes;
uv_mutex_t LockMasterImpl::mapMutex;
uv_key_t LockMasterImpl::currentLockMasterKey;
uv_async_t LockMasterImpl::cleanupMutexesHandle;
void LockMasterImpl::Initialize() {
uv_mutex_init(&mapMutex);
uv_key_create(¤tLockMasterKey);
uv_async_init(uv_default_loop(), &cleanupMutexesHandle, CleanupMutexes);
}
void LockMasterImpl::CleanupMutexes(uv_async_t *async) {
uv_mutex_lock(&mapMutex);
for (auto it = mutexes.begin(); it != mutexes.end(); )
{
uv_mutex_t *mutex = it->second.mutex;
unsigned useCount = it->second.useCount;
// if the mutex is not used by any LockMasters,
// we can destroy it
if (!useCount) {
uv_mutex_destroy(mutex);
free(mutex);
auto to_erase = it;
it++;
mutexes.erase(to_erase);
} else {
it++;
}
}
uv_mutex_unlock(&mapMutex);
}
void LockMaster::Initialize() {
LockMasterImpl::Initialize();
}
std::vector<uv_mutex_t *> LockMasterImpl::GetMutexes(int useCountDelta) {
std::vector<uv_mutex_t *> objectMutexes;
uv_mutex_lock(&mapMutex);
for (auto object : objectsToLock) {
if(object) {
// ensure we have an initialized mutex for each object
auto mutexIt = mutexes.find(object);
if(mutexIt == mutexes.end()) {
mutexIt = mutexes.insert(
std::make_pair(
object,
ObjectInfo((uv_mutex_t *)malloc(sizeof(uv_mutex_t)), 0U)
)
).first;
uv_mutex_init(mutexIt->second.mutex);
}
objectMutexes.push_back(mutexIt->second.mutex);
mutexIt->second.useCount += useCountDelta;
}
}
uv_mutex_unlock(&mapMutex);
return objectMutexes;
}
void LockMasterImpl::Register() {
uv_key_set(¤tLockMasterKey, this);
}
void LockMasterImpl::Unregister() {
uv_key_set(¤tLockMasterKey, NULL);
}
void LockMasterImpl::Lock(bool acquireMutexes) {
std::vector<uv_mutex_t *> objectMutexes = GetMutexes(acquireMutexes * 1);
auto alreadyLocked = objectMutexes.end();
// we will attempt to lock all the mutexes at the same time to avoid deadlocks
// note in most cases we are locking 0 or 1 mutexes. more than 1 implies
// passing objects with different repos/owners in the same call.
std::vector<uv_mutex_t *>::iterator it;
do {
// go through all the mutexes and try to lock them
for(it = objectMutexes.begin(); it != objectMutexes.end(); it++) {
// if we already locked this mutex in a previous pass via uv_mutex_lock,
// we don't need to lock it again
if (it == alreadyLocked) {
continue;
}
// first, try to lock (non-blocking)
bool failure = uv_mutex_trylock(*it);
if(failure) {
// we have failed to lock a mutex... unlock everything we have locked
std::for_each(objectMutexes.begin(), it, uv_mutex_unlock);
if (alreadyLocked > it && alreadyLocked != objectMutexes.end()) {
uv_mutex_unlock(*alreadyLocked);
}
// now do a blocking lock on what we couldn't lock
uv_mutex_lock(*it);
// mark that we have already locked this one
// if there are more mutexes than this one, we will go back to locking everything
alreadyLocked = it;
break;
}
}
} while(it != objectMutexes.end());
}
void LockMasterImpl::Unlock(bool releaseMutexes) {
std::vector<uv_mutex_t *> objectMutexes = GetMutexes(releaseMutexes * -1);
std::for_each(objectMutexes.begin(), objectMutexes.end(), uv_mutex_unlock);
}
void LockMasterImpl::CleanupMutexes() {
// schedule mutex cleanup on the main event loop
// this somewhat delays and debounces cleanup (uv_async_send coalesces calls)
uv_async_send(&cleanupMutexesHandle);
}
// LockMaster
void LockMaster::ConstructorImpl() {
impl = new LockMasterImpl();
}
void LockMaster::DestructorImpl() {
delete impl;
}
void LockMaster::ObjectToLock(const void *objectToLock) {
impl->ObjectToLock(objectToLock);
}
// LockMaster::TemporaryUnlock
void LockMaster::TemporaryUnlock::ConstructorImpl() {
impl = LockMasterImpl::CurrentLockMasterImpl();
impl->Unlock(false);
}
void LockMaster::TemporaryUnlock::DestructorImpl() {
impl->Lock(false);
}
bool LockMaster::enabled = false;
<|endoftext|> |
<commit_before>// Copyright 2014 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 "config.h"
#include "core/inspector/inspector_backend_mojo.h"
#include "base/memory/scoped_ptr.h"
#include "base/run_loop.h"
#include "bindings/core/v8/PageScriptDebugServer.h"
#include "bindings/core/v8/ScriptController.h"
#include "core/frame/FrameHost.h"
#include "core/inspector/InspectorState.h"
#include "core/inspector/InstrumentingAgents.h"
#include "core/inspector/PageDebuggerAgent.h"
#include "core/InspectorBackendDispatcher.h"
#include "core/page/Page.h"
#include "mojo/public/cpp/application/connect.h"
#include "mojo/public/cpp/application/service_provider_impl.h"
#include "mojo/public/interfaces/application/shell.mojom.h"
#include "platform/JSONValues.h"
#include "public/platform/ServiceProvider.h"
namespace blink {
class MessageLoopAdaptor : public PageScriptDebugServer::ClientMessageLoop {
public:
MessageLoopAdaptor() { }
private:
virtual void run(Page* page)
{
if (run_loop_)
return;
run_loop_.reset(new base::RunLoop());
run_loop_->Run();
}
virtual void quitNow()
{
if (run_loop_)
run_loop_->Quit();
}
scoped_ptr<base::RunLoop> run_loop_;
};
InspectorBackendMojo::InspectorBackendMojo(const FrameHost& frame_host)
: frame_host_(frame_host) {
}
InspectorBackendMojo::~InspectorBackendMojo() {
}
void InspectorBackendMojo::Connect() {
mojo::Shell* shell = frame_host_.services().Shell();
mojo::ServiceProviderPtr inspector_service_provider;
shell->ConnectToApplication("mojo:sky_inspector_server",
GetProxy(&inspector_service_provider));
mojo::ConnectToService(inspector_service_provider.get(), &frontend_);
frontend_.set_client(this);
// Theoretically we should load our state from the inspector cookie.
inspector_state_ = adoptPtr(new InspectorState(nullptr, JSONObject::create()));
old_frontend_ = adoptPtr(new InspectorFrontend(this));
v8::Isolate* isolate = frame_host_.page().mainFrame()->script().isolate();
PageScriptDebugServer::setMainThreadIsolate(isolate);
OwnPtr<MessageLoopAdaptor> message_loop = adoptPtr(new MessageLoopAdaptor);
PageScriptDebugServer::shared().setClientMessageLoop(message_loop.release());
// AgentRegistry used to do this, but we don't need it for one agent.
script_manager_ = InjectedScriptManager::createForPage();
debugger_agent_ = PageDebuggerAgent::create(&PageScriptDebugServer::shared(), &frame_host_.page(), script_manager_.get());
agents_ = adoptPtr(new InstrumentingAgents(debugger_agent_.get()));
debugger_agent_->init(agents_.get(), inspector_state_.get());
debugger_agent_->setFrontend(old_frontend_.get());
dispatcher_ = InspectorBackendDispatcher::create(this);
dispatcher_->registerAgent(debugger_agent_.get());
}
void InspectorBackendMojo::sendMessageToFrontend(
PassRefPtr<JSONObject> message) {
frontend_->SendMessage(message->toJSONString().toUTF8());
}
void InspectorBackendMojo::flush() {
// TODO(eseidel): Unclear if this is needed.
}
void InspectorBackendMojo::OnConnect() {
}
void InspectorBackendMojo::OnDisconnect() {
}
void InspectorBackendMojo::OnMessage(const mojo::String& message) {
String wtf_message = String::fromUTF8(message.To<std::string>());
String command_name;
InspectorBackendDispatcher::getCommandName(wtf_message, &command_name);
// InspectorBackendDispatcher will automatically reply with errors
// if agents are missing, since we only want this backend to care about
// the Debugger agent, we manually filter here.
if (command_name.startsWith("Debugger"))
dispatcher_->dispatch(wtf_message);
}
} // namespace blink
<commit_msg>Make debugger stepping work in Sky<commit_after>// Copyright 2014 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 "config.h"
#include "core/inspector/inspector_backend_mojo.h"
#include "base/memory/scoped_ptr.h"
#include "base/run_loop.h"
#include "bindings/core/v8/PageScriptDebugServer.h"
#include "bindings/core/v8/ScriptController.h"
#include "core/frame/FrameHost.h"
#include "core/inspector/InspectorState.h"
#include "core/inspector/InstrumentingAgents.h"
#include "core/inspector/PageDebuggerAgent.h"
#include "core/InspectorBackendDispatcher.h"
#include "core/page/Page.h"
#include "mojo/public/cpp/application/connect.h"
#include "mojo/public/cpp/application/service_provider_impl.h"
#include "mojo/public/interfaces/application/shell.mojom.h"
#include "platform/JSONValues.h"
#include "public/platform/ServiceProvider.h"
namespace blink {
class MessageLoopAdaptor : public PageScriptDebugServer::ClientMessageLoop {
public:
MessageLoopAdaptor() { }
private:
virtual void run(Page* page)
{
run_loop_.reset(new base::RunLoop());
run_loop_->Run();
}
virtual void quitNow()
{
if (run_loop_)
run_loop_->Quit();
}
scoped_ptr<base::RunLoop> run_loop_;
};
InspectorBackendMojo::InspectorBackendMojo(const FrameHost& frame_host)
: frame_host_(frame_host) {
}
InspectorBackendMojo::~InspectorBackendMojo() {
}
void InspectorBackendMojo::Connect() {
mojo::Shell* shell = frame_host_.services().Shell();
mojo::ServiceProviderPtr inspector_service_provider;
shell->ConnectToApplication("mojo:sky_inspector_server",
GetProxy(&inspector_service_provider));
mojo::ConnectToService(inspector_service_provider.get(), &frontend_);
frontend_.set_client(this);
// Theoretically we should load our state from the inspector cookie.
inspector_state_ = adoptPtr(new InspectorState(nullptr, JSONObject::create()));
old_frontend_ = adoptPtr(new InspectorFrontend(this));
v8::Isolate* isolate = frame_host_.page().mainFrame()->script().isolate();
PageScriptDebugServer::setMainThreadIsolate(isolate);
OwnPtr<MessageLoopAdaptor> message_loop = adoptPtr(new MessageLoopAdaptor);
PageScriptDebugServer::shared().setClientMessageLoop(message_loop.release());
// AgentRegistry used to do this, but we don't need it for one agent.
script_manager_ = InjectedScriptManager::createForPage();
debugger_agent_ = PageDebuggerAgent::create(&PageScriptDebugServer::shared(), &frame_host_.page(), script_manager_.get());
agents_ = adoptPtr(new InstrumentingAgents(debugger_agent_.get()));
debugger_agent_->init(agents_.get(), inspector_state_.get());
debugger_agent_->setFrontend(old_frontend_.get());
dispatcher_ = InspectorBackendDispatcher::create(this);
dispatcher_->registerAgent(debugger_agent_.get());
}
void InspectorBackendMojo::sendMessageToFrontend(
PassRefPtr<JSONObject> message) {
frontend_->SendMessage(message->toJSONString().toUTF8());
}
void InspectorBackendMojo::flush() {
// TODO(eseidel): Unclear if this is needed.
}
void InspectorBackendMojo::OnConnect() {
}
void InspectorBackendMojo::OnDisconnect() {
}
void InspectorBackendMojo::OnMessage(const mojo::String& message) {
String wtf_message = String::fromUTF8(message.To<std::string>());
String command_name;
InspectorBackendDispatcher::getCommandName(wtf_message, &command_name);
// InspectorBackendDispatcher will automatically reply with errors
// if agents are missing, since we only want this backend to care about
// the Debugger agent, we manually filter here.
if (command_name.startsWith("Debugger"))
dispatcher_->dispatch(wtf_message);
}
} // namespace blink
<|endoftext|> |
<commit_before>#include "plan_request.hpp"
namespace planning {
void fill_obstacles(const PlanRequest& in, rj_geometry::ShapeSet* out_static,
std::vector<DynamicObstacle>* out_dynamic, bool avoid_ball,
Trajectory* out_ball_trajectory) {
out_static->clear();
out_static->add(in.field_obstacles);
out_static->add(in.virtual_obstacles);
// Add opponent robots as static obstacles.
for (int shell = 0; shell < kNumShells; shell++) {
const auto& robot = in.world_state->their_robots.at(shell);
if (robot.visible) {
out_static->add(
std::make_shared<rj_geometry::Circle>(robot.pose.position(), kRobotRadius));
}
}
// Add our robots, either static or dynamic depending on whether they have
// already been planned.
for (int shell = 0; shell < kNumShells; shell++) {
const auto& robot = in.world_state->our_robots.at(shell);
if (!robot.visible || shell == in.shell_id) {
continue;
}
if (out_dynamic != nullptr && in.planned_trajectories.at(shell) != nullptr) {
// Dynamic obstacle
out_dynamic->emplace_back(kRobotRadius, in.planned_trajectories.at(shell));
} else {
// Static obstacle
out_static->add(
std::make_shared<rj_geometry::Circle>(robot.pose.position(), kRobotRadius));
}
}
// Finally, add the ball as a dynamic obstacle.
if (avoid_ball && out_dynamic != nullptr && out_ball_trajectory != nullptr) {
// Where should we store the ball trajectory?
*out_ball_trajectory = in.world_state->ball.make_trajectory();
out_dynamic->emplace_back(kBallRadius, out_ball_trajectory);
}
}
} // namespace planning<commit_msg>reduce motion planner obs by 10% for our robots radius, introduces crashing<commit_after>#include "plan_request.hpp"
namespace planning {
void fill_obstacles(const PlanRequest& in, rj_geometry::ShapeSet* out_static,
std::vector<DynamicObstacle>* out_dynamic, bool avoid_ball,
Trajectory* out_ball_trajectory) {
out_static->clear();
out_static->add(in.field_obstacles);
out_static->add(in.virtual_obstacles);
// Add opponent robots as static obstacles.
for (int shell = 0; shell < kNumShells; shell++) {
const auto& robot = in.world_state->their_robots.at(shell);
if (robot.visible) {
out_static->add(
std::make_shared<rj_geometry::Circle>(robot.pose.position(), kRobotRadius * 1.0));
}
}
// Add our robots, either static or dynamic depending on whether they have
// already been planned.
//
// 0.90 weight to make robots less hesitant to wall
for (int shell = 0; shell < kNumShells; shell++) {
const auto& robot = in.world_state->our_robots.at(shell);
if (!robot.visible || shell == in.shell_id) {
continue;
}
if (out_dynamic != nullptr && in.planned_trajectories.at(shell) != nullptr) {
// Dynamic obstacle
out_dynamic->emplace_back(kRobotRadius * 0.90, in.planned_trajectories.at(shell));
} else {
// Static obstacle
out_static->add(
std::make_shared<rj_geometry::Circle>(robot.pose.position(), kRobotRadius * 0.90));
}
}
// Finally, add the ball as a dynamic obstacle.
if (avoid_ball && out_dynamic != nullptr && out_ball_trajectory != nullptr) {
// Where should we store the ball trajectory?
*out_ball_trajectory = in.world_state->ball.make_trajectory();
out_dynamic->emplace_back(kBallRadius, out_ball_trajectory);
}
}
} // namespace planning
<|endoftext|> |
<commit_before>/*
* Copyright 2012 Michael Chen <omxcodec@gmail.com>
*
* 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.
*/
//#define LOG_NDEBUG 0
#define LOG_TAG "FFMPEG"
#include <utils/Log.h>
#include <stdlib.h>
#include <media/stagefright/DataSource.h>
#ifdef __cplusplus
extern "C" {
#endif
#include "config.h"
#include "libavformat/url.h"
#ifdef __cplusplus
}
#endif
namespace android {
class FFSource
{
public:
FFSource(DataSource *source);
int init_check();
int read(unsigned char *buf, size_t size);
int64_t seek(int64_t pos);
off64_t getSize();
~FFSource();
protected:
sp<DataSource> mSource;
int64_t mOffset;
};
FFSource::FFSource(DataSource *source)
: mSource(source),
mOffset(0)
{
}
FFSource::~FFSource()
{
mSource = NULL;
}
int FFSource::init_check()
{
if (mSource->initCheck() != OK) {
ALOGE("FFSource initCheck failed");
return -1;
}
return 0;
}
int FFSource::read(unsigned char *buf, size_t size)
{
ssize_t n = 0;
n = mSource->readAt(mOffset, buf, size);
if (n == UNKNOWN_ERROR) {
ALOGE("FFSource readAt failed");
return AVERROR(errno);
}
if (n > 0) {
mOffset += n;
}
return n;
}
int64_t FFSource::seek(int64_t pos)
{
mOffset = pos;
return 0;
}
off64_t FFSource::getSize()
{
off64_t sz = -1;
if (mSource->getSize(&sz) != OK) {
ALOGE("FFSource getSize failed");
return AVERROR(errno);
}
return sz;
}
/////////////////////////////////////////////////////////////////
static int android_open(URLContext *h, const char *url, int flags __unused)
{
// the url in form of "android-source:<DataSource Ptr>",
// the DataSource Pointer passed by the ffmpeg extractor
DataSource *source = NULL;
char url_check[PATH_MAX] = {0};
ALOGV("android source begin open");
if (!url) {
ALOGE("android url is null!");
return -1;
}
ALOGV("android open, url: %s", url);
sscanf(url + strlen("android-source:"), "%p", &source);
if(source == NULL){
ALOGE("ffmpeg open data source error! (invalid source)");
return -1;
}
snprintf(url_check, sizeof(url_check), "android-source:%p",
source);
if (strcmp(url_check, url) != 0) {
String8 uri = source->getUri();
if (!uri.string()) {
ALOGE("ffmpeg open data source error! (source uri)");
return -1;
}
snprintf(url_check, sizeof(url_check), "android-source:%p|file:%s",
source, uri.string());
if (strcmp(url_check, url) != 0) {
ALOGE("ffmpeg open data source error! (url check)");
return -1;
}
}
ALOGV("ffmpeg open android data source success, source ptr: %p", source);
FFSource *ffs = new FFSource(source);
h->priv_data = (void *)ffs;
ALOGV("android source open success");
return 0;
}
static int android_read(URLContext *h, unsigned char *buf, int size)
{
FFSource* ffs = (FFSource *)h->priv_data;
return ffs->read(buf, size);
}
static int android_write(URLContext *h __unused, const unsigned char *buf __unused, int size __unused)
{
return -1;
}
static int64_t android_seek(URLContext *h, int64_t pos, int whence)
{
FFSource* ffs = (FFSource*)h->priv_data;
if (whence == AVSEEK_SIZE) {
return ffs->getSize();
}
ffs->seek(pos);
return 0;
}
static int android_close(URLContext *h)
{
FFSource* ffs = (FFSource*)h->priv_data;
ALOGV("android source close");
delete ffs;
return 0;
}
static int android_get_handle(URLContext *h)
{
return (intptr_t)h->priv_data;
}
static int android_check(URLContext *h, int mask)
{
FFSource* ffs = (FFSource*)h->priv_data;
if (ffs->init_check() < 0)
return AVERROR(EACCES); // FIXME
return (mask & AVIO_FLAG_READ);
}
static URLProtocol ff_android_protocol;
void ffmpeg_register_android_source()
{
memset(&ff_android_protocol, 0, sizeof(URLProtocol));
ff_android_protocol.name = "android-source";
ff_android_protocol.url_open = android_open;
ff_android_protocol.url_read = android_read;
ff_android_protocol.url_write = android_write;
ff_android_protocol.url_seek = android_seek;
ff_android_protocol.url_close = android_close;
ff_android_protocol.url_get_file_handle = android_get_handle;
ff_android_protocol.url_check = android_check;
ffurl_register_protocol(&ff_android_protocol);
}
} // namespace android
<commit_msg>ffmpeg: Fix crash when avio_check is called<commit_after>/*
* Copyright 2012 Michael Chen <omxcodec@gmail.com>
*
* 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.
*/
//#define LOG_NDEBUG 0
#define LOG_TAG "FFMPEG"
#include <utils/Log.h>
#include <stdlib.h>
#include <media/stagefright/DataSource.h>
#ifdef __cplusplus
extern "C" {
#endif
#include "config.h"
#include "libavformat/url.h"
#ifdef __cplusplus
}
#endif
namespace android {
class FFSource
{
public:
FFSource(DataSource *source);
int init_check();
int read(unsigned char *buf, size_t size);
int64_t seek(int64_t pos);
off64_t getSize();
~FFSource();
protected:
sp<DataSource> mSource;
int64_t mOffset;
};
FFSource::FFSource(DataSource *source)
: mSource(source),
mOffset(0)
{
}
FFSource::~FFSource()
{
mSource = NULL;
}
int FFSource::init_check()
{
if (mSource->initCheck() != OK) {
ALOGE("FFSource initCheck failed");
return -1;
}
return 0;
}
int FFSource::read(unsigned char *buf, size_t size)
{
ssize_t n = 0;
n = mSource->readAt(mOffset, buf, size);
if (n == UNKNOWN_ERROR) {
ALOGE("FFSource readAt failed");
return AVERROR(errno);
}
if (n > 0) {
mOffset += n;
}
return n;
}
int64_t FFSource::seek(int64_t pos)
{
mOffset = pos;
return 0;
}
off64_t FFSource::getSize()
{
off64_t sz = -1;
if (mSource->getSize(&sz) != OK) {
ALOGE("FFSource getSize failed");
return AVERROR(errno);
}
return sz;
}
/////////////////////////////////////////////////////////////////
static int android_open(URLContext *h, const char *url, int flags __unused)
{
// the url in form of "android-source:<DataSource Ptr>",
// the DataSource Pointer passed by the ffmpeg extractor
DataSource *source = NULL;
char url_check[PATH_MAX] = {0};
ALOGV("android source begin open");
if (!url) {
ALOGE("android url is null!");
return -1;
}
ALOGV("android open, url: %s", url);
sscanf(url + strlen("android-source:"), "%p", &source);
if(source == NULL){
ALOGE("ffmpeg open data source error! (invalid source)");
return -1;
}
snprintf(url_check, sizeof(url_check), "android-source:%p",
source);
if (strcmp(url_check, url) != 0) {
String8 uri = source->getUri();
if (!uri.string()) {
ALOGE("ffmpeg open data source error! (source uri)");
return -1;
}
snprintf(url_check, sizeof(url_check), "android-source:%p|file:%s",
source, uri.string());
if (strcmp(url_check, url) != 0) {
ALOGE("ffmpeg open data source error! (url check)");
return -1;
}
}
ALOGV("ffmpeg open android data source success, source ptr: %p", source);
FFSource *ffs = new FFSource(source);
h->priv_data = (void *)ffs;
ALOGV("android source open success");
return 0;
}
static int android_read(URLContext *h, unsigned char *buf, int size)
{
FFSource* ffs = (FFSource *)h->priv_data;
return ffs->read(buf, size);
}
static int android_write(URLContext *h __unused, const unsigned char *buf __unused, int size __unused)
{
return -1;
}
static int64_t android_seek(URLContext *h, int64_t pos, int whence)
{
FFSource* ffs = (FFSource*)h->priv_data;
if (whence == AVSEEK_SIZE) {
return ffs->getSize();
}
ffs->seek(pos);
return 0;
}
static int android_close(URLContext *h)
{
FFSource* ffs = (FFSource*)h->priv_data;
ALOGV("android source close");
delete ffs;
h->priv_data = NULL;
return 0;
}
static int android_get_handle(URLContext *h)
{
return (intptr_t)h->priv_data;
}
static int android_check(URLContext *h, int mask)
{
FFSource* ffs = (FFSource*)h->priv_data;
/* url_check does not guarantee url_open will be called
* (and actually it is not designed to do so)
* If url_open is not called before url_check called, ffs
* will be null, and we will assume everything is ok.
*/
if (ffs && (ffs->init_check() < 0))
return AVERROR(EACCES); // FIXME
return (mask & AVIO_FLAG_READ);
}
static URLProtocol ff_android_protocol;
void ffmpeg_register_android_source()
{
memset(&ff_android_protocol, 0, sizeof(URLProtocol));
ff_android_protocol.name = "android-source";
ff_android_protocol.url_open = android_open;
ff_android_protocol.url_read = android_read;
ff_android_protocol.url_write = android_write;
ff_android_protocol.url_seek = android_seek;
ff_android_protocol.url_close = android_close;
ff_android_protocol.url_get_file_handle = android_get_handle;
ff_android_protocol.url_check = android_check;
ffurl_register_protocol(&ff_android_protocol);
}
} // namespace android
<|endoftext|> |
<commit_before>/* filter_streams.cc
Jeremy Barnes, 17 March 2005
Copyright (c) 2005 Jeremy Barnes. All rights reserved.
This file is part of "Jeremy's Machine Learning Library", copyright (c)
1999-2005 Jeremy Barnes.
This program is available under the GNU General Public License, the terms
of which are given by the file "license.txt" in the top level directory of
the source code distribution. If this file is missing, you have no right
to use the program; please contact the author.
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.
---
Implementation of filter streams.
*/
#include "filter_streams.h"
#include <fstream>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/bzip2.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/version.hpp>
#include "jml/arch/exception.h"
#include "jml/arch/format.h"
#include <errno.h>
#include "lzma.h"
using namespace std;
namespace ML {
/*****************************************************************************/
/* FILTER_OSTREAM */
/*****************************************************************************/
filter_ostream::filter_ostream()
: ostream(std::cout.rdbuf())
{
}
filter_ostream::
filter_ostream(const std::string & file, std::ios_base::openmode mode,
const std::string & compression, int level)
: ostream(std::cout.rdbuf())
{
open(file, mode, compression, level);
}
filter_ostream::
filter_ostream(int fd, std::ios_base::openmode mode,
const std::string & compression, int level)
: ostream(std::cout.rdbuf())
{
open(fd, mode);
}
namespace {
bool ends_with(const std::string & str, const std::string & what)
{
string::size_type result = str.rfind(what);
return result != string::npos
&& result == str.size() - what.size();
}
} // file scope
void filter_ostream::
open(const std::string & file_, std::ios_base::openmode mode,
const std::string & compression, int level)
{
exceptions(ios::badbit | ios::failbit);
using namespace boost::iostreams;
string file = file_;
if (file == "") file = "/dev/null";
auto_ptr<filtering_ostream> new_stream
(new filtering_ostream());
if (compression == "gz" || compression == "gzip"
|| (compression == ""
&& (ends_with(file, ".gz") || ends_with(file, ".gz~")))) {
if (level == -1)
new_stream->push(gzip_compressor());
else new_stream->push(gzip_compressor(level));
}
else if (compression == "bz2" || compression == "bzip2"
|| (compression == ""
&& (ends_with(file, ".bz2") || ends_with(file, ".bz2~")))) {
if (level == -1)
new_stream->push(bzip2_compressor());
else new_stream->push(bzip2_compressor(level));
}
else if (compression == "lzma" || compression == "xz"
|| (compression == ""
&& (ends_with(file, ".xz") || ends_with(file, ".xz~")))) {
if (level == -1)
new_stream->push(lzma_compressor());
else new_stream->push(lzma_compressor(level));
}
else if (compression != "" && compression != "none")
throw ML::Exception("unknown filter compression " + compression);
if (file == "-") {
new_stream->push(std::cout);
}
else {
file_sink sink(file.c_str(), mode);
if (!sink.is_open())
throw Exception("couldn't open file " + file);
new_stream->push(sink);
}
stream.reset(new_stream.release());
rdbuf(stream->rdbuf());
//stream.reset(new ofstream(file.c_str(), mode));
}
void filter_ostream::
open(int fd, std::ios_base::openmode mode,
const std::string & compression, int level)
{
exceptions(ios::badbit | ios::failbit);
using namespace boost::iostreams;
auto_ptr<filtering_ostream> new_stream
(new filtering_ostream());
if (compression == "gz" || compression == "gzip") {
if (level == -1)
new_stream->push(gzip_compressor());
else new_stream->push(gzip_compressor(level));
}
else if (compression == "bz2" || compression == "bzip2") {
if (level == -1)
new_stream->push(bzip2_compressor());
else new_stream->push(bzip2_compressor(level));
}
else if (compression == "lzma" || compression == "xz") {
if (level == -1)
new_stream->push(lzma_compressor());
else new_stream->push(lzma_compressor(level));
}
else if (compression != "" && compression != "none")
throw ML::Exception("unknown filter compression " + compression);
#if (BOOST_VERSION < 104100)
new_stream->push(file_descriptor_sink(fd));
#else
new_stream->push(file_descriptor_sink(fd,
boost::iostreams::never_close_handle));
#endif
stream.reset(new_stream.release());
rdbuf(stream->rdbuf());
//stream.reset(new ofstream(file.c_str(), mode));
}
void
filter_ostream::
close()
{
rdbuf(0);
//stream->close();
}
std::string
filter_ostream::
status() const
{
if (*this) return "good";
else return format("%s%s%s",
fail() ? " fail" : "",
bad() ? " bad" : "",
eof() ? " eof" : "");
}
/*****************************************************************************/
/* FILTER_ISTREAM */
/*****************************************************************************/
filter_istream::filter_istream()
: istream(std::cin.rdbuf())
{
}
filter_istream::
filter_istream(const std::string & file, std::ios_base::openmode mode)
: istream(std::cin.rdbuf())
{
open(file, mode);
}
void filter_istream::
open(const std::string & file_, std::ios_base::openmode mode)
{
using namespace boost::iostreams;
exceptions(ios::badbit);
string file = file_;
if (file == "") file = "/dev/null";
auto_ptr<filtering_istream> new_stream
(new filtering_istream());
bool gzip = (ends_with(file, ".gz") || ends_with(file, ".gz~"));
bool bzip2 = (ends_with(file, ".bz2") || ends_with(file, ".bz2~"));
bool lzma = (ends_with(file, ".xz") || ends_with(file, ".xz~"));
if (gzip) new_stream->push(gzip_decompressor());
if (bzip2) new_stream->push(bzip2_decompressor());
if (lzma) new_stream->push(lzma_decompressor());
if (file == "-") {
new_stream->push(std::cin);
}
else {
file_source source(file.c_str(), mode);
if (!source.is_open())
throw Exception("stream open failed for file %s: %s",
file_.c_str(), strerror(errno));
new_stream->push(source);
}
stream.reset(new_stream.release());
rdbuf(stream->rdbuf());
}
void
filter_istream::
close()
{
rdbuf(0);
//stream->close();
}
} // namespace ML
<commit_msg>filter_ostream exceptions improvements<commit_after>/* filter_streams.cc
Jeremy Barnes, 17 March 2005
Copyright (c) 2005 Jeremy Barnes. All rights reserved.
This file is part of "Jeremy's Machine Learning Library", copyright (c)
1999-2005 Jeremy Barnes.
This program is available under the GNU General Public License, the terms
of which are given by the file "license.txt" in the top level directory of
the source code distribution. If this file is missing, you have no right
to use the program; please contact the author.
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.
---
Implementation of filter streams.
*/
#include "filter_streams.h"
#include <fstream>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/bzip2.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/version.hpp>
#include "jml/arch/exception.h"
#include "jml/arch/format.h"
#include <errno.h>
#include "lzma.h"
using namespace std;
namespace ML {
/*****************************************************************************/
/* FILTER_OSTREAM */
/*****************************************************************************/
filter_ostream::filter_ostream()
: ostream(std::cout.rdbuf())
{
}
filter_ostream::
filter_ostream(const std::string & file, std::ios_base::openmode mode,
const std::string & compression, int level)
: ostream(std::cout.rdbuf())
{
open(file, mode, compression, level);
}
filter_ostream::
filter_ostream(int fd, std::ios_base::openmode mode,
const std::string & compression, int level)
: ostream(std::cout.rdbuf())
{
open(fd, mode);
}
namespace {
bool ends_with(const std::string & str, const std::string & what)
{
string::size_type result = str.rfind(what);
return result != string::npos
&& result == str.size() - what.size();
}
} // file scope
void filter_ostream::
open(const std::string & file_, std::ios_base::openmode mode,
const std::string & compression, int level)
{
using namespace boost::iostreams;
string file = file_;
if (file == "") file = "/dev/null";
auto_ptr<filtering_ostream> new_stream
(new filtering_ostream());
if (compression == "gz" || compression == "gzip"
|| (compression == ""
&& (ends_with(file, ".gz") || ends_with(file, ".gz~")))) {
if (level == -1)
new_stream->push(gzip_compressor());
else new_stream->push(gzip_compressor(level));
}
else if (compression == "bz2" || compression == "bzip2"
|| (compression == ""
&& (ends_with(file, ".bz2") || ends_with(file, ".bz2~")))) {
if (level == -1)
new_stream->push(bzip2_compressor());
else new_stream->push(bzip2_compressor(level));
}
else if (compression == "lzma" || compression == "xz"
|| (compression == ""
&& (ends_with(file, ".xz") || ends_with(file, ".xz~")))) {
if (level == -1)
new_stream->push(lzma_compressor());
else new_stream->push(lzma_compressor(level));
}
else if (compression != "" && compression != "none")
throw ML::Exception("unknown filter compression " + compression);
if (file == "-") {
new_stream->push(std::cout);
}
else {
file_sink sink(file.c_str(), mode);
if (!sink.is_open())
throw Exception("couldn't open file " + file);
new_stream->push(sink);
}
stream.reset(new_stream.release());
rdbuf(stream->rdbuf());
exceptions(ios::badbit | ios::failbit);
}
void filter_ostream::
open(int fd, std::ios_base::openmode mode,
const std::string & compression, int level)
{
using namespace boost::iostreams;
auto_ptr<filtering_ostream> new_stream
(new filtering_ostream());
if (compression == "gz" || compression == "gzip") {
if (level == -1)
new_stream->push(gzip_compressor());
else new_stream->push(gzip_compressor(level));
}
else if (compression == "bz2" || compression == "bzip2") {
if (level == -1)
new_stream->push(bzip2_compressor());
else new_stream->push(bzip2_compressor(level));
}
else if (compression == "lzma" || compression == "xz") {
if (level == -1)
new_stream->push(lzma_compressor());
else new_stream->push(lzma_compressor(level));
}
else if (compression != "" && compression != "none")
throw ML::Exception("unknown filter compression " + compression);
#if (BOOST_VERSION < 104100)
new_stream->push(file_descriptor_sink(fd));
#else
new_stream->push(file_descriptor_sink(fd,
boost::iostreams::never_close_handle));
#endif
stream.reset(new_stream.release());
rdbuf(stream->rdbuf());
exceptions(ios::badbit | ios::failbit);
}
void
filter_ostream::
close()
{
rdbuf(0);
//stream->close();
}
std::string
filter_ostream::
status() const
{
if (*this) return "good";
else return format("%s%s%s",
fail() ? " fail" : "",
bad() ? " bad" : "",
eof() ? " eof" : "");
}
/*****************************************************************************/
/* FILTER_ISTREAM */
/*****************************************************************************/
filter_istream::filter_istream()
: istream(std::cin.rdbuf())
{
}
filter_istream::
filter_istream(const std::string & file, std::ios_base::openmode mode)
: istream(std::cin.rdbuf())
{
open(file, mode);
}
void filter_istream::
open(const std::string & file_, std::ios_base::openmode mode)
{
using namespace boost::iostreams;
exceptions(ios::badbit);
string file = file_;
if (file == "") file = "/dev/null";
auto_ptr<filtering_istream> new_stream
(new filtering_istream());
bool gzip = (ends_with(file, ".gz") || ends_with(file, ".gz~"));
bool bzip2 = (ends_with(file, ".bz2") || ends_with(file, ".bz2~"));
bool lzma = (ends_with(file, ".xz") || ends_with(file, ".xz~"));
if (gzip) new_stream->push(gzip_decompressor());
if (bzip2) new_stream->push(bzip2_decompressor());
if (lzma) new_stream->push(lzma_decompressor());
if (file == "-") {
new_stream->push(std::cin);
}
else {
file_source source(file.c_str(), mode);
if (!source.is_open())
throw Exception("stream open failed for file %s: %s",
file_.c_str(), strerror(errno));
new_stream->push(source);
}
stream.reset(new_stream.release());
rdbuf(stream->rdbuf());
}
void
filter_istream::
close()
{
rdbuf(0);
//stream->close();
}
} // namespace ML
<|endoftext|> |
<commit_before>#define CATCH_CONFIG_MAIN
#include "catch/catch.hpp"
#include "tangram.h"
#include "labels/label.h"
#include "labels/textLabel.h"
#include "glm/mat4x4.hpp"
#include "glm/gtc/matrix_transform.hpp"
#define EPSILON 0.00001
using namespace Tangram;
glm::vec2 screenSize(500.f, 500.f);
TextBuffer dummy(nullptr);
TextLabel makeLabel(Label::Transform _transform, Label::Type _type) {
Label::Options options;
options.color = 0xff;
options.offset = {0.0f, 0.0f};
return TextLabel("label", _transform, _type, {0, 0}, dummy, {0, 0}, options);
}
TEST_CASE( "Ensure the transition from wait -> sleep when occlusion happens", "[Core][Label]" ) {
TextLabel l(makeLabel({screenSize/2.f}, Label::Type::point));
REQUIRE(l.getState() == Label::State::wait_occ);
l.setOcclusion(true);
l.update(glm::ortho(0.f, screenSize.x, screenSize.y, 0.f, -1.f, 1.f), screenSize, 0);
REQUIRE(l.getState() != Label::State::sleep);
REQUIRE(l.getState() == Label::State::wait_occ);
REQUIRE(l.canOcclude());
l.setOcclusion(true);
l.occlusionSolved();
l.update(glm::ortho(0.f, screenSize.x, screenSize.y, 0.f, -1.f, 1.f), screenSize, 0);
REQUIRE(l.getState() == Label::State::sleep);
REQUIRE(!l.canOcclude());
}
TEST_CASE( "Ensure the transition from wait -> visible when no occlusion happens", "[Core][Label]" ) {
TextLabel l(makeLabel({screenSize/2.f}, Label::Type::point));
REQUIRE(l.getState() == Label::State::wait_occ);
l.setOcclusion(false);
l.update(glm::ortho(0.f, screenSize.x, screenSize.y, 0.f, -1.f, 1.f), screenSize, 0);
REQUIRE(l.getState() != Label::State::sleep);
REQUIRE(l.getState() == Label::State::wait_occ);
l.setOcclusion(false);
l.occlusionSolved();
l.update(glm::ortho(0.f, screenSize.x, screenSize.y, 0.f, -1.f, 1.f), screenSize, 0);
REQUIRE(l.getState() == Label::State::fading_in);
REQUIRE(l.canOcclude());
l.update(glm::ortho(0.f, screenSize.x, screenSize.y, 0.f, -1.f, 1.f), screenSize, 1.f);
REQUIRE(l.getState() == Label::State::visible);
REQUIRE(l.canOcclude());
}
TEST_CASE( "Ensure the end state after occlusion is leep state", "[Core][Label]" ) {
TextLabel l(makeLabel({screenSize/2.f}, Label::Type::point));
l.setOcclusion(false);
l.occlusionSolved();
l.update(glm::ortho(0.f, screenSize.x, screenSize.y, 0.f, -1.f, 1.f), screenSize, 0.f);
REQUIRE(l.getState() == Label::State::fading_in);
REQUIRE(l.canOcclude());
l.setOcclusion(true);
l.occlusionSolved();
l.update(glm::ortho(0.f, screenSize.x, screenSize.y, 0.f, -1.f, 1.f), screenSize, 0.f);
REQUIRE(l.getState() == Label::State::sleep);
REQUIRE(!l.canOcclude());
}
TEST_CASE( "Ensure the out of screen state transition", "[Core][Label]" ) {
TextLabel l(makeLabel({screenSize*2.f}, Label::Type::point));
REQUIRE(l.getState() == Label::State::wait_occ);
l.update(glm::ortho(0.f, screenSize.x, screenSize.y, 0.f, -1.f, 1.f), screenSize, 0.f);
REQUIRE(l.getState() == Label::State::out_of_screen);
REQUIRE(!l.canOcclude());
l.update(glm::ortho(0.f, screenSize.x * 4.f, screenSize.y * 4.f, 0.f, -1.f, 1.f), screenSize, 0.f);
REQUIRE(l.getState() == Label::State::wait_occ);
REQUIRE(l.canOcclude());
l.setOcclusion(false);
l.occlusionSolved();
l.update(glm::ortho(0.f, screenSize.x * 4.f, screenSize.y * 4.f, 0.f, -1.f, 1.f), screenSize, 0.f);
REQUIRE(l.getState() != Label::State::wait_occ);
REQUIRE(l.getState() == Label::State::fading_in);
REQUIRE(l.canOcclude());
l.update(glm::ortho(0.f, screenSize.x * 4.f, screenSize.y * 4.f, 0.f, -1.f, 1.f), screenSize, 1.f);
REQUIRE(l.getState() == Label::State::visible);
REQUIRE(l.canOcclude());
}
TEST_CASE( "Ensure debug labels are always visible and cannot occlude", "[Core][Label]" ) {
TextLabel l(makeLabel({screenSize/2.f}, Label::Type::debug));
REQUIRE(l.getState() == Label::State::visible);
REQUIRE(!l.canOcclude());
l.update(glm::ortho(0.f, screenSize.x, screenSize.y, 0.f, -1.f, 1.f), screenSize, 1.f);
REQUIRE(l.getState() == Label::State::visible);
REQUIRE(!l.canOcclude());
}
TEST_CASE( "Linear interpolation", "[Core][Label][Fade]" ) {
FadeEffect fadeOut(false, FadeEffect::Interpolation::linear, 1.0);
REQUIRE(fadeOut.update(0.0) == 1.0);
REQUIRE(fadeOut.update(0.5) == 0.5);
REQUIRE(fadeOut.update(0.5) == 0.0);
fadeOut.update(0.01);
REQUIRE(fadeOut.isFinished());
FadeEffect fadeIn(true, FadeEffect::Interpolation::linear, 1.0);
REQUIRE(fadeIn.update(0.0) == 0.0);
REQUIRE(fadeIn.update(0.5) == 0.5);
REQUIRE(fadeIn.update(0.5) == 1.0);
fadeIn.update(0.01);
REQUIRE(fadeIn.isFinished());
}
TEST_CASE( "Pow interpolation", "[Core][Label][Fade]" ) {
FadeEffect fadeOut(false, FadeEffect::Interpolation::pow, 1.0);
REQUIRE(fadeOut.update(0.0) == 1.0);
REQUIRE(fadeOut.update(0.5) == 0.75);
REQUIRE(fadeOut.update(0.5) == 0.0);
fadeOut.update(0.01);
REQUIRE(fadeOut.isFinished());
FadeEffect fadeIn(true, FadeEffect::Interpolation::pow, 1.0);
REQUIRE(fadeIn.update(0.0) == 0.0);
REQUIRE(fadeIn.update(0.5) == 0.25);
REQUIRE(fadeIn.update(0.5) == 1.0);
fadeIn.update(0.01);
REQUIRE(fadeIn.isFinished());
}
TEST_CASE( "Sine interpolation", "[Core][Label][Fade]" ) {
FadeEffect fadeOut(false, FadeEffect::Interpolation::sine, 1.0);
REQUIRE(std::fabs(fadeOut.update(0.0) - 1.0) < EPSILON);
REQUIRE(std::fabs(fadeOut.update(1.0) - 0.0) < EPSILON);
fadeOut.update(0.01);
REQUIRE(fadeOut.isFinished());
FadeEffect fadeIn(true, FadeEffect::Interpolation::sine, 1.0);
REQUIRE(std::fabs(fadeIn.update(0.0) - 0.0) < EPSILON);
REQUIRE(std::fabs(fadeIn.update(1.0) - 1.0) < EPSILON);
fadeIn.update(0.01);
REQUIRE(fadeIn.isFinished());
}
<commit_msg>update test<commit_after>#define CATCH_CONFIG_MAIN
#include "catch/catch.hpp"
#include "tangram.h"
#include "labels/label.h"
#include "labels/textLabel.h"
#include "glm/mat4x4.hpp"
#include "glm/gtc/matrix_transform.hpp"
#define EPSILON 0.00001
using namespace Tangram;
glm::vec2 screenSize(500.f, 500.f);
TextBuffer dummy(nullptr);
TextLabel makeLabel(Label::Transform _transform, Label::Type _type) {
Label::Options options;
options.color = 0xff;
options.offset = {0.0f, 0.0f};
return TextLabel("label", _transform, _type, {0, 0}, dummy, {0, 0}, options);
}
TEST_CASE( "Ensure the transition from wait -> sleep when occlusion happens", "[Core][Label]" ) {
TextLabel l(makeLabel({screenSize/2.f}, Label::Type::point));
REQUIRE(l.getState() == Label::State::wait_occ);
l.setOcclusion(true);
l.update(glm::ortho(0.f, screenSize.x, screenSize.y, 0.f, -1.f, 1.f), screenSize, 0);
REQUIRE(l.getState() != Label::State::sleep);
REQUIRE(l.getState() == Label::State::wait_occ);
REQUIRE(l.canOcclude());
l.setOcclusion(true);
l.occlusionSolved();
l.update(glm::ortho(0.f, screenSize.x, screenSize.y, 0.f, -1.f, 1.f), screenSize, 0);
REQUIRE(l.getState() == Label::State::dead);
REQUIRE(!l.canOcclude());
}
TEST_CASE( "Ensure the transition from wait -> visible when no occlusion happens", "[Core][Label]" ) {
TextLabel l(makeLabel({screenSize/2.f}, Label::Type::point));
REQUIRE(l.getState() == Label::State::wait_occ);
l.setOcclusion(false);
l.update(glm::ortho(0.f, screenSize.x, screenSize.y, 0.f, -1.f, 1.f), screenSize, 0);
REQUIRE(l.getState() != Label::State::sleep);
REQUIRE(l.getState() == Label::State::wait_occ);
l.setOcclusion(false);
l.occlusionSolved();
l.update(glm::ortho(0.f, screenSize.x, screenSize.y, 0.f, -1.f, 1.f), screenSize, 0);
REQUIRE(l.getState() == Label::State::fading_in);
REQUIRE(l.canOcclude());
l.update(glm::ortho(0.f, screenSize.x, screenSize.y, 0.f, -1.f, 1.f), screenSize, 1.f);
REQUIRE(l.getState() == Label::State::visible);
REQUIRE(l.canOcclude());
}
TEST_CASE( "Ensure the end state after occlusion is leep state", "[Core][Label]" ) {
TextLabel l(makeLabel({screenSize/2.f}, Label::Type::point));
l.setOcclusion(false);
l.occlusionSolved();
l.update(glm::ortho(0.f, screenSize.x, screenSize.y, 0.f, -1.f, 1.f), screenSize, 0.f);
REQUIRE(l.getState() == Label::State::fading_in);
REQUIRE(l.canOcclude());
l.setOcclusion(true);
l.occlusionSolved();
l.update(glm::ortho(0.f, screenSize.x, screenSize.y, 0.f, -1.f, 1.f), screenSize, 0.f);
REQUIRE(l.getState() == Label::State::sleep);
REQUIRE(!l.canOcclude());
}
TEST_CASE( "Ensure the out of screen state transition", "[Core][Label]" ) {
TextLabel l(makeLabel({screenSize*2.f}, Label::Type::point));
REQUIRE(l.getState() == Label::State::wait_occ);
l.update(glm::ortho(0.f, screenSize.x, screenSize.y, 0.f, -1.f, 1.f), screenSize, 0.f);
REQUIRE(l.getState() == Label::State::out_of_screen);
REQUIRE(!l.canOcclude());
l.update(glm::ortho(0.f, screenSize.x * 4.f, screenSize.y * 4.f, 0.f, -1.f, 1.f), screenSize, 0.f);
REQUIRE(l.getState() == Label::State::wait_occ);
REQUIRE(l.canOcclude());
l.setOcclusion(false);
l.occlusionSolved();
l.update(glm::ortho(0.f, screenSize.x * 4.f, screenSize.y * 4.f, 0.f, -1.f, 1.f), screenSize, 0.f);
REQUIRE(l.getState() != Label::State::wait_occ);
REQUIRE(l.getState() == Label::State::fading_in);
REQUIRE(l.canOcclude());
l.update(glm::ortho(0.f, screenSize.x * 4.f, screenSize.y * 4.f, 0.f, -1.f, 1.f), screenSize, 1.f);
REQUIRE(l.getState() == Label::State::visible);
REQUIRE(l.canOcclude());
}
TEST_CASE( "Ensure debug labels are always visible and cannot occlude", "[Core][Label]" ) {
TextLabel l(makeLabel({screenSize/2.f}, Label::Type::debug));
REQUIRE(l.getState() == Label::State::visible);
REQUIRE(!l.canOcclude());
l.update(glm::ortho(0.f, screenSize.x, screenSize.y, 0.f, -1.f, 1.f), screenSize, 1.f);
REQUIRE(l.getState() == Label::State::visible);
REQUIRE(!l.canOcclude());
}
TEST_CASE( "Linear interpolation", "[Core][Label][Fade]" ) {
FadeEffect fadeOut(false, FadeEffect::Interpolation::linear, 1.0);
REQUIRE(fadeOut.update(0.0) == 1.0);
REQUIRE(fadeOut.update(0.5) == 0.5);
REQUIRE(fadeOut.update(0.5) == 0.0);
fadeOut.update(0.01);
REQUIRE(fadeOut.isFinished());
FadeEffect fadeIn(true, FadeEffect::Interpolation::linear, 1.0);
REQUIRE(fadeIn.update(0.0) == 0.0);
REQUIRE(fadeIn.update(0.5) == 0.5);
REQUIRE(fadeIn.update(0.5) == 1.0);
fadeIn.update(0.01);
REQUIRE(fadeIn.isFinished());
}
TEST_CASE( "Pow interpolation", "[Core][Label][Fade]" ) {
FadeEffect fadeOut(false, FadeEffect::Interpolation::pow, 1.0);
REQUIRE(fadeOut.update(0.0) == 1.0);
REQUIRE(fadeOut.update(0.5) == 0.75);
REQUIRE(fadeOut.update(0.5) == 0.0);
fadeOut.update(0.01);
REQUIRE(fadeOut.isFinished());
FadeEffect fadeIn(true, FadeEffect::Interpolation::pow, 1.0);
REQUIRE(fadeIn.update(0.0) == 0.0);
REQUIRE(fadeIn.update(0.5) == 0.25);
REQUIRE(fadeIn.update(0.5) == 1.0);
fadeIn.update(0.01);
REQUIRE(fadeIn.isFinished());
}
TEST_CASE( "Sine interpolation", "[Core][Label][Fade]" ) {
FadeEffect fadeOut(false, FadeEffect::Interpolation::sine, 1.0);
REQUIRE(std::fabs(fadeOut.update(0.0) - 1.0) < EPSILON);
REQUIRE(std::fabs(fadeOut.update(1.0) - 0.0) < EPSILON);
fadeOut.update(0.01);
REQUIRE(fadeOut.isFinished());
FadeEffect fadeIn(true, FadeEffect::Interpolation::sine, 1.0);
REQUIRE(std::fabs(fadeIn.update(0.0) - 0.0) < EPSILON);
REQUIRE(std::fabs(fadeIn.update(1.0) - 1.0) < EPSILON);
fadeIn.update(0.01);
REQUIRE(fadeIn.isFinished());
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2016 Patrick P. Frey
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "testUtils.hpp"
#include "strus/analyzer/patternMatcherResultItem.hpp"
#include <iostream>
#include <sstream>
#include <limits>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <stdexcept>
#include <new>
#define RANDINT(MIN,MAX) ((std::rand()%(MAX-MIN))+MIN)
using namespace strus;
using namespace strus::utils;
std::string Document::tostring() const
{
std::ostringstream outbuf;
outbuf << "docid=" << id << ", items={";
std::vector<DocumentItem>::const_iterator ti = itemar.begin(), te = itemar.end();
for (int tidx=0; ti != te; ++ti,++tidx)
{
if (tidx) outbuf << ", ";
outbuf << ti->pos << ":" << ti->termid;
}
outbuf << "}";
return outbuf.str();
}
ZipfDistribution::ZipfDistribution( std::size_t size, double S)
{
std::size_t ii=1, ie=size;
m_ar.push_back( 1.0);
for (; ii < ie; ++ii)
{
if (S > std::numeric_limits<double>::epsilon())
{
m_ar.push_back( m_ar[ ii-1] + 1.0 / pow((double)(ii+1), S));
}
else
{
m_ar.push_back( m_ar[ ii-1] + 1.0 / (double)(ii+1));
}
}
}
unsigned int ZipfDistribution::random() const
{
double val = m_ar.back() * (double)std::rand() / (double)RAND_MAX;
std::size_t ii=0;
for (; ii<m_ar.size(); ++ii)
{
if (val < m_ar[ii])
{
break;
}
while (m_ar.size() - ii > 100 && val > m_ar[ ii+100])
{
ii+=100;
}
}
return ii+1;
}
unsigned int utils::termId( TermType tp, unsigned int no)
{
return ((unsigned int)tp << 24) + no;
}
Document utils::createRandomDocument( unsigned int no, unsigned int size, unsigned int mod)
{
ZipfDistribution featdist( mod);
char docid[ 32];
snprintf( docid, sizeof(docid), "doc_%u", no);
Document rt( docid);
unsigned int ii = 0, ie = size;
for (; ii < ie; ++ii)
{
unsigned int tok = featdist.random();
rt.itemar.push_back( DocumentItem( ii+1, termId( Token, tok)));
if (RANDINT(0,12) == 0)
{
rt.itemar.push_back( DocumentItem( ii+1, termId( SentenceDelim, 0)));
}
}
return rt;
}
typedef strus::PatternMatcherInstanceInterface::JoinOperation JoinOperation;
JoinOperation utils::joinOperation( const char* joinopstr)
{
static const char* ar[] = {"sequence","sequence_struct","within","within_struct","any",0};
std::size_t ai = 0;
for (; ar[ai]; ++ai)
{
if (0 == std::strcmp( joinopstr, ar[ai]))
{
return (JoinOperation)ai;
}
}
throw std::runtime_error( "unknown join operation");
}
unsigned int utils::getUintValue( const char* arg)
{
unsigned int rt = 0, prev = 0;
char const* cc = arg;
for (; *cc; ++cc)
{
if (*cc < '0' || *cc > '9') throw std::runtime_error( std::string( "parameter is not a non negative integer number: ") + arg);
rt = (rt * 10) + (*cc - '0');
if (rt < prev) throw std::runtime_error( std::string( "parameter out of range: ") + arg);
}
return rt;
}
void utils::printResults( std::ostream& out, const std::vector<strus::SegmenterPosition>& segmentposmap, const std::vector<strus::analyzer::PatternMatcherResult>& results, const char* src)
{
std::vector<strus::analyzer::PatternMatcherResult>::const_iterator
ri = results.begin(), re = results.end();
for (; ri != re; ++ri)
{
std::size_t start_origsegsrcpos = segmentposmap.empty()?ri->origpos().seg():segmentposmap[ ri->origpos().seg()];
std::size_t end_origsegsrcpos = segmentposmap.empty()?ri->origend().seg():segmentposmap[ ri->origend().seg()];
out << "match '" << ri->name() << "' at " << ri->ordpos() << ".." << ri->ordend() << " ["
<< start_origsegsrcpos << "|" << ri->origpos().ofs() << ".."
<< end_origsegsrcpos << "|" << ri->origend().ofs()
<< "]:";
std::vector<strus::analyzer::PatternMatcherResultItem>::const_iterator
ei = ri->items().begin(), ee = ri->items().end();
for (; ei != ee; ++ei)
{
start_origsegsrcpos = segmentposmap.empty()?ei->origpos().seg():segmentposmap[ ei->origpos().seg()];
end_origsegsrcpos = segmentposmap.empty()?ei->origend().seg():segmentposmap[ ei->origend().seg()];
out << " " << ei->name() << " [" << ei->ordpos()<< ".." << ei->ordend()
<< ", " << start_origsegsrcpos << "|" << ei->origpos().ofs()
<< ".." << end_origsegsrcpos << "|" << ei->origend().ofs()
<< "]";
if (src)
{
std::size_t start_srcpos = start_origsegsrcpos + ei->origpos().ofs();
std::size_t end_srcpos = end_origsegsrcpos + ei->origend().ofs();
out << " '" << std::string( src+start_srcpos, end_srcpos-start_srcpos) << "'";
}
}
out << std::endl;
}
}
void utils::printStatistics( std::ostream& out, const strus::analyzer::PatternMatcherStatistics& stats)
{
out << "Statistics:" << std::endl;
std::vector<strus::analyzer::PatternMatcherStatistics::Item>::const_iterator
gi = stats.items().begin(), ge = stats.items().end();
for (; gi != ge; ++gi)
{
out << "\t" << gi->name() << ": " << floor( gi->value()+0.5) << std::endl;
}
}
<commit_msg>added a missing include cmath for pow in testUtils.cpp<commit_after>/*
* Copyright (c) 2016 Patrick P. Frey
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "testUtils.hpp"
#include "strus/analyzer/patternMatcherResultItem.hpp"
#include <iostream>
#include <sstream>
#include <limits>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <stdexcept>
#include <new>
#include <cmath>
#define RANDINT(MIN,MAX) ((std::rand()%(MAX-MIN))+MIN)
using namespace strus;
using namespace strus::utils;
std::string Document::tostring() const
{
std::ostringstream outbuf;
outbuf << "docid=" << id << ", items={";
std::vector<DocumentItem>::const_iterator ti = itemar.begin(), te = itemar.end();
for (int tidx=0; ti != te; ++ti,++tidx)
{
if (tidx) outbuf << ", ";
outbuf << ti->pos << ":" << ti->termid;
}
outbuf << "}";
return outbuf.str();
}
ZipfDistribution::ZipfDistribution( std::size_t size, double S)
{
std::size_t ii=1, ie=size;
m_ar.push_back( 1.0);
for (; ii < ie; ++ii)
{
if (S > std::numeric_limits<double>::epsilon())
{
m_ar.push_back( m_ar[ ii-1] + 1.0 / pow((double)(ii+1), S));
}
else
{
m_ar.push_back( m_ar[ ii-1] + 1.0 / (double)(ii+1));
}
}
}
unsigned int ZipfDistribution::random() const
{
double val = m_ar.back() * (double)std::rand() / (double)RAND_MAX;
std::size_t ii=0;
for (; ii<m_ar.size(); ++ii)
{
if (val < m_ar[ii])
{
break;
}
while (m_ar.size() - ii > 100 && val > m_ar[ ii+100])
{
ii+=100;
}
}
return ii+1;
}
unsigned int utils::termId( TermType tp, unsigned int no)
{
return ((unsigned int)tp << 24) + no;
}
Document utils::createRandomDocument( unsigned int no, unsigned int size, unsigned int mod)
{
ZipfDistribution featdist( mod);
char docid[ 32];
snprintf( docid, sizeof(docid), "doc_%u", no);
Document rt( docid);
unsigned int ii = 0, ie = size;
for (; ii < ie; ++ii)
{
unsigned int tok = featdist.random();
rt.itemar.push_back( DocumentItem( ii+1, termId( Token, tok)));
if (RANDINT(0,12) == 0)
{
rt.itemar.push_back( DocumentItem( ii+1, termId( SentenceDelim, 0)));
}
}
return rt;
}
typedef strus::PatternMatcherInstanceInterface::JoinOperation JoinOperation;
JoinOperation utils::joinOperation( const char* joinopstr)
{
static const char* ar[] = {"sequence","sequence_struct","within","within_struct","any",0};
std::size_t ai = 0;
for (; ar[ai]; ++ai)
{
if (0 == std::strcmp( joinopstr, ar[ai]))
{
return (JoinOperation)ai;
}
}
throw std::runtime_error( "unknown join operation");
}
unsigned int utils::getUintValue( const char* arg)
{
unsigned int rt = 0, prev = 0;
char const* cc = arg;
for (; *cc; ++cc)
{
if (*cc < '0' || *cc > '9') throw std::runtime_error( std::string( "parameter is not a non negative integer number: ") + arg);
rt = (rt * 10) + (*cc - '0');
if (rt < prev) throw std::runtime_error( std::string( "parameter out of range: ") + arg);
}
return rt;
}
void utils::printResults( std::ostream& out, const std::vector<strus::SegmenterPosition>& segmentposmap, const std::vector<strus::analyzer::PatternMatcherResult>& results, const char* src)
{
std::vector<strus::analyzer::PatternMatcherResult>::const_iterator
ri = results.begin(), re = results.end();
for (; ri != re; ++ri)
{
std::size_t start_origsegsrcpos = segmentposmap.empty()?ri->origpos().seg():segmentposmap[ ri->origpos().seg()];
std::size_t end_origsegsrcpos = segmentposmap.empty()?ri->origend().seg():segmentposmap[ ri->origend().seg()];
out << "match '" << ri->name() << "' at " << ri->ordpos() << ".." << ri->ordend() << " ["
<< start_origsegsrcpos << "|" << ri->origpos().ofs() << ".."
<< end_origsegsrcpos << "|" << ri->origend().ofs()
<< "]:";
std::vector<strus::analyzer::PatternMatcherResultItem>::const_iterator
ei = ri->items().begin(), ee = ri->items().end();
for (; ei != ee; ++ei)
{
start_origsegsrcpos = segmentposmap.empty()?ei->origpos().seg():segmentposmap[ ei->origpos().seg()];
end_origsegsrcpos = segmentposmap.empty()?ei->origend().seg():segmentposmap[ ei->origend().seg()];
out << " " << ei->name() << " [" << ei->ordpos()<< ".." << ei->ordend()
<< ", " << start_origsegsrcpos << "|" << ei->origpos().ofs()
<< ".." << end_origsegsrcpos << "|" << ei->origend().ofs()
<< "]";
if (src)
{
std::size_t start_srcpos = start_origsegsrcpos + ei->origpos().ofs();
std::size_t end_srcpos = end_origsegsrcpos + ei->origend().ofs();
out << " '" << std::string( src+start_srcpos, end_srcpos-start_srcpos) << "'";
}
}
out << std::endl;
}
}
void utils::printStatistics( std::ostream& out, const strus::analyzer::PatternMatcherStatistics& stats)
{
out << "Statistics:" << std::endl;
std::vector<strus::analyzer::PatternMatcherStatistics::Item>::const_iterator
gi = stats.items().begin(), ge = stats.items().end();
for (; gi != ge; ++gi)
{
out << "\t" << gi->name() << ": " << floor( gi->value()+0.5) << std::endl;
}
}
<|endoftext|> |
<commit_before>// ------------------------------------------------------------------------
// Copyright (C) 2009 Kai Vehmanen
//
// 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
// ------------------------------------------------------------------------
#include "eca-version.h"
#include "samplebuffer.h"
#include "audiofx_amplitude.h"
#include "kvu_procedure_timer.h"
#include "ecatestsuite.h"
int test_sbuf_make_silent(void);
int test_sbuf_copy_ops(void);
int test_sbuf_constructor(void);
int test_sbuf_mix(void);
int test_sbuf_iter(void);
int main(int argc, char *argv[])
{
int res = 0;
std::printf("--------------------------------------------------------\n"
"Testing with libecasound *** v%s *** (%s).\n",
ecasound_library_version, __FILE__);
res += test_sbuf_make_silent();
res += test_sbuf_copy_ops();
res += test_sbuf_constructor();
res += test_sbuf_mix();
res += test_sbuf_iter();
return res;
}
void helper_print_one_result(const char *casename, const PROCEDURE_TIMER& t1, int loops, int bsize)
{
double per_loop = t1.last_duration_seconds() / loops;
std::printf("\t%-20.20s:\t%.03fms (%.03fus/loop, %.04f%% CPU@48kHz)\n",
casename,
t1.last_duration_seconds() * 1000.0,
per_loop * 1000000.0,
(per_loop / (((double)bsize) / 48000.0)));
}
int test_sbuf_make_silent(void)
{
const int loops = 10000;
const int bufsize = 1024;
const int channels = 12;
std::printf("sbuf_make_silent with %d loops (bufsize=%d, ch=%d):\n",
loops, 1024, 12);
PROCEDURE_TIMER t1;
SAMPLE_BUFFER sbuf (bufsize, channels);
/* note: make sure code is paged in */
sbuf.make_silent();
t1.start();
for(int n = 0; n < loops; n++) {
sbuf.make_silent_range(0, bufsize);
}
t1.stop();
helper_print_one_result("make_silent_range", t1, loops, bufsize);
/* note: make sure code is paged in */
sbuf.make_silent_range(0, bufsize);
t1.reset();
t1.start();
for(int n = 0; n < loops; n++) {
sbuf.make_silent();
}
t1.stop();
helper_print_one_result("make_silent", t1, loops, bufsize);
}
int test_sbuf_copy_ops(void)
{
const int loops = 10000;
const int bufsize = 1024;
const int channels = 12;
PROCEDURE_TIMER t1;
SAMPLE_BUFFER sbuf_a (bufsize, channels);
SAMPLE_BUFFER sbuf_b (bufsize, channels);
std::printf("sbuf_copy_ops with %d loops (bufsize=%d, ch=%d):\n",
loops, 1024, 12);
#if LIBECASOUND_VERSION >= 22
/* note: make sure code is paged in */
sbuf_a.copy_all_content(sbuf_b);
t1.start();
for(int n = 0; n < loops; n++) {
sbuf_a.copy_all_content(sbuf_b);
}
t1.stop();
helper_print_one_result("copy_all_content", t1, loops, bufsize);
/* note: make sure code is paged in */
sbuf_a.copy_matching_channels(sbuf_b);
t1.reset();
t1.start();
for(int n = 0; n < loops; n++) {
sbuf_a.copy_matching_channels(sbuf_b);
}
t1.stop();
helper_print_one_result("copy_matching_channels", t1, loops, bufsize);
#else
/* note: make sure code is paged in */
sbuf_a.copy(sbuf_b);
t1.reset();
t1.start();
for(int n = 0; n < loops; n++) {
sbuf_a.copy(sbuf_b);
}
t1.stop();
helper_print_one_result("copy (v21-lib)", t1, loops, bufsize);
#endif
}
int test_sbuf_constructor(void)
{
const int loops = 10000;
const int bufsize = 1024;
const int channels = 12;
PROCEDURE_TIMER t1;
SAMPLE_BUFFER sbuf_a (bufsize, channels);
std::printf("sbuf constructor with %d loops (bufsize=%d, ch=%d):\n",
loops, 1024, 12);
/* note: make sure code is paged in */
t1.start();
for(int n = 0; n < loops; n++) {
SAMPLE_BUFFER sbuf_b (bufsize, channels);
}
t1.stop();
helper_print_one_result("constructor", t1, loops, bufsize);
}
int test_sbuf_mix(void)
{
const int loops = 10000;
const int bufsize = 1024;
const int channels = 12;
std::printf("sbuf_mix with %d loops (bufsize=%d, ch=%d):\n",
loops, bufsize, channels);
PROCEDURE_TIMER t1;
SAMPLE_BUFFER sbuf_a (bufsize, channels);
SAMPLE_BUFFER sbuf_b (bufsize, channels);
/* case 1 */
{
sbuf_a.divide_by(1.23456789);
t1.reset();
t1.start();
for(int n = 0; n < loops; n++) {
sbuf_a.divide_by(1.23456789);
}
t1.stop();
helper_print_one_result("divide_by", t1, loops, bufsize);
}
/* case 1b */
{
#if LIBECASOUND_VERSION >= 22
sbuf_a.divide_by_ref(1.23456789);
t1.reset();
t1.start();
for(int n = 0; n < loops; n++) {
sbuf_a.divide_by_ref(1.23456789);
}
t1.stop();
helper_print_one_result("divide_by_ref", t1, loops, bufsize);
#endif
}
/* case 2 */
{
sbuf_a.add_with_weight(sbuf_b, 2);
t1.reset();
t1.start();
for(int n = 0; n < loops; n++) {
sbuf_a.add_with_weight(sbuf_b, 2);
}
t1.stop();
helper_print_one_result("add_with_weight", t1, loops, bufsize);
}
/* case 3 */
{
#if LIBECASOUND_VERSION >= 22
sbuf_a.add_matching_channels(sbuf_b);
t1.reset();
t1.start();
for(int n = 0; n < loops; n++) {
sbuf_a.add_matching_channels(sbuf_b);
}
t1.stop();
helper_print_one_result("add_matching_channels", t1, loops, bufsize);
/* case 3b */
sbuf_a.add_matching_channels_ref(sbuf_b);
t1.reset();
t1.start();
for(int n = 0; n < loops; n++) {
sbuf_a.add_matching_channels_ref(sbuf_b);
}
t1.stop();
helper_print_one_result("add_matching_ch...ref", t1, loops, bufsize);
#else
sbuf_a.add(sbuf_b);
t1.reset();
t1.start();
for(int n = 0; n < loops; n++) {
sbuf_a.add(sbuf_b);
}
t1.stop();
helper_print_one_result("add (v21-lib)", t1, loops, bufsize);
#endif
}
/* case 4 */
{
sbuf_a.limit_values();
t1.reset();
t1.start();
for(int n = 0; n < loops; n++) {
sbuf_a.limit_values();
}
t1.stop();
helper_print_one_result("limit_values", t1, loops, bufsize);
/* case 4b */
#if LIBECASOUND_VERSION >= 22
sbuf_a.limit_values_ref();
t1.reset();
t1.start();
for(int n = 0; n < loops; n++) {
sbuf_a.limit_values_ref();
}
t1.stop();
helper_print_one_result("limit_values_ref", t1, loops, bufsize);
#endif
}
}
int test_sbuf_iter(void)
{
const int loops = 10000;
const int bufsize = 1024;
const int channels = 12;
const SAMPLE_BUFFER::sample_t multiplier = 100.1f;
std::printf("sbuf_iter with %d loops (bufsize=%d, ch=%d):\n",
loops, bufsize, channels);
PROCEDURE_TIMER t1;
SAMPLE_BUFFER sbuf_a (bufsize, channels);
EFFECT_AMPLIFY amplify (multiplier);
/* case 1 */
{
amplify.init(&sbuf_a);
amplify.process();
t1.reset();
t1.start();
for(int n = 0; n < loops; n++) {
amplify.process();
}
t1.stop();
helper_print_one_result("effect_amplify", t1, loops, bufsize);
}
/* case 2 */
{
int ch_count = sbuf_a.number_of_channels();
int i_count = sbuf_a.length_in_samples();
t1.reset();
t1.start();
for(int n = 0; n < loops; n++) {
for (int ch = 0; ch < ch_count; ch++) {
SAMPLE_BUFFER::sample_t *buf = sbuf_a.buffer[ch];
for (int i = 0; i < i_count; i++) {
buf[i] *= multiplier;
}
}
}
t1.stop();
helper_print_one_result("amplify_memops", t1, loops, bufsize);
}
/* case 3+4 */
{
#if LIBECASOUND_VERSION >= 22
sbuf_a.multiply_by(multiplier);
t1.reset();
t1.start();
for(int n = 0; n < loops; n++) {
sbuf_a.multiply_by(multiplier);
}
t1.stop();
helper_print_one_result("amplify_sbuf", t1, loops, bufsize);
sbuf_a.multiply_by_ref(multiplier);
t1.reset();
t1.start();
for(int n = 0; n < loops; n++) {
sbuf_a.multiply_by_ref(multiplier);
}
t1.stop();
helper_print_one_result("amplify_sbuf_ref", t1, loops, bufsize);
#endif
}
}
<commit_msg>Fixes to eca_loop_bench trace output<commit_after>// ------------------------------------------------------------------------
// Copyright (C) 2009 Kai Vehmanen
//
// 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
// ------------------------------------------------------------------------
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include "eca-version.h"
#include "samplebuffer.h"
#include "audiofx_amplitude.h"
#include "kvu_procedure_timer.h"
#include "ecatestsuite.h"
int test_sbuf_make_silent(void);
int test_sbuf_copy_ops(void);
int test_sbuf_constructor(void);
int test_sbuf_mix(void);
int test_sbuf_iter(void);
int main(int argc, char *argv[])
{
int res = 0;
std::printf("--------------------------------------------------------\n"
"Testing with libecasound *** v%s *** (%s).\n",
ecasound_library_version, __FILE__);
res += test_sbuf_make_silent();
res += test_sbuf_copy_ops();
res += test_sbuf_constructor();
res += test_sbuf_mix();
res += test_sbuf_iter();
return res;
}
void helper_print_one_result(const char *casename, const PROCEDURE_TIMER& t1, int loops, int bsize)
{
double per_loop = t1.last_duration_seconds() / loops;
std::printf("\t%-20.20s:\t%.03fms (%.03fus/loop, %.04f%% CPU@48kHz)\n",
casename,
t1.last_duration_seconds() * 1000.0,
per_loop * 1000000.0,
(per_loop / (((double)bsize) / 48000.0)));
}
int test_sbuf_make_silent(void)
{
const int loops = 10000;
const int bufsize = 1024;
const int channels = 12;
std::printf("sbuf_make_silent with %d loops (bufsize=%d, ch=%d):\n",
loops, bufsize, channels);
PROCEDURE_TIMER t1;
SAMPLE_BUFFER sbuf (bufsize, channels);
/* note: make sure code is paged in */
sbuf.make_silent();
t1.start();
for(int n = 0; n < loops; n++) {
sbuf.make_silent_range(0, bufsize);
}
t1.stop();
helper_print_one_result("make_silent_range", t1, loops, bufsize);
/* note: make sure code is paged in */
sbuf.make_silent_range(0, bufsize);
t1.reset();
t1.start();
for(int n = 0; n < loops; n++) {
sbuf.make_silent();
}
t1.stop();
helper_print_one_result("make_silent", t1, loops, bufsize);
}
int test_sbuf_copy_ops(void)
{
const int loops = 10000;
const int bufsize = 1024;
const int channels = 12;
PROCEDURE_TIMER t1;
SAMPLE_BUFFER sbuf_a (bufsize, channels);
SAMPLE_BUFFER sbuf_b (bufsize, channels);
std::printf("sbuf_copy_ops with %d loops (bufsize=%d, ch=%d):\n",
loops, 1024, 12);
#if LIBECASOUND_VERSION >= 22
/* note: make sure code is paged in */
sbuf_a.copy_all_content(sbuf_b);
t1.start();
for(int n = 0; n < loops; n++) {
sbuf_a.copy_all_content(sbuf_b);
}
t1.stop();
helper_print_one_result("copy_all_content", t1, loops, bufsize);
/* note: make sure code is paged in */
sbuf_a.copy_matching_channels(sbuf_b);
t1.reset();
t1.start();
for(int n = 0; n < loops; n++) {
sbuf_a.copy_matching_channels(sbuf_b);
}
t1.stop();
helper_print_one_result("copy_matching_channels", t1, loops, bufsize);
#else
/* note: make sure code is paged in */
sbuf_a.copy(sbuf_b);
t1.reset();
t1.start();
for(int n = 0; n < loops; n++) {
sbuf_a.copy(sbuf_b);
}
t1.stop();
helper_print_one_result("copy (v21-lib)", t1, loops, bufsize);
#endif
}
int test_sbuf_constructor(void)
{
const int loops = 10000;
const int bufsize = 1024;
const int channels = 12;
PROCEDURE_TIMER t1;
SAMPLE_BUFFER sbuf_a (bufsize, channels);
std::printf("sbuf constructor with %d loops (bufsize=%d, ch=%d):\n",
loops, bufsize, channels);
/* note: make sure code is paged in */
t1.start();
for(int n = 0; n < loops; n++) {
SAMPLE_BUFFER sbuf_b (bufsize, channels);
}
t1.stop();
helper_print_one_result("constructor", t1, loops, bufsize);
}
int test_sbuf_mix(void)
{
const int loops = 10000;
const int bufsize = 1024;
const int channels = 12;
std::printf("sbuf_mix with %d loops (bufsize=%d, ch=%d):\n",
loops, bufsize, channels);
PROCEDURE_TIMER t1;
SAMPLE_BUFFER sbuf_a (bufsize, channels);
SAMPLE_BUFFER sbuf_b (bufsize, channels);
/* case 1 */
{
sbuf_a.divide_by(1.23456789);
t1.reset();
t1.start();
for(int n = 0; n < loops; n++) {
sbuf_a.divide_by(1.23456789);
}
t1.stop();
helper_print_one_result("divide_by", t1, loops, bufsize);
}
/* case 1b */
{
#if LIBECASOUND_VERSION >= 22
sbuf_a.divide_by_ref(1.23456789);
t1.reset();
t1.start();
for(int n = 0; n < loops; n++) {
sbuf_a.divide_by_ref(1.23456789);
}
t1.stop();
helper_print_one_result("divide_by_ref", t1, loops, bufsize);
#endif
}
/* case 2 */
{
sbuf_a.add_with_weight(sbuf_b, 2);
t1.reset();
t1.start();
for(int n = 0; n < loops; n++) {
sbuf_a.add_with_weight(sbuf_b, 2);
}
t1.stop();
helper_print_one_result("add_with_weight", t1, loops, bufsize);
}
/* case 3 */
{
#if LIBECASOUND_VERSION >= 22
sbuf_a.add_matching_channels(sbuf_b);
t1.reset();
t1.start();
for(int n = 0; n < loops; n++) {
sbuf_a.add_matching_channels(sbuf_b);
}
t1.stop();
helper_print_one_result("add_matching_channels", t1, loops, bufsize);
/* case 3b */
sbuf_a.add_matching_channels_ref(sbuf_b);
t1.reset();
t1.start();
for(int n = 0; n < loops; n++) {
sbuf_a.add_matching_channels_ref(sbuf_b);
}
t1.stop();
helper_print_one_result("add_matching_ch...ref", t1, loops, bufsize);
#else
sbuf_a.add(sbuf_b);
t1.reset();
t1.start();
for(int n = 0; n < loops; n++) {
sbuf_a.add(sbuf_b);
}
t1.stop();
helper_print_one_result("add (v21-lib)", t1, loops, bufsize);
#endif
}
/* case 4 */
{
sbuf_a.limit_values();
t1.reset();
t1.start();
for(int n = 0; n < loops; n++) {
sbuf_a.limit_values();
}
t1.stop();
helper_print_one_result("limit_values", t1, loops, bufsize);
/* case 4b */
#if LIBECASOUND_VERSION >= 22
sbuf_a.limit_values_ref();
t1.reset();
t1.start();
for(int n = 0; n < loops; n++) {
sbuf_a.limit_values_ref();
}
t1.stop();
helper_print_one_result("limit_values_ref", t1, loops, bufsize);
#endif
}
}
int test_sbuf_iter(void)
{
const int loops = 10000;
const int bufsize = 1024;
const int channels = 12;
const SAMPLE_BUFFER::sample_t multiplier = 100.1f;
std::printf("sbuf_iter with %d loops (bufsize=%d, ch=%d):\n",
loops, bufsize, channels);
PROCEDURE_TIMER t1;
SAMPLE_BUFFER sbuf_a (bufsize, channels);
EFFECT_AMPLIFY amplify (multiplier);
/* case 1 */
{
amplify.init(&sbuf_a);
amplify.process();
t1.reset();
t1.start();
for(int n = 0; n < loops; n++) {
amplify.process();
}
t1.stop();
helper_print_one_result("effect_amplify", t1, loops, bufsize);
}
/* case 2 */
{
int ch_count = sbuf_a.number_of_channels();
int i_count = sbuf_a.length_in_samples();
t1.reset();
t1.start();
for(int n = 0; n < loops; n++) {
for (int ch = 0; ch < ch_count; ch++) {
SAMPLE_BUFFER::sample_t *buf = sbuf_a.buffer[ch];
for (int i = 0; i < i_count; i++) {
buf[i] *= multiplier;
}
}
}
t1.stop();
helper_print_one_result("amplify_plainc", t1, loops, bufsize);
}
/* case 3+4 */
{
#if LIBECASOUND_VERSION >= 22
sbuf_a.multiply_by(multiplier);
t1.reset();
t1.start();
for(int n = 0; n < loops; n++) {
sbuf_a.multiply_by(multiplier);
}
t1.stop();
helper_print_one_result("amplify_sbuf", t1, loops, bufsize);
sbuf_a.multiply_by_ref(multiplier);
t1.reset();
t1.start();
for(int n = 0; n < loops; n++) {
sbuf_a.multiply_by_ref(multiplier);
}
t1.stop();
helper_print_one_result("amplify_sbuf_ref", t1, loops, bufsize);
#endif
}
}
<|endoftext|> |
<commit_before>
#include <cstdio>
#include <iostream>
#include "utility.hpp"
// Includes common necessary includes for development using depthai library
#include "depthai/depthai.hpp"
int main() {
using namespace std;
using namespace std::chrono;
// Create pipeline
dai::Pipeline pipeline;
// Define sources and outputs
auto imu = pipeline.create<dai::node::IMU>();
auto xlinkOut = pipeline.create<dai::node::XLinkOut>();
xlinkOut->setStreamName("imu");
// enable ACCELEROMETER_RAW and GYROSCOPE_RAW at 500 hz rate
imu->enableIMUSensor({dai::IMUSensor::ACCELEROMETER_RAW, dai::IMUSensor::GYROSCOPE_RAW}, 500);
// above this threshold packets will be sent in batch of X, if the host is not blocked and USB bandwidth is available
imu->setBatchReportThreshold(1);
// maximum number of IMU packets in a batch, if it's reached device will block sending until host can receive it
// if lower or equal to batchReportThreshold then the sending is always blocking on device
// useful to reduce device's CPU load and number of lost packets, if CPU load is high on device side due to multiple nodes
imu->setMaxBatchReports(10);
// Link plugins IMU -> XLINK
imu->out.link(xlinkOut->input);
// Pipeline is defined, now we can connect to the device
dai::Device d(pipeline);
bool firstTs = false;
auto imuQueue = d.getOutputQueue("imu", 50, false);
auto baseTs = std::chrono::time_point<std::chrono::steady_clock, std::chrono::steady_clock::duration>();
while(true) {
auto imuData = imuQueue->get<dai::IMUData>();
auto imuPackets = imuData->packets;
for(auto& imuPacket : imuPackets) {
auto& acceleroValues = imuPacket.acceleroMeter;
auto& gyroValues = imuPacket.gyroscope;
auto acceleroTs1 = acceleroValues.timestamp.get();
auto gyroTs1 = gyroValues.timestamp.get();
if(!firstTs) {
baseTs = std::min(acceleroTs1, gyroTs1);
firstTs = true;
}
auto acceleroTs = acceleroTs1 - baseTs;
auto gyroTs = gyroTs1 - baseTs;
printf("Accelerometer timestamp: %ld ms\n", static_cast<long>(duration_cast<milliseconds>(acceleroTs).count()));
printf("Accelerometer [m/s^2]: x: %.3f y: %.3f z: %.3f \n", acceleroValues.x, acceleroValues.y, acceleroValues.z);
printf("Gyroscope timestamp: %ld ms\n", static_cast<long>(duration_cast<milliseconds>(gyroTs).count()));
printf("Gyroscope [rad/s]: x: %.3f y: %.3f z: %.3f \n", gyroValues.x, gyroValues.y, gyroValues.z);
}
int key = cv::waitKey(1);
if(key == 'q') {
return 0;
}
}
return 0;
}
<commit_msg>Modify IMU example: GYRO at 400 hz to avoid spikes<commit_after>
#include <cstdio>
#include <iostream>
#include "utility.hpp"
// Includes common necessary includes for development using depthai library
#include "depthai/depthai.hpp"
int main() {
using namespace std;
using namespace std::chrono;
// Create pipeline
dai::Pipeline pipeline;
// Define sources and outputs
auto imu = pipeline.create<dai::node::IMU>();
auto xlinkOut = pipeline.create<dai::node::XLinkOut>();
xlinkOut->setStreamName("imu");
// enable ACCELEROMETER_RAW at 500 hz rate
imu->enableIMUSensor(dai::IMUSensor::ACCELEROMETER_RAW, 500);
// enable GYROSCOPE_RAW at 400 hz rate
imu->enableIMUSensor(dai::IMUSensor::GYROSCOPE_RAW, 400);
// it's recommended to set both setBatchReportThreshold and setMaxBatchReports to 20 when integrating in a pipeline with a lot of input/output connections
// above this threshold packets will be sent in batch of X, if the host is not blocked and USB bandwidth is available
imu->setBatchReportThreshold(1);
// maximum number of IMU packets in a batch, if it's reached device will block sending until host can receive it
// if lower or equal to batchReportThreshold then the sending is always blocking on device
// useful to reduce device's CPU load and number of lost packets, if CPU load is high on device side due to multiple nodes
imu->setMaxBatchReports(10);
// Link plugins IMU -> XLINK
imu->out.link(xlinkOut->input);
// Pipeline is defined, now we can connect to the device
dai::Device d(pipeline);
bool firstTs = false;
auto imuQueue = d.getOutputQueue("imu", 50, false);
auto baseTs = std::chrono::time_point<std::chrono::steady_clock, std::chrono::steady_clock::duration>();
while(true) {
auto imuData = imuQueue->get<dai::IMUData>();
auto imuPackets = imuData->packets;
for(auto& imuPacket : imuPackets) {
auto& acceleroValues = imuPacket.acceleroMeter;
auto& gyroValues = imuPacket.gyroscope;
auto acceleroTs1 = acceleroValues.timestamp.get();
auto gyroTs1 = gyroValues.timestamp.get();
if(!firstTs) {
baseTs = std::min(acceleroTs1, gyroTs1);
firstTs = true;
}
auto acceleroTs = acceleroTs1 - baseTs;
auto gyroTs = gyroTs1 - baseTs;
printf("Accelerometer timestamp: %ld ms\n", static_cast<long>(duration_cast<milliseconds>(acceleroTs).count()));
printf("Accelerometer [m/s^2]: x: %.3f y: %.3f z: %.3f \n", acceleroValues.x, acceleroValues.y, acceleroValues.z);
printf("Gyroscope timestamp: %ld ms\n", static_cast<long>(duration_cast<milliseconds>(gyroTs).count()));
printf("Gyroscope [rad/s]: x: %.3f y: %.3f z: %.3f \n", gyroValues.x, gyroValues.y, gyroValues.z);
}
int key = cv::waitKey(1);
if(key == 'q') {
return 0;
}
}
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2021 by Apex.AI 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.
//
// SPDX-License-Identifier: Apache-2.0
#include "iceoryx_posh/internal/roudi/service_registry.hpp"
#include <algorithm>
namespace iox
{
namespace roudi
{
cxx::expected<ServiceRegistry::Error> ServiceRegistry::add(const capro::ServiceDescription& serviceDescription) noexcept
{
if (!serviceDescription.isValid())
{
return cxx::error<Error>(Error::SERVICE_DESCRIPTION_INVALID);
}
// Forbid duplicate service descriptions entries
for (auto& element : m_serviceDescriptionVector)
{
if (element == serviceDescription)
{
return cxx::error<Error>(Error::SERVICE_DESCRIPTION_ALREADY_ADDED);
}
}
if (!m_serviceDescriptionVector.push_back(serviceDescription))
{
return cxx::error<Error>(Error::SERVICE_REGISTRY_FULL);
}
m_serviceMap.insert({serviceDescription.getServiceIDString(), m_serviceDescriptionVector.size() - 1});
m_instanceMap.insert({serviceDescription.getInstanceIDString(), m_serviceDescriptionVector.size() - 1});
return cxx::success<>();
}
bool ServiceRegistry::remove(const capro::ServiceDescription& serviceDescription) noexcept
{
if (!serviceDescription.isValid())
{
return false;
}
bool removedElement{false};
uint64_t index = 0U;
for (auto iterator = m_serviceDescriptionVector.begin(); iterator != m_serviceDescriptionVector.end();)
{
if (m_serviceDescriptionVector[index] == serviceDescription)
{
m_serviceDescriptionVector.erase(iterator);
removedElement = true;
// There can be not more than one element
break;
}
index++;
iterator++;
}
auto removeIndexFromMap = [](std::multimap<capro::IdString_t, uint64_t>& map, uint64_t index) {
bool removedEntry{false};
for (auto it = map.begin(); it != map.end();)
{
if (it->second == index)
{
it = map.erase(it);
removedEntry = true;
continue;
}
else if (removedEntry && it->second > index)
{
// update index due to removed element
it->second--;
}
it++;
}
};
removeIndexFromMap(m_serviceMap, index);
removeIndexFromMap(m_instanceMap, index);
return removedElement;
}
void ServiceRegistry::find(ServiceDescriptionVector_t& searchResult,
const capro::IdString_t& service,
const capro::IdString_t& instance) const noexcept
{
cxx::vector<uint64_t, MAX_SERVICE_DESCRIPTIONS> intersection;
// Find (K1, K2)
// O(log n + log n + max(#PossibleServices + #possiblesInstances) + #intersection)
if (instance != Wildcard && service != Wildcard)
{
cxx::vector<uint64_t, MAX_SERVICE_DESCRIPTIONS> possibleServices;
cxx::vector<uint64_t, MAX_SERVICE_DESCRIPTIONS> possibleInstances;
auto rangeServiceMap = m_serviceMap.equal_range(service);
for (auto entry = rangeServiceMap.first; entry != rangeServiceMap.second; ++entry)
{
possibleServices.push_back(entry->second);
}
auto rangeInstanceMap = m_instanceMap.equal_range(instance);
for (auto entry = rangeInstanceMap.first; entry != rangeInstanceMap.second; ++entry)
{
possibleInstances.push_back(entry->second);
}
::std::set_intersection(possibleServices.begin(),
possibleServices.end(),
possibleInstances.begin(),
possibleInstances.end(),
::std::back_inserter(intersection));
for (auto& value : intersection)
{
searchResult.push_back(m_serviceDescriptionVector[value]);
}
}
else
{
// Find (*, K2)
// O(log n + #result)
if (service == Wildcard && instance != Wildcard)
{
auto range = m_instanceMap.equal_range(instance);
for (auto entry = range.first; entry != range.second; ++entry)
{
searchResult.push_back(m_serviceDescriptionVector[entry->second]);
}
}
// Find (K1, *)
// O(log n + #result)
else if (instance == Wildcard && service != Wildcard)
{
auto range = m_serviceMap.equal_range(service);
for (auto entry = range.first; entry != range.second; ++entry)
{
searchResult.push_back(m_serviceDescriptionVector[entry->second]);
}
}
else
{
// Find (*, *)
// O(1)
searchResult = m_serviceDescriptionVector;
}
}
}
const ServiceRegistry::ServiceDescriptionVector_t ServiceRegistry::getServices() const noexcept
{
return m_serviceDescriptionVector;
}
} // namespace roudi
} // namespace iox
<commit_msg>iox-#415 Move else case in ServiceRegistry::find one level up<commit_after>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2021 by Apex.AI 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.
//
// SPDX-License-Identifier: Apache-2.0
#include "iceoryx_posh/internal/roudi/service_registry.hpp"
#include <algorithm>
namespace iox
{
namespace roudi
{
cxx::expected<ServiceRegistry::Error> ServiceRegistry::add(const capro::ServiceDescription& serviceDescription) noexcept
{
if (!serviceDescription.isValid())
{
return cxx::error<Error>(Error::SERVICE_DESCRIPTION_INVALID);
}
// Forbid duplicate service descriptions entries
for (auto& element : m_serviceDescriptionVector)
{
if (element == serviceDescription)
{
return cxx::error<Error>(Error::SERVICE_DESCRIPTION_ALREADY_ADDED);
}
}
if (!m_serviceDescriptionVector.push_back(serviceDescription))
{
return cxx::error<Error>(Error::SERVICE_REGISTRY_FULL);
}
m_serviceMap.insert({serviceDescription.getServiceIDString(), m_serviceDescriptionVector.size() - 1});
m_instanceMap.insert({serviceDescription.getInstanceIDString(), m_serviceDescriptionVector.size() - 1});
return cxx::success<>();
}
bool ServiceRegistry::remove(const capro::ServiceDescription& serviceDescription) noexcept
{
if (!serviceDescription.isValid())
{
return false;
}
bool removedElement{false};
uint64_t index = 0U;
for (auto iterator = m_serviceDescriptionVector.begin(); iterator != m_serviceDescriptionVector.end();)
{
if (m_serviceDescriptionVector[index] == serviceDescription)
{
m_serviceDescriptionVector.erase(iterator);
removedElement = true;
// There can be not more than one element
break;
}
index++;
iterator++;
}
auto removeIndexFromMap = [](std::multimap<capro::IdString_t, uint64_t>& map, uint64_t index) {
bool removedEntry{false};
for (auto it = map.begin(); it != map.end();)
{
if (it->second == index)
{
it = map.erase(it);
removedEntry = true;
continue;
}
else if (removedEntry && it->second > index)
{
// update index due to removed element
it->second--;
}
it++;
}
};
removeIndexFromMap(m_serviceMap, index);
removeIndexFromMap(m_instanceMap, index);
return removedElement;
}
void ServiceRegistry::find(ServiceDescriptionVector_t& searchResult,
const capro::IdString_t& service,
const capro::IdString_t& instance) const noexcept
{
cxx::vector<uint64_t, MAX_SERVICE_DESCRIPTIONS> intersection;
// Find (K1, K2)
// O(log n + log n + max(#PossibleServices + #possiblesInstances) + #intersection)
if (instance != Wildcard && service != Wildcard)
{
cxx::vector<uint64_t, MAX_SERVICE_DESCRIPTIONS> possibleServices;
cxx::vector<uint64_t, MAX_SERVICE_DESCRIPTIONS> possibleInstances;
auto rangeServiceMap = m_serviceMap.equal_range(service);
for (auto entry = rangeServiceMap.first; entry != rangeServiceMap.second; ++entry)
{
possibleServices.push_back(entry->second);
}
auto rangeInstanceMap = m_instanceMap.equal_range(instance);
for (auto entry = rangeInstanceMap.first; entry != rangeInstanceMap.second; ++entry)
{
possibleInstances.push_back(entry->second);
}
::std::set_intersection(possibleServices.begin(),
possibleServices.end(),
possibleInstances.begin(),
possibleInstances.end(),
::std::back_inserter(intersection));
for (auto& value : intersection)
{
searchResult.push_back(m_serviceDescriptionVector[value]);
}
}
// Find (*, K2)
// O(log n + #result)
else if (service == Wildcard && instance != Wildcard)
{
auto range = m_instanceMap.equal_range(instance);
for (auto entry = range.first; entry != range.second; ++entry)
{
searchResult.push_back(m_serviceDescriptionVector[entry->second]);
}
}
// Find (K1, *)
// O(log n + #result)
else if (instance == Wildcard && service != Wildcard)
{
auto range = m_serviceMap.equal_range(service);
for (auto entry = range.first; entry != range.second; ++entry)
{
searchResult.push_back(m_serviceDescriptionVector[entry->second]);
}
}
else
{
// Find (*, *)
// O(1)
searchResult = m_serviceDescriptionVector;
}
}
const ServiceRegistry::ServiceDescriptionVector_t ServiceRegistry::getServices() const noexcept
{
return m_serviceDescriptionVector;
}
} // namespace roudi
} // namespace iox
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 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
*
*****************************************************************************/
//$Id$
#ifndef MAPNIK_GEOMETRY_WKT_GENERATOR_HPP
#define MAPNIK_GEOMETRY_WKT_GENERATOR_HPP
// mapnik
#include <mapnik/global.hpp>
#include <mapnik/geometry.hpp>
#include <mapnik/util/vertex_iterator.hpp>
#include <mapnik/util/container_adapter.hpp>
// boost
#include <boost/tuple/tuple.hpp>
#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_fusion.hpp>
#include <boost/spirit/include/phoenix_function.hpp>
#include <boost/spirit/home/phoenix/statement/if.hpp>
#include <boost/fusion/include/boost_tuple.hpp>
//#define BOOST_SPIRIT_USE_PHOENIX_V3 1
namespace mapnik { namespace util {
namespace karma = boost::spirit::karma;
namespace phoenix = boost::phoenix;
namespace {
struct get_type
{
template <typename T>
struct result { typedef int type; };
int operator() (geometry_type const& geom) const
{
return (int)geom.type();
}
};
struct get_first
{
template <typename T>
struct result { typedef geometry_type::value_type const type; };
geometry_type::value_type const operator() (geometry_type const& geom) const
{
geometry_type::value_type coord;
boost::get<0>(coord) = geom.get_vertex(0,&boost::get<1>(coord),&boost::get<2>(coord));
return coord;
}
};
struct multi_geometry_
{
template <typename T>
struct result { typedef bool type; };
bool operator() (geometry_container const& geom) const
{
return geom.size() > 1 ? true : false;
}
};
struct multi_geometry_type
{
template <typename T>
struct result { typedef boost::tuple<unsigned,bool> type; };
boost::tuple<unsigned,bool> operator() (geometry_container const& geom) const
{
unsigned type = 0u;
bool collection = false;
geometry_container::const_iterator itr = geom.begin();
geometry_container::const_iterator end = geom.end();
for ( ; itr != end; ++itr)
{
if (type != 0 && itr->type() != type)
{
collection = true;
break;
}
type = itr->type();
}
return boost::tuple<unsigned,bool>(type, collection);
}
};
template <typename T>
struct wkt_coordinate_policy : karma::real_policies<T>
{
typedef boost::spirit::karma::real_policies<T> base_type;
static int floatfield(T n) { return base_type::fmtflags::fixed; }
static unsigned precision(T n) { return 6 ;}
};
}
template <typename OutputIterator>
struct wkt_generator :
karma::grammar<OutputIterator, geometry_type const& ()>
{
wkt_generator(bool single = false)
: wkt_generator::base_type(wkt)
{
using boost::spirit::karma::uint_;
using boost::spirit::karma::_val;
using boost::spirit::karma::_1;
using boost::spirit::karma::lit;
using boost::spirit::karma::_a;
using boost::spirit::karma::_r1;
using boost::spirit::karma::eps;
using boost::spirit::karma::string;
wkt = point | linestring | polygon
;
point = &uint_(mapnik::Point)[_1 = _type(_val)]
<< string[ phoenix::if_ (single) [_1 = "Point("]
.else_[_1 = "("]]
<< point_coord [_1 = _first(_val)] << lit(')')
;
linestring = &uint_(mapnik::LineString)[_1 = _type(_val)]
<< string[ phoenix::if_ (single) [_1 = "LineString("]
.else_[_1 = "("]]
<< coords
<< lit(')')
;
polygon = &uint_(mapnik::Polygon)[_1 = _type(_val)]
<< string[ phoenix::if_ (single) [_1 = "Polygon("]
.else_[_1 = "("]]
<< coords2
<< lit("))")
;
point_coord = &uint_ << coord_type << lit(' ') << coord_type
;
polygon_coord %= ( &uint_(mapnik::SEG_MOVETO) << eps[_r1 += 1]
<< string[ if_ (_r1 > 1) [_1 = "),("]
.else_[_1 = "("] ] | &uint_ << ",")
<< coord_type
<< lit(' ')
<< coord_type
;
coords2 %= *polygon_coord(_a)
;
coords = point_coord % lit(',')
;
}
// rules
karma::rule<OutputIterator, geometry_type const& ()> wkt;
karma::rule<OutputIterator, geometry_type const& ()> point;
karma::rule<OutputIterator, geometry_type const& ()> linestring;
karma::rule<OutputIterator, geometry_type const& ()> polygon;
karma::rule<OutputIterator, geometry_type const& ()> coords;
karma::rule<OutputIterator, karma::locals<unsigned>, geometry_type const& ()> coords2;
karma::rule<OutputIterator, geometry_type::value_type ()> point_coord;
karma::rule<OutputIterator, geometry_type::value_type (unsigned& )> polygon_coord;
// phoenix functions
phoenix::function<get_type > _type;
phoenix::function<get_first> _first;
//
karma::real_generator<double, wkt_coordinate_policy<double> > coord_type;
};
template <typename OutputIterator>
struct wkt_multi_generator :
karma::grammar<OutputIterator, karma::locals< boost::tuple<unsigned,bool> >, geometry_container const& ()>
{
wkt_multi_generator()
: wkt_multi_generator::base_type(wkt)
{
using boost::spirit::karma::lit;
using boost::spirit::karma::eps;
using boost::spirit::karma::_val;
using boost::spirit::karma::_1;
using boost::spirit::karma::_a;
geometry_types.add
(mapnik::Point,"Point")
(mapnik::LineString,"LineString")
(mapnik::Polygon,"Polygon")
;
wkt = eps(phoenix::at_c<1>(_a))[_a = _multi_type(_val)]
<< lit("GeometryCollection(") << geometry << lit(")")
| eps(is_multi(_val)) << lit("Multi") << geometry_types[_1 = phoenix::at_c<0>(_a)]
<< "(" << multi_geometry << ")"
| geometry
;
geometry = -(single_geometry % lit(','))
;
single_geometry = geometry_types[_1 = _type(_val)] << path
;
multi_geometry = -(path % lit(','))
;
}
// rules
karma::rule<OutputIterator, karma::locals<boost::tuple<unsigned,bool> >, geometry_container const& ()> wkt;
karma::rule<OutputIterator, geometry_container const& ()> geometry;
karma::rule<OutputIterator, geometry_type const& ()> single_geometry;
karma::rule<OutputIterator, geometry_container const& ()> multi_geometry;
wkt_generator<OutputIterator> path;
// phoenix
phoenix::function<multi_geometry_> is_multi;
phoenix::function<multi_geometry_type> _multi_type;
phoenix::function<get_type > _type;
//
karma::symbols<unsigned, char const*> geometry_types;
};
}}
#endif // MAPNIK_GEOMETRY_WKT_GENERATOR_HPP
<commit_msg>provide attribute customization point :<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 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
*
*****************************************************************************/
//$Id$
#ifndef MAPNIK_GEOMETRY_WKT_GENERATOR_HPP
#define MAPNIK_GEOMETRY_WKT_GENERATOR_HPP
// mapnik
#include <mapnik/global.hpp>
#include <mapnik/geometry.hpp>
#include <mapnik/util/vertex_iterator.hpp>
#include <mapnik/util/container_adapter.hpp>
// boost
#include <boost/tuple/tuple.hpp>
#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_fusion.hpp>
#include <boost/spirit/include/phoenix_function.hpp>
#include <boost/spirit/home/phoenix/statement/if.hpp>
#include <boost/fusion/include/boost_tuple.hpp>
//#define BOOST_SPIRIT_USE_PHOENIX_V3 1
namespace boost { namespace spirit { namespace traits {
// make gcc and darwin toolsets happy.
template <>
struct is_container<mapnik::geometry_container>
: mpl::false_
{};
}}}
namespace mapnik { namespace util {
namespace karma = boost::spirit::karma;
namespace phoenix = boost::phoenix;
namespace {
struct get_type
{
template <typename T>
struct result { typedef int type; };
int operator() (geometry_type const& geom) const
{
return (int)geom.type();
}
};
struct get_first
{
template <typename T>
struct result { typedef geometry_type::value_type const type; };
geometry_type::value_type const operator() (geometry_type const& geom) const
{
geometry_type::value_type coord;
boost::get<0>(coord) = geom.get_vertex(0,&boost::get<1>(coord),&boost::get<2>(coord));
return coord;
}
};
struct multi_geometry_
{
template <typename T>
struct result { typedef bool type; };
bool operator() (geometry_container const& geom) const
{
return geom.size() > 1 ? true : false;
}
};
struct multi_geometry_type
{
template <typename T>
struct result { typedef boost::tuple<unsigned,bool> type; };
boost::tuple<unsigned,bool> operator() (geometry_container const& geom) const
{
unsigned type = 0u;
bool collection = false;
geometry_container::const_iterator itr = geom.begin();
geometry_container::const_iterator end = geom.end();
for ( ; itr != end; ++itr)
{
if (type != 0 && itr->type() != type)
{
collection = true;
break;
}
type = itr->type();
}
return boost::tuple<unsigned,bool>(type, collection);
}
};
template <typename T>
struct wkt_coordinate_policy : karma::real_policies<T>
{
typedef boost::spirit::karma::real_policies<T> base_type;
static int floatfield(T n) { return base_type::fmtflags::fixed; }
static unsigned precision(T n) { return 6 ;}
};
}
template <typename OutputIterator>
struct wkt_generator :
karma::grammar<OutputIterator, geometry_type const& ()>
{
wkt_generator(bool single = false)
: wkt_generator::base_type(wkt)
{
using boost::spirit::karma::uint_;
using boost::spirit::karma::_val;
using boost::spirit::karma::_1;
using boost::spirit::karma::lit;
using boost::spirit::karma::_a;
using boost::spirit::karma::_r1;
using boost::spirit::karma::eps;
using boost::spirit::karma::string;
wkt = point | linestring | polygon
;
point = &uint_(mapnik::Point)[_1 = _type(_val)]
<< string[ phoenix::if_ (single) [_1 = "Point("]
.else_[_1 = "("]]
<< point_coord [_1 = _first(_val)] << lit(')')
;
linestring = &uint_(mapnik::LineString)[_1 = _type(_val)]
<< string[ phoenix::if_ (single) [_1 = "LineString("]
.else_[_1 = "("]]
<< coords
<< lit(')')
;
polygon = &uint_(mapnik::Polygon)[_1 = _type(_val)]
<< string[ phoenix::if_ (single) [_1 = "Polygon("]
.else_[_1 = "("]]
<< coords2
<< lit("))")
;
point_coord = &uint_ << coord_type << lit(' ') << coord_type
;
polygon_coord %= ( &uint_(mapnik::SEG_MOVETO) << eps[_r1 += 1]
<< string[ if_ (_r1 > 1) [_1 = "),("]
.else_[_1 = "("] ] | &uint_ << ",")
<< coord_type
<< lit(' ')
<< coord_type
;
coords2 %= *polygon_coord(_a)
;
coords = point_coord % lit(',')
;
}
// rules
karma::rule<OutputIterator, geometry_type const& ()> wkt;
karma::rule<OutputIterator, geometry_type const& ()> point;
karma::rule<OutputIterator, geometry_type const& ()> linestring;
karma::rule<OutputIterator, geometry_type const& ()> polygon;
karma::rule<OutputIterator, geometry_type const& ()> coords;
karma::rule<OutputIterator, karma::locals<unsigned>, geometry_type const& ()> coords2;
karma::rule<OutputIterator, geometry_type::value_type ()> point_coord;
karma::rule<OutputIterator, geometry_type::value_type (unsigned& )> polygon_coord;
// phoenix functions
phoenix::function<get_type > _type;
phoenix::function<get_first> _first;
//
karma::real_generator<double, wkt_coordinate_policy<double> > coord_type;
};
template <typename OutputIterator>
struct wkt_multi_generator :
karma::grammar<OutputIterator, karma::locals< boost::tuple<unsigned,bool> >, geometry_container const& ()>
{
wkt_multi_generator()
: wkt_multi_generator::base_type(wkt)
{
using boost::spirit::karma::lit;
using boost::spirit::karma::eps;
using boost::spirit::karma::_val;
using boost::spirit::karma::_1;
using boost::spirit::karma::_a;
geometry_types.add
(mapnik::Point,"Point")
(mapnik::LineString,"LineString")
(mapnik::Polygon,"Polygon")
;
wkt = eps(phoenix::at_c<1>(_a))[_a = _multi_type(_val)]
<< lit("GeometryCollection(") << geometry << lit(")")
| eps(is_multi(_val)) << lit("Multi") << geometry_types[_1 = phoenix::at_c<0>(_a)]
<< "(" << multi_geometry << ")"
| geometry
;
geometry = -(single_geometry % lit(','))
;
single_geometry = geometry_types[_1 = _type(_val)] << path
;
multi_geometry = -(path % lit(','))
;
}
// rules
karma::rule<OutputIterator, karma::locals<boost::tuple<unsigned,bool> >, geometry_container const& ()> wkt;
karma::rule<OutputIterator, geometry_container const& ()> geometry;
karma::rule<OutputIterator, geometry_type const& ()> single_geometry;
karma::rule<OutputIterator, geometry_container const& ()> multi_geometry;
wkt_generator<OutputIterator> path;
// phoenix
phoenix::function<multi_geometry_> is_multi;
phoenix::function<multi_geometry_type> _multi_type;
phoenix::function<get_type > _type;
//
karma::symbols<unsigned, char const*> geometry_types;
};
}}
#endif // MAPNIK_GEOMETRY_WKT_GENERATOR_HPP
<|endoftext|> |
<commit_before>/* Copyright (c) 2018 PaddlePaddle 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 "paddle/fluid/inference/tensorrt/convert/op_converter.h"
#include "paddle/fluid/inference/tensorrt/plugin/pool_op_plugin.h"
namespace paddle {
namespace framework {
class Scope;
namespace proto {
class OpDesc;
} // namespace proto
} // namespace framework
} // namespace paddle
namespace paddle {
namespace inference {
namespace tensorrt {
inline void DealCeilMode(const nvinfer1::Dims &input_shape,
std::vector<int> ksize, std::vector<int> strides,
std::vector<int> paddings, nvinfer1::DimsHW *pre_pad,
nvinfer1::DimsHW *post_pad, int input_dims) {
int input_height = input_shape.d[input_dims - 2];
int input_width = input_shape.d[input_dims - 1];
int floor_h_output_size =
(input_height - ksize[0] + 2 * paddings[0]) / strides[0] + 1;
int ceil_h_output_size =
(input_height - ksize[0] + 2 * paddings[0] + strides[0] - 1) /
strides[0] +
1;
int floor_w_output_size =
(input_width - ksize[1] + 2 * paddings[1]) / strides[1] + 1;
int ceil_w_output_size =
(input_width - ksize[1] + 2 * paddings[1] + strides[1] - 1) / strides[1] +
1;
if (floor_h_output_size != ceil_h_output_size) {
post_pad->h() = strides[0] - 1;
}
if (floor_w_output_size != ceil_w_output_size) {
post_pad->w() = strides[1] - 1;
}
}
/*
* Pool2dOp, IPoolingLayer in TRT. This Layer doesn't has weights.
*/
class Pool2dOpConverter : public OpConverter {
public:
void operator()(const framework::proto::OpDesc &op,
const framework::Scope &scope, bool test_mode) override {
VLOG(4)
<< "convert a fluid pool2d op to tensorrt pool2d layer without bias";
framework::OpDesc op_desc(op, nullptr);
PADDLE_ENFORCE_EQ(op_desc.Input("X").size(), 1UL,
platform::errors::InvalidArgument(
"TRT Pool2d expect 1 input, but got %d input.",
op_desc.Input("X").size()));
PADDLE_ENFORCE_EQ(op_desc.Output("Out").size(), 1UL,
platform::errors::InvalidArgument(
"TRT Pool2d expect 1 Output, but got %d output.",
op_desc.Output("Out").size()));
auto *input1 = engine_->GetITensor(op_desc.Input("X")[0]);
nvinfer1::Dims input_shape = input1->getDimensions();
int input_dims = input_shape.nbDims;
bool global_pooling =
BOOST_GET_CONST(bool, op_desc.GetAttr("global_pooling"));
std::string pool_type =
BOOST_GET_CONST(std::string, op_desc.GetAttr("pooling_type"));
std::vector<int> ksize =
BOOST_GET_CONST(std::vector<int>, op_desc.GetAttr("ksize"));
std::vector<int> strides =
BOOST_GET_CONST(std::vector<int>, op_desc.GetAttr("strides"));
std::vector<int> paddings =
BOOST_GET_CONST(std::vector<int>, op_desc.GetAttr("paddings"));
bool ceil_mode = BOOST_GET_CONST(bool, op_desc.GetAttr("ceil_mode"));
bool adaptive = false;
if (op_desc.HasAttr("adaptive"))
adaptive = BOOST_GET_CONST(bool, op_desc.GetAttr("adaptive"));
nvinfer1::PoolingType nv_pool_type = nvinfer1::PoolingType::kMAX;
plugin::PoolPlugin::PoolType plugin_pool_type =
plugin::PoolPlugin::PoolType::max;
if (pool_type == "max") {
nv_pool_type = nvinfer1::PoolingType::kMAX;
plugin_pool_type = plugin::PoolPlugin::PoolType::max;
} else if (pool_type == "avg") {
nv_pool_type = nvinfer1::PoolingType::kAVERAGE;
plugin_pool_type = plugin::PoolPlugin::PoolType::avg;
} else {
PADDLE_THROW(platform::errors::Fatal(
"Wrong pool op type, the trt do not support the %s pool type.",
pool_type));
}
nvinfer1::DimsHW nv_ksize(ksize[0], ksize[1]);
nvinfer1::DimsHW nv_strides(strides[0], strides[1]);
nvinfer1::DimsHW nv_paddings(paddings[0], paddings[1]);
nvinfer1::ILayer *layer = nullptr;
if (op_desc.HasAttr("enable_int8")) {
#if IS_TRT_VERSION_GE(5000)
CHECK(op_desc.HasAttr("X_scale"));
float input_scale = BOOST_GET_CONST(float, op_desc.GetAttr("X_scale"));
engine_->SetTensorDynamicRange(input1, input_scale);
#endif
}
if (engine_->with_dynamic_shape()) {
if (!adaptive && pool_type == "max" && !global_pooling && !ceil_mode) {
auto *pool_layer = TRT_ENGINE_ADD_LAYER(engine_, Pooling, *input1,
nv_pool_type, nv_ksize);
pool_layer->setStride(nv_strides);
pool_layer->setPadding(nv_paddings);
layer = pool_layer;
} else {
#if IS_TRT_VERSION_GE(6000)
plugin::PoolPluginDynamic *plugin =
new plugin::PoolPluginDynamic(ceil_mode, pool_type, adaptive, ksize,
strides, paddings, global_pooling);
layer = engine_->AddPluginV2(&input1, 1, plugin);
#endif
}
auto output_name = op_desc.Output("Out")[0];
layer->setName(("pool2d (Output: " + output_name + ")").c_str());
layer->getOutput(0)->setName(output_name.c_str());
engine_->SetITensor(output_name, layer->getOutput(0));
if (test_mode) {
engine_->DeclareOutput(output_name);
}
return;
}
if (global_pooling == true) {
nv_ksize.d[0] = input_shape.d[input_dims - 2];
nv_ksize.d[1] = input_shape.d[input_dims - 1];
auto *layer = TRT_ENGINE_ADD_LAYER(
engine_, Pooling, *const_cast<nvinfer1::ITensor *>(input1),
nv_pool_type, nv_ksize);
PADDLE_ENFORCE_NOT_NULL(
layer, platform::errors::Fatal(
"trt pool layer in converter could not be created."));
auto output_name = op_desc.Output("Out")[0];
layer->setName(("pool2d (Output: " + output_name + ")").c_str());
layer->getOutput(0)->setName(output_name.c_str());
engine_->SetITensor(output_name, layer->getOutput(0));
if (test_mode) {
engine_->DeclareOutput(output_name);
}
return;
}
if (!adaptive && pool_type == "max") {
// Under ceil mode, the pre_pad and post_pad are used to
// record the the padding size. In some ceil mode cases,
// we do not need padding, so we initialize the two vars to 0.
nvinfer1::DimsHW pre_pad(0, 0);
nvinfer1::DimsHW post_pad(0, 0);
if (ceil_mode) {
// If ceil mode is true, we will pad the appropriate size to the input.
DealCeilMode(input_shape, ksize, strides, paddings, &pre_pad, &post_pad,
input_dims);
auto *pad_layer = TRT_ENGINE_ADD_LAYER(
engine_, Padding, *const_cast<nvinfer1::ITensor *>(input1), pre_pad,
post_pad);
PADDLE_ENFORCE_NOT_NULL(
pad_layer,
platform::errors::Fatal(
"pad layer in poolOp converter could not be created."));
input1 = pad_layer->getOutput(0);
}
auto *pool_layer = TRT_ENGINE_ADD_LAYER(
engine_, Pooling, *const_cast<nvinfer1::ITensor *>(input1),
nv_pool_type, nv_ksize);
PADDLE_ENFORCE_NOT_NULL(
pool_layer, platform::errors::Fatal(
"trt pool layer in converter could not be created."));
pool_layer->setStride(nv_strides);
pool_layer->setPadding(nv_paddings);
layer = pool_layer;
} else {
// Average pooling needs to exclude the padding pixels from the average
// mean.
// It is not supported well by TRT, we use a plugin here.
std::vector<int> input_shape_v;
for (int i = 0; i < input_dims; i++) {
input_shape_v.push_back(input_shape.d[i]);
}
plugin::PoolPlugin *plugin =
new plugin::PoolPlugin(ceil_mode, plugin_pool_type, adaptive, ksize,
strides, paddings, input_shape_v);
auto *pool_layer = engine_->AddPlugin(&input1, 1, plugin);
PADDLE_ENFORCE_NOT_NULL(
pool_layer,
platform::errors::Fatal(
"trt pool plugin layer in converter could not be created."));
layer = pool_layer;
}
auto output_name = op_desc.Output("Out")[0];
RreplenishLayerAndOutput(layer, "pool2d", {output_name}, test_mode);
}
};
} // namespace tensorrt
} // namespace inference
} // namespace paddle
USE_OP(pool2d);
REGISTER_TRT_OP_CONVERTER(pool2d, Pool2dOpConverter);
<commit_msg>change avg pooling from trt plugin to trt layer (#28032)<commit_after>/* Copyright (c) 2018 PaddlePaddle 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 "paddle/fluid/inference/tensorrt/convert/op_converter.h"
#include "paddle/fluid/inference/tensorrt/plugin/pool_op_plugin.h"
namespace paddle {
namespace framework {
class Scope;
namespace proto {
class OpDesc;
} // namespace proto
} // namespace framework
} // namespace paddle
namespace paddle {
namespace inference {
namespace tensorrt {
inline void DealCeilMode(const nvinfer1::Dims &input_shape,
std::vector<int> ksize, std::vector<int> strides,
std::vector<int> paddings, nvinfer1::DimsHW *pre_pad,
nvinfer1::DimsHW *post_pad, int input_dims) {
int input_height = input_shape.d[input_dims - 2];
int input_width = input_shape.d[input_dims - 1];
int floor_h_output_size =
(input_height - ksize[0] + 2 * paddings[0]) / strides[0] + 1;
int ceil_h_output_size =
(input_height - ksize[0] + 2 * paddings[0] + strides[0] - 1) /
strides[0] +
1;
int floor_w_output_size =
(input_width - ksize[1] + 2 * paddings[1]) / strides[1] + 1;
int ceil_w_output_size =
(input_width - ksize[1] + 2 * paddings[1] + strides[1] - 1) / strides[1] +
1;
if (floor_h_output_size != ceil_h_output_size) {
post_pad->h() = strides[0] - 1;
}
if (floor_w_output_size != ceil_w_output_size) {
post_pad->w() = strides[1] - 1;
}
}
/*
* Pool2dOp, IPoolingLayer in TRT. This Layer doesn't has weights.
*/
class Pool2dOpConverter : public OpConverter {
public:
void operator()(const framework::proto::OpDesc &op,
const framework::Scope &scope, bool test_mode) override {
VLOG(4)
<< "convert a fluid pool2d op to tensorrt pool2d layer without bias";
framework::OpDesc op_desc(op, nullptr);
PADDLE_ENFORCE_EQ(op_desc.Input("X").size(), 1UL,
platform::errors::InvalidArgument(
"TRT Pool2d expect 1 input, but got %d input.",
op_desc.Input("X").size()));
PADDLE_ENFORCE_EQ(op_desc.Output("Out").size(), 1UL,
platform::errors::InvalidArgument(
"TRT Pool2d expect 1 Output, but got %d output.",
op_desc.Output("Out").size()));
auto *input1 = engine_->GetITensor(op_desc.Input("X")[0]);
nvinfer1::Dims input_shape = input1->getDimensions();
int input_dims = input_shape.nbDims;
bool global_pooling =
BOOST_GET_CONST(bool, op_desc.GetAttr("global_pooling"));
std::string pool_type =
BOOST_GET_CONST(std::string, op_desc.GetAttr("pooling_type"));
std::vector<int> ksize =
BOOST_GET_CONST(std::vector<int>, op_desc.GetAttr("ksize"));
std::vector<int> strides =
BOOST_GET_CONST(std::vector<int>, op_desc.GetAttr("strides"));
std::vector<int> paddings =
BOOST_GET_CONST(std::vector<int>, op_desc.GetAttr("paddings"));
bool exclusive = op_desc.HasAttr("exclusive")
? BOOST_GET_CONST(bool, op_desc.GetAttr("exclusive"))
: true;
bool ceil_mode = BOOST_GET_CONST(bool, op_desc.GetAttr("ceil_mode"));
bool adaptive = false;
if (op_desc.HasAttr("adaptive"))
adaptive = BOOST_GET_CONST(bool, op_desc.GetAttr("adaptive"));
nvinfer1::PoolingType nv_pool_type = nvinfer1::PoolingType::kMAX;
plugin::PoolPlugin::PoolType plugin_pool_type =
plugin::PoolPlugin::PoolType::max;
if (pool_type == "max") {
nv_pool_type = nvinfer1::PoolingType::kMAX;
plugin_pool_type = plugin::PoolPlugin::PoolType::max;
} else if (pool_type == "avg") {
nv_pool_type = nvinfer1::PoolingType::kAVERAGE;
plugin_pool_type = plugin::PoolPlugin::PoolType::avg;
} else {
PADDLE_THROW(platform::errors::Fatal(
"Wrong pool op type, the trt do not support the %s pool type.",
pool_type));
}
nvinfer1::DimsHW nv_ksize(ksize[0], ksize[1]);
nvinfer1::DimsHW nv_strides(strides[0], strides[1]);
nvinfer1::DimsHW nv_paddings(paddings[0], paddings[1]);
nvinfer1::ILayer *layer = nullptr;
if (op_desc.HasAttr("enable_int8")) {
#if IS_TRT_VERSION_GE(5000)
CHECK(op_desc.HasAttr("X_scale"));
float input_scale = BOOST_GET_CONST(float, op_desc.GetAttr("X_scale"));
engine_->SetTensorDynamicRange(input1, input_scale);
#endif
}
if (engine_->with_dynamic_shape()) {
if (!adaptive && pool_type == "max" && !global_pooling && !ceil_mode) {
auto *pool_layer = TRT_ENGINE_ADD_LAYER(engine_, Pooling, *input1,
nv_pool_type, nv_ksize);
pool_layer->setStride(nv_strides);
pool_layer->setPadding(nv_paddings);
layer = pool_layer;
} else {
#if IS_TRT_VERSION_GE(6000)
plugin::PoolPluginDynamic *plugin =
new plugin::PoolPluginDynamic(ceil_mode, pool_type, adaptive, ksize,
strides, paddings, global_pooling);
layer = engine_->AddPluginV2(&input1, 1, plugin);
#endif
}
auto output_name = op_desc.Output("Out")[0];
layer->setName(("pool2d (Output: " + output_name + ")").c_str());
layer->getOutput(0)->setName(output_name.c_str());
engine_->SetITensor(output_name, layer->getOutput(0));
if (test_mode) {
engine_->DeclareOutput(output_name);
}
return;
}
if (global_pooling == true) {
nv_ksize.d[0] = input_shape.d[input_dims - 2];
nv_ksize.d[1] = input_shape.d[input_dims - 1];
auto *layer = TRT_ENGINE_ADD_LAYER(
engine_, Pooling, *const_cast<nvinfer1::ITensor *>(input1),
nv_pool_type, nv_ksize);
PADDLE_ENFORCE_NOT_NULL(
layer, platform::errors::Fatal(
"trt pool layer in converter could not be created."));
auto output_name = op_desc.Output("Out")[0];
layer->setName(("pool2d (Output: " + output_name + ")").c_str());
layer->getOutput(0)->setName(output_name.c_str());
engine_->SetITensor(output_name, layer->getOutput(0));
if (test_mode) {
engine_->DeclareOutput(output_name);
}
return;
}
if (!adaptive) {
// Under ceil mode, the pre_pad and post_pad are used to
// record the the padding size. In some ceil mode cases,
// we do not need padding, so we initialize the two vars to 0.
nvinfer1::DimsHW pre_pad(0, 0);
nvinfer1::DimsHW post_pad(0, 0);
if (ceil_mode) {
// If ceil mode is true, we will pad the appropriate size to the input.
DealCeilMode(input_shape, ksize, strides, paddings, &pre_pad, &post_pad,
input_dims);
auto *pad_layer = TRT_ENGINE_ADD_LAYER(
engine_, Padding, *const_cast<nvinfer1::ITensor *>(input1), pre_pad,
post_pad);
PADDLE_ENFORCE_NOT_NULL(
pad_layer,
platform::errors::Fatal(
"pad layer in poolOp converter could not be created."));
input1 = pad_layer->getOutput(0);
}
auto *pool_layer = TRT_ENGINE_ADD_LAYER(
engine_, Pooling, *const_cast<nvinfer1::ITensor *>(input1),
nv_pool_type, nv_ksize);
PADDLE_ENFORCE_NOT_NULL(
pool_layer, platform::errors::Fatal(
"trt pool layer in converter could not be created."));
pool_layer->setStride(nv_strides);
pool_layer->setPadding(nv_paddings);
pool_layer->setAverageCountExcludesPadding(exclusive);
layer = pool_layer;
} else {
// Average pooling needs to exclude the padding pixels from the average
// mean.
// It is not supported well by TRT, we use a plugin here.
std::vector<int> input_shape_v;
for (int i = 0; i < input_dims; i++) {
input_shape_v.push_back(input_shape.d[i]);
}
plugin::PoolPlugin *plugin =
new plugin::PoolPlugin(ceil_mode, plugin_pool_type, adaptive, ksize,
strides, paddings, input_shape_v);
auto *pool_layer = engine_->AddPlugin(&input1, 1, plugin);
PADDLE_ENFORCE_NOT_NULL(
pool_layer,
platform::errors::Fatal(
"trt pool plugin layer in converter could not be created."));
layer = pool_layer;
}
auto output_name = op_desc.Output("Out")[0];
RreplenishLayerAndOutput(layer, "pool2d", {output_name}, test_mode);
}
};
} // namespace tensorrt
} // namespace inference
} // namespace paddle
USE_OP(pool2d);
REGISTER_TRT_OP_CONVERTER(pool2d, Pool2dOpConverter);
<|endoftext|> |
<commit_before>//===--- Linker.cpp -------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
/// \file
///
/// The SIL linker walks the call graph beginning at a starting function,
/// deserializing functions, vtables and witness tables.
///
/// The behavior of the linker is controlled by a LinkMode value. The LinkMode
/// has three possible values:
///
/// - LinkNone: The linker does not deserialize anything. This is only used for
/// debugging and testing purposes, and never during normal operation.
///
/// - LinkNormal: The linker deserializes bodies for declarations that must be
/// emitted into the client because they do not have definitions available
/// externally. This includes:
///
/// - witness tables for imported conformances
///
/// - functions with shared linkage
///
/// - LinkAll: All reachable functions (including public functions) are
/// deserialized, including public functions.
///
/// The primary entry point into the linker is the SILModule::linkFunction()
/// function, which recursively walks the call graph starting from the given
/// function.
///
/// In the mandatory pipeline (-Onone), the linker is invoked from the mandatory
/// SIL linker pass, which pulls in just enough to allow us to emit code, using
/// LinkNormal mode.
///
/// In the performance pipeline, after guaranteed optimizations but before
/// performance optimizations, the 'performance SILLinker' pass links
/// transitively all reachable functions, to uncover optimization opportunities
/// that might be missed from deserializing late. The performance pipeline uses
/// LinkAll mode.
///
/// *NOTE*: In LinkAll mode, we deserialize all vtables and witness tables,
/// even those with public linkage. This is not strictly necessary, since the
/// devirtualizer deserializes vtables and witness tables as needed. However,
/// doing so early creates more opportunities for optimization.
///
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-linker"
#include "Linker.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/Debug.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/SubstitutionMap.h"
#include "swift/ClangImporter/ClangModule.h"
#include "swift/SIL/FormalLinkage.h"
#include <functional>
using namespace swift;
using namespace Lowering;
STATISTIC(NumFuncLinked, "Number of SIL functions linked");
//===----------------------------------------------------------------------===//
// Linker Helpers
//===----------------------------------------------------------------------===//
void SILLinkerVisitor::addFunctionToWorklist(SILFunction *F) {
assert(F->isExternalDeclaration());
LLVM_DEBUG(llvm::dbgs() << "Imported function: "
<< F->getName() << "\n");
if (Mod.loadFunction(F)) {
if (F->isExternalDeclaration())
return;
F->setBare(IsBare);
F->verify();
Worklist.push_back(F);
Changed = true;
++NumFuncLinked;
}
}
/// Deserialize a function and add it to the worklist for processing.
void SILLinkerVisitor::maybeAddFunctionToWorklist(SILFunction *F) {
// Don't need to do anything if the function already has a body.
if (!F->isExternalDeclaration())
return;
// In the performance pipeline, we deserialize all reachable functions.
if (isLinkAll())
return addFunctionToWorklist(F);
// Otherwise, make sure to deserialize shared functions; we need to
// emit them into the client binary since they're not available
// externally.
if (hasSharedVisibility(F->getLinkage()))
return addFunctionToWorklist(F);
// Functions with PublicNonABI linkage are deserialized as having
// HiddenExternal linkage when they are declarations, then they
// become SharedExternal after the body has been deserialized.
// So try deserializing HiddenExternal functions too.
if (F->getLinkage() == SILLinkage::HiddenExternal)
return addFunctionToWorklist(F);
}
/// Process F, recursively deserializing any thing F may reference.
bool SILLinkerVisitor::processFunction(SILFunction *F) {
// If F is a declaration, first deserialize it.
if (F->isExternalDeclaration()) {
maybeAddFunctionToWorklist(F);
} else {
Worklist.push_back(F);
}
process();
return Changed;
}
/// Deserialize the given VTable all SIL the VTable transitively references.
void SILLinkerVisitor::linkInVTable(ClassDecl *D) {
// Devirtualization already deserializes vtables as needed in both the
// mandatory and performance pipelines, and we don't support specialized
// vtables that might have shared linkage yet, so this is only needed in
// the performance pipeline to deserialize more functions early, and expose
// optimization opportunities.
assert(isLinkAll());
// Attempt to lookup the Vtbl from the SILModule.
SILVTable *Vtbl = Mod.lookUpVTable(D);
if (!Vtbl)
return;
// Ok we found our VTable. Visit each function referenced by the VTable. If
// any of the functions are external declarations, add them to the worklist
// for processing.
for (auto P : Vtbl->getEntries()) {
// Deserialize and recursively walk any vtable entries that do not have
// bodies yet.
maybeAddFunctionToWorklist(P.Implementation);
}
}
//===----------------------------------------------------------------------===//
// Visitors
//===----------------------------------------------------------------------===//
static template<typename Inst>
bool applyInstCalleeIsGeneric(Inst AI) {
return AI->getCallee()->getType().template castTo<SILFunctionType>()
->getGenericSignature();
}
void SILLinkerVisitor::visitApplyInst(ApplyInst *AI) {
if (applyInstCalleeIsGeneric(AI)) {
visitApplySubstitutions(AI->getSubstitutionMap());
}
}
void SILLinkerVisitor::visitTryApplyInst(TryApplyInst *TAI) {
if (applyInstCalleeIsGeneric(TAI)) {
visitApplySubstitutions(TAI->getSubstitutionMap());
}
}
void SILLinkerVisitor::visitPartialApplyInst(PartialApplyInst *PAI) {
if (applyInstCalleeIsGeneric(PAI)) {
visitApplySubstitutions(PAI->getSubstitutionMap());
}
}
void SILLinkerVisitor::visitFunctionRefInst(FunctionRefInst *FRI) {
maybeAddFunctionToWorklist(FRI->getReferencedFunction());
}
// Eagerly visiting all used conformances leads to a large blowup
// in the amount of SIL we read in. For optimization purposes we can defer
// reading in most conformances until we need them for devirtualization.
// However, we *must* pull in shared clang-importer-derived conformances
// we potentially use, since we may not otherwise have a local definition.
static bool mustDeserializeProtocolConformance(SILModule &M,
ProtocolConformanceRef c) {
if (!c.isConcrete())
return false;
auto conformance = c.getConcrete()->getRootNormalConformance();
return M.Types.protocolRequiresWitnessTable(conformance->getProtocol())
&& isa<ClangModuleUnit>(conformance->getDeclContext()
->getModuleScopeContext());
}
void SILLinkerVisitor::visitProtocolConformance(
ProtocolConformanceRef ref, const Optional<SILDeclRef> &Member) {
// If an abstract protocol conformance was passed in, just return false.
if (ref.isAbstract())
return;
bool mustDeserialize = mustDeserializeProtocolConformance(Mod, ref);
// Otherwise try and lookup a witness table for C.
auto C = ref.getConcrete();
if (!VisitedConformances.insert(C).second)
return;
SILWitnessTable *WT = Mod.lookUpWitnessTable(C, true);
// If we don't find any witness table for the conformance, bail and return
// false.
if (!WT) {
Mod.createWitnessTableDeclaration(
C, getLinkageForProtocolConformance(
C->getRootNormalConformance(), NotForDefinition));
// Adding the declaration may allow us to now deserialize the body.
// Force the body if we must deserialize this witness table.
if (mustDeserialize) {
WT = Mod.lookUpWitnessTable(C, true);
assert(WT && WT->isDefinition()
&& "unable to deserialize witness table when we must?!");
} else {
return;
}
}
// If the looked up witness table is a declaration, there is nothing we can
// do here. Just bail and return false.
if (WT->isDeclaration())
return;
auto maybeVisitRelatedConformance = [&](ProtocolConformanceRef c) {
// Formally all conformances referenced by a used conformance are used.
// However, eagerly visiting them all at this point leads to a large blowup
// in the amount of SIL we read in. For optimization purposes we can defer
// reading in most conformances until we need them for devirtualization.
// However, we *must* pull in shared clang-importer-derived conformances
// we potentially use, since we may not otherwise have a local definition.
if (mustDeserializeProtocolConformance(Mod, c))
visitProtocolConformance(c, None);
};
// For each entry in the witness table...
for (auto &E : WT->getEntries()) {
switch (E.getKind()) {
// If the entry is a witness method...
case SILWitnessTable::WitnessKind::Method: {
// And we are only interested in deserializing a specific requirement
// and don't have that requirement, don't deserialize this method.
if (Member.hasValue() && E.getMethodWitness().Requirement != *Member)
continue;
// The witness could be removed by dead function elimination.
if (!E.getMethodWitness().Witness)
continue;
// Otherwise, deserialize the witness if it has shared linkage, or if
// we were asked to deserialize everything.
maybeAddFunctionToWorklist(E.getMethodWitness().Witness);
break;
}
// If the entry is a related witness table, see whether we need to
// eagerly deserialize it.
case SILWitnessTable::WitnessKind::BaseProtocol: {
auto baseConformance = E.getBaseProtocolWitness().Witness;
maybeVisitRelatedConformance(ProtocolConformanceRef(baseConformance));
break;
}
case SILWitnessTable::WitnessKind::AssociatedTypeProtocol: {
auto assocConformance = E.getAssociatedTypeProtocolWitness().Witness;
maybeVisitRelatedConformance(assocConformance);
break;
}
case SILWitnessTable::WitnessKind::AssociatedType:
case SILWitnessTable::WitnessKind::Invalid:
break;
}
}
}
void SILLinkerVisitor::visitApplySubstitutions(SubstitutionMap subs) {
for (auto conformance : subs.getConformances()) {
// Formally all conformances referenced in a function application are
// used. However, eagerly visiting them all at this point leads to a
// large blowup in the amount of SIL we read in, and we aren't very
// systematic about laziness. For optimization purposes we can defer
// reading in most conformances until we need them for devirtualization.
// However, we *must* pull in shared clang-importer-derived conformances
// we potentially use, since we may not otherwise have a local definition.
if (mustDeserializeProtocolConformance(Mod, conformance)) {
visitProtocolConformance(conformance, None);
}
}
}
void SILLinkerVisitor::visitInitExistentialAddrInst(
InitExistentialAddrInst *IEI) {
// Link in all protocol conformances that this touches.
//
// TODO: There might be a two step solution where the init_existential_inst
// causes the witness table to be brought in as a declaration and then the
// protocol method inst causes the actual deserialization. For now we are
// not going to be smart about this to enable avoiding any issues with
// visiting the open_existential_addr/witness_method before the
// init_existential_inst.
for (ProtocolConformanceRef C : IEI->getConformances()) {
visitProtocolConformance(C, Optional<SILDeclRef>());
}
}
void SILLinkerVisitor::visitInitExistentialRefInst(
InitExistentialRefInst *IERI) {
// Link in all protocol conformances that this touches.
//
// TODO: There might be a two step solution where the init_existential_inst
// causes the witness table to be brought in as a declaration and then the
// protocol method inst causes the actual deserialization. For now we are
// not going to be smart about this to enable avoiding any issues with
// visiting the protocol_method before the init_existential_inst.
for (ProtocolConformanceRef C : IERI->getConformances()) {
visitProtocolConformance(C, Optional<SILDeclRef>());
}
}
void SILLinkerVisitor::visitAllocRefInst(AllocRefInst *ARI) {
if (!isLinkAll())
return;
// Grab the class decl from the alloc ref inst.
ClassDecl *D = ARI->getType().getClassOrBoundGenericClass();
if (!D)
return;
linkInVTable(D);
}
void SILLinkerVisitor::visitMetatypeInst(MetatypeInst *MI) {
if (!isLinkAll())
return;
CanType instTy = MI->getType().castTo<MetatypeType>().getInstanceType();
ClassDecl *C = instTy.getClassOrBoundGenericClass();
if (!C)
return;
linkInVTable(C);
}
//===----------------------------------------------------------------------===//
// Top Level Routine
//===----------------------------------------------------------------------===//
// Main loop of the visitor. Called by one of the other *visit* methods.
void SILLinkerVisitor::process() {
// Process everything transitively referenced by one of the functions in the
// worklist.
while (!Worklist.empty()) {
auto *Fn = Worklist.pop_back_val();
if (Fn->getModule().isSerialized()) {
// If the containing module has been serialized,
// Remove The Serialized state (if any)
// This allows for more optimizations
Fn->setSerialized(IsSerialized_t::IsNotSerialized);
}
LLVM_DEBUG(llvm::dbgs() << "Process imports in function: "
<< Fn->getName() << "\n");
for (auto &BB : *Fn) {
for (auto &I : BB) {
visit(&I);
}
}
}
}
<commit_msg>[SIL Linker] Remove `applyInstCalleeIsGeneric`<commit_after>//===--- Linker.cpp -------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
/// \file
///
/// The SIL linker walks the call graph beginning at a starting function,
/// deserializing functions, vtables and witness tables.
///
/// The behavior of the linker is controlled by a LinkMode value. The LinkMode
/// has three possible values:
///
/// - LinkNone: The linker does not deserialize anything. This is only used for
/// debugging and testing purposes, and never during normal operation.
///
/// - LinkNormal: The linker deserializes bodies for declarations that must be
/// emitted into the client because they do not have definitions available
/// externally. This includes:
///
/// - witness tables for imported conformances
///
/// - functions with shared linkage
///
/// - LinkAll: All reachable functions (including public functions) are
/// deserialized, including public functions.
///
/// The primary entry point into the linker is the SILModule::linkFunction()
/// function, which recursively walks the call graph starting from the given
/// function.
///
/// In the mandatory pipeline (-Onone), the linker is invoked from the mandatory
/// SIL linker pass, which pulls in just enough to allow us to emit code, using
/// LinkNormal mode.
///
/// In the performance pipeline, after guaranteed optimizations but before
/// performance optimizations, the 'performance SILLinker' pass links
/// transitively all reachable functions, to uncover optimization opportunities
/// that might be missed from deserializing late. The performance pipeline uses
/// LinkAll mode.
///
/// *NOTE*: In LinkAll mode, we deserialize all vtables and witness tables,
/// even those with public linkage. This is not strictly necessary, since the
/// devirtualizer deserializes vtables and witness tables as needed. However,
/// doing so early creates more opportunities for optimization.
///
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-linker"
#include "Linker.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/Debug.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/SubstitutionMap.h"
#include "swift/ClangImporter/ClangModule.h"
#include "swift/SIL/FormalLinkage.h"
#include <functional>
using namespace swift;
using namespace Lowering;
STATISTIC(NumFuncLinked, "Number of SIL functions linked");
//===----------------------------------------------------------------------===//
// Linker Helpers
//===----------------------------------------------------------------------===//
void SILLinkerVisitor::addFunctionToWorklist(SILFunction *F) {
assert(F->isExternalDeclaration());
LLVM_DEBUG(llvm::dbgs() << "Imported function: "
<< F->getName() << "\n");
if (Mod.loadFunction(F)) {
if (F->isExternalDeclaration())
return;
F->setBare(IsBare);
F->verify();
Worklist.push_back(F);
Changed = true;
++NumFuncLinked;
}
}
/// Deserialize a function and add it to the worklist for processing.
void SILLinkerVisitor::maybeAddFunctionToWorklist(SILFunction *F) {
// Don't need to do anything if the function already has a body.
if (!F->isExternalDeclaration())
return;
// In the performance pipeline, we deserialize all reachable functions.
if (isLinkAll())
return addFunctionToWorklist(F);
// Otherwise, make sure to deserialize shared functions; we need to
// emit them into the client binary since they're not available
// externally.
if (hasSharedVisibility(F->getLinkage()))
return addFunctionToWorklist(F);
// Functions with PublicNonABI linkage are deserialized as having
// HiddenExternal linkage when they are declarations, then they
// become SharedExternal after the body has been deserialized.
// So try deserializing HiddenExternal functions too.
if (F->getLinkage() == SILLinkage::HiddenExternal)
return addFunctionToWorklist(F);
}
/// Process F, recursively deserializing any thing F may reference.
bool SILLinkerVisitor::processFunction(SILFunction *F) {
// If F is a declaration, first deserialize it.
if (F->isExternalDeclaration()) {
maybeAddFunctionToWorklist(F);
} else {
Worklist.push_back(F);
}
process();
return Changed;
}
/// Deserialize the given VTable all SIL the VTable transitively references.
void SILLinkerVisitor::linkInVTable(ClassDecl *D) {
// Devirtualization already deserializes vtables as needed in both the
// mandatory and performance pipelines, and we don't support specialized
// vtables that might have shared linkage yet, so this is only needed in
// the performance pipeline to deserialize more functions early, and expose
// optimization opportunities.
assert(isLinkAll());
// Attempt to lookup the Vtbl from the SILModule.
SILVTable *Vtbl = Mod.lookUpVTable(D);
if (!Vtbl)
return;
// Ok we found our VTable. Visit each function referenced by the VTable. If
// any of the functions are external declarations, add them to the worklist
// for processing.
for (auto P : Vtbl->getEntries()) {
// Deserialize and recursively walk any vtable entries that do not have
// bodies yet.
maybeAddFunctionToWorklist(P.Implementation);
}
}
//===----------------------------------------------------------------------===//
// Visitors
//===----------------------------------------------------------------------===//
void SILLinkerVisitor::visitApplyInst(ApplyInst *AI) {
visitApplySubstitutions(AI->getSubstitutionMap());
}
void SILLinkerVisitor::visitTryApplyInst(TryApplyInst *TAI) {
visitApplySubstitutions(TAI->getSubstitutionMap());
}
void SILLinkerVisitor::visitPartialApplyInst(PartialApplyInst *PAI) {
visitApplySubstitutions(PAI->getSubstitutionMap());
}
void SILLinkerVisitor::visitFunctionRefInst(FunctionRefInst *FRI) {
maybeAddFunctionToWorklist(FRI->getReferencedFunction());
}
// Eagerly visiting all used conformances leads to a large blowup
// in the amount of SIL we read in. For optimization purposes we can defer
// reading in most conformances until we need them for devirtualization.
// However, we *must* pull in shared clang-importer-derived conformances
// we potentially use, since we may not otherwise have a local definition.
static bool mustDeserializeProtocolConformance(SILModule &M,
ProtocolConformanceRef c) {
if (!c.isConcrete())
return false;
auto conformance = c.getConcrete()->getRootNormalConformance();
return M.Types.protocolRequiresWitnessTable(conformance->getProtocol())
&& isa<ClangModuleUnit>(conformance->getDeclContext()
->getModuleScopeContext());
}
void SILLinkerVisitor::visitProtocolConformance(
ProtocolConformanceRef ref, const Optional<SILDeclRef> &Member) {
// If an abstract protocol conformance was passed in, just return false.
if (ref.isAbstract())
return;
bool mustDeserialize = mustDeserializeProtocolConformance(Mod, ref);
// Otherwise try and lookup a witness table for C.
auto C = ref.getConcrete();
if (!VisitedConformances.insert(C).second)
return;
SILWitnessTable *WT = Mod.lookUpWitnessTable(C, true);
// If we don't find any witness table for the conformance, bail and return
// false.
if (!WT) {
Mod.createWitnessTableDeclaration(
C, getLinkageForProtocolConformance(
C->getRootNormalConformance(), NotForDefinition));
// Adding the declaration may allow us to now deserialize the body.
// Force the body if we must deserialize this witness table.
if (mustDeserialize) {
WT = Mod.lookUpWitnessTable(C, true);
assert(WT && WT->isDefinition()
&& "unable to deserialize witness table when we must?!");
} else {
return;
}
}
// If the looked up witness table is a declaration, there is nothing we can
// do here. Just bail and return false.
if (WT->isDeclaration())
return;
auto maybeVisitRelatedConformance = [&](ProtocolConformanceRef c) {
// Formally all conformances referenced by a used conformance are used.
// However, eagerly visiting them all at this point leads to a large blowup
// in the amount of SIL we read in. For optimization purposes we can defer
// reading in most conformances until we need them for devirtualization.
// However, we *must* pull in shared clang-importer-derived conformances
// we potentially use, since we may not otherwise have a local definition.
if (mustDeserializeProtocolConformance(Mod, c))
visitProtocolConformance(c, None);
};
// For each entry in the witness table...
for (auto &E : WT->getEntries()) {
switch (E.getKind()) {
// If the entry is a witness method...
case SILWitnessTable::WitnessKind::Method: {
// And we are only interested in deserializing a specific requirement
// and don't have that requirement, don't deserialize this method.
if (Member.hasValue() && E.getMethodWitness().Requirement != *Member)
continue;
// The witness could be removed by dead function elimination.
if (!E.getMethodWitness().Witness)
continue;
// Otherwise, deserialize the witness if it has shared linkage, or if
// we were asked to deserialize everything.
maybeAddFunctionToWorklist(E.getMethodWitness().Witness);
break;
}
// If the entry is a related witness table, see whether we need to
// eagerly deserialize it.
case SILWitnessTable::WitnessKind::BaseProtocol: {
auto baseConformance = E.getBaseProtocolWitness().Witness;
maybeVisitRelatedConformance(ProtocolConformanceRef(baseConformance));
break;
}
case SILWitnessTable::WitnessKind::AssociatedTypeProtocol: {
auto assocConformance = E.getAssociatedTypeProtocolWitness().Witness;
maybeVisitRelatedConformance(assocConformance);
break;
}
case SILWitnessTable::WitnessKind::AssociatedType:
case SILWitnessTable::WitnessKind::Invalid:
break;
}
}
}
void SILLinkerVisitor::visitApplySubstitutions(SubstitutionMap subs) {
for (auto conformance : subs.getConformances()) {
// Formally all conformances referenced in a function application are
// used. However, eagerly visiting them all at this point leads to a
// large blowup in the amount of SIL we read in, and we aren't very
// systematic about laziness. For optimization purposes we can defer
// reading in most conformances until we need them for devirtualization.
// However, we *must* pull in shared clang-importer-derived conformances
// we potentially use, since we may not otherwise have a local definition.
if (mustDeserializeProtocolConformance(Mod, conformance)) {
visitProtocolConformance(conformance, None);
}
}
}
void SILLinkerVisitor::visitInitExistentialAddrInst(
InitExistentialAddrInst *IEI) {
// Link in all protocol conformances that this touches.
//
// TODO: There might be a two step solution where the init_existential_inst
// causes the witness table to be brought in as a declaration and then the
// protocol method inst causes the actual deserialization. For now we are
// not going to be smart about this to enable avoiding any issues with
// visiting the open_existential_addr/witness_method before the
// init_existential_inst.
for (ProtocolConformanceRef C : IEI->getConformances()) {
visitProtocolConformance(C, Optional<SILDeclRef>());
}
}
void SILLinkerVisitor::visitInitExistentialRefInst(
InitExistentialRefInst *IERI) {
// Link in all protocol conformances that this touches.
//
// TODO: There might be a two step solution where the init_existential_inst
// causes the witness table to be brought in as a declaration and then the
// protocol method inst causes the actual deserialization. For now we are
// not going to be smart about this to enable avoiding any issues with
// visiting the protocol_method before the init_existential_inst.
for (ProtocolConformanceRef C : IERI->getConformances()) {
visitProtocolConformance(C, Optional<SILDeclRef>());
}
}
void SILLinkerVisitor::visitAllocRefInst(AllocRefInst *ARI) {
if (!isLinkAll())
return;
// Grab the class decl from the alloc ref inst.
ClassDecl *D = ARI->getType().getClassOrBoundGenericClass();
if (!D)
return;
linkInVTable(D);
}
void SILLinkerVisitor::visitMetatypeInst(MetatypeInst *MI) {
if (!isLinkAll())
return;
CanType instTy = MI->getType().castTo<MetatypeType>().getInstanceType();
ClassDecl *C = instTy.getClassOrBoundGenericClass();
if (!C)
return;
linkInVTable(C);
}
//===----------------------------------------------------------------------===//
// Top Level Routine
//===----------------------------------------------------------------------===//
// Main loop of the visitor. Called by one of the other *visit* methods.
void SILLinkerVisitor::process() {
// Process everything transitively referenced by one of the functions in the
// worklist.
while (!Worklist.empty()) {
auto *Fn = Worklist.pop_back_val();
if (Fn->getModule().isSerialized()) {
// If the containing module has been serialized,
// Remove The Serialized state (if any)
// This allows for more optimizations
Fn->setSerialized(IsSerialized_t::IsNotSerialized);
}
LLVM_DEBUG(llvm::dbgs() << "Process imports in function: "
<< Fn->getName() << "\n");
for (auto &BB : *Fn) {
for (auto &I : BB) {
visit(&I);
}
}
}
}
<|endoftext|> |
<commit_before>#include <jni.h>
#include <android/log.h>
#include <android/bitmap.h>
#include <android/native_window_jni.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>
#include "hello.h"
#include "HalideRuntime.h"
#include "HalideRuntimeOpenCL.h"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,"halide_native",__VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,"halide_native",__VA_ARGS__)
#define DEBUG 1
extern "C" int halide_host_cpu_count();
extern "C" int halide_start_clock(void *user_context);
extern "C" int64_t halide_current_time_ns();
void handler(void */* user_context */, const char *msg) {
LOGE("%s", msg);
}
extern "C" {
JNIEXPORT void JNICALL Java_com_example_hellohalide_CameraPreview_processFrame(
JNIEnv *env, jobject obj, jbyteArray jSrc, jint j_w, jint j_h, jint j_orientation, jobject surf) {
const int w = j_w, h = j_h, orientation = j_orientation;
halide_start_clock(NULL);
halide_set_error_handler(handler);
unsigned char *src = (unsigned char *)env->GetByteArrayElements(jSrc, NULL);
if (!src) {
LOGD("src is null\n");
return;
}
LOGD("[output window size] j_w = %d, j_h = %d", j_w, j_h);
LOGD("[src array length] jSrc.length = %d", env->GetArrayLength(jSrc));
ANativeWindow *win = ANativeWindow_fromSurface(env, surf);
static bool first_call = true;
static unsigned counter = 0;
static unsigned times[16];
if (first_call) {
LOGD("According to Halide, host system has %d cpus\n", halide_host_cpu_count());
LOGD("Resetting buffer format");
ANativeWindow_setBuffersGeometry(win, w, h, 0);
first_call = false;
for (int t = 0; t < 16; t++) times[t] = 0;
}
ANativeWindow_Buffer buf;
ARect rect = {0, 0, w, h};
if (int err = ANativeWindow_lock(win, &buf, NULL)) {
LOGD("ANativeWindow_lock failed with error code %d\n", err);
return;
}
uint8_t *dst = (uint8_t *)buf.bits;
// If we're using opencl, use the gpu backend for it.
#if COMPILING_FOR_OPENCL
halide_opencl_set_device_type("gpu");
#endif
// Make these static so that we can reuse device allocations across frames.
static buffer_t srcBuf = {0};
static buffer_t dstBuf = {0};
if (dst) {
srcBuf.host = (uint8_t *)src;
srcBuf.host_dirty = true;
srcBuf.extent[0] = w;
srcBuf.extent[1] = h;
srcBuf.extent[2] = 0;
srcBuf.extent[3] = 0;
srcBuf.stride[0] = 1;
srcBuf.stride[1] = w;
srcBuf.min[0] = 0;
srcBuf.min[1] = 0;
srcBuf.elem_size = 1;
if (orientation >= 180) {
// Camera sensor is probably upside down (e.g. Nexus 5x)
srcBuf.host += w*h-1;
srcBuf.stride[0] = -1;
srcBuf.stride[1] = -w;
}
dstBuf.host = dst;
dstBuf.extent[0] = w;
dstBuf.extent[1] = h;
dstBuf.extent[2] = 0;
dstBuf.extent[3] = 0;
dstBuf.stride[0] = 1;
dstBuf.stride[1] = w;
dstBuf.min[0] = 0;
dstBuf.min[1] = 0;
dstBuf.elem_size = 1;
// Just set chroma to gray.
memset(dst + w*h, 128, (w*h)/2);
int64_t t1 = halide_current_time_ns();
hello(&srcBuf, &dstBuf);
if (dstBuf.dev) {
halide_copy_to_host(NULL, &dstBuf);
}
int64_t t2 = halide_current_time_ns();
unsigned elapsed_us = (t2 - t1)/1000;
times[counter & 15] = elapsed_us;
counter++;
unsigned min = times[0];
for (int i = 1; i < 16; i++) {
if (times[i] < min) min = times[i];
}
LOGD("Time taken: %d (%d)", elapsed_us, min);
}
ANativeWindow_unlockAndPost(win);
ANativeWindow_release(win);
env->ReleaseByteArrayElements(jSrc, (jbyte *)src, 0);
}
}
<commit_msg>Upgrade HelloAndroid to build with new halide_buffer_t code<commit_after>#include <jni.h>
#include <android/log.h>
#include <android/bitmap.h>
#include <android/native_window_jni.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>
#include "hello.h"
#include "HalideRuntime.h"
#include "HalideRuntimeOpenCL.h"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,"halide_native",__VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,"halide_native",__VA_ARGS__)
#define DEBUG 1
extern "C" int halide_host_cpu_count();
extern "C" int halide_start_clock(void *user_context);
extern "C" int64_t halide_current_time_ns();
void handler(void */* user_context */, const char *msg) {
LOGE("%s", msg);
}
extern "C" {
JNIEXPORT void JNICALL Java_com_example_hellohalide_CameraPreview_processFrame(
JNIEnv *env, jobject obj, jbyteArray jSrc, jint j_w, jint j_h, jint j_orientation, jobject surf) {
const int w = j_w, h = j_h, orientation = j_orientation;
halide_start_clock(NULL);
halide_set_error_handler(handler);
unsigned char *src = (unsigned char *)env->GetByteArrayElements(jSrc, NULL);
if (!src) {
LOGD("src is null\n");
return;
}
LOGD("[output window size] j_w = %d, j_h = %d", j_w, j_h);
LOGD("[src array length] jSrc.length = %d", env->GetArrayLength(jSrc));
ANativeWindow *win = ANativeWindow_fromSurface(env, surf);
static bool first_call = true;
static unsigned counter = 0;
static unsigned times[16];
if (first_call) {
LOGD("According to Halide, host system has %d cpus\n", halide_host_cpu_count());
LOGD("Resetting buffer format");
ANativeWindow_setBuffersGeometry(win, w, h, 0);
first_call = false;
for (int t = 0; t < 16; t++) times[t] = 0;
}
ANativeWindow_Buffer buf;
ARect rect = {0, 0, w, h};
if (int err = ANativeWindow_lock(win, &buf, NULL)) {
LOGD("ANativeWindow_lock failed with error code %d\n", err);
return;
}
uint8_t *dst = (uint8_t *)buf.bits;
// If we're using opencl, use the gpu backend for it.
#if COMPILING_FOR_OPENCL
halide_opencl_set_device_type("gpu");
#endif
// Make these static so that we can reuse device allocations across frames.
static halide_buffer_t srcBuf = {0};
static halide_dimension_t srcDim[2];
static halide_buffer_t dstBuf = {0};
static halide_dimension_t dstDim[2];
if (dst) {
srcBuf.host = (uint8_t *)src;
srcBuf.set_host_dirty();
srcBuf.dim = srcDim;
srcBuf.dim[0].min = 0;
srcBuf.dim[0].extent = w;
srcBuf.dim[0].stride = 1;
srcBuf.dim[1].min = 0;
srcBuf.dim[1].extent = h;
srcBuf.dim[1].stride = w;
srcBuf.type = halide_type_of<uint8_t>();
if (orientation >= 180) {
// Camera sensor is probably upside down (e.g. Nexus 5x)
srcBuf.host += w*h-1;
srcBuf.dim[0].stride = -1;
srcBuf.dim[1].stride = -w;
}
dstBuf.host = dst;
dstBuf.dim = dstDim;
dstBuf.dim[0].min = 0;
dstBuf.dim[0].extent = w;
dstBuf.dim[0].stride = 1;
dstBuf.dim[1].min = 0;
dstBuf.dim[1].extent = h;
dstBuf.dim[1].stride = w;
dstBuf.type = halide_type_of<uint8_t>();
// Just set chroma to gray.
memset(dst + w*h, 128, (w*h)/2);
int64_t t1 = halide_current_time_ns();
hello(&srcBuf, &dstBuf);
halide_copy_to_host(NULL, &dstBuf);
int64_t t2 = halide_current_time_ns();
unsigned elapsed_us = (t2 - t1)/1000;
times[counter & 15] = elapsed_us;
counter++;
unsigned min = times[0];
for (int i = 1; i < 16; i++) {
if (times[i] < min) min = times[i];
}
LOGD("Time taken: %d (%d)", elapsed_us, min);
}
ANativeWindow_unlockAndPost(win);
ANativeWindow_release(win);
env->ReleaseByteArrayElements(jSrc, (jbyte *)src, 0);
}
}
<|endoftext|> |
<commit_before>#include <cstdlib>
#include <cmath>
#include <fstream>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
#include <exception>
#include <sys/time.h>
#include "modules/htmTree.h"
#include "modules/kdTree.h"
#include "misc.h"
#include "feat.h"
#include "structs.h"
#include "collision.h"
#include "global.h"
//reduce redistributes, updates 07/02/15 rnc
int main(int argc, char **argv) {
//// Initializations ---------------------------------------------
srand48(1234); // Make sure we have reproducability
check_args(argc);
Time t, time; // t for global, time for local
init_time(t);
Feat F;
MTL M;
// Read parameters file //
F.readInputFile(argv[1]);
printFile(argv[1]);
// Read Secretfile
// Secret contains the identity of each target: QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF
Gals Secret;
printf("before read secretfile \n");
init_time_at(time,"# read Secret file",t);
Secret=read_Secretfile(F.Secretfile,F);
printf("# Read %d galaxies from %s \n",Secret.size(),F.Secretfile.c_str());
print_time(time,"# ... took :");
std::vector<int> count(10);
count=count_galaxies(Secret);
printf(" Number of galaxies by type, QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF\n");
for(int i=0;i<8;i++){if(count[i]>0)printf (" type %d number %d \n",i, count[i]);}
//read the three input files
init_time_at(time,"# read target, SS, SF files",t);
MTL Targ=read_MTLfile(F.Targfile,F,0,0);
MTL SStars=read_MTLfile(F.SStarsfile,F,1,0);
MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1);
print_time(time,"# ... took :");
//combine the three input files
M=Targ;
printf(" M size %d \n",M.size());
M.insert(M.end(),SStars.begin(),SStars.end());
printf(" M size %d \n",M.size());
M.insert(M.end(),SkyF.begin(),SkyF.end());
printf(" M size %d \n",M.size());
F.Ngal=M.size();
//establish priority classes
init_time_at(time,"# establish priority clasess",t);
assign_priority_class(M);
std::vector <int> count_class(M.priority_list.size(),0);
for(int i;i<M.size();++i){
if(!M[i].SS&&!M[i].SF){
count_class[M[i].priority_class]+=1;
}
}
for(int i;i<M.priority_list.size();++i){
printf(" class %d number %d\n",i,count_class[i]);
}
print_time(time,"# ... took :");
// fiber positioners
PP pp;
pp.read_fiber_positions(F);
F.Nfiber = pp.fp.size()/2;
F.Npetal = max(pp.spectrom)+1;
F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500
pp.get_neighbors(F);
pp.compute_fibsofsp(F);
//P is original list of plates
Plates P = read_plate_centers(F);
F.Nplate=P.size();
printf(" full number of plates %d\n",F.Nplate);
printf("# Read %d plates from %s and %d fibers from %s\n",F.Nplate,F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());
// Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions
F.cb = create_cb(); // cb=central body
F.fh = create_fh(); // fh=fiber holder
//// Collect available galaxies <-> tilefibers --------------------
// HTM Tree of galaxies
const double MinTreeSize = 0.01;
init_time_at(time,"# Start building HTM tree",t);
htmTree<struct target> T(M,MinTreeSize);
print_time(time,"# ... took :");//T.stats();
init_time_at(time,"# collect galaxies at ",t);
// For plates/fibers, collect available galaxies; done in parallel
collect_galaxies_for_all(M,T,P,pp,F);
print_time(time,"# ... took :");//T.stats();
init_time_at(time,"# collect available tile-fibers at",t);
// For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..]
collect_available_tilefibers(M,P,F);
//results_on_inputs("doc/figs/",G,P,F,true);
//// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||
printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber);
Assignment A(M,F);
print_time(t,"# Start assignment at : ");
// Make a plan ----------------------------------------------------
// Plans whole survey without sky fibers, standard stars
// assumes maximum number of observations needed for QSOs, LRGs
simple_assign(M,P,pp,F,A);
//check to see if there are tiles with no galaxies
//need to keep mapping of old tile list to new tile list
//and inverse map
A.inv_order=initList(F.Nplate,-1);
int inv_count=0;
for (int j=0;j<F.Nplate ;++j){
bool not_done=true;
for(int k=0;k<F.Nfiber && not_done;++k){
if(A.TF[j][k]!=-1){
A.suborder.push_back(j);//suborder[jused] is jused-th used plate
not_done=false;
A.inv_order[j]=inv_count;//inv_order[j] is -1 unless used
inv_count++;
//and otherwise the position of plate j in list of used plates
}
}
}
F.NUsedplate=A.suborder.size();
printf(" Plates actually used %d \n",F.NUsedplate);
if(F.diagnose)diagnostic(M,Secret,F,A);
print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs
// Smooth out distribution of free fibers, and increase the number of assignments
for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A,0);// more iterations will improve performance slightly
for (int i=0; i<3; i++) {
improve(M,P,pp,F,A,0);
redistribute_tf(M,P,pp,F,A,0);
}
print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false);
//try assigning SF and SS before real time assignment
for (int jused=0;jused<F.NUsedplate;++jused){
int j=A.suborder[jused];
assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF for each tile
assign_unused(j,M,P,pp,F,A);
}
if(F.diagnose)diagnostic(M,Secret,F,A);
init_time_at(time,"# Begin real time assignment",t);
//Execute plan, updating targets at intervals
for(int i=0;i<F.pass_intervals.size();i++){
printf(" i=%d interval %d \n",i,F.pass_intervals[i]);
std::cout.flush();
}
std::vector <int> update_intervals=F.pass_intervals;
update_intervals.push_back(F.NUsedplate);//to end intervals at last plate
for(int i=0;i<update_intervals.size();++i){
printf("i %d update_interval %d\n",i, update_intervals[i]);
}
for(int i=0;i<update_intervals.size()-1;++i){//go plate by used plate
int starter=update_intervals[i];
printf(" beginning at %d\n",starter);
std::cout.flush();
for (int jused=starter; jused<update_intervals[i+1]; jused++) {
printf(" jused %d\n",jused);
std::cout.flush();
if (0<=jused-F.Analysis) {
update_plan_from_one_obs(jused,Secret,M,P,pp,F,A);
printf(" jused %d\n",jused);
std::cout.flush();
}
else printf("\n no update\n");
// Update corrects all future occurrences of wrong QSOs etc and tries to observe something else
}
redistribute_tf(M,P,pp,F,A,starter);
improve(M,P,pp,F,A,starter);
redistribute_tf(M,P,pp,F,A,starter);
if(F.diagnose)diagnostic(M,Secret,F,A);
}
// check on SS and SF
List SS_hist=initList(11,0);
List SF_hist=initList(41,0);
for(int jused=0;jused<F.NUsedplate;++jused){
int j=A.suborder[jused];
for (int p=0;p<F.Npetal;++p){
int count_SS=0;
int count_SF=0;
for (int k=0;k<F.Nfbp;++k){
int kk=pp.fibers_of_sp[p][k];
int g=A.TF[j][kk];
if(g!=-1 && M[g].SS)count_SS++;
if(g!=-1 && M[g].SF)count_SF++;
}
SS_hist[count_SS]++;
SF_hist[count_SF]++;
}
}
printf(" SS distribution \n");
for(int i=0;i<10;i++)printf("%8d",SS_hist[i]);
printf("\n %8d \n",SS_hist[10]);
printf(" SF distribution \n");
for(int i=0;i<10;i++)printf("%8d",SF_hist[i]);
printf("\n");
for(int i=10;i<20;i++)printf("%8d",SF_hist[i]);
printf("\n");
for(int i=20;i<30;i++)printf("%8d",SF_hist[i]);
printf("\n");
for(int i=30;i<40;i++)printf("%8d",SF_hist[i]);
printf("\n %8d \n",SF_hist[40]);
// Results -------------------------------------------------------
if (F.PrintAscii) for (int jused=0; jused<F.NUsedplate; jused++){
write_FAtile_ascii(A.suborder[jused],F.outDir,M,P,pp,F,A);
}
if (F.PrintFits) for (int jused=0; jused<F.NUsedplate; jused++){
fa_write(A.suborder[jused],F.outDir,M,P,pp,F,A); // Write output
}
display_results("doc/figs/",Secret,M,P,pp,F,A,true);
if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane
print_time(t,"# Finished !... in");
return(0);
}
<commit_msg>diagnostic<commit_after>#include <cstdlib>
#include <cmath>
#include <fstream>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
#include <exception>
#include <sys/time.h>
#include "modules/htmTree.h"
#include "modules/kdTree.h"
#include "misc.h"
#include "feat.h"
#include "structs.h"
#include "collision.h"
#include "global.h"
//reduce redistributes, updates 07/02/15 rnc
int main(int argc, char **argv) {
//// Initializations ---------------------------------------------
srand48(1234); // Make sure we have reproducability
check_args(argc);
Time t, time; // t for global, time for local
init_time(t);
Feat F;
MTL M;
// Read parameters file //
F.readInputFile(argv[1]);
printFile(argv[1]);
// Read Secretfile
// Secret contains the identity of each target: QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF
Gals Secret;
printf("before read secretfile \n");
init_time_at(time,"# read Secret file",t);
Secret=read_Secretfile(F.Secretfile,F);
printf("# Read %d galaxies from %s \n",Secret.size(),F.Secretfile.c_str());
print_time(time,"# ... took :");
std::vector<int> count(10);
count=count_galaxies(Secret);
printf(" Number of galaxies by type, QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF\n");
for(int i=0;i<8;i++){if(count[i]>0)printf (" type %d number %d \n",i, count[i]);}
//read the three input files
init_time_at(time,"# read target, SS, SF files",t);
MTL Targ=read_MTLfile(F.Targfile,F,0,0);
MTL SStars=read_MTLfile(F.SStarsfile,F,1,0);
MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1);
print_time(time,"# ... took :");
//combine the three input files
M=Targ;
printf(" M size %d \n",M.size());
M.insert(M.end(),SStars.begin(),SStars.end());
printf(" M size %d \n",M.size());
M.insert(M.end(),SkyF.begin(),SkyF.end());
printf(" M size %d \n",M.size());
F.Ngal=M.size();
//establish priority classes
init_time_at(time,"# establish priority clasess",t);
assign_priority_class(M);
std::vector <int> count_class(M.priority_list.size(),0);
for(int i;i<M.size();++i){
if(!M[i].SS&&!M[i].SF){
count_class[M[i].priority_class]+=1;
}
}
for(int i;i<M.priority_list.size();++i){
printf(" class %d number %d\n",i,count_class[i]);
}
print_time(time,"# ... took :");
// fiber positioners
PP pp;
pp.read_fiber_positions(F);
F.Nfiber = pp.fp.size()/2;
F.Npetal = max(pp.spectrom)+1;
F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500
pp.get_neighbors(F);
pp.compute_fibsofsp(F);
//P is original list of plates
Plates P = read_plate_centers(F);
F.Nplate=P.size();
printf(" full number of plates %d\n",F.Nplate);
printf("# Read %d plates from %s and %d fibers from %s\n",F.Nplate,F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());
// Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions
F.cb = create_cb(); // cb=central body
F.fh = create_fh(); // fh=fiber holder
//// Collect available galaxies <-> tilefibers --------------------
// HTM Tree of galaxies
const double MinTreeSize = 0.01;
init_time_at(time,"# Start building HTM tree",t);
htmTree<struct target> T(M,MinTreeSize);
print_time(time,"# ... took :");//T.stats();
init_time_at(time,"# collect galaxies at ",t);
// For plates/fibers, collect available galaxies; done in parallel
collect_galaxies_for_all(M,T,P,pp,F);
print_time(time,"# ... took :");//T.stats();
init_time_at(time,"# collect available tile-fibers at",t);
// For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..]
collect_available_tilefibers(M,P,F);
//results_on_inputs("doc/figs/",G,P,F,true);
//// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||
printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber);
Assignment A(M,F);
print_time(t,"# Start assignment at : ");
sstd::cout.flush();
// Make a plan ----------------------------------------------------
// Plans whole survey without sky fibers, standard stars
// assumes maximum number of observations needed for QSOs, LRGs
simple_assign(M,P,pp,F,A);
//check to see if there are tiles with no galaxies
//need to keep mapping of old tile list to new tile list
//and inverse map
A.inv_order=initList(F.Nplate,-1);
int inv_count=0;
for (int j=0;j<F.Nplate ;++j){
bool not_done=true;
for(int k=0;k<F.Nfiber && not_done;++k){
if(A.TF[j][k]!=-1){
A.suborder.push_back(j);//suborder[jused] is jused-th used plate
not_done=false;
A.inv_order[j]=inv_count;//inv_order[j] is -1 unless used
inv_count++;
//and otherwise the position of plate j in list of used plates
}
}
}
F.NUsedplate=A.suborder.size();
printf(" Plates actually used %d \n",F.NUsedplate);
if(F.diagnose)diagnostic(M,Secret,F,A);
print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs
// Smooth out distribution of free fibers, and increase the number of assignments
for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A,0);// more iterations will improve performance slightly
for (int i=0; i<3; i++) {
improve(M,P,pp,F,A,0);
redistribute_tf(M,P,pp,F,A,0);
}
print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false);
//try assigning SF and SS before real time assignment
for (int jused=0;jused<F.NUsedplate;++jused){
int j=A.suborder[jused];
assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF for each tile
assign_unused(j,M,P,pp,F,A);
}
if(F.diagnose)diagnostic(M,Secret,F,A);
init_time_at(time,"# Begin real time assignment",t);
//Execute plan, updating targets at intervals
for(int i=0;i<F.pass_intervals.size();i++){
printf(" i=%d interval %d \n",i,F.pass_intervals[i]);
std::cout.flush();
}
std::vector <int> update_intervals=F.pass_intervals;
update_intervals.push_back(F.NUsedplate);//to end intervals at last plate
for(int i=0;i<update_intervals.size();++i){
printf("i %d update_interval %d\n",i, update_intervals[i]);
}
for(int i=0;i<update_intervals.size()-1;++i){//go plate by used plate
int starter=update_intervals[i];
printf(" beginning at %d\n",starter);
std::cout.flush();
for (int jused=starter; jused<update_intervals[i+1]; jused++) {
printf(" jused %d\n",jused);
std::cout.flush();
if (0<=jused-F.Analysis) {
update_plan_from_one_obs(jused,Secret,M,P,pp,F,A);
printf(" jused %d\n",jused);
std::cout.flush();
}
else printf("\n no update\n");
// Update corrects all future occurrences of wrong QSOs etc and tries to observe something else
}
redistribute_tf(M,P,pp,F,A,starter);
improve(M,P,pp,F,A,starter);
redistribute_tf(M,P,pp,F,A,starter);
if(F.diagnose)diagnostic(M,Secret,F,A);
}
// check on SS and SF
List SS_hist=initList(11,0);
List SF_hist=initList(41,0);
for(int jused=0;jused<F.NUsedplate;++jused){
int j=A.suborder[jused];
for (int p=0;p<F.Npetal;++p){
int count_SS=0;
int count_SF=0;
for (int k=0;k<F.Nfbp;++k){
int kk=pp.fibers_of_sp[p][k];
int g=A.TF[j][kk];
if(g!=-1 && M[g].SS)count_SS++;
if(g!=-1 && M[g].SF)count_SF++;
}
SS_hist[count_SS]++;
SF_hist[count_SF]++;
}
}
printf(" SS distribution \n");
for(int i=0;i<10;i++)printf("%8d",SS_hist[i]);
printf("\n %8d \n",SS_hist[10]);
printf(" SF distribution \n");
for(int i=0;i<10;i++)printf("%8d",SF_hist[i]);
printf("\n");
for(int i=10;i<20;i++)printf("%8d",SF_hist[i]);
printf("\n");
for(int i=20;i<30;i++)printf("%8d",SF_hist[i]);
printf("\n");
for(int i=30;i<40;i++)printf("%8d",SF_hist[i]);
printf("\n %8d \n",SF_hist[40]);
// Results -------------------------------------------------------
if (F.PrintAscii) for (int jused=0; jused<F.NUsedplate; jused++){
write_FAtile_ascii(A.suborder[jused],F.outDir,M,P,pp,F,A);
}
if (F.PrintFits) for (int jused=0; jused<F.NUsedplate; jused++){
fa_write(A.suborder[jused],F.outDir,M,P,pp,F,A); // Write output
}
display_results("doc/figs/",Secret,M,P,pp,F,A,true);
if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane
print_time(t,"# Finished !... in");
return(0);
}
<|endoftext|> |
<commit_before>#include <cstdlib>
#include <cmath>
#include <fstream>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
#include <exception>
#include <sys/time.h>
#include "modules/htmTree.h"
#include "modules/kdTree.h"
#include "misc.h"
#include "feat.h"
#include "structs.h"
#include "collision.h"
#include "global.h"
//reduce redistributes, updates 07/02/15 rnc
int main(int argc, char **argv) {
//// Initializations ---------------------------------------------
srand48(1234); // Make sure we have reproducability
check_args(argc);
Time t, time; // t for global, time for local
init_time(t);
Feat F;
MTL M;
// Read parameters file //
F.readInputFile(argv[1]);
printFile(argv[1]);
// Read Secretfile
// Secret contains the identity of each target: QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF
Gals Secret;
printf("before read secretfile \n");
init_time_at(time,"# read Secret file",t);
Secret=read_Secretfile(F.Secretfile,F);
printf("# Read %d galaxies from %s \n",Secret.size(),F.Secretfile.c_str());
print_time(time,"# ... took :");
std::vector<int> count(10);
count=count_galaxies(Secret);
printf(" Number of galaxies by type, QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF\n");
for(int i=0;i<8;i++){if(count[i]>0)printf (" type %d number %d \n",i, count[i]);}
//read the three input files
init_time_at(time,"# read target, SS, SF files",t);
MTL Targ=read_MTLfile(F.Targfile,F,0,0);
MTL SStars=read_MTLfile(F.SStarsfile,F,1,0);
MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1);
print_time(time,"# ... took :");
//combine the three input files
M=Targ;
printf(" M size %d \n",M.size());
M.insert(M.end(),SStars.begin(),SStars.end());
printf(" M size %d \n",M.size());
M.insert(M.end(),SkyF.begin(),SkyF.end());
printf(" M size %d \n",M.size());
F.Ngal=M.size();
F.Ntarg=Secret.size();
//establish priority classes
init_time_at(time,"# establish priority clasess",t);
assign_priority_class(M);
std::vector <int> count_class(M.priority_list.size(),0);
for(int i;i<M.size();++i){
if(!M[i].SS&&!M[i].SF){
count_class[M[i].priority_class]+=1;
}
}
for(int i;i<M.priority_list.size();++i){
printf(" class %d number %d\n",i,count_class[i]);
}
print_time(time,"# ... took :");
// fiber positioners
PP pp;
pp.read_fiber_positions(F);
F.Nfiber = pp.fp.size()/2;
F.Npetal = max(pp.spectrom)+1;
F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500
pp.get_neighbors(F);
pp.compute_fibsofsp(F);
//P is original list of plates
Plates P = read_plate_centers(F);
F.Nplate=P.size();
printf(" full number of plates %d\n",F.Nplate);
printf("# Read %d plates from %s and %d fibers from %s\n",F.Nplate,F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());
// Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions
F.cb = create_cb(); // cb=central body
F.fh = create_fh(); // fh=fiber holder
//// Collect available galaxies <-> tilefibers --------------------
// HTM Tree of galaxies
const double MinTreeSize = 0.01;
init_time_at(time,"# Start building HTM tree",t);
htmTree<struct target> T(M,MinTreeSize);
print_time(time,"# ... took :");//T.stats();
init_time_at(time,"# collect galaxies at ",t);
// For plates/fibers, collect available galaxies; done in parallel
collect_galaxies_for_all(M,T,P,pp,F);
print_time(time,"# ... took :");//T.stats();
init_time_at(time,"# collect available tile-fibers at",t);
// For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..]
collect_available_tilefibers(M,P,F);
//results_on_inputs("doc/figs/",G,P,F,true);
//// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||
printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber);
Assignment A(M,F);
print_time(t,"# Start assignment at : ");
std::cout.flush();
// Make a plan ----------------------------------------------------
// Plans whole survey without sky fibers, standard stars
// assumes maximum number of observations needed for QSOs, LRGs
simple_assign(M,P,pp,F,A);
//check to see if there are tiles with no galaxies
//need to keep mapping of old tile list to new tile list
//and inverse map
A.inv_order=initList(F.Nplate,-1);
int inv_count=0;
for (int j=0;j<F.Nplate ;++j){
bool not_done=true;
for(int k=0;k<F.Nfiber && not_done;++k){
if(A.TF[j][k]!=-1){
A.suborder.push_back(j);//suborder[jused] is jused-th used plate
not_done=false;
A.inv_order[j]=inv_count;//inv_order[j] is -1 unless used
inv_count++;
//and otherwise the position of plate j in list of used plates
}
}
}
F.NUsedplate=A.suborder.size();
printf(" Plates actually used %d \n",F.NUsedplate);
if(F.diagnose)diagnostic(M,Secret,F,A);
print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs
// Smooth out distribution of free fibers, and increase the number of assignments
for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A,0);// more iterations will improve performance slightly
for (int i=0; i<3; i++) {
improve(M,P,pp,F,A,0);
redistribute_tf(M,P,pp,F,A,0);
}
print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false);
//try assigning SF and SS before real time assignment
for (int jused=0;jused<F.NUsedplate;++jused){
int j=A.suborder[jused];
assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF for each tile
assign_unused(j,M,P,pp,F,A);
}
if(F.diagnose)diagnostic(M,Secret,F,A);
init_time_at(time,"# Begin real time assignment",t);
//Execute plan, updating targets at intervals
for(int i=0;i<F.pass_intervals.size();i++){
printf(" i=%d interval %d \n",i,F.pass_intervals[i]);
std::cout.flush();
}
std::vector <int> update_intervals=F.pass_intervals;
update_intervals.push_back(F.NUsedplate);//to end intervals at last plate
for(int i=0;i<update_intervals.size();++i){
printf("i %d update_interval %d\n",i, update_intervals[i]);
}
for(int i=0;i<update_intervals.size()-1;++i){//go plate by used plate
int starter=update_intervals[i];
//printf(" beginning at %d\n",starter);
//std::cout.flush();
for (int jused=starter; jused<update_intervals[i+1]; jused++) {
//printf(" jused %d\n",jused);
//std::cout.flush();
if (0<=jused-F.Analysis) {
update_plan_from_one_obs(jused,Secret,M,P,pp,F,A);
//printf(" 2 jused %d\n",jused);
//std::cout.flush();
}
else printf("\n no update\n");
// Update corrects all future occurrences of wrong QSOs etc and tries to observe something else
}
redistribute_tf(M,P,pp,F,A,starter);
improve(M,P,pp,F,A,starter);
redistribute_tf(M,P,pp,F,A,starter);
if(F.diagnose)diagnostic(M,Secret,F,A);
}
// check on SS and SF
List SS_hist=initList(11,0);
List SF_hist=initList(41,0);
for(int jused=0;jused<F.NUsedplate;++jused){
int j=A.suborder[jused];
for (int p=0;p<F.Npetal;++p){
int count_SS=0;
int count_SF=0;
for (int k=0;k<F.Nfbp;++k){
int kk=pp.fibers_of_sp[p][k];
int g=A.TF[j][kk];
if(g!=-1 && M[g].SS)count_SS++;
if(g!=-1 && M[g].SF)count_SF++;
}
SS_hist[count_SS]++;
SF_hist[count_SF]++;
}
}
printf(" SS distribution \n");
for(int i=0;i<10;i++)printf("%8d",SS_hist[i]);
printf("\n %8d \n",SS_hist[10]);
printf(" SF distribution \n");
for(int i=0;i<10;i++)printf("%8d",SF_hist[i]);
printf("\n");
for(int i=10;i<20;i++)printf("%8d",SF_hist[i]);
printf("\n");
for(int i=20;i<30;i++)printf("%8d",SF_hist[i]);
printf("\n");
for(int i=30;i<40;i++)printf("%8d",SF_hist[i]);
printf("\n %8d \n",SF_hist[40]);
// Results -------------------------------------------------------
if (F.PrintAscii) for (int jused=0; jused<F.NUsedplate; jused++){
write_FAtile_ascii(A.suborder[jused],F.outDir,M,P,pp,F,A);
}
if (F.PrintFits) for (int jused=0; jused<F.NUsedplate; jused++){
fa_write(A.suborder[jused],F.outDir,M,P,pp,F,A); // Write output
}
display_results("doc/figs/",Secret,M,P,pp,F,A,F.Nplate,true);
if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane
print_time(t,"# Finished !... in");
return(0);
}
<commit_msg>diagnostic in fa<commit_after>#include <cstdlib>
#include <cmath>
#include <fstream>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
#include <exception>
#include <sys/time.h>
#include "modules/htmTree.h"
#include "modules/kdTree.h"
#include "misc.h"
#include "feat.h"
#include "structs.h"
#include "collision.h"
#include "global.h"
//reduce redistributes, updates 07/02/15 rnc
int main(int argc, char **argv) {
//// Initializations ---------------------------------------------
srand48(1234); // Make sure we have reproducability
check_args(argc);
Time t, time; // t for global, time for local
init_time(t);
Feat F;
MTL M;
// Read parameters file //
F.readInputFile(argv[1]);
printFile(argv[1]);
// Read Secretfile
// Secret contains the identity of each target: QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF
Gals Secret;
printf("before read secretfile \n");
init_time_at(time,"# read Secret file",t);
Secret=read_Secretfile(F.Secretfile,F);
printf("# Read %d galaxies from %s \n",Secret.size(),F.Secretfile.c_str());
print_time(time,"# ... took :");
std::vector<int> count(10);
count=count_galaxies(Secret);
printf(" Number of galaxies by type, QSO-Ly-a, QSO-tracers, LRG, ELG, fake QSO, fake LRG, SS, SF\n");
for(int i=0;i<8;i++){if(count[i]>0)printf (" type %d number %d \n",i, count[i]);}
//read the three input files
init_time_at(time,"# read target, SS, SF files",t);
MTL Targ=read_MTLfile(F.Targfile,F,0,0);
MTL SStars=read_MTLfile(F.SStarsfile,F,1,0);
MTL SkyF=read_MTLfile(F.SkyFfile,F,0,1);
print_time(time,"# ... took :");
//combine the three input files
M=Targ;
printf(" M size %d \n",M.size());
M.insert(M.end(),SStars.begin(),SStars.end());
printf(" M size %d \n",M.size());
M.insert(M.end(),SkyF.begin(),SkyF.end());
printf(" M size %d \n",M.size());
F.Ngal=M.size();
F.Ntarg=Secret.size();
//establish priority classes
init_time_at(time,"# establish priority clasess",t);
assign_priority_class(M);
std::vector <int> count_class(M.priority_list.size(),0);
for(int i;i<M.size();++i){
if(!M[i].SS&&!M[i].SF){
count_class[M[i].priority_class]+=1;
}
}
for(int i;i<M.priority_list.size();++i){
printf(" class %d number %d\n",i,count_class[i]);
}
print_time(time,"# ... took :");
// fiber positioners
PP pp;
pp.read_fiber_positions(F);
F.Nfiber = pp.fp.size()/2;
F.Npetal = max(pp.spectrom)+1;
F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500
pp.get_neighbors(F);
pp.compute_fibsofsp(F);
//P is original list of plates
Plates P = read_plate_centers(F);
F.Nplate=P.size();
printf(" full number of plates %d\n",F.Nplate);
printf("# Read %d plates from %s and %d fibers from %s\n",F.Nplate,F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());
// Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions
F.cb = create_cb(); // cb=central body
F.fh = create_fh(); // fh=fiber holder
//// Collect available galaxies <-> tilefibers --------------------
// HTM Tree of galaxies
const double MinTreeSize = 0.01;
init_time_at(time,"# Start building HTM tree",t);
htmTree<struct target> T(M,MinTreeSize);
print_time(time,"# ... took :");//T.stats();
init_time_at(time,"# collect galaxies at ",t);
// For plates/fibers, collect available galaxies; done in parallel
collect_galaxies_for_all(M,T,P,pp,F);
print_time(time,"# ... took :");//T.stats();
init_time_at(time,"# collect available tile-fibers at",t);
// For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..]
collect_available_tilefibers(M,P,F);
//results_on_inputs("doc/figs/",G,P,F,true);
//// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||
printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber);
Assignment A(M,F);
print_time(t,"# Start assignment at : ");
std::cout.flush();
// Make a plan ----------------------------------------------------
// Plans whole survey without sky fibers, standard stars
// assumes maximum number of observations needed for QSOs, LRGs
simple_assign(M,P,pp,F,A);
//check to see if there are tiles with no galaxies
//need to keep mapping of old tile list to new tile list
//and inverse map
A.inv_order=initList(F.Nplate,-1);
int inv_count=0;
for (int j=0;j<F.Nplate ;++j){
bool not_done=true;
for(int k=0;k<F.Nfiber && not_done;++k){
if(A.TF[j][k]!=-1){
A.suborder.push_back(j);//suborder[jused] is jused-th used plate
not_done=false;
A.inv_order[j]=inv_count;//inv_order[j] is -1 unless used
inv_count++;
//and otherwise the position of plate j in list of used plates
}
}
}
F.NUsedplate=A.suborder.size();
printf(" Plates actually used %d \n",F.NUsedplate);
if(F.diagnose)diagnostic(M,Secret,F,A);
print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs
// Smooth out distribution of free fibers, and increase the number of assignments
for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A,0);// more iterations will improve performance slightly
for (int i=0; i<3; i++) {
improve(M,P,pp,F,A,0);
redistribute_tf(M,P,pp,F,A,0);
}
print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false);
//try assigning SF and SS before real time assignment
for (int jused=0;jused<F.NUsedplate;++jused){
int j=A.suborder[jused];
printf("j = %d jused= %d\n",j,jused);
assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF for each tile
assign_unused(j,M,P,pp,F,A);
}
if(F.diagnose)diagnostic(M,Secret,F,A);
init_time_at(time,"# Begin real time assignment",t);
//Execute plan, updating targets at intervals
for(int i=0;i<F.pass_intervals.size();i++){
printf(" i=%d interval %d \n",i,F.pass_intervals[i]);
std::cout.flush();
}
std::vector <int> update_intervals=F.pass_intervals;
update_intervals.push_back(F.NUsedplate);//to end intervals at last plate
for(int i=0;i<update_intervals.size();++i){
printf("i %d update_interval %d\n",i, update_intervals[i]);
}
for(int i=0;i<update_intervals.size()-1;++i){//go plate by used plate
int starter=update_intervals[i];
//printf(" beginning at %d\n",starter);
//std::cout.flush();
for (int jused=starter; jused<update_intervals[i+1]; jused++) {
//printf(" jused %d\n",jused);
//std::cout.flush();
if (0<=jused-F.Analysis) {
update_plan_from_one_obs(jused,Secret,M,P,pp,F,A);
//printf(" 2 jused %d\n",jused);
//std::cout.flush();
}
else printf("\n no update\n");
// Update corrects all future occurrences of wrong QSOs etc and tries to observe something else
}
redistribute_tf(M,P,pp,F,A,starter);
improve(M,P,pp,F,A,starter);
redistribute_tf(M,P,pp,F,A,starter);
if(F.diagnose)diagnostic(M,Secret,F,A);
}
// check on SS and SF
List SS_hist=initList(11,0);
List SF_hist=initList(41,0);
for(int jused=0;jused<F.NUsedplate;++jused){
int j=A.suborder[jused];
for (int p=0;p<F.Npetal;++p){
int count_SS=0;
int count_SF=0;
for (int k=0;k<F.Nfbp;++k){
int kk=pp.fibers_of_sp[p][k];
int g=A.TF[j][kk];
if(g!=-1 && M[g].SS)count_SS++;
if(g!=-1 && M[g].SF)count_SF++;
}
SS_hist[count_SS]++;
SF_hist[count_SF]++;
}
}
printf(" SS distribution \n");
for(int i=0;i<10;i++)printf("%8d",SS_hist[i]);
printf("\n %8d \n",SS_hist[10]);
printf(" SF distribution \n");
for(int i=0;i<10;i++)printf("%8d",SF_hist[i]);
printf("\n");
for(int i=10;i<20;i++)printf("%8d",SF_hist[i]);
printf("\n");
for(int i=20;i<30;i++)printf("%8d",SF_hist[i]);
printf("\n");
for(int i=30;i<40;i++)printf("%8d",SF_hist[i]);
printf("\n %8d \n",SF_hist[40]);
// Results -------------------------------------------------------
if (F.PrintAscii) for (int jused=0; jused<F.NUsedplate; jused++){
write_FAtile_ascii(A.suborder[jused],F.outDir,M,P,pp,F,A);
}
if (F.PrintFits) for (int jused=0; jused<F.NUsedplate; jused++){
fa_write(A.suborder[jused],F.outDir,M,P,pp,F,A); // Write output
}
display_results("doc/figs/",Secret,M,P,pp,F,A,F.Nplate,true);
if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane
print_time(t,"# Finished !... in");
return(0);
}
<|endoftext|> |
<commit_before>#include <map>
#include <iostream>
#include "globals.hh"
#include "normalise.hh"
#include "shared.hh"
typedef ATerm Expr;
typedef map<ATerm, ATerm> NormalForms;
typedef map<FSId, Hash> PkgHashes;
struct EvalState
{
Strings searchDirs;
NormalForms normalForms;
PkgHashes pkgHashes; /* normalised package hashes */
};
static Expr evalFile(EvalState & state, string fileName);
static Expr evalExpr(EvalState & state, Expr e);
static string searchPath(const Strings & searchDirs, string relPath)
{
if (string(relPath, 0, 1) == "/") return relPath;
for (Strings::const_iterator i = searchDirs.begin();
i != searchDirs.end(); i++)
{
string path = *i + "/" + relPath;
if (pathExists(path)) return path;
}
throw Error(
format("path `%1%' not found in any of the search directories")
% relPath);
}
static Expr substExpr(string x, Expr rep, Expr e)
{
char * s;
Expr e2;
if (ATmatch(e, "Var(<str>)", &s))
if (x == s)
return rep;
else
return e;
if (ATmatch(e, "Lam(<str>, <term>)", &s, &e2))
if (x == s)
return e;
/* !!! unfair substitutions */
/* Generically substitute in subterms. */
if (ATgetType(e) == AT_APPL) {
AFun fun = ATgetAFun(e);
int arity = ATgetArity(fun);
ATermList args = ATempty;
for (int i = arity - 1; i >= 0; i--)
args = ATinsert(args, substExpr(x, rep, ATgetArgument(e, i)));
return (ATerm) ATmakeApplList(fun, args);
}
if (ATgetType(e) == AT_LIST) {
ATermList in = (ATermList) e;
ATermList out = ATempty;
while (!ATisEmpty(in)) {
out = ATinsert(out, substExpr(x, rep, ATgetFirst(in)));
in = ATgetNext(in);
}
return (ATerm) ATreverse(out);
}
throw badTerm("do not know how to substitute", e);
}
static Expr substExprMany(ATermList formals, ATermList args, Expr body)
{
char * s;
Expr e;
/* !!! check args against formals */
while (!ATisEmpty(args)) {
ATerm tup = ATgetFirst(args);
if (!ATmatch(tup, "(<str>, <term>)", &s, &e))
throw badTerm("expected an argument tuple", tup);
body = substExpr(s, e, body);
args = ATgetNext(args);
}
return body;
}
Hash hashPackage(EvalState & state, FState fs)
{
if (fs.type == FState::fsDerive) {
for (FSIds::iterator i = fs.derive.inputs.begin();
i != fs.derive.inputs.end(); i++)
{
PkgHashes::iterator j = state.pkgHashes.find(*i);
if (j == state.pkgHashes.end())
throw Error(format("unknown package id %1%") % (string) *i);
*i = j->second;
}
}
return hashTerm(unparseFState(fs));
}
static Expr evalExpr2(EvalState & state, Expr e)
{
char * s1;
Expr e1, e2, e3, e4;
ATermList bnds;
/* Normal forms. */
if (ATmatch(e, "<str>", &s1) ||
ATmatch(e, "[<list>]", &e1) ||
ATmatch(e, "Function([<list>], <term>)", &e1, &e2) ||
ATmatch(e, "FSId(<str>)", &s1))
return e;
try {
Hash pkgHash = hashPackage(state, parseFState(e));
FSId pkgId = writeTerm(e, "");
state.pkgHashes[pkgId] = pkgHash;
return ATmake("FSId(<str>)", ((string) pkgId).c_str());
} catch (...) { /* !!! catch parse errors only */
}
/* Application. */
if (ATmatch(e, "App(<term>, [<list>])", &e1, &e2)) {
e1 = evalExpr(state, e1);
if (!ATmatch(e1, "Function([<list>], <term>)", &e3, &e4))
throw badTerm("expecting a function", e1);
return evalExpr(state,
substExprMany((ATermList) e3, (ATermList) e2, e4));
}
/* Fix inclusion. */
if (ATmatch(e, "IncludeFix(<str>)", &s1)) {
string fileName(s1);
return evalFile(state, s1);
}
/* Relative files. */
if (ATmatch(e, "Relative(<str>)", &s1)) {
string srcPath = searchPath(state.searchDirs, s1);
string dstPath;
FSId id;
addToStore(srcPath, dstPath, id, true);
SliceElem elem;
elem.path = dstPath;
elem.id = id;
FState fs;
fs.type = FState::fsSlice;
fs.slice.roots.push_back(id);
fs.slice.elems.push_back(elem);
Hash pkgHash = hashPackage(state, fs);
FSId pkgId = writeTerm(unparseFState(fs), "");
state.pkgHashes[pkgId] = pkgHash;
msg(lvlChatty, format("copied `%1%' -> %2%")
% srcPath % (string) pkgId);
return ATmake("FSId(<str>)", ((string) pkgId).c_str());
}
/* Packages are transformed into Derive fstate expressions. */
if (ATmatch(e, "Package([<list>])", &bnds)) {
/* Evaluate the bindings and put them in a map. */
map<string, ATerm> bndMap;
bndMap["platform"] = ATmake("<str>", SYSTEM);
while (!ATisEmpty(bnds)) {
ATerm bnd = ATgetFirst(bnds);
if (!ATmatch(bnd, "(<str>, <term>)", &s1, &e1))
throw badTerm("binding expected", bnd);
bndMap[s1] = evalExpr(state, e1);
bnds = ATgetNext(bnds);
}
/* Gather information for building the Derive expression. */
FState fs;
fs.type = FState::fsDerive;
fs.derive.platform = SYSTEM;
string name;
FSId outId;
bool outIdGiven = false;
bnds = ATempty;
for (map<string, ATerm>::iterator it = bndMap.begin();
it != bndMap.end(); it++)
{
string key = it->first;
ATerm value = it->second;
if (ATmatch(value, "FSId(<str>)", &s1)) {
FSId id = parseHash(s1);
Strings paths = fstatePaths(id);
if (paths.size() != 1) abort();
string path = *(paths.begin());
fs.derive.inputs.push_back(id);
fs.derive.env.push_back(StringPair(key, path));
if (key == "build") fs.derive.builder = path;
}
else if (ATmatch(value, "<str>", &s1)) {
if (key == "name") name = s1;
if (key == "id") {
outId = parseHash(s1);
outIdGiven = true;
}
fs.derive.env.push_back(StringPair(key, s1));
}
else throw badTerm("invalid package argument", value);
bnds = ATinsert(bnds,
ATmake("(<str>, <term>)", key.c_str(), value));
}
if (fs.derive.builder == "")
throw badTerm("no builder specified", e);
if (name == "")
throw badTerm("no package name specified", e);
/* Hash the fstate-expression with no outputs to produce a
unique but deterministic path name for this package. */
if (!outIdGiven) outId = hashPackage(state, fs);
string outPath =
canonPath(nixStore + "/" + ((string) outId).c_str() + "-" + name);
fs.derive.env.push_back(StringPair("out", outPath));
fs.derive.outputs.push_back(DeriveOutput(outPath, outId));
/* Write the resulting term into the Nix store directory. */
Hash pkgHash = outIdGiven
? hashString((string) outId + outPath)
: hashPackage(state, fs);
FSId pkgId = writeTerm(unparseFState(fs), "-d-" + name);
state.pkgHashes[pkgId] = pkgHash;
msg(lvlChatty, format("instantiated `%1%' -> %2%")
% name % (string) pkgId);
return ATmake("FSId(<str>)", ((string) pkgId).c_str());
}
/* BaseName primitive function. */
if (ATmatch(e, "BaseName(<term>)", &e1)) {
e1 = evalExpr(state, e1);
if (!ATmatch(e1, "<str>", &s1))
throw badTerm("string expected", e1);
return ATmake("<str>", baseNameOf(s1).c_str());
}
/* Barf. */
throw badTerm("invalid expression", e);
}
static Expr evalExpr(EvalState & state, Expr e)
{
/* Consult the memo table to quickly get the normal form of
previously evaluated expressions. */
NormalForms::iterator i = state.normalForms.find(e);
if (i != state.normalForms.end()) return i->second;
/* Otherwise, evaluate and memoize. */
Expr nf = evalExpr2(state, e);
state.normalForms[e] = nf;
return nf;
}
static Expr evalFile(EvalState & state, string relPath)
{
string path = searchPath(state.searchDirs, relPath);
Nest nest(lvlTalkative, format("evaluating file `%1%'") % path);
Expr e = ATreadFromNamedFile(path.c_str());
if (!e)
throw Error(format("unable to read a term from `%1%'") % path);
return evalExpr(state, e);
}
static void printFSId(EvalState & state, Expr e)
{
ATermList es;
char * s;
if (ATmatch(e, "FSId(<str>)", &s)) {
cout << format("%1%\n") % s;
}
else if (ATmatch(e, "[<list>]", &es)) {
while (!ATisEmpty(es)) {
printFSId(state, evalExpr(state, ATgetFirst(es)));
es = ATgetNext(es);
}
}
else throw badTerm("top level does not evaluate to a (list of) Nix expression(s)", e);
}
void run(Strings args)
{
openDB();
EvalState state;
Strings files;
state.searchDirs.push_back(".");
state.searchDirs.push_back(nixDataDir + "/fix");
for (Strings::iterator it = args.begin();
it != args.end(); )
{
string arg = *it++;
if (arg == "--includedir" || arg == "-I") {
if (it == args.end())
throw UsageError(format("argument required in `%1%'") % arg);
state.searchDirs.push_back(*it++);
}
else if (arg == "--verbose" || arg == "-v")
verbosity = (Verbosity) ((int) verbosity + 1);
else if (arg[0] == '-')
throw UsageError(format("unknown flag `%1%`") % arg);
else
files.push_back(arg);
}
if (files.empty()) throw UsageError("no files specified");
for (Strings::iterator it = files.begin();
it != files.end(); it++)
{
Expr e = evalFile(state, *it);
printFSId(state, e);
}
}
string programId = "fix";
<commit_msg>* Cache result of fstatePaths(). TODO: do this in fstore.cc.<commit_after>#include <map>
#include <iostream>
#include "globals.hh"
#include "normalise.hh"
#include "shared.hh"
typedef ATerm Expr;
typedef map<ATerm, ATerm> NormalForms;
typedef map<FSId, Strings> PkgPaths;
typedef map<FSId, Hash> PkgHashes;
struct EvalState
{
Strings searchDirs;
NormalForms normalForms;
PkgPaths pkgPaths;
PkgHashes pkgHashes; /* normalised package hashes */
};
static Expr evalFile(EvalState & state, string fileName);
static Expr evalExpr(EvalState & state, Expr e);
static string searchPath(const Strings & searchDirs, string relPath)
{
if (string(relPath, 0, 1) == "/") return relPath;
for (Strings::const_iterator i = searchDirs.begin();
i != searchDirs.end(); i++)
{
string path = *i + "/" + relPath;
if (pathExists(path)) return path;
}
throw Error(
format("path `%1%' not found in any of the search directories")
% relPath);
}
static Expr substExpr(string x, Expr rep, Expr e)
{
char * s;
Expr e2;
if (ATmatch(e, "Var(<str>)", &s))
if (x == s)
return rep;
else
return e;
if (ATmatch(e, "Lam(<str>, <term>)", &s, &e2))
if (x == s)
return e;
/* !!! unfair substitutions */
/* Generically substitute in subterms. */
if (ATgetType(e) == AT_APPL) {
AFun fun = ATgetAFun(e);
int arity = ATgetArity(fun);
ATermList args = ATempty;
for (int i = arity - 1; i >= 0; i--)
args = ATinsert(args, substExpr(x, rep, ATgetArgument(e, i)));
return (ATerm) ATmakeApplList(fun, args);
}
if (ATgetType(e) == AT_LIST) {
ATermList in = (ATermList) e;
ATermList out = ATempty;
while (!ATisEmpty(in)) {
out = ATinsert(out, substExpr(x, rep, ATgetFirst(in)));
in = ATgetNext(in);
}
return (ATerm) ATreverse(out);
}
throw badTerm("do not know how to substitute", e);
}
static Expr substExprMany(ATermList formals, ATermList args, Expr body)
{
char * s;
Expr e;
/* !!! check args against formals */
while (!ATisEmpty(args)) {
ATerm tup = ATgetFirst(args);
if (!ATmatch(tup, "(<str>, <term>)", &s, &e))
throw badTerm("expected an argument tuple", tup);
body = substExpr(s, e, body);
args = ATgetNext(args);
}
return body;
}
static Strings fstatePathsCached(EvalState & state, const FSId & id)
{
PkgPaths::iterator i = state.pkgPaths.find(id);
if (i != state.pkgPaths.end())
return i->second;
else {
Strings paths = fstatePaths(id);
state.pkgPaths[id] = paths;
return paths;
}
}
static Hash hashPackage(EvalState & state, FState fs)
{
if (fs.type == FState::fsDerive) {
for (FSIds::iterator i = fs.derive.inputs.begin();
i != fs.derive.inputs.end(); i++)
{
PkgHashes::iterator j = state.pkgHashes.find(*i);
if (j == state.pkgHashes.end())
throw Error(format("unknown package id %1%") % (string) *i);
*i = j->second;
}
}
return hashTerm(unparseFState(fs));
}
static Expr evalExpr2(EvalState & state, Expr e)
{
char * s1;
Expr e1, e2, e3, e4;
ATermList bnds;
/* Normal forms. */
if (ATmatch(e, "<str>", &s1) ||
ATmatch(e, "[<list>]", &e1) ||
ATmatch(e, "Function([<list>], <term>)", &e1, &e2) ||
ATmatch(e, "FSId(<str>)", &s1))
return e;
try {
Hash pkgHash = hashPackage(state, parseFState(e));
FSId pkgId = writeTerm(e, "");
state.pkgHashes[pkgId] = pkgHash;
return ATmake("FSId(<str>)", ((string) pkgId).c_str());
} catch (...) { /* !!! catch parse errors only */
}
/* Application. */
if (ATmatch(e, "App(<term>, [<list>])", &e1, &e2)) {
e1 = evalExpr(state, e1);
if (!ATmatch(e1, "Function([<list>], <term>)", &e3, &e4))
throw badTerm("expecting a function", e1);
return evalExpr(state,
substExprMany((ATermList) e3, (ATermList) e2, e4));
}
/* Fix inclusion. */
if (ATmatch(e, "IncludeFix(<str>)", &s1)) {
string fileName(s1);
return evalFile(state, s1);
}
/* Relative files. */
if (ATmatch(e, "Relative(<str>)", &s1)) {
string srcPath = searchPath(state.searchDirs, s1);
string dstPath;
FSId id;
addToStore(srcPath, dstPath, id, true);
SliceElem elem;
elem.path = dstPath;
elem.id = id;
FState fs;
fs.type = FState::fsSlice;
fs.slice.roots.push_back(id);
fs.slice.elems.push_back(elem);
Hash pkgHash = hashPackage(state, fs);
FSId pkgId = writeTerm(unparseFState(fs), "");
state.pkgHashes[pkgId] = pkgHash;
msg(lvlChatty, format("copied `%1%' -> %2%")
% srcPath % (string) pkgId);
return ATmake("FSId(<str>)", ((string) pkgId).c_str());
}
/* Packages are transformed into Derive fstate expressions. */
if (ATmatch(e, "Package([<list>])", &bnds)) {
/* Evaluate the bindings and put them in a map. */
map<string, ATerm> bndMap;
bndMap["platform"] = ATmake("<str>", SYSTEM);
while (!ATisEmpty(bnds)) {
ATerm bnd = ATgetFirst(bnds);
if (!ATmatch(bnd, "(<str>, <term>)", &s1, &e1))
throw badTerm("binding expected", bnd);
bndMap[s1] = evalExpr(state, e1);
bnds = ATgetNext(bnds);
}
/* Gather information for building the Derive expression. */
FState fs;
fs.type = FState::fsDerive;
fs.derive.platform = SYSTEM;
string name;
FSId outId;
bool outIdGiven = false;
bnds = ATempty;
for (map<string, ATerm>::iterator it = bndMap.begin();
it != bndMap.end(); it++)
{
string key = it->first;
ATerm value = it->second;
if (ATmatch(value, "FSId(<str>)", &s1)) {
FSId id = parseHash(s1);
Strings paths = fstatePathsCached(state, id);
if (paths.size() != 1) abort();
string path = *(paths.begin());
fs.derive.inputs.push_back(id);
fs.derive.env.push_back(StringPair(key, path));
if (key == "build") fs.derive.builder = path;
}
else if (ATmatch(value, "<str>", &s1)) {
if (key == "name") name = s1;
if (key == "id") {
outId = parseHash(s1);
outIdGiven = true;
}
fs.derive.env.push_back(StringPair(key, s1));
}
else throw badTerm("invalid package argument", value);
bnds = ATinsert(bnds,
ATmake("(<str>, <term>)", key.c_str(), value));
}
if (fs.derive.builder == "")
throw badTerm("no builder specified", e);
if (name == "")
throw badTerm("no package name specified", e);
/* Hash the fstate-expression with no outputs to produce a
unique but deterministic path name for this package. */
if (!outIdGiven) outId = hashPackage(state, fs);
string outPath =
canonPath(nixStore + "/" + ((string) outId).c_str() + "-" + name);
fs.derive.env.push_back(StringPair("out", outPath));
fs.derive.outputs.push_back(DeriveOutput(outPath, outId));
/* Write the resulting term into the Nix store directory. */
Hash pkgHash = outIdGiven
? hashString((string) outId + outPath)
: hashPackage(state, fs);
FSId pkgId = writeTerm(unparseFState(fs), "-d-" + name);
state.pkgHashes[pkgId] = pkgHash;
msg(lvlChatty, format("instantiated `%1%' -> %2%")
% name % (string) pkgId);
return ATmake("FSId(<str>)", ((string) pkgId).c_str());
}
/* BaseName primitive function. */
if (ATmatch(e, "BaseName(<term>)", &e1)) {
e1 = evalExpr(state, e1);
if (!ATmatch(e1, "<str>", &s1))
throw badTerm("string expected", e1);
return ATmake("<str>", baseNameOf(s1).c_str());
}
/* Barf. */
throw badTerm("invalid expression", e);
}
static Expr evalExpr(EvalState & state, Expr e)
{
/* Consult the memo table to quickly get the normal form of
previously evaluated expressions. */
NormalForms::iterator i = state.normalForms.find(e);
if (i != state.normalForms.end()) return i->second;
/* Otherwise, evaluate and memoize. */
Expr nf = evalExpr2(state, e);
state.normalForms[e] = nf;
return nf;
}
static Expr evalFile(EvalState & state, string relPath)
{
string path = searchPath(state.searchDirs, relPath);
Nest nest(lvlTalkative, format("evaluating file `%1%'") % path);
Expr e = ATreadFromNamedFile(path.c_str());
if (!e)
throw Error(format("unable to read a term from `%1%'") % path);
return evalExpr(state, e);
}
static void printFSId(EvalState & state, Expr e)
{
ATermList es;
char * s;
if (ATmatch(e, "FSId(<str>)", &s)) {
cout << format("%1%\n") % s;
}
else if (ATmatch(e, "[<list>]", &es)) {
while (!ATisEmpty(es)) {
printFSId(state, evalExpr(state, ATgetFirst(es)));
es = ATgetNext(es);
}
}
else throw badTerm("top level does not evaluate to a (list of) Nix expression(s)", e);
}
void run(Strings args)
{
openDB();
EvalState state;
Strings files;
state.searchDirs.push_back(".");
state.searchDirs.push_back(nixDataDir + "/fix");
for (Strings::iterator it = args.begin();
it != args.end(); )
{
string arg = *it++;
if (arg == "--includedir" || arg == "-I") {
if (it == args.end())
throw UsageError(format("argument required in `%1%'") % arg);
state.searchDirs.push_back(*it++);
}
else if (arg == "--verbose" || arg == "-v")
verbosity = (Verbosity) ((int) verbosity + 1);
else if (arg[0] == '-')
throw UsageError(format("unknown flag `%1%`") % arg);
else
files.push_back(arg);
}
if (files.empty()) throw UsageError("no files specified");
for (Strings::iterator it = files.begin();
it != files.end(); it++)
{
Expr e = evalFile(state, *it);
printFSId(state, e);
}
}
string programId = "fix";
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: propertyinfo.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: vg $ $Date: 2006-03-14 11:30:56 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _EXTENSIONS_PROPCTRLR_PROPERTYINFO_HXX_
#define _EXTENSIONS_PROPCTRLR_PROPERTYINFO_HXX_
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#include <vector>
//............................................................................
namespace pcr
{
//............................................................................
//========================================================================
//= IPropertyInfoService
//========================================================================
class IPropertyInfoService
{
public:
virtual sal_Int32 getPropertyId(const String& _rName) const = 0;
virtual String getPropertyTranslation(sal_Int32 _nId) const = 0;
virtual sal_Int32 getPropertyHelpId(sal_Int32 _nId) const = 0;
virtual sal_Int16 getPropertyPos(sal_Int32 _nId) const = 0;
virtual sal_uInt32 getPropertyUIFlags(sal_Int32 _nId) const = 0;
virtual ::std::vector< ::rtl::OUString > getPropertyEnumRepresentations(sal_Int32 _nId) const = 0;
// this is only temporary, until the UNOization of the property browser is completed
virtual String getPropertyName( sal_Int32 _nPropId ) = 0;
};
//............................................................................
} // namespace pcr
//............................................................................
#endif // _EXTENSIONS_PROPCTRLR_PROPERTYINFO_HXX_
<commit_msg>INTEGRATION: CWS dba204b (1.7.68); FILE MERGED 2006/07/06 14:52:30 fs 1.7.68.1: #i65159# describePropertyLine now returning a LineDescriptor, instead of taking an out parameter / some less warnings<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: propertyinfo.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2006-07-26 08:00:20 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _EXTENSIONS_PROPCTRLR_PROPERTYINFO_HXX_
#define _EXTENSIONS_PROPCTRLR_PROPERTYINFO_HXX_
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#include <vector>
//............................................................................
namespace pcr
{
//............................................................................
//========================================================================
//= IPropertyInfoService
//========================================================================
class SAL_NO_VTABLE IPropertyInfoService
{
public:
virtual sal_Int32 getPropertyId(const String& _rName) const = 0;
virtual String getPropertyTranslation(sal_Int32 _nId) const = 0;
virtual sal_Int32 getPropertyHelpId(sal_Int32 _nId) const = 0;
virtual sal_Int16 getPropertyPos(sal_Int32 _nId) const = 0;
virtual sal_uInt32 getPropertyUIFlags(sal_Int32 _nId) const = 0;
virtual ::std::vector< ::rtl::OUString > getPropertyEnumRepresentations(sal_Int32 _nId) const = 0;
// this is only temporary, until the UNOization of the property browser is completed
virtual String getPropertyName( sal_Int32 _nPropId ) = 0;
virtual ~IPropertyInfoService() { }
};
//............................................................................
} // namespace pcr
//............................................................................
#endif // _EXTENSIONS_PROPCTRLR_PROPERTYINFO_HXX_
<|endoftext|> |
<commit_before>#include <iostream>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <vector>
#include "pin.H"
#include "AnalysisProcessor.h"
#include "IRBuilder.h"
#include "IRBuilderFactory.h"
#include "Inst.h"
#include "PINContextHandler.h"
#include "ProcessingPyConf.h"
#include "Trigger.h"
#include <boost/filesystem.hpp>
using boost::filesystem::absolute;
using boost::filesystem::path;
/* Pin options: -script */
KNOB<std::string> KnobPythonModule(KNOB_MODE_WRITEONCE, "pintool", "script", "", "Python script");
AnalysisProcessor ap;
Trigger analysisTrigger = Trigger();
ProcessingPyConf processingPyConf(&ap, &analysisTrigger);
static void callbackBefore(IRBuilder *irb, CONTEXT *ctx, BOOL hasEA, ADDRINT ea, THREADID threadId)
{
/* Some configurations must be applied before processing */
processingPyConf.applyConfBeforeProcessing(irb);
if (!analysisTrigger.getState())
/* Analysis locked */
return;
if (hasEA)
irb->setup(ea);
/* Update the current context handler */
ap.updateCurrentCtxH(new PINContextHandler(ctx, threadId));
/* Setup Information into Irb */
irb->setThreadID(ap.getThreadID());
/* Python callback before IR processing */
processingPyConf.callbackBeforeIRProc(irb, &ap);
Inst *inst = irb->process(ap);
ap.addInstructionToTrace(inst);
/* Export some information from Irb to Inst */
inst->setOpcode(irb->getOpcode());
inst->setOpcodeCategory(irb->getOpcodeCategory());
inst->setOperands(irb->getOperands());
/* Python callback before instruction processing */
processingPyConf.callbackBefore(inst, &ap);
}
static void callbackAfter(CONTEXT *ctx, THREADID threadId)
{
Inst *inst;
if (!analysisTrigger.getState())
/* Analysis locked */
return;
/* Update the current context handler */
ap.updateCurrentCtxH(new PINContextHandler(ctx, threadId));
/* Get the last instruction */
inst = ap.getLastInstruction();
/* Update statistics */
ap.incNumberOfBranchesTaken(inst->isBranch());
/* Python callback after instruction processing */
processingPyConf.callbackAfter(inst, &ap);
}
static void callbackSnapshot(UINT64 mem, UINT32 writeSize)
{
if (!analysisTrigger.getState())
/* Analysis locked */
return;
/* If the snapshot is not enable we don't save the memory */
if (ap.isSnapshotLocked())
return;
uint32_t i = 0;
for (; i < writeSize ; i++)
ap.addSnapshotModification(mem+i, *(reinterpret_cast<UINT8*>(mem+i)));
}
static void TRACE_Instrumentation(TRACE trace, VOID *programName)
{
boost::filesystem::path pname(reinterpret_cast<char*>(programName));
for (BBL bbl = TRACE_BblHead(trace); BBL_Valid(bbl); bbl = BBL_Next(bbl)){
for (INS ins = BBL_InsHead(bbl); INS_Valid(ins); ins = INS_Next(ins)) {
/* ---- Speed up process ---- */
IMG currentImgName = IMG_FindByAddress(INS_Address(ins));
if (!analysisTrigger.getState() || !IMG_Valid(currentImgName))
break;
boost::filesystem::path pcurrent(IMG_Name(currentImgName));
if (!analysisTrigger.getState() || strcmp(pname.leaf().c_str(), pcurrent.leaf().c_str()))
break;
/* ---- End of speed up process ---- */
IRBuilder *irb = createIRBuilder(ins);
/* Callback before */
if (INS_MemoryOperandCount(ins) > 0)
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR) callbackBefore,
IARG_PTR, irb,
IARG_CONTEXT,
IARG_BOOL, true,
IARG_MEMORYOP_EA, 0,
IARG_THREAD_ID,
IARG_END);
else
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR) callbackBefore,
IARG_PTR, irb,
IARG_CONTEXT,
IARG_BOOL, false,
IARG_ADDRINT, 0,
IARG_THREAD_ID,
IARG_END);
/* Callback after */
/* Syscall after context must be catcher with IDREF.CALLBACK.SYSCALL_EXIT */
if (INS_IsSyscall(ins) == false){
IPOINT where = IPOINT_AFTER;
if (INS_HasFallThrough(ins) == false)
where = IPOINT_TAKEN_BRANCH;
INS_InsertCall(ins, where, (AFUNPTR)callbackAfter, IARG_CONTEXT, IARG_THREAD_ID, IARG_END);
}
/* I/O memory monitoring for snapshot */
if (INS_OperandCount(ins) > 1 && INS_MemoryOperandIsWritten(ins, 0))
INS_InsertCall(
ins, IPOINT_BEFORE, (AFUNPTR)callbackSnapshot,
IARG_MEMORYOP_EA, 0,
IARG_UINT32, INS_MemoryWriteSize(ins),
IARG_END);
}
}
}
static void toggleWrapper(bool flag)
{
analysisTrigger.update(flag);
}
static void callbackRoutineEntry(THREADID threadId, PyObject *callback)
{
if (!analysisTrigger.getState())
/* Analysis locked */
return;
processingPyConf.callbackRoutine(threadId, callback);
}
static void callbackRoutineExit(THREADID threadId, PyObject *callback)
{
if (!analysisTrigger.getState())
/* Analysis locked */
return;
processingPyConf.callbackRoutine(threadId, callback);
}
static void IMG_Instrumentation(IMG img, VOID *)
{
/* Lock / Unlock the Analysis */
if (PyTritonOptions::startAnalysisFromSymbol != nullptr){
RTN targetRTN = RTN_FindByName(img, PyTritonOptions::startAnalysisFromSymbol);
if (RTN_Valid(targetRTN)){
RTN_Open(targetRTN);
RTN_InsertCall(targetRTN,
IPOINT_BEFORE,
(AFUNPTR) toggleWrapper,
IARG_BOOL, true,
IARG_END);
RTN_InsertCall(targetRTN,
IPOINT_AFTER,
(AFUNPTR) toggleWrapper,
IARG_BOOL, false,
IARG_END);
RTN_Close(targetRTN);
}
}
/* Callback on routine entry */
std::map<const char *, PyObject *>::iterator it;
for (it = PyTritonOptions::callbackRoutineEntry.begin(); it != PyTritonOptions::callbackRoutineEntry.end(); it++){
RTN targetRTN = RTN_FindByName(img, it->first);
if (RTN_Valid(targetRTN)){
RTN_Open(targetRTN);
RTN_InsertCall(targetRTN, IPOINT_BEFORE, (AFUNPTR)callbackRoutineEntry, IARG_THREAD_ID, IARG_PTR, it->second, IARG_END);
RTN_Close(targetRTN);
}
}
/* Callback on routine exit */
for (it = PyTritonOptions::callbackRoutineExit.begin(); it != PyTritonOptions::callbackRoutineExit.end(); it++){
RTN targetRTN = RTN_FindByName(img, it->first);
if (RTN_Valid(targetRTN)){
RTN_Open(targetRTN);
RTN_InsertCall(targetRTN, IPOINT_AFTER, (AFUNPTR)callbackRoutineExit, IARG_THREAD_ID, IARG_PTR, it->second, IARG_END);
RTN_Close(targetRTN);
}
}
}
/* Callback at the end of the execution */
static void Fini(INT32, VOID *)
{
/* Python callback at the end of execution */
processingPyConf.callbackFini();
/* End of Python */
Py_Finalize();
}
/* Callback at the syscall entry */
static void callbackSyscallEntry(THREADID threadId, CONTEXT *ctx, SYSCALL_STANDARD std, VOID *v)
{
if (!analysisTrigger.getState())
/* Analysis locked */
return;
/* Update the current context handler */
ap.updateCurrentCtxH(new PINContextHandler(ctx, threadId));
/* Python callback at the end of execution */
processingPyConf.callbackSyscallEntry(threadId, std);
}
/* Callback at the syscall exit */
static void callbackSyscallExit(THREADID threadId, CONTEXT *ctx, SYSCALL_STANDARD std, VOID *v)
{
if (!analysisTrigger.getState())
/* Analysis locked */
return;
/* Update the current context handler */
ap.updateCurrentCtxH(new PINContextHandler(ctx, threadId));
/* Python callback at the end of execution */
processingPyConf.callbackSyscallExit(threadId, std);
}
/*
* Usage function if Pin fail to start.
* Display the help message.
*/
static int32_t Usage()
{
std::cerr << KNOB_BASE::StringKnobSummary() << std::endl;
return -1;
}
/* Get the name of the target binary */
static char *getProgramName(char *argv[])
{
uint64_t offset;
for (offset = 0; argv[offset]; offset++){
if (!strcmp(argv[offset], "--") && argv[offset+1])
return argv[offset+1];
}
return nullptr;
}
int main(int argc, char *argv[])
{
PIN_InitSymbols();
PIN_SetSyntaxIntel();
if(PIN_Init(argc, argv))
return Usage();
/* Init Python Bindings */
initBindings();
/* Image callback */
IMG_AddInstrumentFunction(IMG_Instrumentation, nullptr);
/* Instruction callback */
TRACE_AddInstrumentFunction(TRACE_Instrumentation, getProgramName(argv));
/* End instrumentation callback */
PIN_AddFiniFunction(Fini, nullptr);
/* Syscall entry callback */
PIN_AddSyscallEntryFunction(callbackSyscallEntry, 0);
/* Syscall exit callback */
PIN_AddSyscallExitFunction(callbackSyscallExit, 0);
/* Exec the python bindings file */
if (!execBindings(KnobPythonModule.Value().c_str())) {
std::cerr << "Error: Script file can't be found!" << std::endl;
exit(1);
}
return 0;
}
<commit_msg>Fix speed up<commit_after>#include <iostream>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <vector>
#include "pin.H"
#include "AnalysisProcessor.h"
#include "IRBuilder.h"
#include "IRBuilderFactory.h"
#include "Inst.h"
#include "PINContextHandler.h"
#include "ProcessingPyConf.h"
#include "Trigger.h"
#include <boost/filesystem.hpp>
using boost::filesystem::absolute;
using boost::filesystem::path;
/* Pin options: -script */
KNOB<std::string> KnobPythonModule(KNOB_MODE_WRITEONCE, "pintool", "script", "", "Python script");
AnalysisProcessor ap;
Trigger analysisTrigger = Trigger();
ProcessingPyConf processingPyConf(&ap, &analysisTrigger);
static void callbackBefore(IRBuilder *irb, CONTEXT *ctx, BOOL hasEA, ADDRINT ea, THREADID threadId)
{
/* Some configurations must be applied before processing */
processingPyConf.applyConfBeforeProcessing(irb);
if (!analysisTrigger.getState())
/* Analysis locked */
return;
if (hasEA)
irb->setup(ea);
/* Update the current context handler */
ap.updateCurrentCtxH(new PINContextHandler(ctx, threadId));
/* Setup Information into Irb */
irb->setThreadID(ap.getThreadID());
/* Python callback before IR processing */
processingPyConf.callbackBeforeIRProc(irb, &ap);
Inst *inst = irb->process(ap);
ap.addInstructionToTrace(inst);
/* Export some information from Irb to Inst */
inst->setOpcode(irb->getOpcode());
inst->setOpcodeCategory(irb->getOpcodeCategory());
inst->setOperands(irb->getOperands());
/* Python callback before instruction processing */
processingPyConf.callbackBefore(inst, &ap);
}
static void callbackAfter(CONTEXT *ctx, THREADID threadId)
{
Inst *inst;
if (!analysisTrigger.getState())
/* Analysis locked */
return;
/* Update the current context handler */
ap.updateCurrentCtxH(new PINContextHandler(ctx, threadId));
/* Get the last instruction */
inst = ap.getLastInstruction();
/* Update statistics */
ap.incNumberOfBranchesTaken(inst->isBranch());
/* Python callback after instruction processing */
processingPyConf.callbackAfter(inst, &ap);
}
static void callbackSnapshot(UINT64 mem, UINT32 writeSize)
{
if (!analysisTrigger.getState())
/* Analysis locked */
return;
/* If the snapshot is not enable we don't save the memory */
if (ap.isSnapshotLocked())
return;
uint32_t i = 0;
for (; i < writeSize ; i++)
ap.addSnapshotModification(mem+i, *(reinterpret_cast<UINT8*>(mem+i)));
}
static void TRACE_Instrumentation(TRACE trace, VOID *programName)
{
boost::filesystem::path pname(reinterpret_cast<char*>(programName));
for (BBL bbl = TRACE_BblHead(trace); BBL_Valid(bbl); bbl = BBL_Next(bbl)){
for (INS ins = BBL_InsHead(bbl); INS_Valid(ins); ins = INS_Next(ins)) {
/* ---- Speed up process ---- */
IMG currentImgName = IMG_FindByAddress(INS_Address(ins));
if (!IMG_Valid(currentImgName))
continue;
boost::filesystem::path pcurrent(IMG_Name(currentImgName));
if (!analysisTrigger.getState() && strcmp(pname.leaf().c_str(), pcurrent.leaf().c_str()))
continue;
/* ---- End of speed up process ---- */
IRBuilder *irb = createIRBuilder(ins);
/* Callback before */
if (INS_MemoryOperandCount(ins) > 0)
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR) callbackBefore,
IARG_PTR, irb,
IARG_CONTEXT,
IARG_BOOL, true,
IARG_MEMORYOP_EA, 0,
IARG_THREAD_ID,
IARG_END);
else
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR) callbackBefore,
IARG_PTR, irb,
IARG_CONTEXT,
IARG_BOOL, false,
IARG_ADDRINT, 0,
IARG_THREAD_ID,
IARG_END);
/* Callback after */
/* Syscall after context must be catcher with IDREF.CALLBACK.SYSCALL_EXIT */
if (INS_IsSyscall(ins) == false){
IPOINT where = IPOINT_AFTER;
if (INS_HasFallThrough(ins) == false)
where = IPOINT_TAKEN_BRANCH;
INS_InsertCall(ins, where, (AFUNPTR)callbackAfter, IARG_CONTEXT, IARG_THREAD_ID, IARG_END);
}
/* I/O memory monitoring for snapshot */
if (INS_OperandCount(ins) > 1 && INS_MemoryOperandIsWritten(ins, 0))
INS_InsertCall(
ins, IPOINT_BEFORE, (AFUNPTR)callbackSnapshot,
IARG_MEMORYOP_EA, 0,
IARG_UINT32, INS_MemoryWriteSize(ins),
IARG_END);
}
}
}
static void toggleWrapper(bool flag)
{
analysisTrigger.update(flag);
}
static void callbackRoutineEntry(THREADID threadId, PyObject *callback)
{
if (!analysisTrigger.getState())
/* Analysis locked */
return;
processingPyConf.callbackRoutine(threadId, callback);
}
static void callbackRoutineExit(THREADID threadId, PyObject *callback)
{
if (!analysisTrigger.getState())
/* Analysis locked */
return;
processingPyConf.callbackRoutine(threadId, callback);
}
static void IMG_Instrumentation(IMG img, VOID *)
{
/* Lock / Unlock the Analysis */
if (PyTritonOptions::startAnalysisFromSymbol != nullptr){
RTN targetRTN = RTN_FindByName(img, PyTritonOptions::startAnalysisFromSymbol);
if (RTN_Valid(targetRTN)){
RTN_Open(targetRTN);
RTN_InsertCall(targetRTN,
IPOINT_BEFORE,
(AFUNPTR) toggleWrapper,
IARG_BOOL, true,
IARG_END);
RTN_InsertCall(targetRTN,
IPOINT_AFTER,
(AFUNPTR) toggleWrapper,
IARG_BOOL, false,
IARG_END);
RTN_Close(targetRTN);
}
}
/* Callback on routine entry */
std::map<const char *, PyObject *>::iterator it;
for (it = PyTritonOptions::callbackRoutineEntry.begin(); it != PyTritonOptions::callbackRoutineEntry.end(); it++){
RTN targetRTN = RTN_FindByName(img, it->first);
if (RTN_Valid(targetRTN)){
RTN_Open(targetRTN);
RTN_InsertCall(targetRTN, IPOINT_BEFORE, (AFUNPTR)callbackRoutineEntry, IARG_THREAD_ID, IARG_PTR, it->second, IARG_END);
RTN_Close(targetRTN);
}
}
/* Callback on routine exit */
for (it = PyTritonOptions::callbackRoutineExit.begin(); it != PyTritonOptions::callbackRoutineExit.end(); it++){
RTN targetRTN = RTN_FindByName(img, it->first);
if (RTN_Valid(targetRTN)){
RTN_Open(targetRTN);
RTN_InsertCall(targetRTN, IPOINT_AFTER, (AFUNPTR)callbackRoutineExit, IARG_THREAD_ID, IARG_PTR, it->second, IARG_END);
RTN_Close(targetRTN);
}
}
}
/* Callback at the end of the execution */
static void Fini(INT32, VOID *)
{
/* Python callback at the end of execution */
processingPyConf.callbackFini();
/* End of Python */
Py_Finalize();
}
/* Callback at the syscall entry */
static void callbackSyscallEntry(THREADID threadId, CONTEXT *ctx, SYSCALL_STANDARD std, VOID *v)
{
if (!analysisTrigger.getState())
/* Analysis locked */
return;
/* Update the current context handler */
ap.updateCurrentCtxH(new PINContextHandler(ctx, threadId));
/* Python callback at the end of execution */
processingPyConf.callbackSyscallEntry(threadId, std);
}
/* Callback at the syscall exit */
static void callbackSyscallExit(THREADID threadId, CONTEXT *ctx, SYSCALL_STANDARD std, VOID *v)
{
if (!analysisTrigger.getState())
/* Analysis locked */
return;
/* Update the current context handler */
ap.updateCurrentCtxH(new PINContextHandler(ctx, threadId));
/* Python callback at the end of execution */
processingPyConf.callbackSyscallExit(threadId, std);
}
/*
* Usage function if Pin fail to start.
* Display the help message.
*/
static int32_t Usage()
{
std::cerr << KNOB_BASE::StringKnobSummary() << std::endl;
return -1;
}
/* Get the name of the target binary */
static char *getProgramName(char *argv[])
{
uint64_t offset;
for (offset = 0; argv[offset]; offset++){
if (!strcmp(argv[offset], "--") && argv[offset+1])
return argv[offset+1];
}
return nullptr;
}
int main(int argc, char *argv[])
{
PIN_InitSymbols();
PIN_SetSyntaxIntel();
if(PIN_Init(argc, argv))
return Usage();
/* Init Python Bindings */
initBindings();
/* Image callback */
IMG_AddInstrumentFunction(IMG_Instrumentation, nullptr);
/* Instruction callback */
TRACE_AddInstrumentFunction(TRACE_Instrumentation, getProgramName(argv));
/* End instrumentation callback */
PIN_AddFiniFunction(Fini, nullptr);
/* Syscall entry callback */
PIN_AddSyscallEntryFunction(callbackSyscallEntry, 0);
/* Syscall exit callback */
PIN_AddSyscallExitFunction(callbackSyscallExit, 0);
/* Exec the python bindings file */
if (!execBindings(KnobPythonModule.Value().c_str())) {
std::cerr << "Error: Script file can't be found!" << std::endl;
exit(1);
}
return 0;
}
<|endoftext|> |
<commit_before>
/**
* This file is part of the boostcache package.
*
* (c) Azat Khuzhin <a3at.mail@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#include "commands.h"
#include "util/log.h"
#include <boost/format.hpp>
namespace PlaceHolders = std::placeholders;
Commands::Callback Commands::find(const std::string& commandName)
{
HashTable::const_iterator command = m_commands.find(commandName);
if (command == m_commands.end()) {
return std::bind(&Commands::notImplementedYetCallback,
this, PlaceHolders::_1);
}
return command->second;
}
Commands::Commands()
{
Callback defaultCallback = std::bind(&Commands::notImplementedYetCallback,
this, PlaceHolders::_1);
// Service commands
m_commands["STATUS"] = defaultCallback;
m_commands["SHUTDOWN"] = defaultCallback;
// "db" operations
m_commands["GET"] = defaultCallback;
m_commands["SET"] = defaultCallback;
m_commands["DEL"] = defaultCallback;
m_commands["INC"] = defaultCallback;
m_commands["DEC"] = defaultCallback;
m_commands["CAS"] = defaultCallback;
}
std::string Commands::notImplementedYetCallback(const Command::Arguments& arguments)
{
return str(boost::format("-ERR %s is not implemented\n") % arguments[0]);
}<commit_msg>[kernel] drop extra header from Commands (logger).<commit_after>
/**
* This file is part of the boostcache package.
*
* (c) Azat Khuzhin <a3at.mail@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#include "commands.h"
#include <boost/format.hpp>
namespace PlaceHolders = std::placeholders;
Commands::Callback Commands::find(const std::string& commandName)
{
HashTable::const_iterator command = m_commands.find(commandName);
if (command == m_commands.end()) {
return std::bind(&Commands::notImplementedYetCallback,
this, PlaceHolders::_1);
}
return command->second;
}
Commands::Commands()
{
Callback defaultCallback = std::bind(&Commands::notImplementedYetCallback,
this, PlaceHolders::_1);
// Service commands
m_commands["STATUS"] = defaultCallback;
m_commands["SHUTDOWN"] = defaultCallback;
// "db" operations
m_commands["GET"] = defaultCallback;
m_commands["SET"] = defaultCallback;
m_commands["DEL"] = defaultCallback;
m_commands["INC"] = defaultCallback;
m_commands["DEC"] = defaultCallback;
m_commands["CAS"] = defaultCallback;
}
std::string Commands::notImplementedYetCallback(const Command::Arguments& arguments)
{
return str(boost::format("-ERR %s is not implemented\n") % arguments[0]);
}<|endoftext|> |
<commit_before><commit_msg>Minor improvement to Vulkan robustness.<commit_after><|endoftext|> |
<commit_before>#include <stdio.h>
#include <string.h>
#include <iostream>
#include <signal.h>
#include "ArgParser.h"
#include "TcpSocket.h"
#include "TcpClient.h"
#include "Thread.h"
#include "Queue.h"
#include "ChatMsg.h"
#include "ChatMsgPacket.h"
#include "UpdateRequestPacket.h"
#include "UpdateResponsePacket.h"
bool g_bStopCommanded = false;
Queue<ChatMsg> g_ChatMstQ;
std::string g_sHostName;
int g_nPort = 5000;
int g_nUserId = 0;
void sighandler(int s)
{
g_bStopCommanded = true;
}
void printChatMsg(const ChatMsg &msg);
void rxThread(ThreadArg* pArg);
void inputThread(ThreadArg* pArg);
int main(int argc, char *argv[])
{
ArgParser args;
Thread* m_pRxThread = NULL;
Thread* m_pInputThread = NULL;
printf("Chat Client:\n\n");
args.addArg("name: HostName, primary: h, alt: host, type: opt, \
vtype: string, required, desc: Host name/address");
args.addArg("name: Port, primary: p, alt: port, type: opt, \
vtype: int, required, desc: Set port number");
args.addArg("name: UID, primary: u, alt: uid, type: opt, \
vtype: int, required, desc: User ID");
if (!args.parse((const char**)argv, argc))
{
args.printArgErrors(true);
return 1;
}
args.getArgVal(g_sHostName, Argument::ArgName, "HostName");
args.getArgVal(g_nPort, Argument::ArgName, "Port");
args.getArgVal(g_nUserId, Argument::ArgName, "UID");
g_ChatMstQ.initialize(20);
m_pRxThread = Thread::Create(rxThread, NULL);
if (m_pRxThread == NULL)
{
printf("Failed to start RX thread.\n");
return 1;
}
m_pInputThread = Thread::Create(inputThread, NULL);
if (m_pInputThread == NULL)
{
printf("Failed to start input thread.\n");
return 1;
}
while (!g_bStopCommanded)
{
sleep(1);
}
if (m_pRxThread)
{
m_pRxThread->stop();
m_pRxThread->join();
}
return 0;
}
void printChatMsg(const ChatMsg &msg)
{
char msgStr[170];
ui32 l_nMsgLen = 0;
ui32 l_nUserId = 0;
msg.getMsg(msgStr, l_nMsgLen);
l_nUserId = msg.getUserId();
printf("%d: %s\n", l_nUserId, msgStr);
}
//------------------------------------------------------------------------------
void rxThread(ThreadArg* pArg)
{
TcpSocket* l_pSocket = NULL;
ChatPacketHdr header;
ui32 l_nDataLen = 0;
ui32 l_nCurrentTs = 0;
ui32 l_nBytesRecvd = 0;
ChatMsg msg;
std::vector<ChatMsg*> msgVecRx;
std::vector<ChatMsg*>::iterator msgVecRxIt;
UpdateRequestPacket* l_pUpdateReq = NULL;
char* l_pPkt = NULL;
ChatPacket* l_pChatPkt = NULL;
// Connect to server
l_pSocket = TcpClient::Connect(g_sHostName.c_str(), g_nPort, 2000);
if (l_pSocket == NULL)
{
printf("Failed to connect to server\n");
while (!pArg->stopSignalled()) sleep(1);
}
while (!pArg->stopSignalled())
{
l_pPkt = NULL;
l_pChatPkt = NULL;
l_pUpdateReq = new UpdateRequestPacket(g_nUserId, l_nCurrentTs);
if (l_pUpdateReq)
{
char* l_pPackedUpdateReq = NULL;
ui32 l_nPackedUpdateReqLen = 0;
l_pUpdateReq->pack((void**)&l_pPackedUpdateReq,
l_nPackedUpdateReqLen);
l_pSocket->send(l_pPackedUpdateReq, l_nPackedUpdateReqLen);
delete[] l_pPackedUpdateReq;
l_pPackedUpdateReq = NULL;
}
l_nBytesRecvd = l_pSocket->recv((char*)&header,
sizeof(ChatPacketHdr),
1000);
if (header.marker != ChatPacketHdr::marker)
{
continue;
}
l_nDataLen = header.length;
l_pPkt = new char[sizeof(ChatPacketHdr) + l_nDataLen];
if (!l_pPkt) continue;
memcpy(l_pPkt, &header, sizeof(ChatPacketHdr));
l_nBytesRecvd = l_pSocket->recv(l_pPkt + sizeof(ChatPacketHdr),
l_nDataLen, 1000);
if ((l_nBytesRecvd == l_nDataLen) &&
(header.type == ChatPacket::UpdateResponseType))
{
printf("Got update response\n");
UpdateResponsePacket* l_pRespPkt = new UpdateResponsePacket();
l_pRespPkt->unpack(l_pPkt, sizeof(ChatPacketHdr) + l_nDataLen);
l_pRespPkt->getMsgList(msgVecRx);
l_pRespPkt->getTs(l_nCurrentTs);
msgVecRxIt = msgVecRx.begin();
for (; msgVecRxIt < msgVecRx.end(); ++msgVecRxIt)
{
printChatMsg(*(*msgVecRxIt));
}
}
if (l_pPkt)
{
delete l_pPkt;
}
// Check for a new msg in the tx queue
if (g_ChatMstQ.pop(msg, 0))
{
ChatMsgPacket* pMsgPacket = NULL;
char* pMsgData = NULL;
ui32 msgLen = 0;
pMsgPacket = new ChatMsgPacket(msg);
pMsgPacket->pack((void**)&pMsgData, msgLen);
l_pSocket->send(pMsgData, msgLen);
delete[] pMsgData;
pMsgData = NULL;
}
}
l_pSocket->closeSocket();
}
//------------------------------------------------------------------------------
void inputThread(ThreadArg* pArg)
{
std::string msgString;
ChatMsg msg;
while (!pArg->stopSignalled())
{
std::cin >> msgString;
msg.setUserId(g_nUserId);
msg.setMsg(msgString.c_str(), msgString.length());
}
}
<commit_msg>Refactored chat client. turns out it was causing the weird message problems<commit_after>#include <stdio.h>
#include <string.h>
#include <iostream>
#include <signal.h>
#include "ArgParser.h"
#include "TcpSocket.h"
#include "TcpClient.h"
#include "Thread.h"
#include "Queue.h"
#include "ChatMsg.h"
#include "ChatMsgPacket.h"
#include "UpdateRequestPacket.h"
#include "UpdateResponsePacket.h"
bool g_bStopCommanded = false;
Queue<ChatMsg> g_ChatMstQ;
std::string g_sHostName;
int g_nPort = 5000;
int g_nUserId = 0;
void sighandler(int s)
{
g_bStopCommanded = true;
}
void printChatMsg(const ChatMsg &msg);
void rxThread(ThreadArg* pArg);
void inputThread(ThreadArg* pArg);
bool receiveRespUpdate(UpdateResponsePacket** pResp, TcpSocket* pSocket);
int main(int argc, char *argv[])
{
ArgParser args;
Thread* m_pRxThread = NULL;
Thread* m_pInputThread = NULL;
printf("Chat Client:\n\n");
args.addArg("name: HostName, primary: h, alt: host, type: opt, \
vtype: string, required, desc: Host name/address");
args.addArg("name: Port, primary: p, alt: port, type: opt, \
vtype: int, required, desc: Set port number");
args.addArg("name: UID, primary: u, alt: uid, type: opt, \
vtype: int, required, desc: User ID");
if (!args.parse((const char**)argv, argc))
{
args.printArgErrors(true);
return 1;
}
args.getArgVal(g_sHostName, Argument::ArgName, "HostName");
args.getArgVal(g_nPort, Argument::ArgName, "Port");
args.getArgVal(g_nUserId, Argument::ArgName, "UID");
g_ChatMstQ.initialize(20);
m_pRxThread = Thread::Create(rxThread, NULL);
if (m_pRxThread == NULL)
{
printf("Failed to start RX thread.\n");
return 1;
}
m_pInputThread = Thread::Create(inputThread, NULL);
if (m_pInputThread == NULL)
{
printf("Failed to start input thread.\n");
return 1;
}
while (!g_bStopCommanded)
{
sleep(1);
}
if (m_pRxThread)
{
m_pRxThread->stop();
m_pRxThread->join();
}
return 0;
}
void printChatMsg(const ChatMsg &msg)
{
char msgStr[170];
ui32 l_nMsgLen = 0;
ui32 l_nUserId = 0;
msg.getMsg(msgStr, l_nMsgLen);
l_nUserId = msg.getUserId();
printf("%d, %d: %s\n", l_nUserId, msg.getTs(), msgStr);
}
//------------------------------------------------------------------------------
void rxThread(ThreadArg* pArg)
{
TcpSocket* l_pSocket = NULL;
ui32 l_nCurrentTs = 0;
ChatMsg msg;
std::vector<ChatMsg*> msgVecRx;
std::vector<ChatMsg*>::iterator msgVecRxIt;
UpdateRequestPacket* l_pUpdateReq = NULL;
UpdateResponsePacket* l_pUpdResp = NULL;
ChatPacket* l_pChatPkt = NULL;
// Connect to server
l_pSocket = TcpClient::Connect(g_sHostName.c_str(), g_nPort, 2000);
if (l_pSocket == NULL)
{
printf("Failed to connect to server\n");
while (!pArg->stopSignalled()) sleep(1);
}
while (!pArg->stopSignalled())
{
l_pChatPkt = NULL;
// Check for a new msg in the tx queue
if (g_ChatMstQ.pop(msg, 1000))
{
ChatMsgPacket* pMsgPacket = NULL;
char* pMsgData = NULL;
ui32 msgLen = 0;
pMsgPacket = new ChatMsgPacket(msg);
pMsgPacket->pack((void**)&pMsgData, msgLen);
l_pSocket->send(pMsgData, msgLen);
// printf("rxThread: sent %u bytes\n", msgLen);
delete[] pMsgData;
pMsgData = NULL;
receiveRespUpdate(&l_pUpdResp, l_pSocket);
if (l_pUpdResp)
{
ui32 l_nNewTs = 0;
l_pUpdResp->getMsgList(msgVecRx);
l_pUpdResp->getTs(l_nNewTs);
if (l_nNewTs > l_nCurrentTs)
{
l_nCurrentTs = l_nNewTs;
msgVecRxIt = msgVecRx.begin();
for (; msgVecRxIt < msgVecRx.end(); ++msgVecRxIt)
{
printChatMsg(*(*msgVecRxIt));
}
// Done't need to store the messages.
msgVecRx.clear();
}
delete l_pUpdResp;
l_pUpdResp = NULL;
}
}
// Request that the server send all chat messages after the specified
// logical timestamp.
l_pUpdateReq = new UpdateRequestPacket(g_nUserId, l_nCurrentTs);
if (l_pUpdateReq)
{
char* l_pPackedUpdateReq = NULL;
ui32 l_nPackedUpdateReqLen = 0;
// printf("currentTs = %d\n", l_nCurrentTs);
l_pUpdateReq->pack((void**)&l_pPackedUpdateReq,
l_nPackedUpdateReqLen);
l_pSocket->send(l_pPackedUpdateReq, l_nPackedUpdateReqLen);
delete[] l_pPackedUpdateReq;
l_pPackedUpdateReq = NULL;
receiveRespUpdate(&l_pUpdResp, l_pSocket);
if (l_pUpdResp)
{
ui32 l_nNewTs = 0;
l_pUpdResp->getMsgList(msgVecRx);
l_pUpdResp->getTs(l_nNewTs);
if (l_nNewTs > l_nCurrentTs)
{
l_nCurrentTs = l_nNewTs;
msgVecRxIt = msgVecRx.begin();
for (; msgVecRxIt < msgVecRx.end(); ++msgVecRxIt)
{
printChatMsg(*(*msgVecRxIt));
}
// Done't need to store the messages.
msgVecRx.clear();
}
delete l_pUpdResp;
l_pUpdResp = NULL;
}
}
}
l_pSocket->closeSocket();
}
//------------------------------------------------------------------------------
void inputThread(ThreadArg* pArg)
{
std::string msgString;
ChatMsg msg;
while (!pArg->stopSignalled())
{
//std::cin >> msgString;
msgString = "";
std::getline(std::cin, msgString);
msg.reset();
msg.setUserId(g_nUserId);
msg.setMsg(msgString.c_str(), msgString.length());
g_ChatMstQ.push(msg, 0);
}
}
//------------------------------------------------------------------------------
bool receiveRespUpdate(UpdateResponsePacket** pResp, TcpSocket* pSocket)
{
ChatPacketHdr header;
bool l_bSuccess = false;
ui32 l_nBytesRecvd = 0;
char* l_pPkt = NULL;
ui32 l_nDataLen = 0;
// Attempt to receive a chat packet header
l_nBytesRecvd = pSocket->recv((char*)&header,
sizeof(ChatPacketHdr),
1000);
if (header.marker != ChatPacketHdr::marker) return false;
// Determine how much data is included in the packet.
l_nDataLen = header.length;
l_pPkt = new char[sizeof(ChatPacketHdr) + l_nDataLen];
if (!l_pPkt) return false;
// Copy the previously read header into the allocated packet.
memcpy(l_pPkt, &header, sizeof(ChatPacketHdr));
// Receive the rest of the packet directly into the allocated buffer.
l_nBytesRecvd = pSocket->recv(l_pPkt + sizeof(ChatPacketHdr),
l_nDataLen, 1000);
if ((l_nBytesRecvd == l_nDataLen) &&
(header.type == ChatPacket::UpdateResponseType))
{
*pResp = new UpdateResponsePacket();
(*pResp)->unpack(l_pPkt, sizeof(ChatPacketHdr) + l_nDataLen);
l_bSuccess = true;
}
if (l_pPkt)
{
delete l_pPkt;
}
return l_bSuccess;
}
<|endoftext|> |
<commit_before>#include <cassert>
#include <exception>
#include <map>
#include "CardinalDirection.h"
#include "CardinalDirectionName.h"
// Wikipedia says the intermediate directions don't have a space, so that's the
// convention I'll use here.
const std::map<CardinalDirectionName, std::string> CardinalDirectionDisplayNames =
{
{ CardinalDirectionName::North, "North" },
{ CardinalDirectionName::NorthEast, "Northeast" },
{ CardinalDirectionName::East, "East" },
{ CardinalDirectionName::SouthEast, "Southeast" },
{ CardinalDirectionName::South, "South" },
{ CardinalDirectionName::SouthWest, "Southwest" },
{ CardinalDirectionName::West, "West" },
{ CardinalDirectionName::NorthWest, "Northwest" }
};
const Double2 CardinalDirection::North = Double2(1.0, 0.0);
const Double2 CardinalDirection::South = Double2(-1.0, 0.0);
const Double2 CardinalDirection::East = Double2(0.0, 1.0);
const Double2 CardinalDirection::West = Double2(0.0, -1.0);
CardinalDirectionName CardinalDirection::getDirectionName(const Double2 &direction)
{
// The caller should normalize their vector. A "direction" is implied to be normalized.
assert(direction.isNormalized());
const Double2 northEast = CardinalDirection::North.slerp(CardinalDirection::East, 0.5);
const Double2 southEast = CardinalDirection::South.slerp(CardinalDirection::East, 0.5);
const Double2 southWest = CardinalDirection::South.slerp(CardinalDirection::West, 0.5);
const Double2 northWest = CardinalDirection::North.slerp(CardinalDirection::West, 0.5);
// The spherical interpolations should already be normalized if their parent vectors
// are normalized.
assert(northEast.isNormalized());
assert(southEast.isNormalized());
assert(southWest.isNormalized());
assert(northWest.isNormalized());
// Each direction gets an eighth of the circle's area. In dot product terms,
// that's an allowance of 0.25 deviation from the direction.
const double deviation = 0.25;
auto isCloseEnoughTo = [deviation, &direction](const Double2 &cardinalDirection)
{
return direction.dot(cardinalDirection) >= (1.0 - deviation);
};
// Find the cardinal direction closest to the given direction. Start with
// a default name and figure out the true one from there.
auto name = CardinalDirectionName::North;
if (isCloseEnoughTo(CardinalDirection::North))
{
name = CardinalDirectionName::North;
}
else if (isCloseEnoughTo(northEast))
{
name = CardinalDirectionName::NorthEast;
}
else if (isCloseEnoughTo(CardinalDirection::East))
{
name = CardinalDirectionName::East;
}
else if (isCloseEnoughTo(southEast))
{
name = CardinalDirectionName::SouthEast;
}
else if (isCloseEnoughTo(CardinalDirection::South))
{
name = CardinalDirectionName::South;
}
else if (isCloseEnoughTo(southWest))
{
name = CardinalDirectionName::SouthWest;
}
else if (isCloseEnoughTo(CardinalDirection::West))
{
name = CardinalDirectionName::West;
}
else if (isCloseEnoughTo(northWest))
{
name = CardinalDirectionName::NorthWest;
}
else
{
throw std::runtime_error("Invalid direction for CardinalDirection.");
}
return name;
}
const std::string &CardinalDirection::toString(CardinalDirectionName directionName)
{
const std::string &displayName = CardinalDirectionDisplayNames.at(directionName);
return displayName;
}
<commit_msg>Revised cardinal direction calculation.<commit_after>#include <cassert>
#include <exception>
#include <map>
#include "CardinalDirection.h"
#include "CardinalDirectionName.h"
// Wikipedia says the intermediate directions don't have a space, so that's the
// convention I'll use here.
const std::map<CardinalDirectionName, std::string> CardinalDirectionDisplayNames =
{
{ CardinalDirectionName::North, "North" },
{ CardinalDirectionName::NorthEast, "Northeast" },
{ CardinalDirectionName::East, "East" },
{ CardinalDirectionName::SouthEast, "Southeast" },
{ CardinalDirectionName::South, "South" },
{ CardinalDirectionName::SouthWest, "Southwest" },
{ CardinalDirectionName::West, "West" },
{ CardinalDirectionName::NorthWest, "Northwest" }
};
const Double2 CardinalDirection::North = Double2(1.0, 0.0);
const Double2 CardinalDirection::South = Double2(-1.0, 0.0);
const Double2 CardinalDirection::East = Double2(0.0, 1.0);
const Double2 CardinalDirection::West = Double2(0.0, -1.0);
CardinalDirectionName CardinalDirection::getDirectionName(const Double2 &direction)
{
// The caller should normalize their vector. A "direction" is implied to be normalized.
assert(direction.isNormalized());
const Double2 northEast = CardinalDirection::North.slerp(CardinalDirection::East, 0.5);
const Double2 southEast = CardinalDirection::South.slerp(CardinalDirection::East, 0.5);
const Double2 southWest = CardinalDirection::South.slerp(CardinalDirection::West, 0.5);
const Double2 northWest = CardinalDirection::North.slerp(CardinalDirection::West, 0.5);
// The spherical interpolations should already be normalized if their parent vectors
// are normalized.
assert(northEast.isNormalized());
assert(southEast.isNormalized());
assert(southWest.isNormalized());
assert(northWest.isNormalized());
// Each direction gets an equal slice of the circle's area.
// (I'm not sure why the deviation is 1/12th; at a glance it should be 1/8th).
const double deviation = 1.0 / 12.0;
auto isCloseEnoughTo = [deviation, &direction](const Double2 &cardinalDirection)
{
return direction.dot(cardinalDirection) >= (1.0 - deviation);
};
// Find the cardinal direction closest to the given direction. Start with
// a default name and figure out the true one from there.
auto name = CardinalDirectionName::North;
if (isCloseEnoughTo(CardinalDirection::North))
{
name = CardinalDirectionName::North;
}
else if (isCloseEnoughTo(northEast))
{
name = CardinalDirectionName::NorthEast;
}
else if (isCloseEnoughTo(CardinalDirection::East))
{
name = CardinalDirectionName::East;
}
else if (isCloseEnoughTo(southEast))
{
name = CardinalDirectionName::SouthEast;
}
else if (isCloseEnoughTo(CardinalDirection::South))
{
name = CardinalDirectionName::South;
}
else if (isCloseEnoughTo(southWest))
{
name = CardinalDirectionName::SouthWest;
}
else if (isCloseEnoughTo(CardinalDirection::West))
{
name = CardinalDirectionName::West;
}
else if (isCloseEnoughTo(northWest))
{
name = CardinalDirectionName::NorthWest;
}
else
{
throw std::runtime_error("Invalid direction for CardinalDirection.");
}
return name;
}
const std::string &CardinalDirection::toString(CardinalDirectionName directionName)
{
const std::string &displayName = CardinalDirectionDisplayNames.at(directionName);
return displayName;
}
<|endoftext|> |
<commit_before>#include "callbackHandler.h"
#include <maya/MMessage.h>
#include <maya/MUuid.h>
#include <maya/MFnDependencyNode.h>
#include <maya/MTimerMessage.h>
#include <maya/MDagMessage.h>
#include <maya/MDGMessage.h>
#include "hackprint.h"
#include "mayaUtils.h"
#include <ctime>
#include <string>
///////////////////////////// callbacks
void nodeChangeCallback(MNodeMessage::AttributeMessage msg, MPlug & plug, MPlug & otherPlug, void*)
{
if (msg & MNodeMessage::kAttributeSet ||
msg & MNodeMessage::kAttributeRemoved ||
msg & MNodeMessage::kAttributeRenamed ||
msg & MNodeMessage::kAttributeAdded ||
msg & MNodeMessage::kAttributeArrayAdded ||
msg & MNodeMessage::kAttributeArrayRemoved)
{
// not bothered about cache inputs
if (plug.partialName() == "cin") return;
std::string test = plug.info().asChar();
MFnDependencyNode node(plug.node());
std::string uuid = node.uuid().asString().asChar();
CallbackHandler::getInstance().addNodeToEditList(uuid, std::time(nullptr));
}
}
void preRemoveCallback(MObject& node, void*)
{
MFnDependencyNode depNode(node);
std::string uuid = depNode.uuid().asString().asChar();
CallbackHandler::getInstance().addNodeToDeleteList(uuid, std::time(nullptr));
}
void newNodeCallback(MObject &node, void *clientData)
{
MFnDependencyNode depNode(node);
if (MayaUtils::isValidNodeType(depNode.typeName()))
{
std::string uuid = depNode.uuid().asString().asChar();
CallbackHandler::getInstance().addNodeToAddedList(uuid, std::time(nullptr));
}
}
void timerCallback(float elapsedTime, float lastTime, void *clientData)
{
MGlobal::executeCommandOnIdle("SendUpdates");
}
//////////////////////////class methods
CallbackHandler::CallbackHandler()
:
timerCallbackEnabled(false),
newNodeCallbackEnabled(false)
{
}
CallbackHandler::~CallbackHandler()
{
MMessage::removeCallbacks(callbackIds);
}
MStatus CallbackHandler::clearCallbacks()
{
MStatus status = MMessage::removeCallbacks(callbackIds);
callbackIds.clear();
timerCallbackEnabled = false;
newNodeCallbackEnabled = false;
return status;
}
MStatus CallbackHandler::registerCallbacksToNode(MObject& _node)
{
MStatus status;
// wipe the callbacks off a node if its already has them
status = cleanNodeOfCallbacks(_node);
MCallbackId id = MNodeMessage::addAttributeChangedCallback(_node,
nodeChangeCallback,
NULL,
&status);
if (status == MStatus::kSuccess)
{
callbackIds.append(id);
}
id = MNodeMessage::addNodePreRemovalCallback(_node,
preRemoveCallback,
NULL,
&status);
if (status == MStatus::kSuccess)
{
callbackIds.append(id);
}
// TODO Name Change
// TODO added nodes
// TODO attribute added or removed
return status;
}
MStatus CallbackHandler::registerCallbacksToDetectNewNodes()
{
if (newNodeCallbackEnabled) return MStatus::kSuccess;
MStatus status;
MCallbackId id = MDGMessage::addNodeAddedCallback(newNodeCallback,
"dependNode",
NULL,
&status);
if (status == MStatus::kSuccess)
{
callbackIds.append(id);
newNodeCallbackEnabled = true;
}
return status;
}
MStatus CallbackHandler::startTimerCallback()
{
if (timerCallbackEnabled) return MStatus::kSuccess;
MStatus status;
MCallbackId id = MTimerMessage::addTimerCallback(2.0f,
timerCallback,
NULL,
&status);
if (status == MStatus::kSuccess)
{
callbackIds.append(id);
timerCallbackEnabled = true;
}
return status;
}
MStatus CallbackHandler::cleanNodeOfCallbacks(MObject& _node)
{
MCallbackIdArray nodeCallbacks;
MStatus status = MMessage::nodeCallbacks(_node, nodeCallbacks);
// remove the callbacks
for (unsigned int i = 0; i < nodeCallbacks.length(); i++)
{
// remove the callback in general
status = MMessage::removeCallback(nodeCallbacks[i]);
// remove the id from our list
for (unsigned int j = 0; i < callbackIds.length(); i++)
{
if (nodeCallbacks[i] == callbackIds[i])
{
callbackIds.remove(j);
break;
}
}
}
return status;
}
// deletes
std::unordered_map<std::string, std::time_t> CallbackHandler::getDeletedList()
{
return delList;
}
void CallbackHandler::addNodeToDeleteList(std::string uuid, time_t time)
{
delList[uuid] = time;
}
void CallbackHandler::resetDeleteList()
{
delList.clear();
}
// adds
std::unordered_map<std::string, std::time_t> CallbackHandler::getAddedList()
{
return addList;
}
void CallbackHandler::addNodeToAddedList(std::string uuid, time_t time)
{
addList[uuid] = time;
}
void CallbackHandler::resetAddedList()
{
addList.clear();
}
// edits
std::unordered_map<std::string, std::time_t> CallbackHandler::getEditsList()
{
return editList;
}
void CallbackHandler::addNodeToEditList(std::string uuid, time_t time)
{
editList[uuid] = time;
}
void CallbackHandler::resetEditList()
{
editList.clear();
}
std::string CallbackHandler::getCurrentRegisteredMesh()
{
return currentMeshID;
}
void CallbackHandler::setCurrentRegisteredMesh(std::string meshID)
{
currentMeshID = meshID;
}<commit_msg>added some more callbacks<commit_after>#include "callbackHandler.h"
#include <maya/MMessage.h>
#include <maya/MUuid.h>
#include <maya/MFnDependencyNode.h>
#include <maya/MTimerMessage.h>
#include <maya/MDagMessage.h>
#include <maya/MDGMessage.h>
#include "hackprint.h"
#include "mayaUtils.h"
#include <ctime>
#include <string>
///////////////////////////// callbacks
void nodeChangeCallback(MNodeMessage::AttributeMessage msg, MPlug & plug, MPlug & otherPlug, void*)
{
if (msg & MNodeMessage::kAttributeSet ||
msg & MNodeMessage::kAttributeRemoved ||
msg & MNodeMessage::kAttributeRenamed ||
msg & MNodeMessage::kAttributeAdded ||
msg & MNodeMessage::kAttributeArrayAdded ||
msg & MNodeMessage::kAttributeArrayRemoved)
{
// not bothered about cache inputs
if (plug.partialName() == "cin") return;
std::string test = plug.info().asChar();
MFnDependencyNode node(plug.node());
std::string uuid = node.uuid().asString().asChar();
CallbackHandler::getInstance().addNodeToEditList(uuid, std::time(nullptr));
}
}
void preRemoveCallback(MObject& node, void*)
{
MFnDependencyNode depNode(node);
std::string uuid = depNode.uuid().asString().asChar();
CallbackHandler::getInstance().addNodeToDeleteList(uuid, std::time(nullptr));
}
void uuidChangeCallback(MObject &node, const MUuid &uuid, void *clientData)
{
// TODO
// find a nice way of handling uuid changes
//MFnDependencyNode depNode(node);
//std::string uuid = depNode.uuid().asString().asChar();
//CallbackHandler::getInstance().addNodeToDeleteList(uuid, std::time(nullptr));
}
void nodeNameChangeCallback(MObject &node, const MString &str, void *clientData)
{
MFnDependencyNode depNode(node);
std::string uuid = depNode.uuid().asString().asChar();
CallbackHandler::getInstance().addNodeToDeleteList(uuid, std::time(nullptr));
}
void nodeAttribAddCallback(MNodeMessage::AttributeMessage msg, MPlug &plug, void *clientData)
{
if (msg & MNodeMessage::kAttributeSet ||
msg & MNodeMessage::kAttributeRemoved ||
msg & MNodeMessage::kAttributeRenamed ||
msg & MNodeMessage::kAttributeAdded ||
msg & MNodeMessage::kAttributeArrayAdded ||
msg & MNodeMessage::kAttributeArrayRemoved)
{
// not bothered about cache inputs
if (plug.partialName() == "cin") return;
std::string test = plug.info().asChar();
MFnDependencyNode node(plug.node());
std::string uuid = node.uuid().asString().asChar();
CallbackHandler::getInstance().addNodeToEditList(uuid, std::time(nullptr));
}
}
void newNodeCallback(MObject &node, void *clientData)
{
MFnDependencyNode depNode(node);
if (MayaUtils::isValidNodeType(depNode.typeName()))
{
std::string uuid = depNode.uuid().asString().asChar();
CallbackHandler::getInstance().addNodeToAddedList(uuid, std::time(nullptr));
}
}
void timerCallback(float elapsedTime, float lastTime, void *clientData)
{
MGlobal::executeCommandOnIdle("SendUpdates");
}
//////////////////////////class methods
CallbackHandler::CallbackHandler()
:
timerCallbackEnabled(false),
newNodeCallbackEnabled(false)
{
}
CallbackHandler::~CallbackHandler()
{
MMessage::removeCallbacks(callbackIds);
}
MStatus CallbackHandler::clearCallbacks()
{
MStatus status = MMessage::removeCallbacks(callbackIds);
callbackIds.clear();
timerCallbackEnabled = false;
newNodeCallbackEnabled = false;
return status;
}
MStatus CallbackHandler::registerCallbacksToNode(MObject& _node)
{
MStatus status;
// wipe the callbacks off a node if its already has them
status = cleanNodeOfCallbacks(_node);
MCallbackId id = MNodeMessage::addAttributeChangedCallback(_node,
nodeChangeCallback,
NULL,
&status);
if (status == MStatus::kSuccess)
{
callbackIds.append(id);
}
id = MNodeMessage::addNodePreRemovalCallback(_node,
preRemoveCallback,
NULL,
&status);
if (status == MStatus::kSuccess)
{
callbackIds.append(id);
}
id = MNodeMessage::addUuidChangedCallback( _node,
uuidChangeCallback,
NULL,
&status);
if (status == MStatus::kSuccess)
{
callbackIds.append(id);
}
id = MNodeMessage::addNameChangedCallback( _node,
nodeNameChangeCallback,
NULL,
&status);
if (status == MStatus::kSuccess)
{
callbackIds.append(id);
}
id = MNodeMessage::addAttributeAddedOrRemovedCallback( _node,
nodeAttribAddCallback,
NULL,
&status);
if (status == MStatus::kSuccess)
{
callbackIds.append(id);
}
return status;
}
MStatus CallbackHandler::registerCallbacksToDetectNewNodes()
{
if (newNodeCallbackEnabled) return MStatus::kSuccess;
MStatus status;
MCallbackId id = MDGMessage::addNodeAddedCallback(newNodeCallback,
"dependNode",
NULL,
&status);
if (status == MStatus::kSuccess)
{
callbackIds.append(id);
newNodeCallbackEnabled = true;
}
return status;
}
MStatus CallbackHandler::startTimerCallback()
{
if (timerCallbackEnabled) return MStatus::kSuccess;
MStatus status;
MCallbackId id = MTimerMessage::addTimerCallback(2.0f,
timerCallback,
NULL,
&status);
if (status == MStatus::kSuccess)
{
callbackIds.append(id);
timerCallbackEnabled = true;
}
return status;
}
MStatus CallbackHandler::cleanNodeOfCallbacks(MObject& _node)
{
MCallbackIdArray nodeCallbacks;
MStatus status = MMessage::nodeCallbacks(_node, nodeCallbacks);
// remove the callbacks
for (unsigned int i = 0; i < nodeCallbacks.length(); i++)
{
// remove the callback in general
status = MMessage::removeCallback(nodeCallbacks[i]);
// remove the id from our list
for (unsigned int j = 0; i < callbackIds.length(); i++)
{
if (nodeCallbacks[i] == callbackIds[i])
{
callbackIds.remove(j);
break;
}
}
}
return status;
}
// deletes
std::unordered_map<std::string, std::time_t> CallbackHandler::getDeletedList()
{
return delList;
}
void CallbackHandler::addNodeToDeleteList(std::string uuid, time_t time)
{
delList[uuid] = time;
}
void CallbackHandler::resetDeleteList()
{
delList.clear();
}
// adds
std::unordered_map<std::string, std::time_t> CallbackHandler::getAddedList()
{
return addList;
}
void CallbackHandler::addNodeToAddedList(std::string uuid, time_t time)
{
addList[uuid] = time;
}
void CallbackHandler::resetAddedList()
{
addList.clear();
}
// edits
std::unordered_map<std::string, std::time_t> CallbackHandler::getEditsList()
{
return editList;
}
void CallbackHandler::addNodeToEditList(std::string uuid, time_t time)
{
editList[uuid] = time;
}
void CallbackHandler::resetEditList()
{
editList.clear();
}
std::string CallbackHandler::getCurrentRegisteredMesh()
{
return currentMeshID;
}
void CallbackHandler::setCurrentRegisteredMesh(std::string meshID)
{
currentMeshID = meshID;
}<|endoftext|> |
<commit_before>#include <GLFW/glfw3.h>
#include <cstring>
#include <stdlib.h> // srand, rand
#include <thread> // std::this_thread::sleep_for
#include <chrono> // std::chrono::seconds
#include "shape.h"
using namespace std;
void icon::draw()
{
drawIcon(x0, y0, r, t, 1, 0, 0, 0, 0, 1, xpos, ypos);
}
void icon2::draw()
{
drawIcon2(x0, y0, x1, y1, t, 0, 0, 1, 1, 0, 0, xpos, ypos);
}
void line :: draw()
{
drawLine(x0, y0, x1, y1, t, 0, 0, 0);
}
void rect :: draw()
{
drawRect(x0, y0, x1, y1, t, 0, 0, 0);
}
void f_rect:: draw()
{
drawRectF(x0, y0, x1, y1, 0, 0, 0);
}
void circle::draw()
{
drawCirc(x0, y0, r, t, 0, 0, 0);
}
void arrow_up::draw()
{
drawLine(x0, y0 - 30, x0, y0 + 30, 0, 0, 0, 0);
drawLine(x0 - 20, y0 + 10, x0, y0 + 30, 0, 0, 0, 0);
drawLine(x0, y0 + 30, x0 + 20, y0 + 10, 0, 0, 0, 0);
}
void arrow_down::draw()
{
drawLine(x0, y0 - 30, x0, y0 + 30, 0, 0, 0, 0);
drawLine(x0 - 20, y0 - 10, x0, y0 - 30, 0, 0, 0, 0);
drawLine(x0, y0 - 30, x0 + 20, y0 - 10, 0, 0, 0, 0);
}
void arrow_left::draw()
{
drawLine(x0 - 30, y0, x0 + 30, y0, 0, 0, 0, 0);
drawLine(x0 - 30, y0, x0 - 10, y0 - 20, 0, 0, 0, 0);
drawLine(x0 - 30, y0, x0 - 10, y0 + 20, 0, 0, 0, 0);
}
void arrow_right::draw()
{
drawLine(x0 - 30, y0, x0 + 30, y0, 0, 0, 0, 0);
drawLine(x0 + 10, y0 - 20, x0 + 30, y0, 0, 0, 0, 0);
drawLine(x0 + 10, y0 + 20, x0 + 30, y0, 0, 0, 0, 0);
}
void draw_X::draw()
{
drawLine(x0 - 30, y0 - 30, x0 + 30, y0 + 30, 0, 0, 0, 0);
drawLine(x0 - 30, y0 + 30, x0 + 30, y0 - 30, 0, 0, 0, 0);
}
void draw_A::draw()
{
drawLine(x0 - 30, y0 - 30, x0, y0 + 30, 0, 0, 0, 0);
drawLine(x0, y0 + 30, x0 + 30, y0 - 30, 0, 0, 0, 0);
drawLine(x0 - 15, y0, x0 + 15, y0, 0, 0, 0, 0);
}<commit_msg>Delete shape_1008.cpp<commit_after><|endoftext|> |
<commit_before>// Implementation file for String functions, include this file in string.h
// DO NOT INCLUDE/COMPILE THIS FILE SEPARATELY.
#ifdef CODE_STRING_H
/*******************************
* 1. Constructors and operator =
*******************************/
// empty constructor.
String::String() {
_len = 0;
_data = 0;
}
// copy contructors : assignment is copy
String::String(const String& s) {
_len = s.length();
_data = 0;
_data = new char[_len];
if( !_data ) forcequit("string|heap exhausted");
for(int i=0; i<_len; i++)
_data[i] = s.charAt(i);
}
String::String(const char *s) {
_len = strlen(s);
_data = 0;
_data = new char[ _len ];
if( !_data ) forcequit("string|heap exhausted");
for( __SIZETYPE i=0; i<_len; i++)
_data[i] = s[i];
}
String::String(char ch) {
_len = 1;
_data = 0;
_data = new char[1];
if( !_data ) forcequit("string|heap exhausted");
_data[0] = ch;
}
// operator =
String& String::operator= (const String& s) {
_len = s.length();
delete[] _data;
_data = 0;
_data = new char[_len];
if( !_data ) forcequit("string|heap exhausted");
for(int i=0; i<_len; i++)
_data[i] = s.charAt(i);
return *this;
}
String& String::operator= (const char* s ) {
_len = strlen(s);
delete[] _data;
_data = 0;
_data = new char[_len];
if( !_data ) forcequit("string|heap exhausted");
for(int i=0; i<_len; i++)
_data[i] = s[i];
return *this;
}
String& String::operator=(char ch ) {
_len = 1;
delete[] _data;
_data = 0;
_data = new char[1];
if( !_data ) forcequit("string|heap exhausted");
_data[0] = ch;
return *this;
}
// Destructor : free some space
String::~String() {
clear();
}
// clears all data.
bool String::clear() {
_len = 0;
delete[] _data;
_data = 0;
return 1;
}
// Typecast to string constant : char *
String::operator char* () {
char ret[_len+1];
for(__SIZETYPE i=0; i<_len; i++) ret[i] = _data[i];
ret[_len] = '\0';
return ret;
}
/**************************
* 2. Read properties/data of a given string
**************************/
//size() : returns the size of the string
__SIZETYPE String::length() const {
return _len;
}
// return the character at an index
char String::charAt(__SIZETYPE index) const {
if( index < 0 ) index += _len;
if( index > _len ) return 0;
return _data[index];
}
// operator [] : gives reference to char at index .
char String::zerochar = 0; // returned on erraneous requests(out of bounds)
char& String::operator[] (__SIZETYPE index ) const {
if( index < 0 ) index += _len;
if( index > _len ){
zerochar = 0;
return zerochar;
}
return _data[index];
}
/*******************************
* 3. Manipulations
********************************/
// Operator +
String String::operator+ (const String& r ) const {
int tlen = r.length();
char tmp[ _len+ tlen +1];
for(__SIZETYPE i=0;i<_len;i++)
tmp[i] = _data[i];
for(__SIZETYPE i=0;i<tlen;i++)
tmp[i+_len] = r[i];
tmp[_len+ tlen]= '\0';
String c(tmp);
return c;
}
// shorthand operator +=
String String::operator+= (const String& s) {
return ( *this = *this + s );
}
// substring : returns the substring from index st , and length len.
String String::substr(__SIZETYPE st, __SIZETYPE len) const {
if( st < 0 ) st += _len;
String ret;
if( st < 0 || st+len > _len ) return ""; // return null string, as bounds are erred
char s[ len+1 ];
for( __SIZETYPE i=0 ; i<len ; ++i ){
s[i] = _data[ st+i ];
}
s[len] = '\0';
ret = s;
return ret;
}
// replace : replaces all occurences of <find> with <rep>
String String::replace(const String& find, const String& rep) const {
String tmp , ch(*this);
__SIZETYPE repPos = ch.indexOf(find),
flen = find.length(),
rlen = rep.length();
while( repPos >= 0 ){
tmp += ch.substr(0,repPos) + rep;
ch = ch.substr(repPos+flen);
repPos = ch.indexOf(find);
}
tmp += ch;
return tmp;
}
// tolower : converts all alphabet values to lower case.
String String::tolower() const {
String ret(*this );
for( __SIZETYPE i=0; i<ret.length(); i++)
if( ret[i] >= 'A' && ret[i] <= 'Z' )
ret[i] = ret[i] - 'A' + 'a';
return ret;
}
// toupper : converts all alphabet values to upper case.
String String::toupper() const {
String ret( *this );
for( __SIZETYPE i=0; i<ret.length(); i++)
if( ret[i] >= 'a' && ret[i] <= 'z' )
ret[i] = ret[i] - 'a' + 'A';
return ret;
}
// trim : removes all preceding and trailing spaces
String String::trim() const {
__SIZETYPE st,en;
for( st = 0; _data[st] == ' ' && st < _len; st++);
if( st == _len ) return String("");
for( en = _len-1; _data[en] == ' ' && en >= 0; en--);
return this->substr( st, en-st+1 );
}
// indexOf : gives index of first occurrance of s
__SIZETYPE String::indexOf(const String& s ) const {
__SIZETYPE tlen = s.length();
bool isfound ;
for( __SIZETYPE i = 0; i < _len-tlen ; ++i ){
isfound = true;
for( __SIZETYPE j = 0; j < tlen ; ++j ){
if( s[j] != _data[i+j] ){
isfound = false;
break;
}
}
if( isfound ) return i;
}
return -1;
}
// numOccurences : gives the number of times s appears in the given string ( without overlaps )
__SIZETYPE String::countOccurences(const String& find ) const {
__SIZETYPE tot = 0;
int flen = find.length();
for( int i = 0; i<_len-flen ; i++ ){
bool match = false;
for( int j = 0; j<flen ; j++ )
if( _data[i+j] != find[j] ){
match = false;
break;
}
if( match ){
tot++;
i += flen-1;
}
}
return tot;
}
/***********************************
* 4. Relational Operators
************************************/
// operator ! : returns true if string is empty
bool String::operator!() const {
return !_len;
}
// operator == : returns true if both strings are equal( each char matches )
bool String::operator==(const String& s ) const {
if( _len != s.length() ) return false;
for( __SIZETYPE it = 0; it < _len ; it++ )
if( _data[it] != s[it] )
return false;
return true;
}
// operator != : returns true if both strings are not equal
bool String::operator!=(const String& s ) const {
return !( *this == s );
}
/************************************
* 5. Stream IO operators : >> <<
************************************/
ostream& operator<<(ostream& output, String& str) {
str.print( output );
return output;
}
bool String::print(ostream& output) const {
for( __SIZETYPE i=0;i<_len;++i)
output<<_data[i];
}
// this is the global input buffer for all strings.
char *String::stringInputBuffer = new char[ MAX_STRING_LENGTH ];
bool String::get(istream& input, char delim ) {
input.getline( String::stringInputBuffer, MAX_STRING_LENGTH, delim );
*this = String::stringInputBuffer;
return true;
}
istream& operator>>(istream& input, String& str) {
str.get(input, ' ');
return input;
}
#endif /* CODE_STRING_H */
<commit_msg>some style changes<commit_after>// Implementation file for String functions, include this file in string.h
// DO NOT INCLUDE/COMPILE THIS FILE SEPARATELY.
#ifdef CODE_STRING_H
/*******************************
* 1. Constructors and operator =
*******************************/
// empty constructor.
String::String() {
_len = 0;
_data = 0;
}
// copy contructors : assignment is copy
String::String(const String& s) {
_len = s.length();
_data = 0;
_data = new char[_len];
if( !_data ) forcequit("string|heap exhausted");
for(int i=0; i<_len; i++)
_data[i] = s.charAt(i);
}
String::String(const char *s) {
_len = strlen(s);
_data = 0;
_data = new char[ _len ];
if( !_data ) forcequit("string|heap exhausted");
for( __SIZETYPE i=0; i<_len; i++)
_data[i] = s[i];
}
String::String(char ch) {
_len = 1;
_data = 0;
_data = new char[1];
if( !_data ) forcequit("string|heap exhausted");
_data[0] = ch;
}
// operator =
String& String::operator= (const String& s) {
_len = s.length();
delete[] _data;
_data = 0;
_data = new char[_len];
if( !_data ) forcequit("string|heap exhausted");
for(int i=0; i<_len; i++)
_data[i] = s.charAt(i);
return *this;
}
String& String::operator= (const char* s ) {
_len = strlen(s);
delete[] _data;
_data = 0;
_data = new char[_len];
if( !_data ) forcequit("string|heap exhausted");
for(int i=0; i<_len; i++)
_data[i] = s[i];
return *this;
}
String& String::operator=(char ch ) {
_len = 1;
delete[] _data;
_data = 0;
_data = new char[1];
if( !_data ) forcequit("string|heap exhausted");
_data[0] = ch;
return *this;
}
// Destructor : free some space
String::~String() {
clear();
}
// clears all data.
bool String::clear() {
_len = 0;
delete[] _data;
_data = 0;
return 1;
}
// Typecast to string constant : char *
String::operator char* () {
char ret[_len+1];
for(__SIZETYPE i=0; i<_len; i++) ret[i] = _data[i];
ret[_len] = '\0';
return ret;
}
/**************************
* 2. Read properties/data of a given string
**************************/
//size() : returns the size of the string
__SIZETYPE String::length() const {
return _len;
}
// return the character at an index
char String::charAt(__SIZETYPE index) const {
if( index < 0 ) index += _len;
if( index > _len ) return 0;
return _data[index];
}
// operator [] : gives reference to char at index .
char String::zerochar = 0; // returned on erraneous requests(out of bounds)
char& String::operator[] (__SIZETYPE index ) const {
if( index < 0 ) index += _len;
if( index > _len ){
zerochar = 0;
return zerochar;
}
return _data[index];
}
/*******************************
* 3. Manipulations
********************************/
// Operator +
String String::operator+ (const String& r ) const {
int tlen = r.length();
char tmp[ _len+ tlen +1];
for(__SIZETYPE i=0;i<_len;i++)
tmp[i] = _data[i];
for(__SIZETYPE i=0;i<tlen;i++)
tmp[i+_len] = r[i];
tmp[_len+ tlen]= '\0';
String c(tmp);
return c;
}
// shorthand operator +=
String String::operator+= (const String& s) {
return ( *this = *this + s );
}
// substring : returns the substring from index st , and length len.
String String::substr(__SIZETYPE st, __SIZETYPE len) const {
if( st < 0 ) st += _len;
String ret;
if( st < 0 || st+len > _len ) return ""; // return null string, as bounds are erred
char s[ len+1 ];
for( __SIZETYPE i=0 ; i<len ; ++i ){
s[i] = _data[ st+i ];
}
s[len] = '\0';
ret = s;
return ret;
}
// replace : replaces all occurences of <find> with <rep>
String String::replace(const String& find, const String& rep) const {
String tmp , ch(*this);
__SIZETYPE repPos = ch.indexOf(find),
flen = find.length(),
rlen = rep.length();
while( repPos >= 0 ){
tmp += ch.substr(0,repPos) + rep;
ch = ch.substr(repPos+flen);
repPos = ch.indexOf(find);
}
tmp += ch;
return tmp;
}
// tolower : converts all alphabet values to lower case.
String String::tolower() const {
String ret(*this );
for( __SIZETYPE i=0; i<ret.length(); i++)
if( ret[i] >= 'A' && ret[i] <= 'Z' )
ret[i] = ret[i] - 'A' + 'a';
return ret;
}
// toupper : converts all alphabet values to upper case.
String String::toupper() const {
String ret( *this );
for( __SIZETYPE i=0; i<ret.length(); i++)
if( ret[i] >= 'a' && ret[i] <= 'z' )
ret[i] = ret[i] - 'a' + 'A';
return ret;
}
// trim : removes all preceding and trailing spaces
String String::trim() const {
__SIZETYPE st,en;
for( st = 0; _data[st] == ' ' && st < _len; st++);
if( st == _len ) return String("");
for( en = _len-1; _data[en] == ' ' && en >= 0; en--);
return this->substr( st, en-st+1 );
}
// indexOf : gives index of first occurrance of s
__SIZETYPE String::indexOf(const String& s ) const {
__SIZETYPE tlen = s.length();
bool isfound ;
for( __SIZETYPE i = 0; i < _len-tlen ; ++i ){
isfound = true;
for( __SIZETYPE j = 0; j < tlen ; ++j ){
if( s[j] != _data[i+j] ){
isfound = false;
break;
}
}
if( isfound ) return i;
}
return -1;
}
// numOccurences : gives the number of times s appears in the given string ( without overlaps )
__SIZETYPE String::countOccurences(const String& find ) const {
__SIZETYPE tot = 0;
int flen = find.length();
for( int i = 0; i<_len-flen ; i++ ){
bool match = false;
for( int j = 0; j<flen ; j++ )
if( _data[i+j] != find[j] ){
match = false;
break;
}
if( match ){
tot++;
i += flen-1;
}
}
return tot;
}
/***********************************
* 4. Relational Operators
************************************/
// operator ! : returns true if string is empty
bool String::operator!() const {
return !_len;
}
// operator == : returns true if both strings are equal( each char matches )
bool String::operator==(const String& s ) const {
if( _len != s.length() ) return false;
for( __SIZETYPE it = 0; it < _len ; it++ )
if( _data[it] != s[it] )
return false;
return true;
}
// operator != : returns true if both strings are not equal
bool String::operator!=(const String& s ) const {
return !( *this == s );
}
/************************************
* 5. Stream IO operators : >> <<
************************************/
ostream& operator<<(ostream& output, String& str) {
str.print(output);
return output;
}
bool String::print(ostream& output) const {
for( __SIZETYPE i=0; i<_len; ++i)
output<<_data[i];
}
// this is the global input buffer for all strings.
char *String::stringInputBuffer = new char[ MAX_STRING_LENGTH ];
bool String::get(istream& input, char delim ) {
input.getline(String::stringInputBuffer, MAX_STRING_LENGTH, delim);
*this = String::stringInputBuffer;
return true;
}
istream& operator>>(istream& input, String& str) {
str.get(input, ' ');
return input;
}
#endif /* CODE_STRING_H */
<|endoftext|> |
<commit_before>// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "google/cloud/log.h"
#include <gmock/gmock.h>
using namespace google::cloud;
using namespace ::testing;
TEST(LogSeverityTest, Streaming) {
std::ostringstream os;
os << Severity::GCP_LS_TRACE;
EXPECT_EQ("TRACE", os.str());
}
TEST(LogSinkTest, CompileTimeEnabled) {
EXPECT_TRUE(LogSink::CompileTimeEnabled(Severity::GCP_LS_CRITICAL));
if (Severity::GCP_LS_LOWEST_ENABLED >= Severity::GCP_LS_TRACE) {
EXPECT_FALSE(LogSink::CompileTimeEnabled(Severity::GCP_LS_TRACE));
}
}
TEST(LogSinkTest, RuntimeSeverity) {
LogSink sink;
EXPECT_EQ(Severity::GCP_LS_LOWEST_ENABLED, sink.minimum_severity());
sink.set_minimum_severity(Severity::GCP_LS_ERROR);
EXPECT_EQ(Severity::GCP_LS_ERROR, sink.minimum_severity());
}
namespace {
class MockLogBackend : public LogBackend {
public:
MOCK_METHOD1(Process, void(LogRecord const&));
MOCK_METHOD1(ProcessWithOwnership, void(LogRecord));
};
} // namespace
TEST(LogSinkTest, BackendAddRemove) {
LogSink sink;
EXPECT_TRUE(sink.empty());
long id = sink.AddBackend(std::make_shared<MockLogBackend>());
EXPECT_FALSE(sink.empty());
sink.RemoveBackend(id);
EXPECT_TRUE(sink.empty());
}
TEST(LogSinkTest, ClearBackend) {
LogSink sink;
(void)sink.AddBackend(std::make_shared<MockLogBackend>());
(void)sink.AddBackend(std::make_shared<MockLogBackend>());
EXPECT_FALSE(sink.empty());
sink.ClearBackends();
EXPECT_TRUE(sink.empty());
}
TEST(LogSinkTest, LogEnabled) {
LogSink sink;
auto backend = std::make_shared<MockLogBackend>();
EXPECT_CALL(*backend, ProcessWithOwnership(_))
.WillOnce(Invoke([](LogRecord lr) {
EXPECT_EQ(Severity::GCP_LS_WARNING, lr.severity);
EXPECT_EQ("test message", lr.message);
}));
sink.AddBackend(backend);
GOOGLE_CLOUD_CPP_LOG_I(GCP_LS_WARNING, sink) << "test message";
}
TEST(LogSinkTest, LogEnabledMultipleBackends) {
LogSink sink;
auto be1 = std::make_shared<MockLogBackend>();
auto be2 = std::make_shared<MockLogBackend>();
EXPECT_CALL(*be1, Process(_)).WillOnce(Invoke([](LogRecord const& lr) {
EXPECT_EQ(Severity::GCP_LS_WARNING, lr.severity);
EXPECT_EQ("test message", lr.message);
}));
sink.AddBackend(be1);
EXPECT_CALL(*be2, Process(_)).WillOnce(Invoke([](LogRecord const& lr) {
EXPECT_EQ(Severity::GCP_LS_WARNING, lr.severity);
EXPECT_EQ("test message", lr.message);
}));
sink.AddBackend(be2);
GOOGLE_CLOUD_CPP_LOG_I(GCP_LS_WARNING, sink) << "test message";
}
TEST(LogSinkTest, LogDefaultInstance) {
auto backend = std::make_shared<MockLogBackend>();
EXPECT_CALL(*backend, ProcessWithOwnership(_))
.WillOnce(Invoke([](LogRecord lr) {
EXPECT_EQ(Severity::GCP_LS_WARNING, lr.severity);
EXPECT_EQ("test message", lr.message);
}));
LogSink::Instance().AddBackend(backend);
GCP_LOG(WARNING) << "test message";
LogSink::Instance().ClearBackends();
}
TEST(LogSinkTest, LogToClog) {
LogSink::EnableStdClog();
EXPECT_FALSE(LogSink::Instance().empty());
LogSink::Instance().set_minimum_severity(Severity::GCP_LS_NOTICE);
GCP_LOG(NOTICE) << "test message";
LogSink::DisableStdClog();
EXPECT_TRUE(LogSink::Instance().empty());
EXPECT_EQ(0U, LogSink::Instance().BackendCount());
LogSink::Instance().ClearBackends();
}
TEST(LogSinkTest, ClogMultiple) {
LogSink::EnableStdClog();
EXPECT_FALSE(LogSink::Instance().empty());
EXPECT_EQ(1U, LogSink::Instance().BackendCount());
LogSink::EnableStdClog();
EXPECT_FALSE(LogSink::Instance().empty());
EXPECT_EQ(1U, LogSink::Instance().BackendCount());
LogSink::EnableStdClog();
EXPECT_FALSE(LogSink::Instance().empty());
EXPECT_EQ(1U, LogSink::Instance().BackendCount());
LogSink::Instance().set_minimum_severity(Severity::GCP_LS_NOTICE);
GCP_LOG(NOTICE) << "test message";
LogSink::DisableStdClog();
EXPECT_TRUE(LogSink::Instance().empty());
EXPECT_EQ(0U, LogSink::Instance().BackendCount());
}
namespace {
/// A class to count calls to IOStream operator.
struct IOStreamCounter {
int count;
};
std::ostream& operator<<(std::ostream& os, IOStreamCounter& rhs) {
++rhs.count;
return os;
}
} // namespace
TEST(LogSinkTest, LogCheckCounter) {
LogSink sink;
IOStreamCounter counter{0};
// The following tests could pass if the << operator was a no-op, so for
// extra paranoia check that this is not the case.
auto backend = std::make_shared<MockLogBackend>();
EXPECT_CALL(*backend, ProcessWithOwnership(_)).Times(2);
sink.AddBackend(backend);
GOOGLE_CLOUD_CPP_LOG_I(GCP_LS_ALERT, sink) << "count is " << counter;
GOOGLE_CLOUD_CPP_LOG_I(GCP_LS_FATAL, sink) << "count is " << counter;
EXPECT_EQ(2, counter.count);
}
TEST(LogSinkTest, LogNoSinks) {
LogSink sink;
IOStreamCounter counter{0};
EXPECT_EQ(0, counter.count);
GOOGLE_CLOUD_CPP_LOG_I(GCP_LS_WARNING, sink) << "count is " << counter;
// With no backends, we expect no calls to the iostream operators.
EXPECT_EQ(0, counter.count);
}
TEST(LogSinkTest, LogDisabledLevels) {
LogSink sink;
IOStreamCounter counter{0};
auto backend = std::make_shared<MockLogBackend>();
EXPECT_CALL(*backend, ProcessWithOwnership(_)).Times(1);
sink.AddBackend(backend);
sink.set_minimum_severity(Severity::GCP_LS_INFO);
GOOGLE_CLOUD_CPP_LOG_I(GCP_LS_DEBUG, sink) << "count is " << counter;
// With the DEBUG level disabled we expect no calls.
EXPECT_EQ(0, counter.count);
sink.set_minimum_severity(Severity::GCP_LS_ALERT);
GOOGLE_CLOUD_CPP_LOG_I(GCP_LS_ALERT, sink) << "count is " << counter;
EXPECT_EQ(1, counter.count);
}
TEST(LogSinkTest, CompileTimeDisabledCannotBeEnabled) {
LogSink sink;
IOStreamCounter counter{0};
auto backend = std::make_shared<MockLogBackend>();
EXPECT_CALL(*backend, ProcessWithOwnership(_)).Times(1);
sink.AddBackend(backend);
// Compile-time disabled logs cannot be enabled at r
if (Severity::GCP_LS_LOWEST_ENABLED >= Severity::GCP_LS_TRACE) {
sink.set_minimum_severity(Severity::GCP_LS_TRACE);
GOOGLE_CLOUD_CPP_LOG_I(GCP_LS_TRACE, sink) << "count is " << counter;
EXPECT_EQ(0, counter.count);
}
sink.set_minimum_severity(Severity::GCP_LS_CRITICAL);
GOOGLE_CLOUD_CPP_LOG_I(GCP_LS_CRITICAL, sink) << "count is " << counter;
EXPECT_EQ(1, counter.count);
}
TEST(LogSinkTest, DisabledLogsMakeNoCalls) {
LogSink sink;
int counter = 0;
auto caller = [&counter] { return ++counter; };
EXPECT_EQ(0, counter);
GOOGLE_CLOUD_CPP_LOG_I(GCP_LS_WARNING, sink) << "count is " << caller();
GOOGLE_CLOUD_CPP_LOG_I(GCP_LS_WARNING, sink) << "count is " << caller();
GOOGLE_CLOUD_CPP_LOG_I(GCP_LS_WARNING, sink) << "count is " << caller();
GOOGLE_CLOUD_CPP_LOG_I(GCP_LS_WARNING, sink) << "count is " << caller();
// With no backends, we expect no calls to the expressions in the log line.
EXPECT_EQ(0, counter);
}
<commit_msg>moved tests into namespace to avoid using directive (#2023)<commit_after>// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "google/cloud/log.h"
#include <gmock/gmock.h>
namespace google {
namespace cloud {
inline namespace GOOGLE_CLOUD_CPP_NS {
namespace {
using namespace ::testing;
TEST(LogSeverityTest, Streaming) {
std::ostringstream os;
os << Severity::GCP_LS_TRACE;
EXPECT_EQ("TRACE", os.str());
}
TEST(LogSinkTest, CompileTimeEnabled) {
EXPECT_TRUE(LogSink::CompileTimeEnabled(Severity::GCP_LS_CRITICAL));
if (Severity::GCP_LS_LOWEST_ENABLED >= Severity::GCP_LS_TRACE) {
EXPECT_FALSE(LogSink::CompileTimeEnabled(Severity::GCP_LS_TRACE));
}
}
TEST(LogSinkTest, RuntimeSeverity) {
LogSink sink;
EXPECT_EQ(Severity::GCP_LS_LOWEST_ENABLED, sink.minimum_severity());
sink.set_minimum_severity(Severity::GCP_LS_ERROR);
EXPECT_EQ(Severity::GCP_LS_ERROR, sink.minimum_severity());
}
namespace {
class MockLogBackend : public LogBackend {
public:
MOCK_METHOD1(Process, void(LogRecord const&));
MOCK_METHOD1(ProcessWithOwnership, void(LogRecord));
};
} // namespace
TEST(LogSinkTest, BackendAddRemove) {
LogSink sink;
EXPECT_TRUE(sink.empty());
long id = sink.AddBackend(std::make_shared<MockLogBackend>());
EXPECT_FALSE(sink.empty());
sink.RemoveBackend(id);
EXPECT_TRUE(sink.empty());
}
TEST(LogSinkTest, ClearBackend) {
LogSink sink;
(void)sink.AddBackend(std::make_shared<MockLogBackend>());
(void)sink.AddBackend(std::make_shared<MockLogBackend>());
EXPECT_FALSE(sink.empty());
sink.ClearBackends();
EXPECT_TRUE(sink.empty());
}
TEST(LogSinkTest, LogEnabled) {
LogSink sink;
auto backend = std::make_shared<MockLogBackend>();
EXPECT_CALL(*backend, ProcessWithOwnership(_))
.WillOnce(Invoke([](LogRecord lr) {
EXPECT_EQ(Severity::GCP_LS_WARNING, lr.severity);
EXPECT_EQ("test message", lr.message);
}));
sink.AddBackend(backend);
GOOGLE_CLOUD_CPP_LOG_I(GCP_LS_WARNING, sink) << "test message";
}
TEST(LogSinkTest, LogEnabledMultipleBackends) {
LogSink sink;
auto be1 = std::make_shared<MockLogBackend>();
auto be2 = std::make_shared<MockLogBackend>();
EXPECT_CALL(*be1, Process(_)).WillOnce(Invoke([](LogRecord const& lr) {
EXPECT_EQ(Severity::GCP_LS_WARNING, lr.severity);
EXPECT_EQ("test message", lr.message);
}));
sink.AddBackend(be1);
EXPECT_CALL(*be2, Process(_)).WillOnce(Invoke([](LogRecord const& lr) {
EXPECT_EQ(Severity::GCP_LS_WARNING, lr.severity);
EXPECT_EQ("test message", lr.message);
}));
sink.AddBackend(be2);
GOOGLE_CLOUD_CPP_LOG_I(GCP_LS_WARNING, sink) << "test message";
}
TEST(LogSinkTest, LogDefaultInstance) {
auto backend = std::make_shared<MockLogBackend>();
EXPECT_CALL(*backend, ProcessWithOwnership(_))
.WillOnce(Invoke([](LogRecord lr) {
EXPECT_EQ(Severity::GCP_LS_WARNING, lr.severity);
EXPECT_EQ("test message", lr.message);
}));
LogSink::Instance().AddBackend(backend);
GCP_LOG(WARNING) << "test message";
LogSink::Instance().ClearBackends();
}
TEST(LogSinkTest, LogToClog) {
LogSink::EnableStdClog();
EXPECT_FALSE(LogSink::Instance().empty());
LogSink::Instance().set_minimum_severity(Severity::GCP_LS_NOTICE);
GCP_LOG(NOTICE) << "test message";
LogSink::DisableStdClog();
EXPECT_TRUE(LogSink::Instance().empty());
EXPECT_EQ(0U, LogSink::Instance().BackendCount());
LogSink::Instance().ClearBackends();
}
TEST(LogSinkTest, ClogMultiple) {
LogSink::EnableStdClog();
EXPECT_FALSE(LogSink::Instance().empty());
EXPECT_EQ(1U, LogSink::Instance().BackendCount());
LogSink::EnableStdClog();
EXPECT_FALSE(LogSink::Instance().empty());
EXPECT_EQ(1U, LogSink::Instance().BackendCount());
LogSink::EnableStdClog();
EXPECT_FALSE(LogSink::Instance().empty());
EXPECT_EQ(1U, LogSink::Instance().BackendCount());
LogSink::Instance().set_minimum_severity(Severity::GCP_LS_NOTICE);
GCP_LOG(NOTICE) << "test message";
LogSink::DisableStdClog();
EXPECT_TRUE(LogSink::Instance().empty());
EXPECT_EQ(0U, LogSink::Instance().BackendCount());
}
namespace {
/// A class to count calls to IOStream operator.
struct IOStreamCounter {
int count;
};
std::ostream& operator<<(std::ostream& os, IOStreamCounter& rhs) {
++rhs.count;
return os;
}
} // namespace
TEST(LogSinkTest, LogCheckCounter) {
LogSink sink;
IOStreamCounter counter{0};
// The following tests could pass if the << operator was a no-op, so for
// extra paranoia check that this is not the case.
auto backend = std::make_shared<MockLogBackend>();
EXPECT_CALL(*backend, ProcessWithOwnership(_)).Times(2);
sink.AddBackend(backend);
GOOGLE_CLOUD_CPP_LOG_I(GCP_LS_ALERT, sink) << "count is " << counter;
GOOGLE_CLOUD_CPP_LOG_I(GCP_LS_FATAL, sink) << "count is " << counter;
EXPECT_EQ(2, counter.count);
}
TEST(LogSinkTest, LogNoSinks) {
LogSink sink;
IOStreamCounter counter{0};
EXPECT_EQ(0, counter.count);
GOOGLE_CLOUD_CPP_LOG_I(GCP_LS_WARNING, sink) << "count is " << counter;
// With no backends, we expect no calls to the iostream operators.
EXPECT_EQ(0, counter.count);
}
TEST(LogSinkTest, LogDisabledLevels) {
LogSink sink;
IOStreamCounter counter{0};
auto backend = std::make_shared<MockLogBackend>();
EXPECT_CALL(*backend, ProcessWithOwnership(_)).Times(1);
sink.AddBackend(backend);
sink.set_minimum_severity(Severity::GCP_LS_INFO);
GOOGLE_CLOUD_CPP_LOG_I(GCP_LS_DEBUG, sink) << "count is " << counter;
// With the DEBUG level disabled we expect no calls.
EXPECT_EQ(0, counter.count);
sink.set_minimum_severity(Severity::GCP_LS_ALERT);
GOOGLE_CLOUD_CPP_LOG_I(GCP_LS_ALERT, sink) << "count is " << counter;
EXPECT_EQ(1, counter.count);
}
TEST(LogSinkTest, CompileTimeDisabledCannotBeEnabled) {
LogSink sink;
IOStreamCounter counter{0};
auto backend = std::make_shared<MockLogBackend>();
EXPECT_CALL(*backend, ProcessWithOwnership(_)).Times(1);
sink.AddBackend(backend);
// Compile-time disabled logs cannot be enabled at r
if (Severity::GCP_LS_LOWEST_ENABLED >= Severity::GCP_LS_TRACE) {
sink.set_minimum_severity(Severity::GCP_LS_TRACE);
GOOGLE_CLOUD_CPP_LOG_I(GCP_LS_TRACE, sink) << "count is " << counter;
EXPECT_EQ(0, counter.count);
}
sink.set_minimum_severity(Severity::GCP_LS_CRITICAL);
GOOGLE_CLOUD_CPP_LOG_I(GCP_LS_CRITICAL, sink) << "count is " << counter;
EXPECT_EQ(1, counter.count);
}
TEST(LogSinkTest, DisabledLogsMakeNoCalls) {
LogSink sink;
int counter = 0;
auto caller = [&counter] { return ++counter; };
EXPECT_EQ(0, counter);
GOOGLE_CLOUD_CPP_LOG_I(GCP_LS_WARNING, sink) << "count is " << caller();
GOOGLE_CLOUD_CPP_LOG_I(GCP_LS_WARNING, sink) << "count is " << caller();
GOOGLE_CLOUD_CPP_LOG_I(GCP_LS_WARNING, sink) << "count is " << caller();
GOOGLE_CLOUD_CPP_LOG_I(GCP_LS_WARNING, sink) << "count is " << caller();
// With no backends, we expect no calls to the expressions in the log line.
EXPECT_EQ(0, counter);
}
} // namespace
} // namespace GOOGLE_CLOUD_CPP_NS
} // namespace cloud
} // namespace google
<|endoftext|> |
<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Youssef Kashef
// Copyright (c) 2015, ELM Library Project
// 3-clause BSD License
//
//M*/
#include "elm/layers/layerfactory.h"
#include "gtest/gtest.h"
#include "elm/core/exception.h"
#include "elm/core/inputname.h"
#include "elm/core/layerconfig.h"
#include "elm/core/signal.h"
#include "elm/layers/saliencyitti.h" ///< to have layer dervied classes to test with
#include "elm/layers/weightedsum.h" ///< to have layer dervied classes to test with
#include "elm/ts/mat_assertions.h"
using std::string;
using namespace elm;
namespace {
/**
* @brief class or testing LayerFactory's static methods
*/
class LayerFactoryStaticTest : public ::testing::Test
{
protected:
static void SetUpTestCase() {
LayerFactory();
}
};
TEST_F(LayerFactoryStaticTest, CreateLayerPtrShared)
{
{
LayerShared ptr = LayerFactory::CreateShared("LayerY");
EXPECT_TRUE(bool(ptr));
}
{
LayerShared ptr = LayerFactory::CreateShared("WeightedSum");
EXPECT_TRUE(bool(ptr));
}
}
TEST_F(LayerFactoryStaticTest, CreateLayerPtrShared_WrongType)
{
EXPECT_THROW(LayerFactory::CreateShared("Blahbla"), elm::ExceptionTypeError);
}
TEST_F(LayerFactoryStaticTest, CreateLayerPtrShared_UniqueInstancesSameType)
{
const string TYPE="WeightedSum";
LayerShared ptr1 = LayerFactory::CreateShared(TYPE);
LayerShared ptr2 = LayerFactory::CreateShared(TYPE);
EXPECT_NE(ptr1, ptr2);
}
TEST_F(LayerFactoryStaticTest, CreateLayerPtrShared_WithConfig)
{
PTree params;
params.put(WeightedSum::PARAM_A, 0.2f);
params.put(WeightedSum::PARAM_B, 0.3f);
LayerConfig config;
config.Params(params);
const string NAME_STIMULUS = "in";
const string NAME_RESPONSE = "out";
config.Input(WeightedSum::KEY_INPUT_STIMULUS, NAME_STIMULUS);
config.Output(WeightedSum::KEY_OUTPUT_RESPONSE, NAME_RESPONSE);
LayerShared ptr = LayerFactory::CreateShared("WeightedSum", config, config);
EXPECT_TRUE(bool(ptr));
// populate signal with input feature
Signal signal;
signal.Append("in", cv::Mat1f::ones(1, 2));
EXPECT_TRUE(signal.Exists(NAME_STIMULUS));
EXPECT_FALSE(signal.Exists(NAME_RESPONSE));
// apply signal to layer
ptr->Activate(signal);
ptr->Response(signal);
// check response
EXPECT_TRUE(signal.Exists(NAME_RESPONSE));
EXPECT_MAT_DIMS_EQ(signal.MostRecentMat1f(NAME_RESPONSE), cv::Size2i(1, 1));
EXPECT_FLOAT_EQ(signal.MostRecentMat1f(NAME_RESPONSE).at<float>(0), 0.5f);
}
TEST_F(LayerFactoryStaticTest, Exists)
{
EXPECT_FALSE(LayerFactory::Exists("Blahbla"));
EXPECT_TRUE(LayerFactory::Exists("WeightedSum"));
}
TEST_F(LayerFactoryStaticTest, InitLayerPtrShared_WithConfig)
{
PTree params;
params.put(WeightedSum::PARAM_A, 0.2f);
params.put(WeightedSum::PARAM_B, 0.3f);
LayerConfig config;
config.Params(params);
const string NAME_STIMULUS = "in";
const string NAME_RESPONSE = "out";
config.Input(WeightedSum::KEY_INPUT_STIMULUS, NAME_STIMULUS);
config.Output(WeightedSum::KEY_OUTPUT_RESPONSE, NAME_RESPONSE);
LayerShared ptr(new WeightedSum);
LayerFactory::Init(ptr, config, config);
EXPECT_TRUE(bool(ptr));
// populate signal with input feature
Signal signal;
signal.Append("in", cv::Mat1f::ones(1, 2));
EXPECT_TRUE(signal.Exists(NAME_STIMULUS));
EXPECT_FALSE(signal.Exists(NAME_RESPONSE));
// apply signal to layer
ptr->Activate(signal);
ptr->Response(signal);
// check response
EXPECT_TRUE(signal.Exists(NAME_RESPONSE));
EXPECT_MAT_DIMS_EQ(signal.MostRecentMat1f(NAME_RESPONSE), cv::Size2i(1, 1));
EXPECT_FLOAT_EQ(signal.MostRecentMat1f(NAME_RESPONSE).at<float>(0), 0.5f);
}
TEST_F(LayerFactoryStaticTest, InitLayerPtrShared_WithConfig_invalid_ptr)
{
PTree params;
params.put(WeightedSum::PARAM_A, 0.2f);
params.put(WeightedSum::PARAM_B, 0.3f);
LayerConfig config;
config.Params(params);
const string NAME_STIMULUS = "in";
const string NAME_RESPONSE = "out";
config.Input(WeightedSum::KEY_INPUT_STIMULUS, NAME_STIMULUS);
config.Output(WeightedSum::KEY_OUTPUT_RESPONSE, NAME_RESPONSE);
LayerShared ptr;
ASSERT_FALSE(bool(ptr));
EXPECT_THROW(LayerFactory::Init(ptr, config, config), ExceptionValueError);
ptr.reset(new WeightedSum);
EXPECT_TRUE(bool(ptr));
EXPECT_NO_THROW(LayerFactory::Init(ptr, config, config));
}
class LayerFactoryTest : public ::testing::Test
{
};
TEST_F(LayerFactoryStaticTest, Constructor)
{
EXPECT_NO_THROW(LayerFactory to);
}
} // annonymous namespace
<commit_msg>remove redundant namespace scoping<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Youssef Kashef
// Copyright (c) 2015, ELM Library Project
// 3-clause BSD License
//
//M*/
#include "elm/layers/layerfactory.h"
#include "gtest/gtest.h"
#include "elm/core/exception.h"
#include "elm/core/inputname.h"
#include "elm/core/layerconfig.h"
#include "elm/core/signal.h"
#include "elm/layers/saliencyitti.h" ///< to have layer dervied classes to test with
#include "elm/layers/weightedsum.h" ///< to have layer dervied classes to test with
#include "elm/ts/mat_assertions.h"
using std::string;
using namespace elm;
namespace {
/**
* @brief class or testing LayerFactory's static methods
*/
class LayerFactoryStaticTest : public ::testing::Test
{
protected:
static void SetUpTestCase() {
LayerFactory();
}
};
TEST_F(LayerFactoryStaticTest, CreateLayerPtrShared)
{
{
LayerShared ptr = LayerFactory::CreateShared("LayerY");
EXPECT_TRUE(bool(ptr));
}
{
LayerShared ptr = LayerFactory::CreateShared("WeightedSum");
EXPECT_TRUE(bool(ptr));
}
}
TEST_F(LayerFactoryStaticTest, CreateLayerPtrShared_WrongType)
{
EXPECT_THROW(LayerFactory::CreateShared("Blahbla"), ExceptionTypeError);
}
TEST_F(LayerFactoryStaticTest, CreateLayerPtrShared_UniqueInstancesSameType)
{
const string TYPE="WeightedSum";
LayerShared ptr1 = LayerFactory::CreateShared(TYPE);
LayerShared ptr2 = LayerFactory::CreateShared(TYPE);
EXPECT_NE(ptr1, ptr2);
}
TEST_F(LayerFactoryStaticTest, CreateLayerPtrShared_WithConfig)
{
PTree params;
params.put(WeightedSum::PARAM_A, 0.2f);
params.put(WeightedSum::PARAM_B, 0.3f);
LayerConfig config;
config.Params(params);
const string NAME_STIMULUS = "in";
const string NAME_RESPONSE = "out";
config.Input(WeightedSum::KEY_INPUT_STIMULUS, NAME_STIMULUS);
config.Output(WeightedSum::KEY_OUTPUT_RESPONSE, NAME_RESPONSE);
LayerShared ptr = LayerFactory::CreateShared("WeightedSum", config, config);
EXPECT_TRUE(bool(ptr));
// populate signal with input feature
Signal signal;
signal.Append("in", cv::Mat1f::ones(1, 2));
EXPECT_TRUE(signal.Exists(NAME_STIMULUS));
EXPECT_FALSE(signal.Exists(NAME_RESPONSE));
// apply signal to layer
ptr->Activate(signal);
ptr->Response(signal);
// check response
EXPECT_TRUE(signal.Exists(NAME_RESPONSE));
EXPECT_MAT_DIMS_EQ(signal.MostRecentMat1f(NAME_RESPONSE), cv::Size2i(1, 1));
EXPECT_FLOAT_EQ(signal.MostRecentMat1f(NAME_RESPONSE).at<float>(0), 0.5f);
}
TEST_F(LayerFactoryStaticTest, Exists)
{
EXPECT_FALSE(LayerFactory::Exists("Blahbla"));
EXPECT_TRUE(LayerFactory::Exists("WeightedSum"));
}
TEST_F(LayerFactoryStaticTest, InitLayerPtrShared_WithConfig)
{
PTree params;
params.put(WeightedSum::PARAM_A, 0.2f);
params.put(WeightedSum::PARAM_B, 0.3f);
LayerConfig config;
config.Params(params);
const string NAME_STIMULUS = "in";
const string NAME_RESPONSE = "out";
config.Input(WeightedSum::KEY_INPUT_STIMULUS, NAME_STIMULUS);
config.Output(WeightedSum::KEY_OUTPUT_RESPONSE, NAME_RESPONSE);
LayerShared ptr(new WeightedSum);
LayerFactory::Init(ptr, config, config);
EXPECT_TRUE(bool(ptr));
// populate signal with input feature
Signal signal;
signal.Append("in", cv::Mat1f::ones(1, 2));
EXPECT_TRUE(signal.Exists(NAME_STIMULUS));
EXPECT_FALSE(signal.Exists(NAME_RESPONSE));
// apply signal to layer
ptr->Activate(signal);
ptr->Response(signal);
// check response
EXPECT_TRUE(signal.Exists(NAME_RESPONSE));
EXPECT_MAT_DIMS_EQ(signal.MostRecentMat1f(NAME_RESPONSE), cv::Size2i(1, 1));
EXPECT_FLOAT_EQ(signal.MostRecentMat1f(NAME_RESPONSE).at<float>(0), 0.5f);
}
TEST_F(LayerFactoryStaticTest, InitLayerPtrShared_WithConfig_invalid_ptr)
{
PTree params;
params.put(WeightedSum::PARAM_A, 0.2f);
params.put(WeightedSum::PARAM_B, 0.3f);
LayerConfig config;
config.Params(params);
const string NAME_STIMULUS = "in";
const string NAME_RESPONSE = "out";
config.Input(WeightedSum::KEY_INPUT_STIMULUS, NAME_STIMULUS);
config.Output(WeightedSum::KEY_OUTPUT_RESPONSE, NAME_RESPONSE);
LayerShared ptr;
ASSERT_FALSE(bool(ptr));
EXPECT_THROW(LayerFactory::Init(ptr, config, config), ExceptionValueError);
ptr.reset(new WeightedSum);
EXPECT_TRUE(bool(ptr));
EXPECT_NO_THROW(LayerFactory::Init(ptr, config, config));
}
class LayerFactoryTest : public ::testing::Test
{
};
TEST_F(LayerFactoryStaticTest, Constructor)
{
EXPECT_NO_THROW(LayerFactory to);
}
} // annonymous namespace
<|endoftext|> |
<commit_before>#include "SiteInfo.h"
#include <unistd.h>
std::string get_pwd()
{
char pwd_char[512];
getcwd(pwd_char, 512);
std::string pwd = pwd_char;
return pwd;
}
void unrecognisedCommand(const std::string from, const std::string cmd)
{
std::cout << "error: " << from << " does not recognise the command '" << cmd << "'" << std::endl;
}
bool parError(int noParams, char* argv[], const std::string &expectedNo)
{
std::cout << "error: " << noParams << " is more than the " << expectedNo << " parameters expected" << std::endl;
std::cout << "parameters given:";
for(int p=1; p<=noParams; p++)
std::cout << " " << argv[p];
std::cout << std::endl;
return 1;
}
int main(int argc, char* argv[])
{
int noParams = argc-1;
if(noParams == 0)
{
std::cout << "no commands given, nothing to do" << std::endl;
return 0;
}
std::string cmd = argv[1];
if(cmd == "commands")
{
std::cout << "------------------- available commands -------------------" << std::endl;
std::cout << "nsm commands | lists all nsm commands" << std::endl;
std::cout << "nsm config | lists config settings" << std::endl;
std::cout << "nsm init | initialise managing a site" << std::endl;
std::cout << "nsm status | lists updated and problem pages" << std::endl;
std::cout << "nsm info | input: page-name-1 .. page-name-k" << std::endl;
std::cout << "nsm info-all | lists tracked pages" << std::endl;
std::cout << "nsm info-names | lists tracked page names" << std::endl;
std::cout << "nsm track | input: page-name (page-title) (template-path)" << std::endl;
std::cout << "nsm untrack | input: page-name" << std::endl;
std::cout << "nsm rm | input: page-name" << std::endl;
std::cout << "nsm mv | input: old-name new-name" << std::endl;
std::cout << "nsm cp | input: tracked-name new-name" << std::endl;
std::cout << "nsm build | input: page-name-1 .. page-name-k" << std::endl;
std::cout << "nsm build-updated | builds updated pages" << std::endl;
std::cout << "nsm build-all | builds all tracked pages " << std::endl;
std::cout << "nsm new-title | input: page-name new-title" << std::endl;
std::cout << "nsm new-template | input: page-name template-path" << std::endl;
std::cout << "----------------------------------------------------------" << std::endl;
return 0;
}
if(cmd == "init")
{
//ensures correct number of parameters given
if(noParams > 1)
return parError(noParams, argv, "1");
//ensures nsm isn't already managing a site from directory
if(std::ifstream(".siteinfo/pages.list"))
{
std::cout << "error: nsm is already managing a site in " << get_pwd() << "/" << std::endl;
return 1;
}
//sets up
Path pagesListPath(".siteinfo/", "pages.list");
//ensures pages list file exists
pagesListPath.ensurePathExists();
//adds read and write permissions to pages list file
chmod(pagesListPath.str().c_str(), 0666);
std::ofstream ofs(".siteinfo/nsm.config");
ofs << "contentDir content/" << std::endl;
ofs << "contentExt .content" << std::endl;
ofs << "siteDir site/" << std::endl;
ofs << "pageExt .html" << std::endl;
ofs << "defaultTemplate template/page.template" << std::endl;
ofs.close();
std::cout << "nsm: initialised empty site in " << get_pwd() << "/.siteinfo/" << std::endl;
return 0;
}
//ensures nsm is managing a site from this directory or one of the parent directories
std::string parentDir = "../",
rootDir = "/",
owd = get_pwd(),
pwd = get_pwd(),
prevPwd;
while(!std::ifstream(".siteinfo/pages.list") && !std::ifstream(".siteinfo/nsm.config"))
{
//sets old pwd
prevPwd = pwd;
//changes to parent directory
chdir(parentDir.c_str());
//gets new pwd
pwd = get_pwd();
//checks we haven't made it to root directory or stuck at same dir
if(pwd == rootDir || pwd == prevPwd)
{
std::cout << "nsm is not managing a site from " << owd << " (or any accessible parent directories)" << std::endl;
return 1;
}
}
//ensures both pages.list and nsm.config exist
if(!std::ifstream(".siteinfo/pages.list"))
{
std::cout << "error: " << get_pwd() << "/.siteinfo/pages.list is missing" << std::endl;
return 1;
}
if(!std::ifstream(".siteinfo/nsm.config"))
{
std::cout << "error: " << get_pwd() << "/.siteinfo/nsm.config is missing" << std::endl;
return 1;
}
//opens up site information
SiteInfo site;
if(site.open() > 0)
return 1;
if(cmd == "config")
{
std::cout << "contentDir: " << site.contentDir << std::endl;
std::cout << "contentExt: " << site.contentExt << std::endl;
std::cout << "siteDir: " << site.siteDir << std::endl;
std::cout << "pageExt: " << site.pageExt << std::endl;
std::cout << "defaultTemplate: " << site.defaultTemplate << std::endl;
return 0;
}
if(cmd == "status")
{
//ensures correct number of parameters given
if(noParams != 1)
return parError(noParams, argv, "1");
return site.status();
}
else if(cmd == "info")
{
//ensures correct number of parameters given
if(noParams <= 1)
return parError(noParams, argv, ">1");
std::vector<Name> pageNames;
Name pageName;
for(int p=2; p<argc; p++)
pageNames.push_back(argv[p]);
return site.info(pageNames);
}
else if(cmd == "info-all")
{
//ensures correct number of parameters given
if(noParams > 1)
return parError(noParams, argv, "1");
return site.info_all();
}
else if(cmd == "info-names")
{
//ensures correct number of parameters given
if(noParams > 1)
return parError(noParams, argv, "1");
return site.info_names();
}
else if(cmd == "track")
{
//ensures correct number of parameters given
if(noParams < 2 || noParams > 4)
return parError(noParams, argv, "2-4");
Name newPageName = argv[2];
Title newPageTitle;
if(noParams >= 3)
newPageTitle = argv[3];
else
newPageTitle = argv[2];
Path newTemplatePath;
if(noParams == 4)
newTemplatePath.set_file_path_from(argv[4]);
else
newTemplatePath = site.defaultTemplate;
return site.track(newPageName, newPageTitle, newTemplatePath);
}
else if(cmd == "untrack")
{
//ensures correct number of parameters given
if(noParams != 2)
return parError(noParams, argv, "2");
Name pageNameToUntrack = argv[2];
return site.untrack(pageNameToUntrack);
}
else if(cmd == "rm")
{
//ensures correct number of parameters given
if(noParams != 2)
return parError(noParams, argv, "2");
Name pageNameToRemove = argv[2];
return site.rm(pageNameToRemove);
}
else if(cmd == "mv")
{
//ensures correct number of parameters given
if(noParams != 3)
return parError(noParams, argv, "3");
Name oldPageName = argv[2],
newPageName = argv[3];
return site.mv(oldPageName, newPageName);
}
else if(cmd == "cp")
{
//ensures correct number of parameters given
if(noParams != 3)
return parError(noParams, argv, "3");
Name trackedPageName = argv[2],
newPageName = argv[3];
return site.cp(trackedPageName, newPageName);
}
else if(cmd == "new-title")
{
//ensures correct number of parameters given
if(noParams != 3)
return parError(noParams, argv, "3");
Name pageName = argv[2];
Title newTitle;
newTitle.str = argv[3];
return site.new_title(pageName, newTitle);
}
else if(cmd == "new-template")
{
//ensures correct number of parameters given
if(noParams != 3)
return parError(noParams, argv, "3");
Name pageName = argv[2];
Path newTemplatePath;
newTemplatePath.set_file_path_from(argv[3]);
return site.new_template(pageName, newTemplatePath);
}
else if(cmd == "build-updated")
{
//ensures correct number of parameters given
if(noParams > 1)
return parError(noParams, argv, "1");
return site.build_updated();
}
else if(cmd == "build")
{
//ensures correct number of parameters given
if(noParams <= 1)
return parError(noParams, argv, ">1");
std::vector<Name> pageNamesToBuild;
for(int p=2; p<argc; p++)
{
pageNamesToBuild.push_back(argv[p]);
}
return site.build(pageNamesToBuild);
}
else if(cmd == "build-all")
{
//ensures correct number of parameters given
if(noParams != 1)
return parError(noParams, argv, "1");
return site.build_all();
}
else
{
unrecognisedCommand("nsm", cmd);
}
return 0;
}
<commit_msg>changed get_pwd()<commit_after>#include "SiteInfo.h"
#include <unistd.h>
std::string get_pwd()
{
char * pwd_char = getcwd(NULL, 0);
std::string pwd = pwd_char;
free(pwd_char);
return pwd;
}
void unrecognisedCommand(const std::string from, const std::string cmd)
{
std::cout << "error: " << from << " does not recognise the command '" << cmd << "'" << std::endl;
}
bool parError(int noParams, char* argv[], const std::string &expectedNo)
{
std::cout << "error: " << noParams << " is more than the " << expectedNo << " parameters expected" << std::endl;
std::cout << "parameters given:";
for(int p=1; p<=noParams; p++)
std::cout << " " << argv[p];
std::cout << std::endl;
return 1;
}
int main(int argc, char* argv[])
{
int noParams = argc-1;
if(noParams == 0)
{
std::cout << "no commands given, nothing to do" << std::endl;
return 0;
}
std::string cmd = argv[1];
if(cmd == "commands")
{
std::cout << "------------------- available commands -------------------" << std::endl;
std::cout << "nsm commands | lists all nsm commands" << std::endl;
std::cout << "nsm config | lists config settings" << std::endl;
std::cout << "nsm init | initialise managing a site" << std::endl;
std::cout << "nsm status | lists updated and problem pages" << std::endl;
std::cout << "nsm info | input: page-name-1 .. page-name-k" << std::endl;
std::cout << "nsm info-all | lists tracked pages" << std::endl;
std::cout << "nsm info-names | lists tracked page names" << std::endl;
std::cout << "nsm track | input: page-name (page-title) (template-path)" << std::endl;
std::cout << "nsm untrack | input: page-name" << std::endl;
std::cout << "nsm rm | input: page-name" << std::endl;
std::cout << "nsm mv | input: old-name new-name" << std::endl;
std::cout << "nsm cp | input: tracked-name new-name" << std::endl;
std::cout << "nsm build | input: page-name-1 .. page-name-k" << std::endl;
std::cout << "nsm build-updated | builds updated pages" << std::endl;
std::cout << "nsm build-all | builds all tracked pages " << std::endl;
std::cout << "nsm new-title | input: page-name new-title" << std::endl;
std::cout << "nsm new-template | input: page-name template-path" << std::endl;
std::cout << "----------------------------------------------------------" << std::endl;
return 0;
}
if(cmd == "init")
{
//ensures correct number of parameters given
if(noParams > 1)
return parError(noParams, argv, "1");
//ensures nsm isn't already managing a site from directory
if(std::ifstream(".siteinfo/pages.list"))
{
std::cout << "error: nsm is already managing a site in " << get_pwd() << "/" << std::endl;
return 1;
}
//sets up
Path pagesListPath(".siteinfo/", "pages.list");
//ensures pages list file exists
pagesListPath.ensurePathExists();
//adds read and write permissions to pages list file
chmod(pagesListPath.str().c_str(), 0666);
std::ofstream ofs(".siteinfo/nsm.config");
ofs << "contentDir content/" << std::endl;
ofs << "contentExt .content" << std::endl;
ofs << "siteDir site/" << std::endl;
ofs << "pageExt .html" << std::endl;
ofs << "defaultTemplate template/page.template" << std::endl;
ofs.close();
std::cout << "nsm: initialised empty site in " << get_pwd() << "/.siteinfo/" << std::endl;
return 0;
}
//ensures nsm is managing a site from this directory or one of the parent directories
std::string parentDir = "../",
rootDir = "/",
owd = get_pwd(),
pwd = get_pwd(),
prevPwd;
while(!std::ifstream(".siteinfo/pages.list") && !std::ifstream(".siteinfo/nsm.config"))
{
//sets old pwd
prevPwd = pwd;
//changes to parent directory
chdir(parentDir.c_str());
//gets new pwd
pwd = get_pwd();
//checks we haven't made it to root directory or stuck at same dir
if(pwd == rootDir || pwd == prevPwd)
{
std::cout << "nsm is not managing a site from " << owd << " (or any accessible parent directories)" << std::endl;
return 1;
}
}
//ensures both pages.list and nsm.config exist
if(!std::ifstream(".siteinfo/pages.list"))
{
std::cout << "error: " << get_pwd() << "/.siteinfo/pages.list is missing" << std::endl;
return 1;
}
if(!std::ifstream(".siteinfo/nsm.config"))
{
std::cout << "error: " << get_pwd() << "/.siteinfo/nsm.config is missing" << std::endl;
return 1;
}
//opens up site information
SiteInfo site;
if(site.open() > 0)
return 1;
if(cmd == "config")
{
std::cout << "contentDir: " << site.contentDir << std::endl;
std::cout << "contentExt: " << site.contentExt << std::endl;
std::cout << "siteDir: " << site.siteDir << std::endl;
std::cout << "pageExt: " << site.pageExt << std::endl;
std::cout << "defaultTemplate: " << site.defaultTemplate << std::endl;
return 0;
}
if(cmd == "status")
{
//ensures correct number of parameters given
if(noParams != 1)
return parError(noParams, argv, "1");
return site.status();
}
else if(cmd == "info")
{
//ensures correct number of parameters given
if(noParams <= 1)
return parError(noParams, argv, ">1");
std::vector<Name> pageNames;
Name pageName;
for(int p=2; p<argc; p++)
pageNames.push_back(argv[p]);
return site.info(pageNames);
}
else if(cmd == "info-all")
{
//ensures correct number of parameters given
if(noParams > 1)
return parError(noParams, argv, "1");
return site.info_all();
}
else if(cmd == "info-names")
{
//ensures correct number of parameters given
if(noParams > 1)
return parError(noParams, argv, "1");
return site.info_names();
}
else if(cmd == "track")
{
//ensures correct number of parameters given
if(noParams < 2 || noParams > 4)
return parError(noParams, argv, "2-4");
Name newPageName = argv[2];
Title newPageTitle;
if(noParams >= 3)
newPageTitle = argv[3];
else
newPageTitle = argv[2];
Path newTemplatePath;
if(noParams == 4)
newTemplatePath.set_file_path_from(argv[4]);
else
newTemplatePath = site.defaultTemplate;
return site.track(newPageName, newPageTitle, newTemplatePath);
}
else if(cmd == "untrack")
{
//ensures correct number of parameters given
if(noParams != 2)
return parError(noParams, argv, "2");
Name pageNameToUntrack = argv[2];
return site.untrack(pageNameToUntrack);
}
else if(cmd == "rm")
{
//ensures correct number of parameters given
if(noParams != 2)
return parError(noParams, argv, "2");
Name pageNameToRemove = argv[2];
return site.rm(pageNameToRemove);
}
else if(cmd == "mv")
{
//ensures correct number of parameters given
if(noParams != 3)
return parError(noParams, argv, "3");
Name oldPageName = argv[2],
newPageName = argv[3];
return site.mv(oldPageName, newPageName);
}
else if(cmd == "cp")
{
//ensures correct number of parameters given
if(noParams != 3)
return parError(noParams, argv, "3");
Name trackedPageName = argv[2],
newPageName = argv[3];
return site.cp(trackedPageName, newPageName);
}
else if(cmd == "new-title")
{
//ensures correct number of parameters given
if(noParams != 3)
return parError(noParams, argv, "3");
Name pageName = argv[2];
Title newTitle;
newTitle.str = argv[3];
return site.new_title(pageName, newTitle);
}
else if(cmd == "new-template")
{
//ensures correct number of parameters given
if(noParams != 3)
return parError(noParams, argv, "3");
Name pageName = argv[2];
Path newTemplatePath;
newTemplatePath.set_file_path_from(argv[3]);
return site.new_template(pageName, newTemplatePath);
}
else if(cmd == "build-updated")
{
//ensures correct number of parameters given
if(noParams > 1)
return parError(noParams, argv, "1");
return site.build_updated();
}
else if(cmd == "build")
{
//ensures correct number of parameters given
if(noParams <= 1)
return parError(noParams, argv, ">1");
std::vector<Name> pageNamesToBuild;
for(int p=2; p<argc; p++)
{
pageNamesToBuild.push_back(argv[p]);
}
return site.build(pageNamesToBuild);
}
else if(cmd == "build-all")
{
//ensures correct number of parameters given
if(noParams != 1)
return parError(noParams, argv, "1");
return site.build_all();
}
else
{
unrecognisedCommand("nsm", cmd);
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* Runtime CPU detection
* (C) 2009-2010,2013 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/cpuid.h>
#include <botan/types.h>
#include <botan/get_byte.h>
#include <botan/mem_ops.h>
#include <ostream>
#if defined(BOTAN_TARGET_CPU_IS_PPC_FAMILY)
#if defined(BOTAN_TARGET_OS_IS_DARWIN)
#include <sys/sysctl.h>
#endif
#if defined(BOTAN_TARGET_OS_IS_OPENBSD)
#include <sys/param.h>
#include <sys/sysctl.h>
#include <machine/cpu.h>
#endif
#endif
#if defined(BOTAN_TARGET_CPU_IS_X86_FAMILY)
#if defined(BOTAN_BUILD_COMPILER_IS_MSVC)
#include <intrin.h>
#define X86_CPUID(type, out) do { __cpuid((int*)out, type); } while(0)
#define X86_CPUID_SUBLEVEL(type, level, out) do { __cpuidex((int*)out, type, level); } while(0)
#elif defined(BOTAN_BUILD_COMPILER_IS_INTEL)
#include <ia32intrin.h>
#define X86_CPUID(type, out) do { __cpuid(out, type); } while(0)
#define X86_CPUID_SUBLEVEL(type, level, out) do { __cpuidex((int*)out, type, level); } while(0)
#elif defined(BOTAN_TARGET_ARCH_IS_X86_64) && defined(BOTAN_USE_GCC_INLINE_ASM)
#define X86_CPUID(type, out) \
asm("cpuid\n\t" : "=a" (out[0]), "=b" (out[1]), "=c" (out[2]), "=d" (out[3]) \
: "0" (type))
#define X86_CPUID_SUBLEVEL(type, level, out) \
asm("cpuid\n\t" : "=a" (out[0]), "=b" (out[1]), "=c" (out[2]), "=d" (out[3]) \
: "0" (type), "2" (level))
#elif defined(BOTAN_BUILD_COMPILER_IS_GCC)
#include <cpuid.h>
#define X86_CPUID(type, out) do { __get_cpuid(type, out, out+1, out+2, out+3); } while(0)
#define X86_CPUID_SUBLEVEL(type, level, out) \
do { __cpuid_count(type, level, out[0], out[1], out[2], out[3]); } while(0)
#else
#warning "No way of calling cpuid for this compiler"
#define X86_CPUID(type, out) do { clear_mem(out, 4); } while(0)
#define X86_CPUID_SUBLEVEL(type, level, out) do { clear_mem(out, 4); } while(0)
#endif
#endif
namespace Botan {
u64bit CPUID::g_x86_processor_flags[2] = { 0, 0 };
size_t CPUID::g_cache_line_size = 0;
bool CPUID::g_altivec_capable = false;
bool CPUID::g_initialized = false;
namespace {
#if defined(BOTAN_TARGET_CPU_IS_PPC_FAMILY)
bool altivec_check_sysctl()
{
#if defined(BOTAN_TARGET_OS_IS_DARWIN) || defined(BOTAN_TARGET_OS_IS_OPENBSD)
#if defined(BOTAN_TARGET_OS_IS_OPENBSD)
int sels[2] = { CTL_MACHDEP, CPU_ALTIVEC };
#else
// From Apple's docs
int sels[2] = { CTL_HW, HW_VECTORUNIT };
#endif
int vector_type = 0;
size_t length = sizeof(vector_type);
int error = sysctl(sels, 2, &vector_type, &length, NULL, 0);
if(error == 0 && vector_type > 0)
return true;
#endif
return false;
}
bool altivec_check_pvr_emul()
{
bool altivec_capable = false;
#if defined(BOTAN_TARGET_OS_IS_LINUX) || defined(BOTAN_TARGET_OS_IS_NETBSD)
/*
On PowerPC, MSR 287 is PVR, the Processor Version Number
Normally it is only accessible to ring 0, but Linux and NetBSD
(others, too, maybe?) will trap and emulate it for us.
PVR identifiers for various AltiVec enabled CPUs. Taken from
PearPC and Linux sources, mostly.
*/
const u16bit PVR_G4_7400 = 0x000C;
const u16bit PVR_G5_970 = 0x0039;
const u16bit PVR_G5_970FX = 0x003C;
const u16bit PVR_G5_970MP = 0x0044;
const u16bit PVR_G5_970GX = 0x0045;
const u16bit PVR_POWER6 = 0x003E;
const u16bit PVR_POWER7 = 0x003F;
const u16bit PVR_POWER8 = 0x004B;
const u16bit PVR_CELL_PPU = 0x0070;
// Motorola produced G4s with PVR 0x800[0123C] (at least)
const u16bit PVR_G4_74xx_24 = 0x800;
u32bit pvr = 0;
asm volatile("mfspr %0, 287" : "=r" (pvr));
// Top 16 bit suffice to identify model
pvr >>= 16;
altivec_capable |= (pvr == PVR_G4_7400);
altivec_capable |= ((pvr >> 4) == PVR_G4_74xx_24);
altivec_capable |= (pvr == PVR_G5_970);
altivec_capable |= (pvr == PVR_G5_970FX);
altivec_capable |= (pvr == PVR_G5_970MP);
altivec_capable |= (pvr == PVR_G5_970GX);
altivec_capable |= (pvr == PVR_POWER6);
altivec_capable |= (pvr == PVR_POWER7);
altivec_capable |= (pvr == PVR_POWER8);
altivec_capable |= (pvr == PVR_CELL_PPU);
#endif
return altivec_capable;
}
#endif
}
void CPUID::print(std::ostream& o)
{
o << "CPUID flags: ";
#define CPUID_PRINT(flag) do { if(has_##flag()) o << #flag << " "; } while(0)
CPUID_PRINT(sse2);
CPUID_PRINT(ssse3);
CPUID_PRINT(sse41);
CPUID_PRINT(sse42);
CPUID_PRINT(avx2);
CPUID_PRINT(avx512f);
CPUID_PRINT(altivec);
CPUID_PRINT(rdtsc);
CPUID_PRINT(bmi2);
CPUID_PRINT(clmul);
CPUID_PRINT(aes_ni);
CPUID_PRINT(rdrand);
CPUID_PRINT(rdseed);
CPUID_PRINT(intel_sha);
CPUID_PRINT(adx);
#undef CPUID_PRINT
o << "\n";
}
void CPUID::initialize()
{
if(g_initialized)
return;
#if defined(BOTAN_TARGET_CPU_IS_PPC_FAMILY)
if(altivec_check_sysctl() || altivec_check_pvr_emul())
g_altivec_capable = true;
#endif
#if defined(BOTAN_TARGET_CPU_IS_X86_FAMILY)
const u32bit INTEL_CPUID[3] = { 0x756E6547, 0x6C65746E, 0x49656E69 };
const u32bit AMD_CPUID[3] = { 0x68747541, 0x444D4163, 0x69746E65 };
u32bit cpuid[4] = { 0 };
X86_CPUID(0, cpuid);
const u32bit max_supported_sublevel = cpuid[0];
if(max_supported_sublevel == 0)
return;
const bool is_intel = same_mem(cpuid + 1, INTEL_CPUID, 3);
const bool is_amd = same_mem(cpuid + 1, AMD_CPUID, 3);
X86_CPUID(1, cpuid);
g_x86_processor_flags[0] = (static_cast<u64bit>(cpuid[2]) << 32) | cpuid[3];
if(is_intel)
g_cache_line_size = 8 * get_byte(2, cpuid[1]);
if(max_supported_sublevel >= 7)
{
clear_mem(cpuid, 4);
X86_CPUID_SUBLEVEL(7, 0, cpuid);
g_x86_processor_flags[1] = (static_cast<u64bit>(cpuid[2]) << 32) | cpuid[1];
}
if(is_amd)
{
X86_CPUID(0x80000005, cpuid);
g_cache_line_size = get_byte(3, cpuid[2]);
}
#endif
#if defined(BOTAN_TARGET_ARCH_IS_X86_64)
/*
* If we don't have access to CPUID, we can still safely assume that
* any x86-64 processor has SSE2 and RDTSC
*/
if(g_x86_processor_flags[0] == 0)
g_x86_processor_flags[0] = (1 << CPUID_SSE2_BIT) | (1 << CPUID_RDTSC_BIT);
#endif
g_initialized = true;
}
}
<commit_msg>Enable use of cpuid.h with clang<commit_after>/*
* Runtime CPU detection
* (C) 2009-2010,2013 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/cpuid.h>
#include <botan/types.h>
#include <botan/get_byte.h>
#include <botan/mem_ops.h>
#include <ostream>
#if defined(BOTAN_TARGET_CPU_IS_PPC_FAMILY)
#if defined(BOTAN_TARGET_OS_IS_DARWIN)
#include <sys/sysctl.h>
#endif
#if defined(BOTAN_TARGET_OS_IS_OPENBSD)
#include <sys/param.h>
#include <sys/sysctl.h>
#include <machine/cpu.h>
#endif
#endif
#if defined(BOTAN_TARGET_CPU_IS_X86_FAMILY)
#if defined(BOTAN_BUILD_COMPILER_IS_MSVC)
#include <intrin.h>
#define X86_CPUID(type, out) do { __cpuid((int*)out, type); } while(0)
#define X86_CPUID_SUBLEVEL(type, level, out) do { __cpuidex((int*)out, type, level); } while(0)
#elif defined(BOTAN_BUILD_COMPILER_IS_INTEL)
#include <ia32intrin.h>
#define X86_CPUID(type, out) do { __cpuid(out, type); } while(0)
#define X86_CPUID_SUBLEVEL(type, level, out) do { __cpuidex((int*)out, type, level); } while(0)
#elif defined(BOTAN_TARGET_ARCH_IS_X86_64) && defined(BOTAN_USE_GCC_INLINE_ASM)
#define X86_CPUID(type, out) \
asm("cpuid\n\t" : "=a" (out[0]), "=b" (out[1]), "=c" (out[2]), "=d" (out[3]) \
: "0" (type))
#define X86_CPUID_SUBLEVEL(type, level, out) \
asm("cpuid\n\t" : "=a" (out[0]), "=b" (out[1]), "=c" (out[2]), "=d" (out[3]) \
: "0" (type), "2" (level))
#elif defined(BOTAN_BUILD_COMPILER_IS_GCC) || defined(BOTAN_BUILD_COMPILER_IS_CLANG)
#include <cpuid.h>
#define X86_CPUID(type, out) do { __get_cpuid(type, out, out+1, out+2, out+3); } while(0)
#define X86_CPUID_SUBLEVEL(type, level, out) \
do { __cpuid_count(type, level, out[0], out[1], out[2], out[3]); } while(0)
#else
#warning "No way of calling cpuid for this compiler"
#define X86_CPUID(type, out) do { clear_mem(out, 4); } while(0)
#define X86_CPUID_SUBLEVEL(type, level, out) do { clear_mem(out, 4); } while(0)
#endif
#endif
namespace Botan {
u64bit CPUID::g_x86_processor_flags[2] = { 0, 0 };
size_t CPUID::g_cache_line_size = 0;
bool CPUID::g_altivec_capable = false;
bool CPUID::g_initialized = false;
namespace {
#if defined(BOTAN_TARGET_CPU_IS_PPC_FAMILY)
bool altivec_check_sysctl()
{
#if defined(BOTAN_TARGET_OS_IS_DARWIN) || defined(BOTAN_TARGET_OS_IS_OPENBSD)
#if defined(BOTAN_TARGET_OS_IS_OPENBSD)
int sels[2] = { CTL_MACHDEP, CPU_ALTIVEC };
#else
// From Apple's docs
int sels[2] = { CTL_HW, HW_VECTORUNIT };
#endif
int vector_type = 0;
size_t length = sizeof(vector_type);
int error = sysctl(sels, 2, &vector_type, &length, NULL, 0);
if(error == 0 && vector_type > 0)
return true;
#endif
return false;
}
bool altivec_check_pvr_emul()
{
bool altivec_capable = false;
#if defined(BOTAN_TARGET_OS_IS_LINUX) || defined(BOTAN_TARGET_OS_IS_NETBSD)
/*
On PowerPC, MSR 287 is PVR, the Processor Version Number
Normally it is only accessible to ring 0, but Linux and NetBSD
(others, too, maybe?) will trap and emulate it for us.
PVR identifiers for various AltiVec enabled CPUs. Taken from
PearPC and Linux sources, mostly.
*/
const u16bit PVR_G4_7400 = 0x000C;
const u16bit PVR_G5_970 = 0x0039;
const u16bit PVR_G5_970FX = 0x003C;
const u16bit PVR_G5_970MP = 0x0044;
const u16bit PVR_G5_970GX = 0x0045;
const u16bit PVR_POWER6 = 0x003E;
const u16bit PVR_POWER7 = 0x003F;
const u16bit PVR_POWER8 = 0x004B;
const u16bit PVR_CELL_PPU = 0x0070;
// Motorola produced G4s with PVR 0x800[0123C] (at least)
const u16bit PVR_G4_74xx_24 = 0x800;
u32bit pvr = 0;
asm volatile("mfspr %0, 287" : "=r" (pvr));
// Top 16 bit suffice to identify model
pvr >>= 16;
altivec_capable |= (pvr == PVR_G4_7400);
altivec_capable |= ((pvr >> 4) == PVR_G4_74xx_24);
altivec_capable |= (pvr == PVR_G5_970);
altivec_capable |= (pvr == PVR_G5_970FX);
altivec_capable |= (pvr == PVR_G5_970MP);
altivec_capable |= (pvr == PVR_G5_970GX);
altivec_capable |= (pvr == PVR_POWER6);
altivec_capable |= (pvr == PVR_POWER7);
altivec_capable |= (pvr == PVR_POWER8);
altivec_capable |= (pvr == PVR_CELL_PPU);
#endif
return altivec_capable;
}
#endif
}
void CPUID::print(std::ostream& o)
{
o << "CPUID flags: ";
#define CPUID_PRINT(flag) do { if(has_##flag()) o << #flag << " "; } while(0)
CPUID_PRINT(sse2);
CPUID_PRINT(ssse3);
CPUID_PRINT(sse41);
CPUID_PRINT(sse42);
CPUID_PRINT(avx2);
CPUID_PRINT(avx512f);
CPUID_PRINT(altivec);
CPUID_PRINT(rdtsc);
CPUID_PRINT(bmi2);
CPUID_PRINT(clmul);
CPUID_PRINT(aes_ni);
CPUID_PRINT(rdrand);
CPUID_PRINT(rdseed);
CPUID_PRINT(intel_sha);
CPUID_PRINT(adx);
#undef CPUID_PRINT
o << "\n";
}
void CPUID::initialize()
{
if(g_initialized)
return;
#if defined(BOTAN_TARGET_CPU_IS_PPC_FAMILY)
if(altivec_check_sysctl() || altivec_check_pvr_emul())
g_altivec_capable = true;
#endif
#if defined(BOTAN_TARGET_CPU_IS_X86_FAMILY)
const u32bit INTEL_CPUID[3] = { 0x756E6547, 0x6C65746E, 0x49656E69 };
const u32bit AMD_CPUID[3] = { 0x68747541, 0x444D4163, 0x69746E65 };
u32bit cpuid[4] = { 0 };
X86_CPUID(0, cpuid);
const u32bit max_supported_sublevel = cpuid[0];
if(max_supported_sublevel == 0)
return;
const bool is_intel = same_mem(cpuid + 1, INTEL_CPUID, 3);
const bool is_amd = same_mem(cpuid + 1, AMD_CPUID, 3);
X86_CPUID(1, cpuid);
g_x86_processor_flags[0] = (static_cast<u64bit>(cpuid[2]) << 32) | cpuid[3];
if(is_intel)
g_cache_line_size = 8 * get_byte(2, cpuid[1]);
if(max_supported_sublevel >= 7)
{
clear_mem(cpuid, 4);
X86_CPUID_SUBLEVEL(7, 0, cpuid);
g_x86_processor_flags[1] = (static_cast<u64bit>(cpuid[2]) << 32) | cpuid[1];
}
if(is_amd)
{
X86_CPUID(0x80000005, cpuid);
g_cache_line_size = get_byte(3, cpuid[2]);
}
#endif
#if defined(BOTAN_TARGET_ARCH_IS_X86_64)
/*
* If we don't have access to CPUID, we can still safely assume that
* any x86-64 processor has SSE2 and RDTSC
*/
if(g_x86_processor_flags[0] == 0)
g_x86_processor_flags[0] = (1 << CPUID_SSE2_BIT) | (1 << CPUID_RDTSC_BIT);
#endif
g_initialized = true;
}
}
<|endoftext|> |
<commit_before>/*
This file is part of KAddressBook.
Copyright (c) 2002 Mike Pilone <mpilone@slac.com>
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.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <qlayout.h>
#include <qlabel.h>
#include <qtooltip.h>
#include <qpushbutton.h>
#include <qcheckbox.h>
#include <qstring.h>
#include <qlistbox.h>
#include <qlistview.h>
#include <qbuttongroup.h>
#include <kbuttonbox.h>
#include <klistview.h>
#include <kapplication.h>
#include <kconfig.h>
#include <klineedit.h>
#include <kcombobox.h>
#include <klocale.h>
#include <kdebug.h>
#include <kiconloader.h>
#include <kabc/phonenumber.h>
#include "typecombo.h"
#include "phoneeditwidget.h"
PhoneEditWidget::PhoneEditWidget( QWidget *parent, const char *name )
: QWidget( parent, name )
{
QGridLayout *layout = new QGridLayout( this, 5, 2 );
layout->setSpacing( KDialog::spacingHint() );
mPrefCombo = new PhoneTypeCombo( mPhoneList, this );
mPrefEdit = new KLineEdit( this );
mPrefEdit->setMinimumWidth( mPrefEdit->sizeHint().width() * 1.5 );
mPrefCombo->setLineEdit( mPrefEdit );
layout->addWidget( mPrefCombo, 0, 0 );
layout->addWidget( mPrefEdit, 0, 1 );
mSecondCombo = new PhoneTypeCombo( mPhoneList, this );
mSecondEdit = new KLineEdit( this );
mSecondCombo->setLineEdit( mSecondEdit );
layout->addWidget( mSecondCombo, 1, 0 );
layout->addWidget( mSecondEdit, 1, 1 );
mThirdCombo = new PhoneTypeCombo( mPhoneList, this );
mThirdEdit = new KLineEdit( this );
mThirdCombo->setLineEdit( mThirdEdit );
layout->addWidget( mThirdCombo, 2, 0 );
layout->addWidget( mThirdEdit, 2, 1 );
mFourthCombo = new PhoneTypeCombo( mPhoneList, this );
mFourthEdit = new KLineEdit( this );
mFourthCombo->setLineEdit( mFourthEdit );
layout->addWidget( mFourthCombo, 3, 0 );
layout->addWidget( mFourthEdit, 3, 1 );
// Four numbers don't fit in the current dialog
mFourthCombo->hide();
mFourthEdit->hide();
QPushButton *editButton = new QPushButton( i18n( "Edit Phone Numbers..." ),
this );
layout->addMultiCellWidget( editButton, 4, 4, 0, 1 );
connect( mPrefEdit, SIGNAL( textChanged( const QString& ) ),
SLOT( slotPrefEditChanged() ) );
connect( mSecondEdit, SIGNAL( textChanged( const QString& ) ),
SLOT( slotSecondEditChanged() ) );
connect( mThirdEdit, SIGNAL( textChanged( const QString& ) ),
SLOT( slotThirdEditChanged() ) );
connect( mFourthEdit, SIGNAL( textChanged( const QString& ) ),
SLOT( slotFourthEditChanged() ) );
connect( editButton, SIGNAL( clicked() ), SLOT( edit() ) );
connect( mPrefCombo, SIGNAL( activated( int ) ),
SLOT( updatePrefEdit() ) );
connect( mSecondCombo, SIGNAL( activated( int ) ),
SLOT( updateSecondEdit() ) );
connect( mThirdCombo, SIGNAL( activated( int ) ),
SLOT( updateThirdEdit() ) );
connect( mFourthCombo, SIGNAL( activated( int ) ),
SLOT( updateFourthEdit() ) );
}
PhoneEditWidget::~PhoneEditWidget()
{
}
void PhoneEditWidget::setPhoneNumbers( const KABC::PhoneNumber::List &list )
{
mPhoneList.clear();
// Insert types for existing numbers.
mPrefCombo->insertTypeList( list );
QValueList<int> defaultTypes;
defaultTypes << KABC::PhoneNumber::Home;
defaultTypes << KABC::PhoneNumber::Work;
defaultTypes << KABC::PhoneNumber::Cell;
defaultTypes << ( KABC::PhoneNumber::Work | KABC::PhoneNumber::Fax );
defaultTypes << ( KABC::PhoneNumber::Home | KABC::PhoneNumber::Fax );
// Insert default types.
// Doing this for mPrefCombo is enough because the list is shared by all
// combos.
QValueList<int>::ConstIterator it;
for( it = defaultTypes.begin(); it != defaultTypes.end(); ++it ) {
if ( !mPrefCombo->hasType( *it ) )
mPrefCombo->insertType( list, *it, PhoneNumber( "", *it ) );
}
updateCombos();
mPrefCombo->selectType( defaultTypes[ 0 ] );
mSecondCombo->selectType( defaultTypes[ 1 ] );
mThirdCombo->selectType( defaultTypes[ 2 ] );
mFourthCombo->selectType( defaultTypes[ 3 ] );
updateLineEdits();
}
void PhoneEditWidget::updateLineEdits()
{
updatePrefEdit();
updateSecondEdit();
updateThirdEdit();
updateFourthEdit();
}
void PhoneEditWidget::updateCombos()
{
mPrefCombo->updateTypes();
mSecondCombo->updateTypes();
mThirdCombo->updateTypes();
mFourthCombo->updateTypes();
}
KABC::PhoneNumber::List PhoneEditWidget::phoneNumbers()
{
KABC::PhoneNumber::List retList;
KABC::PhoneNumber::List::Iterator it;
for ( it = mPhoneList.begin(); it != mPhoneList.end(); ++it )
if ( !(*it).number().isEmpty() )
retList.append( *it );
return retList;
}
void PhoneEditWidget::edit()
{
PhoneEditDialog dlg( mPhoneList, this );
if ( dlg.exec() ) {
if ( dlg.changed() ) {
mPhoneList = dlg.phoneNumbers();
updateCombos();
emit modified();
}
}
}
void PhoneEditWidget::updatePrefEdit()
{
updateEdit( mPrefCombo );
}
void PhoneEditWidget::updateSecondEdit()
{
updateEdit( mSecondCombo );
}
void PhoneEditWidget::updateThirdEdit()
{
updateEdit( mThirdCombo );
}
void PhoneEditWidget::updateFourthEdit()
{
updateEdit( mFourthCombo );
}
void PhoneEditWidget::updateEdit( PhoneTypeCombo *combo )
{
QLineEdit *edit = combo->lineEdit();
if ( !edit )
return;
#if 0
if ( edit == mPrefEdit ) kdDebug(5720) << " prefEdit" << endl;
if ( edit == mSecondEdit ) kdDebug(5720) << " secondEdit" << endl;
if ( edit == mThirdEdit ) kdDebug(5720) << " thirdEdit" << endl;
if ( edit == mFourthEdit ) kdDebug(5720) << " fourthEdit" << endl;
#endif
PhoneNumber::List::Iterator it = combo->selectedElement();
if ( it != mPhoneList.end() ) {
edit->setText( (*it).number() );
} else {
kdDebug(5720) << "PhoneEditWidget::updateEdit(): no selected element" << endl;
}
}
void PhoneEditWidget::slotPrefEditChanged()
{
updatePhoneNumber( mPrefCombo );
}
void PhoneEditWidget::slotSecondEditChanged()
{
updatePhoneNumber( mSecondCombo );
}
void PhoneEditWidget::slotThirdEditChanged()
{
updatePhoneNumber( mThirdCombo );
}
void PhoneEditWidget::slotFourthEditChanged()
{
updatePhoneNumber( mFourthCombo );
}
void PhoneEditWidget::updatePhoneNumber( PhoneTypeCombo *combo )
{
QLineEdit *edit = combo->lineEdit();
if ( !edit ) return;
PhoneNumber::List::Iterator it = combo->selectedElement();
if ( it != mPhoneList.end() ) {
(*it).setNumber( edit->text() );
} else {
kdDebug(5720) << "PhoneEditWidget::updatePhoneNumber(): no selected element"
<< endl;
}
updateOtherEdit( combo, mPrefCombo );
updateOtherEdit( combo, mSecondCombo );
updateOtherEdit( combo, mThirdCombo );
updateOtherEdit( combo, mFourthCombo );
emit modified();
}
void PhoneEditWidget::updateOtherEdit( PhoneTypeCombo *combo, PhoneTypeCombo *otherCombo )
{
if ( combo == otherCombo ) return;
if ( combo->currentItem() == otherCombo->currentItem() ) {
updateEdit( otherCombo );
}
}
///////////////////////////////////////////
// PhoneEditDialog
class PhoneViewItem : public QListViewItem
{
public:
PhoneViewItem( QListView *parent, const KABC::PhoneNumber &number );
void setPhoneNumber( const KABC::PhoneNumber &number )
{
mPhoneNumber = number;
makeText();
}
QString key() { return mPhoneNumber.id(); }
QString country() { return ""; }
QString region() { return ""; }
QString number() { return ""; }
KABC::PhoneNumber phoneNumber() { return mPhoneNumber; }
private:
void makeText();
KABC::PhoneNumber mPhoneNumber;
};
PhoneViewItem::PhoneViewItem( QListView *parent, const KABC::PhoneNumber &number )
: QListViewItem( parent ), mPhoneNumber( number )
{
makeText();
}
void PhoneViewItem::makeText()
{
/**
* Will be used in future versions of kaddressbook/libkabc
setText( 0, mPhoneNumber.country() );
setText( 1, mPhoneNumber.region() );
setText( 2, mPhoneNumber.number() );
setText( 3, mPhoneNumber.typeLabel() );
*/
setText( 0, mPhoneNumber.number() );
setText( 1, mPhoneNumber.typeLabel() );
}
PhoneEditDialog::PhoneEditDialog( const KABC::PhoneNumber::List &list, QWidget *parent, const char *name )
: KDialogBase( KDialogBase::Plain, i18n( "Edit Phone Numbers" ),
KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok,
parent, name, true)
{
mPhoneNumberList = list;
QWidget *page = plainPage();
QGridLayout *layout = new QGridLayout( page, 1, 2 );
layout->setSpacing( spacingHint() );
mListView = new KListView( page );
mListView->setAllColumnsShowFocus( true );
mListView->addColumn( i18n( "Number" ) );
mListView->addColumn( i18n( "Type" ) );
KButtonBox *buttonBox = new KButtonBox( page, Vertical );
buttonBox->addButton( i18n( "&Add..." ), this, SLOT( slotAddPhoneNumber() ) );
mEditButton = buttonBox->addButton( i18n( "&Edit..." ), this, SLOT( slotEditPhoneNumber() ) );
mEditButton->setEnabled( false );
mRemoveButton = buttonBox->addButton( i18n( "&Remove" ), this, SLOT( slotRemovePhoneNumber() ) );
mRemoveButton->setEnabled( false );
buttonBox->layout();
layout->addWidget( mListView, 0, 0 );
layout->addWidget( buttonBox, 0, 1 );
connect( mListView, SIGNAL(selectionChanged()), SLOT(slotSelectionChanged()) );
connect( mListView, SIGNAL(doubleClicked( QListViewItem *, const QPoint &, int )), this, SLOT( slotEditPhoneNumber()));
KABC::PhoneNumber::List::Iterator it;
for ( it = mPhoneNumberList.begin(); it != mPhoneNumberList.end(); ++it )
new PhoneViewItem( mListView, *it );
mChanged = false;
}
PhoneEditDialog::~PhoneEditDialog()
{
}
void PhoneEditDialog::slotAddPhoneNumber()
{
KABC::PhoneNumber tmp( "", 0 );
PhoneTypeDialog dlg( tmp, this );
if ( dlg.exec() ) {
KABC::PhoneNumber phoneNumber = dlg.phoneNumber();
mPhoneNumberList.append( phoneNumber );
new PhoneViewItem( mListView, phoneNumber );
mChanged = true;
}
}
void PhoneEditDialog::slotRemovePhoneNumber()
{
PhoneViewItem *item = static_cast<PhoneViewItem*>( mListView->currentItem() );
if ( !item )
return;
mPhoneNumberList.remove( item->phoneNumber() );
QListViewItem *currItem = mListView->currentItem();
mListView->takeItem( currItem );
delete currItem;
mChanged = true;
}
void PhoneEditDialog::slotEditPhoneNumber()
{
PhoneViewItem *item = static_cast<PhoneViewItem*>( mListView->currentItem() );
if ( !item )
return;
PhoneTypeDialog dlg( item->phoneNumber(), this );
if ( dlg.exec() ) {
slotRemovePhoneNumber();
KABC::PhoneNumber phoneNumber = dlg.phoneNumber();
mPhoneNumberList.append( phoneNumber );
new PhoneViewItem( mListView, phoneNumber );
mChanged = true;
}
}
void PhoneEditDialog::slotSelectionChanged()
{
bool state = ( mListView->currentItem() != 0 );
mRemoveButton->setEnabled( state );
mEditButton->setEnabled( state );
}
const KABC::PhoneNumber::List &PhoneEditDialog::phoneNumbers()
{
return mPhoneNumberList;
}
bool PhoneEditDialog::changed() const
{
return mChanged;
}
///////////////////////////////////////////
// PhoneTypeDialog
PhoneTypeDialog::PhoneTypeDialog( const KABC::PhoneNumber &phoneNumber,
QWidget *parent, const char *name)
: KDialogBase( KDialogBase::Plain, i18n( "Edit Phone Number" ),
KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok,
parent, name, true), mPhoneNumber( phoneNumber )
{
QWidget *page = plainPage();
QLabel *label = 0;
QGridLayout *layout = new QGridLayout( page, 3, 2, marginHint(), spacingHint() );
label = new QLabel( i18n( "Number:" ), page );
layout->addWidget( label, 0, 0 );
mNumber = new KLineEdit( page );
layout->addWidget( mNumber, 0, 1 );
mPreferredBox = new QCheckBox( i18n( "This is the preferred phone number" ), page );
layout->addMultiCellWidget( mPreferredBox, 1, 1, 0, 1 );
mGroup = new QButtonGroup( 2, Horizontal, i18n( "Types" ), page );
layout->addMultiCellWidget( mGroup, 2, 2, 0, 1 );
// fill widgets
mNumber->setText( mPhoneNumber.number() );
mTypeList = KABC::PhoneNumber::typeList();
mTypeList.remove( KABC::PhoneNumber::Pref );
KABC::PhoneNumber::TypeList::Iterator it;
for ( it = mTypeList.begin(); it != mTypeList.end(); ++it )
new QCheckBox( KABC::PhoneNumber::typeLabel( *it ), mGroup );
for ( int i = 0; i < mGroup->count(); ++i ) {
int type = mPhoneNumber.type();
QCheckBox *box = (QCheckBox*)mGroup->find( i );
box->setChecked( type & mTypeList[ i ] );
}
mPreferredBox->setChecked( mPhoneNumber.type() & KABC::PhoneNumber::Pref );
}
KABC::PhoneNumber PhoneTypeDialog::phoneNumber()
{
mPhoneNumber.setNumber( mNumber->text() );
int type = 0;
for ( int i = 0; i < mGroup->count(); ++i ) {
QCheckBox *box = (QCheckBox*)mGroup->find( i );
if ( box->isChecked() )
type += mTypeList[ i ];
}
if ( mPreferredBox->isChecked() )
mPhoneNumber.setType( type | KABC::PhoneNumber::Pref );
else
mPhoneNumber.setType( type & ~KABC::PhoneNumber::Pref );
return mPhoneNumber;
}
#include "phoneeditwidget.moc"
<commit_msg>shhh!<commit_after>/*
This file is part of KAddressBook.
Copyright (c) 2002 Mike Pilone <mpilone@slac.com>
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.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <qlayout.h>
#include <qlabel.h>
#include <qtooltip.h>
#include <qpushbutton.h>
#include <qcheckbox.h>
#include <qstring.h>
#include <qlistbox.h>
#include <qlistview.h>
#include <qbuttongroup.h>
#include <kbuttonbox.h>
#include <klistview.h>
#include <kapplication.h>
#include <kconfig.h>
#include <klineedit.h>
#include <kcombobox.h>
#include <klocale.h>
#include <kdebug.h>
#include <kiconloader.h>
#include <kabc/phonenumber.h>
#include "typecombo.h"
#include "phoneeditwidget.h"
PhoneEditWidget::PhoneEditWidget( QWidget *parent, const char *name )
: QWidget( parent, name )
{
QGridLayout *layout = new QGridLayout( this, 5, 2 );
layout->setSpacing( KDialog::spacingHint() );
mPrefCombo = new PhoneTypeCombo( mPhoneList, this );
mPrefEdit = new KLineEdit( this );
mPrefEdit->setMinimumWidth( int(mPrefEdit->sizeHint().width() * 1.5) );
mPrefCombo->setLineEdit( mPrefEdit );
layout->addWidget( mPrefCombo, 0, 0 );
layout->addWidget( mPrefEdit, 0, 1 );
mSecondCombo = new PhoneTypeCombo( mPhoneList, this );
mSecondEdit = new KLineEdit( this );
mSecondCombo->setLineEdit( mSecondEdit );
layout->addWidget( mSecondCombo, 1, 0 );
layout->addWidget( mSecondEdit, 1, 1 );
mThirdCombo = new PhoneTypeCombo( mPhoneList, this );
mThirdEdit = new KLineEdit( this );
mThirdCombo->setLineEdit( mThirdEdit );
layout->addWidget( mThirdCombo, 2, 0 );
layout->addWidget( mThirdEdit, 2, 1 );
mFourthCombo = new PhoneTypeCombo( mPhoneList, this );
mFourthEdit = new KLineEdit( this );
mFourthCombo->setLineEdit( mFourthEdit );
layout->addWidget( mFourthCombo, 3, 0 );
layout->addWidget( mFourthEdit, 3, 1 );
// Four numbers don't fit in the current dialog
mFourthCombo->hide();
mFourthEdit->hide();
QPushButton *editButton = new QPushButton( i18n( "Edit Phone Numbers..." ),
this );
layout->addMultiCellWidget( editButton, 4, 4, 0, 1 );
connect( mPrefEdit, SIGNAL( textChanged( const QString& ) ),
SLOT( slotPrefEditChanged() ) );
connect( mSecondEdit, SIGNAL( textChanged( const QString& ) ),
SLOT( slotSecondEditChanged() ) );
connect( mThirdEdit, SIGNAL( textChanged( const QString& ) ),
SLOT( slotThirdEditChanged() ) );
connect( mFourthEdit, SIGNAL( textChanged( const QString& ) ),
SLOT( slotFourthEditChanged() ) );
connect( editButton, SIGNAL( clicked() ), SLOT( edit() ) );
connect( mPrefCombo, SIGNAL( activated( int ) ),
SLOT( updatePrefEdit() ) );
connect( mSecondCombo, SIGNAL( activated( int ) ),
SLOT( updateSecondEdit() ) );
connect( mThirdCombo, SIGNAL( activated( int ) ),
SLOT( updateThirdEdit() ) );
connect( mFourthCombo, SIGNAL( activated( int ) ),
SLOT( updateFourthEdit() ) );
}
PhoneEditWidget::~PhoneEditWidget()
{
}
void PhoneEditWidget::setPhoneNumbers( const KABC::PhoneNumber::List &list )
{
mPhoneList.clear();
// Insert types for existing numbers.
mPrefCombo->insertTypeList( list );
QValueList<int> defaultTypes;
defaultTypes << KABC::PhoneNumber::Home;
defaultTypes << KABC::PhoneNumber::Work;
defaultTypes << KABC::PhoneNumber::Cell;
defaultTypes << ( KABC::PhoneNumber::Work | KABC::PhoneNumber::Fax );
defaultTypes << ( KABC::PhoneNumber::Home | KABC::PhoneNumber::Fax );
// Insert default types.
// Doing this for mPrefCombo is enough because the list is shared by all
// combos.
QValueList<int>::ConstIterator it;
for( it = defaultTypes.begin(); it != defaultTypes.end(); ++it ) {
if ( !mPrefCombo->hasType( *it ) )
mPrefCombo->insertType( list, *it, PhoneNumber( "", *it ) );
}
updateCombos();
mPrefCombo->selectType( defaultTypes[ 0 ] );
mSecondCombo->selectType( defaultTypes[ 1 ] );
mThirdCombo->selectType( defaultTypes[ 2 ] );
mFourthCombo->selectType( defaultTypes[ 3 ] );
updateLineEdits();
}
void PhoneEditWidget::updateLineEdits()
{
updatePrefEdit();
updateSecondEdit();
updateThirdEdit();
updateFourthEdit();
}
void PhoneEditWidget::updateCombos()
{
mPrefCombo->updateTypes();
mSecondCombo->updateTypes();
mThirdCombo->updateTypes();
mFourthCombo->updateTypes();
}
KABC::PhoneNumber::List PhoneEditWidget::phoneNumbers()
{
KABC::PhoneNumber::List retList;
KABC::PhoneNumber::List::Iterator it;
for ( it = mPhoneList.begin(); it != mPhoneList.end(); ++it )
if ( !(*it).number().isEmpty() )
retList.append( *it );
return retList;
}
void PhoneEditWidget::edit()
{
PhoneEditDialog dlg( mPhoneList, this );
if ( dlg.exec() ) {
if ( dlg.changed() ) {
mPhoneList = dlg.phoneNumbers();
updateCombos();
emit modified();
}
}
}
void PhoneEditWidget::updatePrefEdit()
{
updateEdit( mPrefCombo );
}
void PhoneEditWidget::updateSecondEdit()
{
updateEdit( mSecondCombo );
}
void PhoneEditWidget::updateThirdEdit()
{
updateEdit( mThirdCombo );
}
void PhoneEditWidget::updateFourthEdit()
{
updateEdit( mFourthCombo );
}
void PhoneEditWidget::updateEdit( PhoneTypeCombo *combo )
{
QLineEdit *edit = combo->lineEdit();
if ( !edit )
return;
#if 0
if ( edit == mPrefEdit ) kdDebug(5720) << " prefEdit" << endl;
if ( edit == mSecondEdit ) kdDebug(5720) << " secondEdit" << endl;
if ( edit == mThirdEdit ) kdDebug(5720) << " thirdEdit" << endl;
if ( edit == mFourthEdit ) kdDebug(5720) << " fourthEdit" << endl;
#endif
PhoneNumber::List::Iterator it = combo->selectedElement();
if ( it != mPhoneList.end() ) {
edit->setText( (*it).number() );
} else {
kdDebug(5720) << "PhoneEditWidget::updateEdit(): no selected element" << endl;
}
}
void PhoneEditWidget::slotPrefEditChanged()
{
updatePhoneNumber( mPrefCombo );
}
void PhoneEditWidget::slotSecondEditChanged()
{
updatePhoneNumber( mSecondCombo );
}
void PhoneEditWidget::slotThirdEditChanged()
{
updatePhoneNumber( mThirdCombo );
}
void PhoneEditWidget::slotFourthEditChanged()
{
updatePhoneNumber( mFourthCombo );
}
void PhoneEditWidget::updatePhoneNumber( PhoneTypeCombo *combo )
{
QLineEdit *edit = combo->lineEdit();
if ( !edit ) return;
PhoneNumber::List::Iterator it = combo->selectedElement();
if ( it != mPhoneList.end() ) {
(*it).setNumber( edit->text() );
} else {
kdDebug(5720) << "PhoneEditWidget::updatePhoneNumber(): no selected element"
<< endl;
}
updateOtherEdit( combo, mPrefCombo );
updateOtherEdit( combo, mSecondCombo );
updateOtherEdit( combo, mThirdCombo );
updateOtherEdit( combo, mFourthCombo );
emit modified();
}
void PhoneEditWidget::updateOtherEdit( PhoneTypeCombo *combo, PhoneTypeCombo *otherCombo )
{
if ( combo == otherCombo ) return;
if ( combo->currentItem() == otherCombo->currentItem() ) {
updateEdit( otherCombo );
}
}
///////////////////////////////////////////
// PhoneEditDialog
class PhoneViewItem : public QListViewItem
{
public:
PhoneViewItem( QListView *parent, const KABC::PhoneNumber &number );
void setPhoneNumber( const KABC::PhoneNumber &number )
{
mPhoneNumber = number;
makeText();
}
QString key() { return mPhoneNumber.id(); }
QString country() { return ""; }
QString region() { return ""; }
QString number() { return ""; }
KABC::PhoneNumber phoneNumber() { return mPhoneNumber; }
private:
void makeText();
KABC::PhoneNumber mPhoneNumber;
};
PhoneViewItem::PhoneViewItem( QListView *parent, const KABC::PhoneNumber &number )
: QListViewItem( parent ), mPhoneNumber( number )
{
makeText();
}
void PhoneViewItem::makeText()
{
/**
* Will be used in future versions of kaddressbook/libkabc
setText( 0, mPhoneNumber.country() );
setText( 1, mPhoneNumber.region() );
setText( 2, mPhoneNumber.number() );
setText( 3, mPhoneNumber.typeLabel() );
*/
setText( 0, mPhoneNumber.number() );
setText( 1, mPhoneNumber.typeLabel() );
}
PhoneEditDialog::PhoneEditDialog( const KABC::PhoneNumber::List &list, QWidget *parent, const char *name )
: KDialogBase( KDialogBase::Plain, i18n( "Edit Phone Numbers" ),
KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok,
parent, name, true)
{
mPhoneNumberList = list;
QWidget *page = plainPage();
QGridLayout *layout = new QGridLayout( page, 1, 2 );
layout->setSpacing( spacingHint() );
mListView = new KListView( page );
mListView->setAllColumnsShowFocus( true );
mListView->addColumn( i18n( "Number" ) );
mListView->addColumn( i18n( "Type" ) );
KButtonBox *buttonBox = new KButtonBox( page, Vertical );
buttonBox->addButton( i18n( "&Add..." ), this, SLOT( slotAddPhoneNumber() ) );
mEditButton = buttonBox->addButton( i18n( "&Edit..." ), this, SLOT( slotEditPhoneNumber() ) );
mEditButton->setEnabled( false );
mRemoveButton = buttonBox->addButton( i18n( "&Remove" ), this, SLOT( slotRemovePhoneNumber() ) );
mRemoveButton->setEnabled( false );
buttonBox->layout();
layout->addWidget( mListView, 0, 0 );
layout->addWidget( buttonBox, 0, 1 );
connect( mListView, SIGNAL(selectionChanged()), SLOT(slotSelectionChanged()) );
connect( mListView, SIGNAL(doubleClicked( QListViewItem *, const QPoint &, int )), this, SLOT( slotEditPhoneNumber()));
KABC::PhoneNumber::List::Iterator it;
for ( it = mPhoneNumberList.begin(); it != mPhoneNumberList.end(); ++it )
new PhoneViewItem( mListView, *it );
mChanged = false;
}
PhoneEditDialog::~PhoneEditDialog()
{
}
void PhoneEditDialog::slotAddPhoneNumber()
{
KABC::PhoneNumber tmp( "", 0 );
PhoneTypeDialog dlg( tmp, this );
if ( dlg.exec() ) {
KABC::PhoneNumber phoneNumber = dlg.phoneNumber();
mPhoneNumberList.append( phoneNumber );
new PhoneViewItem( mListView, phoneNumber );
mChanged = true;
}
}
void PhoneEditDialog::slotRemovePhoneNumber()
{
PhoneViewItem *item = static_cast<PhoneViewItem*>( mListView->currentItem() );
if ( !item )
return;
mPhoneNumberList.remove( item->phoneNumber() );
QListViewItem *currItem = mListView->currentItem();
mListView->takeItem( currItem );
delete currItem;
mChanged = true;
}
void PhoneEditDialog::slotEditPhoneNumber()
{
PhoneViewItem *item = static_cast<PhoneViewItem*>( mListView->currentItem() );
if ( !item )
return;
PhoneTypeDialog dlg( item->phoneNumber(), this );
if ( dlg.exec() ) {
slotRemovePhoneNumber();
KABC::PhoneNumber phoneNumber = dlg.phoneNumber();
mPhoneNumberList.append( phoneNumber );
new PhoneViewItem( mListView, phoneNumber );
mChanged = true;
}
}
void PhoneEditDialog::slotSelectionChanged()
{
bool state = ( mListView->currentItem() != 0 );
mRemoveButton->setEnabled( state );
mEditButton->setEnabled( state );
}
const KABC::PhoneNumber::List &PhoneEditDialog::phoneNumbers()
{
return mPhoneNumberList;
}
bool PhoneEditDialog::changed() const
{
return mChanged;
}
///////////////////////////////////////////
// PhoneTypeDialog
PhoneTypeDialog::PhoneTypeDialog( const KABC::PhoneNumber &phoneNumber,
QWidget *parent, const char *name)
: KDialogBase( KDialogBase::Plain, i18n( "Edit Phone Number" ),
KDialogBase::Ok | KDialogBase::Cancel, KDialogBase::Ok,
parent, name, true), mPhoneNumber( phoneNumber )
{
QWidget *page = plainPage();
QLabel *label = 0;
QGridLayout *layout = new QGridLayout( page, 3, 2, marginHint(), spacingHint() );
label = new QLabel( i18n( "Number:" ), page );
layout->addWidget( label, 0, 0 );
mNumber = new KLineEdit( page );
layout->addWidget( mNumber, 0, 1 );
mPreferredBox = new QCheckBox( i18n( "This is the preferred phone number" ), page );
layout->addMultiCellWidget( mPreferredBox, 1, 1, 0, 1 );
mGroup = new QButtonGroup( 2, Horizontal, i18n( "Types" ), page );
layout->addMultiCellWidget( mGroup, 2, 2, 0, 1 );
// fill widgets
mNumber->setText( mPhoneNumber.number() );
mTypeList = KABC::PhoneNumber::typeList();
mTypeList.remove( KABC::PhoneNumber::Pref );
KABC::PhoneNumber::TypeList::Iterator it;
for ( it = mTypeList.begin(); it != mTypeList.end(); ++it )
new QCheckBox( KABC::PhoneNumber::typeLabel( *it ), mGroup );
for ( int i = 0; i < mGroup->count(); ++i ) {
int type = mPhoneNumber.type();
QCheckBox *box = (QCheckBox*)mGroup->find( i );
box->setChecked( type & mTypeList[ i ] );
}
mPreferredBox->setChecked( mPhoneNumber.type() & KABC::PhoneNumber::Pref );
}
KABC::PhoneNumber PhoneTypeDialog::phoneNumber()
{
mPhoneNumber.setNumber( mNumber->text() );
int type = 0;
for ( int i = 0; i < mGroup->count(); ++i ) {
QCheckBox *box = (QCheckBox*)mGroup->find( i );
if ( box->isChecked() )
type += mTypeList[ i ];
}
if ( mPreferredBox->isChecked() )
mPhoneNumber.setType( type | KABC::PhoneNumber::Pref );
else
mPhoneNumber.setType( type & ~KABC::PhoneNumber::Pref );
return mPhoneNumber;
}
#include "phoneeditwidget.moc"
<|endoftext|> |
<commit_before>
<commit_msg>Delete 1.cpp<commit_after><|endoftext|> |
<commit_before>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
#include <stdio.h>
#include <cmath>
#include <cblas.h>
#include <random>
#include <lapacke.h>
const double PI = 3.141592653589793238463;
const double SQRT_1_2PI = 1/sqrt(2*PI);
const double SQRT_1_2 = 1/sqrt(2);
double pdf(double z){
//if (-0.5*pow(z,2)<-704.8){printf(" pdf underflow");}
return SQRT_1_2PI*exp(-0.5*pow(z,2));
}
double lpdf(double z){
//if (-0.5*pow(z,2)<-704.8){printf(" pdf underflow");}
return log(SQRT_1_2PI) - 0.5*pow(z,2);
}
double cdf(double z){
//if (-SQRT_1_2*z>26.55){printf(" cdf underflow");}
return 0.5 * erfc(-SQRT_1_2*z);
}
extern "C" int EI(double* m, double* s, double y, int N, double* R){
double S;
double c;
double p;
for (int i=0; i<N; i++){
S = (y-m[i])/s[i];
c = cdf(S);
p = pdf(S);
R[i] = (y-m[i])*c+s[i]*p;
//printf("\nm: %f s: %f y: %f S: %f cdf: %f pdf: %f",m[i],s[i],y,S,cdf(S),pdf(S));
//TODO fix EI for values that make pdf and cdf zero
//if (R[i]==0.){printf("_ei=0 %f %f %f||%f %f %f_[ %f %f %f]\n",y,m[i],s[i],S,pdf(S),cdf(S),log(s[i]),lpdf(S),exp(log(s[i])+lpdf(S)));}
}
return 0;
}
extern "C" int lEI(double* m, double* s, double y, int N, double* R){
double S;
double c;
double p;
for (int i=0; i<N; i++){
EI(m,s,y,1,&R[i]);
//TODO this switch to log puts a kink in the curve
if (R[i]<=0.){
S = (y-m[i])/s[i];
R[i] = log(s[i])+lpdf(S);
//printf("logversion: %f\n",R[i]);
}
else{
//printf("regversion: %f %f\n",R[i], log(R[i]));
R[i] = log(R[i]);
}
}
return 0;
}
//make m draws from a multivariate Gaussian of size n where the cholesky deom of the covariance is the lower triangular matrix K
//matrix mult means the draws are down the columns of R
extern "C" int drawcov(double* K, int n, double* R, int m){
std::random_device rand_dev; // Use random_device to get a random seed.
std::mt19937 rand_engine(rand_dev()); //seed merseene twister with random number
std::normal_distribution<double> nmdist(0., 1.); //normal unit dist
for (int i=0;i<n*m;i++){
R[i] = nmdist(rand_engine);
}
cblas_dtrmm(CblasRowMajor,CblasLeft,CblasLower,CblasNoTrans,CblasNonUnit,n,m,1.,K,n,R,m);
return 0;
}
//as drawcov but for the original covariance matrix. K is overwritten.
extern "C" int drawk(double* K, int n, double* R, int m){
int j = -9;
printf("adding 10e%d diagonal to covariance in drawk\n",j);
for (int i=0; i<n; i++){
K[i*n+i]+=pow(10,j);
}
LAPACKE_dpotrf(LAPACK_ROW_MAJOR,'L',n,&K[0],n);
drawcov(&K[0],n, &R[0], m);
return 0;
}<commit_msg>step up conditioning noise with retrys<commit_after>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
#include <stdio.h>
#include <cmath>
#include <cblas.h>
#include <random>
#include <lapacke.h>
const double PI = 3.141592653589793238463;
const double SQRT_1_2PI = 1/sqrt(2*PI);
const double SQRT_1_2 = 1/sqrt(2);
double pdf(double z){
//if (-0.5*pow(z,2)<-704.8){printf(" pdf underflow");}
return SQRT_1_2PI*exp(-0.5*pow(z,2));
}
double lpdf(double z){
//if (-0.5*pow(z,2)<-704.8){printf(" pdf underflow");}
return log(SQRT_1_2PI) - 0.5*pow(z,2);
}
double cdf(double z){
//if (-SQRT_1_2*z>26.55){printf(" cdf underflow");}
return 0.5 * erfc(-SQRT_1_2*z);
}
extern "C" int EI(double* m, double* s, double y, int N, double* R){
double S;
double c;
double p;
for (int i=0; i<N; i++){
S = (y-m[i])/s[i];
c = cdf(S);
p = pdf(S);
R[i] = (y-m[i])*c+s[i]*p;
//printf("\nm: %f s: %f y: %f S: %f cdf: %f pdf: %f",m[i],s[i],y,S,cdf(S),pdf(S));
//TODO fix EI for values that make pdf and cdf zero
//if (R[i]==0.){printf("_ei=0 %f %f %f||%f %f %f_[ %f %f %f]\n",y,m[i],s[i],S,pdf(S),cdf(S),log(s[i]),lpdf(S),exp(log(s[i])+lpdf(S)));}
}
return 0;
}
extern "C" int lEI(double* m, double* s, double y, int N, double* R){
double S;
double c;
double p;
for (int i=0; i<N; i++){
EI(m,s,y,1,&R[i]);
//TODO this switch to log puts a kink in the curve
if (R[i]<=0.){
S = (y-m[i])/s[i];
R[i] = log(s[i])+lpdf(S);
//printf("logversion: %f\n",R[i]);
}
else{
//printf("regversion: %f %f\n",R[i], log(R[i]));
R[i] = log(R[i]);
}
}
return 0;
}
//make m draws from a multivariate Gaussian of size n where the cholesky deom of the covariance is the lower triangular matrix K
//matrix mult means the draws are down the columns of R
extern "C" int drawcov(double* K, int n, double* R, int m){
std::random_device rand_dev; // Use random_device to get a random seed.
std::mt19937 rand_engine(rand_dev()); //seed merseene twister with random number
std::normal_distribution<double> nmdist(0., 1.); //normal unit dist
for (int i=0;i<n*m;i++){
R[i] = nmdist(rand_engine);
}
cblas_dtrmm(CblasRowMajor,CblasLeft,CblasLower,CblasNoTrans,CblasNonUnit,n,m,1.,K,n,R,m);
return 0;
}
//as drawcov but for the original covariance matrix. K is overwritten.
extern "C" int drawk(double* K_in, int n, double* R, int m){
int j = -19;
int info = 1;
std::vector<double>K = std::vector<double>(n*n);
while (info != 0){
printf("adding 10e%d diagonal to covariance in drawk\n",j);
for (int i=0; i<n; i++){
for (int j=0; j<n; j++){
K[i*n+j]=K_in[i*n+j];
}
K[i*n+i]+=pow(10,j);
}
info = LAPACKE_dpotrf(LAPACK_ROW_MAJOR,'L',n,&K[0],n);
printf("info%d\n",info);
j+=1;
}
drawcov(&K[0],n, &R[0], m);
return 0;
}<|endoftext|> |
<commit_before>#include "disassembler.h"
#include "util.h"
#include "symtab.h"
#include <vector>
#include <cctype>
using namespace std;
enum ByteTypeGuess {
UNINITIALIZED,
UNKNOWN,
CHAR_DATA,
UNINITIALIZED_CHAR_DATA,
WORD_DATA,
UNINITIALIZED_WORD_DATA,
CODE,
};
struct program {
ByteTypeGuess byte_type_guess[65536];
char memory[65536];
bool is_labelled[65536];
string name;
string starting_address;
int length_of_program;
string first_executable_instruction;
program() {
for ( int i = 0 ; i < 65536 ; i++ ) {
byte_type_guess[i] = UNINITIALIZED;
memory[i] = 0;
is_labelled[i] = false;
}
name = "";
starting_address = "";
length_of_program = 0;
first_executable_instruction = "";
}
};
bool read_record(ifstream &ifile, string &record);
void record_to_memory(const string record, program &p);
void analyze_code_data(program &p);
void write_assembly(const program &p, ofstream &ofile);
bool disassemble(ifstream &ifile, ofstream &ofile) {
string record;
program p;
while ( read_record(ifile, record) ) {
record_to_memory(record, p);
}
status("Done reading records");
analyze_code_data(p);
status("Done analyzing program for code and data");
write_assembly(p, ofile);
status("Done writing output file");
return true;
}
string read_columns(ifstream &ifile, int col_begin, int col_end, char record_type = 'a') { // inclusive of both
string ret;
char t;
for ( int col = col_begin ; col <= col_end ; col++ ) {
t = ifile.get();
if ( t == EOF || t == '\n' ) {
string errstr;
errstr += "Unexpected end of ";
errstr += record_type;
errstr += " record";
fatal(errstr);
}
ret += t;
}
return ret;
}
string read_hex_columns(ifstream &ifile, int col_begin, int col_end, char record_type = 'a') { // inclusive of both
string ret;
ret = read_columns(ifile,col_begin,col_end,record_type);
make_upper_case(ret);
if ( !is_hex_string(ret) ) {
string errstr;
errstr += "Unexpected non-hexadecimal character found in ";
errstr += record_type;
errstr += " record";
fatal(errstr);
}
return ret;
}
bool read_record(ifstream &ifile, string &record) {
int temp_int;
string temp_str;
char t;
do {
t = ifile.get();
if ( t == EOF ) {
return false;
}
} while ( t == '\n' || t == ' ' );
record = "";
record += t;
switch (t) {
case 'H': // Header
record += read_columns(ifile,2,7,'H');
record += read_hex_columns(ifile,8,19,'H');
break;
case 'T': // Text
record += read_hex_columns(ifile,2,7,'T');
temp_str = read_hex_columns(ifile,8,9,'T');
temp_int = hex2int(temp_str);
record += temp_str;
record += read_hex_columns(ifile,10,9+2*temp_int,'T');
break;
case 'E': // End
record += read_hex_columns(ifile,2,7,'E');
break;
default:
{
string errstr = "Unknown record type ";
errstr += t;
fatal(errstr);
}
}
return true;
}
void record_to_memory(const string record, program &p) {
const char * c_record = record.c_str();
switch (*c_record) {
case 'H': // Header
if ( p.name.length() != 0 ) {
fatal("Multiple H records");
}
p.name = record.substr(1,6);
p.starting_address = record.substr(7,6);
p.length_of_program = hex2int(record.substr(13,6));
break;
case 'T': // Text
{
int text_start = hex2int(record.substr(1,6));
int bit_length = hex2int(record.substr(7,2));
for ( int i = 0 ; i < bit_length ; i++ ) {
p.memory[i+text_start] = hex2int(record.substr(9+2*i,2));
p.byte_type_guess[i+text_start] = UNKNOWN;
}
}
break;
case 'E': // End
if ( p.first_executable_instruction.length() != 0 ) {
fatal("Multiple E records");
}
p.first_executable_instruction = record.substr(1,6);
break;
default:
{
string errstr;
errstr += "Unknown record type ";
errstr += *c_record;
fatal(errstr);
}
}
}
void mark_code_data(program &p, int location, ByteTypeGuess btg) {
if ( location >= hex2int(p.starting_address) + p.length_of_program ) {
return;
}
switch (btg) {
case UNINITIALIZED:
case UNKNOWN:
break;
case CHAR_DATA:
case UNINITIALIZED_CHAR_DATA:
{
if ( p.byte_type_guess[location] != UNKNOWN &&
p.byte_type_guess[location] != UNINITIALIZED ) {
break;
}
if ( p.byte_type_guess[location] == UNINITIALIZED )
btg = UNINITIALIZED_CHAR_DATA;
p.byte_type_guess[location] = btg;
break;
}
case WORD_DATA:
case UNINITIALIZED_WORD_DATA:
{
if ( p.byte_type_guess[location] != UNKNOWN &&
p.byte_type_guess[location] != UNINITIALIZED ) {
break;
}
if ( p.byte_type_guess[location] == UNINITIALIZED )
btg = UNINITIALIZED_WORD_DATA;
p.byte_type_guess[location+0] = btg;
p.byte_type_guess[location+1] = btg;
p.byte_type_guess[location+2] = btg;
break;
}
case CODE:
{
if ( p.byte_type_guess[location] == UNINITIALIZED ) {
fatal("Attempting to use uninitialized section as code");
}
if ( p.byte_type_guess[location] == CODE ) {
break;
}
p.byte_type_guess[location+0] = btg;
p.byte_type_guess[location+1] = btg;
p.byte_type_guess[location+2] = btg;
string opcode_val = byte2hex(p.memory[location]);
string opcode;
string operand = byte2hex(p.memory[location+1])+byte2hex(p.memory[location+2]);
operand = int2hex(hex2int(operand)&0x7FFF); // remove index flag
if ( ! find_from_symtab(opcode,opcode_val) ) {
string errstr;
errstr += "Unknown opcode ";
errstr += opcode_val;
errstr += " at location ";
errstr += int2hex(location);
fatal(errstr);
}
if ( opcode == "ADD" ||
opcode == "AND" ||
opcode == "COMP" ||
opcode == "DIV" ||
opcode == "LDA" ||
opcode == "LDL" ||
opcode == "LDX" ||
opcode == "MUL" ||
opcode == "OR" ||
opcode == "STA" ||
opcode == "STL" ||
opcode == "STX" ||
opcode == "SUB" ||
opcode == "TIX" ) {
give_label(operand);
p.is_labelled[hex2int(operand)] = true;
mark_code_data(p,hex2int(operand),WORD_DATA);
}
if ( opcode == "LDCH" ||
opcode == "STCH" ) {
give_label(operand);
p.is_labelled[hex2int(operand)] = true;
mark_code_data(p,hex2int(operand),CHAR_DATA);
}
if ( opcode == "J" ||
opcode == "JEQ" ||
opcode == "JGT" ||
opcode == "JLT" ||
opcode == "JSUB" ) {
give_label(operand);
p.is_labelled[hex2int(operand)] = true;
mark_code_data(p,hex2int(operand),CODE);
}
if ( opcode != "J" &&
opcode != "RSUB" ) {
mark_code_data(p,location+3,btg);
}
break;
}
}
}
void analyze_code_data(program &p) {
if ( p.name.length() == 0 ) {
fatal("No Header record");
}
if ( p.first_executable_instruction.length() == 0 ) {
fatal("No End record");
}
initialize_symtab();
add_to_symtab("FIRST",p.first_executable_instruction);
p.is_labelled[hex2int(p.first_executable_instruction)] = true;
mark_code_data(p,hex2int(p.first_executable_instruction),CODE);
}
string asm_to_line(string label, string opcode, string operand, bool is_indexed) {
const int labellength = 8;
const int opcodelength = 6;
string ret = "";
ret += label + string(labellength-label.length(),' ');
ret += opcode + string(opcodelength-opcode.length(),' ');
ret += operand;
if ( is_indexed ) {
ret += ",X";
}
ret += '\n';
return ret;
}
void write_assembly(const program &p, ofstream &ofile) {
ofile << asm_to_line(p.name,"START",p.starting_address,false);
int start_of_program = hex2int(p.starting_address);
int end_of_program = start_of_program + p.length_of_program;
for ( int locctr = start_of_program ; locctr < end_of_program ; ) {
string label = "";
string opcode = "";
string operand = "";
bool is_indexed = false;
if ( p.is_labelled[locctr] ) {
if ( !find_from_symtab(label,int2hex(locctr)) ) {
string errstr;
errstr += "Label not created for location ";
errstr += int2hex(locctr);
error(errstr);
}
}
if ( p.byte_type_guess[locctr] == CODE ) {
if ( ! find_from_symtab(opcode,byte2hex(p.memory[locctr])) ) {
string errstr;
errstr += "Unknown opcode ";
errstr += opcode;
errstr += " at location ";
errstr += int2hex(locctr);
fatal(errstr);
}
operand = byte2hex(p.memory[locctr+1])+byte2hex(p.memory[locctr+2]);
is_indexed = (hex2int(operand)&0x8000);
operand = int2hex(hex2int(operand)&0x7FFF); // remove index flag
if ( opcode != "RD" &&
opcode != "TD" &&
opcode != "WD" &&
opcode != "RSUB" ) {
if ( !find_from_symtab(operand,operand) ) {
string errstr;
errstr += "Label not created for operand ";
errstr += operand;
error(errstr);
}
}
if ( opcode == "RSUB" ) {
operand = "";
}
locctr += 3;
} else if ( p.byte_type_guess[locctr] == CHAR_DATA ||
p.byte_type_guess[locctr] == UNKNOWN ) {
if ( p.byte_type_guess[locctr] == UNKNOWN ) {
label = "UNUSED"; // This should not happen in a well written code
}
vector<char> byte_list;
bool type_c = true;
do {
byte_list.push_back(p.memory[locctr]);
if ( !isprint(p.memory[locctr]) ) {
type_c = false;
}
locctr++;
} while ( p.byte_type_guess[locctr] == CHAR_DATA && !p.is_labelled[locctr] );
opcode = "CHAR";
operand += (type_c?"C":"X");
operand += "'";
for ( int i = 0 ; i < (int)byte_list.size() ; i++ ) {
if ( type_c ) {
operand += byte_list[i];
} else {
operand += byte2hex(byte_list[i]);
}
}
operand += "'";
} else if ( p.byte_type_guess[locctr] == WORD_DATA ) {
opcode = "WORD";
operand = int2str(
p.memory[locctr+0]*256*256+
p.memory[locctr+1]*256+
p.memory[locctr+2]
);
locctr += 3;
} else if ( p.byte_type_guess[locctr] == UNINITIALIZED_CHAR_DATA ||
p.byte_type_guess[locctr] == UNINITIALIZED ) {
opcode = "RESB";
int buf_size = 0;
do {
buf_size++;
locctr++;
} while ( (p.byte_type_guess[locctr] == UNINITIALIZED_CHAR_DATA
|| p.byte_type_guess[locctr] == UNINITIALIZED)
&& !p.is_labelled[locctr]
&& locctr < end_of_program);
if ( locctr >= end_of_program ) {
buf_size--;
}
operand = int2str(buf_size);
} else if ( p.byte_type_guess[locctr] == UNINITIALIZED_WORD_DATA ) {
opcode = "RESW";
int buf_size = 0;
do {
buf_size++;
locctr+=3;
} while ( (p.byte_type_guess[locctr] == UNINITIALIZED_WORD_DATA
|| p.byte_type_guess[locctr] == UNINITIALIZED)
&& !p.is_labelled[locctr]
&& locctr < end_of_program);
if ( locctr >= end_of_program ) {
buf_size--;
}
operand = int2str(buf_size);
} else {
fatal("Reached part of decompiler that should not be reached");
}
ofile << asm_to_line(label,opcode,operand,is_indexed);
}
ofile << asm_to_line("","END","FIRST",false);
}<commit_msg>Use as unsigned byte rather than as a signed byte<commit_after>#include "disassembler.h"
#include "util.h"
#include "symtab.h"
#include <vector>
#include <cctype>
using namespace std;
enum ByteTypeGuess {
UNINITIALIZED,
UNKNOWN,
CHAR_DATA,
UNINITIALIZED_CHAR_DATA,
WORD_DATA,
UNINITIALIZED_WORD_DATA,
CODE,
};
struct program {
ByteTypeGuess byte_type_guess[65536];
unsigned char memory[65536];
bool is_labelled[65536];
string name;
string starting_address;
int length_of_program;
string first_executable_instruction;
program() {
for ( int i = 0 ; i < 65536 ; i++ ) {
byte_type_guess[i] = UNINITIALIZED;
memory[i] = 0;
is_labelled[i] = false;
}
name = "";
starting_address = "";
length_of_program = 0;
first_executable_instruction = "";
}
};
bool read_record(ifstream &ifile, string &record);
void record_to_memory(const string record, program &p);
void analyze_code_data(program &p);
void write_assembly(const program &p, ofstream &ofile);
bool disassemble(ifstream &ifile, ofstream &ofile) {
string record;
program p;
while ( read_record(ifile, record) ) {
record_to_memory(record, p);
}
status("Done reading records");
analyze_code_data(p);
status("Done analyzing program for code and data");
write_assembly(p, ofile);
status("Done writing output file");
return true;
}
string read_columns(ifstream &ifile, int col_begin, int col_end, char record_type = 'a') { // inclusive of both
string ret;
char t;
for ( int col = col_begin ; col <= col_end ; col++ ) {
t = ifile.get();
if ( t == EOF || t == '\n' ) {
string errstr;
errstr += "Unexpected end of ";
errstr += record_type;
errstr += " record";
fatal(errstr);
}
ret += t;
}
return ret;
}
string read_hex_columns(ifstream &ifile, int col_begin, int col_end, char record_type = 'a') { // inclusive of both
string ret;
ret = read_columns(ifile,col_begin,col_end,record_type);
make_upper_case(ret);
if ( !is_hex_string(ret) ) {
string errstr;
errstr += "Unexpected non-hexadecimal character found in ";
errstr += record_type;
errstr += " record";
fatal(errstr);
}
return ret;
}
bool read_record(ifstream &ifile, string &record) {
int temp_int;
string temp_str;
char t;
do {
t = ifile.get();
if ( t == EOF ) {
return false;
}
} while ( t == '\n' || t == ' ' );
record = "";
record += t;
switch (t) {
case 'H': // Header
record += read_columns(ifile,2,7,'H');
record += read_hex_columns(ifile,8,19,'H');
break;
case 'T': // Text
record += read_hex_columns(ifile,2,7,'T');
temp_str = read_hex_columns(ifile,8,9,'T');
temp_int = hex2int(temp_str);
record += temp_str;
record += read_hex_columns(ifile,10,9+2*temp_int,'T');
break;
case 'E': // End
record += read_hex_columns(ifile,2,7,'E');
break;
default:
{
string errstr = "Unknown record type ";
errstr += t;
fatal(errstr);
}
}
return true;
}
void record_to_memory(const string record, program &p) {
const char * c_record = record.c_str();
switch (*c_record) {
case 'H': // Header
if ( p.name.length() != 0 ) {
fatal("Multiple H records");
}
p.name = record.substr(1,6);
p.starting_address = record.substr(7,6);
p.length_of_program = hex2int(record.substr(13,6));
break;
case 'T': // Text
{
int text_start = hex2int(record.substr(1,6));
int bit_length = hex2int(record.substr(7,2));
for ( int i = 0 ; i < bit_length ; i++ ) {
p.memory[i+text_start] = hex2int(record.substr(9+2*i,2));
p.byte_type_guess[i+text_start] = UNKNOWN;
}
}
break;
case 'E': // End
if ( p.first_executable_instruction.length() != 0 ) {
fatal("Multiple E records");
}
p.first_executable_instruction = record.substr(1,6);
break;
default:
{
string errstr;
errstr += "Unknown record type ";
errstr += *c_record;
fatal(errstr);
}
}
}
void mark_code_data(program &p, int location, ByteTypeGuess btg) {
if ( location >= hex2int(p.starting_address) + p.length_of_program ) {
return;
}
switch (btg) {
case UNINITIALIZED:
case UNKNOWN:
break;
case CHAR_DATA:
case UNINITIALIZED_CHAR_DATA:
{
if ( p.byte_type_guess[location] != UNKNOWN &&
p.byte_type_guess[location] != UNINITIALIZED ) {
break;
}
if ( p.byte_type_guess[location] == UNINITIALIZED )
btg = UNINITIALIZED_CHAR_DATA;
p.byte_type_guess[location] = btg;
break;
}
case WORD_DATA:
case UNINITIALIZED_WORD_DATA:
{
if ( p.byte_type_guess[location] != UNKNOWN &&
p.byte_type_guess[location] != UNINITIALIZED ) {
break;
}
if ( p.byte_type_guess[location] == UNINITIALIZED )
btg = UNINITIALIZED_WORD_DATA;
p.byte_type_guess[location+0] = btg;
p.byte_type_guess[location+1] = btg;
p.byte_type_guess[location+2] = btg;
break;
}
case CODE:
{
if ( p.byte_type_guess[location] == UNINITIALIZED ) {
fatal("Attempting to use uninitialized section as code");
}
if ( p.byte_type_guess[location] == CODE ) {
break;
}
p.byte_type_guess[location+0] = btg;
p.byte_type_guess[location+1] = btg;
p.byte_type_guess[location+2] = btg;
string opcode_val = byte2hex(p.memory[location]);
string opcode;
string operand = byte2hex(p.memory[location+1])+byte2hex(p.memory[location+2]);
operand = int2hex(hex2int(operand)&0x7FFF); // remove index flag
if ( ! find_from_symtab(opcode,opcode_val) ) {
string errstr;
errstr += "Unknown opcode ";
errstr += opcode_val;
errstr += " at location ";
errstr += int2hex(location);
fatal(errstr);
}
if ( opcode == "ADD" ||
opcode == "AND" ||
opcode == "COMP" ||
opcode == "DIV" ||
opcode == "LDA" ||
opcode == "LDL" ||
opcode == "LDX" ||
opcode == "MUL" ||
opcode == "OR" ||
opcode == "STA" ||
opcode == "STL" ||
opcode == "STX" ||
opcode == "SUB" ||
opcode == "TIX" ) {
give_label(operand);
p.is_labelled[hex2int(operand)] = true;
mark_code_data(p,hex2int(operand),WORD_DATA);
}
if ( opcode == "LDCH" ||
opcode == "STCH" ) {
give_label(operand);
p.is_labelled[hex2int(operand)] = true;
mark_code_data(p,hex2int(operand),CHAR_DATA);
}
if ( opcode == "J" ||
opcode == "JEQ" ||
opcode == "JGT" ||
opcode == "JLT" ||
opcode == "JSUB" ) {
give_label(operand);
p.is_labelled[hex2int(operand)] = true;
mark_code_data(p,hex2int(operand),CODE);
}
if ( opcode != "J" &&
opcode != "RSUB" ) {
mark_code_data(p,location+3,btg);
}
break;
}
}
}
void analyze_code_data(program &p) {
if ( p.name.length() == 0 ) {
fatal("No Header record");
}
if ( p.first_executable_instruction.length() == 0 ) {
fatal("No End record");
}
initialize_symtab();
add_to_symtab("FIRST",p.first_executable_instruction);
p.is_labelled[hex2int(p.first_executable_instruction)] = true;
mark_code_data(p,hex2int(p.first_executable_instruction),CODE);
}
string asm_to_line(string label, string opcode, string operand, bool is_indexed) {
const int labellength = 8;
const int opcodelength = 6;
string ret = "";
ret += label + string(labellength-label.length(),' ');
ret += opcode + string(opcodelength-opcode.length(),' ');
ret += operand;
if ( is_indexed ) {
ret += ",X";
}
ret += '\n';
return ret;
}
void write_assembly(const program &p, ofstream &ofile) {
ofile << asm_to_line(p.name,"START",p.starting_address,false);
int start_of_program = hex2int(p.starting_address);
int end_of_program = start_of_program + p.length_of_program;
for ( int locctr = start_of_program ; locctr < end_of_program ; ) {
string label = "";
string opcode = "";
string operand = "";
bool is_indexed = false;
if ( p.is_labelled[locctr] ) {
if ( !find_from_symtab(label,int2hex(locctr)) ) {
string errstr;
errstr += "Label not created for location ";
errstr += int2hex(locctr);
error(errstr);
}
}
if ( p.byte_type_guess[locctr] == CODE ) {
if ( ! find_from_symtab(opcode,byte2hex(p.memory[locctr])) ) {
string errstr;
errstr += "Unknown opcode ";
errstr += opcode;
errstr += " at location ";
errstr += int2hex(locctr);
fatal(errstr);
}
operand = byte2hex(p.memory[locctr+1])+byte2hex(p.memory[locctr+2]);
is_indexed = (hex2int(operand)&0x8000);
operand = int2hex(hex2int(operand)&0x7FFF); // remove index flag
if ( opcode != "RD" &&
opcode != "TD" &&
opcode != "WD" &&
opcode != "RSUB" ) {
if ( !find_from_symtab(operand,operand) ) {
string errstr;
errstr += "Label not created for operand ";
errstr += operand;
error(errstr);
}
}
if ( opcode == "RSUB" ) {
operand = "";
}
locctr += 3;
} else if ( p.byte_type_guess[locctr] == CHAR_DATA ||
p.byte_type_guess[locctr] == UNKNOWN ) {
if ( p.byte_type_guess[locctr] == UNKNOWN ) {
label = "UNUSED"; // This should not happen in a well written code
}
vector<char> byte_list;
bool type_c = true;
do {
byte_list.push_back(p.memory[locctr]);
if ( !isprint(p.memory[locctr]) ) {
type_c = false;
}
locctr++;
} while ( p.byte_type_guess[locctr] == CHAR_DATA && !p.is_labelled[locctr] );
opcode = "CHAR";
operand += (type_c?"C":"X");
operand += "'";
for ( int i = 0 ; i < (int)byte_list.size() ; i++ ) {
if ( type_c ) {
operand += byte_list[i];
} else {
operand += byte2hex(byte_list[i]);
}
}
operand += "'";
} else if ( p.byte_type_guess[locctr] == WORD_DATA ) {
opcode = "WORD";
operand = int2str(
p.memory[locctr+0]*256*256+
p.memory[locctr+1]*256+
p.memory[locctr+2]
);
locctr += 3;
} else if ( p.byte_type_guess[locctr] == UNINITIALIZED_CHAR_DATA ||
p.byte_type_guess[locctr] == UNINITIALIZED ) {
opcode = "RESB";
int buf_size = 0;
do {
buf_size++;
locctr++;
} while ( (p.byte_type_guess[locctr] == UNINITIALIZED_CHAR_DATA
|| p.byte_type_guess[locctr] == UNINITIALIZED)
&& !p.is_labelled[locctr]
&& locctr < end_of_program);
if ( locctr >= end_of_program ) {
buf_size--;
}
operand = int2str(buf_size);
} else if ( p.byte_type_guess[locctr] == UNINITIALIZED_WORD_DATA ) {
opcode = "RESW";
int buf_size = 0;
do {
buf_size++;
locctr+=3;
} while ( (p.byte_type_guess[locctr] == UNINITIALIZED_WORD_DATA
|| p.byte_type_guess[locctr] == UNINITIALIZED)
&& !p.is_labelled[locctr]
&& locctr < end_of_program);
if ( locctr >= end_of_program ) {
buf_size--;
}
operand = int2str(buf_size);
} else {
fatal("Reached part of decompiler that should not be reached");
}
ofile << asm_to_line(label,opcode,operand,is_indexed);
}
ofile << asm_to_line("","END","FIRST",false);
}<|endoftext|> |
<commit_before>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "ExtraElementIDAux.h"
registerMooseObject("MooseApp", ExtraElementIDAux);
registerMooseObjectRenamed("MooseApp", ElemExtraIDAux, "01/30/2022 24:00", ExtraElementIDAux);
InputParameters
ExtraElementIDAux::validParams()
{
InputParameters params = AuxKernel::validParams();
params.addRequiredParam<std::vector<ExtraElementIDName>>("extra_id_name",
"The extra ID name in the mesh");
params.addClassDescription("Puts element extra IDs into an aux variable.");
return params;
}
ExtraElementIDAux::ExtraElementIDAux(const InputParameters & parameters)
: AuxKernel(parameters), _id(getElementID("extra_id_name"))
{
}
Real
ExtraElementIDAux::computeValue()
{
return (_id == DofObject::invalid_id) ? -1.0 : _id;
}
<commit_msg>ExtraElementIDAux relies on current_elem through reinit FE, cant be used with nodal variables, refs #6090<commit_after>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "ExtraElementIDAux.h"
registerMooseObject("MooseApp", ExtraElementIDAux);
registerMooseObjectRenamed("MooseApp", ElemExtraIDAux, "01/30/2022 24:00", ExtraElementIDAux);
InputParameters
ExtraElementIDAux::validParams()
{
InputParameters params = AuxKernel::validParams();
params.addRequiredParam<std::vector<ExtraElementIDName>>("extra_id_name",
"The extra ID name in the mesh");
params.addClassDescription("Puts element extra IDs into an aux variable.");
return params;
}
ExtraElementIDAux::ExtraElementIDAux(const InputParameters & parameters)
: AuxKernel(parameters), _id(getElementID("extra_id_name"))
{
if (isNodal())
paramError("variable", "This AuxKernel only supports Elemental fields");
}
Real
ExtraElementIDAux::computeValue()
{
return (_id == DofObject::invalid_id) ? -1.0 : _id;
}
<|endoftext|> |
<commit_before>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
// Moose
#include "PenetrationThread.h"
#include "ParallelUniqueId.h"
#include "FindContactPoint.h"
#include "NearestNodeLocator.h"
// libmesh includes
#include "threads.h"
// Mutex to use when accessing _penetration_info;
Threads::spin_mutex pinfo_mutex;
PenetrationThread::PenetrationThread(const MeshBase & mesh,
unsigned int master_boundary,
unsigned int slave_boundary,
std::map<unsigned int, PenetrationLocator::PenetrationInfo *> & penetration_info,
bool update_location,
std::vector<FEBase * > & fes,
FEType & fe_type,
NearestNodeLocator & nearest_node,
std::vector<std::vector<unsigned int> > & node_to_elem_map,
std::vector< unsigned int > & elem_list,
std::vector< unsigned short int > & side_list,
std::vector< short int > & id_list) :
_mesh(mesh),
_master_boundary(master_boundary),
_slave_boundary(slave_boundary),
_penetration_info(penetration_info),
_update_location(update_location),
_fes(fes),
_fe_type(fe_type),
_nearest_node(nearest_node),
_node_to_elem_map(node_to_elem_map),
_elem_list(elem_list),
_side_list(side_list),
_id_list(id_list),
_n_elems(elem_list.size())
{
}
// Splitting Constructor
PenetrationThread::PenetrationThread(PenetrationThread & x, Threads::split /*split*/) :
_mesh(x._mesh),
_master_boundary(x._master_boundary),
_slave_boundary(x._slave_boundary),
_penetration_info(x._penetration_info),
_update_location(x._update_location),
_fes(x._fes),
_fe_type(x._fe_type),
_nearest_node(x._nearest_node),
_node_to_elem_map(x._node_to_elem_map),
_elem_list(x._elem_list),
_side_list(x._side_list),
_id_list(x._id_list),
_n_elems(x._n_elems)
{
}
void
PenetrationThread::operator() (const NodeIdRange & range)
{
ParallelUniqueId puid;
_tid = puid.id;
// Note this is called _fe for backward compatibility... it's actually _not_ a member variable!
// TODO: Replace _fe with fe
FEBase * _fe = _fes[_tid];
for (NodeIdRange::const_iterator nd = range.begin() ; nd != range.end(); ++nd)
{
const Node & node = _mesh.node(*nd);
// We're going to get a reference to the pointer for the pinfo for this node
// This will alow us to manipulate this pointer without having to go through
// the _penetration_info map... meaning this is the only mutex we'll have to do!
pinfo_mutex.lock();
PenetrationLocator::PenetrationInfo * & info = _penetration_info[node.id()];
pinfo_mutex.unlock();
// See if we already have info about this node
if(info)
{
Elem * elem = info->_elem;
if (!_update_location && info->_distance > 0)
{
const Point contact_ref = info->_closest_point_ref;
const Real distance = info->_distance;
bool contact_point_on_side(false);
// Slave position must be the previous contact point
// Use the previous reference coordinates
std::vector<Point> points(1);
points[0] = contact_ref;
_fe->reinit(info->_side, &points);
const std::vector<Point> slave_pos = _fe->get_xyz();
Moose::findContactPoint(*info, _fe, _fe_type, slave_pos[0],
false, contact_point_on_side);
// Restore the original reference coordinates
info->_closest_point_ref = contact_ref;
info->_distance = distance;
mooseAssert(info->_distance >= 0, "Error in PenetrationLocator: Slave node contained in element but contact distance was negative!");
continue;
}
// See if the same element still contains this point
// The default tolerance is TOLERANCE, 1e-6. Bump that up to something more
// forgiving of slight movement of slave nodes.
if(elem->contains_point(node, 100*TOLERANCE))
{
bool contact_point_on_side(false);
Moose::findContactPoint(*info, _fe, _fe_type, node,
false, contact_point_on_side);
// I hate continues but this is actually cleaner than anything I can think of
continue;
}
else
{
// See if this element still has the same one across from it
bool contact_point_on_side;
Moose::findContactPoint(*info, _fe, _fe_type, node,
false, contact_point_on_side);
if(contact_point_on_side)
{
mooseAssert(info->_distance <= 0, "Error in PenetrationLocator: Slave node not contained in element but distance was positive!");
continue;
}
else
{
delete info;
info = NULL;
}
}
}
const Node * closest_node = _nearest_node.nearestNode(node.id());
std::vector<unsigned int> & closest_elems = _node_to_elem_map[closest_node->id()];
std::vector<PenetrationLocator::PenetrationInfo*> p_info;
for(unsigned int j=0; j<closest_elems.size(); j++)
{
unsigned int elem_id = closest_elems[j];
Elem * elem = _mesh.elem(elem_id);
// TODO: This is a horribly inefficient way to do this! We need to cache information about which boundary ids elements are connected to
// and which sides are on those boundaries in MooseMesh! That way we can look this information up directly!
for(unsigned int m=0; m<_n_elems; ++m)
{
if(_elem_list[m] == elem_id && _id_list[m] == static_cast<short>(_master_boundary))
{
unsigned int side_num = _side_list[m];
Elem *side = (elem->build_side(side_num,false)).release();
Point contact_ref;
Point contact_phys;
Real distance = 0.;
RealGradient normal;
bool contact_point_on_side;
std::vector<std::vector<Real> > side_phi;
std::vector<RealGradient> dxyzdxi;
std::vector<RealGradient> dxyzdeta;
std::vector<RealGradient> d2xyzdxideta;
PenetrationLocator::PenetrationInfo * pen_info =
new PenetrationLocator::PenetrationInfo(&node,
elem,
side,
side_num,
normal,
distance,
contact_phys,
contact_ref,
side_phi,
dxyzdxi,
dxyzdeta,
d2xyzdxideta);
Moose::findContactPoint(*pen_info, _fe, _fe_type, node,
true, contact_point_on_side);
if(contact_point_on_side && info &&
(
(std::abs(info->_distance) > std::abs(distance)) ||
(info->_distance < 0 && distance > 0)
)
)
{
delete info;
info = NULL;
}
if(contact_point_on_side && (!info ||
(
(std::abs(info->_distance) > std::abs(distance)) ||
(info->_distance < 0 && distance > 0)
)
)
)
{
info = pen_info;
}
else
{
p_info.push_back( pen_info );
}
}
}
}
// if we didn't find a match and there are two or more candidates...
if (!info && p_info.size() > 1)
{
// No face is clearly above/below this node.
// See if we need to force a match.
// Restrict the parametric coordinates to the domain of the face
for ( unsigned int j(0); j < p_info.size(); ++j )
{
for ( unsigned int k(0); k < p_info[j]->_elem->dim(); ++k )
{
if ( p_info[j]->_closest_point_ref(k) < -1 )
{
p_info[j]->_closest_point_ref(k) = -1;
}
if ( p_info[j]->_closest_point_ref(k) > 1 )
{
p_info[j]->_closest_point_ref(k) = 1;
}
}
}
// Find the element/face closest to the node
unsigned int closest_index(0);
std::vector<Point> points(1);
points[0] = p_info[0]->_closest_point_ref;
_fe->reinit(p_info[0]->_side, &points);
Point closest_coor = _fe->get_xyz()[0];
Real dist = (closest_coor - node).size();
for ( unsigned int j(1); j < p_info.size(); ++j )
{
points[0] = p_info[j]->_closest_point_ref;
_fe->reinit(p_info[j]->_side, &points);
const Point coor = _fe->get_xyz()[0];
Real dist2 = (coor - node).size();
if (dist2 < dist)
{
dist = dist2;
closest_coor = coor;
closest_index = j;
}
}
// We now have the index for the closest face.
for ( unsigned int j(0); j < p_info.size(); ++j )
{
if ( j != closest_index )
{
Point contact_ref;
Point contact_phys;
//Real distance;
RealGradient normal;
bool contact_point_on_side(false);
std::vector<std::vector<Real> > side_phi;
Moose::findContactPoint(*p_info[j], _fe, _fe_type, closest_coor,
true, contact_point_on_side);
if ( contact_point_on_side )
{
// We have found a match. This node is in contact.
p_info[closest_index]->_closest_point = p_info[j]->_closest_point;
p_info[closest_index]->_distance = (p_info[closest_index]->_distance > 0 ? 1 : -1) * dist;
Point normal(closest_coor - node);
const Real len(normal.size());
if (len > 0)
{
normal /= len;
}
const Real dot(normal * p_info[closest_index]->_normal);
if (dot < 0)
{
normal *= -1;
}
p_info[closest_index]->_normal = normal;
points[0] = p_info[closest_index]->_closest_point_ref;
_fe->reinit(p_info[closest_index]->_side, &points);
p_info[closest_index]->_side_phi = _fe->get_phi();
p_info[closest_index]->_dxyzdxi = _fe->get_dxyzdxi();
p_info[closest_index]->_dxyzdeta = _fe->get_dxyzdeta();
p_info[closest_index]->_d2xyzdxideta = _fe->get_d2xyzdxideta();
info = p_info[closest_index];
// Set the entry in p_info to NULL so that we don't delete it (it is now
// owned by _penetration_info).
p_info[closest_index] = NULL;
break;
}
}
}
}
for ( unsigned int j(0); j < p_info.size(); ++j )
{
delete p_info[j];
}
}
}
void
PenetrationThread::join(const PenetrationThread & /*other*/)
{}
<commit_msg>Contact bug fix<commit_after>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
// Moose
#include "PenetrationThread.h"
#include "ParallelUniqueId.h"
#include "FindContactPoint.h"
#include "NearestNodeLocator.h"
// libmesh includes
#include "threads.h"
// Mutex to use when accessing _penetration_info;
Threads::spin_mutex pinfo_mutex;
PenetrationThread::PenetrationThread(const MeshBase & mesh,
unsigned int master_boundary,
unsigned int slave_boundary,
std::map<unsigned int, PenetrationLocator::PenetrationInfo *> & penetration_info,
bool update_location,
std::vector<FEBase * > & fes,
FEType & fe_type,
NearestNodeLocator & nearest_node,
std::vector<std::vector<unsigned int> > & node_to_elem_map,
std::vector< unsigned int > & elem_list,
std::vector< unsigned short int > & side_list,
std::vector< short int > & id_list) :
_mesh(mesh),
_master_boundary(master_boundary),
_slave_boundary(slave_boundary),
_penetration_info(penetration_info),
_update_location(update_location),
_fes(fes),
_fe_type(fe_type),
_nearest_node(nearest_node),
_node_to_elem_map(node_to_elem_map),
_elem_list(elem_list),
_side_list(side_list),
_id_list(id_list),
_n_elems(elem_list.size())
{
}
// Splitting Constructor
PenetrationThread::PenetrationThread(PenetrationThread & x, Threads::split /*split*/) :
_mesh(x._mesh),
_master_boundary(x._master_boundary),
_slave_boundary(x._slave_boundary),
_penetration_info(x._penetration_info),
_update_location(x._update_location),
_fes(x._fes),
_fe_type(x._fe_type),
_nearest_node(x._nearest_node),
_node_to_elem_map(x._node_to_elem_map),
_elem_list(x._elem_list),
_side_list(x._side_list),
_id_list(x._id_list),
_n_elems(x._n_elems)
{
}
void
PenetrationThread::operator() (const NodeIdRange & range)
{
ParallelUniqueId puid;
_tid = puid.id;
// Note this is called _fe for backward compatibility... it's actually _not_ a member variable!
// TODO: Replace _fe with fe
FEBase * _fe = _fes[_tid];
for (NodeIdRange::const_iterator nd = range.begin() ; nd != range.end(); ++nd)
{
const Node & node = _mesh.node(*nd);
// We're going to get a reference to the pointer for the pinfo for this node
// This will alow us to manipulate this pointer without having to go through
// the _penetration_info map... meaning this is the only mutex we'll have to do!
pinfo_mutex.lock();
PenetrationLocator::PenetrationInfo * & info = _penetration_info[node.id()];
pinfo_mutex.unlock();
// See if we already have info about this node
if(info)
{
Elem * elem = info->_elem;
if (!_update_location && info->_distance > 0)
{
const Point contact_ref = info->_closest_point_ref;
const Real distance = info->_distance;
bool contact_point_on_side(false);
// Slave position must be the previous contact point
// Use the previous reference coordinates
std::vector<Point> points(1);
points[0] = contact_ref;
_fe->reinit(info->_side, &points);
const std::vector<Point> slave_pos = _fe->get_xyz();
Moose::findContactPoint(*info, _fe, _fe_type, slave_pos[0],
false, contact_point_on_side);
// Restore the original reference coordinates
info->_closest_point_ref = contact_ref;
info->_distance = distance;
mooseAssert(info->_distance >= 0, "Error in PenetrationLocator: Slave node contained in element but contact distance was negative!");
continue;
}
// See if the same element still contains this point
// The default tolerance is TOLERANCE, 1e-6. Bump that up to something more
// forgiving of slight movement of slave nodes.
if(elem->contains_point(node, 100*TOLERANCE))
{
bool contact_point_on_side(false);
Moose::findContactPoint(*info, _fe, _fe_type, node,
false, contact_point_on_side);
// I hate continues but this is actually cleaner than anything I can think of
continue;
}
else
{
// See if this element still has the same one across from it
bool contact_point_on_side;
Moose::findContactPoint(*info, _fe, _fe_type, node,
false, contact_point_on_side);
if(contact_point_on_side)
{
mooseAssert(info->_distance <= 0, "Error in PenetrationLocator: Slave node not contained in element but distance was positive!");
continue;
}
else
{
delete info;
info = NULL;
}
}
}
const Node * closest_node = _nearest_node.nearestNode(node.id());
std::vector<unsigned int> & closest_elems = _node_to_elem_map[closest_node->id()];
std::vector<PenetrationLocator::PenetrationInfo*> p_info;
for(unsigned int j=0; j<closest_elems.size(); j++)
{
unsigned int elem_id = closest_elems[j];
Elem * elem = _mesh.elem(elem_id);
// TODO: This is a horribly inefficient way to do this! We need to cache information about which boundary ids elements are connected to
// and which sides are on those boundaries in MooseMesh! That way we can look this information up directly!
for(unsigned int m=0; m<_n_elems; ++m)
{
if(_elem_list[m] == elem_id && _id_list[m] == static_cast<short>(_master_boundary))
{
unsigned int side_num = _side_list[m];
Elem *side = (elem->build_side(side_num,false)).release();
Point contact_ref;
Point contact_phys;
Real distance = 0.;
RealGradient normal;
bool contact_point_on_side;
std::vector<std::vector<Real> > side_phi;
std::vector<RealGradient> dxyzdxi;
std::vector<RealGradient> dxyzdeta;
std::vector<RealGradient> d2xyzdxideta;
PenetrationLocator::PenetrationInfo * pen_info =
new PenetrationLocator::PenetrationInfo(&node,
elem,
side,
side_num,
normal,
distance,
contact_phys,
contact_ref,
side_phi,
dxyzdxi,
dxyzdeta,
d2xyzdxideta);
Moose::findContactPoint(*pen_info, _fe, _fe_type, node,
true, contact_point_on_side);
if (contact_point_on_side)
{
if (!info)
{
info = pen_info;
}
else if ((std::abs(info->_distance) > std::abs(pen_info->_distance)) ||
(info->_distance < 0 && pen_info->_distance > 0))
{
delete info;
info = pen_info;
}
}
else
{
p_info.push_back( pen_info );
}
}
}
}
// if we didn't find a match and there are two or more candidates...
if (!info && p_info.size() > 1)
{
// No face is clearly above/below this node.
// See if we need to force a match.
//TODO: This won't work for tet/tri elements
// Restrict the parametric coordinates to the domain of the face
for ( unsigned int j(0); j < p_info.size(); ++j )
{
for ( unsigned int k(0); k < p_info[j]->_elem->dim(); ++k )
{
if ( p_info[j]->_closest_point_ref(k) < -1 )
{
p_info[j]->_closest_point_ref(k) = -1;
}
else if ( p_info[j]->_closest_point_ref(k) > 1 )
{
p_info[j]->_closest_point_ref(k) = 1;
}
}
}
// Find the element/face closest to the node
unsigned int closest_index(0);
std::vector<Point> points(1);
points[0] = p_info[0]->_closest_point_ref;
_fe->reinit(p_info[0]->_side, &points);
Point closest_coor = _fe->get_xyz()[0];
Real dist = (closest_coor - node).size();
for ( unsigned int j(1); j < p_info.size(); ++j )
{
points[0] = p_info[j]->_closest_point_ref;
_fe->reinit(p_info[j]->_side, &points);
const Point coor = _fe->get_xyz()[0];
Real dist2 = (coor - node).size();
if (dist2 < dist)
{
dist = dist2;
closest_coor = coor;
closest_index = j;
}
}
// We now have the index for the closest face.
for ( unsigned int j(0); j < p_info.size(); ++j )
{
if ( j != closest_index )
{
Point contact_ref;
Point contact_phys;
//Real distance;
RealGradient normal;
bool contact_point_on_side(false);
std::vector<std::vector<Real> > side_phi;
Moose::findContactPoint(*p_info[j], _fe, _fe_type, closest_coor,
true, contact_point_on_side);
if ( contact_point_on_side )
{
// We have found a match. This node is in contact.
p_info[closest_index]->_closest_point = p_info[j]->_closest_point;
p_info[closest_index]->_distance = (p_info[closest_index]->_distance > 0 ? 1 : -1) * dist;
Point normal(closest_coor - node);
const Real len(normal.size());
if (len > 0)
{
normal /= len;
}
const Real dot(normal * p_info[closest_index]->_normal);
if (dot < 0)
{
normal *= -1;
}
p_info[closest_index]->_normal = normal;
points[0] = p_info[closest_index]->_closest_point_ref;
_fe->reinit(p_info[closest_index]->_side, &points);
p_info[closest_index]->_side_phi = _fe->get_phi();
p_info[closest_index]->_dxyzdxi = _fe->get_dxyzdxi();
p_info[closest_index]->_dxyzdeta = _fe->get_dxyzdeta();
p_info[closest_index]->_d2xyzdxideta = _fe->get_d2xyzdxideta();
info = p_info[closest_index];
// Set the entry in p_info to NULL so that we don't delete it (it is now
// owned by _penetration_info).
p_info[closest_index] = NULL;
break;
}
}
}
}
for ( unsigned int j(0); j < p_info.size(); ++j )
{
delete p_info[j];
}
}
}
void
PenetrationThread::join(const PenetrationThread & /*other*/)
{}
<|endoftext|> |
<commit_before>/**
* Clever programming language
* Copyright (c) 2011-2012 Clever Team
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include "compiler/cstring.h"
#include "compiler/compiler.h"
#include "compiler/scope.h"
#include "compiler/value.h"
#include "interpreter/location.hh"
#include "types/native_types.h"
namespace clever {
// Declaration of namespace global type ptrs for Clever native types
DECLARE_CLEVER_NATIVE_TYPES();
/// Compiler initialization phase
void Compiler::init()
{
m_scope = new Scope;
m_ir.reserve(20);
m_scope_pool.reserve(10);
m_type_pool.reserve(15);
m_scope_pool[m_scope_id++] = m_scope;
// Native type allocation
m_type_pool[m_type_id++] = CLEVER_INT_TYPE = new IntType;
m_type_pool[m_type_id++] = CLEVER_DOUBLE_TYPE = new DoubleType;
m_type_pool[m_type_id++] = CLEVER_STR_TYPE = new StrType;
m_type_pool[m_type_id++] = CLEVER_FUNC_TYPE = new FuncType;
m_pkg.init();
}
/// Frees all resource used by the compiler
void Compiler::shutdown()
{
m_pkg.shutdown();
CLEVER_SAFE_DELETE(g_cstring_tbl);
CLEVER_SAFE_DELETE(m_scope);
TypePool::const_iterator it2 = m_type_pool.begin(),
end2 = m_type_pool.end();
while (it2 != end2) {
delete *it2;
++it2;
}
}
// Compiler termination phase
void Compiler::end()
{
}
/// Displays an error message and exits
void Compiler::error(const char* msg) const
{
std::cerr << "Compile error: " << msg << std::endl;
CLEVER_EXIT_FATAL();
}
/// Displays an error message
void Compiler::error(const std::string& message, const location& loc) const
{
if (loc.begin.filename) {
std::cerr << "Compile error: " << message << " on "
<< *loc.begin.filename << " line " << loc.begin.line << "\n";
} else {
std::cerr << "Compile error: " << message << " on line "
<< loc.begin.line << "\n";
}
CLEVER_EXIT_FATAL();
}
/// Displays a formatted error message and abort the compilation
void Compiler::errorf(const location& loc, const char* format, ...) const
{
std::ostringstream out;
va_list args;
va_start(args, format);
vsprintf(out, format, args);
va_end(args);
error(out.str(), loc);
}
/// Abstracts the Value* ptr gets from Node
// NOTE: When the Node is a STRCONST, it automatically increments the Value's
// refcount related to the Symbol
Value* Compiler::getValue(Node& node, Symbol** symbol, const location& loc) const
{
if (node.type == VALUE) {
return node.data.val;
} else if (node.type == STRCONST) {
Symbol* sym = m_scope->getAny(node.data.str);
if (!sym) {
errorf(loc, "Variable `%S' cannot be found!", node.data.str);
}
if (symbol) {
*symbol = sym;
}
return m_scope_pool[sym->scope->getId()]->getVar(sym->value_id);
}
return NULL;
}
/// Compiles a variable declaration
void Compiler::varDeclaration(Node& var, Node* node, const location& loc)
{
Symbol* sym = m_scope->getLocal(var.data.str);
if (sym) {
errorf(loc, "Variable `%S' already declared in the scope!", var.data.str);
}
size_t sym_id = m_scope->pushVar(var.data.str, new Value());
// A NULL value is created for uninitialized declaration
sym = NULL;
Value* val = node ? getValue(*node, &sym, loc) : new Value();
// Value to be assigned
if (sym) {
m_ir.push_back(
IR(OP_ASSIGN, FETCH_VAL, sym_id, FETCH_VAL, sym->value_id));
m_ir.back().op2_scope = sym->scope->getId();
} else {
m_ir.push_back(
IR(OP_ASSIGN, FETCH_VAL, sym_id, FETCH_VAL, m_scope->pushConst(val)));
m_ir.back().op2_scope = m_scope->getId();
}
m_ir.back().op1_scope = m_scope->getId();
}
/// Compiles a variable assignment
void Compiler::assignment(Node& var, Node& value, const location& loc)
{
Symbol* var_sym = NULL, *val_sym = NULL;
(void)getValue(var, &var_sym, loc);
Value* val = getValue(value, &val_sym, loc);
if (val_sym) {
m_ir.push_back(
IR(OP_ASSIGN, FETCH_VAL, var_sym->value_id, FETCH_VAL, val_sym->value_id));
m_ir.back().op1_scope = var_sym->scope->getId();
m_ir.back().op2_scope = val_sym->scope->getId();
} else {
m_ir.push_back(
IR(OP_ASSIGN, FETCH_VAL, var_sym->value_id, FETCH_VAL, m_scope->pushConst(val)));
m_ir.back().op1_scope = var_sym->scope->getId();
m_ir.back().op2_scope = m_scope->getId();
}
}
/// Compiles a set of binary operation
void Compiler::binOp(Opcode op, Node& lhs, Node& rhs, Node& res,
const location& loc)
{/*
size_t rhs_id = 0, lhs_id = 0;
Value* result = new Value();
Value* val = getValue(lhs, &lhs_id, loc);
if (!lhs_id) {
lhs_id = m_value_id++;
m_value_pool[lhs_id] = val;
}
val = getValue(rhs, &rhs_id, loc);
if (!rhs_id) {
rhs_id = m_value_id++;
m_value_pool[rhs_id] = val;
}
m_ir.push_back(
IR(op, FETCH_VAL, lhs_id, FETCH_VAL, rhs_id, result));
res.type = VALUE;
res.data.val = result;*/
}
/// Creates a list of arguments
ArgDeclList* Compiler::newArgDeclList(const CString* arg) const
{
ArgDeclList* arg_list = new ArgDeclList;
arg_list->push_back(arg);
return arg_list;
}
/// Starts the function compilation
void Compiler::funcDecl(Node& node, ArgDeclList* arg_list, const location& loc)
{
Symbol* sym = m_scope->getAny(node.data.str);
if (sym) {
errorf(loc, "Name `%S' already in used!", node.data.str);
}
// Saves the current instruction size to be used as a index for
// changing the jmp address to right after the end of function declaration
m_curr_func = m_ir.size();
Value* func = new Value();
Function* funcdata = static_cast<Function*>(CLEVER_FUNC_TYPE->allocData());
func->setType(CLEVER_FUNC_TYPE);
func->setObj(funcdata);
funcdata->setName(*node.data.str);
funcdata->setUserDefined();
funcdata->setAddr(m_curr_func + 1);
m_ir.push_back(IR(OP_JMP, JMP_ADDR, 0));
// Adds the function symbol to the current scope
m_scope->pushVar(node.data.str, func);
// Create a scope for argument list when used
if (arg_list) {
ArgDeclList::const_iterator it = arg_list->begin(),
end = arg_list->end();
newScope();
while (it != end) {
m_scope->pushVar(*it, new Value());
++it;
}
delete arg_list;
funcdata->setArgVars(m_scope);
}
// Creates a scope for the local vars
newScope();
funcdata->setLocalVars(m_scope);
}
/// Adds new argument to the call argument list
ArgCallList* Compiler::addArgCall(ArgCallList* arg_list, Node& arg, const location& loc)
{
Symbol* sym = NULL;
Value* val = getValue(arg, &sym, loc);
if (!arg_list) {
arg_list = new ArgCallList;
}
if (sym) {
arg_list->push_back(std::pair<size_t, size_t>(sym->scope->getId(), sym->value_id));
} else {
arg_list->push_back(std::pair<size_t, size_t>(m_scope->getId(), m_scope->pushConst(val)));
}
return arg_list;
}
/// Ends the current function compilation
void Compiler::funcEndDecl(bool has_args)
{
m_ir.push_back(IR(OP_LEAVE));
// Changes the JMP's addr created right before the func declaration
// to point to the end of current function, thus skipping its opcodes
m_ir[m_curr_func].op1 = m_ir.size();
// Switchs to the global scope again
if (has_args) {
endScope();
}
endScope();
}
/// Function call compilation
void Compiler::funcCall(Node& name, ArgCallList* arg_list, Node& res,
const location& loc)
{
Symbol* sym = m_scope->getAny(name.data.str);
if (!sym) {
errorf(loc, "Function `%S' cannot be found!", name.data.str);
}
Value* result = new Value();
if (arg_list) {
for (size_t i = 0, j = arg_list->size(); i < j; ++i) {
m_ir.push_back(IR(OP_SEND_VAL, FETCH_VAL, arg_list->at(i).second));
m_ir.back().op1_scope = arg_list->at(i).first;
}
}
res.type = VALUE;
res.data.val = result;
m_ir.push_back(
IR(OP_FCALL, FETCH_VAL, sym->value_id, result));
m_ir.back().op1_scope = sym->scope->getId();
if (arg_list) {
delete arg_list;
}
}
/// Compiles a return statement
void Compiler::retStmt(Node* expr, const location& loc)
{
if (expr) {
Symbol* sym = NULL;
Value* value = getValue(*expr, &sym, loc);
if (sym) {
m_ir.push_back(IR(OP_RET, FETCH_VAL, sym->value_id));
m_ir.back().op1_scope = sym->scope->getId();
} else {
m_ir.push_back(IR(OP_RET, FETCH_VAL, m_scope->pushConst(value)));
m_ir.back().op1_scope = m_scope->getId();
}
} else {
m_ir.push_back(IR(OP_RET));
m_ir.back().op1_scope = m_scope->getId();
}
}
void Compiler::importStmt(Node& package)
{
m_pkg.importPackage(m_scope, package.data.str);
}
void Compiler::importStmt(Node& package, Node& module)
{
m_pkg.importModule(m_scope, package.data.str, module.data.str);
}
void Compiler::whileLoop(Node& cond, const location& loc)
{
Symbol* sym = NULL;
Value* val = getValue(cond, &sym, loc);
m_jmps.push(std::vector<size_t>());
m_jmps.top().push_back(m_ir.size());
if (sym) {
m_ir.push_back(IR(OP_JMPZ, FETCH_VAL, sym->value_id, JMP_ADDR, 0));
m_ir.back().op1_scope = sym->scope->getId();
} else {
m_ir.push_back(IR(OP_JMPZ, FETCH_VAL, m_scope->pushConst(val), JMP_ADDR, 0));
m_ir.back().op1_scope = m_scope->getId();
}
}
/// Handles end of while loop
void Compiler::endWhileLoop()
{
// Adds a JMP to the loop condition
m_ir.push_back(IR(OP_JMP, JMP_ADDR, m_jmps.top().at(0)));
// Sets the jmp address of JMPZ instructon related to the loop condition
m_ir[m_jmps.top().at(0)].op2 = m_ir.size();
}
/// Creates a new lexical scope
void Compiler::newScope()
{
m_scope = m_scope->newLexicalScope();
m_scope->setId(m_scope_id);
m_scope_pool[m_scope_id++] = m_scope;
}
/// Scope end marker to switch to parent scope
void Compiler::endScope()
{
m_scope = m_scope->getParent();
}
} // clever
<commit_msg>- Drying Compiler::assignment() a little<commit_after>/**
* Clever programming language
* Copyright (c) 2011-2012 Clever Team
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include "compiler/cstring.h"
#include "compiler/compiler.h"
#include "compiler/scope.h"
#include "compiler/value.h"
#include "interpreter/location.hh"
#include "types/native_types.h"
namespace clever {
// Declaration of namespace global type ptrs for Clever native types
DECLARE_CLEVER_NATIVE_TYPES();
/// Compiler initialization phase
void Compiler::init()
{
m_scope = new Scope;
m_ir.reserve(20);
m_scope_pool.reserve(10);
m_type_pool.reserve(15);
m_scope_pool[m_scope_id++] = m_scope;
// Native type allocation
m_type_pool[m_type_id++] = CLEVER_INT_TYPE = new IntType;
m_type_pool[m_type_id++] = CLEVER_DOUBLE_TYPE = new DoubleType;
m_type_pool[m_type_id++] = CLEVER_STR_TYPE = new StrType;
m_type_pool[m_type_id++] = CLEVER_FUNC_TYPE = new FuncType;
m_pkg.init();
}
/// Frees all resource used by the compiler
void Compiler::shutdown()
{
m_pkg.shutdown();
CLEVER_SAFE_DELETE(g_cstring_tbl);
CLEVER_SAFE_DELETE(m_scope);
TypePool::const_iterator it2 = m_type_pool.begin(),
end2 = m_type_pool.end();
while (it2 != end2) {
delete *it2;
++it2;
}
}
// Compiler termination phase
void Compiler::end()
{
}
/// Displays an error message and exits
void Compiler::error(const char* msg) const
{
std::cerr << "Compile error: " << msg << std::endl;
CLEVER_EXIT_FATAL();
}
/// Displays an error message
void Compiler::error(const std::string& message, const location& loc) const
{
if (loc.begin.filename) {
std::cerr << "Compile error: " << message << " on "
<< *loc.begin.filename << " line " << loc.begin.line << "\n";
} else {
std::cerr << "Compile error: " << message << " on line "
<< loc.begin.line << "\n";
}
CLEVER_EXIT_FATAL();
}
/// Displays a formatted error message and abort the compilation
void Compiler::errorf(const location& loc, const char* format, ...) const
{
std::ostringstream out;
va_list args;
va_start(args, format);
vsprintf(out, format, args);
va_end(args);
error(out.str(), loc);
}
/// Abstracts the Value* ptr gets from Node
// NOTE: When the Node is a STRCONST, it automatically increments the Value's
// refcount related to the Symbol
Value* Compiler::getValue(Node& node, Symbol** symbol, const location& loc) const
{
if (node.type == VALUE) {
return node.data.val;
} else if (node.type == STRCONST) {
Symbol* sym = m_scope->getAny(node.data.str);
if (!sym) {
errorf(loc, "Variable `%S' cannot be found!", node.data.str);
}
if (symbol) {
*symbol = sym;
}
return m_scope_pool[sym->scope->getId()]->getVar(sym->value_id);
}
return NULL;
}
/// Compiles a variable declaration
void Compiler::varDeclaration(Node& var, Node* node, const location& loc)
{
Symbol* sym = m_scope->getLocal(var.data.str);
if (sym) {
errorf(loc, "Variable `%S' already declared in the scope!", var.data.str);
}
size_t sym_id = m_scope->pushVar(var.data.str, new Value());
// A NULL value is created for uninitialized declaration
sym = NULL;
Value* val = node ? getValue(*node, &sym, loc) : new Value();
// Value to be assigned
if (sym) {
m_ir.push_back(
IR(OP_ASSIGN, FETCH_VAL, sym_id, FETCH_VAL, sym->value_id));
m_ir.back().op2_scope = sym->scope->getId();
} else {
m_ir.push_back(
IR(OP_ASSIGN, FETCH_VAL, sym_id, FETCH_VAL, m_scope->pushConst(val)));
m_ir.back().op2_scope = m_scope->getId();
}
m_ir.back().op1_scope = m_scope->getId();
}
/// Compiles a variable assignment
void Compiler::assignment(Node& var, Node& value, const location& loc)
{
Symbol* var_sym = NULL, *val_sym = NULL;
(void)getValue(var, &var_sym, loc);
Value* val = getValue(value, &val_sym, loc);
size_t val_id, val_scope;
if (val_sym) {
val_id = val_sym->value_id;
val_scope = val_sym->scope->getId();
} else {
val_id = m_scope->pushConst(val);
val_scope = m_scope->getId();
}
m_ir.push_back(IR(OP_ASSIGN, FETCH_VAL, var_sym->value_id, FETCH_VAL, val_id));
m_ir.back().op1_scope = var_sym->scope->getId();
m_ir.back().op2_scope = val_scope;
}
/// Compiles a set of binary operation
void Compiler::binOp(Opcode op, Node& lhs, Node& rhs, Node& res,
const location& loc)
{/*
size_t rhs_id = 0, lhs_id = 0;
Value* result = new Value();
Value* val = getValue(lhs, &lhs_id, loc);
if (!lhs_id) {
lhs_id = m_value_id++;
m_value_pool[lhs_id] = val;
}
val = getValue(rhs, &rhs_id, loc);
if (!rhs_id) {
rhs_id = m_value_id++;
m_value_pool[rhs_id] = val;
}
m_ir.push_back(
IR(op, FETCH_VAL, lhs_id, FETCH_VAL, rhs_id, result));
res.type = VALUE;
res.data.val = result;*/
}
/// Creates a list of arguments
ArgDeclList* Compiler::newArgDeclList(const CString* arg) const
{
ArgDeclList* arg_list = new ArgDeclList;
arg_list->push_back(arg);
return arg_list;
}
/// Starts the function compilation
void Compiler::funcDecl(Node& node, ArgDeclList* arg_list, const location& loc)
{
Symbol* sym = m_scope->getAny(node.data.str);
if (sym) {
errorf(loc, "Name `%S' already in used!", node.data.str);
}
// Saves the current instruction size to be used as a index for
// changing the jmp address to right after the end of function declaration
m_curr_func = m_ir.size();
Value* func = new Value();
Function* funcdata = static_cast<Function*>(CLEVER_FUNC_TYPE->allocData());
func->setType(CLEVER_FUNC_TYPE);
func->setObj(funcdata);
funcdata->setName(*node.data.str);
funcdata->setUserDefined();
funcdata->setAddr(m_curr_func + 1);
m_ir.push_back(IR(OP_JMP, JMP_ADDR, 0));
// Adds the function symbol to the current scope
m_scope->pushVar(node.data.str, func);
// Create a scope for argument list when used
if (arg_list) {
ArgDeclList::const_iterator it = arg_list->begin(),
end = arg_list->end();
newScope();
while (it != end) {
m_scope->pushVar(*it, new Value());
++it;
}
delete arg_list;
funcdata->setArgVars(m_scope);
}
// Creates a scope for the local vars
newScope();
funcdata->setLocalVars(m_scope);
}
/// Adds new argument to the call argument list
ArgCallList* Compiler::addArgCall(ArgCallList* arg_list, Node& arg, const location& loc)
{
Symbol* sym = NULL;
Value* val = getValue(arg, &sym, loc);
if (!arg_list) {
arg_list = new ArgCallList;
}
if (sym) {
arg_list->push_back(std::pair<size_t, size_t>(sym->scope->getId(), sym->value_id));
} else {
arg_list->push_back(std::pair<size_t, size_t>(m_scope->getId(), m_scope->pushConst(val)));
}
return arg_list;
}
/// Ends the current function compilation
void Compiler::funcEndDecl(bool has_args)
{
m_ir.push_back(IR(OP_LEAVE));
// Changes the JMP's addr created right before the func declaration
// to point to the end of current function, thus skipping its opcodes
m_ir[m_curr_func].op1 = m_ir.size();
// Switchs to the global scope again
if (has_args) {
endScope();
}
endScope();
}
/// Function call compilation
void Compiler::funcCall(Node& name, ArgCallList* arg_list, Node& res,
const location& loc)
{
Symbol* sym = m_scope->getAny(name.data.str);
if (!sym) {
errorf(loc, "Function `%S' cannot be found!", name.data.str);
}
Value* result = new Value();
if (arg_list) {
for (size_t i = 0, j = arg_list->size(); i < j; ++i) {
m_ir.push_back(IR(OP_SEND_VAL, FETCH_VAL, arg_list->at(i).second));
m_ir.back().op1_scope = arg_list->at(i).first;
}
}
res.type = VALUE;
res.data.val = result;
m_ir.push_back(
IR(OP_FCALL, FETCH_VAL, sym->value_id, result));
m_ir.back().op1_scope = sym->scope->getId();
if (arg_list) {
delete arg_list;
}
}
/// Compiles a return statement
void Compiler::retStmt(Node* expr, const location& loc)
{
if (expr) {
Symbol* sym = NULL;
Value* value = getValue(*expr, &sym, loc);
if (sym) {
m_ir.push_back(IR(OP_RET, FETCH_VAL, sym->value_id));
m_ir.back().op1_scope = sym->scope->getId();
} else {
m_ir.push_back(IR(OP_RET, FETCH_VAL, m_scope->pushConst(value)));
m_ir.back().op1_scope = m_scope->getId();
}
} else {
m_ir.push_back(IR(OP_RET));
m_ir.back().op1_scope = m_scope->getId();
}
}
void Compiler::importStmt(Node& package)
{
m_pkg.importPackage(m_scope, package.data.str);
}
void Compiler::importStmt(Node& package, Node& module)
{
m_pkg.importModule(m_scope, package.data.str, module.data.str);
}
void Compiler::whileLoop(Node& cond, const location& loc)
{
Symbol* sym = NULL;
Value* val = getValue(cond, &sym, loc);
m_jmps.push(std::vector<size_t>());
m_jmps.top().push_back(m_ir.size());
if (sym) {
m_ir.push_back(IR(OP_JMPZ, FETCH_VAL, sym->value_id, JMP_ADDR, 0));
m_ir.back().op1_scope = sym->scope->getId();
} else {
m_ir.push_back(IR(OP_JMPZ, FETCH_VAL, m_scope->pushConst(val), JMP_ADDR, 0));
m_ir.back().op1_scope = m_scope->getId();
}
}
/// Handles end of while loop
void Compiler::endWhileLoop()
{
// Adds a JMP to the loop condition
m_ir.push_back(IR(OP_JMP, JMP_ADDR, m_jmps.top().at(0)));
// Sets the jmp address of JMPZ instructon related to the loop condition
m_ir[m_jmps.top().at(0)].op2 = m_ir.size();
}
/// Creates a new lexical scope
void Compiler::newScope()
{
m_scope = m_scope->newLexicalScope();
m_scope->setId(m_scope_id);
m_scope_pool[m_scope_id++] = m_scope;
}
/// Scope end marker to switch to parent scope
void Compiler::endScope()
{
m_scope = m_scope->getParent();
}
} // clever
<|endoftext|> |
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreGLES2Plugin.h"
#include "OgreRoot.h"
#include "OgreGLES2RenderSystem.h"
namespace Ogre {
static const String sPluginName = "OpenGL ES 2.0 RenderSystem";
GLES2Plugin::GLES2Plugin()
: mRenderSystem(0)
{
}
const String& GLES2Plugin::getName() const
{
return sPluginName;
}
void GLES2Plugin::install()
{
mRenderSystem = OGRE_NEW GLES2RenderSystem();
Root::getSingleton().addRenderSystem(mRenderSystem);
Root::getSingleton().setRenderSystem(mRenderSystem);
}
void GLES2Plugin::initialise()
{
// nothing to do
}
void GLES2Plugin::shutdown()
{
// nothing to do
}
void GLES2Plugin::uninstall()
{
OGRE_DELETE mRenderSystem;
mRenderSystem = 0;
}
}
<commit_msg>GLES2: do not automatically activate, as no other RS does this<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreGLES2Plugin.h"
#include "OgreRoot.h"
#include "OgreGLES2RenderSystem.h"
namespace Ogre {
static const String sPluginName = "OpenGL ES 2.0 RenderSystem";
GLES2Plugin::GLES2Plugin()
: mRenderSystem(0)
{
}
const String& GLES2Plugin::getName() const
{
return sPluginName;
}
void GLES2Plugin::install()
{
mRenderSystem = OGRE_NEW GLES2RenderSystem();
Root::getSingleton().addRenderSystem(mRenderSystem);
}
void GLES2Plugin::initialise()
{
// nothing to do
}
void GLES2Plugin::shutdown()
{
// nothing to do
}
void GLES2Plugin::uninstall()
{
OGRE_DELETE mRenderSystem;
mRenderSystem = 0;
}
}
<|endoftext|> |
<commit_before>/*
sound_pool_item.cpp: To be used by the sound_pool.
* By 2MB Solutions: https//2mb.solutions
* Released under the MIT license. See license.txt for details.
* Billy: https://stormdragon.tk/
* Michael: https://michaeltaboada.me
* */
#include "sound_pool_item.h"
sound_pool_item::sound_pool_item(void)
{
s = NULL;
reset();
}
sound_pool_item::~sound_pool_item(void)
{
if(s) {
delete s;
}
}
void sound_pool_item::reset() {
if(s) {
delete s;
s = NULL;
}
filename="";
x=0;
y=0;
z=0;
looping=false;
pan_step=0.0;
volume_step=0.0;
behind_pitch_decrease=0.0;
start_pan=0.0;
start_volume=0.0;
start_pitch=100.0;
left_range=0;
right_range=0;
forward_range=0;
backward_range=0;
up_range=0;
down_range=0;
is_2d=false;
is_3d=false;
paused=false;
stationary=false;
persistent=false;
}
void sound_pool_item::update(int listener_x, int listener_y, int listener_z, double listener_angle, int max_distance) {
if(!s) {
return;
}
if(max_distance > 0 && looping) {
int total_distance = get_total_distance(listener_x, listener_y, listener_z);
if(total_distance>max_distance && (s->is_playing() || s->get_paused())) {
delete s;
s = new sound();
return;
}
if(total_distance<=max_distance && !(s->is_playing() || s->get_paused())) {
if(s->load(filename)) {
update_listener_position(listener_x, listener_y, listener_z, listener_angle);
if(!paused) {
s->set_loop(true);
s->play();
}
}
return;
}
}
update_listener_position(listener_x, listener_y, listener_z, listener_angle);
}
void sound_pool_item::update_listener_position(int listener_x, int listener_y, int listener_z, double listener_angle) {
if(s) {
if(!s->get_active()) {
return;
}
if(stationary) {
return;
}
int delta_left=x-left_range;
int delta_right=x+right_range;
int delta_backward=y-backward_range;
int delta_forward=y+forward_range;
int delta_up = z+up_range;
int delta_down = z-down_range;
int true_x=listener_x;
int true_y=listener_y;
int true_z = listener_z;
if(!is_2d) {
if(listener_x>=delta_left && listener_x<=delta_right) {
position_sound_1d(s, listener_x, listener_x, pan_step, volume_step, start_pan, start_volume);
return;
}
if(listener_x<delta_left)
position_sound_1d(s, listener_x, delta_left, pan_step, volume_step, start_pan, start_volume);
if(listener_x>delta_right)
position_sound_1d(s, listener_x, delta_right, pan_step, volume_step, start_pan, start_volume);
return;
}
else if(!is_3d) {
if(listener_x < delta_left)
true_x = delta_left;
else if(listener_x > delta_right)
true_x = delta_right;
if(listener_y < delta_backward)
true_y = delta_backward;
else if(listener_y > delta_forward)
true_y = delta_forward;
position_sound_2d(s, listener_x, listener_y, listener_angle, true_x, true_y, pan_step, volume_step, behind_pitch_decrease, behind_volume_decrease, start_pan, start_volume, start_pitch);
return;
}
if(listener_x < delta_left)
true_x = delta_left;
else if(listener_x > delta_right)
true_x = delta_right;
if(listener_y < delta_backward)
true_y = delta_backward;
else if(listener_y > delta_forward)
true_y = delta_forward;
if(listener_z < delta_down)
true_z = delta_down;
else if(listener_z > delta_up)
true_z = delta_up;
position_sound_3d(s, listener_x, listener_y, listener_z, listener_angle, true_x, true_y, true_z, pan_step, volume_step, above_pitch, behind_pitch_decrease, behind_volume_decrease, start_pan, start_volume, start_pitch);
}
}
void sound_pool_item::position_sound_1d(sound* s, int x, int sx, double pan_step, double volume_step, double start_pan, double start_volume, double start_pitch) {
position_sound_2d(s, x, 0, 0, sx, 0, pan_step, volume_step, 0, 0, start_pan, start_volume, start_pitch);
}
void sound_pool_item::position_sound_2d(sound* s, int x, int y, double angle, int sx, int sy, double pan_step, double volume_step, double behind_pitch_decrease, double behind_volume_decrease, double start_pan, double start_volume, double start_pitch) {
position_sound_3d(s, x, y, 0, angle, sx, sy, 0, pan_step, volume_step, 0, behind_pitch_decrease, behind_volume_decrease, start_pan, start_volume, start_pitch);
}
void sound_pool_item::position_sound_3d(sound* s, double x, double y, double z, double theta, double sx, double sy, double sz, double pan_step, double volume_step, double above_pitch, double behind_pitch_decrease, double behind_volume_decrease, double start_pan, double start_volume, double start_pitch) {
double xd = x-sx;
double yd = y-sy;
double zd = z-sz;
double d = sqrt((xd*xd)+(yd*yd)+(zd*zd));
double atheta, rtheta;
if(yd == 0){
if(xd == 0) {
atheta=0;
}
else if(xd < 0) {
atheta = M_PI/2;
}
else {
atheta = (3*M_PI)/2;
}
}
else if(yd < 0)
atheta = atan(xd/yd);
else
atheta = atan(xd/yd)+M_PI;
atheta = atheta*180.0/M_PI;
rtheta = atheta-theta;
double pan = sin(rtheta*M_PI/180.0);
pan = pan*d*pan_step+start_pan;
double behind = -cos(rtheta*M_PI/180.0);
double volume = -d*volume_step+start_volume;
double pitch = start_pitch;
if(behind > 0) {
volume = volume-behind_volume_decrease;
pitch = pitch-behind_pitch_decrease;
}
double phi;
if(zd == 0)
phi = 0;
else
if(d != 0)
phi = atan(zd/d);
else
phi = M_PI/2.0*abs(zd)/zd;
phi = phi*2.0;
double temppitch = -above_pitch*sin(phi);
pitch = pitch+temppitch;
s->set_pan(pan);
s->set_gain(volume);
s->set_pitch(pitch);
}
int sound_pool_item::get_total_distance(int listener_x, int listener_y, int listener_z) {
if(stationary==true) {
return 0;
}
int delta_left=x-left_range;
int delta_right=x+right_range;
int delta_backward=y-backward_range;
int delta_forward=y+forward_range;
int delta_up = z+up_range;
int delta_down = z-down_range;
int true_x=listener_x;
int true_y=listener_y;
int true_z = listener_z;
int distance=0;
if(is_2d==false) {
if(listener_x>=delta_left && listener_x<=delta_right) {
return distance;
}
if(listener_x<delta_left)
distance=delta_left-listener_x;
if(listener_x>delta_right)
distance=listener_x-delta_right;
return distance;
}
else if(is_3d == false) {
if(listener_x<delta_left)
true_x=delta_left;
else if(listener_x>delta_right)
true_x=delta_right;
if(listener_y<delta_backward)
true_y=delta_backward;
else if(listener_y>delta_forward)
true_y=delta_forward;
if(listener_x<true_x)
distance=(true_x-listener_x);
if(listener_x>true_x)
distance=(listener_x-true_x);
if(listener_y<true_y)
distance+=(true_y-listener_y);
if(listener_y>true_y)
distance+=(listener_y-true_y);
return distance;
}
if(listener_x<delta_left)
true_x=delta_left;
else if(listener_x>delta_right)
true_x=delta_right;
if(listener_y<delta_backward)
true_y=delta_backward;
else if(listener_y>delta_forward)
true_y=delta_forward;
if(listener_z < delta_down)
true_z = delta_down;
else if(listener_z > delta_up)
true_z = delta_up;
if(listener_x<true_x)
distance=(true_x-listener_x);
if(listener_x>true_x)
distance=(listener_x-true_x);
if(listener_y<true_y)
distance+=(true_y-listener_y);
if(listener_y>true_y)
distance+=(listener_y-true_y);
if(listener_z < true_z)
distance+= true_z-listener_z;
if(listener_z>true_z)
distance+= listener_z-true_z;
return distance;
}
<commit_msg>Updates to hpoefully stop warnings on mac<commit_after>/*
sound_pool_item.cpp: To be used by the sound_pool.
* By 2MB Solutions: https//2mb.solutions
* Released under the MIT license. See license.txt for details.
* Billy: https://stormdragon.tk/
* Michael: https://michaeltaboada.me
* */
#include "sound_pool_item.h"
sound_pool_item::sound_pool_item(void)
{
s = NULL;
reset();
}
sound_pool_item::~sound_pool_item(void)
{
if(s) {
delete s;
}
}
void sound_pool_item::reset() {
if(s) {
delete s;
s = NULL;
}
filename="";
x=0;
y=0;
z=0;
looping=false;
pan_step=0.0;
volume_step=0.0;
behind_pitch_decrease=0.0;
start_pan=0.0;
start_volume=0.0;
start_pitch=100.0;
left_range=0;
right_range=0;
forward_range=0;
backward_range=0;
up_range=0;
down_range=0;
is_2d=false;
is_3d=false;
paused=false;
stationary=false;
persistent=false;
}
void sound_pool_item::update(int listener_x, int listener_y, int listener_z, double listener_angle, int max_distance) {
if(!s) {
return;
}
if(max_distance > 0 && looping) {
int total_distance = get_total_distance(listener_x, listener_y, listener_z);
if(total_distance>max_distance && (s->is_playing() || s->get_paused())) {
delete s;
s = new sound();
return;
}
if(total_distance<=max_distance && !(s->is_playing() || s->get_paused())) {
if(s->load(filename)) {
update_listener_position(listener_x, listener_y, listener_z, listener_angle);
if(!paused) {
s->set_loop(true);
s->play();
}
}
return;
}
}
update_listener_position(listener_x, listener_y, listener_z, listener_angle);
}
void sound_pool_item::update_listener_position(int listener_x, int listener_y, int listener_z, double listener_angle) {
if(s) {
if(!s->get_active()) {
return;
}
if(stationary) {
return;
}
int delta_left=x-left_range;
int delta_right=x+right_range;
int delta_backward=y-backward_range;
int delta_forward=y+forward_range;
int delta_up = z+up_range;
int delta_down = z-down_range;
int true_x=listener_x;
int true_y=listener_y;
int true_z = listener_z;
if(!is_2d) {
if(listener_x>=delta_left && listener_x<=delta_right) {
position_sound_1d(s, listener_x, listener_x, pan_step, volume_step, start_pan, start_volume);
return;
}
if(listener_x<delta_left)
position_sound_1d(s, listener_x, delta_left, pan_step, volume_step, start_pan, start_volume);
if(listener_x>delta_right)
position_sound_1d(s, listener_x, delta_right, pan_step, volume_step, start_pan, start_volume);
return;
}
else if(!is_3d) {
if(listener_x < delta_left)
true_x = delta_left;
else if(listener_x > delta_right)
true_x = delta_right;
if(listener_y < delta_backward)
true_y = delta_backward;
else if(listener_y > delta_forward)
true_y = delta_forward;
position_sound_2d(s, listener_x, listener_y, listener_angle, true_x, true_y, pan_step, volume_step, behind_pitch_decrease, behind_volume_decrease, start_pan, start_volume, start_pitch);
return;
}
if(listener_x < delta_left)
true_x = delta_left;
else if(listener_x > delta_right)
true_x = delta_right;
if(listener_y < delta_backward)
true_y = delta_backward;
else if(listener_y > delta_forward)
true_y = delta_forward;
if(listener_z < delta_down)
true_z = delta_down;
else if(listener_z > delta_up)
true_z = delta_up;
position_sound_3d(s, listener_x, listener_y, listener_z, listener_angle, true_x, true_y, true_z, pan_step, volume_step, above_pitch, behind_pitch_decrease, behind_volume_decrease, start_pan, start_volume, start_pitch);
}
}
void sound_pool_item::position_sound_1d(sound* s, int x, int sx, double pan_step, double volume_step, double start_pan, double start_volume, double start_pitch) {
position_sound_2d(s, x, 0, 0, sx, 0, pan_step, volume_step, 0, 0, start_pan, start_volume, start_pitch);
}
void sound_pool_item::position_sound_2d(sound* s, int x, int y, double angle, int sx, int sy, double pan_step, double volume_step, double behind_pitch_decrease, double behind_volume_decrease, double start_pan, double start_volume, double start_pitch) {
position_sound_3d(s, x, y, 0, angle, sx, sy, 0, pan_step, volume_step, 0, behind_pitch_decrease, behind_volume_decrease, start_pan, start_volume, start_pitch);
}
void sound_pool_item::position_sound_3d(sound* s, double x, double y, double z, double theta, double sx, double sy, double sz, double pan_step, double volume_step, double above_pitch, double behind_pitch_decrease, double behind_volume_decrease, double start_pan, double start_volume, double start_pitch) {
double xd = x-sx;
double yd = y-sy;
double zd = z-sz;
double d = sqrt((xd*xd)+(yd*yd)+(zd*zd));
double atheta, rtheta;
if(yd == 0){
if(xd == 0) {
atheta=0;
}
else if(xd < 0) {
atheta = M_PI/2;
}
else {
atheta = (3*M_PI)/2;
}
}
else if(yd < 0)
atheta = atan(xd/yd);
else
atheta = atan(xd/yd)+M_PI;
atheta = atheta*180.0/M_PI;
rtheta = atheta-theta;
double pan = sin(rtheta*M_PI/180.0);
pan = pan*d*pan_step+start_pan;
double behind = -cos(rtheta*M_PI/180.0);
double volume = -d*volume_step+start_volume;
double pitch = start_pitch;
if(behind > 0) {
volume = volume-behind_volume_decrease;
pitch = pitch-behind_pitch_decrease;
}
double phi;
if(zd == 0)
phi = 0;
else
if(d != 0)
phi = atan(zd/d);
else
phi = M_PI/2.0*fabs(zd)/zd;
phi = phi*2.0;
double temppitch = -above_pitch*sin(phi);
pitch = pitch+temppitch;
s->set_pan(pan);
s->set_gain(volume);
s->set_pitch(pitch);
}
int sound_pool_item::get_total_distance(int listener_x, int listener_y, int listener_z) {
if(stationary==true) {
return 0;
}
int delta_left=x-left_range;
int delta_right=x+right_range;
int delta_backward=y-backward_range;
int delta_forward=y+forward_range;
int delta_up = z+up_range;
int delta_down = z-down_range;
int true_x=listener_x;
int true_y=listener_y;
int true_z = listener_z;
int distance=0;
if(is_2d==false) {
if(listener_x>=delta_left && listener_x<=delta_right) {
return distance;
}
if(listener_x<delta_left)
distance=delta_left-listener_x;
if(listener_x>delta_right)
distance=listener_x-delta_right;
return distance;
}
else if(is_3d == false) {
if(listener_x<delta_left)
true_x=delta_left;
else if(listener_x>delta_right)
true_x=delta_right;
if(listener_y<delta_backward)
true_y=delta_backward;
else if(listener_y>delta_forward)
true_y=delta_forward;
if(listener_x<true_x)
distance=(true_x-listener_x);
if(listener_x>true_x)
distance=(listener_x-true_x);
if(listener_y<true_y)
distance+=(true_y-listener_y);
if(listener_y>true_y)
distance+=(listener_y-true_y);
return distance;
}
if(listener_x<delta_left)
true_x=delta_left;
else if(listener_x>delta_right)
true_x=delta_right;
if(listener_y<delta_backward)
true_y=delta_backward;
else if(listener_y>delta_forward)
true_y=delta_forward;
if(listener_z < delta_down)
true_z = delta_down;
else if(listener_z > delta_up)
true_z = delta_up;
if(listener_x<true_x)
distance=(true_x-listener_x);
if(listener_x>true_x)
distance=(listener_x-true_x);
if(listener_y<true_y)
distance+=(true_y-listener_y);
if(listener_y>true_y)
distance+=(listener_y-true_y);
if(listener_z < true_z)
distance+= true_z-listener_z;
if(listener_z>true_z)
distance+= listener_z-true_z;
return distance;
}
<|endoftext|> |
<commit_before>#include "Layer.hpp"
#include "ClipperUtils.hpp"
#include "Print.hpp"
#include "Fill/Fill.hpp"
#include "ShortestPath.hpp"
#include "SVG.hpp"
#include <boost/log/trivial.hpp>
namespace Slic3r {
Layer::~Layer()
{
this->lower_layer = this->upper_layer = nullptr;
for (LayerRegion *region : m_regions)
delete region;
m_regions.clear();
}
// Test whether whether there are any slices assigned to this layer.
bool Layer::empty() const
{
for (const LayerRegion *layerm : m_regions)
if (layerm != nullptr && ! layerm->slices.empty())
// Non empty layer.
return false;
return true;
}
LayerRegion* Layer::add_region(PrintRegion* print_region)
{
m_regions.emplace_back(new LayerRegion(this, print_region));
return m_regions.back();
}
// merge all regions' slices to get islands
void Layer::make_slices()
{
ExPolygons slices;
if (m_regions.size() == 1) {
// optimization: if we only have one region, take its slices
slices = m_regions.front()->slices;
} else {
Polygons slices_p;
for (LayerRegion *layerm : m_regions)
polygons_append(slices_p, to_polygons(layerm->slices));
slices = union_ex(slices_p);
}
this->lslices.clear();
this->lslices.reserve(slices.size());
// prepare ordering points
Points ordering_points;
ordering_points.reserve(slices.size());
for (const ExPolygon &ex : slices)
ordering_points.push_back(ex.contour.first_point());
// sort slices
std::vector<Points::size_type> order = chain_points(ordering_points);
// populate slices vector
for (size_t i : order)
this->lslices.emplace_back(std::move(slices[i]));
}
// Merge typed slices into untyped slices. This method is used to revert the effects of detect_surfaces_type() called for posPrepareInfill.
void Layer::merge_slices()
{
if (m_regions.size() == 1 && (this->id() > 0 || this->object()->config().elefant_foot_compensation.value == 0)) {
// Optimization, also more robust. Don't merge classified pieces of layerm->slices,
// but use the non-split islands of a layer. For a single region print, these shall be equal.
// Don't use this optimization on 1st layer with Elephant foot compensation applied, as this->lslices are uncompensated,
// while regions are compensated.
m_regions.front()->slices.set(this->lslices, stInternal);
} else {
for (LayerRegion *layerm : m_regions)
// without safety offset, artifacts are generated (upstream Slic3r GH #2494)
layerm->slices.set(union_ex(to_polygons(std::move(layerm->slices.surfaces)), true), stInternal);
}
}
ExPolygons Layer::merged(float offset_scaled) const
{
assert(offset_scaled >= 0.f);
// If no offset is set, apply EPSILON offset before union, and revert it afterwards.
float offset_scaled2 = 0;
if (offset_scaled == 0.f) {
offset_scaled = float( EPSILON);
offset_scaled2 = float(- EPSILON);
}
Polygons polygons;
for (LayerRegion *layerm : m_regions) {
const PrintRegionConfig &config = layerm->region()->config();
// Our users learned to bend Slic3r to produce empty volumes to act as subtracters. Only add the region if it is non-empty.
if (config.bottom_solid_layers > 0 || config.top_solid_layers > 0 || config.fill_density > 0. || config.perimeters > 0)
append(polygons, offset(to_expolygons(layerm->slices.surfaces), offset_scaled));
}
ExPolygons out = union_ex(polygons);
if (offset_scaled2 != 0.f)
out = offset_ex(out, offset_scaled2);
return out;
}
// Here the perimeters are created cummulatively for all layer regions sharing the same parameters influencing the perimeters.
// The perimeter paths and the thin fills (ExtrusionEntityCollection) are assigned to the first compatible layer region.
// The resulting fill surface is split back among the originating regions.
void Layer::make_perimeters()
{
BOOST_LOG_TRIVIAL(trace) << "Generating perimeters for layer " << this->id();
// keep track of regions whose perimeters we have already generated
std::vector<unsigned char> done(m_regions.size(), false);
for (LayerRegionPtrs::iterator layerm = m_regions.begin(); layerm != m_regions.end(); ++ layerm) {
size_t region_id = layerm - m_regions.begin();
if (done[region_id])
continue;
BOOST_LOG_TRIVIAL(trace) << "Generating perimeters for layer " << this->id() << ", region " << region_id;
done[region_id] = true;
const PrintRegionConfig &config = (*layerm)->region()->config();
// find compatible regions
LayerRegionPtrs layerms;
layerms.push_back(*layerm);
for (LayerRegionPtrs::const_iterator it = layerm + 1; it != m_regions.end(); ++it) {
LayerRegion* other_layerm = *it;
const PrintRegionConfig &other_config = other_layerm->region()->config();
if (config.perimeter_extruder == other_config.perimeter_extruder
&& config.perimeters == other_config.perimeters
&& config.perimeter_speed == other_config.perimeter_speed
&& config.external_perimeter_speed == other_config.external_perimeter_speed
&& config.gap_fill_speed == other_config.gap_fill_speed
&& config.overhangs == other_config.overhangs
&& config.opt_serialize("perimeter_extrusion_width") == other_config.opt_serialize("perimeter_extrusion_width")
&& config.thin_walls == other_config.thin_walls
&& config.external_perimeters_first == other_config.external_perimeters_first
&& config.infill_overlap == other_config.infill_overlap) {
layerms.push_back(other_layerm);
done[it - m_regions.begin()] = true;
}
}
if (layerms.size() == 1) { // optimization
(*layerm)->fill_surfaces.surfaces.clear();
(*layerm)->make_perimeters((*layerm)->slices, &(*layerm)->fill_surfaces);
(*layerm)->fill_expolygons = to_expolygons((*layerm)->fill_surfaces.surfaces);
} else {
SurfaceCollection new_slices;
// Use the region with highest infill rate, as the make_perimeters() function below decides on the gap fill based on the infill existence.
LayerRegion *layerm_config = layerms.front();
{
// group slices (surfaces) according to number of extra perimeters
std::map<unsigned short, Surfaces> slices; // extra_perimeters => [ surface, surface... ]
for (LayerRegion *layerm : layerms) {
for (Surface &surface : layerm->slices.surfaces)
slices[surface.extra_perimeters].emplace_back(surface);
if (layerm->region()->config().fill_density > layerm_config->region()->config().fill_density)
layerm_config = layerm;
}
// merge the surfaces assigned to each group
for (std::pair<const unsigned short,Surfaces> &surfaces_with_extra_perimeters : slices)
new_slices.append(union_ex(surfaces_with_extra_perimeters.second, true), surfaces_with_extra_perimeters.second.front());
}
// make perimeters
SurfaceCollection fill_surfaces;
layerm_config->make_perimeters(new_slices, &fill_surfaces);
// assign fill_surfaces to each layer
if (!fill_surfaces.surfaces.empty()) {
for (LayerRegionPtrs::iterator l = layerms.begin(); l != layerms.end(); ++l) {
// Separate the fill surfaces.
ExPolygons expp = intersection_ex(to_polygons(fill_surfaces), (*l)->slices);
(*l)->fill_expolygons = expp;
(*l)->fill_surfaces.set(std::move(expp), fill_surfaces.surfaces.front());
}
}
}
}
BOOST_LOG_TRIVIAL(trace) << "Generating perimeters for layer " << this->id() << " - Done";
}
void Layer::export_region_slices_to_svg(const char *path) const
{
BoundingBox bbox;
for (const auto *region : m_regions)
for (const auto &surface : region->slices.surfaces)
bbox.merge(get_extents(surface.expolygon));
Point legend_size = export_surface_type_legend_to_svg_box_size();
Point legend_pos(bbox.min(0), bbox.max(1));
bbox.merge(Point(std::max(bbox.min(0) + legend_size(0), bbox.max(0)), bbox.max(1) + legend_size(1)));
SVG svg(path, bbox);
const float transparency = 0.5f;
for (const auto *region : m_regions)
for (const auto &surface : region->slices.surfaces)
svg.draw(surface.expolygon, surface_type_to_color_name(surface.surface_type), transparency);
export_surface_type_legend_to_svg(svg, legend_pos);
svg.Close();
}
// Export to "out/LayerRegion-name-%d.svg" with an increasing index with every export.
void Layer::export_region_slices_to_svg_debug(const char *name) const
{
static size_t idx = 0;
this->export_region_slices_to_svg(debug_out_path("Layer-slices-%s-%d.svg", name, idx ++).c_str());
}
void Layer::export_region_fill_surfaces_to_svg(const char *path) const
{
BoundingBox bbox;
for (const auto *region : m_regions)
for (const auto &surface : region->slices.surfaces)
bbox.merge(get_extents(surface.expolygon));
Point legend_size = export_surface_type_legend_to_svg_box_size();
Point legend_pos(bbox.min(0), bbox.max(1));
bbox.merge(Point(std::max(bbox.min(0) + legend_size(0), bbox.max(0)), bbox.max(1) + legend_size(1)));
SVG svg(path, bbox);
const float transparency = 0.5f;
for (const auto *region : m_regions)
for (const auto &surface : region->slices.surfaces)
svg.draw(surface.expolygon, surface_type_to_color_name(surface.surface_type), transparency);
export_surface_type_legend_to_svg(svg, legend_pos);
svg.Close();
}
// Export to "out/LayerRegion-name-%d.svg" with an increasing index with every export.
void Layer::export_region_fill_surfaces_to_svg_debug(const char *name) const
{
static size_t idx = 0;
this->export_region_fill_surfaces_to_svg(debug_out_path("Layer-fill_surfaces-%s-%d.svg", name, idx ++).c_str());
}
}
<commit_msg>Fix of weird double extrusions with multiple regions and their parameters being changed between slicing runs.<commit_after>#include "Layer.hpp"
#include "ClipperUtils.hpp"
#include "Print.hpp"
#include "Fill/Fill.hpp"
#include "ShortestPath.hpp"
#include "SVG.hpp"
#include <boost/log/trivial.hpp>
namespace Slic3r {
Layer::~Layer()
{
this->lower_layer = this->upper_layer = nullptr;
for (LayerRegion *region : m_regions)
delete region;
m_regions.clear();
}
// Test whether whether there are any slices assigned to this layer.
bool Layer::empty() const
{
for (const LayerRegion *layerm : m_regions)
if (layerm != nullptr && ! layerm->slices.empty())
// Non empty layer.
return false;
return true;
}
LayerRegion* Layer::add_region(PrintRegion* print_region)
{
m_regions.emplace_back(new LayerRegion(this, print_region));
return m_regions.back();
}
// merge all regions' slices to get islands
void Layer::make_slices()
{
ExPolygons slices;
if (m_regions.size() == 1) {
// optimization: if we only have one region, take its slices
slices = m_regions.front()->slices;
} else {
Polygons slices_p;
for (LayerRegion *layerm : m_regions)
polygons_append(slices_p, to_polygons(layerm->slices));
slices = union_ex(slices_p);
}
this->lslices.clear();
this->lslices.reserve(slices.size());
// prepare ordering points
Points ordering_points;
ordering_points.reserve(slices.size());
for (const ExPolygon &ex : slices)
ordering_points.push_back(ex.contour.first_point());
// sort slices
std::vector<Points::size_type> order = chain_points(ordering_points);
// populate slices vector
for (size_t i : order)
this->lslices.emplace_back(std::move(slices[i]));
}
// Merge typed slices into untyped slices. This method is used to revert the effects of detect_surfaces_type() called for posPrepareInfill.
void Layer::merge_slices()
{
if (m_regions.size() == 1 && (this->id() > 0 || this->object()->config().elefant_foot_compensation.value == 0)) {
// Optimization, also more robust. Don't merge classified pieces of layerm->slices,
// but use the non-split islands of a layer. For a single region print, these shall be equal.
// Don't use this optimization on 1st layer with Elephant foot compensation applied, as this->lslices are uncompensated,
// while regions are compensated.
m_regions.front()->slices.set(this->lslices, stInternal);
} else {
for (LayerRegion *layerm : m_regions)
// without safety offset, artifacts are generated (upstream Slic3r GH #2494)
layerm->slices.set(union_ex(to_polygons(std::move(layerm->slices.surfaces)), true), stInternal);
}
}
ExPolygons Layer::merged(float offset_scaled) const
{
assert(offset_scaled >= 0.f);
// If no offset is set, apply EPSILON offset before union, and revert it afterwards.
float offset_scaled2 = 0;
if (offset_scaled == 0.f) {
offset_scaled = float( EPSILON);
offset_scaled2 = float(- EPSILON);
}
Polygons polygons;
for (LayerRegion *layerm : m_regions) {
const PrintRegionConfig &config = layerm->region()->config();
// Our users learned to bend Slic3r to produce empty volumes to act as subtracters. Only add the region if it is non-empty.
if (config.bottom_solid_layers > 0 || config.top_solid_layers > 0 || config.fill_density > 0. || config.perimeters > 0)
append(polygons, offset(to_expolygons(layerm->slices.surfaces), offset_scaled));
}
ExPolygons out = union_ex(polygons);
if (offset_scaled2 != 0.f)
out = offset_ex(out, offset_scaled2);
return out;
}
// Here the perimeters are created cummulatively for all layer regions sharing the same parameters influencing the perimeters.
// The perimeter paths and the thin fills (ExtrusionEntityCollection) are assigned to the first compatible layer region.
// The resulting fill surface is split back among the originating regions.
void Layer::make_perimeters()
{
BOOST_LOG_TRIVIAL(trace) << "Generating perimeters for layer " << this->id();
// keep track of regions whose perimeters we have already generated
std::vector<unsigned char> done(m_regions.size(), false);
for (LayerRegionPtrs::iterator layerm = m_regions.begin(); layerm != m_regions.end(); ++ layerm)
if ((*layerm)->slices.empty()) {
(*layerm)->perimeters.clear();
(*layerm)->fills.clear();
(*layerm)->thin_fills.clear();
} else {
size_t region_id = layerm - m_regions.begin();
if (done[region_id])
continue;
BOOST_LOG_TRIVIAL(trace) << "Generating perimeters for layer " << this->id() << ", region " << region_id;
done[region_id] = true;
const PrintRegionConfig &config = (*layerm)->region()->config();
// find compatible regions
LayerRegionPtrs layerms;
layerms.push_back(*layerm);
for (LayerRegionPtrs::const_iterator it = layerm + 1; it != m_regions.end(); ++it)
if (! (*it)->slices.empty()) {
LayerRegion* other_layerm = *it;
const PrintRegionConfig &other_config = other_layerm->region()->config();
if (config.perimeter_extruder == other_config.perimeter_extruder
&& config.perimeters == other_config.perimeters
&& config.perimeter_speed == other_config.perimeter_speed
&& config.external_perimeter_speed == other_config.external_perimeter_speed
&& config.gap_fill_speed == other_config.gap_fill_speed
&& config.overhangs == other_config.overhangs
&& config.opt_serialize("perimeter_extrusion_width") == other_config.opt_serialize("perimeter_extrusion_width")
&& config.thin_walls == other_config.thin_walls
&& config.external_perimeters_first == other_config.external_perimeters_first
&& config.infill_overlap == other_config.infill_overlap)
{
other_layerm->perimeters.clear();
other_layerm->fills.clear();
other_layerm->thin_fills.clear();
layerms.push_back(other_layerm);
done[it - m_regions.begin()] = true;
}
}
if (layerms.size() == 1) { // optimization
(*layerm)->fill_surfaces.surfaces.clear();
(*layerm)->make_perimeters((*layerm)->slices, &(*layerm)->fill_surfaces);
(*layerm)->fill_expolygons = to_expolygons((*layerm)->fill_surfaces.surfaces);
} else {
SurfaceCollection new_slices;
// Use the region with highest infill rate, as the make_perimeters() function below decides on the gap fill based on the infill existence.
LayerRegion *layerm_config = layerms.front();
{
// group slices (surfaces) according to number of extra perimeters
std::map<unsigned short, Surfaces> slices; // extra_perimeters => [ surface, surface... ]
for (LayerRegion *layerm : layerms) {
for (Surface &surface : layerm->slices.surfaces)
slices[surface.extra_perimeters].emplace_back(surface);
if (layerm->region()->config().fill_density > layerm_config->region()->config().fill_density)
layerm_config = layerm;
}
// merge the surfaces assigned to each group
for (std::pair<const unsigned short,Surfaces> &surfaces_with_extra_perimeters : slices)
new_slices.append(union_ex(surfaces_with_extra_perimeters.second, true), surfaces_with_extra_perimeters.second.front());
}
// make perimeters
SurfaceCollection fill_surfaces;
layerm_config->make_perimeters(new_slices, &fill_surfaces);
// assign fill_surfaces to each layer
if (!fill_surfaces.surfaces.empty()) {
for (LayerRegionPtrs::iterator l = layerms.begin(); l != layerms.end(); ++l) {
// Separate the fill surfaces.
ExPolygons expp = intersection_ex(to_polygons(fill_surfaces), (*l)->slices);
(*l)->fill_expolygons = expp;
(*l)->fill_surfaces.set(std::move(expp), fill_surfaces.surfaces.front());
}
}
}
}
BOOST_LOG_TRIVIAL(trace) << "Generating perimeters for layer " << this->id() << " - Done";
}
void Layer::export_region_slices_to_svg(const char *path) const
{
BoundingBox bbox;
for (const auto *region : m_regions)
for (const auto &surface : region->slices.surfaces)
bbox.merge(get_extents(surface.expolygon));
Point legend_size = export_surface_type_legend_to_svg_box_size();
Point legend_pos(bbox.min(0), bbox.max(1));
bbox.merge(Point(std::max(bbox.min(0) + legend_size(0), bbox.max(0)), bbox.max(1) + legend_size(1)));
SVG svg(path, bbox);
const float transparency = 0.5f;
for (const auto *region : m_regions)
for (const auto &surface : region->slices.surfaces)
svg.draw(surface.expolygon, surface_type_to_color_name(surface.surface_type), transparency);
export_surface_type_legend_to_svg(svg, legend_pos);
svg.Close();
}
// Export to "out/LayerRegion-name-%d.svg" with an increasing index with every export.
void Layer::export_region_slices_to_svg_debug(const char *name) const
{
static size_t idx = 0;
this->export_region_slices_to_svg(debug_out_path("Layer-slices-%s-%d.svg", name, idx ++).c_str());
}
void Layer::export_region_fill_surfaces_to_svg(const char *path) const
{
BoundingBox bbox;
for (const auto *region : m_regions)
for (const auto &surface : region->slices.surfaces)
bbox.merge(get_extents(surface.expolygon));
Point legend_size = export_surface_type_legend_to_svg_box_size();
Point legend_pos(bbox.min(0), bbox.max(1));
bbox.merge(Point(std::max(bbox.min(0) + legend_size(0), bbox.max(0)), bbox.max(1) + legend_size(1)));
SVG svg(path, bbox);
const float transparency = 0.5f;
for (const auto *region : m_regions)
for (const auto &surface : region->slices.surfaces)
svg.draw(surface.expolygon, surface_type_to_color_name(surface.surface_type), transparency);
export_surface_type_legend_to_svg(svg, legend_pos);
svg.Close();
}
// Export to "out/LayerRegion-name-%d.svg" with an increasing index with every export.
void Layer::export_region_fill_surfaces_to_svg_debug(const char *name) const
{
static size_t idx = 0;
this->export_region_fill_surfaces_to_svg(debug_out_path("Layer-fill_surfaces-%s-%d.svg", name, idx ++).c_str());
}
}
<|endoftext|> |
<commit_before>/* This file is part of Mapnik (c++ mapping toolkit)
* Copyright (C) 2005 Artem Pavlenko
*
* Mapnik 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 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.
*/
//$Id$
#include "line_symbolizer.hpp"
#include "agg_basics.h"
#include "agg_rendering_buffer.h"
#include "agg_rasterizer_scanline_aa.h"
#include "agg_conv_stroke.h"
#include "agg_conv_dash.h"
#include "agg_conv_contour.h"
#include "agg_vcgen_stroke.h"
#include "agg_conv_adaptor_vcgen.h"
#include "agg_conv_smooth_poly1.h"
#include "agg_conv_marker.h"
#include "agg_arrowhead.h"
#include "agg_vcgen_markers_term.h"
#include "agg_scanline_p.h"
#include "agg_scanline_u.h"
#include "agg_renderer_scanline.h"
#include "agg_pixfmt_rgba.h"
#include "agg_path_storage.h"
#include "agg_renderer_outline_aa.h"
#include "agg_rasterizer_outline_aa.h"
#include "agg_rasterizer_outline.h"
#include "agg_renderer_outline_image.h"
namespace mapnik
{
line_symbolizer::line_symbolizer(stroke const& stroke)
: symbolizer(),
stroke_(stroke) {}
line_symbolizer::line_symbolizer(const Color& pen,float width)
: symbolizer(),
stroke_(pen,width) {}
void line_symbolizer::render(Feature const& feat, CoordTransform const& t,Image32& image) const
{
typedef agg::renderer_base<agg::pixfmt_rgba32> ren_base;
typedef coord_transform<CoordTransform,geometry_type> path_type;
geometry_ptr const& geom=feat.get_geometry();
if (geom)
{
path_type path(t,*geom);
agg::row_ptr_cache<agg::int8u> buf(image.raw_data(),image.width(),image.height(),
image.width()*4);
agg::pixfmt_rgba32 pixf(buf);
ren_base renb(pixf);
Color const& col = stroke_.get_color();
unsigned r=col.red();
unsigned g=col.green();
unsigned b=col.blue();
if (0)//stroke_.get_width() <= 1.0)
{
typedef agg::renderer_outline_aa<ren_base> renderer_oaa;
typedef agg::rasterizer_outline_aa<renderer_oaa> rasterizer_outline_aa;
agg::line_profile_aa prof;
prof.width(stroke_.get_width());
renderer_oaa ren_oaa(renb, prof);
rasterizer_outline_aa ras_oaa(ren_oaa);
ren_oaa.color(agg::rgba8(r, g, b, int(255*stroke_.get_opacity())));
ren_oaa.clip_box(0,0,image.width(),image.height());
ras_oaa.add_path(path);
}
else
{
typedef agg::renderer_scanline_aa_solid<ren_base> renderer;
renderer ren(renb);
agg::rasterizer_scanline_aa<> ras;
agg::scanline_u8 sl;
if (stroke_.has_dash())
{
agg::conv_dash<path_type> dash(path);
dash_array const& d = stroke_.get_dash_array();
dash_array::const_iterator itr = d.begin();
dash_array::const_iterator end = d.end();
while (itr != end)
{
dash.add_dash(itr->first, itr->second);
++itr;
}
agg::conv_stroke<agg::conv_dash<path_type > > stroke(dash);
line_join_e join=stroke_.get_line_join();
if ( join == MITER_JOIN)
stroke.generator().line_join(agg::miter_join);
else if( join == MITER_REVERT_JOIN)
stroke.generator().line_join(agg::miter_join);
else if( join == ROUND_JOIN)
stroke.generator().line_join(agg::round_join);
else
stroke.generator().line_join(agg::bevel_join);
line_cap_e cap=stroke_.get_line_cap();
if (cap == BUTT_CAP)
stroke.generator().line_cap(agg::butt_cap);
else if (cap == SQUARE_CAP)
stroke.generator().line_cap(agg::square_cap);
else
stroke.generator().line_cap(agg::round_cap);
stroke.generator().miter_limit(4.0);
stroke.generator().width(stroke_.get_width());
ras.clip_box(0,0,image.width(),image.height());
ras.add_path(stroke);
ren.color(agg::rgba8(r, g, b, int(255*stroke_.get_opacity())));
agg::render_scanlines(ras, sl, ren);
}
else
{
agg::conv_stroke<path_type> stroke(path);
line_join_e join=stroke_.get_line_join();
if ( join == MITER_JOIN)
stroke.generator().line_join(agg::miter_join);
else if( join == MITER_REVERT_JOIN)
stroke.generator().line_join(agg::miter_join);
else if( join == ROUND_JOIN)
stroke.generator().line_join(agg::round_join);
else
stroke.generator().line_join(agg::bevel_join);
line_cap_e cap=stroke_.get_line_cap();
if (cap == BUTT_CAP)
stroke.generator().line_cap(agg::butt_cap);
else if (cap == SQUARE_CAP)
stroke.generator().line_cap(agg::square_cap);
else
stroke.generator().line_cap(agg::round_cap);
stroke.generator().miter_limit(4.0);
stroke.generator().width(stroke_.get_width());
ras.clip_box(0,0,image.width(),image.height());
ras.add_path(stroke);
ren.color(agg::rgba8(r, g, b, int(255*stroke_.get_opacity())));
agg::render_scanlines(ras, sl, ren);
}
}
}
}
}
<commit_msg>some minor changes (+fast line rendering needs fixing clipping)<commit_after>/* This file is part of Mapnik (c++ mapping toolkit)
* Copyright (C) 2005 Artem Pavlenko
*
* Mapnik 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 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.
*/
//$Id$
#include "line_symbolizer.hpp"
#include "agg_basics.h"
#include "agg_rendering_buffer.h"
#include "agg_rasterizer_scanline_aa.h"
#include "agg_conv_stroke.h"
#include "agg_conv_dash.h"
#include "agg_conv_contour.h"
#include "agg_vcgen_stroke.h"
#include "agg_conv_adaptor_vcgen.h"
#include "agg_conv_smooth_poly1.h"
#include "agg_conv_marker.h"
#include "agg_arrowhead.h"
#include "agg_vcgen_markers_term.h"
#include "agg_scanline_p.h"
#include "agg_scanline_u.h"
#include "agg_renderer_scanline.h"
#include "agg_pixfmt_rgba.h"
#include "agg_path_storage.h"
#include "agg_renderer_outline_aa.h"
#include "agg_rasterizer_outline_aa.h"
#include "agg_rasterizer_outline.h"
#include "agg_renderer_outline_image.h"
namespace mapnik
{
line_symbolizer::line_symbolizer(stroke const& stroke)
: symbolizer(),
stroke_(stroke) {}
line_symbolizer::line_symbolizer(const Color& pen,float width)
: symbolizer(),
stroke_(pen,width) {}
void line_symbolizer::render(Feature const& feat, CoordTransform const& t,Image32& image) const
{
typedef agg::renderer_base<agg::pixfmt_rgba32> ren_base;
typedef coord_transform<CoordTransform,geometry_type> path_type;
typedef agg::renderer_outline_aa<ren_base> renderer_oaa;
typedef agg::rasterizer_outline_aa<renderer_oaa> rasterizer_outline_aa;
typedef agg::renderer_scanline_aa_solid<ren_base> renderer;
geometry_ptr const& geom=feat.get_geometry();
if (geom)
{
path_type path(t,*geom);
agg::row_ptr_cache<agg::int8u> buf(image.raw_data(),image.width(),image.height(),
image.width()*4);
agg::pixfmt_rgba32 pixf(buf);
ren_base renb(pixf);
Color const& col = stroke_.get_color();
unsigned r=col.red();
unsigned g=col.green();
unsigned b=col.blue();
if (stroke_.has_dash())
{
renderer ren(renb);
agg::rasterizer_scanline_aa<> ras;
agg::scanline_u8 sl;
agg::conv_dash<path_type> dash(path);
dash_array const& d = stroke_.get_dash_array();
dash_array::const_iterator itr = d.begin();
dash_array::const_iterator end = d.end();
while (itr != end)
{
dash.add_dash(itr->first, itr->second);
++itr;
}
agg::conv_stroke<agg::conv_dash<path_type > > stroke(dash);
line_join_e join=stroke_.get_line_join();
if ( join == MITER_JOIN)
stroke.generator().line_join(agg::miter_join);
else if( join == MITER_REVERT_JOIN)
stroke.generator().line_join(agg::miter_join);
else if( join == ROUND_JOIN)
stroke.generator().line_join(agg::round_join);
else
stroke.generator().line_join(agg::bevel_join);
line_cap_e cap=stroke_.get_line_cap();
if (cap == BUTT_CAP)
stroke.generator().line_cap(agg::butt_cap);
else if (cap == SQUARE_CAP)
stroke.generator().line_cap(agg::square_cap);
else
stroke.generator().line_cap(agg::round_cap);
stroke.generator().miter_limit(4.0);
stroke.generator().width(stroke_.get_width());
ras.clip_box(0,0,image.width(),image.height());
ras.add_path(stroke);
ren.color(agg::rgba8(r, g, b, int(255*stroke_.get_opacity())));
agg::render_scanlines(ras, sl, ren);
}
else if (0)//(stroke_.get_width() <= 1.0)
{
//faster but clipping doesn't work
agg::line_profile_aa prof;
prof.width(stroke_.get_width());
renderer_oaa ren_oaa(renb, prof);
rasterizer_outline_aa ras_oaa(ren_oaa);
ren_oaa.color(agg::rgba8(r, g, b, int(255*stroke_.get_opacity())));
ren_oaa.clip_box(0,0,image.width(),image.height());
ras_oaa.add_path(path);
}
else
{
renderer ren(renb);
agg::rasterizer_scanline_aa<> ras;
agg::scanline_p8 sl;
agg::conv_stroke<path_type> stroke(path);
line_join_e join=stroke_.get_line_join();
if ( join == MITER_JOIN)
stroke.generator().line_join(agg::miter_join);
else if( join == MITER_REVERT_JOIN)
stroke.generator().line_join(agg::miter_join);
else if( join == ROUND_JOIN)
stroke.generator().line_join(agg::round_join);
else
stroke.generator().line_join(agg::bevel_join);
line_cap_e cap=stroke_.get_line_cap();
if (cap == BUTT_CAP)
stroke.generator().line_cap(agg::butt_cap);
else if (cap == SQUARE_CAP)
stroke.generator().line_cap(agg::square_cap);
else
stroke.generator().line_cap(agg::round_cap);
stroke.generator().miter_limit(4.0);
stroke.generator().width(stroke_.get_width());
ras.clip_box(0,0,image.width(),image.height());
ras.add_path(stroke);
ren.color(agg::rgba8(r, g, b, int(255*stroke_.get_opacity())));
agg::render_scanlines(ras, sl, ren);
}
}
}
}
<|endoftext|> |
<commit_before>// HeaterMeter Copyright 2011 Bryan Mayland <bmayland@capnbry.net>
#include "strings.h"
#include "rfmanager.h"
#include "hmcore.h"
void RFSource::setId(unsigned char id)
{
if (_id == id) return;
_id = id;
Value = 0;
}
void RFSource::update(rf12_packet_t *pkt)
{
_lastReceive = millis();
unsigned char newFlags = 0;
if ((pkt->byte1 & 0x10) == 0)
newFlags |= NativeItPlus;
if ((pkt->byte1 & 0x20) != 0)
newFlags |= RecentReset;
if ((pkt->hygro & 0x80) != 0)
newFlags |= LowBattery;
if (rf12_rssi() == 0)
newFlags |= LowSignal;
_flags = newFlags;
if (isNative())
Value = (((pkt->byte1 & 0x0f) * 100) + ((pkt->byte2 >> 4) * 10) + (pkt->byte2 & 0x0f)) - 400;
else
Value = ((pkt->byte1 & 0x0f) << 8) | pkt->byte2;
}
void RFManager::init(unsigned char band)
{
if (!_initialized)
{
rf12_initialize(1, band);
_initialized = true;
}
}
void RFManager::freeStaleSources(void)
{
for (unsigned char idx=0; idx<RF_SOURCE_COUNT; ++idx)
if (_sources[idx].isStale())
{
if (_callback) _callback(_sources[idx], Remove);
_sources[idx].setId(RFSOURCEID_ANY);
}
}
unsigned char RFManager::findFreeSourceIdx(void)
{
for (unsigned char idx=0; idx<RF_SOURCE_COUNT; ++idx)
if (_sources[idx].isFree())
return idx;
return 0xff;
}
unsigned char RFManager::findSourceIdx(unsigned char srcId)
{
// Get the index of the srcId, returns 0xff if it doesn't exist
for (unsigned char idx=0; idx<RF_SOURCE_COUNT; ++idx)
if (_sources[idx].getId() == srcId)
return idx;
return 0xff;
}
RFSource *RFManager::getSourceById(unsigned char srcId)
{
unsigned char idx = findSourceIdx(srcId);
return (idx != 0xff) ? &_sources[idx] : NULL;
}
void RFManager::status(void)
{
if (!_initialized)
return;
// The first item in the list the manager RFSOURCEID_NONE,CrcOk
print_P(PSTR("HMRF" CSV_DELIMITER "255" CSV_DELIMITER));
SerialX.print(_crcOk, DEC); // signalish
//Serial_csv();
//unsigned long m = millis();
//SerialX.print((m - getLastReceive()) / 1000, DEC);
// The rest of the items are Id,Flags
for (unsigned char idx=0; idx<RF_SOURCE_COUNT; ++idx)
{
if (_sources[idx].isFree())
continue;
Serial_csv();
SerialX.print(_sources[idx].getId(),DEC);
Serial_csv();
SerialX.print(_sources[idx].getFlags(), DEC);
//Serial_csv();
//unsigned int since = (m - _sources[idx].getLastReceive()) / 1000;
//SerialX.print(since, DEC);
}
Serial_nl();
}
boolean RFManager::doWork(void)
{
if (!_initialized)
return false;
boolean retVal = false;
while (rf12_recvDone())
{
_lastReceive = millis();
//print_P(PSTR("RF in")); Serial_nl();
if (rf12_crc == 0)
{
if (_crcOk < 0xff)
++_crcOk;
rf12_packet_t *pkt = (rf12_packet_t *)rf12_buf;
event e = Update;
unsigned char srcId = ((pkt->byte0 & 0x0f) << 2) | (pkt->byte1 >> 6);
unsigned char srcIdx = findSourceIdx(srcId);
if (srcIdx == 0xff)
{
srcIdx = findFreeSourceIdx();
e = static_cast<event>(Add | Update);
}
if (srcIdx != 0xff)
{
_sources[srcIdx].setId(srcId);
_sources[srcIdx].update(pkt);
if (_callback) _callback(_sources[srcIdx], e);
}
} /* if crc ok */
else if (_crcOk > 0)
{
//print_P(PSTR("RF ERR")); Serial_nl();
--_crcOk;
}
retVal = true;
} /* while recvDone() */
freeStaleSources();
return retVal;
}
<commit_msg>[hm] Fix rfmanager going bonkers after freeing the first source<commit_after>// HeaterMeter Copyright 2011 Bryan Mayland <bmayland@capnbry.net>
#include "strings.h"
#include "rfmanager.h"
#include "hmcore.h"
void RFSource::setId(unsigned char id)
{
if (_id == id) return;
_id = id;
Value = 0;
}
void RFSource::update(rf12_packet_t *pkt)
{
_lastReceive = millis();
unsigned char newFlags = 0;
if ((pkt->byte1 & 0x10) == 0)
newFlags |= NativeItPlus;
if ((pkt->byte1 & 0x20) != 0)
newFlags |= RecentReset;
if ((pkt->hygro & 0x80) != 0)
newFlags |= LowBattery;
if (rf12_rssi() == 0)
newFlags |= LowSignal;
_flags = newFlags;
if (isNative())
Value = (((pkt->byte1 & 0x0f) * 100) + ((pkt->byte2 >> 4) * 10) + (pkt->byte2 & 0x0f)) - 400;
else
Value = ((pkt->byte1 & 0x0f) << 8) | pkt->byte2;
}
void RFManager::init(unsigned char band)
{
if (!_initialized)
{
rf12_initialize(1, band);
_initialized = true;
}
}
void RFManager::freeStaleSources(void)
{
for (unsigned char idx=0; idx<RF_SOURCE_COUNT; ++idx)
if (_sources[idx].isStale())
{
if (_callback) _callback(_sources[idx], Remove);
_sources[idx].setId(RFSOURCEID_NONE);
}
}
unsigned char RFManager::findFreeSourceIdx(void)
{
for (unsigned char idx=0; idx<RF_SOURCE_COUNT; ++idx)
if (_sources[idx].isFree())
return idx;
return 0xff;
}
unsigned char RFManager::findSourceIdx(unsigned char srcId)
{
// Get the index of the srcId, returns 0xff if it doesn't exist
for (unsigned char idx=0; idx<RF_SOURCE_COUNT; ++idx)
if (_sources[idx].getId() == srcId)
return idx;
return 0xff;
}
RFSource *RFManager::getSourceById(unsigned char srcId)
{
unsigned char idx = findSourceIdx(srcId);
return (idx != 0xff) ? &_sources[idx] : NULL;
}
void RFManager::status(void)
{
if (!_initialized)
return;
// The first item in the list the manager RFSOURCEID_NONE,CrcOk
print_P(PSTR("HMRF" CSV_DELIMITER "255" CSV_DELIMITER));
SerialX.print(_crcOk, DEC); // signalish
//Serial_csv();
//unsigned long m = millis();
//SerialX.print((m - getLastReceive()) / 1000, DEC);
// The rest of the items are Id,Flags
for (unsigned char idx=0; idx<RF_SOURCE_COUNT; ++idx)
{
if (_sources[idx].isFree())
continue;
Serial_csv();
SerialX.print(_sources[idx].getId(),DEC);
Serial_csv();
SerialX.print(_sources[idx].getFlags(), DEC);
//Serial_csv();
//unsigned int since = (m - _sources[idx].getLastReceive()) / 1000;
//SerialX.print(since, DEC);
}
Serial_nl();
}
boolean RFManager::doWork(void)
{
if (!_initialized)
return false;
boolean retVal = false;
while (rf12_recvDone())
{
_lastReceive = millis();
//print_P(PSTR("RF in")); Serial_nl();
if (rf12_crc == 0)
{
if (_crcOk < 0xff)
++_crcOk;
rf12_packet_t *pkt = (rf12_packet_t *)rf12_buf;
event e = Update;
unsigned char srcId = ((pkt->byte0 & 0x0f) << 2) | (pkt->byte1 >> 6);
unsigned char srcIdx = findSourceIdx(srcId);
if (srcIdx == 0xff)
{
srcIdx = findFreeSourceIdx();
e = static_cast<event>(Add | Update);
}
if (srcIdx != 0xff)
{
_sources[srcIdx].setId(srcId);
_sources[srcIdx].update(pkt);
if (_callback) _callback(_sources[srcIdx], e);
}
} /* if crc ok */
else if (_crcOk > 0)
{
//print_P(PSTR("RF ERR")); Serial_nl();
--_crcOk;
}
retVal = true;
} /* while recvDone() */
freeStaleSources();
return retVal;
}
<|endoftext|> |
<commit_before>/*
kopetedbusinterfaceprivate.h - Kopete D-Bus interface private class
Copyright (c) 2008 by Dennis Nienhüser <earthwings@gentoo.org>
Kopete (c) 2002-2008 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* 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 of the License, or (at your option) any later version. *
* *
*************************************************************************
*/
#include "kopetedbusinterface_p.h"
#include <QtCore/QTimer>
#include <kopetecontactlist.h>
#include <kopetemetacontact.h>
#include <kopetecontact.h>
#include <kopetechatsessionmanager.h>
#include <kopeteviewmanager.h>
#include <kopetemessageevent.h>
ContactStalker::ContactStalker(Kopete::MetaContact *contact)
{
m_contact = contact;
QObject::connect( Kopete::ContactList::self(),
SIGNAL(metaContactRemoved( Kopete::MetaContact *)),
this, SLOT(slotMetaContactRemoved(Kopete::MetaContact *)) );
QObject::connect( contact, SIGNAL(onlineStatusChanged(Kopete::MetaContact*,Kopete::OnlineStatus::StatusType)),
this, SLOT(slotEmitSignalDelayed()));
QObject::connect( contact, SIGNAL(displayNameChanged(const QString &, const QString &)),
this, SLOT(slotEmitSignalDelayed()));
QObject::connect( contact, SIGNAL(photoChanged()),
this, SLOT(slotEmitSignalDelayed()));
QObject::connect( contact, SIGNAL(contactAdded(Kopete::Contact*)),
this, SLOT(slotEmitSignalDelayed()));
QObject::connect( contact, SIGNAL(contactRemoved(Kopete::Contact*)),
this, SLOT(slotEmitSignalDelayed()));
QObject::connect(Kopete::ChatSessionManager::self(),
SIGNAL( display( Kopete::Message &, Kopete::ChatSession *) ),
this, SLOT ( messageAppended( Kopete::Message &, Kopete::ChatSession *) ) );
m_lastChange = QTime::currentTime();
slotEmitSignal();
}
void ContactStalker::slotEmitSignalDelayed()
{
const int timeout(1500);
if (m_lastChange.elapsed() >= timeout)
{
m_lastChange = QTime::currentTime();
QTimer::singleShot(timeout, this, SLOT(slotEmitSignal()));
}
}
void ContactStalker::slotEmitSignal()
{
if (m_contact)
{
emit contactChanged(m_contact->metaContactId());
}
}
void ContactStalker::messageAppended(Kopete::Message &message,
Kopete::ChatSession *session)
{
Q_UNUSED(session);
if(!m_contact)
{
return;
}
if ( message.direction() == Kopete::Message::Inbound ) {
QString contactId = message.from()->metaContact()->metaContactId();
if (contactId == m_contact->metaContactId())
{
foreach(Kopete::Contact *subContact, m_contact->contacts())
{
QList<Kopete::MessageEvent*> pendingMessages = KopeteViewManager::viewManager()->pendingMessages(subContact);
foreach(Kopete::MessageEvent *event, pendingMessages)
{
connect(event, SIGNAL(done(Kopete::MessageEvent*)), this, SLOT(slotEmitSignalDelayed()));
}
}
emit contactChanged(contactId);
}
}
}
void ContactStalker::slotMetaContactRemoved(Kopete::MetaContact *contact)
{
if (contact == m_contact)
{
m_contact = 0L;
emit contactChanged(contact->metaContactId());
}
}
KopeteDBusInterfacePrivate::KopeteDBusInterfacePrivate()
{
QObject::connect(Kopete::ContactList::self(),
SIGNAL(metaContactAdded(Kopete::MetaContact*)),
this, SLOT(slotMetaContactAdded(Kopete::MetaContact*)));
foreach( Kopete::MetaContact *contact, Kopete::ContactList::self()->metaContacts() )
{
this->slotMetaContactAdded(contact);
}
}
void KopeteDBusInterfacePrivate::slotMetaContactAdded(
Kopete::MetaContact* contact)
{
if ( contact ) {
ContactStalker * stalker = new ContactStalker(contact);
connect( stalker, SIGNAL(contactChanged(QString)),
this, SIGNAL(contactChanged(QString)));
}
}
QStringList KopeteDBusInterfacePrivate::listContact(const QList<
Kopete::MetaContact*> &contactList)
{
QStringList result;
foreach(Kopete::MetaContact *contact, contactList)
{
result << contact->metaContactId();
}
return result;
}
Kopete::OnlineStatusManager::Categories KopeteDBusInterfacePrivate::status2Value(
const QString &status)
{
Kopete::OnlineStatusManager::Categories statusValue;
if ( status.toLower() == QLatin1String("online") || status.toLower()
== QLatin1String("available") ) {
statusValue = Kopete::OnlineStatusManager::Online;
} else if ( status.toLower() == QLatin1String("busy") ) {
statusValue = Kopete::OnlineStatusManager::Busy;
} else if ( status.toLower() == QLatin1String("away") ) {
statusValue = Kopete::OnlineStatusManager::Away;
} else if ( status.toLower() == QLatin1String("invisible") ) {
statusValue = Kopete::OnlineStatusManager::Invisible;
} else if ( status.toLower() == QLatin1String("offline") ) {
statusValue = Kopete::OnlineStatusManager::Offline;
}
return statusValue;
}
Kopete::MetaContact *KopeteDBusInterfacePrivate::findContact(
const QString &nameOrId)
{
Kopete::MetaContact *contact = 0L;
if ( nameOrId.count(':') == 2 ) {
QStringList tokens = nameOrId.split(':');
Q_ASSERT(tokens.size() == 3);
Kopete::Contact *candidate = Kopete::ContactList::self()->findContact(
tokens.at(0), tokens.at(1), tokens.at(2));
if ( candidate ) {
contact = candidate->metaContact();
}
}
if ( !contact ) {
contact = Kopete::ContactList::self()->findMetaContactByContactId(
nameOrId);
}
if ( !contact ) {
contact = Kopete::ContactList::self()->findMetaContactByDisplayName(
nameOrId);
}
return contact;
}
#include "kopetedbusinterface_p.moc"
<commit_msg>D-Bus Interface: Adds the possibility to manage contacts by MetaContact IDs http://reviewboard.kde.org/r/670/<commit_after>/*
kopetedbusinterfaceprivate.h - Kopete D-Bus interface private class
Copyright (c) 2008 by Dennis Nienhüser <earthwings@gentoo.org>
Kopete (c) 2002-2008 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* 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 of the License, or (at your option) any later version. *
* *
*************************************************************************
*/
#include "kopetedbusinterface_p.h"
#include <QtCore/QTimer>
#include <kopetecontactlist.h>
#include <kopetemetacontact.h>
#include <kopetecontact.h>
#include <kopetechatsessionmanager.h>
#include <kopeteviewmanager.h>
#include <kopetemessageevent.h>
ContactStalker::ContactStalker(Kopete::MetaContact *contact)
{
m_contact = contact;
QObject::connect( Kopete::ContactList::self(),
SIGNAL(metaContactRemoved( Kopete::MetaContact *)),
this, SLOT(slotMetaContactRemoved(Kopete::MetaContact *)) );
QObject::connect( contact, SIGNAL(onlineStatusChanged(Kopete::MetaContact*,Kopete::OnlineStatus::StatusType)),
this, SLOT(slotEmitSignalDelayed()));
QObject::connect( contact, SIGNAL(displayNameChanged(const QString &, const QString &)),
this, SLOT(slotEmitSignalDelayed()));
QObject::connect( contact, SIGNAL(photoChanged()),
this, SLOT(slotEmitSignalDelayed()));
QObject::connect( contact, SIGNAL(contactAdded(Kopete::Contact*)),
this, SLOT(slotEmitSignalDelayed()));
QObject::connect( contact, SIGNAL(contactRemoved(Kopete::Contact*)),
this, SLOT(slotEmitSignalDelayed()));
QObject::connect(Kopete::ChatSessionManager::self(),
SIGNAL( display( Kopete::Message &, Kopete::ChatSession *) ),
this, SLOT ( messageAppended( Kopete::Message &, Kopete::ChatSession *) ) );
m_lastChange = QTime::currentTime();
slotEmitSignal();
}
void ContactStalker::slotEmitSignalDelayed()
{
const int timeout(1500);
if (m_lastChange.elapsed() >= timeout)
{
m_lastChange = QTime::currentTime();
QTimer::singleShot(timeout, this, SLOT(slotEmitSignal()));
}
}
void ContactStalker::slotEmitSignal()
{
if (m_contact)
{
emit contactChanged(m_contact->metaContactId());
}
}
void ContactStalker::messageAppended(Kopete::Message &message,
Kopete::ChatSession *session)
{
Q_UNUSED(session);
if(!m_contact)
{
return;
}
if ( message.direction() == Kopete::Message::Inbound ) {
QString contactId = message.from()->metaContact()->metaContactId();
if (contactId == m_contact->metaContactId())
{
foreach(Kopete::Contact *subContact, m_contact->contacts())
{
QList<Kopete::MessageEvent*> pendingMessages = KopeteViewManager::viewManager()->pendingMessages(subContact);
foreach(Kopete::MessageEvent *event, pendingMessages)
{
connect(event, SIGNAL(done(Kopete::MessageEvent*)), this, SLOT(slotEmitSignalDelayed()));
}
}
emit contactChanged(contactId);
}
}
}
void ContactStalker::slotMetaContactRemoved(Kopete::MetaContact *contact)
{
if (contact == m_contact)
{
m_contact = 0L;
emit contactChanged(contact->metaContactId());
}
}
KopeteDBusInterfacePrivate::KopeteDBusInterfacePrivate()
{
QObject::connect(Kopete::ContactList::self(),
SIGNAL(metaContactAdded(Kopete::MetaContact*)),
this, SLOT(slotMetaContactAdded(Kopete::MetaContact*)));
foreach( Kopete::MetaContact *contact, Kopete::ContactList::self()->metaContacts() )
{
this->slotMetaContactAdded(contact);
}
}
void KopeteDBusInterfacePrivate::slotMetaContactAdded(
Kopete::MetaContact* contact)
{
if ( contact ) {
ContactStalker * stalker = new ContactStalker(contact);
connect( stalker, SIGNAL(contactChanged(QString)),
this, SIGNAL(contactChanged(QString)));
}
}
QStringList KopeteDBusInterfacePrivate::listContact(const QList<
Kopete::MetaContact*> &contactList)
{
QStringList result;
foreach(Kopete::MetaContact *contact, contactList)
{
result << contact->metaContactId();
}
return result;
}
Kopete::OnlineStatusManager::Categories KopeteDBusInterfacePrivate::status2Value(
const QString &status)
{
Kopete::OnlineStatusManager::Categories statusValue;
if ( status.toLower() == QLatin1String("online") || status.toLower()
== QLatin1String("available") ) {
statusValue = Kopete::OnlineStatusManager::Online;
} else if ( status.toLower() == QLatin1String("busy") ) {
statusValue = Kopete::OnlineStatusManager::Busy;
} else if ( status.toLower() == QLatin1String("away") ) {
statusValue = Kopete::OnlineStatusManager::Away;
} else if ( status.toLower() == QLatin1String("invisible") ) {
statusValue = Kopete::OnlineStatusManager::Invisible;
} else if ( status.toLower() == QLatin1String("offline") ) {
statusValue = Kopete::OnlineStatusManager::Offline;
}
return statusValue;
}
Kopete::MetaContact *KopeteDBusInterfacePrivate::findContact(
const QString &nameOrId)
{
Kopete::MetaContact *contact = 0L;
if ( nameOrId.count(':') == 2 ) {
QStringList tokens = nameOrId.split(':');
Q_ASSERT(tokens.size() == 3);
Kopete::Contact *candidate = Kopete::ContactList::self()->findContact(
tokens.at(0), tokens.at(1), tokens.at(2));
if ( candidate ) {
contact = candidate->metaContact();
}
}
if ( !contact ) {
contact = Kopete::ContactList::self()->metaContact(nameOrId);
}
if ( !contact ) {
contact = Kopete::ContactList::self()->findMetaContactByContactId(
nameOrId);
}
if ( !contact ) {
contact = Kopete::ContactList::self()->findMetaContactByDisplayName(
nameOrId);
}
return contact;
}
#include "kopetedbusinterface_p.moc"
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/debug_util.h"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/sysctl.h>
#include <sys/types.h>
#include <unistd.h>
#include <string>
#include <vector>
#if defined(__GLIBCXX__)
#include <cxxabi.h>
#endif
#if defined(OS_MACOSX)
#include <AvailabilityMacros.h>
#endif
#include <iostream>
#include "base/basictypes.h"
#include "base/compat_execinfo.h"
#include "base/eintr_wrapper.h"
#include "base/logging.h"
#include "base/safe_strerror_posix.h"
#include "base/scoped_ptr.h"
#include "base/string_piece.h"
#include "base/stringprintf.h"
#if defined(USE_SYMBOLIZE)
#include "base/third_party/symbolize/symbolize.h"
#endif
namespace {
// The prefix used for mangled symbols, per the Itanium C++ ABI:
// http://www.codesourcery.com/cxx-abi/abi.html#mangling
const char kMangledSymbolPrefix[] = "_Z";
// Characters that can be used for symbols, generated by Ruby:
// (('a'..'z').to_a+('A'..'Z').to_a+('0'..'9').to_a + ['_']).join
const char kSymbolCharacters[] =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
// Demangles C++ symbols in the given text. Example:
//
// "sconsbuild/Debug/base_unittests(_ZN10StackTraceC1Ev+0x20) [0x817778c]"
// =>
// "sconsbuild/Debug/base_unittests(StackTrace::StackTrace()+0x20) [0x817778c]"
void DemangleSymbols(std::string* text) {
#if defined(__GLIBCXX__)
std::string::size_type search_from = 0;
while (search_from < text->size()) {
// Look for the start of a mangled symbol, from search_from.
std::string::size_type mangled_start =
text->find(kMangledSymbolPrefix, search_from);
if (mangled_start == std::string::npos) {
break; // Mangled symbol not found.
}
// Look for the end of the mangled symbol.
std::string::size_type mangled_end =
text->find_first_not_of(kSymbolCharacters, mangled_start);
if (mangled_end == std::string::npos) {
mangled_end = text->size();
}
std::string mangled_symbol =
text->substr(mangled_start, mangled_end - mangled_start);
// Try to demangle the mangled symbol candidate.
int status = 0;
scoped_ptr_malloc<char> demangled_symbol(
abi::__cxa_demangle(mangled_symbol.c_str(), NULL, 0, &status));
if (status == 0) { // Demangling is successful.
// Remove the mangled symbol.
text->erase(mangled_start, mangled_end - mangled_start);
// Insert the demangled symbol.
text->insert(mangled_start, demangled_symbol.get());
// Next time, we'll start right after the demangled symbol we inserted.
search_from = mangled_start + strlen(demangled_symbol.get());
} else {
// Failed to demangle. Retry after the "_Z" we just found.
search_from = mangled_start + 2;
}
}
#endif // defined(__GLIBCXX__)
}
// Gets the backtrace as a vector of strings. If possible, resolve symbol
// names and attach these. Otherwise just use raw addresses. Returns true
// if any symbol name is resolved.
bool GetBacktraceStrings(void **trace, int size,
std::vector<std::string>* trace_strings) {
bool symbolized = false;
#if defined(USE_SYMBOLIZE)
for (int i = 0; i < size; ++i) {
char symbol[1024];
// Subtract by one as return address of function may be in the next
// function when a function is annotated as noreturn.
if (google::Symbolize(static_cast<char *>(trace[i]) - 1,
symbol, sizeof(symbol))) {
// Don't call DemangleSymbols() here as the symbol is demangled by
// google::Symbolize().
trace_strings->push_back(
base::StringPrintf("%s [%p]", symbol, trace[i]));
symbolized = true;
} else {
trace_strings->push_back(base::StringPrintf("%p", trace[i]));
}
}
#else
scoped_ptr_malloc<char*> trace_symbols(backtrace_symbols(trace, size));
if (trace_symbols.get()) {
for (int i = 0; i < size; ++i) {
std::string trace_symbol = trace_symbols.get()[i];
DemangleSymbols(&trace_symbol);
trace_strings->push_back(trace_symbol);
}
symbolized = true;
} else {
for (int i = 0; i < size; ++i) {
trace_strings->push_back(base::StringPrintf("%p", trace[i]));
}
}
#endif // defined(USE_SYMBOLIZE)
return symbolized;
}
} // namespace
// static
bool DebugUtil::SpawnDebuggerOnProcess(unsigned /* process_id */) {
NOTIMPLEMENTED();
return false;
}
#if defined(OS_MACOSX)
// Based on Apple's recommended method as described in
// http://developer.apple.com/qa/qa2004/qa1361.html
// static
bool DebugUtil::BeingDebugged() {
// If the process is sandboxed then we can't use the sysctl, so cache the
// value.
static bool is_set = false;
static bool being_debugged = false;
if (is_set) {
return being_debugged;
}
// Initialize mib, which tells sysctl what info we want. In this case,
// we're looking for information about a specific process ID.
int mib[] = {
CTL_KERN,
KERN_PROC,
KERN_PROC_PID,
getpid()
};
// Caution: struct kinfo_proc is marked __APPLE_API_UNSTABLE. The source and
// binary interfaces may change.
struct kinfo_proc info;
size_t info_size = sizeof(info);
int sysctl_result = sysctl(mib, arraysize(mib), &info, &info_size, NULL, 0);
DCHECK_EQ(sysctl_result, 0);
if (sysctl_result != 0) {
is_set = true;
being_debugged = false;
return being_debugged;
}
// This process is being debugged if the P_TRACED flag is set.
is_set = true;
being_debugged = (info.kp_proc.p_flag & P_TRACED) != 0;
return being_debugged;
}
#elif defined(OS_LINUX)
// We can look in /proc/self/status for TracerPid. We are likely used in crash
// handling, so we are careful not to use the heap or have side effects.
// Another option that is common is to try to ptrace yourself, but then we
// can't detach without forking(), and that's not so great.
// static
bool DebugUtil::BeingDebugged() {
int status_fd = open("/proc/self/status", O_RDONLY);
if (status_fd == -1)
return false;
// We assume our line will be in the first 1024 characters and that we can
// read this much all at once. In practice this will generally be true.
// This simplifies and speeds up things considerably.
char buf[1024];
ssize_t num_read = HANDLE_EINTR(read(status_fd, buf, sizeof(buf)));
if (HANDLE_EINTR(close(status_fd)) < 0)
return false;
if (num_read <= 0)
return false;
base::StringPiece status(buf, num_read);
base::StringPiece tracer("TracerPid:\t");
base::StringPiece::size_type pid_index = status.find(tracer);
if (pid_index == base::StringPiece::npos)
return false;
// Our pid is 0 without a debugger, assume this for any pid starting with 0.
pid_index += tracer.size();
return pid_index < status.size() && status[pid_index] != '0';
}
#elif defined(OS_FREEBSD)
bool DebugUtil::BeingDebugged() {
// TODO(benl): can we determine this under FreeBSD?
NOTIMPLEMENTED();
return false;
}
#endif // defined(OS_FREEBSD)
// We want to break into the debugger in Debug mode, and cause a crash dump in
// Release mode. Breakpad behaves as follows:
//
// +-------+-----------------+-----------------+
// | OS | Dump on SIGTRAP | Dump on SIGABRT |
// +-------+-----------------+-----------------+
// | Linux | N | Y |
// | Mac | Y | N |
// +-------+-----------------+-----------------+
//
// Thus we do the following:
// Linux: Debug mode, send SIGTRAP; Release mode, send SIGABRT.
// Mac: Always send SIGTRAP.
#if defined(NDEBUG) && !defined(OS_MACOSX)
#define DEBUG_BREAK() abort()
#elif defined(ARCH_CPU_ARM_FAMILY)
#define DEBUG_BREAK() asm("bkpt 0")
#else
#define DEBUG_BREAK() asm("int3")
#endif
// static
void DebugUtil::BreakDebugger() {
DEBUG_BREAK();
}
StackTrace::StackTrace() {
#if defined(OS_MACOSX) && MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
if (backtrace == NULL) {
count_ = 0;
return;
}
#endif
// Though the backtrace API man page does not list any possible negative
// return values, we take no chance.
count_ = std::max(backtrace(trace_, arraysize(trace_)), 0);
}
void StackTrace::PrintBacktrace() {
#if defined(OS_MACOSX) && MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
if (backtrace_symbols_fd == NULL)
return;
#endif
fflush(stderr);
std::vector<std::string> trace_strings;
GetBacktraceStrings(trace_, count_, &trace_strings);
for (size_t i = 0; i < trace_strings.size(); ++i) {
std::cerr << "\t" << trace_strings[i] << "\n";
}
}
void StackTrace::OutputToStream(std::ostream* os) {
#if defined(OS_MACOSX) && MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
if (backtrace_symbols == NULL)
return;
#endif
std::vector<std::string> trace_strings;
if (GetBacktraceStrings(trace_, count_, &trace_strings)) {
(*os) << "Backtrace:\n";
} else {
(*os) << "Unable get symbols for backtrace (" << safe_strerror(errno)
<< "). Dumping raw addresses in trace:\n";
}
for (size_t i = 0; i < trace_strings.size(); ++i) {
(*os) << "\t" << trace_strings[i] << "\n";
}
}
<commit_msg>clang: don't build unused function<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/debug_util.h"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/sysctl.h>
#include <sys/types.h>
#include <unistd.h>
#include <string>
#include <vector>
#if defined(__GLIBCXX__)
#include <cxxabi.h>
#endif
#if defined(OS_MACOSX)
#include <AvailabilityMacros.h>
#endif
#include <iostream>
#include "base/basictypes.h"
#include "base/compat_execinfo.h"
#include "base/eintr_wrapper.h"
#include "base/logging.h"
#include "base/safe_strerror_posix.h"
#include "base/scoped_ptr.h"
#include "base/string_piece.h"
#include "base/stringprintf.h"
#if defined(USE_SYMBOLIZE)
#include "base/third_party/symbolize/symbolize.h"
#endif
namespace {
// The prefix used for mangled symbols, per the Itanium C++ ABI:
// http://www.codesourcery.com/cxx-abi/abi.html#mangling
const char kMangledSymbolPrefix[] = "_Z";
// Characters that can be used for symbols, generated by Ruby:
// (('a'..'z').to_a+('A'..'Z').to_a+('0'..'9').to_a + ['_']).join
const char kSymbolCharacters[] =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
#if !defined(USE_SYMBOLIZE)
// Demangles C++ symbols in the given text. Example:
//
// "sconsbuild/Debug/base_unittests(_ZN10StackTraceC1Ev+0x20) [0x817778c]"
// =>
// "sconsbuild/Debug/base_unittests(StackTrace::StackTrace()+0x20) [0x817778c]"
void DemangleSymbols(std::string* text) {
#if defined(__GLIBCXX__)
std::string::size_type search_from = 0;
while (search_from < text->size()) {
// Look for the start of a mangled symbol, from search_from.
std::string::size_type mangled_start =
text->find(kMangledSymbolPrefix, search_from);
if (mangled_start == std::string::npos) {
break; // Mangled symbol not found.
}
// Look for the end of the mangled symbol.
std::string::size_type mangled_end =
text->find_first_not_of(kSymbolCharacters, mangled_start);
if (mangled_end == std::string::npos) {
mangled_end = text->size();
}
std::string mangled_symbol =
text->substr(mangled_start, mangled_end - mangled_start);
// Try to demangle the mangled symbol candidate.
int status = 0;
scoped_ptr_malloc<char> demangled_symbol(
abi::__cxa_demangle(mangled_symbol.c_str(), NULL, 0, &status));
if (status == 0) { // Demangling is successful.
// Remove the mangled symbol.
text->erase(mangled_start, mangled_end - mangled_start);
// Insert the demangled symbol.
text->insert(mangled_start, demangled_symbol.get());
// Next time, we'll start right after the demangled symbol we inserted.
search_from = mangled_start + strlen(demangled_symbol.get());
} else {
// Failed to demangle. Retry after the "_Z" we just found.
search_from = mangled_start + 2;
}
}
#endif // defined(__GLIBCXX__)
}
#endif // !defined(USE_SYMBOLIZE)
// Gets the backtrace as a vector of strings. If possible, resolve symbol
// names and attach these. Otherwise just use raw addresses. Returns true
// if any symbol name is resolved.
bool GetBacktraceStrings(void **trace, int size,
std::vector<std::string>* trace_strings) {
bool symbolized = false;
#if defined(USE_SYMBOLIZE)
for (int i = 0; i < size; ++i) {
char symbol[1024];
// Subtract by one as return address of function may be in the next
// function when a function is annotated as noreturn.
if (google::Symbolize(static_cast<char *>(trace[i]) - 1,
symbol, sizeof(symbol))) {
// Don't call DemangleSymbols() here as the symbol is demangled by
// google::Symbolize().
trace_strings->push_back(
base::StringPrintf("%s [%p]", symbol, trace[i]));
symbolized = true;
} else {
trace_strings->push_back(base::StringPrintf("%p", trace[i]));
}
}
#else
scoped_ptr_malloc<char*> trace_symbols(backtrace_symbols(trace, size));
if (trace_symbols.get()) {
for (int i = 0; i < size; ++i) {
std::string trace_symbol = trace_symbols.get()[i];
DemangleSymbols(&trace_symbol);
trace_strings->push_back(trace_symbol);
}
symbolized = true;
} else {
for (int i = 0; i < size; ++i) {
trace_strings->push_back(base::StringPrintf("%p", trace[i]));
}
}
#endif // defined(USE_SYMBOLIZE)
return symbolized;
}
} // namespace
// static
bool DebugUtil::SpawnDebuggerOnProcess(unsigned /* process_id */) {
NOTIMPLEMENTED();
return false;
}
#if defined(OS_MACOSX)
// Based on Apple's recommended method as described in
// http://developer.apple.com/qa/qa2004/qa1361.html
// static
bool DebugUtil::BeingDebugged() {
// If the process is sandboxed then we can't use the sysctl, so cache the
// value.
static bool is_set = false;
static bool being_debugged = false;
if (is_set) {
return being_debugged;
}
// Initialize mib, which tells sysctl what info we want. In this case,
// we're looking for information about a specific process ID.
int mib[] = {
CTL_KERN,
KERN_PROC,
KERN_PROC_PID,
getpid()
};
// Caution: struct kinfo_proc is marked __APPLE_API_UNSTABLE. The source and
// binary interfaces may change.
struct kinfo_proc info;
size_t info_size = sizeof(info);
int sysctl_result = sysctl(mib, arraysize(mib), &info, &info_size, NULL, 0);
DCHECK_EQ(sysctl_result, 0);
if (sysctl_result != 0) {
is_set = true;
being_debugged = false;
return being_debugged;
}
// This process is being debugged if the P_TRACED flag is set.
is_set = true;
being_debugged = (info.kp_proc.p_flag & P_TRACED) != 0;
return being_debugged;
}
#elif defined(OS_LINUX)
// We can look in /proc/self/status for TracerPid. We are likely used in crash
// handling, so we are careful not to use the heap or have side effects.
// Another option that is common is to try to ptrace yourself, but then we
// can't detach without forking(), and that's not so great.
// static
bool DebugUtil::BeingDebugged() {
int status_fd = open("/proc/self/status", O_RDONLY);
if (status_fd == -1)
return false;
// We assume our line will be in the first 1024 characters and that we can
// read this much all at once. In practice this will generally be true.
// This simplifies and speeds up things considerably.
char buf[1024];
ssize_t num_read = HANDLE_EINTR(read(status_fd, buf, sizeof(buf)));
if (HANDLE_EINTR(close(status_fd)) < 0)
return false;
if (num_read <= 0)
return false;
base::StringPiece status(buf, num_read);
base::StringPiece tracer("TracerPid:\t");
base::StringPiece::size_type pid_index = status.find(tracer);
if (pid_index == base::StringPiece::npos)
return false;
// Our pid is 0 without a debugger, assume this for any pid starting with 0.
pid_index += tracer.size();
return pid_index < status.size() && status[pid_index] != '0';
}
#elif defined(OS_FREEBSD)
bool DebugUtil::BeingDebugged() {
// TODO(benl): can we determine this under FreeBSD?
NOTIMPLEMENTED();
return false;
}
#endif // defined(OS_FREEBSD)
// We want to break into the debugger in Debug mode, and cause a crash dump in
// Release mode. Breakpad behaves as follows:
//
// +-------+-----------------+-----------------+
// | OS | Dump on SIGTRAP | Dump on SIGABRT |
// +-------+-----------------+-----------------+
// | Linux | N | Y |
// | Mac | Y | N |
// +-------+-----------------+-----------------+
//
// Thus we do the following:
// Linux: Debug mode, send SIGTRAP; Release mode, send SIGABRT.
// Mac: Always send SIGTRAP.
#if defined(NDEBUG) && !defined(OS_MACOSX)
#define DEBUG_BREAK() abort()
#elif defined(ARCH_CPU_ARM_FAMILY)
#define DEBUG_BREAK() asm("bkpt 0")
#else
#define DEBUG_BREAK() asm("int3")
#endif
// static
void DebugUtil::BreakDebugger() {
DEBUG_BREAK();
}
StackTrace::StackTrace() {
#if defined(OS_MACOSX) && MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
if (backtrace == NULL) {
count_ = 0;
return;
}
#endif
// Though the backtrace API man page does not list any possible negative
// return values, we take no chance.
count_ = std::max(backtrace(trace_, arraysize(trace_)), 0);
}
void StackTrace::PrintBacktrace() {
#if defined(OS_MACOSX) && MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
if (backtrace_symbols_fd == NULL)
return;
#endif
fflush(stderr);
std::vector<std::string> trace_strings;
GetBacktraceStrings(trace_, count_, &trace_strings);
for (size_t i = 0; i < trace_strings.size(); ++i) {
std::cerr << "\t" << trace_strings[i] << "\n";
}
}
void StackTrace::OutputToStream(std::ostream* os) {
#if defined(OS_MACOSX) && MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
if (backtrace_symbols == NULL)
return;
#endif
std::vector<std::string> trace_strings;
if (GetBacktraceStrings(trace_, count_, &trace_strings)) {
(*os) << "Backtrace:\n";
} else {
(*os) << "Unable get symbols for backtrace (" << safe_strerror(errno)
<< "). Dumping raw addresses in trace:\n";
}
for (size_t i = 0; i < trace_strings.size(); ++i) {
(*os) << "\t" << trace_strings[i] << "\n";
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 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 "build/build_config.h"
#include "base/debug_util.h"
#if defined(OS_LINUX)
#include <unistd.h>
#include <execinfo.h>
#endif
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/sysctl.h>
#include <sys/types.h>
#include <unistd.h>
#include "base/basictypes.h"
#include "base/logging.h"
#include "base/string_piece.h"
// static
bool DebugUtil::SpawnDebuggerOnProcess(unsigned /* process_id */) {
NOTIMPLEMENTED();
return false;
}
#if defined(OS_MACOSX)
// Based on Apple's recommended method as described in
// http://developer.apple.com/qa/qa2004/qa1361.html
// static
bool DebugUtil::BeingDebugged() {
// Initialize mib, which tells sysctl what info we want. In this case,
// we're looking for information about a specific process ID.
int mib[] = {
CTL_KERN,
KERN_PROC,
KERN_PROC_PID,
getpid()
};
// Caution: struct kinfo_proc is marked __APPLE_API_UNSTABLE. The source and
// binary interfaces may change.
struct kinfo_proc info;
size_t info_size = sizeof(info);
int sysctl_result = sysctl(mib, arraysize(mib), &info, &info_size, NULL, 0);
DCHECK(sysctl_result == 0);
if (sysctl_result != 0)
return false;
// This process is being debugged if the P_TRACED flag is set.
return (info.kp_proc.p_flag & P_TRACED) != 0;
}
#elif defined(OS_LINUX)
// We can look in /proc/self/status for TracerPid. We are likely used in crash
// handling, so we are careful not to use the heap or have side effects.
// Another option that is common is to try to ptrace yourself, but then we
// can't detach without forking(), and that's not so great.
// static
bool DebugUtil::BeingDebugged() {
int status_fd = open("/proc/self/status", O_RDONLY);
if (status_fd == -1)
return false;
// We assume our line will be in the first 1024 characters and that we can
// read this much all at once. In practice this will generally be true.
// This simplifies and speeds up things considerably.
char buf[1024];
ssize_t num_read = read(status_fd, buf, sizeof(buf));
close(status_fd);
if (num_read <= 0)
return false;
StringPiece status(buf, num_read);
StringPiece tracer("TracerPid:\t");
StringPiece::size_type pid_index = status.find(tracer);
if (pid_index == StringPiece::npos)
return false;
// Our pid is 0 without a debugger, assume this for any pid starting with 0.
pid_index += tracer.size();
return pid_index < status.size() && status[pid_index] != '0';
}
#endif // OS_LINUX
// static
void DebugUtil::BreakDebugger() {
asm ("int3");
}
#if defined(OS_LINUX)
StackTrace::StackTrace() {
static const unsigned kMaxCallers = 256;
void* callers[kMaxCallers];
int count = backtrace(callers, kMaxCallers);
trace_.resize(count);
memcpy(&trace_[0], callers, sizeof(void*) * count);
}
void StackTrace::PrintBacktrace() {
fflush(stderr);
backtrace_symbols_fd(&trace_[0], trace_.size(), STDERR_FILENO);
}
#elif defined(OS_MACOSX)
// TODO(port): complete this code
StackTrace::StackTrace() { }
StackTrace::PrintBacktrace() {
NOTIMPLEMENTED();
}
#endif // defined(OS_MACOSX)
const void *const *StackTrace::Addresses(size_t* count) {
*count = trace_.size();
if (trace_.size())
return &trace_[0];
return NULL;
}
<commit_msg>Mac build fix<commit_after>// Copyright (c) 2006-2008 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 "build/build_config.h"
#include "base/debug_util.h"
#if defined(OS_LINUX)
#include <unistd.h>
#include <execinfo.h>
#endif
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/sysctl.h>
#include <sys/types.h>
#include <unistd.h>
#include "base/basictypes.h"
#include "base/logging.h"
#include "base/string_piece.h"
// static
bool DebugUtil::SpawnDebuggerOnProcess(unsigned /* process_id */) {
NOTIMPLEMENTED();
return false;
}
#if defined(OS_MACOSX)
// Based on Apple's recommended method as described in
// http://developer.apple.com/qa/qa2004/qa1361.html
// static
bool DebugUtil::BeingDebugged() {
// Initialize mib, which tells sysctl what info we want. In this case,
// we're looking for information about a specific process ID.
int mib[] = {
CTL_KERN,
KERN_PROC,
KERN_PROC_PID,
getpid()
};
// Caution: struct kinfo_proc is marked __APPLE_API_UNSTABLE. The source and
// binary interfaces may change.
struct kinfo_proc info;
size_t info_size = sizeof(info);
int sysctl_result = sysctl(mib, arraysize(mib), &info, &info_size, NULL, 0);
DCHECK(sysctl_result == 0);
if (sysctl_result != 0)
return false;
// This process is being debugged if the P_TRACED flag is set.
return (info.kp_proc.p_flag & P_TRACED) != 0;
}
#elif defined(OS_LINUX)
// We can look in /proc/self/status for TracerPid. We are likely used in crash
// handling, so we are careful not to use the heap or have side effects.
// Another option that is common is to try to ptrace yourself, but then we
// can't detach without forking(), and that's not so great.
// static
bool DebugUtil::BeingDebugged() {
int status_fd = open("/proc/self/status", O_RDONLY);
if (status_fd == -1)
return false;
// We assume our line will be in the first 1024 characters and that we can
// read this much all at once. In practice this will generally be true.
// This simplifies and speeds up things considerably.
char buf[1024];
ssize_t num_read = read(status_fd, buf, sizeof(buf));
close(status_fd);
if (num_read <= 0)
return false;
StringPiece status(buf, num_read);
StringPiece tracer("TracerPid:\t");
StringPiece::size_type pid_index = status.find(tracer);
if (pid_index == StringPiece::npos)
return false;
// Our pid is 0 without a debugger, assume this for any pid starting with 0.
pid_index += tracer.size();
return pid_index < status.size() && status[pid_index] != '0';
}
#endif // OS_LINUX
// static
void DebugUtil::BreakDebugger() {
asm ("int3");
}
#if defined(OS_LINUX)
StackTrace::StackTrace() {
static const unsigned kMaxCallers = 256;
void* callers[kMaxCallers];
int count = backtrace(callers, kMaxCallers);
trace_.resize(count);
memcpy(&trace_[0], callers, sizeof(void*) * count);
}
void StackTrace::PrintBacktrace() {
fflush(stderr);
backtrace_symbols_fd(&trace_[0], trace_.size(), STDERR_FILENO);
}
#elif defined(OS_MACOSX)
// TODO(port): complete this code
StackTrace::StackTrace() { }
void StackTrace::PrintBacktrace() {
NOTIMPLEMENTED();
}
#endif // defined(OS_MACOSX)
const void *const *StackTrace::Addresses(size_t* count) {
*count = trace_.size();
if (trace_.size())
return &trace_[0];
return NULL;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012-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 "dbwrapper.h"
#include "util.h"
#include "random.h"
#include <boost/filesystem.hpp>
#include <leveldb/cache.h>
#include <leveldb/env.h>
#include <leveldb/filter_policy.h>
// #include <memenv.h>
#if defined(__APPLE__) && defined(__MACH__)
#include <helpers/memenv/memenv.h> // qtum
#else
#include <leveldb/helpers/memenv.h> // qtum
#endif
#include <stdint.h>
static leveldb::Options GetOptions(size_t nCacheSize)
{
leveldb::Options options;
options.block_cache = leveldb::NewLRUCache(nCacheSize / 2);
options.write_buffer_size = nCacheSize / 4; // up to two write buffers may be held in memory simultaneously
options.filter_policy = leveldb::NewBloomFilterPolicy(10);
options.compression = leveldb::kNoCompression;
options.max_open_files = 64;
if (leveldb::kMajorVersion > 1 || (leveldb::kMajorVersion == 1 && leveldb::kMinorVersion >= 16)) {
// LevelDB versions before 1.16 consider short writes to be corruption. Only trigger error
// on corruption in later versions.
options.paranoid_checks = true;
}
return options;
}
CDBWrapper::CDBWrapper(const boost::filesystem::path& path, size_t nCacheSize, bool fMemory, bool fWipe, bool obfuscate)
{
penv = NULL;
readoptions.verify_checksums = true;
iteroptions.verify_checksums = true;
iteroptions.fill_cache = false;
syncoptions.sync = true;
options = GetOptions(nCacheSize);
options.create_if_missing = true;
if (fMemory) {
penv = leveldb::NewMemEnv(leveldb::Env::Default());
options.env = penv;
} else {
if (fWipe) {
LogPrintf("Wiping LevelDB in %s\n", path.string());
leveldb::Status result = leveldb::DestroyDB(path.string(), options);
dbwrapper_private::HandleError(result);
}
TryCreateDirectory(path);
LogPrintf("Opening LevelDB in %s\n", path.string());
}
leveldb::Status status = leveldb::DB::Open(options, path.string(), &pdb);
dbwrapper_private::HandleError(status);
LogPrintf("Opened LevelDB successfully\n");
// The base-case obfuscation key, which is a noop.
obfuscate_key = std::vector<unsigned char>(OBFUSCATE_KEY_NUM_BYTES, '\000');
bool key_exists = Read(OBFUSCATE_KEY_KEY, obfuscate_key);
if (!key_exists && obfuscate && IsEmpty()) {
// Initialize non-degenerate obfuscation if it won't upset
// existing, non-obfuscated data.
std::vector<unsigned char> new_key = CreateObfuscateKey();
// Write `new_key` so we don't obfuscate the key with itself
Write(OBFUSCATE_KEY_KEY, new_key);
obfuscate_key = new_key;
LogPrintf("Wrote new obfuscate key for %s: %s\n", path.string(), HexStr(obfuscate_key));
}
LogPrintf("Using obfuscation key for %s: %s\n", path.string(), HexStr(obfuscate_key));
}
CDBWrapper::~CDBWrapper()
{
delete pdb;
pdb = NULL;
delete options.filter_policy;
options.filter_policy = NULL;
delete options.block_cache;
options.block_cache = NULL;
delete penv;
options.env = NULL;
}
bool CDBWrapper::WriteBatch(CDBBatch& batch, bool fSync)
{
leveldb::Status status = pdb->Write(fSync ? syncoptions : writeoptions, &batch.batch);
dbwrapper_private::HandleError(status);
return true;
}
// Prefixed with null character to avoid collisions with other keys
//
// We must use a string constructor which specifies length so that we copy
// past the null-terminator.
const std::string CDBWrapper::OBFUSCATE_KEY_KEY("\000obfuscate_key", 14);
const unsigned int CDBWrapper::OBFUSCATE_KEY_NUM_BYTES = 8;
/**
* Returns a string (consisting of 8 random bytes) suitable for use as an
* obfuscating XOR key.
*/
std::vector<unsigned char> CDBWrapper::CreateObfuscateKey() const
{
unsigned char buff[OBFUSCATE_KEY_NUM_BYTES];
GetRandBytes(buff, OBFUSCATE_KEY_NUM_BYTES);
return std::vector<unsigned char>(&buff[0], &buff[OBFUSCATE_KEY_NUM_BYTES]);
}
bool CDBWrapper::IsEmpty()
{
std::unique_ptr<CDBIterator> it(NewIterator());
it->SeekToFirst();
return !(it->Valid());
}
CDBIterator::~CDBIterator() { delete piter; }
bool CDBIterator::Valid() { return piter->Valid(); }
void CDBIterator::SeekToFirst() { piter->SeekToFirst(); }
void CDBIterator::Next() { piter->Next(); }
namespace dbwrapper_private {
void HandleError(const leveldb::Status& status)
{
if (status.ok())
return;
LogPrintf("%s\n", status.ToString());
if (status.IsCorruption())
throw dbwrapper_error("Database corrupted");
if (status.IsIOError())
throw dbwrapper_error("Database I/O error");
if (status.IsNotFound())
throw dbwrapper_error("Database entry missing");
throw dbwrapper_error("Unknown database error");
}
const std::vector<unsigned char>& GetObfuscateKey(const CDBWrapper &w)
{
return w.obfuscate_key;
}
};
<commit_msg>Fix weird leveldb include<commit_after>// Copyright (c) 2012-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 "dbwrapper.h"
#include "util.h"
#include "random.h"
#include <boost/filesystem.hpp>
#include <leveldb/cache.h>
#include <leveldb/env.h>
#include <leveldb/filter_policy.h>
#include <memenv.h>
#include <stdint.h>
static leveldb::Options GetOptions(size_t nCacheSize)
{
leveldb::Options options;
options.block_cache = leveldb::NewLRUCache(nCacheSize / 2);
options.write_buffer_size = nCacheSize / 4; // up to two write buffers may be held in memory simultaneously
options.filter_policy = leveldb::NewBloomFilterPolicy(10);
options.compression = leveldb::kNoCompression;
options.max_open_files = 64;
if (leveldb::kMajorVersion > 1 || (leveldb::kMajorVersion == 1 && leveldb::kMinorVersion >= 16)) {
// LevelDB versions before 1.16 consider short writes to be corruption. Only trigger error
// on corruption in later versions.
options.paranoid_checks = true;
}
return options;
}
CDBWrapper::CDBWrapper(const boost::filesystem::path& path, size_t nCacheSize, bool fMemory, bool fWipe, bool obfuscate)
{
penv = NULL;
readoptions.verify_checksums = true;
iteroptions.verify_checksums = true;
iteroptions.fill_cache = false;
syncoptions.sync = true;
options = GetOptions(nCacheSize);
options.create_if_missing = true;
if (fMemory) {
penv = leveldb::NewMemEnv(leveldb::Env::Default());
options.env = penv;
} else {
if (fWipe) {
LogPrintf("Wiping LevelDB in %s\n", path.string());
leveldb::Status result = leveldb::DestroyDB(path.string(), options);
dbwrapper_private::HandleError(result);
}
TryCreateDirectory(path);
LogPrintf("Opening LevelDB in %s\n", path.string());
}
leveldb::Status status = leveldb::DB::Open(options, path.string(), &pdb);
dbwrapper_private::HandleError(status);
LogPrintf("Opened LevelDB successfully\n");
// The base-case obfuscation key, which is a noop.
obfuscate_key = std::vector<unsigned char>(OBFUSCATE_KEY_NUM_BYTES, '\000');
bool key_exists = Read(OBFUSCATE_KEY_KEY, obfuscate_key);
if (!key_exists && obfuscate && IsEmpty()) {
// Initialize non-degenerate obfuscation if it won't upset
// existing, non-obfuscated data.
std::vector<unsigned char> new_key = CreateObfuscateKey();
// Write `new_key` so we don't obfuscate the key with itself
Write(OBFUSCATE_KEY_KEY, new_key);
obfuscate_key = new_key;
LogPrintf("Wrote new obfuscate key for %s: %s\n", path.string(), HexStr(obfuscate_key));
}
LogPrintf("Using obfuscation key for %s: %s\n", path.string(), HexStr(obfuscate_key));
}
CDBWrapper::~CDBWrapper()
{
delete pdb;
pdb = NULL;
delete options.filter_policy;
options.filter_policy = NULL;
delete options.block_cache;
options.block_cache = NULL;
delete penv;
options.env = NULL;
}
bool CDBWrapper::WriteBatch(CDBBatch& batch, bool fSync)
{
leveldb::Status status = pdb->Write(fSync ? syncoptions : writeoptions, &batch.batch);
dbwrapper_private::HandleError(status);
return true;
}
// Prefixed with null character to avoid collisions with other keys
//
// We must use a string constructor which specifies length so that we copy
// past the null-terminator.
const std::string CDBWrapper::OBFUSCATE_KEY_KEY("\000obfuscate_key", 14);
const unsigned int CDBWrapper::OBFUSCATE_KEY_NUM_BYTES = 8;
/**
* Returns a string (consisting of 8 random bytes) suitable for use as an
* obfuscating XOR key.
*/
std::vector<unsigned char> CDBWrapper::CreateObfuscateKey() const
{
unsigned char buff[OBFUSCATE_KEY_NUM_BYTES];
GetRandBytes(buff, OBFUSCATE_KEY_NUM_BYTES);
return std::vector<unsigned char>(&buff[0], &buff[OBFUSCATE_KEY_NUM_BYTES]);
}
bool CDBWrapper::IsEmpty()
{
std::unique_ptr<CDBIterator> it(NewIterator());
it->SeekToFirst();
return !(it->Valid());
}
CDBIterator::~CDBIterator() { delete piter; }
bool CDBIterator::Valid() { return piter->Valid(); }
void CDBIterator::SeekToFirst() { piter->SeekToFirst(); }
void CDBIterator::Next() { piter->Next(); }
namespace dbwrapper_private {
void HandleError(const leveldb::Status& status)
{
if (status.ok())
return;
LogPrintf("%s\n", status.ToString());
if (status.IsCorruption())
throw dbwrapper_error("Database corrupted");
if (status.IsIOError())
throw dbwrapper_error("Database I/O error");
if (status.IsNotFound())
throw dbwrapper_error("Database entry missing");
throw dbwrapper_error("Unknown database error");
}
const std::vector<unsigned char>& GetObfuscateKey(const CDBWrapper &w)
{
return w.obfuscate_key;
}
};
<|endoftext|> |
<commit_before>#ifndef BUW_COMPOSITE_HPP
#define BUW_COMPOSITE_HPP
#include <shape.hpp>
#include <memory>
#include <map>
#include <sphere.hpp>
#include <box.hpp>
#include <triangle.hpp>
class Composite : public Shape {
public:
Composite();
Composite(std::string const& name);
~Composition();
void add(std::shared_ptr<Shape>& shape);
void remove(std::string const& name);
std::ostream& print(std::ostream& os) const override;
std::map<std::string, std::shared_ptr<Shape>> get_children();
private:
std::map<std::string,std::shared_ptr<Shape>> shapes_;
};
#endif<commit_msg>composite<commit_after>#ifndef BUW_COMPOSITE_HPP
#define BUW_COMPOSITE_HPP
#include <iostream>
#include <memory>
#include <map>
#include <shape.hpp>
#include <sphere.hpp>
#include <box.hpp>
#include <triangle.hpp>
class Composite : public Shape {
public:
Composite();
Composite(std::string const& name);
~Composition();
void add(std::shared_ptr<Shape>& shape);
void remove(std::string const& name);
std::ostream& print(std::ostream& os) const override;
std::map<std::string, std::shared_ptr<Shape>> get_children();
private:
std::map<std::string,std::shared_ptr<Shape>> shapes_;
};
#endif<|endoftext|> |
<commit_before>/*
threadedjobmixin.cpp
This file is part of qgpgme, the Qt API binding for gpgme
Copyright (c) 2008 Klarälvdalens Datakonsult AB
Copyright (c) 2016 by Bundesamt für Sicherheit in der Informationstechnik
Software engineering by Intevation GmbH
QGpgME 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.
QGpgME is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "threadedjobmixin.h"
#include "dataprovider.h"
#include "data.h"
#include <QString>
#include <QStringList>
#include <QByteArray>
#include <algorithm>
#include <iterator>
using namespace QGpgME;
using namespace GpgME;
#ifdef Q_OS_WIN
#include <windows.h>
static QString fromEncoding (unsigned int src_encoding, const char *data)
{
int n = MultiByteToWideChar(src_encoding, 0, data, -1, NULL, 0);
if (n < 0) {
return QString();
}
wchar_t *result = (wchar_t *) malloc ((n+1) * sizeof *result);
n = MultiByteToWideChar(src_encoding, 0, data, -1, result, n);
if (n < 0) {
free(result);
return QString();
}
const auto ret = QString::fromWCharArray(result, n);
free(result);
return ret;
}
#endif
static QString stringFromGpgOutput(const QByteArray &ba)
{
#ifdef Q_OS_WIN
/* Qt on Windows uses GetACP while GnuPG prefers
* GetConsoleOutputCP.
*
* As we are not a console application GetConsoleOutputCP
* usually returns 0.
* From experience the closest thing that let's us guess
* what GetConsoleOutputCP returns for a console application
* it appears to be the OEMCP.
*/
unsigned int cpno = GetConsoleOutputCP ();
if (!cpno) {
cpno = GetOEMCP();
}
if (!cpno) {
cpno = GetACP();
}
if (!cpno) {
return QString();
}
return fromEncoding(cpno, ba.constData());
#else
return QString::fromLocal8Bit(ba);
#endif
}
static QString markupDiagnostics(const QString &data)
{
// First ensure that we don't have html in the diag.
QString ret = QStringLiteral("<pre>%1</pre>").arg(data.toHtmlEscaped());
return ret;
}
static const unsigned int CMSAuditLogFlags = Context::AuditLogWithHelp | Context::HtmlAuditLog;
static const unsigned int OpenPGPAuditLogFlags = Context::DiagnosticAuditLog;
QString _detail::audit_log_as_html(Context *ctx, GpgME::Error &err)
{
assert(ctx);
QGpgME::QByteArrayDataProvider dp;
Data data(&dp);
assert(!data.isNull());
if (ctx->protocol() == OpenPGP) {
if ((err = ctx->getAuditLog(data, OpenPGPAuditLogFlags))) {
return QString::fromLocal8Bit(err.asString());
}
const QByteArray ba = dp.data();
return markupDiagnostics(stringFromGpgOutput(ba));
}
if (ctx->protocol() == CMS) {
if ((err = ctx->lastError()) || (err = ctx->getAuditLog(data, CMSAuditLogFlags))) {
return QString::fromLocal8Bit(err.asString());
}
const QByteArray ba = dp.data();
return QString::fromUtf8(ba.data(), ba.size());
}
return QStringLiteral("Unsupported protocol for Audit Log");
}
static QList<QByteArray> from_sl(const QStringList &sl)
{
QList<QByteArray> result;
Q_FOREACH (const QString &str, sl) {
result.append(str.toUtf8());
}
#if 0
std::transform(sl.begin(), sl.end(), std::back_inserter(result),
mem_fn(static_cast<QByteArray()const>(&QString::toUtf8)));
#endif
return result;
}
static QList<QByteArray> single(const QByteArray &ba)
{
QList<QByteArray> result;
result.push_back(ba);
return result;
}
_detail::PatternConverter::PatternConverter(const QByteArray &ba)
: m_list(single(ba)), m_patterns(nullptr) {}
_detail::PatternConverter::PatternConverter(const QString &s)
: m_list(single(s.toUtf8())), m_patterns(nullptr) {}
_detail::PatternConverter::PatternConverter(const QList<QByteArray> &lba)
: m_list(lba), m_patterns(nullptr) {}
_detail::PatternConverter::PatternConverter(const QStringList &sl)
: m_list(from_sl(sl)), m_patterns(nullptr) {}
const char **_detail::PatternConverter::patterns() const
{
if (!m_patterns) {
m_patterns = new const char *[ m_list.size() + 1 ];
const char **end = std::transform(m_list.begin(), m_list.end(), m_patterns,
std::mem_fn(&QByteArray::constData));
*end = nullptr;
}
return m_patterns;
}
_detail::PatternConverter::~PatternConverter()
{
delete [] m_patterns;
}
<commit_msg>qt: Handle diagnostic audit log for CMS<commit_after>/*
threadedjobmixin.cpp
This file is part of qgpgme, the Qt API binding for gpgme
Copyright (c) 2008 Klarälvdalens Datakonsult AB
Copyright (c) 2016 by Bundesamt für Sicherheit in der Informationstechnik
Software engineering by Intevation GmbH
QGpgME 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.
QGpgME is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
In addition, as a special exception, the copyright holders give
permission to link the code of this program with any edition of
the Qt library by Trolltech AS, Norway (or with modified versions
of Qt that use the same license as Qt), and distribute linked
combinations including the two. You must obey the GNU General
Public License in all respects for all of the code used other than
Qt. If you modify this file, you may extend this exception to
your version of the file, but you are not obligated to do so. If
you do not wish to do so, delete this exception statement from
your version.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "threadedjobmixin.h"
#include "dataprovider.h"
#include "data.h"
#include <QString>
#include <QStringList>
#include <QByteArray>
#include <algorithm>
#include <iterator>
using namespace QGpgME;
using namespace GpgME;
#ifdef Q_OS_WIN
#include <windows.h>
static QString fromEncoding (unsigned int src_encoding, const char *data)
{
int n = MultiByteToWideChar(src_encoding, 0, data, -1, NULL, 0);
if (n < 0) {
return QString();
}
wchar_t *result = (wchar_t *) malloc ((n+1) * sizeof *result);
n = MultiByteToWideChar(src_encoding, 0, data, -1, result, n);
if (n < 0) {
free(result);
return QString();
}
const auto ret = QString::fromWCharArray(result, n);
free(result);
return ret;
}
#endif
static QString stringFromGpgOutput(const QByteArray &ba)
{
#ifdef Q_OS_WIN
/* Qt on Windows uses GetACP while GnuPG prefers
* GetConsoleOutputCP.
*
* As we are not a console application GetConsoleOutputCP
* usually returns 0.
* From experience the closest thing that let's us guess
* what GetConsoleOutputCP returns for a console application
* it appears to be the OEMCP.
*/
unsigned int cpno = GetConsoleOutputCP ();
if (!cpno) {
cpno = GetOEMCP();
}
if (!cpno) {
cpno = GetACP();
}
if (!cpno) {
return QString();
}
return fromEncoding(cpno, ba.constData());
#else
return QString::fromLocal8Bit(ba);
#endif
}
static QString markupDiagnostics(const QString &data)
{
// First ensure that we don't have html in the diag.
QString ret = QStringLiteral("<pre>%1</pre>").arg(data.toHtmlEscaped());
return ret;
}
static const unsigned int CMSAuditLogFlags = Context::AuditLogWithHelp | Context::HtmlAuditLog;
static const unsigned int OpenPGPAuditLogFlags = Context::DiagnosticAuditLog;
QString _detail::audit_log_as_html(Context *ctx, GpgME::Error &err)
{
assert(ctx);
QGpgME::QByteArrayDataProvider dp;
Data data(&dp);
assert(!data.isNull());
if (ctx->protocol() == OpenPGP) {
if ((err = ctx->getAuditLog(data, OpenPGPAuditLogFlags))) {
return QString::fromLocal8Bit(err.asString());
}
const QByteArray ba = dp.data();
return markupDiagnostics(stringFromGpgOutput(ba));
}
if (ctx->protocol() == CMS) {
if ((err = ctx->lastError())) {
if ((err = ctx->getAuditLog(data, Context::DiagnosticAuditLog))) {
return QString::fromLocal8Bit(err.asString());
}
const QByteArray ba = dp.data();
return markupDiagnostics(stringFromGpgOutput(ba));
} else if ((err = ctx->getAuditLog(data, CMSAuditLogFlags))) {
return QString::fromLocal8Bit(err.asString());
}
const QByteArray ba = dp.data();
return QString::fromUtf8(ba.data(), ba.size());
}
return QStringLiteral("Unsupported protocol for Audit Log");
}
static QList<QByteArray> from_sl(const QStringList &sl)
{
QList<QByteArray> result;
Q_FOREACH (const QString &str, sl) {
result.append(str.toUtf8());
}
#if 0
std::transform(sl.begin(), sl.end(), std::back_inserter(result),
mem_fn(static_cast<QByteArray()const>(&QString::toUtf8)));
#endif
return result;
}
static QList<QByteArray> single(const QByteArray &ba)
{
QList<QByteArray> result;
result.push_back(ba);
return result;
}
_detail::PatternConverter::PatternConverter(const QByteArray &ba)
: m_list(single(ba)), m_patterns(nullptr) {}
_detail::PatternConverter::PatternConverter(const QString &s)
: m_list(single(s.toUtf8())), m_patterns(nullptr) {}
_detail::PatternConverter::PatternConverter(const QList<QByteArray> &lba)
: m_list(lba), m_patterns(nullptr) {}
_detail::PatternConverter::PatternConverter(const QStringList &sl)
: m_list(from_sl(sl)), m_patterns(nullptr) {}
const char **_detail::PatternConverter::patterns() const
{
if (!m_patterns) {
m_patterns = new const char *[ m_list.size() + 1 ];
const char **end = std::transform(m_list.begin(), m_list.end(), m_patterns,
std::mem_fn(&QByteArray::constData));
*end = nullptr;
}
return m_patterns;
}
_detail::PatternConverter::~PatternConverter()
{
delete [] m_patterns;
}
<|endoftext|> |
<commit_before>//===--- ExecuteCompilerInvocation.cpp ------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file holds ExecuteCompilerInvocation(). It is split into its own file to
// minimize the impact of pulling in essentially everything else in Clang.
//
//===----------------------------------------------------------------------===//
#include "clang/FrontendTool/Utils.h"
#include "clang/ARCMigrate/ARCMTActions.h"
#include "clang/CodeGen/CodeGenAction.h"
#include "clang/Driver/OptTable.h"
#include "clang/Driver/Option.h"
#include "clang/Driver/Options.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/CompilerInvocation.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Frontend/FrontendPluginRegistry.h"
#include "clang/Rewrite/Frontend/FrontendActions.h"
#include "clang/StaticAnalyzer/Frontend/FrontendActions.h"
#include "llvm/Support/DynamicLibrary.h"
#include "llvm/Support/ErrorHandling.h"
using namespace clang;
static FrontendAction *CreateFrontendBaseAction(CompilerInstance &CI) {
using namespace clang::frontend;
StringRef Action("unknown");
switch (CI.getFrontendOpts().ProgramAction) {
case ASTDeclList: return new ASTDeclListAction();
case ASTDump: return new ASTDumpAction();
case ASTDumpXML: return new ASTDumpXMLAction();
case ASTPrint: return new ASTPrintAction();
case ASTView: return new ASTViewAction();
case DumpRawTokens: return new DumpRawTokensAction();
case DumpTokens: return new DumpTokensAction();
case EmitAssembly: return new EmitAssemblyAction();
case EmitBC: return new EmitBCAction();
#ifdef CLANG_ENABLE_REWRITER
case EmitHTML: return new HTMLPrintAction();
#else
case EmitHTML: Action = "EmitHTML"; break;
#endif
case EmitLLVM: return new EmitLLVMAction();
case EmitLLVMOnly: return new EmitLLVMOnlyAction();
case EmitCodeGenOnly: return new EmitCodeGenOnlyAction();
case EmitObj: return new EmitObjAction();
#ifdef CLANG_ENABLE_REWRITER
case FixIt: return new FixItAction();
#else
case FixIt: Action = "FixIt"; break;
#endif
case GenerateModule: return new GenerateModuleAction;
case GeneratePCH: return new GeneratePCHAction;
case GeneratePTH: return new GeneratePTHAction();
case InitOnly: return new InitOnlyAction();
case ParseSyntaxOnly: return new SyntaxOnlyAction();
case PluginAction: {
for (FrontendPluginRegistry::iterator it =
FrontendPluginRegistry::begin(), ie = FrontendPluginRegistry::end();
it != ie; ++it) {
if (it->getName() == CI.getFrontendOpts().ActionName) {
OwningPtr<PluginASTAction> P(it->instantiate());
if (!P->ParseArgs(CI, CI.getFrontendOpts().PluginArgs))
return 0;
return P.take();
}
}
CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
<< CI.getFrontendOpts().ActionName;
return 0;
}
case PrintDeclContext: return new DeclContextPrintAction();
case PrintPreamble: return new PrintPreambleAction();
case PrintPreprocessedInput: {
if (CI.getPreprocessorOutputOpts().RewriteIncludes) {
#ifdef CLANG_ENABLE_REWRITER
return new RewriteIncludesAction();
#else
Action = "RewriteIncludesAction";
break;
#endif
}
return new PrintPreprocessedAction();
}
#ifdef CLANG_ENABLE_REWRITER
case RewriteMacros: return new RewriteMacrosAction();
case RewriteObjC: return new RewriteObjCAction();
case RewriteTest: return new RewriteTestAction();
#else
case RewriteMacros: Action = "RewriteMacros"; break;
case RewriteObjC: Action = "RewriteObjC"; break;
case RewriteTest: Action = "RewriteTest"; break;
#endif
#ifdef CLANG_ENABLE_ARCMT
case MigrateSource: return new arcmt::MigrateSourceAction();
#else
case MigrateSource: Action = "MigrateSource"; break;
#endif
#ifdef CLANG_ENABLE_STATIC_ANALYZER
case RunAnalysis: return new ento::AnalysisAction();
#else
case RunAnalysis: Action = "RunAnalysis"; break;
#endif
case RunPreprocessorOnly: return new PreprocessOnlyAction();
}
#if !defined(CLANG_ENABLE_ARCMT) || !defined(CLANG_ENABLE_STATIC_ANALYZER) \
|| !defined(CLANG_ENABLE_REWRITER)
CI.getDiagnostics().Report(diag::err_fe_action_not_available) << Action;
return 0;
#else
llvm_unreachable("Invalid program action!");
#endif
}
static FrontendAction *CreateFrontendAction(CompilerInstance &CI) {
// Create the underlying action.
FrontendAction *Act = CreateFrontendBaseAction(CI);
if (!Act)
return 0;
const FrontendOptions &FEOpts = CI.getFrontendOpts();
#ifdef CLANG_ENABLE_REWRITER
if (FEOpts.FixAndRecompile) {
Act = new FixItRecompile(Act);
}
#endif
#ifdef CLANG_ENABLE_ARCMT
// Potentially wrap the base FE action in an ARC Migrate Tool action.
switch (FEOpts.ARCMTAction) {
case FrontendOptions::ARCMT_None:
break;
case FrontendOptions::ARCMT_Check:
Act = new arcmt::CheckAction(Act);
break;
case FrontendOptions::ARCMT_Modify:
Act = new arcmt::ModifyAction(Act);
break;
case FrontendOptions::ARCMT_Migrate:
Act = new arcmt::MigrateAction(Act,
FEOpts.MTMigrateDir,
FEOpts.ARCMTMigrateReportOut,
FEOpts.ARCMTMigrateEmitARCErrors);
break;
}
if (FEOpts.ObjCMTAction != FrontendOptions::ObjCMT_None) {
Act = new arcmt::ObjCMigrateAction(Act, FEOpts.MTMigrateDir,
FEOpts.ObjCMTAction & ~FrontendOptions::ObjCMT_Literals,
FEOpts.ObjCMTAction & ~FrontendOptions::ObjCMT_Subscripting);
}
#endif
// If there are any AST files to merge, create a frontend action
// adaptor to perform the merge.
if (!FEOpts.ASTMergeFiles.empty())
Act = new ASTMergeAction(Act, FEOpts.ASTMergeFiles);
return Act;
}
bool clang::ExecuteCompilerInvocation(CompilerInstance *Clang) {
// Honor -help.
if (Clang->getFrontendOpts().ShowHelp) {
OwningPtr<driver::OptTable> Opts(driver::createDriverOptTable());
Opts->PrintHelp(llvm::outs(), "clang -cc1",
"LLVM 'Clang' Compiler: http://clang.llvm.org",
/*Include=*/driver::options::CC1Option,
/*Exclude=*/0);
return 0;
}
// Honor -version.
//
// FIXME: Use a better -version message?
if (Clang->getFrontendOpts().ShowVersion) {
llvm::cl::PrintVersionMessage();
return 0;
}
// Load any requested plugins.
for (unsigned i = 0,
e = Clang->getFrontendOpts().Plugins.size(); i != e; ++i) {
const std::string &Path = Clang->getFrontendOpts().Plugins[i];
std::string Error;
if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(Path.c_str(), &Error))
Clang->getDiagnostics().Report(diag::err_fe_unable_to_load_plugin)
<< Path << Error;
}
// Honor -mllvm.
//
// FIXME: Remove this, one day.
// This should happen AFTER plugins have been loaded!
if (!Clang->getFrontendOpts().LLVMArgs.empty()) {
unsigned NumArgs = Clang->getFrontendOpts().LLVMArgs.size();
const char **Args = new const char*[NumArgs + 2];
Args[0] = "clang (LLVM option parsing)";
for (unsigned i = 0; i != NumArgs; ++i)
Args[i + 1] = Clang->getFrontendOpts().LLVMArgs[i].c_str();
Args[NumArgs + 1] = 0;
llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args);
}
#ifdef CLANG_ENABLE_STATIC_ANALYZER
// Honor -analyzer-checker-help.
// This should happen AFTER plugins have been loaded!
if (Clang->getAnalyzerOpts()->ShowCheckerHelp) {
ento::printCheckerHelp(llvm::outs(), Clang->getFrontendOpts().Plugins);
return 0;
}
#endif
// If there were errors in processing arguments, don't do anything else.
bool Success = false;
if (!Clang->getDiagnostics().hasErrorOccurred()) {
// Create and execute the frontend action.
OwningPtr<FrontendAction> Act(CreateFrontendAction(*Clang));
if (Act) {
Success = Clang->ExecuteAction(*Act);
if (Clang->getFrontendOpts().DisableFree)
Act.take();
}
}
return Success;
}
<commit_msg>use early returns to simplify and de-nest<commit_after>//===--- ExecuteCompilerInvocation.cpp ------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file holds ExecuteCompilerInvocation(). It is split into its own file to
// minimize the impact of pulling in essentially everything else in Clang.
//
//===----------------------------------------------------------------------===//
#include "clang/FrontendTool/Utils.h"
#include "clang/ARCMigrate/ARCMTActions.h"
#include "clang/CodeGen/CodeGenAction.h"
#include "clang/Driver/OptTable.h"
#include "clang/Driver/Option.h"
#include "clang/Driver/Options.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/CompilerInvocation.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Frontend/FrontendPluginRegistry.h"
#include "clang/Rewrite/Frontend/FrontendActions.h"
#include "clang/StaticAnalyzer/Frontend/FrontendActions.h"
#include "llvm/Support/DynamicLibrary.h"
#include "llvm/Support/ErrorHandling.h"
using namespace clang;
static FrontendAction *CreateFrontendBaseAction(CompilerInstance &CI) {
using namespace clang::frontend;
StringRef Action("unknown");
switch (CI.getFrontendOpts().ProgramAction) {
case ASTDeclList: return new ASTDeclListAction();
case ASTDump: return new ASTDumpAction();
case ASTDumpXML: return new ASTDumpXMLAction();
case ASTPrint: return new ASTPrintAction();
case ASTView: return new ASTViewAction();
case DumpRawTokens: return new DumpRawTokensAction();
case DumpTokens: return new DumpTokensAction();
case EmitAssembly: return new EmitAssemblyAction();
case EmitBC: return new EmitBCAction();
#ifdef CLANG_ENABLE_REWRITER
case EmitHTML: return new HTMLPrintAction();
#else
case EmitHTML: Action = "EmitHTML"; break;
#endif
case EmitLLVM: return new EmitLLVMAction();
case EmitLLVMOnly: return new EmitLLVMOnlyAction();
case EmitCodeGenOnly: return new EmitCodeGenOnlyAction();
case EmitObj: return new EmitObjAction();
#ifdef CLANG_ENABLE_REWRITER
case FixIt: return new FixItAction();
#else
case FixIt: Action = "FixIt"; break;
#endif
case GenerateModule: return new GenerateModuleAction;
case GeneratePCH: return new GeneratePCHAction;
case GeneratePTH: return new GeneratePTHAction();
case InitOnly: return new InitOnlyAction();
case ParseSyntaxOnly: return new SyntaxOnlyAction();
case PluginAction: {
for (FrontendPluginRegistry::iterator it =
FrontendPluginRegistry::begin(), ie = FrontendPluginRegistry::end();
it != ie; ++it) {
if (it->getName() == CI.getFrontendOpts().ActionName) {
OwningPtr<PluginASTAction> P(it->instantiate());
if (!P->ParseArgs(CI, CI.getFrontendOpts().PluginArgs))
return 0;
return P.take();
}
}
CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
<< CI.getFrontendOpts().ActionName;
return 0;
}
case PrintDeclContext: return new DeclContextPrintAction();
case PrintPreamble: return new PrintPreambleAction();
case PrintPreprocessedInput: {
if (CI.getPreprocessorOutputOpts().RewriteIncludes) {
#ifdef CLANG_ENABLE_REWRITER
return new RewriteIncludesAction();
#else
Action = "RewriteIncludesAction";
break;
#endif
}
return new PrintPreprocessedAction();
}
#ifdef CLANG_ENABLE_REWRITER
case RewriteMacros: return new RewriteMacrosAction();
case RewriteObjC: return new RewriteObjCAction();
case RewriteTest: return new RewriteTestAction();
#else
case RewriteMacros: Action = "RewriteMacros"; break;
case RewriteObjC: Action = "RewriteObjC"; break;
case RewriteTest: Action = "RewriteTest"; break;
#endif
#ifdef CLANG_ENABLE_ARCMT
case MigrateSource: return new arcmt::MigrateSourceAction();
#else
case MigrateSource: Action = "MigrateSource"; break;
#endif
#ifdef CLANG_ENABLE_STATIC_ANALYZER
case RunAnalysis: return new ento::AnalysisAction();
#else
case RunAnalysis: Action = "RunAnalysis"; break;
#endif
case RunPreprocessorOnly: return new PreprocessOnlyAction();
}
#if !defined(CLANG_ENABLE_ARCMT) || !defined(CLANG_ENABLE_STATIC_ANALYZER) \
|| !defined(CLANG_ENABLE_REWRITER)
CI.getDiagnostics().Report(diag::err_fe_action_not_available) << Action;
return 0;
#else
llvm_unreachable("Invalid program action!");
#endif
}
static FrontendAction *CreateFrontendAction(CompilerInstance &CI) {
// Create the underlying action.
FrontendAction *Act = CreateFrontendBaseAction(CI);
if (!Act)
return 0;
const FrontendOptions &FEOpts = CI.getFrontendOpts();
#ifdef CLANG_ENABLE_REWRITER
if (FEOpts.FixAndRecompile) {
Act = new FixItRecompile(Act);
}
#endif
#ifdef CLANG_ENABLE_ARCMT
// Potentially wrap the base FE action in an ARC Migrate Tool action.
switch (FEOpts.ARCMTAction) {
case FrontendOptions::ARCMT_None:
break;
case FrontendOptions::ARCMT_Check:
Act = new arcmt::CheckAction(Act);
break;
case FrontendOptions::ARCMT_Modify:
Act = new arcmt::ModifyAction(Act);
break;
case FrontendOptions::ARCMT_Migrate:
Act = new arcmt::MigrateAction(Act,
FEOpts.MTMigrateDir,
FEOpts.ARCMTMigrateReportOut,
FEOpts.ARCMTMigrateEmitARCErrors);
break;
}
if (FEOpts.ObjCMTAction != FrontendOptions::ObjCMT_None) {
Act = new arcmt::ObjCMigrateAction(Act, FEOpts.MTMigrateDir,
FEOpts.ObjCMTAction & ~FrontendOptions::ObjCMT_Literals,
FEOpts.ObjCMTAction & ~FrontendOptions::ObjCMT_Subscripting);
}
#endif
// If there are any AST files to merge, create a frontend action
// adaptor to perform the merge.
if (!FEOpts.ASTMergeFiles.empty())
Act = new ASTMergeAction(Act, FEOpts.ASTMergeFiles);
return Act;
}
bool clang::ExecuteCompilerInvocation(CompilerInstance *Clang) {
// Honor -help.
if (Clang->getFrontendOpts().ShowHelp) {
OwningPtr<driver::OptTable> Opts(driver::createDriverOptTable());
Opts->PrintHelp(llvm::outs(), "clang -cc1",
"LLVM 'Clang' Compiler: http://clang.llvm.org",
/*Include=*/driver::options::CC1Option,
/*Exclude=*/0);
return 0;
}
// Honor -version.
//
// FIXME: Use a better -version message?
if (Clang->getFrontendOpts().ShowVersion) {
llvm::cl::PrintVersionMessage();
return 0;
}
// Load any requested plugins.
for (unsigned i = 0,
e = Clang->getFrontendOpts().Plugins.size(); i != e; ++i) {
const std::string &Path = Clang->getFrontendOpts().Plugins[i];
std::string Error;
if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(Path.c_str(), &Error))
Clang->getDiagnostics().Report(diag::err_fe_unable_to_load_plugin)
<< Path << Error;
}
// Honor -mllvm.
//
// FIXME: Remove this, one day.
// This should happen AFTER plugins have been loaded!
if (!Clang->getFrontendOpts().LLVMArgs.empty()) {
unsigned NumArgs = Clang->getFrontendOpts().LLVMArgs.size();
const char **Args = new const char*[NumArgs + 2];
Args[0] = "clang (LLVM option parsing)";
for (unsigned i = 0; i != NumArgs; ++i)
Args[i + 1] = Clang->getFrontendOpts().LLVMArgs[i].c_str();
Args[NumArgs + 1] = 0;
llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args);
}
#ifdef CLANG_ENABLE_STATIC_ANALYZER
// Honor -analyzer-checker-help.
// This should happen AFTER plugins have been loaded!
if (Clang->getAnalyzerOpts()->ShowCheckerHelp) {
ento::printCheckerHelp(llvm::outs(), Clang->getFrontendOpts().Plugins);
return 0;
}
#endif
// If there were errors in processing arguments, don't do anything else.
if (Clang->getDiagnostics().hasErrorOccurred())
return false;
// Create and execute the frontend action.
OwningPtr<FrontendAction> Act(CreateFrontendAction(*Clang));
if (!Act)
return false;
bool Success = Clang->ExecuteAction(*Act);
if (Clang->getFrontendOpts().DisableFree)
Act.take();
return Success;
}
<|endoftext|> |
<commit_before>/* Software License Agreement (BSD License)
*
* Copyright (c) 2014, Robotiq, 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 Robotiq, 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.
*
* Copyright (c) 2014, Robotiq, Inc
*/
/**
* \file rq_sensor.cpp
* \date July 14, 2014
* \author Jonathan Savoie <jonathan.savoie@robotiq.com>
* \maintainer Nicolas Lauzier <nicolas@robotiq.com>
*/
#include <string.h>
#include <stdio.h>
#include "ros/ros.h"
#include "std_msgs/String.h"
#include "std_msgs/Bool.h"
#include "geometry_msgs/WrenchStamped.h"
#include "robotiq_force_torque_sensor/rq_sensor_state.h"
#include "robotiq_force_torque_sensor/ft_sensor.h"
#include "robotiq_force_torque_sensor/sensor_accessor.h"
static void decode_message_and_do(INT_8 const * const buff, INT_8 * const ret);
bool wait_for_other_connection(void);
bool try_connection(void);
static int max_retries_(100);
ros::Publisher sensor_pub_acc;
/**
* \brief Decode the message received and do the associated action
* \param buff message to decode
* \param ret buffer containing the return value from a GET command
*/
static void decode_message_and_do(INT_8 const * const buff, INT_8 * const ret)
{
INT_8 get_or_set[3];
INT_8 nom_var[4];
if(buff == NULL || strlen(buff) != 7)
{
return;
}
strncpy(get_or_set, &buff[0], 3);
strncpy(nom_var, &buff[4], strlen(buff) -3);
if(strstr(get_or_set, "GET"))
{
rq_state_get_command(nom_var, ret);
}
else if(strstr(get_or_set, "SET"))
{
if(strstr(nom_var, "ZRO"))
{
rq_state_do_zero_force_flag();
strcpy(ret,"Done");
}
}
}
bool receiverCallback(robotiq_force_torque_sensor::sensor_accessor::Request& req,
robotiq_force_torque_sensor::sensor_accessor::Response& res)
{
ROS_INFO("I heard: [%s]",req.command.c_str());
INT_8 buffer[512];
decode_message_and_do((char*)req.command.c_str(), buffer);
res.res = buffer;
ROS_INFO("I send: [%s]", res.res.c_str());
return true;
}
/**
* \fn bool wait_for_other_connection()
* \brief Each second, checks for a sensor that has been connected
*/
bool wait_for_other_connection(void)
{
INT_8 ret;
INT_8 count = 0;
while(ros::ok() && count < 6)
{
if (count % 2 == 0)
{
ROS_INFO("Waiting for sensor connection...");
}
usleep(1000000); //Attend 1 seconde.
ret = rq_sensor_state(max_retries_);
if(ret == 0)
{
ROS_INFO("Sensor connected!");
return true;
}
count++;
ros::spinOnce();
}
return false;
}
/**
* \fn bool try_connection()
* \brief A helper function to avoid repeated code
*/
bool try_connection(void)
{
INT_8 ret;
ret = rq_sensor_state(max_retries_);
if(ret == -1)
{
if (!wait_for_other_connection())
{
return false;
}
}
return true;
}
/**
* \fn void get_data(void)
* \brief Builds the message with the force/torque data
* \return ft_sensor updated with the latest data
*/
static robotiq_force_torque_sensor::ft_sensor get_data(void)
{
robotiq_force_torque_sensor::ft_sensor msgStream;
msgStream.Fx = rq_state_get_received_data(0);
msgStream.Fy = rq_state_get_received_data(1);
msgStream.Fz = rq_state_get_received_data(2);
msgStream.Mx = rq_state_get_received_data(3);
msgStream.My = rq_state_get_received_data(4);
msgStream.Mz = rq_state_get_received_data(5);
return msgStream;
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "robotiq_force_torque_sensor");
ROS_INFO("Trying to Start Sensor");
ros::NodeHandle n;
std_msgs::Bool connection_msg;
ros::param::param<int>("~max_retries", max_retries_, 100);
INT_8 bufStream[512];
INT_32 publish_count = 0;
robotiq_force_torque_sensor::ft_sensor msgStream;
bool connected = false;
//If we can't initialize, we return an error
connected = try_connection();
//Reads basic info on the sensor
connected = try_connection();
//Starts the stream
connected = try_connection();
ros::Publisher sensor_pub = n.advertise<robotiq_force_torque_sensor::ft_sensor>("robotiq_force_torque_sensor", 512);
ros::Publisher wrench_pub = n.advertise<geometry_msgs::WrenchStamped>("robotiq_force_torque_wrench", 512);
ros::Publisher connection_pub = n.advertise<std_msgs::Bool>("robotiq_force_torque_sensor_connected", 1);
ros::Publisher watchdog_pub = n.advertise<std_msgs::Empty>("/robotiq_ft300_force_torque_sensor/watchdog", 1);
ros::ServiceServer service = n.advertiseService("robotiq_force_torque_sensor_acc", receiverCallback);
//std_msgs::String msg;
geometry_msgs::WrenchStamped wrenchMsg;
std_msgs::Empty watchdog_msg;
ros::param::param<std::string>("~frame_id", wrenchMsg.header.frame_id, "robotiq_force_torque_frame_id");
// Publish the connection state
connection_msg.data = connected;
connection_pub.publish(connection_msg);
ros::spinOnce();
if (connected)
{
ROS_INFO("Starting Sensor");
}
while(ros::ok() && connected)
{
connected = try_connection();
if(rq_sensor_get_current_state() == RQ_STATE_RUN)
{
strcpy(bufStream,"");
msgStream = get_data();
if(rq_state_got_new_message())
{
sensor_pub.publish(msgStream);
// compose WrenchStamped Msg
wrenchMsg.header.stamp = ros::Time::now();
wrenchMsg.wrench.force.x = msgStream.Fx;
wrenchMsg.wrench.force.y = msgStream.Fy;
wrenchMsg.wrench.force.z = msgStream.Fz;
wrenchMsg.wrench.torque.x = msgStream.Mx;
wrenchMsg.wrench.torque.y = msgStream.My;
wrenchMsg.wrench.torque.z = msgStream.Mz;
wrench_pub.publish(wrenchMsg);
}
}
// Publish the connection state every 1000 iterations
if (publish_count == 250)
{
watchdog_pub.publish(watchdog_msg);
}
if (publish_count == 1000)
{
connection_msg.data = connected;
connection_pub.publish(connection_msg);
publish_count = 0;
}
publish_count++;
ros::spinOnce();
}
if (!connected)
{
connection_msg.data = connected;
connection_pub.publish(connection_msg);
ros::spinOnce();
}
ROS_INFO("Sensor Stopped");
return 0;
}
<commit_msg>Added empty message to source<commit_after>/* Software License Agreement (BSD License)
*
* Copyright (c) 2014, Robotiq, 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 Robotiq, 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.
*
* Copyright (c) 2014, Robotiq, Inc
*/
/**
* \file rq_sensor.cpp
* \date July 14, 2014
* \author Jonathan Savoie <jonathan.savoie@robotiq.com>
* \maintainer Nicolas Lauzier <nicolas@robotiq.com>
*/
#include <string.h>
#include <stdio.h>
#include "ros/ros.h"
#include "std_msgs/String.h"
#include "std_msgs/Bool.h"
#include "std_msgs/Empty.h"
#include "geometry_msgs/WrenchStamped.h"
#include "robotiq_force_torque_sensor/rq_sensor_state.h"
#include "robotiq_force_torque_sensor/ft_sensor.h"
#include "robotiq_force_torque_sensor/sensor_accessor.h"
static void decode_message_and_do(INT_8 const * const buff, INT_8 * const ret);
bool wait_for_other_connection(void);
bool try_connection(void);
static int max_retries_(100);
ros::Publisher sensor_pub_acc;
/**
* \brief Decode the message received and do the associated action
* \param buff message to decode
* \param ret buffer containing the return value from a GET command
*/
static void decode_message_and_do(INT_8 const * const buff, INT_8 * const ret)
{
INT_8 get_or_set[3];
INT_8 nom_var[4];
if(buff == NULL || strlen(buff) != 7)
{
return;
}
strncpy(get_or_set, &buff[0], 3);
strncpy(nom_var, &buff[4], strlen(buff) -3);
if(strstr(get_or_set, "GET"))
{
rq_state_get_command(nom_var, ret);
}
else if(strstr(get_or_set, "SET"))
{
if(strstr(nom_var, "ZRO"))
{
rq_state_do_zero_force_flag();
strcpy(ret,"Done");
}
}
}
bool receiverCallback(robotiq_force_torque_sensor::sensor_accessor::Request& req,
robotiq_force_torque_sensor::sensor_accessor::Response& res)
{
ROS_INFO("I heard: [%s]",req.command.c_str());
INT_8 buffer[512];
decode_message_and_do((char*)req.command.c_str(), buffer);
res.res = buffer;
ROS_INFO("I send: [%s]", res.res.c_str());
return true;
}
/**
* \fn bool wait_for_other_connection()
* \brief Each second, checks for a sensor that has been connected
*/
bool wait_for_other_connection(void)
{
INT_8 ret;
INT_8 count = 0;
while(ros::ok() && count < 6)
{
if (count % 2 == 0)
{
ROS_INFO("Waiting for sensor connection...");
}
usleep(1000000); //Attend 1 seconde.
ret = rq_sensor_state(max_retries_);
if(ret == 0)
{
ROS_INFO("Sensor connected!");
return true;
}
count++;
ros::spinOnce();
}
return false;
}
/**
* \fn bool try_connection()
* \brief A helper function to avoid repeated code
*/
bool try_connection(void)
{
INT_8 ret;
ret = rq_sensor_state(max_retries_);
if(ret == -1)
{
if (!wait_for_other_connection())
{
return false;
}
}
return true;
}
/**
* \fn void get_data(void)
* \brief Builds the message with the force/torque data
* \return ft_sensor updated with the latest data
*/
static robotiq_force_torque_sensor::ft_sensor get_data(void)
{
robotiq_force_torque_sensor::ft_sensor msgStream;
msgStream.Fx = rq_state_get_received_data(0);
msgStream.Fy = rq_state_get_received_data(1);
msgStream.Fz = rq_state_get_received_data(2);
msgStream.Mx = rq_state_get_received_data(3);
msgStream.My = rq_state_get_received_data(4);
msgStream.Mz = rq_state_get_received_data(5);
return msgStream;
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "robotiq_force_torque_sensor");
ROS_INFO("Trying to Start Sensor");
ros::NodeHandle n;
std_msgs::Bool connection_msg;
ros::param::param<int>("~max_retries", max_retries_, 100);
INT_8 bufStream[512];
INT_32 publish_count = 0;
robotiq_force_torque_sensor::ft_sensor msgStream;
bool connected = false;
//If we can't initialize, we return an error
connected = try_connection();
//Reads basic info on the sensor
connected = try_connection();
//Starts the stream
connected = try_connection();
ros::Publisher sensor_pub = n.advertise<robotiq_force_torque_sensor::ft_sensor>("robotiq_force_torque_sensor", 512);
ros::Publisher wrench_pub = n.advertise<geometry_msgs::WrenchStamped>("robotiq_force_torque_wrench", 512);
ros::Publisher connection_pub = n.advertise<std_msgs::Bool>("robotiq_force_torque_sensor_connected", 1);
ros::Publisher watchdog_pub = n.advertise<std_msgs::Empty>("/robotiq_ft300_force_torque_sensor/watchdog", 1);
ros::ServiceServer service = n.advertiseService("robotiq_force_torque_sensor_acc", receiverCallback);
//std_msgs::String msg;
geometry_msgs::WrenchStamped wrenchMsg;
std_msgs::Empty watchdog_msg;
ros::param::param<std::string>("~frame_id", wrenchMsg.header.frame_id, "robotiq_force_torque_frame_id");
// Publish the connection state
connection_msg.data = connected;
connection_pub.publish(connection_msg);
ros::spinOnce();
if (connected)
{
ROS_INFO("Starting Sensor");
}
while(ros::ok() && connected)
{
connected = try_connection();
if(rq_sensor_get_current_state() == RQ_STATE_RUN)
{
strcpy(bufStream,"");
msgStream = get_data();
if(rq_state_got_new_message())
{
sensor_pub.publish(msgStream);
// compose WrenchStamped Msg
wrenchMsg.header.stamp = ros::Time::now();
wrenchMsg.wrench.force.x = msgStream.Fx;
wrenchMsg.wrench.force.y = msgStream.Fy;
wrenchMsg.wrench.force.z = msgStream.Fz;
wrenchMsg.wrench.torque.x = msgStream.Mx;
wrenchMsg.wrench.torque.y = msgStream.My;
wrenchMsg.wrench.torque.z = msgStream.Mz;
wrench_pub.publish(wrenchMsg);
}
}
// Publish the connection state every 1000 iterations
if (publish_count == 250)
{
watchdog_pub.publish(watchdog_msg);
}
if (publish_count == 1000)
{
connection_msg.data = connected;
connection_pub.publish(connection_msg);
publish_count = 0;
}
publish_count++;
ros::spinOnce();
}
if (!connected)
{
connection_msg.data = connected;
connection_pub.publish(connection_msg);
ros::spinOnce();
}
ROS_INFO("Sensor Stopped");
return 0;
}
<|endoftext|> |
<commit_before>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (C) 2008 Sacha Schutz <istdasklar@free.fr>
* Copyright (C) 2008 Olivier Gueudelot <gueudelotolive@gmail.com>
* Copyright (C) 2008 Charles Huet <packadal@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <gluon/audio/sound.h>
#include <QDebug>
int main( int argc, char* argv[] )
{
GluonAudio::Sound* sound = new GluonAudio::Sound;
sound->load( "/usr/share/sounds/KDE-Sys-Log-In.ogg" );
sound->setVolume( 0.9 ); //between 0 and 1
qDebug() << "Playing sound with duration" << sound->duration() << "seconds.";
sound->play();
while( sound->isPlaying() );
return 0;
}
<commit_msg>Audio: Fix a memory leak in the first example (use delete before exit)<commit_after>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (C) 2008 Sacha Schutz <istdasklar@free.fr>
* Copyright (C) 2008 Olivier Gueudelot <gueudelotolive@gmail.com>
* Copyright (C) 2008 Charles Huet <packadal@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <gluon/audio/sound.h>
#include <QDebug>
int main( int argc, char* argv[] )
{
GluonAudio::Sound* sound = new GluonAudio::Sound;
sound->load( "/usr/share/sounds/KDE-Sys-Log-In.ogg" );
sound->setVolume( 0.9 ); //between 0 and 1
qDebug() << "Playing sound with duration" << sound->duration() << "seconds.";
sound->play();
while( sound->isPlaying() );
delete sound;
return 0;
}
<|endoftext|> |
<commit_before>#include "detection.h"
#define OBJECT_ITEM_LOCATION_ID "locationId"
#define OBJECT_ITEM_VENDOR_ID "vendorId"
#define OBJECT_ITEM_PRODUCT_ID "productId"
#define OBJECT_ITEM_DEVICE_NAME "deviceName"
#define OBJECT_ITEM_MANUFACTURER "manufacturer"
#define OBJECT_ITEM_SERIAL_NUMBER "serialNumber"
#define OBJECT_ITEM_DEVICE_ADDRESS "deviceAddress"
Nan::Callback* addedCallback;
bool isAddedRegistered = false;
Nan::Callback* removedCallback;
bool isRemovedRegistered = false;
void RegisterAdded(const Nan::FunctionCallbackInfo<v8::Value>& args) {
Nan::HandleScope scope;
v8::Local<v8::Function> callback;
if (args.Length() == 0) {
return Nan::ThrowTypeError("First argument must be a function");
}
if (args.Length() == 1) {
// callback
if(!args[0]->IsFunction()) {
return Nan::ThrowTypeError("First argument must be a function");
}
callback = args[0].As<v8::Function>();
}
addedCallback = new Nan::Callback(callback);
isAddedRegistered = true;
}
void NotifyAdded(ListResultItem_t* it) {
Nan::HandleScope scope;
if (it == NULL) {
return;
}
if (isAddedRegistered){
v8::Local<v8::Value> argv[1];
v8::Local<v8::Object> item = Nan::New<v8::Object>();
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_LOCATION_ID).ToLocalChecked(), Nan::New<v8::Number>(it->locationId));
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_VENDOR_ID).ToLocalChecked(), Nan::New<v8::Number>(it->vendorId));
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_PRODUCT_ID).ToLocalChecked(), Nan::New<v8::Number>(it->productId));
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_DEVICE_NAME).ToLocalChecked(), Nan::New<v8::String>(it->deviceName.c_str()).ToLocalChecked());
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_MANUFACTURER).ToLocalChecked(), Nan::New<v8::String>(it->manufacturer.c_str()).ToLocalChecked());
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_SERIAL_NUMBER).ToLocalChecked(), Nan::New<v8::String>(it->serialNumber.c_str()).ToLocalChecked());
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_DEVICE_ADDRESS).ToLocalChecked(), Nan::New<v8::Number>(it->deviceAddress));
argv[0] = item;
addedCallback->Call(1, argv);
}
}
void RegisterRemoved(const Nan::FunctionCallbackInfo<v8::Value>& args) {
Nan::HandleScope scope;
v8::Local<v8::Function> callback;
if (args.Length() == 0) {
return Nan::ThrowTypeError("First argument must be a function");
}
if (args.Length() == 1) {
// callback
if(!args[0]->IsFunction()) {
return Nan::ThrowTypeError("First argument must be a function");
}
callback = args[0].As<v8::Function>();
}
removedCallback = new Nan::Callback(callback);
isRemovedRegistered = true;
}
void NotifyRemoved(ListResultItem_t* it) {
Nan::HandleScope scope;
if (it == NULL) {
return;
}
if (isRemovedRegistered) {
v8::Local<v8::Value> argv[1];
v8::Local<v8::Object> item = Nan::New<v8::Object>();
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_LOCATION_ID).ToLocalChecked(), Nan::New<v8::Number>(it->locationId));
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_VENDOR_ID).ToLocalChecked(), Nan::New<v8::Number>(it->vendorId));
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_PRODUCT_ID).ToLocalChecked(), Nan::New<v8::Number>(it->productId));
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_DEVICE_NAME).ToLocalChecked(), Nan::New<v8::String>(it->deviceName.c_str()).ToLocalChecked());
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_MANUFACTURER).ToLocalChecked(), Nan::New<v8::String>(it->manufacturer.c_str()).ToLocalChecked());
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_SERIAL_NUMBER).ToLocalChecked(), Nan::New<v8::String>(it->serialNumber.c_str()).ToLocalChecked());
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_DEVICE_ADDRESS).ToLocalChecked(), Nan::New<v8::Number>(it->deviceAddress));
argv[0] = item;
removedCallback->Call(1, argv);
}
}
void Find(const Nan::FunctionCallbackInfo<v8::Value>& args) {
Nan::HandleScope scope;
int vid = 0;
int pid = 0;
v8::Local<v8::Function> callback;
if (args.Length() == 0) {
return Nan::ThrowTypeError("First argument must be a function");
}
if (args.Length() == 3) {
if (args[0]->IsNumber() && args[1]->IsNumber()) {
vid = (int) Nan::To<int>(args[0]).FromJust();
pid = (int) Nan::To<int>(args[1]).FromJust();
}
// callback
if(!args[2]->IsFunction()) {
return Nan::ThrowTypeError("Third argument must be a function");
}
callback = args[2].As<v8::Function>();
}
if (args.Length() == 2) {
if (args[0]->IsNumber()) {
vid = (int) Nan::To<int>(args[0]).FromJust();
}
// callback
if(!args[1]->IsFunction()) {
return Nan::ThrowTypeError("Second argument must be a function");
}
callback = args[1].As<v8::Function>();
}
if (args.Length() == 1) {
// callback
if(!args[0]->IsFunction()) {
return Nan::ThrowTypeError("First argument must be a function");
}
callback = args[0].As<v8::Function>();
}
ListBaton* baton = new ListBaton();
strcpy(baton->errorString, "");
baton->callback = new Nan::Callback(callback);
baton->vid = vid;
baton->pid = pid;
uv_work_t* req = new uv_work_t();
req->data = baton;
uv_queue_work(uv_default_loop(), req, EIO_Find, (uv_after_work_cb)EIO_AfterFind);
}
void EIO_AfterFind(uv_work_t* req) {
Nan::HandleScope scope;
ListBaton* data = static_cast<ListBaton*>(req->data);
v8::Local<v8::Value> argv[2];
if(data->errorString[0]) {
argv[0] = v8::Exception::Error(Nan::New<v8::String>(data->errorString).ToLocalChecked());
argv[1] = Nan::Undefined();
}
else {
v8::Local<v8::Array> results = Nan::New<v8::Array>();
int i = 0;
for(std::list<ListResultItem_t*>::iterator it = data->results.begin(); it != data->results.end(); it++, i++) {
v8::Local<v8::Object> item = Nan::New<v8::Object>();
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_LOCATION_ID).ToLocalChecked(), Nan::New<v8::Number>((*it)->locationId));
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_VENDOR_ID).ToLocalChecked(), Nan::New<v8::Number>((*it)->vendorId));
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_PRODUCT_ID).ToLocalChecked(), Nan::New<v8::Number>((*it)->productId));
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_DEVICE_NAME).ToLocalChecked(), Nan::New<v8::String>((*it)->deviceName.c_str()).ToLocalChecked());
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_MANUFACTURER).ToLocalChecked(), Nan::New<v8::String>((*it)->manufacturer.c_str()).ToLocalChecked());
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_SERIAL_NUMBER).ToLocalChecked(), Nan::New<v8::String>((*it)->serialNumber.c_str()).ToLocalChecked());
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_DEVICE_ADDRESS).ToLocalChecked(), Nan::New<v8::Number>((*it)->deviceAddress));
Nan::Set(results, i, item);
}
argv[0] = Nan::Undefined();
argv[1] = results;
}
data->callback->Call(2, argv);
for(std::list<ListResultItem_t*>::iterator it = data->results.begin(); it != data->results.end(); it++) {
delete *it;
}
delete data;
delete req;
}
void StartMonitoring(const Nan::FunctionCallbackInfo<v8::Value>& args) {
Start();
}
void StopMonitoring(const Nan::FunctionCallbackInfo<v8::Value>& args) {
Stop();
}
extern "C" {
void init (v8::Local<v8::Object> target) {
Nan::SetMethod(target, "find", Find);
Nan::SetMethod(target, "registerAdded", RegisterAdded);
Nan::SetMethod(target, "registerRemoved", RegisterRemoved);
Nan::SetMethod(target, "startMonitoring", StartMonitoring);
Nan::SetMethod(target, "stopMonitoring", StopMonitoring);
InitDetection();
}
}
NODE_MODULE(detection, init);
<commit_msg>Fix deprecation warnings for Nan::Callback:Call()<commit_after>#include "detection.h"
#define OBJECT_ITEM_LOCATION_ID "locationId"
#define OBJECT_ITEM_VENDOR_ID "vendorId"
#define OBJECT_ITEM_PRODUCT_ID "productId"
#define OBJECT_ITEM_DEVICE_NAME "deviceName"
#define OBJECT_ITEM_MANUFACTURER "manufacturer"
#define OBJECT_ITEM_SERIAL_NUMBER "serialNumber"
#define OBJECT_ITEM_DEVICE_ADDRESS "deviceAddress"
Nan::Callback* addedCallback;
bool isAddedRegistered = false;
Nan::Callback* removedCallback;
bool isRemovedRegistered = false;
void RegisterAdded(const Nan::FunctionCallbackInfo<v8::Value>& args) {
Nan::HandleScope scope;
v8::Local<v8::Function> callback;
if (args.Length() == 0) {
return Nan::ThrowTypeError("First argument must be a function");
}
if (args.Length() == 1) {
// callback
if(!args[0]->IsFunction()) {
return Nan::ThrowTypeError("First argument must be a function");
}
callback = args[0].As<v8::Function>();
}
addedCallback = new Nan::Callback(callback);
isAddedRegistered = true;
}
void NotifyAdded(ListResultItem_t* it) {
Nan::HandleScope scope;
if (it == NULL) {
return;
}
if (isAddedRegistered){
v8::Local<v8::Value> argv[1];
v8::Local<v8::Object> item = Nan::New<v8::Object>();
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_LOCATION_ID).ToLocalChecked(), Nan::New<v8::Number>(it->locationId));
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_VENDOR_ID).ToLocalChecked(), Nan::New<v8::Number>(it->vendorId));
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_PRODUCT_ID).ToLocalChecked(), Nan::New<v8::Number>(it->productId));
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_DEVICE_NAME).ToLocalChecked(), Nan::New<v8::String>(it->deviceName.c_str()).ToLocalChecked());
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_MANUFACTURER).ToLocalChecked(), Nan::New<v8::String>(it->manufacturer.c_str()).ToLocalChecked());
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_SERIAL_NUMBER).ToLocalChecked(), Nan::New<v8::String>(it->serialNumber.c_str()).ToLocalChecked());
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_DEVICE_ADDRESS).ToLocalChecked(), Nan::New<v8::Number>(it->deviceAddress));
argv[0] = item;
Nan::AsyncResource resource("usb-detection:NotifyAdded");
addedCallback->Call(1, argv, &resource);
}
}
void RegisterRemoved(const Nan::FunctionCallbackInfo<v8::Value>& args) {
Nan::HandleScope scope;
v8::Local<v8::Function> callback;
if (args.Length() == 0) {
return Nan::ThrowTypeError("First argument must be a function");
}
if (args.Length() == 1) {
// callback
if(!args[0]->IsFunction()) {
return Nan::ThrowTypeError("First argument must be a function");
}
callback = args[0].As<v8::Function>();
}
removedCallback = new Nan::Callback(callback);
isRemovedRegistered = true;
}
void NotifyRemoved(ListResultItem_t* it) {
Nan::HandleScope scope;
if (it == NULL) {
return;
}
if (isRemovedRegistered) {
v8::Local<v8::Value> argv[1];
v8::Local<v8::Object> item = Nan::New<v8::Object>();
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_LOCATION_ID).ToLocalChecked(), Nan::New<v8::Number>(it->locationId));
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_VENDOR_ID).ToLocalChecked(), Nan::New<v8::Number>(it->vendorId));
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_PRODUCT_ID).ToLocalChecked(), Nan::New<v8::Number>(it->productId));
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_DEVICE_NAME).ToLocalChecked(), Nan::New<v8::String>(it->deviceName.c_str()).ToLocalChecked());
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_MANUFACTURER).ToLocalChecked(), Nan::New<v8::String>(it->manufacturer.c_str()).ToLocalChecked());
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_SERIAL_NUMBER).ToLocalChecked(), Nan::New<v8::String>(it->serialNumber.c_str()).ToLocalChecked());
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_DEVICE_ADDRESS).ToLocalChecked(), Nan::New<v8::Number>(it->deviceAddress));
argv[0] = item;
Nan::AsyncResource resource("usb-detection:NotifyRemoved");
removedCallback->Call(1, argv, &resource);
}
}
void Find(const Nan::FunctionCallbackInfo<v8::Value>& args) {
Nan::HandleScope scope;
int vid = 0;
int pid = 0;
v8::Local<v8::Function> callback;
if (args.Length() == 0) {
return Nan::ThrowTypeError("First argument must be a function");
}
if (args.Length() == 3) {
if (args[0]->IsNumber() && args[1]->IsNumber()) {
vid = (int) Nan::To<int>(args[0]).FromJust();
pid = (int) Nan::To<int>(args[1]).FromJust();
}
// callback
if(!args[2]->IsFunction()) {
return Nan::ThrowTypeError("Third argument must be a function");
}
callback = args[2].As<v8::Function>();
}
if (args.Length() == 2) {
if (args[0]->IsNumber()) {
vid = (int) Nan::To<int>(args[0]).FromJust();
}
// callback
if(!args[1]->IsFunction()) {
return Nan::ThrowTypeError("Second argument must be a function");
}
callback = args[1].As<v8::Function>();
}
if (args.Length() == 1) {
// callback
if(!args[0]->IsFunction()) {
return Nan::ThrowTypeError("First argument must be a function");
}
callback = args[0].As<v8::Function>();
}
ListBaton* baton = new ListBaton();
strcpy(baton->errorString, "");
baton->callback = new Nan::Callback(callback);
baton->vid = vid;
baton->pid = pid;
uv_work_t* req = new uv_work_t();
req->data = baton;
uv_queue_work(uv_default_loop(), req, EIO_Find, (uv_after_work_cb)EIO_AfterFind);
}
void EIO_AfterFind(uv_work_t* req) {
Nan::HandleScope scope;
ListBaton* data = static_cast<ListBaton*>(req->data);
v8::Local<v8::Value> argv[2];
if(data->errorString[0]) {
argv[0] = v8::Exception::Error(Nan::New<v8::String>(data->errorString).ToLocalChecked());
argv[1] = Nan::Undefined();
}
else {
v8::Local<v8::Array> results = Nan::New<v8::Array>();
int i = 0;
for(std::list<ListResultItem_t*>::iterator it = data->results.begin(); it != data->results.end(); it++, i++) {
v8::Local<v8::Object> item = Nan::New<v8::Object>();
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_LOCATION_ID).ToLocalChecked(), Nan::New<v8::Number>((*it)->locationId));
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_VENDOR_ID).ToLocalChecked(), Nan::New<v8::Number>((*it)->vendorId));
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_PRODUCT_ID).ToLocalChecked(), Nan::New<v8::Number>((*it)->productId));
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_DEVICE_NAME).ToLocalChecked(), Nan::New<v8::String>((*it)->deviceName.c_str()).ToLocalChecked());
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_MANUFACTURER).ToLocalChecked(), Nan::New<v8::String>((*it)->manufacturer.c_str()).ToLocalChecked());
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_SERIAL_NUMBER).ToLocalChecked(), Nan::New<v8::String>((*it)->serialNumber.c_str()).ToLocalChecked());
Nan::Set(item, Nan::New<v8::String>(OBJECT_ITEM_DEVICE_ADDRESS).ToLocalChecked(), Nan::New<v8::Number>((*it)->deviceAddress));
Nan::Set(results, i, item);
}
argv[0] = Nan::Undefined();
argv[1] = results;
}
Nan::AsyncResource resource("usb-detection:EIO_AfterFind");
data->callback->Call(2, argv, &resource);
for(std::list<ListResultItem_t*>::iterator it = data->results.begin(); it != data->results.end(); it++) {
delete *it;
}
delete data;
delete req;
}
void StartMonitoring(const Nan::FunctionCallbackInfo<v8::Value>& args) {
Start();
}
void StopMonitoring(const Nan::FunctionCallbackInfo<v8::Value>& args) {
Stop();
}
extern "C" {
void init (v8::Local<v8::Object> target) {
Nan::SetMethod(target, "find", Find);
Nan::SetMethod(target, "registerAdded", RegisterAdded);
Nan::SetMethod(target, "registerRemoved", RegisterRemoved);
Nan::SetMethod(target, "startMonitoring", StartMonitoring);
Nan::SetMethod(target, "stopMonitoring", StopMonitoring);
InitDetection();
}
}
NODE_MODULE(detection, init);
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2001-2004 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders 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 <unistd.h>
#include <fcntl.h>
#include <cstdio>
#include <string>
#include "base/intmath.hh"
#include "base/loader/object_file.hh"
#include "base/statistics.hh"
#include "cpu/exec_context.hh"
#include "cpu/full_cpu/smt.hh"
#include "cpu/full_cpu/thread.hh"
#include "eio/eio.hh"
#include "mem/functional_mem/main_memory.hh"
#include "sim/builder.hh"
#include "sim/fake_syscall.hh"
#include "sim/process.hh"
#include "sim/stats.hh"
#ifdef TARGET_ALPHA
#include "arch/alpha/alpha_tru64_process.hh"
#include "arch/alpha/alpha_linux_process.hh"
#endif
using namespace std;
//
// The purpose of this code is to fake the loader & syscall mechanism
// when there's no OS: thus there's no resone to use it in FULL_SYSTEM
// mode when we do have an OS
//
#ifdef FULL_SYSTEM
#error "process.cc not compatible with FULL_SYSTEM"
#endif
// current number of allocated processes
int num_processes = 0;
Process::Process(const string &name,
int stdin_fd, // initial I/O descriptors
int stdout_fd,
int stderr_fd)
: SimObject(name)
{
// allocate memory space
memory = new MainMemory(name + ".MainMem");
// allocate initial register file
init_regs = new RegFile;
memset(init_regs, 0, sizeof(RegFile));
// initialize first 3 fds (stdin, stdout, stderr)
fd_map[STDIN_FILENO] = stdin_fd;
fd_map[STDOUT_FILENO] = stdout_fd;
fd_map[STDERR_FILENO] = stderr_fd;
// mark remaining fds as free
for (int i = 3; i <= MAX_FD; ++i) {
fd_map[i] = -1;
}
num_syscalls = 0;
// other parameters will be initialized when the program is loaded
}
void
Process::regStats()
{
using namespace Stats;
num_syscalls
.name(name() + ".PROG:num_syscalls")
.desc("Number of system calls")
;
}
//
// static helper functions
//
int
Process::openInputFile(const string &filename)
{
int fd = open(filename.c_str(), O_RDONLY);
if (fd == -1) {
perror(NULL);
cerr << "unable to open \"" << filename << "\" for reading\n";
fatal("can't open input file");
}
return fd;
}
int
Process::openOutputFile(const string &filename)
{
int fd = open(filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0774);
if (fd == -1) {
perror(NULL);
cerr << "unable to open \"" << filename << "\" for writing\n";
fatal("can't open output file");
}
return fd;
}
int
Process::registerExecContext(ExecContext *xc)
{
// add to list
int myIndex = execContexts.size();
execContexts.push_back(xc);
if (myIndex == 0) {
// first exec context for this process... initialize & enable
// copy process's initial regs struct
xc->regs = *init_regs;
// mark this context as active.
// activate with zero delay so that we start ticking right
// away on cycle 0
xc->activate(0);
}
// return CPU number to caller and increment available CPU count
return myIndex;
}
void
Process::replaceExecContext(ExecContext *xc, int xcIndex)
{
if (xcIndex >= execContexts.size()) {
panic("replaceExecContext: bad xcIndex, %d >= %d\n",
xcIndex, execContexts.size());
}
execContexts[xcIndex] = xc;
}
// map simulator fd sim_fd to target fd tgt_fd
void
Process::dup_fd(int sim_fd, int tgt_fd)
{
if (tgt_fd < 0 || tgt_fd > MAX_FD)
panic("Process::dup_fd tried to dup past MAX_FD (%d)", tgt_fd);
fd_map[tgt_fd] = sim_fd;
}
// generate new target fd for sim_fd
int
Process::open_fd(int sim_fd)
{
int free_fd;
// in case open() returns an error, don't allocate a new fd
if (sim_fd == -1)
return -1;
// find first free target fd
for (free_fd = 0; fd_map[free_fd] >= 0; ++free_fd) {
if (free_fd == MAX_FD)
panic("Process::open_fd: out of file descriptors!");
}
fd_map[free_fd] = sim_fd;
return free_fd;
}
// look up simulator fd for given target fd
int
Process::sim_fd(int tgt_fd)
{
if (tgt_fd > MAX_FD)
return -1;
return fd_map[tgt_fd];
}
//
// need to declare these here since there is no concrete Process type
// that can be constructed (i.e., no REGISTER_SIM_OBJECT() macro call,
// which is where these get declared for concrete types).
//
DEFINE_SIM_OBJECT_CLASS_NAME("Process", Process)
////////////////////////////////////////////////////////////////////////
//
// LiveProcess member definitions
//
////////////////////////////////////////////////////////////////////////
static void
copyStringArray(vector<string> &strings, Addr array_ptr, Addr data_ptr,
FunctionalMemory *memory)
{
for (int i = 0; i < strings.size(); ++i) {
memory->access(Write, array_ptr, &data_ptr, sizeof(Addr));
memory->writeString(data_ptr, strings[i].c_str());
array_ptr += sizeof(Addr);
data_ptr += strings[i].size() + 1;
}
// add NULL terminator
data_ptr = 0;
memory->access(Write, array_ptr, &data_ptr, sizeof(Addr));
}
LiveProcess::LiveProcess(const string &name, ObjectFile *objFile,
int stdin_fd, int stdout_fd, int stderr_fd,
vector<string> &argv, vector<string> &envp)
: Process(name, stdin_fd, stdout_fd, stderr_fd)
{
prog_fname = argv[0];
prog_entry = objFile->entryPoint();
text_base = objFile->textBase();
text_size = objFile->textSize();
data_base = objFile->dataBase();
data_size = objFile->dataSize() + objFile->bssSize();
brk_point = RoundUp<uint64_t>(data_base + data_size, VMPageSize);
// load object file into target memory
objFile->loadSections(memory);
// Set up stack. On Alpha, stack goes below text section. This
// code should get moved to some architecture-specific spot.
stack_base = text_base - (409600+4096);
// Set up region for mmaps. Tru64 seems to start just above 0 and
// grow up from there.
mmap_base = 0x10000;
// Set pointer for next thread stack. Reserve 8M for main stack.
next_thread_stack_base = stack_base - (8 * 1024 * 1024);
// Calculate how much space we need for arg & env arrays.
int argv_array_size = sizeof(Addr) * (argv.size() + 1);
int envp_array_size = sizeof(Addr) * (envp.size() + 1);
int arg_data_size = 0;
for (int i = 0; i < argv.size(); ++i) {
arg_data_size += argv[i].size() + 1;
}
int env_data_size = 0;
for (int i = 0; i < envp.size(); ++i) {
env_data_size += envp[i].size() + 1;
}
int space_needed =
argv_array_size + envp_array_size + arg_data_size + env_data_size;
// for SimpleScalar compatibility
if (space_needed < 16384)
space_needed = 16384;
// set bottom of stack
stack_min = stack_base - space_needed;
// align it
stack_min &= ~7;
stack_size = stack_base - stack_min;
// map out initial stack contents
Addr argv_array_base = stack_min + sizeof(uint64_t); // room for argc
Addr envp_array_base = argv_array_base + argv_array_size;
Addr arg_data_base = envp_array_base + envp_array_size;
Addr env_data_base = arg_data_base + arg_data_size;
// write contents to stack
uint64_t argc = argv.size();
memory->access(Write, stack_min, &argc, sizeof(uint64_t));
copyStringArray(argv, argv_array_base, arg_data_base, memory);
copyStringArray(envp, envp_array_base, env_data_base, memory);
init_regs->intRegFile[ArgumentReg0] = argc;
init_regs->intRegFile[ArgumentReg1] = argv_array_base;
init_regs->intRegFile[StackPointerReg] = stack_min;
init_regs->intRegFile[GlobalPointerReg] = objFile->globalPointer();
init_regs->pc = prog_entry;
init_regs->npc = prog_entry + sizeof(MachInst);
}
LiveProcess *
LiveProcess::create(const string &name,
int stdin_fd, int stdout_fd, int stderr_fd,
vector<string> &argv, vector<string> &envp)
{
LiveProcess *process = NULL;
ObjectFile *objFile = createObjectFile(argv[0]);
if (objFile == NULL) {
fatal("Can't load object file %s", argv[0]);
}
// check object type & set up syscall emulation pointer
if (objFile->getArch() == ObjectFile::Alpha) {
switch (objFile->getOpSys()) {
case ObjectFile::Tru64:
process = new AlphaTru64Process(name, objFile,
stdin_fd, stdout_fd, stderr_fd,
argv, envp);
break;
case ObjectFile::Linux:
process = new AlphaLinuxProcess(name, objFile,
stdin_fd, stdout_fd, stderr_fd,
argv, envp);
break;
default:
fatal("Unknown/unsupported operating system.");
}
} else {
fatal("Unknown object file architecture.");
}
delete objFile;
if (process == NULL)
fatal("Unknown error creating process object.");
return process;
}
BEGIN_DECLARE_SIM_OBJECT_PARAMS(LiveProcess)
VectorParam<string> cmd;
Param<string> input;
Param<string> output;
VectorParam<string> env;
END_DECLARE_SIM_OBJECT_PARAMS(LiveProcess)
BEGIN_INIT_SIM_OBJECT_PARAMS(LiveProcess)
INIT_PARAM(cmd, "command line (executable plus arguments)"),
INIT_PARAM(input, "filename for stdin (dflt: use sim stdin)"),
INIT_PARAM(output, "filename for stdout/stderr (dflt: use sim stdout)"),
INIT_PARAM(env, "environment settings")
END_INIT_SIM_OBJECT_PARAMS(LiveProcess)
CREATE_SIM_OBJECT(LiveProcess)
{
// initialize file descriptors to default: same as simulator
int stdin_fd = input.isValid() ? Process::openInputFile(input) : 0;
int stdout_fd = output.isValid() ? Process::openOutputFile(output) : 1;
int stderr_fd = output.isValid() ? stdout_fd : 2;
// dummy for default env
vector<string> null_vec;
// We do this with "temp" because of the bogus compiler warning
// you get with g++ 2.95 -O if you just "return new LiveProcess(..."
LiveProcess *temp = LiveProcess::create(getInstanceName(),
stdin_fd, stdout_fd, stderr_fd,
cmd,
env.isValid() ? env : null_vec);
return temp;
}
REGISTER_SIM_OBJECT("LiveProcess", LiveProcess)
<commit_msg>Clean up obsolete g++ 2.95 workaround.<commit_after>/*
* Copyright (c) 2001-2004 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders 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 <unistd.h>
#include <fcntl.h>
#include <cstdio>
#include <string>
#include "base/intmath.hh"
#include "base/loader/object_file.hh"
#include "base/statistics.hh"
#include "cpu/exec_context.hh"
#include "cpu/full_cpu/smt.hh"
#include "cpu/full_cpu/thread.hh"
#include "eio/eio.hh"
#include "mem/functional_mem/main_memory.hh"
#include "sim/builder.hh"
#include "sim/fake_syscall.hh"
#include "sim/process.hh"
#include "sim/stats.hh"
#ifdef TARGET_ALPHA
#include "arch/alpha/alpha_tru64_process.hh"
#include "arch/alpha/alpha_linux_process.hh"
#endif
using namespace std;
//
// The purpose of this code is to fake the loader & syscall mechanism
// when there's no OS: thus there's no resone to use it in FULL_SYSTEM
// mode when we do have an OS
//
#ifdef FULL_SYSTEM
#error "process.cc not compatible with FULL_SYSTEM"
#endif
// current number of allocated processes
int num_processes = 0;
Process::Process(const string &name,
int stdin_fd, // initial I/O descriptors
int stdout_fd,
int stderr_fd)
: SimObject(name)
{
// allocate memory space
memory = new MainMemory(name + ".MainMem");
// allocate initial register file
init_regs = new RegFile;
memset(init_regs, 0, sizeof(RegFile));
// initialize first 3 fds (stdin, stdout, stderr)
fd_map[STDIN_FILENO] = stdin_fd;
fd_map[STDOUT_FILENO] = stdout_fd;
fd_map[STDERR_FILENO] = stderr_fd;
// mark remaining fds as free
for (int i = 3; i <= MAX_FD; ++i) {
fd_map[i] = -1;
}
num_syscalls = 0;
// other parameters will be initialized when the program is loaded
}
void
Process::regStats()
{
using namespace Stats;
num_syscalls
.name(name() + ".PROG:num_syscalls")
.desc("Number of system calls")
;
}
//
// static helper functions
//
int
Process::openInputFile(const string &filename)
{
int fd = open(filename.c_str(), O_RDONLY);
if (fd == -1) {
perror(NULL);
cerr << "unable to open \"" << filename << "\" for reading\n";
fatal("can't open input file");
}
return fd;
}
int
Process::openOutputFile(const string &filename)
{
int fd = open(filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0774);
if (fd == -1) {
perror(NULL);
cerr << "unable to open \"" << filename << "\" for writing\n";
fatal("can't open output file");
}
return fd;
}
int
Process::registerExecContext(ExecContext *xc)
{
// add to list
int myIndex = execContexts.size();
execContexts.push_back(xc);
if (myIndex == 0) {
// first exec context for this process... initialize & enable
// copy process's initial regs struct
xc->regs = *init_regs;
// mark this context as active.
// activate with zero delay so that we start ticking right
// away on cycle 0
xc->activate(0);
}
// return CPU number to caller and increment available CPU count
return myIndex;
}
void
Process::replaceExecContext(ExecContext *xc, int xcIndex)
{
if (xcIndex >= execContexts.size()) {
panic("replaceExecContext: bad xcIndex, %d >= %d\n",
xcIndex, execContexts.size());
}
execContexts[xcIndex] = xc;
}
// map simulator fd sim_fd to target fd tgt_fd
void
Process::dup_fd(int sim_fd, int tgt_fd)
{
if (tgt_fd < 0 || tgt_fd > MAX_FD)
panic("Process::dup_fd tried to dup past MAX_FD (%d)", tgt_fd);
fd_map[tgt_fd] = sim_fd;
}
// generate new target fd for sim_fd
int
Process::open_fd(int sim_fd)
{
int free_fd;
// in case open() returns an error, don't allocate a new fd
if (sim_fd == -1)
return -1;
// find first free target fd
for (free_fd = 0; fd_map[free_fd] >= 0; ++free_fd) {
if (free_fd == MAX_FD)
panic("Process::open_fd: out of file descriptors!");
}
fd_map[free_fd] = sim_fd;
return free_fd;
}
// look up simulator fd for given target fd
int
Process::sim_fd(int tgt_fd)
{
if (tgt_fd > MAX_FD)
return -1;
return fd_map[tgt_fd];
}
//
// need to declare these here since there is no concrete Process type
// that can be constructed (i.e., no REGISTER_SIM_OBJECT() macro call,
// which is where these get declared for concrete types).
//
DEFINE_SIM_OBJECT_CLASS_NAME("Process", Process)
////////////////////////////////////////////////////////////////////////
//
// LiveProcess member definitions
//
////////////////////////////////////////////////////////////////////////
static void
copyStringArray(vector<string> &strings, Addr array_ptr, Addr data_ptr,
FunctionalMemory *memory)
{
for (int i = 0; i < strings.size(); ++i) {
memory->access(Write, array_ptr, &data_ptr, sizeof(Addr));
memory->writeString(data_ptr, strings[i].c_str());
array_ptr += sizeof(Addr);
data_ptr += strings[i].size() + 1;
}
// add NULL terminator
data_ptr = 0;
memory->access(Write, array_ptr, &data_ptr, sizeof(Addr));
}
LiveProcess::LiveProcess(const string &name, ObjectFile *objFile,
int stdin_fd, int stdout_fd, int stderr_fd,
vector<string> &argv, vector<string> &envp)
: Process(name, stdin_fd, stdout_fd, stderr_fd)
{
prog_fname = argv[0];
prog_entry = objFile->entryPoint();
text_base = objFile->textBase();
text_size = objFile->textSize();
data_base = objFile->dataBase();
data_size = objFile->dataSize() + objFile->bssSize();
brk_point = RoundUp<uint64_t>(data_base + data_size, VMPageSize);
// load object file into target memory
objFile->loadSections(memory);
// Set up stack. On Alpha, stack goes below text section. This
// code should get moved to some architecture-specific spot.
stack_base = text_base - (409600+4096);
// Set up region for mmaps. Tru64 seems to start just above 0 and
// grow up from there.
mmap_base = 0x10000;
// Set pointer for next thread stack. Reserve 8M for main stack.
next_thread_stack_base = stack_base - (8 * 1024 * 1024);
// Calculate how much space we need for arg & env arrays.
int argv_array_size = sizeof(Addr) * (argv.size() + 1);
int envp_array_size = sizeof(Addr) * (envp.size() + 1);
int arg_data_size = 0;
for (int i = 0; i < argv.size(); ++i) {
arg_data_size += argv[i].size() + 1;
}
int env_data_size = 0;
for (int i = 0; i < envp.size(); ++i) {
env_data_size += envp[i].size() + 1;
}
int space_needed =
argv_array_size + envp_array_size + arg_data_size + env_data_size;
// for SimpleScalar compatibility
if (space_needed < 16384)
space_needed = 16384;
// set bottom of stack
stack_min = stack_base - space_needed;
// align it
stack_min &= ~7;
stack_size = stack_base - stack_min;
// map out initial stack contents
Addr argv_array_base = stack_min + sizeof(uint64_t); // room for argc
Addr envp_array_base = argv_array_base + argv_array_size;
Addr arg_data_base = envp_array_base + envp_array_size;
Addr env_data_base = arg_data_base + arg_data_size;
// write contents to stack
uint64_t argc = argv.size();
memory->access(Write, stack_min, &argc, sizeof(uint64_t));
copyStringArray(argv, argv_array_base, arg_data_base, memory);
copyStringArray(envp, envp_array_base, env_data_base, memory);
init_regs->intRegFile[ArgumentReg0] = argc;
init_regs->intRegFile[ArgumentReg1] = argv_array_base;
init_regs->intRegFile[StackPointerReg] = stack_min;
init_regs->intRegFile[GlobalPointerReg] = objFile->globalPointer();
init_regs->pc = prog_entry;
init_regs->npc = prog_entry + sizeof(MachInst);
}
LiveProcess *
LiveProcess::create(const string &name,
int stdin_fd, int stdout_fd, int stderr_fd,
vector<string> &argv, vector<string> &envp)
{
LiveProcess *process = NULL;
ObjectFile *objFile = createObjectFile(argv[0]);
if (objFile == NULL) {
fatal("Can't load object file %s", argv[0]);
}
// check object type & set up syscall emulation pointer
if (objFile->getArch() == ObjectFile::Alpha) {
switch (objFile->getOpSys()) {
case ObjectFile::Tru64:
process = new AlphaTru64Process(name, objFile,
stdin_fd, stdout_fd, stderr_fd,
argv, envp);
break;
case ObjectFile::Linux:
process = new AlphaLinuxProcess(name, objFile,
stdin_fd, stdout_fd, stderr_fd,
argv, envp);
break;
default:
fatal("Unknown/unsupported operating system.");
}
} else {
fatal("Unknown object file architecture.");
}
delete objFile;
if (process == NULL)
fatal("Unknown error creating process object.");
return process;
}
BEGIN_DECLARE_SIM_OBJECT_PARAMS(LiveProcess)
VectorParam<string> cmd;
Param<string> input;
Param<string> output;
VectorParam<string> env;
END_DECLARE_SIM_OBJECT_PARAMS(LiveProcess)
BEGIN_INIT_SIM_OBJECT_PARAMS(LiveProcess)
INIT_PARAM(cmd, "command line (executable plus arguments)"),
INIT_PARAM(input, "filename for stdin (dflt: use sim stdin)"),
INIT_PARAM(output, "filename for stdout/stderr (dflt: use sim stdout)"),
INIT_PARAM(env, "environment settings")
END_INIT_SIM_OBJECT_PARAMS(LiveProcess)
CREATE_SIM_OBJECT(LiveProcess)
{
// initialize file descriptors to default: same as simulator
int stdin_fd = input.isValid() ? Process::openInputFile(input) : 0;
int stdout_fd = output.isValid() ? Process::openOutputFile(output) : 1;
int stderr_fd = output.isValid() ? stdout_fd : 2;
// dummy for default env
vector<string> null_vec;
return LiveProcess::create(getInstanceName(),
stdin_fd, stdout_fd, stderr_fd,
cmd,
env.isValid() ? env : null_vec);
}
REGISTER_SIM_OBJECT("LiveProcess", LiveProcess)
<|endoftext|> |
<commit_before>/******************************************************************************
This source file is part of the Avogadro project.
Copyright 2015 Kitware, Inc.
This source code is released under the New BSD License, (the "License").
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
******************************************************************************/
#include "nwchemjson.h"
#include <avogadro/core/crystaltools.h>
#include <avogadro/core/elements.h>
#include <avogadro/core/gaussianset.h>
#include <avogadro/core/molecule.h>
#include <avogadro/core/unitcell.h>
#include <jsoncpp.cpp>
#include <iostream>
namespace Avogadro {
namespace QuantumIO {
using std::string;
using std::vector;
using std::cout;
using std::endl;
using Json::Value;
using Json::Reader;
using Json::StyledStreamWriter;
using Core::Array;
using Core::Atom;
using Core::BasisSet;
using Core::Bond;
using Core::CrystalTools;
using Core::Elements;
using Core::GaussianSet;
using Core::Molecule;
using Core::Variant;
NWChemJson::NWChemJson()
{
}
NWChemJson::~NWChemJson()
{
}
bool NWChemJson::read(std::istream &file, Molecule &molecule)
{
Value root;
Reader reader;
bool ok = reader.parse(file, root);
if (!ok) {
appendError("Error parsing JSON: " + reader.getFormatedErrorMessages());
return false;
}
if (!root.isObject()) {
appendError("Error: Input is not a JSON object.");
return false;
}
Value simulation = root["simulation"];
if (simulation.empty()) {
appendError("Error: no \"simulation\" key found.");
return false;
}
// Scan the calculations array for calculationSetup.molecule objects.
Value calculations = simulation["calculations"];
if (calculations.empty() || !calculations.isArray()) {
appendError("Error: no \"calculations\" array found.");
return false;
}
// Iterate through the objects in the array, and print out any molecules.
Value moleculeArray(Json::arrayValue);
Value calculationVib;
for (size_t i = 0; i < calculations.size(); ++i) {
Value calcObj = calculations.get(i, "");
if (calcObj.isObject()) {
string calcType = calcObj["calculationType"].asString();
// Store the last vibrational frequencies calculation object.
if (calcType == "vibrationalModes")
calculationVib = calcObj;
Value calcSetup = calcObj["calculationSetup"];
Value calcMol = calcSetup["molecule"];
string calcMolStr = calcMol.toStyledString();
if (!calcMol.isNull() && calcMol.isObject()) {
calcMolStr = "Object with id: " + calcMol["id"].asString();
moleculeArray.append(calcMol);
}
Value calcResults = calcObj["calculationResults"];
calcMol = calcResults["molecule"];
if (!calcMol.isNull() && calcMol.isObject()) {
calcMolStr = "Object with id: " + calcMol["id"].asString();
moleculeArray.append(calcMol);
}
}
}
// For now, we are just grabbing the "last" molecule, and using that. This
// needs more complex logic to step through the file and do it properly.
Value finalMol = moleculeArray.get(moleculeArray.size() - 1, 0);
Value atoms = finalMol["atoms"];
if (atoms.isArray()) {
for (size_t i = 0; i < atoms.size(); ++i) {
Value jsonAtom = atoms.get(i, 0);
if (jsonAtom.isNull() || !jsonAtom.isObject())
continue;
Atom a =
molecule.addAtom(static_cast<unsigned char>(jsonAtom["elementNumber"]
.asInt()));
Value pos = jsonAtom["cartesianCoordinates"]["value"];
Vector3 position(pos.get(Json::Value::ArrayIndex(0), 0.0).asDouble(),
pos.get(Json::Value::ArrayIndex(1), 0.0).asDouble(),
pos.get(Json::Value::ArrayIndex(2), 0.0).asDouble());
string units = jsonAtom["cartesianCoordinates"]["units"].asString();
if (units == "bohr")
position *= BOHR_TO_ANGSTROM_D;
a.setPosition3d(position);
}
}
// Perceive bonds for the molecule.
molecule.perceiveBondsSimple();
// Now to see if there was a vibrational frequencies calculation.
if (!calculationVib.isNull() && calculationVib.isObject()) {
Value normalModes = calculationVib["calculationResults"]["normalModes"];
if (!normalModes.isNull() && normalModes.isArray()) {
Array<double> frequencies;
Array<double> intensities;
Array< Array<Vector3> > Lx;
for (size_t i = 0; i < normalModes.size(); ++i) {
Value mode = normalModes.get(i, "");
frequencies.push_back(mode["normalModeFrequency"]["value"].asDouble());
intensities.push_back(mode["normalModeInfraRedIntensity"]["value"].asDouble());
Value lx = mode["normalModeVector"]["value"];
if (!lx.empty() && lx.isArray()) {
Array<Vector3> modeLx;
modeLx.resize(lx.size() / 3);
for (size_t k = 0; k < lx.size(); ++k)
modeLx[k / 3][k % 3] = lx.get(k, 0).asDouble();
Lx.push_back(modeLx);
}
}
molecule.setVibrationFrequencies(frequencies);
molecule.setVibrationIntensities(intensities);
molecule.setVibrationLx(Lx);
}
}
return true;
}
bool NWChemJson::write(std::ostream &file, const Molecule &molecule)
{
return false;
}
vector<std::string> NWChemJson::fileExtensions() const
{
vector<std::string> ext;
ext.push_back("json");
ext.push_back("nwjson");
return ext;
}
vector<std::string> NWChemJson::mimeTypes() const
{
vector<std::string> mime;
mime.push_back("chemical/x-nwjson");
return mime;
}
} // end QuantumIO namespace
} // end Avogadro namespace
<commit_msg>NWChem JSON file electronic structure support<commit_after>/******************************************************************************
This source file is part of the Avogadro project.
Copyright 2015 Kitware, Inc.
This source code is released under the New BSD License, (the "License").
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
******************************************************************************/
#include "nwchemjson.h"
#include <avogadro/core/crystaltools.h>
#include <avogadro/core/elements.h>
#include <avogadro/core/gaussianset.h>
#include <avogadro/core/molecule.h>
#include <avogadro/core/unitcell.h>
#include <avogadro/core/utilities.h>
#include <jsoncpp.cpp>
#include <iostream>
namespace Avogadro {
namespace QuantumIO {
using std::string;
using std::vector;
using std::cout;
using std::endl;
using Json::Value;
using Json::Reader;
using Json::StyledStreamWriter;
using Core::Array;
using Core::Atom;
using Core::BasisSet;
using Core::Bond;
using Core::CrystalTools;
using Core::Elements;
using Core::GaussianSet;
using Core::Molecule;
using Core::Variant;
using Core::split;
NWChemJson::NWChemJson()
{
}
NWChemJson::~NWChemJson()
{
}
bool NWChemJson::read(std::istream &file, Molecule &molecule)
{
Value root;
Reader reader;
bool ok = reader.parse(file, root);
if (!ok) {
appendError("Error parsing JSON: " + reader.getFormatedErrorMessages());
return false;
}
if (!root.isObject()) {
appendError("Error: Input is not a JSON object.");
return false;
}
Value simulation = root["simulation"];
if (simulation.empty()) {
appendError("Error: no \"simulation\" key found.");
return false;
}
// Scan the calculations array for calculationSetup.molecule objects.
Value calculations = simulation["calculations"];
if (calculations.empty() || !calculations.isArray()) {
appendError("Error: no \"calculations\" array found.");
return false;
}
// Iterate through the objects in the array, and print out any molecules.
Value moleculeArray(Json::arrayValue);
Value basisSetArray(Json::arrayValue);
Value calculationVib;
Value molecularOrbitals;
int numberOfElectrons = 0;
for (size_t i = 0; i < calculations.size(); ++i) {
Value calcObj = calculations.get(i, "");
if (calcObj.isObject()) {
string calcType = calcObj["calculationType"].asString();
// Store the last vibrational frequencies calculation object.
if (calcType == "vibrationalModes")
calculationVib = calcObj;
Value calcSetup = calcObj["calculationSetup"];
Value calcMol = calcSetup["molecule"];
numberOfElectrons = calcSetup["numberOfElectrons"].asInt();
if (!calcMol.isNull() && calcMol.isObject())
moleculeArray.append(calcMol);
Value basisSet = calcSetup["basisSet"];
if (!basisSet.isNull() && basisSet.isObject())
basisSetArray.append(basisSet);
Value calcResults = calcObj["calculationResults"];
calcMol = calcResults["molecule"];
if (!calcMol.isNull() && calcMol.isObject())
moleculeArray.append(calcMol);
// There is currently one id for all, just get the last one we find.
if (!calcResults["molecularOrbitals"].isNull()
&& calcResults["molecularOrbitals"].isObject())
molecularOrbitals = calcResults["molecularOrbitals"];
}
}
// For now, we are just grabbing the "last" molecule, and using that. This
// needs more complex logic to step through the file and do it properly.
Value finalMol = moleculeArray.get(moleculeArray.size() - 1, 0);
Value atoms = finalMol["atoms"];
if (atoms.isArray()) {
for (size_t i = 0; i < atoms.size(); ++i) {
Value jsonAtom = atoms.get(i, 0);
if (jsonAtom.isNull() || !jsonAtom.isObject())
continue;
Atom a =
molecule.addAtom(static_cast<unsigned char>(jsonAtom["elementNumber"]
.asInt()));
Value pos = jsonAtom["cartesianCoordinates"]["value"];
Vector3 position(pos.get(Json::Value::ArrayIndex(0), 0.0).asDouble(),
pos.get(Json::Value::ArrayIndex(1), 0.0).asDouble(),
pos.get(Json::Value::ArrayIndex(2), 0.0).asDouble());
string units = jsonAtom["cartesianCoordinates"]["units"].asString();
if (units == "bohr")
position *= BOHR_TO_ANGSTROM_D;
a.setPosition3d(position);
}
}
// Perceive bonds for the molecule.
molecule.perceiveBondsSimple();
// Add in the electronic structure information if available.
if (molecularOrbitals.isObject()
&& molecularOrbitals["atomicOrbitalDescriptions"].isArray()) {
Value basisSet = basisSetArray.get(basisSetArray.size() - 1, 0);
Value orbDesc = molecularOrbitals["atomicOrbitalDescriptions"];
// Figure out the mapping of basis set to molecular orbitals.
Array<int> atomNumber;
Array<string> atomSymbol;
for (size_t i = 0; i < orbDesc.size(); ++i) {
string desc = orbDesc.get(i, 0).asString();
vector<string> parts = split(desc, ' ');
assert(parts.size() == 3);
int num = Core::lexicalCast<int>(parts[0]);
if (atomNumber.size() > 0 && atomNumber.back() == num)
continue;
atomNumber.push_back(num);
atomSymbol.push_back(parts[1]);
}
// Now create the structure, and expand out the orbitals.
GaussianSet *basis = new GaussianSet;
basis->setMolecule(&molecule);
for (size_t i = 0; i < atomSymbol.size(); ++i) {
string symbol = atomSymbol[i];
Value basisFunctions = basisSet["basisFunctions"];
Value currentFunction;
for (size_t j = 0; j < basisFunctions.size(); ++j) {
currentFunction = basisFunctions.get(j, 0);
if (currentFunction["elementType"].asString() == symbol)
break;
currentFunction = Json::nullValue;
}
if (currentFunction.isNull())
break;
Value contraction = currentFunction["basisSetContraction"];
for (size_t j = 0; j < contraction.size(); ++j) {
Value contractionShell = contraction.get(j, Json::nullValue);
string shellType = contractionShell["basisSetShell"].asString();
Value exponent = contractionShell["basisSetExponent"];
Value coefficient = contractionShell["basisSetCoefficient"];
assert(exponent.size() == coefficient.size());
GaussianSet::orbital type = GaussianSet::UU;
if (shellType == "s")
type = GaussianSet::S;
else if (shellType == "p")
type = GaussianSet::P;
else if (shellType =="d")
type = GaussianSet::D;
if (type != GaussianSet::UU) {
int b = basis->addBasis(i, type);
for (size_t k = 0; k < exponent.size(); ++k) {
basis->addGto(b, coefficient.get(k, 0).asDouble(),
exponent.get(k, 0).asDouble());
}
}
}
}
// Now to add the molecular orbital coefficients.
Value moCoeffs = molecularOrbitals["molecularOrbital"];
vector<double> coeffArray;
for (size_t i = 0; i < moCoeffs.size(); ++i) {
Value coeff = moCoeffs.get(i, Json::nullValue)["moCoefficients"];
for (size_t j = 0; j < coeff.size(); ++j)
coeffArray.push_back(coeff.get(j, 0).asDouble());
}
basis->setMolecularOrbitals(coeffArray);
basis->setElectronCount(numberOfElectrons);
molecule.setBasisSet(basis);
}
// Now to see if there was a vibrational frequencies calculation.
if (!calculationVib.isNull() && calculationVib.isObject()) {
Value normalModes = calculationVib["calculationResults"]["normalModes"];
if (!normalModes.isNull() && normalModes.isArray()) {
Array<double> frequencies;
Array<double> intensities;
Array< Array<Vector3> > Lx;
for (size_t i = 0; i < normalModes.size(); ++i) {
Value mode = normalModes.get(i, "");
frequencies.push_back(mode["normalModeFrequency"]["value"].asDouble());
intensities.push_back(mode["normalModeInfraRedIntensity"]["value"].asDouble());
Value lx = mode["normalModeVector"]["value"];
if (!lx.empty() && lx.isArray()) {
Array<Vector3> modeLx;
modeLx.resize(lx.size() / 3);
for (size_t k = 0; k < lx.size(); ++k)
modeLx[k / 3][k % 3] = lx.get(k, 0).asDouble();
Lx.push_back(modeLx);
}
}
molecule.setVibrationFrequencies(frequencies);
molecule.setVibrationIntensities(intensities);
molecule.setVibrationLx(Lx);
}
}
return true;
}
bool NWChemJson::write(std::ostream &file, const Molecule &molecule)
{
return false;
}
vector<std::string> NWChemJson::fileExtensions() const
{
vector<std::string> ext;
ext.push_back("json");
ext.push_back("nwjson");
return ext;
}
vector<std::string> NWChemJson::mimeTypes() const
{
vector<std::string> mime;
mime.push_back("chemical/x-nwjson");
return mime;
}
} // end QuantumIO namespace
} // end Avogadro namespace
<|endoftext|> |
<commit_before>#include <algorithm>
#include <iostream>
#include <fstream>
#include <cstring>
#include <string>
#include <vector>
#include <list>
#include <map>
#include <unistd.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <pwd.h>
#include <dirent.h>
#include "dinit-util.h"
#include "service-constants.h"
#include "load-service.h"
#include "options-processing.h"
// dinitcheck: utility to check Dinit configuration for correctness/lint
using string = std::string;
using string_iterator = std::string::iterator;
// prelim_dep: A preliminary (unresolved) service dependency
class prelim_dep
{
public:
std::string name;
dependency_type dep_type;
prelim_dep(const std::string &name_p, dependency_type dep_type_p)
: name(name_p), dep_type(dep_type_p) { }
prelim_dep(std::string &&name_p, dependency_type dep_type_p)
: name(std::move(name_p)), dep_type(dep_type_p) { }
};
class service_record
{
public:
service_record(std::string name_p, std::list<prelim_dep> dependencies_p)
: name(name_p), dependencies(dependencies_p) {}
std::string name;
std::list<prelim_dep> dependencies;
bool visited = false; // flag used to detect cyclic dependencies
bool cycle_free = false;
};
using service_set_t = std::map<std::string, service_record *>;
service_record *load_service(service_set_t &services, const std::string &name,
const service_dir_pathlist &service_dirs);
// Add some missing standard library functionality...
template <typename T> bool contains(std::vector<T> vec, const T& elem)
{
return std::find(vec.begin(), vec.end(), elem) != vec.end();
}
static bool errors_found = false;
int main(int argc, char **argv)
{
using namespace std;
service_dir_opt service_dir_opts;
bool am_system_init = (getuid() == 0);
std::vector<std::string> services_to_check;
// Process command line
if (argc > 1) {
for (int i = 1; i < argc; i++) {
if (argv[i][0] == '-') {
// An option...
if (strcmp(argv[i], "--services-dir") == 0 || strcmp(argv[i], "-d") == 0) {
if (++i < argc) {
service_dir_opts.set_specified_service_dir(argv[i]);
}
else {
cerr << "dinitcheck: '--services-dir' (-d) requires an argument" << endl;
return 1;
}
}
else if (strcmp(argv[i], "--help")) {
cout << "dinitcheck: check dinit service descriptions\n"
" --help display help\n"
" --services-dir <dir>, -d <dir>\n"
" set base directory for service description\n"
" files\n"
" <service-name> check service with name <service-name>\n";
return EXIT_SUCCESS;
}
else {
std::cerr << "dinitcheck: Unrecognized option: '" << argv[i] << "' (use '--help' for help)\n";
return EXIT_FAILURE;
}
}
else {
services_to_check.push_back(argv[i]);
}
}
}
service_dir_opts.build_paths(am_system_init);
if (services_to_check.empty()) {
services_to_check.push_back("boot");
}
size_t num_services_to_check = services_to_check.size();
// Load named service(s)
// - load the service, store dependencies as strings
// - recurse
std::map<std::string, service_record *> service_set;
for (size_t i = 0; i < services_to_check.size(); ++i) {
const std::string &name = services_to_check[i];
std::cout << "Checking service: " << name << "...\n";
try {
service_record *sr = load_service(service_set, name, service_dir_opts.get_paths());
service_set[name] = sr;
// add dependencies to services_to_check
for (auto &dep : sr->dependencies) {
if (service_set.count(dep.name) == 0 && !contains(services_to_check, dep.name)) {
services_to_check.push_back(dep.name);
}
}
}
catch (service_load_exc &exc) {
std::cerr << "Unable to load service '" << name << "': " << exc.exc_description << "\n";
errors_found = true;
}
}
// Check for circular dependencies
std::vector<std::tuple<service_record *, size_t>> service_chain;
for (size_t i = 0; i < num_services_to_check; ++i) {
service_record *root = service_set[services_to_check[i]];
if (root->visited) continue;
// invariant: service_chain is empty
service_chain.emplace_back(root, 0);
// Depth first traversal. If we find a link (dependency) on a service already visited (but not
// marked as cycle-free), we know then that we've found a cycle.
while (true) {
auto n = service_chain.size() - 1;
auto &last = service_chain[n];
service_record *last_record = std::get<0>(last);
size_t &index = std::get<1>(last);
if (index >= last_record->dependencies.size()) {
// Processed all dependencies, go back up:
last_record->cycle_free = true;
service_chain.pop_back();
if (n == 0) break;
size_t &prev_index = std::get<1>(service_chain[n - 1]);
++prev_index;
continue;
}
// Down the tree:
auto dep_it = std::next(last_record->dependencies.begin(), index);
service_record *next_link = service_set[dep_it->name];
if (next_link == nullptr) {
++index;
continue;
}
if (next_link->visited) {
if (! next_link->cycle_free) {
// We've found a cycle. Clear entries before the beginning of the cycle, then
// exit the loop.
auto first = std::find_if(service_chain.begin(), service_chain.end(),
[next_link](std::tuple<service_record *, size_t> &a) -> bool {
return std::get<0>(a) == next_link;
});
service_chain.erase(service_chain.begin(), first);
break;
}
}
next_link->visited = true;
service_chain.emplace_back(next_link, 0);
}
// Report only one cycle; otherwise difficult to avoid reporting duplicates or overlapping
// cycles.
if (!service_chain.empty()) break;
}
if (!service_chain.empty()) {
errors_found = true;
std::cerr << "Found dependency cycle:\n";
for (auto chain_link : service_chain) {
std::cerr << " " << std::get<0>(chain_link)->name << " ->\n";
}
std::cerr << " " << std::get<0>(service_chain[0])->name << ".\n";
}
// TODO additional: check chain-to, other lint
if (! errors_found) {
std::cout << "No problems found.\n";
}
else {
std::cout << "One or more errors found.\n";
}
return errors_found ? EXIT_FAILURE : EXIT_SUCCESS;
}
static void report_service_description_exc(service_description_exc &exc)
{
std::cerr << "Service '" << exc.service_name << "': " << exc.exc_description << "\n";
errors_found = true;
}
static void report_error(std::system_error &exc, const std::string &service_name)
{
std::cerr << "Service '" << service_name << "', error reading service description: " << exc.what() << "\n";
errors_found = true;
}
static void report_dir_error(const char *service_name, const std::string &dirpath)
{
std::cerr << "Service '" << service_name << "', error reading dependencies from directory " << dirpath
<< ": " << strerror(errno) << "\n";
errors_found = true;
}
// Process a dependency directory - filenames contained within correspond to service names which
// are loaded and added as a dependency of the given type. Expected use is with a directory
// containing symbolic links to other service descriptions, but this isn't required.
// Failure to read the directory contents, or to find a service listed within, is not considered
// a fatal error.
static void process_dep_dir(const char *servicename,
const string &service_filename,
std::list<prelim_dep> &deplist, const std::string &depdirpath,
dependency_type dep_type)
{
std::string depdir_fname = combine_paths(parent_path(service_filename), depdirpath.c_str());
DIR *depdir = opendir(depdir_fname.c_str());
if (depdir == nullptr) {
report_dir_error(servicename, depdirpath);
return;
}
errno = 0;
dirent * dent = readdir(depdir);
while (dent != nullptr) {
char * name = dent->d_name;
if (name[0] != '.') {
deplist.emplace_back(name, dep_type);
}
dent = readdir(depdir);
}
if (errno != 0) {
report_dir_error(servicename, depdirpath);
}
closedir(depdir);
}
service_record *load_service(service_set_t &services, const std::string &name,
const service_dir_pathlist &service_dirs)
{
using namespace std;
using namespace dinit_load;
auto found = services.find(name);
if (found != services.end()) {
return found->second;
}
string service_filename;
ifstream service_file;
// Couldn't find one. Have to load it.
for (auto &service_dir : service_dirs) {
service_filename = service_dir.get_dir();
if (*(service_filename.rbegin()) != '/') {
service_filename += '/';
}
service_filename += name;
service_file.open(service_filename.c_str(), ios::in);
if (service_file) break;
}
if (! service_file) {
throw service_not_found(string(name));
}
service_settings_wrapper<prelim_dep> settings;
string line;
service_file.exceptions(ios::badbit);
try {
process_service_file(name, service_file,
[&](string &line, string &setting, string_iterator &i, string_iterator &end) -> void {
auto process_dep_dir_n = [&](std::list<prelim_dep> &deplist, const std::string &waitsford,
dependency_type dep_type) -> void {
process_dep_dir(name.c_str(), service_filename, deplist, waitsford, dep_type);
};
auto load_service_n = [&](const string &dep_name) -> const string & {
return dep_name;
};
try {
process_service_line(settings, name.c_str(), line, setting, i, end, load_service_n, process_dep_dir_n);
}
catch (service_description_exc &exc) {
report_service_description_exc(exc);
}
});
}
catch (std::system_error &sys_err)
{
report_error(sys_err, name);
return nullptr;
}
return new service_record(name, settings.depends);
}
<commit_msg>Fix --help option in dinitcheck<commit_after>#include <algorithm>
#include <iostream>
#include <fstream>
#include <cstring>
#include <string>
#include <vector>
#include <list>
#include <map>
#include <unistd.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <pwd.h>
#include <dirent.h>
#include "dinit-util.h"
#include "service-constants.h"
#include "load-service.h"
#include "options-processing.h"
// dinitcheck: utility to check Dinit configuration for correctness/lint
using string = std::string;
using string_iterator = std::string::iterator;
// prelim_dep: A preliminary (unresolved) service dependency
class prelim_dep
{
public:
std::string name;
dependency_type dep_type;
prelim_dep(const std::string &name_p, dependency_type dep_type_p)
: name(name_p), dep_type(dep_type_p) { }
prelim_dep(std::string &&name_p, dependency_type dep_type_p)
: name(std::move(name_p)), dep_type(dep_type_p) { }
};
class service_record
{
public:
service_record(std::string name_p, std::list<prelim_dep> dependencies_p)
: name(name_p), dependencies(dependencies_p) {}
std::string name;
std::list<prelim_dep> dependencies;
bool visited = false; // flag used to detect cyclic dependencies
bool cycle_free = false;
};
using service_set_t = std::map<std::string, service_record *>;
service_record *load_service(service_set_t &services, const std::string &name,
const service_dir_pathlist &service_dirs);
// Add some missing standard library functionality...
template <typename T> bool contains(std::vector<T> vec, const T& elem)
{
return std::find(vec.begin(), vec.end(), elem) != vec.end();
}
static bool errors_found = false;
int main(int argc, char **argv)
{
using namespace std;
service_dir_opt service_dir_opts;
bool am_system_init = (getuid() == 0);
std::vector<std::string> services_to_check;
// Process command line
if (argc > 1) {
for (int i = 1; i < argc; i++) {
if (argv[i][0] == '-') {
// An option...
if (strcmp(argv[i], "--services-dir") == 0 || strcmp(argv[i], "-d") == 0) {
if (++i < argc) {
service_dir_opts.set_specified_service_dir(argv[i]);
}
else {
cerr << "dinitcheck: '--services-dir' (-d) requires an argument" << endl;
return 1;
}
}
else if (strcmp(argv[i], "--help") == 0) {
cout << "dinitcheck: check dinit service descriptions\n"
" --help display help\n"
" --services-dir <dir>, -d <dir>\n"
" set base directory for service description\n"
" files\n"
" <service-name> check service with name <service-name>\n";
return EXIT_SUCCESS;
}
else {
std::cerr << "dinitcheck: Unrecognized option: '" << argv[i] << "' (use '--help' for help)\n";
return EXIT_FAILURE;
}
}
else {
services_to_check.push_back(argv[i]);
}
}
}
service_dir_opts.build_paths(am_system_init);
if (services_to_check.empty()) {
services_to_check.push_back("boot");
}
size_t num_services_to_check = services_to_check.size();
// Load named service(s)
// - load the service, store dependencies as strings
// - recurse
std::map<std::string, service_record *> service_set;
for (size_t i = 0; i < services_to_check.size(); ++i) {
const std::string &name = services_to_check[i];
std::cout << "Checking service: " << name << "...\n";
try {
service_record *sr = load_service(service_set, name, service_dir_opts.get_paths());
service_set[name] = sr;
// add dependencies to services_to_check
for (auto &dep : sr->dependencies) {
if (service_set.count(dep.name) == 0 && !contains(services_to_check, dep.name)) {
services_to_check.push_back(dep.name);
}
}
}
catch (service_load_exc &exc) {
std::cerr << "Unable to load service '" << name << "': " << exc.exc_description << "\n";
errors_found = true;
}
}
// Check for circular dependencies
std::vector<std::tuple<service_record *, size_t>> service_chain;
for (size_t i = 0; i < num_services_to_check; ++i) {
service_record *root = service_set[services_to_check[i]];
if (root->visited) continue;
// invariant: service_chain is empty
service_chain.emplace_back(root, 0);
// Depth first traversal. If we find a link (dependency) on a service already visited (but not
// marked as cycle-free), we know then that we've found a cycle.
while (true) {
auto n = service_chain.size() - 1;
auto &last = service_chain[n];
service_record *last_record = std::get<0>(last);
size_t &index = std::get<1>(last);
if (index >= last_record->dependencies.size()) {
// Processed all dependencies, go back up:
last_record->cycle_free = true;
service_chain.pop_back();
if (n == 0) break;
size_t &prev_index = std::get<1>(service_chain[n - 1]);
++prev_index;
continue;
}
// Down the tree:
auto dep_it = std::next(last_record->dependencies.begin(), index);
service_record *next_link = service_set[dep_it->name];
if (next_link == nullptr) {
++index;
continue;
}
if (next_link->visited) {
if (! next_link->cycle_free) {
// We've found a cycle. Clear entries before the beginning of the cycle, then
// exit the loop.
auto first = std::find_if(service_chain.begin(), service_chain.end(),
[next_link](std::tuple<service_record *, size_t> &a) -> bool {
return std::get<0>(a) == next_link;
});
service_chain.erase(service_chain.begin(), first);
break;
}
}
next_link->visited = true;
service_chain.emplace_back(next_link, 0);
}
// Report only one cycle; otherwise difficult to avoid reporting duplicates or overlapping
// cycles.
if (!service_chain.empty()) break;
}
if (!service_chain.empty()) {
errors_found = true;
std::cerr << "Found dependency cycle:\n";
for (auto chain_link : service_chain) {
std::cerr << " " << std::get<0>(chain_link)->name << " ->\n";
}
std::cerr << " " << std::get<0>(service_chain[0])->name << ".\n";
}
// TODO additional: check chain-to, other lint
if (! errors_found) {
std::cout << "No problems found.\n";
}
else {
std::cout << "One or more errors found.\n";
}
return errors_found ? EXIT_FAILURE : EXIT_SUCCESS;
}
static void report_service_description_exc(service_description_exc &exc)
{
std::cerr << "Service '" << exc.service_name << "': " << exc.exc_description << "\n";
errors_found = true;
}
static void report_error(std::system_error &exc, const std::string &service_name)
{
std::cerr << "Service '" << service_name << "', error reading service description: " << exc.what() << "\n";
errors_found = true;
}
static void report_dir_error(const char *service_name, const std::string &dirpath)
{
std::cerr << "Service '" << service_name << "', error reading dependencies from directory " << dirpath
<< ": " << strerror(errno) << "\n";
errors_found = true;
}
// Process a dependency directory - filenames contained within correspond to service names which
// are loaded and added as a dependency of the given type. Expected use is with a directory
// containing symbolic links to other service descriptions, but this isn't required.
// Failure to read the directory contents, or to find a service listed within, is not considered
// a fatal error.
static void process_dep_dir(const char *servicename,
const string &service_filename,
std::list<prelim_dep> &deplist, const std::string &depdirpath,
dependency_type dep_type)
{
std::string depdir_fname = combine_paths(parent_path(service_filename), depdirpath.c_str());
DIR *depdir = opendir(depdir_fname.c_str());
if (depdir == nullptr) {
report_dir_error(servicename, depdirpath);
return;
}
errno = 0;
dirent * dent = readdir(depdir);
while (dent != nullptr) {
char * name = dent->d_name;
if (name[0] != '.') {
deplist.emplace_back(name, dep_type);
}
dent = readdir(depdir);
}
if (errno != 0) {
report_dir_error(servicename, depdirpath);
}
closedir(depdir);
}
service_record *load_service(service_set_t &services, const std::string &name,
const service_dir_pathlist &service_dirs)
{
using namespace std;
using namespace dinit_load;
auto found = services.find(name);
if (found != services.end()) {
return found->second;
}
string service_filename;
ifstream service_file;
// Couldn't find one. Have to load it.
for (auto &service_dir : service_dirs) {
service_filename = service_dir.get_dir();
if (*(service_filename.rbegin()) != '/') {
service_filename += '/';
}
service_filename += name;
service_file.open(service_filename.c_str(), ios::in);
if (service_file) break;
}
if (! service_file) {
throw service_not_found(string(name));
}
service_settings_wrapper<prelim_dep> settings;
string line;
service_file.exceptions(ios::badbit);
try {
process_service_file(name, service_file,
[&](string &line, string &setting, string_iterator &i, string_iterator &end) -> void {
auto process_dep_dir_n = [&](std::list<prelim_dep> &deplist, const std::string &waitsford,
dependency_type dep_type) -> void {
process_dep_dir(name.c_str(), service_filename, deplist, waitsford, dep_type);
};
auto load_service_n = [&](const string &dep_name) -> const string & {
return dep_name;
};
try {
process_service_line(settings, name.c_str(), line, setting, i, end, load_service_n, process_dep_dir_n);
}
catch (service_description_exc &exc) {
report_service_description_exc(exc);
}
});
}
catch (std::system_error &sys_err)
{
report_error(sys_err, name);
return nullptr;
}
return new service_record(name, settings.depends);
}
<|endoftext|> |
<commit_before>/*
* Eos - A 3D Morphable Model fitting library written in modern C++11/14.
*
* File: include/eos/fitting/linear_shape_fitting.hpp
*
* Copyright 2014, 2015 Patrik Huber
*
* 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.
*/
#pragma once
#ifndef LINEARSHAPEFITTING_HPP_
#define LINEARSHAPEFITTING_HPP_
#include "eos/morphablemodel/MorphableModel.hpp"
//#include "Eigen/LU"
#include "opencv2/core/core.hpp"
#include "boost/optional.hpp"
#include <vector>
#include <cassert>
namespace eos {
namespace fitting {
/**
* Fits the shape of a Morphable Model to given 2D landmarks (i.e. estimates the maximum likelihood solution of the shape coefficients) as proposed in [1].
* It's a linear, closed-form solution fitting of the shape, with regularisation (prior towards the mean).
*
* [1] O. Aldrian & W. Smith, Inverse Rendering of Faces with a 3D Morphable Model, PAMI 2013.
*
* Note: Using less than the maximum number of coefficients to fit is not thoroughly tested yet and may contain an error.
* Note: Returns coefficients following standard normal distribution (i.e. all have similar magnitude). Why? Because we fit using the normalised basis?
* Note: The standard deviations given should be a vector, i.e. different for each landmark. This is not implemented yet.
*
* @param[in] morphable_model The Morphable Model whose shape (coefficients) are estimated.
* @param[in] affine_camera_matrix A 3x4 affine camera matrix from model to screen-space (should probably be of type CV_32FC1 as all our calculations are done with float).
* @param[in] landmarks 2D landmarks from an image to fit the model to.
* @param[in] vertex_ids The vertex ids in the model that correspond to the 2D points.
* @param[in] base_face The base or reference face from where the fitting is started. Usually this would be the models mean face, which is what will be used if the parameter is not explicitly specified.
* @param[in] lambda The regularisation parameter (weight of the prior towards the mean).
* @param[in] num_coefficients_to_fit How many shape-coefficients to fit (all others will stay 0). Not tested thoroughly.
* @param[in] detector_standard_deviation The standard deviation of the 2D landmarks given (e.g. of the detector used), in pixels.
* @param[in] model_standard_deviation The standard deviation of the 3D vertex points in the 3D model, projected to 2D (so the value is in pixels).
* @return The estimated shape-coefficients (alphas).
*/
inline std::vector<float> fit_shape_to_landmarks_linear(morphablemodel::MorphableModel morphable_model, cv::Mat affine_camera_matrix, std::vector<cv::Vec2f> landmarks, std::vector<int> vertex_ids, cv::Mat base_face=cv::Mat(), float lambda=3.0f, boost::optional<int> num_coefficients_to_fit=boost::optional<int>(), boost::optional<float> detector_standard_deviation=boost::optional<float>(), boost::optional<float> model_standard_deviation=boost::optional<float>())
{
using cv::Mat;
assert(landmarks.size() == vertex_ids.size());
int num_coeffs_to_fit = num_coefficients_to_fit.get_value_or(morphable_model.get_shape_model().get_num_principal_components());
int num_landmarks = static_cast<int>(landmarks.size());
if (base_face.empty())
{
base_face = morphable_model.get_shape_model().get_mean();
}
// $\hat{V} \in R^{3N\times m-1}$, subselect the rows of the eigenvector matrix $V$ associated with the $N$ feature points
// And we insert a row of zeros after every third row, resulting in matrix $\hat{V}_h \in R^{4N\times m-1}$:
Mat V_hat_h = Mat::zeros(4 * num_landmarks, num_coeffs_to_fit, CV_32FC1);
int row_index = 0;
for (int i = 0; i < num_landmarks; ++i) {
Mat basis_rows = morphable_model.get_shape_model().get_normalised_pca_basis(vertex_ids[i]); // In the paper, the not-normalised basis might be used? I'm not sure, check it. It's even a mess in the paper. PH 26.5.2014: I think the normalised basis is fine/better.
//basisRows.copyTo(V_hat_h.rowRange(rowIndex, rowIndex + 3));
basis_rows.colRange(0, num_coeffs_to_fit).copyTo(V_hat_h.rowRange(row_index, row_index + 3));
row_index += 4; // replace 3 rows and skip the 4th one, it has all zeros
}
// Form a block diagonal matrix $P \in R^{3N\times 4N}$ in which the camera matrix C (P_Affine, affine_camera_matrix) is placed on the diagonal:
Mat P = Mat::zeros(3 * num_landmarks, 4 * num_landmarks, CV_32FC1);
for (int i = 0; i < num_landmarks; ++i) {
Mat submatrix_to_replace = P.colRange(4 * i, (4 * i) + 4).rowRange(3 * i, (3 * i) + 3);
affine_camera_matrix.copyTo(submatrix_to_replace);
}
// The variances: Add the 2D and 3D standard deviations.
// If the user doesn't provide them, we choose the following:
// 2D (detector) standard deviation: In pixel, we follow [1] and choose sqrt(3) as the default value.
// 3D (model) variance: 0.0f. It only makes sense to set it to something when we have a different variance for different vertices.
// The 3D variance has to be projected to 2D (for details, see paper [1]) so the units do match up.
float sigma_squared_2D = std::pow(detector_standard_deviation.get_value_or(std::sqrt(3.0f)), 2) + std::pow(model_standard_deviation.get_value_or(0.0f), 2);
Mat Sigma = Mat::zeros(3 * num_landmarks, 3 * num_landmarks, CV_32FC1);
for (int i = 0; i < 3 * num_landmarks; ++i) {
Sigma.at<float>(i, i) = 1.0f / std::sqrt(sigma_squared_2D); // the higher the sigma_squared_2D, the smaller the diagonal entries of Sigma will be
}
Mat Omega = Sigma.t() * Sigma; // just squares the diagonal
// The landmarks in matrix notation (in homogeneous coordinates), $3N\times 1$
Mat y = Mat::ones(3 * num_landmarks, 1, CV_32FC1);
for (int i = 0; i < num_landmarks; ++i) {
y.at<float>(3 * i, 0) = landmarks[i][0];
y.at<float>((3 * i) + 1, 0) = landmarks[i][1];
//y.at<float>((3 * i) + 2, 0) = 1; // already 1, stays (homogeneous coordinate)
}
// The mean, with an added homogeneous coordinate (x_1, y_1, z_1, 1, x_2, ...)^t
Mat v_bar = Mat::ones(4 * num_landmarks, 1, CV_32FC1);
for (int i = 0; i < num_landmarks; ++i) {
//cv::Vec4f model_mean = morphable_model.get_shape_model().get_mean_at_point(vertex_ids[i]);
cv::Vec4f model_mean(base_face.at<float>(vertex_ids[i] * 3), base_face.at<float>(vertex_ids[i] * 3 + 1), base_face.at<float>(vertex_ids[i] * 3 + 2), 1.0f);
v_bar.at<float>(4 * i, 0) = model_mean[0];
v_bar.at<float>((4 * i) + 1, 0) = model_mean[1];
v_bar.at<float>((4 * i) + 2, 0) = model_mean[2];
//v_bar.at<float>((4 * i) + 3, 0) = 1; // already 1, stays (homogeneous coordinate)
// note: now that a Vec4f is returned, we could use copyTo?
}
// Bring into standard regularised quadratic form with diagonal distance matrix Omega
Mat A = P * V_hat_h; // camera matrix times the basis
Mat b = P * v_bar - y; // camera matrix times the mean, minus the landmarks.
//Mat c_s; // The x, we solve for this! (the variance-normalised shape parameter vector, $c_s = [a_1/sigma_{s,1} , ..., a_m-1/sigma_{s,m-1}]^t$
//int numShapePc = morphableModel.getShapeModel().getNumberOfPrincipalComponents();
const int num_shape_pc = num_coeffs_to_fit;
Mat AtOmegaA = A.t() * Omega * A;
Mat AtOmegaAReg = AtOmegaA + lambda * Mat::eye(num_shape_pc, num_shape_pc, CV_32FC1);
// Invert (and perform some sanity checks) using Eigen:
/* using RowMajorMatrixXf = Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
Eigen::Map<RowMajorMatrixXf> AtOmegaAReg_Eigen(AtOmegaAReg.ptr<float>(), AtOmegaAReg.rows, AtOmegaAReg.cols);
Eigen::FullPivLU<RowMajorMatrixXf> luOfAtOmegaAReg(AtOmegaAReg_Eigen); // Calculate the full-pivoting LU decomposition of the regularized AtA. Note: We could also try FullPivHouseholderQR if our system is non-minimal (i.e. there are more constraints than unknowns).
auto rankOfAtOmegaAReg = luOfAtOmegaAReg.rank();
bool isAtOmegaARegInvertible = luOfAtOmegaAReg.isInvertible();
float threshold = std::abs(luOfAtOmegaAReg.maxPivot()) * luOfAtOmegaAReg.threshold(); // originaly "2 * ..." but I commented it out
RowMajorMatrixXf AtARegInv_EigenFullLU = luOfAtOmegaAReg.inverse(); // Note: We should use ::solve() instead
Mat AtOmegaARegInvFullLU(AtARegInv_EigenFullLU.rows(), AtARegInv_EigenFullLU.cols(), CV_32FC1, AtARegInv_EigenFullLU.data()); // create an OpenCV Mat header for the Eigen data
*/
// Solve using OpenCV:
Mat c_s; // Note/Todo: We get coefficients ~ N(0, sigma) I think. They are not multiplied with the eigenvalues.
bool non_singular = cv::solve(AtOmegaAReg, -A.t() * Omega.t() * b, c_s, cv::DECOMP_SVD); // DECOMP_SVD calculates the pseudo-inverse if the matrix is not invertible.
// Because we're using SVD, non_singular will always be true. If we were to use e.g. Cholesky, we could return an expected<T>.
return std::vector<float>(c_s);
};
} /* namespace fitting */
} /* namespace eos */
#endif /* LINEARSHAPEFITTING_HPP_ */
<commit_msg>Minor documentation update<commit_after>/*
* Eos - A 3D Morphable Model fitting library written in modern C++11/14.
*
* File: include/eos/fitting/linear_shape_fitting.hpp
*
* Copyright 2014, 2015 Patrik Huber
*
* 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.
*/
#pragma once
#ifndef LINEARSHAPEFITTING_HPP_
#define LINEARSHAPEFITTING_HPP_
#include "eos/morphablemodel/MorphableModel.hpp"
//#include "Eigen/LU"
#include "opencv2/core/core.hpp"
#include "boost/optional.hpp"
#include <vector>
#include <cassert>
namespace eos {
namespace fitting {
/**
* Fits the shape of a Morphable Model to given 2D landmarks (i.e. estimates the maximum likelihood solution of the shape coefficients) as proposed in [1].
* It's a linear, closed-form solution fitting of the shape, with regularisation (prior towards the mean).
*
* [1] O. Aldrian & W. Smith, Inverse Rendering of Faces with a 3D Morphable Model, PAMI 2013.
*
* Note: Using less than the maximum number of coefficients to fit is not thoroughly tested yet and may contain an error.
* Note: Returns coefficients following standard normal distribution (i.e. all have similar magnitude). Why? Because we fit using the normalised basis?
* Note: The standard deviations given should be a vector, i.e. different for each landmark. This is not implemented yet.
*
* @param[in] morphable_model The Morphable Model whose shape (coefficients) are estimated.
* @param[in] affine_camera_matrix A 3x4 affine camera matrix from model to screen-space (should probably be of type CV_32FC1 as all our calculations are done with float).
* @param[in] landmarks 2D landmarks from an image to fit the model to.
* @param[in] vertex_ids The vertex ids in the model that correspond to the 2D points.
* @param[in] base_face The base or reference face from where the fitting is started. Usually this would be the models mean face, which is what will be used if the parameter is not explicitly specified.
* @param[in] lambda The regularisation parameter (weight of the prior towards the mean).
* @param[in] num_coefficients_to_fit How many shape-coefficients to fit (all others will stay 0). Should be bigger than zero, or boost::none to fit all coefficients.
* @param[in] detector_standard_deviation The standard deviation of the 2D landmarks given (e.g. of the detector used), in pixels.
* @param[in] model_standard_deviation The standard deviation of the 3D vertex points in the 3D model, projected to 2D (so the value is in pixels).
* @return The estimated shape-coefficients (alphas).
*/
inline std::vector<float> fit_shape_to_landmarks_linear(morphablemodel::MorphableModel morphable_model, cv::Mat affine_camera_matrix, std::vector<cv::Vec2f> landmarks, std::vector<int> vertex_ids, cv::Mat base_face=cv::Mat(), float lambda=3.0f, boost::optional<int> num_coefficients_to_fit=boost::optional<int>(), boost::optional<float> detector_standard_deviation=boost::optional<float>(), boost::optional<float> model_standard_deviation=boost::optional<float>())
{
using cv::Mat;
assert(landmarks.size() == vertex_ids.size());
int num_coeffs_to_fit = num_coefficients_to_fit.get_value_or(morphable_model.get_shape_model().get_num_principal_components());
int num_landmarks = static_cast<int>(landmarks.size());
if (base_face.empty())
{
base_face = morphable_model.get_shape_model().get_mean();
}
// $\hat{V} \in R^{3N\times m-1}$, subselect the rows of the eigenvector matrix $V$ associated with the $N$ feature points
// And we insert a row of zeros after every third row, resulting in matrix $\hat{V}_h \in R^{4N\times m-1}$:
Mat V_hat_h = Mat::zeros(4 * num_landmarks, num_coeffs_to_fit, CV_32FC1);
int row_index = 0;
for (int i = 0; i < num_landmarks; ++i) {
Mat basis_rows = morphable_model.get_shape_model().get_normalised_pca_basis(vertex_ids[i]); // In the paper, the not-normalised basis might be used? I'm not sure, check it. It's even a mess in the paper. PH 26.5.2014: I think the normalised basis is fine/better.
//basisRows.copyTo(V_hat_h.rowRange(rowIndex, rowIndex + 3));
basis_rows.colRange(0, num_coeffs_to_fit).copyTo(V_hat_h.rowRange(row_index, row_index + 3));
row_index += 4; // replace 3 rows and skip the 4th one, it has all zeros
}
// Form a block diagonal matrix $P \in R^{3N\times 4N}$ in which the camera matrix C (P_Affine, affine_camera_matrix) is placed on the diagonal:
Mat P = Mat::zeros(3 * num_landmarks, 4 * num_landmarks, CV_32FC1);
for (int i = 0; i < num_landmarks; ++i) {
Mat submatrix_to_replace = P.colRange(4 * i, (4 * i) + 4).rowRange(3 * i, (3 * i) + 3);
affine_camera_matrix.copyTo(submatrix_to_replace);
}
// The variances: Add the 2D and 3D standard deviations.
// If the user doesn't provide them, we choose the following:
// 2D (detector) standard deviation: In pixel, we follow [1] and choose sqrt(3) as the default value.
// 3D (model) variance: 0.0f. It only makes sense to set it to something when we have a different variance for different vertices.
// The 3D variance has to be projected to 2D (for details, see paper [1]) so the units do match up.
float sigma_squared_2D = std::pow(detector_standard_deviation.get_value_or(std::sqrt(3.0f)), 2) + std::pow(model_standard_deviation.get_value_or(0.0f), 2);
Mat Sigma = Mat::zeros(3 * num_landmarks, 3 * num_landmarks, CV_32FC1);
for (int i = 0; i < 3 * num_landmarks; ++i) {
Sigma.at<float>(i, i) = 1.0f / std::sqrt(sigma_squared_2D); // the higher the sigma_squared_2D, the smaller the diagonal entries of Sigma will be
}
Mat Omega = Sigma.t() * Sigma; // just squares the diagonal
// The landmarks in matrix notation (in homogeneous coordinates), $3N\times 1$
Mat y = Mat::ones(3 * num_landmarks, 1, CV_32FC1);
for (int i = 0; i < num_landmarks; ++i) {
y.at<float>(3 * i, 0) = landmarks[i][0];
y.at<float>((3 * i) + 1, 0) = landmarks[i][1];
//y.at<float>((3 * i) + 2, 0) = 1; // already 1, stays (homogeneous coordinate)
}
// The mean, with an added homogeneous coordinate (x_1, y_1, z_1, 1, x_2, ...)^t
Mat v_bar = Mat::ones(4 * num_landmarks, 1, CV_32FC1);
for (int i = 0; i < num_landmarks; ++i) {
//cv::Vec4f model_mean = morphable_model.get_shape_model().get_mean_at_point(vertex_ids[i]);
cv::Vec4f model_mean(base_face.at<float>(vertex_ids[i] * 3), base_face.at<float>(vertex_ids[i] * 3 + 1), base_face.at<float>(vertex_ids[i] * 3 + 2), 1.0f);
v_bar.at<float>(4 * i, 0) = model_mean[0];
v_bar.at<float>((4 * i) + 1, 0) = model_mean[1];
v_bar.at<float>((4 * i) + 2, 0) = model_mean[2];
//v_bar.at<float>((4 * i) + 3, 0) = 1; // already 1, stays (homogeneous coordinate)
// note: now that a Vec4f is returned, we could use copyTo?
}
// Bring into standard regularised quadratic form with diagonal distance matrix Omega
Mat A = P * V_hat_h; // camera matrix times the basis
Mat b = P * v_bar - y; // camera matrix times the mean, minus the landmarks.
//Mat c_s; // The x, we solve for this! (the variance-normalised shape parameter vector, $c_s = [a_1/sigma_{s,1} , ..., a_m-1/sigma_{s,m-1}]^t$
//int numShapePc = morphableModel.getShapeModel().getNumberOfPrincipalComponents();
const int num_shape_pc = num_coeffs_to_fit;
Mat AtOmegaA = A.t() * Omega * A;
Mat AtOmegaAReg = AtOmegaA + lambda * Mat::eye(num_shape_pc, num_shape_pc, CV_32FC1);
// Invert (and perform some sanity checks) using Eigen:
/* using RowMajorMatrixXf = Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
Eigen::Map<RowMajorMatrixXf> AtOmegaAReg_Eigen(AtOmegaAReg.ptr<float>(), AtOmegaAReg.rows, AtOmegaAReg.cols);
Eigen::FullPivLU<RowMajorMatrixXf> luOfAtOmegaAReg(AtOmegaAReg_Eigen); // Calculate the full-pivoting LU decomposition of the regularized AtA. Note: We could also try FullPivHouseholderQR if our system is non-minimal (i.e. there are more constraints than unknowns).
auto rankOfAtOmegaAReg = luOfAtOmegaAReg.rank();
bool isAtOmegaARegInvertible = luOfAtOmegaAReg.isInvertible();
float threshold = std::abs(luOfAtOmegaAReg.maxPivot()) * luOfAtOmegaAReg.threshold(); // originaly "2 * ..." but I commented it out
RowMajorMatrixXf AtARegInv_EigenFullLU = luOfAtOmegaAReg.inverse(); // Note: We should use ::solve() instead
Mat AtOmegaARegInvFullLU(AtARegInv_EigenFullLU.rows(), AtARegInv_EigenFullLU.cols(), CV_32FC1, AtARegInv_EigenFullLU.data()); // create an OpenCV Mat header for the Eigen data
*/
// Solve using OpenCV:
Mat c_s; // Note/Todo: We get coefficients ~ N(0, sigma) I think. They are not multiplied with the eigenvalues.
bool non_singular = cv::solve(AtOmegaAReg, -A.t() * Omega.t() * b, c_s, cv::DECOMP_SVD); // DECOMP_SVD calculates the pseudo-inverse if the matrix is not invertible.
// Because we're using SVD, non_singular will always be true. If we were to use e.g. Cholesky, we could return an expected<T>.
return std::vector<float>(c_s);
};
} /* namespace fitting */
} /* namespace eos */
#endif /* LINEARSHAPEFITTING_HPP_ */
<|endoftext|> |
<commit_before>// The MIT License (MIT)
//
// Copyright (c) 2014 Siyuan Ren (netheril96@gmail.com)
//
// 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 AUTOJSONCXX_MAP_TYPES_HPP_29A4C106C1B1
#define AUTOJSONCXX_MAP_TYPES_HPP_29A4C106C1B1
#include <autojsoncxx/utility.hpp>
#include <autojsoncxx/base.hpp>
#include <autojsoncxx/error.hpp>
#include <map>
#if AUTOJSONCXX_HAS_MODERN_TYPES
#include <unordered_map>
#endif
namespace autojsoncxx {
template <class ElementType, class Derived>
class MapBaseSAXEventHandler {
private:
std::string key;
ElementType value;
SAXEventHandler<ElementType> internal_handler;
utility::scoped_ptr<error::ErrorBase> the_error;
std::stack<signed char> state;
// A stack of StartArray() and StartObject() event
// must be recorded, so we know when the current
// element has been fully parsed, and needs to be
// pushed back into the container
bool emplace_when_time_is_right()
{
if (state.size() == 1 && state.top() == internal::OBJECT) {
if (!static_cast<Derived*>(this)->Emplace(key, AUTOJSONCXX_MOVE_IF_NOEXCEPT(value))) {
the_error.reset(new error::DuplicateKeyError(AUTOJSONCXX_MOVE(key)));
return false;
}
value = ElementType();
internal_handler.PrepareForReuse();
}
return true;
}
bool check_depth(const char* type)
{
if (state.empty()) {
the_error.reset(new error::TypeMismatchError("object", type));
return false;
}
return true;
}
bool checked_event_forwarding(bool success)
{
if (success)
return emplace_when_time_is_right();
set_member_error();
return false;
}
void set_member_error()
{
this->the_error.reset(new error::ObjectMemberError(key));
}
public:
explicit MapBaseSAXEventHandler()
: key()
, value()
, internal_handler(&value)
{
}
bool Null()
{
return check_depth("null") && checked_event_forwarding(internal_handler.Null());
}
bool Bool(bool b)
{
return check_depth("bool") && checked_event_forwarding(internal_handler.Bool(b));
}
bool Int(int i)
{
return check_depth("int") && checked_event_forwarding(internal_handler.Int(i));
}
bool Uint(unsigned i)
{
return check_depth("unsigned") && checked_event_forwarding(internal_handler.Uint(i));
}
bool Int64(int64_t i)
{
return check_depth("int64_t") && checked_event_forwarding(internal_handler.Int64(i));
}
bool Uint64(uint64_t i)
{
return check_depth("uint64_t") && checked_event_forwarding(internal_handler.Uint64(i));
}
bool Double(double d)
{
return check_depth("double") && checked_event_forwarding(internal_handler.Double(d));
}
bool String(const char* str, SizeType length, bool copy)
{
return check_depth("string") && checked_event_forwarding(internal_handler.String(str, length, copy));
}
bool Key(const char* str, SizeType length, bool copy)
{
if (state.size() > 1)
return checked_event_forwarding(internal_handler.Key(str, length, copy));
key.assign(str, length);
return true;
}
bool StartArray()
{
state.push(internal::ARRAY);
return check_depth("array") && checked_event_forwarding(internal_handler.StartArray());
}
bool EndArray(SizeType length)
{
assert(state.top() == internal::ARRAY);
state.pop();
return check_depth("array") && checked_event_forwarding(internal_handler.EndArray(length));
}
bool StartObject()
{
state.push(internal::OBJECT);
if (state.size() > 1)
return checked_event_forwarding(internal_handler.StartObject());
return true;
}
bool EndObject(SizeType length)
{
assert(state.top() == internal::OBJECT);
state.pop();
if (!state.empty())
return checked_event_forwarding(internal_handler.EndObject(length));
return true;
}
bool HasError() const
{
return !this->the_error.empty();
}
bool ReapError(error::ErrorStack& errs)
{
if (this->the_error.empty())
return false;
errs.push(this->the_error.release());
internal_handler.ReapError(errs);
return true;
}
void PrepareForReuse()
{
std::stack<signed char>().swap(state);
}
};
template <class Writer, class MapType, class ElementType, class ConstIteratorType>
struct MapSerializer {
void operator()(Writer& w, const MapType& map) const
{
w.StartObject();
for (ConstIteratorType it = map.begin(), end = map.end(); it != end; ++it) {
w.Key(it->first.data(), static_cast<SizeType>(it->first.size()));
Serializer<Writer, ElementType>()(w, it->second);
}
w.EndObject();
}
};
template <class ElementType, class Compare, class Allocator>
class SAXEventHandler<std::map<std::string, ElementType, Compare, Allocator> >
: public MapBaseSAXEventHandler<ElementType,
SAXEventHandler<std::map<std::string,
ElementType, Compare, Allocator> > > {
private:
typedef std::map<std::string, ElementType, Compare, Allocator> map_type;
map_type* m_value;
public:
explicit SAXEventHandler(map_type* v)
: m_value(v)
{
}
bool Emplace(const std::string& key, const ElementType& value)
{
return m_value->insert(std::make_pair(key, value)).second;
}
#if AUTOJSONCXX_HAS_RVALUE
bool Emplace(const std::string& key, ElementType&& value)
{
return m_value->insert(std::make_pair(AUTOJSONCXX_MOVE(key), AUTOJSONCXX_MOVE(value))).second;
}
#endif
};
template <class Writer, class ElementType, class Compare, class Allocator>
struct Serializer<Writer, std::map<std::string, ElementType, Compare, Allocator> >
: public MapSerializer<Writer, std::map<std::string, ElementType, Compare, Allocator>,
ElementType, typename std::map<std::string, ElementType, Compare, Allocator>::const_iterator> {
};
template <class ElementType, class Compare, class Allocator>
class SAXEventHandler<std::multimap<std::string, ElementType, Compare, Allocator> >
: public MapBaseSAXEventHandler<ElementType,
SAXEventHandler<std::multimap<std::string,
ElementType, Compare, Allocator> > > {
private:
typedef std::multimap<std::string, ElementType, Compare, Allocator> map_type;
map_type* m_value;
public:
explicit SAXEventHandler(map_type* v)
: m_value(v)
{
}
bool Emplace(const std::string& key, const ElementType& value)
{
return m_value->insert(std::make_pair(key, value)).second;
}
#if AUTOJSONCXX_HAS_RVALUE
bool Emplace(const std::string& key, ElementType&& value)
{
return m_value->insert(std::make_pair(AUTOJSONCXX_MOVE(key), AUTOJSONCXX_MOVE(value))).second;
}
#endif
};
template <class Writer, class ElementType, class Compare, class Allocator>
struct Serializer<Writer, std::multimap<std::string, ElementType, Compare, Allocator> >
: public MapSerializer<Writer, std::multimap<std::string, ElementType, Compare, Allocator>,
ElementType, typename std::multimap<std::string, ElementType, Compare, Allocator>::const_iterator> {
};
#if AUTOJSONCXX_HAS_MODERN_TYPES
template <class ElementType, class Hash, class Equal, class Allocator>
class SAXEventHandler<std::unordered_map<std::string, ElementType, Hash, Equal, Allocator> >
: public MapBaseSAXEventHandler<ElementType,
SAXEventHandler<std::unordered_map<std::string, ElementType, Hash, Equal, Allocator> > > {
private:
typedef std::unordered_map<std::string, ElementType, Hash, Equal, Allocator> map_type;
map_type* m_value;
public:
explicit SAXEventHandler(map_type* v)
: m_value(v)
{
}
bool Emplace(const std::string& key, const ElementType& value)
{
return m_value->insert(std::make_pair(key, value)).second;
}
#if AUTOJSONCXX_HAS_RVALUE
bool Emplace(const std::string& key, ElementType&& value)
{
return m_value->insert(std::make_pair(AUTOJSONCXX_MOVE(key), AUTOJSONCXX_MOVE(value))).second;
}
#endif
};
template <class Writer, class ElementType, class Hash, class Equal, class Allocator>
struct Serializer<Writer, std::unordered_map<std::string, ElementType, Hash, Equal, Allocator> >
: public MapSerializer<Writer, std::unordered_map<std::string, ElementType, Hash, Equal, Allocator>, ElementType, typename std::unordered_map<std::string, ElementType, Hash, Equal, Allocator>::const_iterator> {
};
template <class ElementType, class Hash, class Equal, class Allocator>
class SAXEventHandler<std::unordered_multimap<std::string, ElementType, Hash, Equal, Allocator> >
: public MapBaseSAXEventHandler<ElementType,
SAXEventHandler<std::unordered_multimap<std::string, ElementType, Hash, Equal, Allocator> > > {
private:
typedef std::unordered_multimap<std::string, ElementType, Hash, Equal, Allocator> map_type;
map_type* m_value;
public:
explicit SAXEventHandler(map_type* v)
: m_value(v)
{
}
bool Emplace(const std::string& key, const ElementType& value)
{
return m_value->insert(std::make_pair(key, value)).second;
}
#if AUTOJSONCXX_HAS_RVALUE
bool Emplace(const std::string& key, ElementType&& value)
{
return m_value->insert(std::make_pair(AUTOJSONCXX_MOVE(key), AUTOJSONCXX_MOVE(value))).second;
}
#endif
};
template <class Writer, class ElementType, class Hash, class Equal, class Allocator>
struct Serializer<Writer, std::unordered_multimap<std::string, ElementType, Hash, Equal, Allocator> >
: public MapSerializer<Writer, std::unordered_multimap<std::string, ElementType, Hash, Equal, Allocator>, ElementType, typename std::unordered_multimap<std::string, ElementType, Hash, Equal, Allocator>::const_iterator> {
};
#endif
}
#endif
<commit_msg>Fix detection of mismatch between array and map<commit_after>// The MIT License (MIT)
//
// Copyright (c) 2014 Siyuan Ren (netheril96@gmail.com)
//
// 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 AUTOJSONCXX_MAP_TYPES_HPP_29A4C106C1B1
#define AUTOJSONCXX_MAP_TYPES_HPP_29A4C106C1B1
#include <autojsoncxx/utility.hpp>
#include <autojsoncxx/base.hpp>
#include <autojsoncxx/error.hpp>
#include <map>
#if AUTOJSONCXX_HAS_MODERN_TYPES
#include <unordered_map>
#endif
namespace autojsoncxx {
template <class ElementType, class Derived>
class MapBaseSAXEventHandler {
private:
std::string key;
ElementType value;
SAXEventHandler<ElementType> internal_handler;
utility::scoped_ptr<error::ErrorBase> the_error;
std::stack<signed char> state;
// A stack of StartArray() and StartObject() event
// must be recorded, so we know when the current
// element has been fully parsed, and needs to be
// pushed back into the container
bool emplace_when_time_is_right()
{
if (state.size() == 1 && state.top() == internal::OBJECT) {
if (!static_cast<Derived*>(this)->Emplace(key, AUTOJSONCXX_MOVE_IF_NOEXCEPT(value))) {
the_error.reset(new error::DuplicateKeyError(AUTOJSONCXX_MOVE(key)));
return false;
}
value = ElementType();
internal_handler.PrepareForReuse();
}
return true;
}
bool check_depth(const char* type)
{
if (state.empty()) {
the_error.reset(new error::TypeMismatchError("object", type));
return false;
}
return true;
}
bool checked_event_forwarding(bool success)
{
if (success)
return emplace_when_time_is_right();
set_member_error();
return false;
}
void set_member_error()
{
this->the_error.reset(new error::ObjectMemberError(key));
}
public:
explicit MapBaseSAXEventHandler()
: key()
, value()
, internal_handler(&value)
{
}
bool Null()
{
return check_depth("null") && checked_event_forwarding(internal_handler.Null());
}
bool Bool(bool b)
{
return check_depth("bool") && checked_event_forwarding(internal_handler.Bool(b));
}
bool Int(int i)
{
return check_depth("int") && checked_event_forwarding(internal_handler.Int(i));
}
bool Uint(unsigned i)
{
return check_depth("unsigned") && checked_event_forwarding(internal_handler.Uint(i));
}
bool Int64(int64_t i)
{
return check_depth("int64_t") && checked_event_forwarding(internal_handler.Int64(i));
}
bool Uint64(uint64_t i)
{
return check_depth("uint64_t") && checked_event_forwarding(internal_handler.Uint64(i));
}
bool Double(double d)
{
return check_depth("double") && checked_event_forwarding(internal_handler.Double(d));
}
bool String(const char* str, SizeType length, bool copy)
{
return check_depth("string") && checked_event_forwarding(internal_handler.String(str, length, copy));
}
bool Key(const char* str, SizeType length, bool copy)
{
if (state.size() > 1)
return checked_event_forwarding(internal_handler.Key(str, length, copy));
key.assign(str, length);
return true;
}
bool StartArray()
{
if (!check_depth("array"))
return false;
state.push(internal::ARRAY);
return checked_event_forwarding(internal_handler.StartArray());
}
bool EndArray(SizeType length)
{
assert(state.top() == internal::ARRAY);
state.pop();
return check_depth("array") && checked_event_forwarding(internal_handler.EndArray(length));
}
bool StartObject()
{
state.push(internal::OBJECT);
if (state.size() > 1)
return checked_event_forwarding(internal_handler.StartObject());
return true;
}
bool EndObject(SizeType length)
{
assert(state.top() == internal::OBJECT);
state.pop();
if (!state.empty())
return checked_event_forwarding(internal_handler.EndObject(length));
return true;
}
bool HasError() const
{
return !this->the_error.empty();
}
bool ReapError(error::ErrorStack& errs)
{
if (this->the_error.empty())
return false;
errs.push(this->the_error.release());
internal_handler.ReapError(errs);
return true;
}
void PrepareForReuse()
{
std::stack<signed char>().swap(state);
}
};
template <class Writer, class MapType, class ElementType, class ConstIteratorType>
struct MapSerializer {
void operator()(Writer& w, const MapType& map) const
{
w.StartObject();
for (ConstIteratorType it = map.begin(), end = map.end(); it != end; ++it) {
w.Key(it->first.data(), static_cast<SizeType>(it->first.size()));
Serializer<Writer, ElementType>()(w, it->second);
}
w.EndObject();
}
};
template <class ElementType, class Compare, class Allocator>
class SAXEventHandler<std::map<std::string, ElementType, Compare, Allocator> >
: public MapBaseSAXEventHandler<ElementType,
SAXEventHandler<std::map<std::string,
ElementType, Compare, Allocator> > > {
private:
typedef std::map<std::string, ElementType, Compare, Allocator> map_type;
map_type* m_value;
public:
explicit SAXEventHandler(map_type* v)
: m_value(v)
{
}
bool Emplace(const std::string& key, const ElementType& value)
{
return m_value->insert(std::make_pair(key, value)).second;
}
#if AUTOJSONCXX_HAS_RVALUE
bool Emplace(const std::string& key, ElementType&& value)
{
return m_value->insert(std::make_pair(AUTOJSONCXX_MOVE(key), AUTOJSONCXX_MOVE(value))).second;
}
#endif
};
template <class Writer, class ElementType, class Compare, class Allocator>
struct Serializer<Writer, std::map<std::string, ElementType, Compare, Allocator> >
: public MapSerializer<Writer, std::map<std::string, ElementType, Compare, Allocator>,
ElementType, typename std::map<std::string, ElementType, Compare, Allocator>::const_iterator> {
};
template <class ElementType, class Compare, class Allocator>
class SAXEventHandler<std::multimap<std::string, ElementType, Compare, Allocator> >
: public MapBaseSAXEventHandler<ElementType,
SAXEventHandler<std::multimap<std::string,
ElementType, Compare, Allocator> > > {
private:
typedef std::multimap<std::string, ElementType, Compare, Allocator> map_type;
map_type* m_value;
public:
explicit SAXEventHandler(map_type* v)
: m_value(v)
{
}
bool Emplace(const std::string& key, const ElementType& value)
{
return m_value->insert(std::make_pair(key, value)).second;
}
#if AUTOJSONCXX_HAS_RVALUE
bool Emplace(const std::string& key, ElementType&& value)
{
return m_value->insert(std::make_pair(AUTOJSONCXX_MOVE(key), AUTOJSONCXX_MOVE(value))).second;
}
#endif
};
template <class Writer, class ElementType, class Compare, class Allocator>
struct Serializer<Writer, std::multimap<std::string, ElementType, Compare, Allocator> >
: public MapSerializer<Writer, std::multimap<std::string, ElementType, Compare, Allocator>,
ElementType, typename std::multimap<std::string, ElementType, Compare, Allocator>::const_iterator> {
};
#if AUTOJSONCXX_HAS_MODERN_TYPES
template <class ElementType, class Hash, class Equal, class Allocator>
class SAXEventHandler<std::unordered_map<std::string, ElementType, Hash, Equal, Allocator> >
: public MapBaseSAXEventHandler<ElementType,
SAXEventHandler<std::unordered_map<std::string, ElementType, Hash, Equal, Allocator> > > {
private:
typedef std::unordered_map<std::string, ElementType, Hash, Equal, Allocator> map_type;
map_type* m_value;
public:
explicit SAXEventHandler(map_type* v)
: m_value(v)
{
}
bool Emplace(const std::string& key, const ElementType& value)
{
return m_value->insert(std::make_pair(key, value)).second;
}
#if AUTOJSONCXX_HAS_RVALUE
bool Emplace(const std::string& key, ElementType&& value)
{
return m_value->insert(std::make_pair(AUTOJSONCXX_MOVE(key), AUTOJSONCXX_MOVE(value))).second;
}
#endif
};
template <class Writer, class ElementType, class Hash, class Equal, class Allocator>
struct Serializer<Writer, std::unordered_map<std::string, ElementType, Hash, Equal, Allocator> >
: public MapSerializer<Writer, std::unordered_map<std::string, ElementType, Hash, Equal, Allocator>, ElementType, typename std::unordered_map<std::string, ElementType, Hash, Equal, Allocator>::const_iterator> {
};
template <class ElementType, class Hash, class Equal, class Allocator>
class SAXEventHandler<std::unordered_multimap<std::string, ElementType, Hash, Equal, Allocator> >
: public MapBaseSAXEventHandler<ElementType,
SAXEventHandler<std::unordered_multimap<std::string, ElementType, Hash, Equal, Allocator> > > {
private:
typedef std::unordered_multimap<std::string, ElementType, Hash, Equal, Allocator> map_type;
map_type* m_value;
public:
explicit SAXEventHandler(map_type* v)
: m_value(v)
{
}
bool Emplace(const std::string& key, const ElementType& value)
{
return m_value->insert(std::make_pair(key, value)).second;
}
#if AUTOJSONCXX_HAS_RVALUE
bool Emplace(const std::string& key, ElementType&& value)
{
return m_value->insert(std::make_pair(AUTOJSONCXX_MOVE(key), AUTOJSONCXX_MOVE(value))).second;
}
#endif
};
template <class Writer, class ElementType, class Hash, class Equal, class Allocator>
struct Serializer<Writer, std::unordered_multimap<std::string, ElementType, Hash, Equal, Allocator> >
: public MapSerializer<Writer, std::unordered_multimap<std::string, ElementType, Hash, Equal, Allocator>, ElementType, typename std::unordered_multimap<std::string, ElementType, Hash, Equal, Allocator>::const_iterator> {
};
#endif
}
#endif
<|endoftext|> |
<commit_before>//ibnu.yahya@toroo.org
#include "ign.h"
#include "fs.h"
#include "cmath"
#include <QtCore/QVariant>
#include <qjson/parser.h>
#include <qjson/parserrunnable.h>
#include <qjson/serializer.h>
#include <qjson/serializerrunnable.h>
#include <qjson/qjson_export.h>
#include <qjson/qobjecthelper.h>
#include <iostream>
using namespace std;
ign::ign(QObject *parent)
: QObject(parent)
{
frame = web.page()->mainFrame();
connect(frame,SIGNAL(javaScriptWindowObjectCleared()), SLOT(ignJS()));
this->filesystem = new fs;
this->dl = new QtDownload;
QFile jqueryfile;
QString jquery;
jqueryfile.setFileName(":/js/jquery.js");
if(jqueryfile.open(QIODevice::ReadOnly)){
jquery = jqueryfile.readAll();
frame->evaluateJavaScript(jquery);
}
jqueryfile.close();
QWebSettings::globalSettings()->setAttribute(QWebSettings::PluginsEnabled, true);
web.settings()->setAttribute(QWebSettings::PluginsEnabled, true);
web.settings()->setAttribute(QWebSettings::LocalStorageEnabled, true);
web.settings()->setAttribute(QWebSettings::OfflineStorageDatabaseEnabled, true);
web.settings()->setAttribute(QWebSettings::OfflineWebApplicationCacheEnabled, true);
web.settings()->setAttribute(QWebSettings::JavascriptEnabled,true);
web.settings()->setAttribute(QWebSettings::JavascriptCanOpenWindows,true);
web.settings()->setAttribute(QWebSettings::JavascriptCanAccessClipboard,true);
web.settings()->setAttribute(QWebSettings::JavaEnabled,true);
web.settings()->setAttribute(QWebSettings::AcceleratedCompositingEnabled,true);
web.settings()->setAttribute(QWebSettings::WebGLEnabled,true);
web.settings()->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls,false);
//webstorage
QString home = QDir::homePath();
home += "/.ignsdk";
web.settings()->setLocalStoragePath(home);
web.settings()->enablePersistentStorage(home);
web.settings()->setOfflineWebApplicationCachePath(home);
//stylesheet default
web.settings()->setUserStyleSheetUrl(QUrl("qrc:/css/ign.css"));
//config mode disable
web.page()->action(QWebPage::Back)->setVisible(false);
web.page()->action(QWebPage::Forward)->setVisible(false);
web.page()->action(QWebPage::Reload)->setVisible(false);
web.page()->action(QWebPage::Stop)->setVisible(false);
//set fullscrean mode default to false
fullscreen = false;
//web.setWindowOpacity(0.1);
}
void ign::ignJS(){
this->frame->addToJavaScriptWindowObject("ign",this);
//fs filesystem;
//this->frame->addToJavaScriptWindowObject("fs",filesystem);
}
void ign::getToggleFullScreen(){
if(this->fullscreen){
this->web.showNormal();
this->fullscreen = false;
}
else{
this->web.showFullScreen();
this->fullscreen = true;
}
}
void ign::getFullScreen(bool screen){
if(screen){
this->web.showFullScreen();
this->fullscreen = true;
}
else {
this->web.showNormal();
this->fullscreen = false;
}
}
void ign::render(QString w){
this->web.load(QUrl(w));
}
void ign::show(){
this->web.show();
}
void ign::showMaximized(){
this->web.showMaximized();
}
void ign::showMinimized(){
this->web.showMinimized();
}
void ign::showMessage(const QString &msg)
{
QMessageBox::information(0, "Information", msg);
}
void ign::quit(){
this->web.close();
}
void ign::Back(){
this->web.page()->action(QWebPage::Back)->setVisible(true);
}
void ign::Forward(){
this->web.page()->action(QWebPage::Forward)->setVisible(true);
}
void ign::Stop(){
this->web.page()->action(QWebPage::Stop)->setVisible(true);
}
void ign::Reload(){
this->web.page()->action(QWebPage::Reload)->setVisible(true);
}
void ign::setDev(bool v){
this->web.settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, v);
}
void ign::websecurity(bool c){
web.settings()->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls,c);
}
void ign::WidgetSizeMax(int w, int h){
this->web.setMaximumSize(w,h);
}
void ign::WidgetSizeMin(int w, int h){
this->web.setMinimumSize(w,h);
}
void ign::WidgetSize(int w, int h){
this->web.resize(w,h);
}
void ign::WidgetNoFrame(){
this->web.setWindowFlags(Qt::FramelessWindowHint);
}
void ign::WidgetTransparent(){
QPalette pal = this->web.palette();
pal.setBrush(QPalette::Base, Qt::transparent);
this->web.setPalette(pal);
this->web.setAttribute(Qt::WA_OpaquePaintEvent, false);
this->web.setAttribute(Qt::WA_TranslucentBackground, true);
}
QString ign::cliOut(const QString& cli){
QProcess os;
os.start(cli);
os.waitForFinished(-1);
return os.readAllStandardOutput();
}
void ign::mousePressEvent(QMouseEvent *event)
{
qDebug()<<event->type();
}
void ign::config(QString path){
QFile config_file;
QDir::setCurrent(path);
config_file.setFileName("ignsdk.json");
QByteArray config;
if(config_file.open(QIODevice::ReadOnly)){
config = config_file.readAll();
QJson::Parser parse;
bool ok;
QVariantMap result = parse.parse(config, &ok).toMap();
if (!ok) {
qFatal("An error occurred during parsing");
exit (1);
}
QVariantMap configure = result["config"].toMap();
if(configure["debug"].toBool()){
this->setDev(true);
}
if(configure["websecurity"].toBool()){
this->websecurity(true);
}
QVariantMap window = result["window"].toMap();
if(window["transparent"].toBool()){
this->WidgetTransparent();
}
if(window["noframe"].toBool()){
this->WidgetNoFrame();
}
if(window["fullscreen"].toBool()){
this->getToggleFullScreen();
}
if(window["width"].toInt() != 0){
if(window["height"].toInt() != 0){
this->WidgetSize(window["width"].toInt(),window["height"].toInt());
}
}
foreach (QVariant button, result["button"].toList()) {
if (button.toString() == "back"){
this->Back();
}
if (button.toString() == "forward"){
this->Forward();
}
if (button.toString() == "stop"){
this->Stop();
}
if (button.toString() == "reload"){
this->Reload();
}
}
}
config_file.close();
}
QString ign::hash(const QString &data,QString hash_func){
QByteArray hash;
QByteArray byteArray = data.toLatin1();
if(hash_func == "md4"){
hash=QCryptographicHash::hash(byteArray,QCryptographicHash::Md4);
}
else if(hash_func == "md5"){
hash=QCryptographicHash::hash(byteArray,QCryptographicHash::Md5);
}
else if(hash_func == "sha1"){
hash=QCryptographicHash::hash(byteArray,QCryptographicHash::Sha1);
}
return hash.toHex();
}
QString ign::homePath(){
return this->filesystem->home_path();
}
void ign::saveFile(const QByteArray &data, QString filename, QString path){
QByteArray byteArray = QByteArray::fromBase64(data);
QString home;
home = path+"/"+filename;
QFile localFile(home);
if (!localFile.open(QIODevice::WriteOnly))
return;
localFile.write(byteArray);
localFile.close();
}
void ign::download(QString data,QString path,QString id){
this->dl = new QtDownload;
this->id = id;
this->dl->setTarget(data);
this->dl->save(path);
this->dl->download();
connect(this->dl, SIGNAL(download_signal(qint64,qint64)), this, SLOT(download_signal(qint64,qint64)));
}
void ign::download_signal(qint64 recieved, qint64 total){
QString r = QString::number(recieved);
QString t = QString::number(total);
float pr = (r.toFloat()/t.toFloat())*100;
qDebug() << recieved << total << pr;
QString prs = QString::number(pr,'g',5);
qDebug() << prs;
QString idx = this->id;
frame->evaluateJavaScript("document.getElementById('"+idx+"').setAttribute('style','width : "+prs+"%')");
}
/*void ign::mousePressEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
{
QMessageBox::information(0, "Information", "press");
mMoving = true;
mLastMousePosition = event->pos();
}
}
void ign::mouseMoveEvent(QMouseEvent *event)
{
if( event->buttons().testFlag(Qt::LeftButton) && mMoving)
{
this->web.move(this->web.pos() + (event->pos() - mLastMousePosition));
mLastMousePosition = event->pos();
}
}
void ign::mouseReleaseEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
{
mMoving = false;
}
}*/
<commit_msg>CLEAN: downlader<commit_after>//ibnu.yahya@toroo.org
#include "ign.h"
#include "fs.h"
#include "cmath"
#include <QtCore/QVariant>
#include <qjson/parser.h>
#include <qjson/parserrunnable.h>
#include <qjson/serializer.h>
#include <qjson/serializerrunnable.h>
#include <qjson/qjson_export.h>
#include <qjson/qobjecthelper.h>
#include <iostream>
using namespace std;
ign::ign(QObject *parent)
: QObject(parent)
{
frame = web.page()->mainFrame();
connect(frame,SIGNAL(javaScriptWindowObjectCleared()), SLOT(ignJS()));
this->filesystem = new fs;
this->dl = new QtDownload;
QFile jqueryfile;
QString jquery;
jqueryfile.setFileName(":/js/jquery.js");
if(jqueryfile.open(QIODevice::ReadOnly)){
jquery = jqueryfile.readAll();
frame->evaluateJavaScript(jquery);
}
jqueryfile.close();
QWebSettings::globalSettings()->setAttribute(QWebSettings::PluginsEnabled, true);
web.settings()->setAttribute(QWebSettings::PluginsEnabled, true);
web.settings()->setAttribute(QWebSettings::LocalStorageEnabled, true);
web.settings()->setAttribute(QWebSettings::OfflineStorageDatabaseEnabled, true);
web.settings()->setAttribute(QWebSettings::OfflineWebApplicationCacheEnabled, true);
web.settings()->setAttribute(QWebSettings::JavascriptEnabled,true);
web.settings()->setAttribute(QWebSettings::JavascriptCanOpenWindows,true);
web.settings()->setAttribute(QWebSettings::JavascriptCanAccessClipboard,true);
web.settings()->setAttribute(QWebSettings::JavaEnabled,true);
web.settings()->setAttribute(QWebSettings::AcceleratedCompositingEnabled,true);
web.settings()->setAttribute(QWebSettings::WebGLEnabled,true);
web.settings()->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls,false);
//webstorage
QString home = QDir::homePath();
home += "/.ignsdk";
web.settings()->setLocalStoragePath(home);
web.settings()->enablePersistentStorage(home);
web.settings()->setOfflineWebApplicationCachePath(home);
//stylesheet default
web.settings()->setUserStyleSheetUrl(QUrl("qrc:/css/ign.css"));
//config mode disable
web.page()->action(QWebPage::Back)->setVisible(false);
web.page()->action(QWebPage::Forward)->setVisible(false);
web.page()->action(QWebPage::Reload)->setVisible(false);
web.page()->action(QWebPage::Stop)->setVisible(false);
//set fullscrean mode default to false
fullscreen = false;
//web.setWindowOpacity(0.1);
}
void ign::ignJS(){
this->frame->addToJavaScriptWindowObject("ign",this);
//fs filesystem;
//this->frame->addToJavaScriptWindowObject("fs",filesystem);
}
void ign::getToggleFullScreen(){
if(this->fullscreen){
this->web.showNormal();
this->fullscreen = false;
}
else{
this->web.showFullScreen();
this->fullscreen = true;
}
}
void ign::getFullScreen(bool screen){
if(screen){
this->web.showFullScreen();
this->fullscreen = true;
}
else {
this->web.showNormal();
this->fullscreen = false;
}
}
void ign::render(QString w){
this->web.load(QUrl(w));
}
void ign::show(){
this->web.show();
}
void ign::showMaximized(){
this->web.showMaximized();
}
void ign::showMinimized(){
this->web.showMinimized();
}
void ign::showMessage(const QString &msg)
{
QMessageBox::information(0, "Information", msg);
}
void ign::quit(){
this->web.close();
}
void ign::Back(){
this->web.page()->action(QWebPage::Back)->setVisible(true);
}
void ign::Forward(){
this->web.page()->action(QWebPage::Forward)->setVisible(true);
}
void ign::Stop(){
this->web.page()->action(QWebPage::Stop)->setVisible(true);
}
void ign::Reload(){
this->web.page()->action(QWebPage::Reload)->setVisible(true);
}
void ign::setDev(bool v){
this->web.settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, v);
}
void ign::websecurity(bool c){
web.settings()->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls,c);
}
void ign::WidgetSizeMax(int w, int h){
this->web.setMaximumSize(w,h);
}
void ign::WidgetSizeMin(int w, int h){
this->web.setMinimumSize(w,h);
}
void ign::WidgetSize(int w, int h){
this->web.resize(w,h);
}
void ign::WidgetNoFrame(){
this->web.setWindowFlags(Qt::FramelessWindowHint);
}
void ign::WidgetTransparent(){
QPalette pal = this->web.palette();
pal.setBrush(QPalette::Base, Qt::transparent);
this->web.setPalette(pal);
this->web.setAttribute(Qt::WA_OpaquePaintEvent, false);
this->web.setAttribute(Qt::WA_TranslucentBackground, true);
}
QString ign::cliOut(const QString& cli){
QProcess os;
os.start(cli);
os.waitForFinished(-1);
return os.readAllStandardOutput();
}
void ign::mousePressEvent(QMouseEvent *event)
{
qDebug()<<event->type();
}
void ign::config(QString path){
QFile config_file;
QDir::setCurrent(path);
config_file.setFileName("ignsdk.json");
QByteArray config;
if(config_file.open(QIODevice::ReadOnly)){
config = config_file.readAll();
QJson::Parser parse;
bool ok;
QVariantMap result = parse.parse(config, &ok).toMap();
if (!ok) {
qFatal("An error occurred during parsing");
exit (1);
}
QVariantMap configure = result["config"].toMap();
if(configure["debug"].toBool()){
this->setDev(true);
}
if(configure["websecurity"].toBool()){
this->websecurity(true);
}
QVariantMap window = result["window"].toMap();
if(window["transparent"].toBool()){
this->WidgetTransparent();
}
if(window["noframe"].toBool()){
this->WidgetNoFrame();
}
if(window["fullscreen"].toBool()){
this->getToggleFullScreen();
}
if(window["width"].toInt() != 0){
if(window["height"].toInt() != 0){
this->WidgetSize(window["width"].toInt(),window["height"].toInt());
}
}
foreach (QVariant button, result["button"].toList()) {
if (button.toString() == "back"){
this->Back();
}
if (button.toString() == "forward"){
this->Forward();
}
if (button.toString() == "stop"){
this->Stop();
}
if (button.toString() == "reload"){
this->Reload();
}
}
}
config_file.close();
}
QString ign::hash(const QString &data,QString hash_func){
QByteArray hash;
QByteArray byteArray = data.toLatin1();
if(hash_func == "md4"){
hash=QCryptographicHash::hash(byteArray,QCryptographicHash::Md4);
}
else if(hash_func == "md5"){
hash=QCryptographicHash::hash(byteArray,QCryptographicHash::Md5);
}
else if(hash_func == "sha1"){
hash=QCryptographicHash::hash(byteArray,QCryptographicHash::Sha1);
}
return hash.toHex();
}
QString ign::homePath(){
return this->filesystem->home_path();
}
void ign::saveFile(const QByteArray &data, QString filename, QString path){
QByteArray byteArray = QByteArray::fromBase64(data);
QString home;
home = path+"/"+filename;
QFile localFile(home);
if (!localFile.open(QIODevice::WriteOnly))
return;
localFile.write(byteArray);
localFile.close();
}
void ign::download(QString data,QString path,QString id){
this->dl = new QtDownload;
this->id = id;
this->dl->setTarget(data);
this->dl->save(path);
this->dl->download();
connect(this->dl, SIGNAL(download_signal(qint64,qint64)), this, SLOT(download_signal(qint64,qint64)));
}
void ign::download_signal(qint64 recieved, qint64 total){
QString r = QString::number(recieved);
QString t = QString::number(total);
float pr = (r.toFloat()/t.toFloat())*100;
QString prs = QString::number(pr,'g',5);
qDebug() << prs;
QString idx = this->id;
frame->evaluateJavaScript("document.getElementById('"+idx+"').setAttribute('style','width : "+prs+"%')");
}
/*void ign::mousePressEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
{
QMessageBox::information(0, "Information", "press");
mMoving = true;
mLastMousePosition = event->pos();
}
}
void ign::mouseMoveEvent(QMouseEvent *event)
{
if( event->buttons().testFlag(Qt::LeftButton) && mMoving)
{
this->web.move(this->web.pos() + (event->pos() - mLastMousePosition));
mLastMousePosition = event->pos();
}
}
void ign::mouseReleaseEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
{
mMoving = false;
}
}*/
<|endoftext|> |
<commit_before>// Copyright (c) 2013-2018 mogemimi. Distributed under the MIT license.
#pragma once
#include <string>
namespace Pomdog {
struct GamepadCapabilities final {
std::string Name;
int ButtonCount = 0;
int ThumbStickCount = 0;
bool IsConnected = false;
bool HasLeftXThumbStick = false;
bool HasLeftYThumbStick = false;
bool HasRightXThumbStick = false;
bool HasRightYThumbStick = false;
};
} // namespace Pomdog
<commit_msg>Remove IsConnected from GamepadCapabilities class in favour of GamepadState::IsConnected<commit_after>// Copyright (c) 2013-2018 mogemimi. Distributed under the MIT license.
#pragma once
#include <string>
namespace Pomdog {
struct GamepadCapabilities final {
std::string Name;
int ButtonCount = 0;
int ThumbStickCount = 0;
bool HasLeftXThumbStick = false;
bool HasLeftYThumbStick = false;
bool HasRightXThumbStick = false;
bool HasRightYThumbStick = false;
};
} // namespace Pomdog
<|endoftext|> |
<commit_before>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
Bohrium 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 Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <bh.h>
#include <bh_dag.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <boost/foreach.hpp>
#include <boost/graph/topological_sort.hpp>
#include <boost/range/adaptors.hpp>
#include <vector>
#include <map>
#include <iterator>
#include <signal.h>
#include <stdio.h>
#include <sys/time.h>
#define VERBOSE
using namespace std;
using namespace boost;
using namespace bohrium::dag;
/* Help function that fuses the edges in 'edges2explore' where the 'mask' is true */
pair<int64_t,bool> fuse_mask(int64_t best_cost, const vector<EdgeW> &edges2explore,
const GraphDW &graph, const vector<bool> &mask, bh_ir &bhir,
GraphD &dag)
{
bool fusibility=true;
vector<EdgeW> edges2merge;
unsigned int i=0;
BOOST_FOREACH(const EdgeW &e, edges2explore)
{
if(mask[i++])
edges2merge.push_back(e);
}
//Help function to find the new location
struct find_new_location
{
Vertex operator()(const map<Vertex, Vertex> &loc_map, Vertex v)
{
Vertex v_mapped = loc_map.at(v);
if(v_mapped == v)
return v;
else
return (*this)(loc_map, v_mapped);
}
}find_loc;
//'loc_map' maps a vertex before the merge to the corresponding vertex after the merge
map<Vertex, Vertex> loc_map;
BOOST_FOREACH(Vertex v, vertices(dag))
{
loc_map[v] = v;
}
//Lets record the merges into 'loc_map'
BOOST_FOREACH(const EdgeW &e, edges2merge)
{
Vertex v1 = find_loc(loc_map, source(e, graph.bglW()));
Vertex v2 = find_loc(loc_map, target(e, graph.bglW()));
loc_map[v1] = v2;
}
//Pack 'loc_map' such that all keys maps directly to a new vertex thus after
//this point there is no need to call find_loc().
BOOST_FOREACH(Vertex v, vertices(dag))
{
Vertex v_mapped = find_loc(loc_map, loc_map.at(v));
if(v_mapped != v)
loc_map[v] = v_mapped;
}
//Create the new vertices and insert instruction topologically
map<Vertex, bh_ir_kernel> new_vertices;
BOOST_FOREACH(Vertex v, vertices(dag))
{
if(loc_map.at(v) == v)
new_vertices[v] = bh_ir_kernel(bhir);
}
vector<Vertex> topological_order;
topological_sort(dag, back_inserter(topological_order));
BOOST_REVERSE_FOREACH(Vertex vertex, topological_order)
{
Vertex v = loc_map.at(vertex);
bh_ir_kernel &k = new_vertices.at(v);
BOOST_FOREACH(uint64_t idx, dag[vertex].instr_indexes)
{
if(not k.fusible(idx))
fusibility = false;
k.add_instr(idx);
}
}
//TODO: Remove this assert check
BOOST_FOREACH(Vertex v, vertices(dag))
{
if(loc_map.at(v) == v)
assert(new_vertices[v].instr_indexes.size() > 0);
}
//Find the total cost
int64_t cost=0;
BOOST_FOREACH(const bh_ir_kernel &k, new_vertices | adaptors::map_values)
{
cost += k.cost();
}
//Check if we need to continue
if(cost >= best_cost or not fusibility)
return make_pair(cost,false);
//Merge the vertice in the DAG
BOOST_FOREACH(Vertex v, vertices(dag))
{
Vertex loc_v = loc_map.at(v);
if(loc_v == v)
{
dag[v] = new_vertices.at(v);
assert(dag[v].instr_indexes.size() > 0);
}
else//Lets merge 'v' into 'loc_v'
{
BOOST_FOREACH(Vertex a, adjacent_vertices(v, dag))
{
a = loc_map.at(a);
if(a != loc_v)
add_edge(loc_v, a, dag);
}
BOOST_FOREACH(Vertex a, inv_adjacent_vertices(v, dag))
{
a = loc_map.at(a);
if(a != loc_v)
add_edge(a, loc_v, dag);
}
clear_vertex(v, dag);
dag[v] = bh_ir_kernel(bhir);
}
}
//TODO: remove assert check
BOOST_FOREACH(Vertex v, vertices(dag))
{
if(dag[loc_map.at(v)].instr_indexes.size() == 0)
{
cout << v << endl;
cout << loc_map.at(v) << endl;
assert(1 == 2);
}
}
//Check for cycles
if(cycles(dag))
{
return make_pair(cost,false);
}
assert(cost == (int64_t)dag_cost(dag));
return make_pair(cost,true);
}
#ifdef VERBOSE
int fuser_count=0;
#endif
/* Private class to find the optimal solution through branch and bound */
class Solver
{
public:
bh_ir &bhir;
const GraphDW &dag;
const vector<EdgeW> &edges2explore;
int64_t best_cost;
int64_t one_cost;
GraphD best_dag;
#ifdef VERBOSE
double purge_count=0;
uint64_t explore_count=0;
#endif
/* The constructor */
Solver(bh_ir &b, const GraphDW &d, const vector<EdgeW> &e):bhir(b),dag(d),edges2explore(e)
{
//Wwe use the greedy algorithm to find a good initial guess
GraphDW new_dag(dag);
fuse_greedy(new_dag);
best_dag = new_dag.bglD();
best_cost = dag_cost(best_dag);
}
/* Find the optimal solution through branch and bound */
void branch_n_bound(vector<bool> mask, unsigned int offset, bool merge_next)
{
if(not merge_next)
{
GraphD new_dag(dag.bglD());
mask[offset] = merge_next;
bool fusibility;
int64_t cost;
tie(cost, fusibility) = fuse_mask(best_cost, edges2explore, dag, mask, bhir, new_dag);
#ifdef VERBOSE
if(explore_count%1000 == 0)
{
cout << "[" << explore_count << "] " << "purge count: ";
cout << purge_count << " / " << pow(2.0,mask.size()) << endl;
cout << "cost: " << cost << ", best_cost: " << best_cost;
cout << ", fusibility: " << fusibility << endl;
}
++explore_count;
#endif
if(cost >= best_cost)
{
#ifdef VERBOSE
purge_count += pow(2.0, mask.size()-offset-1);
#endif
return;
}
if(fusibility)
{
best_cost = cost;
best_dag = new_dag;
#ifdef VERBOSE
std::stringstream ss;
ss << "new_best_dag-" << fuser_count << "-" << dag_cost(new_dag) << ".dot";
printf("write file: %s\n", ss.str().c_str());
pprint(GraphDW(new_dag), ss.str().c_str());
purge_count += pow(2.0, mask.size()-offset-1);
#endif
return;
}
}
if(offset+1 < mask.size())
{
branch_n_bound(mask, offset+1, false);
branch_n_bound(mask, offset+1, true);
}
}
};
/* Fuse the 'dag' optimally */
void fuse_optimal(bh_ir &bhir, const GraphDW &dag, GraphD &output)
{
//The list of edges that we should try to merge
vector<EdgeW> edges2explore;
BOOST_FOREACH(const EdgeW &e, edges(dag.bglW()))
{
edges2explore.push_back(e);
}
sort_weights(dag.bglW(), edges2explore);
//reverse(edges2explore.begin(), edges2explore.end());
if(edges2explore.size() == 0)
{
return;
}
//First we check the trivial case where all kernels are merged
vector<bool> mask(edges2explore.size(), true);
{
GraphD new_dag(dag.bglD());
bool fuse = fuse_mask(numeric_limits<int64_t>::max(), edges2explore,
dag, mask, bhir, new_dag).second;
if(fuse)
{
output = new_dag;
return;
}
}
Solver solver(bhir, dag, edges2explore);
if(mask.size() > 100)
{
cout << "FUSER-OPTIMAL: ABORT the size of the search space is too large: 2^";
cout << mask.size() << "!" << endl;
}
else
{
cout << "FUSER-OPTIMAL: the size of the search space is 2^" << mask.size() << "!" << endl;
solver.branch_n_bound(mask, 0, false);
solver.branch_n_bound(mask, 0, true);
}
output = solver.best_dag;
}
void timer_handler(int signum)
{
cout << "ABORT! - timeout" << endl;
exit(-1);
}
void set_abort_timer()
{
const char *bh_fuser_timeout = getenv("BH_FUSER_TIMEOUT");
if(bh_fuser_timeout == NULL)
return;
long int timeout = strtol(bh_fuser_timeout, NULL, 10);
cout << "[ABORT] Fuse-Abort timeout is " << timeout << " sec" << endl;
struct sigaction sa;
struct itimerval timer;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = &timer_handler;
sigaction(SIGALRM, &sa, NULL);
timer.it_value.tv_sec = timeout;
timer.it_value.tv_usec = 0;
timer.it_interval.tv_sec = 0;
timer.it_interval.tv_usec = 100000;
setitimer (ITIMER_REAL, &timer, NULL);
}
void fuser(bh_ir &bhir)
{
#ifdef VERBOSE
++fuser_count;
#endif
set_abort_timer();
GraphDW dag;
from_bhir(bhir, dag);
fuse_gentle(dag);
dag.transitive_reduction();
assert(dag_validate(dag.bglD()));
GraphD output;
fuse_optimal(bhir, dag, output);
if(num_vertices(output) == 0)
output = dag.bglD();
assert(dag_validate(output));
fill_bhir_kernel_list(output, bhir);
}
<commit_msg>optimal-fuser: Implemented componentized<commit_after>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
Bohrium 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 Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <bh.h>
#include <bh_dag.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <boost/foreach.hpp>
#include <boost/graph/topological_sort.hpp>
#include <boost/graph/connected_components.hpp>
#include <boost/range/adaptors.hpp>
#include <vector>
#include <map>
#include <iterator>
#include <signal.h>
#include <stdio.h>
#include <sys/time.h>
#define VERBOSE
using namespace std;
using namespace boost;
using namespace bohrium::dag;
/* Help function that fuses the edges in 'edges2explore' where the 'mask' is true */
pair<int64_t,bool> fuse_mask(int64_t best_cost, const vector<EdgeW> &edges2explore,
const GraphDW &graph, const vector<bool> &mask, bh_ir &bhir,
GraphD &dag)
{
bool fusibility=true;
vector<EdgeW> edges2merge;
unsigned int i=0;
BOOST_FOREACH(const EdgeW &e, edges2explore)
{
if(mask[i++])
edges2merge.push_back(e);
}
//Help function to find the new location
struct find_new_location
{
Vertex operator()(const map<Vertex, Vertex> &loc_map, Vertex v)
{
Vertex v_mapped = loc_map.at(v);
if(v_mapped == v)
return v;
else
return (*this)(loc_map, v_mapped);
}
}find_loc;
//'loc_map' maps a vertex before the merge to the corresponding vertex after the merge
map<Vertex, Vertex> loc_map;
BOOST_FOREACH(Vertex v, vertices(dag))
{
loc_map[v] = v;
}
//Lets record the merges into 'loc_map'
BOOST_FOREACH(const EdgeW &e, edges2merge)
{
Vertex v1 = find_loc(loc_map, source(e, graph.bglW()));
Vertex v2 = find_loc(loc_map, target(e, graph.bglW()));
loc_map[v1] = v2;
}
//Pack 'loc_map' such that all keys maps directly to a new vertex thus after
//this point there is no need to call find_loc().
BOOST_FOREACH(Vertex v, vertices(dag))
{
Vertex v_mapped = find_loc(loc_map, loc_map.at(v));
if(v_mapped != v)
loc_map[v] = v_mapped;
}
//Create the new vertices and insert instruction topologically
map<Vertex, bh_ir_kernel> new_vertices;
BOOST_FOREACH(Vertex v, vertices(dag))
{
if(loc_map.at(v) == v)
new_vertices[v] = bh_ir_kernel(bhir);
}
vector<Vertex> topological_order;
topological_sort(dag, back_inserter(topological_order));
BOOST_REVERSE_FOREACH(Vertex vertex, topological_order)
{
Vertex v = loc_map.at(vertex);
bh_ir_kernel &k = new_vertices.at(v);
BOOST_FOREACH(uint64_t idx, dag[vertex].instr_indexes)
{
if(not k.fusible(idx))
fusibility = false;
k.add_instr(idx);
}
}
//TODO: Remove this assert check
BOOST_FOREACH(Vertex v, vertices(dag))
{
if(loc_map.at(v) == v)
assert(new_vertices[v].instr_indexes.size() > 0);
}
//Find the total cost
int64_t cost=0;
BOOST_FOREACH(const bh_ir_kernel &k, new_vertices | adaptors::map_values)
{
cost += k.cost();
}
//Check if we need to continue
if(cost >= best_cost or not fusibility)
return make_pair(cost,false);
//Merge the vertice in the DAG
BOOST_FOREACH(Vertex v, vertices(dag))
{
Vertex loc_v = loc_map.at(v);
if(loc_v == v)
{
dag[v] = new_vertices.at(v);
assert(dag[v].instr_indexes.size() > 0);
}
else//Lets merge 'v' into 'loc_v'
{
BOOST_FOREACH(Vertex a, adjacent_vertices(v, dag))
{
a = loc_map.at(a);
if(a != loc_v)
add_edge(loc_v, a, dag);
}
BOOST_FOREACH(Vertex a, inv_adjacent_vertices(v, dag))
{
a = loc_map.at(a);
if(a != loc_v)
add_edge(a, loc_v, dag);
}
clear_vertex(v, dag);
dag[v] = bh_ir_kernel(bhir);
}
}
//TODO: remove assert check
BOOST_FOREACH(Vertex v, vertices(dag))
{
if(dag[loc_map.at(v)].instr_indexes.size() == 0)
{
cout << v << endl;
cout << loc_map.at(v) << endl;
assert(1 == 2);
}
}
//Check for cycles
if(cycles(dag))
{
return make_pair(cost,false);
}
assert(cost == (int64_t)dag_cost(dag));
return make_pair(cost,true);
}
#ifdef VERBOSE
int fuser_count=0;
#endif
/* Private class to find the optimal solution through branch and bound */
class Solver
{
public:
bh_ir &bhir;
const GraphDW &dag;
const vector<EdgeW> &edges2explore;
int64_t best_cost;
int64_t one_cost;
GraphD best_dag;
#ifdef VERBOSE
double purge_count=0;
uint64_t explore_count=0;
#endif
/* The constructor */
Solver(bh_ir &b, const GraphDW &d, const vector<EdgeW> &e):bhir(b),dag(d),edges2explore(e)
{
//Wwe use the greedy algorithm to find a good initial guess
GraphDW new_dag(dag);
fuse_greedy(new_dag);
best_dag = new_dag.bglD();
best_cost = dag_cost(best_dag);
}
/* Find the optimal solution through branch and bound */
void branch_n_bound(vector<bool> mask, unsigned int offset, bool merge_next)
{
if(not merge_next)
{
GraphD new_dag(dag.bglD());
mask[offset] = merge_next;
bool fusibility;
int64_t cost;
tie(cost, fusibility) = fuse_mask(best_cost, edges2explore, dag, mask, bhir, new_dag);
#ifdef VERBOSE
if(explore_count%1000 == 0)
{
cout << "[" << explore_count << "] " << "purge count: ";
cout << purge_count << " / " << pow(2.0,mask.size()) << endl;
cout << "cost: " << cost << ", best_cost: " << best_cost;
cout << ", fusibility: " << fusibility << endl;
}
++explore_count;
#endif
if(cost >= best_cost)
{
#ifdef VERBOSE
purge_count += pow(2.0, mask.size()-offset-1);
#endif
return;
}
if(fusibility)
{
best_cost = cost;
best_dag = new_dag;
#ifdef VERBOSE
std::stringstream ss;
ss << "new_best_dag-" << fuser_count << "-" << dag_cost(new_dag) << ".dot";
printf("write file: %s\n", ss.str().c_str());
pprint(GraphDW(new_dag), ss.str().c_str());
purge_count += pow(2.0, mask.size()-offset-1);
#endif
return;
}
}
if(offset+1 < mask.size())
{
branch_n_bound(mask, offset+1, false);
branch_n_bound(mask, offset+1, true);
}
}
};
/* Fuse the 'dag' optimally */
void fuse_optimal(bh_ir &bhir, const GraphDW &dag, const set<Vertex> &vertices2explore, GraphD &output)
{
//The list of edges that we should try to merge
vector<EdgeW> edges2explore;
BOOST_FOREACH(const EdgeW &e, edges(dag.bglW()))
{
if(vertices2explore.find(source(e, dag.bglW())) != vertices2explore.end() or
vertices2explore.find(target(e, dag.bglW())) != vertices2explore.end())
edges2explore.push_back(e);
}
sort_weights(dag.bglW(), edges2explore);
//reverse(edges2explore.begin(), edges2explore.end());
if(edges2explore.size() == 0)
return;
//First we check the trivial case where all kernels are merged
vector<bool> mask(edges2explore.size(), true);
{
GraphD new_dag(dag.bglD());
bool fuse = fuse_mask(numeric_limits<int64_t>::max(), edges2explore,
dag, mask, bhir, new_dag).second;
if(fuse)
{
output = new_dag;
return;
}
}
Solver solver(bhir, dag, edges2explore);
if(mask.size() > 100)
{
cout << "FUSER-OPTIMAL: ABORT the size of the search space is too large: 2^";
cout << mask.size() << "!" << endl;
}
else
{
cout << "FUSER-OPTIMAL: the size of the search space is 2^" << mask.size() << "!" << endl;
solver.branch_n_bound(mask, 0, false);
solver.branch_n_bound(mask, 0, true);
}
output = solver.best_dag;
}
void timer_handler(int signum)
{
cout << "ABORT! - timeout" << endl;
exit(-1);
}
void set_abort_timer()
{
const char *bh_fuser_timeout = getenv("BH_FUSER_TIMEOUT");
if(bh_fuser_timeout == NULL)
return;
long int timeout = strtol(bh_fuser_timeout, NULL, 10);
cout << "[ABORT] Fuse-Abort timeout is " << timeout << " sec" << endl;
struct sigaction sa;
struct itimerval timer;
memset(&sa, 0, sizeof(sa));
sa.sa_handler = &timer_handler;
sigaction(SIGALRM, &sa, NULL);
timer.it_value.tv_sec = timeout;
timer.it_value.tv_usec = 0;
timer.it_interval.tv_sec = 0;
timer.it_interval.tv_usec = 100000;
setitimer (ITIMER_REAL, &timer, NULL);
}
void fuser(bh_ir &bhir)
{
#ifdef VERBOSE
++fuser_count;
#endif
set_abort_timer();
{
GraphDW dag;
from_bhir(bhir, dag);
fuse_gentle(dag);
fill_bhir_kernel_list(dag.bglD(), bhir);
}
while(true)
{
GraphDW dag;
from_kernels(bhir.kernel_list, dag);
fuse_gentle(dag);
dag.transitive_reduction();
assert(dag_validate(dag.bglD()));
vector<set<Vertex> > component2vertices;
{
vector<Vertex> vertex2component(num_vertices(dag.bglW()));
uint64_t num = connected_components(dag.bglW(), &vertex2component[0]);
component2vertices.resize(num);
for(Vertex v=0; v<vertex2component.size(); ++v)
{
component2vertices[vertex2component[v]].insert(v);
}
}
uint64_t component_id = 0;
BOOST_FOREACH(set<Vertex> &vertices, component2vertices)
{
cout << "Component " << component_id << ": ";
BOOST_FOREACH(Vertex v, vertices)
{
cout << v << ", ";
}
cout << endl;
++component_id;
}
//Find the first component with more than one vertex
uint64_t comp_id;
for(comp_id=0; comp_id < component2vertices.size(); ++comp_id)
{
if(component2vertices[comp_id].size() > 1)
break;
}
if(comp_id >= component2vertices.size())
break;//No more singleton components to fuse
GraphD output;
fuse_optimal(bhir, dag, component2vertices[comp_id], output);
assert(num_vertices(output) > 0);
assert(dag_validate(output));
bhir.kernel_list.clear();
fill_bhir_kernel_list(output, bhir);
}
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.