{"text":"\/*\n This file is part of Magnum.\n\n Copyright © 2010, 2011, 2012, 2013, 2014, 2015\n Vladimír Vondruš \n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n#include \"Context.h\"\n\n#include \n#include \n#include \n\n#include \"Magnum\/Magnum.h\"\n\nnamespace Magnum { namespace Audio {\n\nContext* Context::_current = nullptr;\n\nContext::Context() {\n CORRADE_ASSERT(!_current, \"Audio::Context: context already created\", );\n\n \/* Open default device *\/\n const ALCchar* const defaultDevice = alcGetString(nullptr, ALC_DEFAULT_DEVICE_SPECIFIER);\n _device = alcOpenDevice(defaultDevice);\n if(!_device) {\n Error() << \"Audio::Context: cannot open sound device\" << defaultDevice;\n std::exit(1);\n }\n\n _context = alcCreateContext(_device, nullptr);\n if(!_context) {\n Error() << \"Audio::Context: cannot create context:\" << alcGetError(_device);\n std::exit(1);\n }\n\n alcMakeContextCurrent(_context);\n _current = this;\n}\n\nContext::~Context() {\n CORRADE_INTERNAL_ASSERT(_current == this);\n\n alcDestroyContext(_context);\n alcCloseDevice(_device);\n}\n\n}}\nAudio: Print additional info on Context creation\/*\n This file is part of Magnum.\n\n Copyright © 2010, 2011, 2012, 2013, 2014, 2015\n Vladimír Vondruš \n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n#include \"Context.h\"\n\n#include \n#include \n#include \n\n#include \"Magnum\/Magnum.h\"\n\nnamespace Magnum { namespace Audio {\n\nContext* Context::_current = nullptr;\n\nContext::Context() {\n CORRADE_ASSERT(!_current, \"Audio::Context: context already created\", );\n\n \/* Open default device *\/\n const ALCchar* const defaultDevice = alcGetString(nullptr, ALC_DEFAULT_DEVICE_SPECIFIER);\n _device = alcOpenDevice(defaultDevice);\n if(!_device) {\n Error() << \"Audio::Context: cannot open sound device\" << defaultDevice;\n std::exit(1);\n }\n\n _context = alcCreateContext(_device, nullptr);\n if(!_context) {\n Error() << \"Audio::Context: cannot create context:\" << alcGetError(_device);\n std::exit(1);\n }\n\n alcMakeContextCurrent(_context);\n _current = this;\n\n \/* Print some info *\/\n Debug() << \"Audio Renderer:\" << rendererString() << \"by\" << vendorString();\n Debug() << \"OpenAL version:\" << versionString();\n}\n\nContext::~Context() {\n CORRADE_INTERNAL_ASSERT(_current == this);\n\n alcDestroyContext(_context);\n alcCloseDevice(_device);\n}\n\n}}\n<|endoftext|>"} {"text":"\/*************************************************************************\/\n\/* register_server_types.cpp *\/\n\/*************************************************************************\/\n\/* This file is part of: *\/\n\/* GODOT ENGINE *\/\n\/* http:\/\/www.godotengine.org *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the *\/\n\/* \"Software\"), to deal in the Software without restriction, including *\/\n\/* without limitation the rights to use, copy, modify, merge, publish, *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\/\n\/*************************************************************************\/\n#include \"register_server_types.h\"\n#include \"globals.h\"\n\n#include \"visual_server.h\"\n#include \"audio_server.h\"\n#include \"physics_server.h\"\n#include \"physics_2d_server.h\"\n#include \"spatial_sound_server.h\"\n#include \"spatial_sound_2d_server.h\"\n\nvoid register_server_types() {\n\n\tGlobals::get_singleton()->add_singleton( Globals::Singleton(\"VisualServer\",VisualServer::get_singleton()) );\n\tGlobals::get_singleton()->add_singleton( Globals::Singleton(\"VS\",VisualServer::get_singleton()) );\n\tGlobals::get_singleton()->add_singleton( Globals::Singleton(\"AudioServer\",AudioServer::get_singleton()) );\n\tGlobals::get_singleton()->add_singleton( Globals::Singleton(\"AS\",AudioServer::get_singleton()) );\n\tGlobals::get_singleton()->add_singleton( Globals::Singleton(\"PhysicsServer\",PhysicsServer::get_singleton()) );\n\tGlobals::get_singleton()->add_singleton( Globals::Singleton(\"PS\",PhysicsServer::get_singleton()) );\n\tGlobals::get_singleton()->add_singleton( Globals::Singleton(\"Physics2DServer\",Physics2DServer::get_singleton()) );\n\tGlobals::get_singleton()->add_singleton( Globals::Singleton(\"PS2D\",Physics2DServer::get_singleton()) );\n\tGlobals::get_singleton()->add_singleton( Globals::Singleton(\"SpatialSoundServer\",SpatialSound2DServer::get_singleton()) );\n\tGlobals::get_singleton()->add_singleton( Globals::Singleton(\"SS\",SpatialSound2DServer::get_singleton()) );\n\tGlobals::get_singleton()->add_singleton( Globals::Singleton(\"SpatialSound2DServer\",SpatialSound2DServer::get_singleton()) );\n\tGlobals::get_singleton()->add_singleton( Globals::Singleton(\"SS2D\",SpatialSound2DServer::get_singleton()) );\n\n\n\tObjectTypeDB::register_virtual_type();\n\tObjectTypeDB::register_virtual_type();\n\tObjectTypeDB::register_virtual_type();\n\tObjectTypeDB::register_virtual_type();\n\tObjectTypeDB::register_type();\n\n\tObjectTypeDB::register_type();\n\tObjectTypeDB::register_virtual_type();\n\tObjectTypeDB::register_virtual_type();\n\tObjectTypeDB::register_virtual_type();\n\n}\n\nvoid unregister_server_types(){\n\n\n}\nfix register Physics2DTestMotionResult\/*************************************************************************\/\n\/* register_server_types.cpp *\/\n\/*************************************************************************\/\n\/* This file is part of: *\/\n\/* GODOT ENGINE *\/\n\/* http:\/\/www.godotengine.org *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the *\/\n\/* \"Software\"), to deal in the Software without restriction, including *\/\n\/* without limitation the rights to use, copy, modify, merge, publish, *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\/\n\/*************************************************************************\/\n#include \"register_server_types.h\"\n#include \"globals.h\"\n\n#include \"visual_server.h\"\n#include \"audio_server.h\"\n#include \"physics_server.h\"\n#include \"physics_2d_server.h\"\n#include \"spatial_sound_server.h\"\n#include \"spatial_sound_2d_server.h\"\n\nvoid register_server_types() {\n\n\tGlobals::get_singleton()->add_singleton( Globals::Singleton(\"VisualServer\",VisualServer::get_singleton()) );\n\tGlobals::get_singleton()->add_singleton( Globals::Singleton(\"VS\",VisualServer::get_singleton()) );\n\tGlobals::get_singleton()->add_singleton( Globals::Singleton(\"AudioServer\",AudioServer::get_singleton()) );\n\tGlobals::get_singleton()->add_singleton( Globals::Singleton(\"AS\",AudioServer::get_singleton()) );\n\tGlobals::get_singleton()->add_singleton( Globals::Singleton(\"PhysicsServer\",PhysicsServer::get_singleton()) );\n\tGlobals::get_singleton()->add_singleton( Globals::Singleton(\"PS\",PhysicsServer::get_singleton()) );\n\tGlobals::get_singleton()->add_singleton( Globals::Singleton(\"Physics2DServer\",Physics2DServer::get_singleton()) );\n\tGlobals::get_singleton()->add_singleton( Globals::Singleton(\"PS2D\",Physics2DServer::get_singleton()) );\n\tGlobals::get_singleton()->add_singleton( Globals::Singleton(\"SpatialSoundServer\",SpatialSound2DServer::get_singleton()) );\n\tGlobals::get_singleton()->add_singleton( Globals::Singleton(\"SS\",SpatialSound2DServer::get_singleton()) );\n\tGlobals::get_singleton()->add_singleton( Globals::Singleton(\"SpatialSound2DServer\",SpatialSound2DServer::get_singleton()) );\n\tGlobals::get_singleton()->add_singleton( Globals::Singleton(\"SS2D\",SpatialSound2DServer::get_singleton()) );\n\n\n\tObjectTypeDB::register_virtual_type();\n\tObjectTypeDB::register_virtual_type();\n\tObjectTypeDB::register_virtual_type();\n\tObjectTypeDB::register_type();\n\tObjectTypeDB::register_type();\n\n\tObjectTypeDB::register_type();\n\tObjectTypeDB::register_virtual_type();\n\tObjectTypeDB::register_virtual_type();\n\tObjectTypeDB::register_virtual_type();\n\n}\n\nvoid unregister_server_types(){\n\n\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2017-2018 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nInitInterfaces* g_rpc_interfaces = nullptr;\n\n\/\/ Converts a hex string to a public key if possible\nCPubKey HexToPubKey(const std::string& hex_in)\n{\n if (!IsHex(hex_in)) {\n throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Invalid public key: \" + hex_in);\n }\n CPubKey vchPubKey(ParseHex(hex_in));\n if (!vchPubKey.IsFullyValid()) {\n throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Invalid public key: \" + hex_in);\n }\n return vchPubKey;\n}\n\n\/\/ Retrieves a public key for an address from the given CKeyStore\nCPubKey AddrToPubKey(CKeyStore* const keystore, const std::string& addr_in)\n{\n CTxDestination dest = DecodeDestination(addr_in);\n if (!IsValidDestination(dest)) {\n throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Invalid address: \" + addr_in);\n }\n CKeyID key = GetKeyForDestination(*keystore, dest);\n if (key.IsNull()) {\n throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf(\"%s does not refer to a key\", addr_in));\n }\n CPubKey vchPubKey;\n if (!keystore->GetPubKey(key, vchPubKey)) {\n throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf(\"no full public key for address %s\", addr_in));\n }\n if (!vchPubKey.IsFullyValid()) {\n throw JSONRPCError(RPC_INTERNAL_ERROR, \"Wallet contains an invalid public key\");\n }\n return vchPubKey;\n}\n\n\/\/ Creates a multisig redeemscript from a given list of public keys and number required.\nCScript CreateMultisigRedeemscript(const int required, const std::vector& pubkeys)\n{\n \/\/ Gather public keys\n if (required < 1) {\n throw JSONRPCError(RPC_INVALID_PARAMETER, \"a multisignature address must require at least one key to redeem\");\n }\n if ((int)pubkeys.size() < required) {\n throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf(\"not enough keys supplied (got %u keys, but need at least %d to redeem)\", pubkeys.size(), required));\n }\n if (pubkeys.size() > 16) {\n throw JSONRPCError(RPC_INVALID_PARAMETER, \"Number of keys involved in the multisignature address creation > 16\\nReduce the number\");\n }\n\n CScript result = GetScriptForMultisig(required, pubkeys);\n\n if (result.size() > MAX_SCRIPT_ELEMENT_SIZE) {\n throw JSONRPCError(RPC_INVALID_PARAMETER, (strprintf(\"redeemScript exceeds size limit: %d > %d\", result.size(), MAX_SCRIPT_ELEMENT_SIZE)));\n }\n\n return result;\n}\n\nclass DescribeAddressVisitor : public boost::static_visitor\n{\npublic:\n explicit DescribeAddressVisitor() {}\n\n UniValue operator()(const CNoDestination& dest) const\n {\n return UniValue(UniValue::VOBJ);\n }\n\n UniValue operator()(const CKeyID& keyID) const\n {\n UniValue obj(UniValue::VOBJ);\n obj.pushKV(\"isscript\", false);\n obj.pushKV(\"iswitness\", false);\n return obj;\n }\n\n UniValue operator()(const CScriptID& scriptID) const\n {\n UniValue obj(UniValue::VOBJ);\n obj.pushKV(\"isscript\", true);\n obj.pushKV(\"iswitness\", false);\n return obj;\n }\n\n UniValue operator()(const WitnessV0KeyHash& id) const\n {\n UniValue obj(UniValue::VOBJ);\n obj.pushKV(\"isscript\", false);\n obj.pushKV(\"iswitness\", true);\n obj.pushKV(\"witness_version\", 0);\n obj.pushKV(\"witness_program\", HexStr(id.begin(), id.end()));\n return obj;\n }\n\n UniValue operator()(const WitnessV0ScriptHash& id) const\n {\n UniValue obj(UniValue::VOBJ);\n obj.pushKV(\"isscript\", true);\n obj.pushKV(\"iswitness\", true);\n obj.pushKV(\"witness_version\", 0);\n obj.pushKV(\"witness_program\", HexStr(id.begin(), id.end()));\n return obj;\n }\n\n UniValue operator()(const WitnessUnknown& id) const\n {\n UniValue obj(UniValue::VOBJ);\n obj.pushKV(\"iswitness\", true);\n obj.pushKV(\"witness_version\", (int)id.version);\n obj.pushKV(\"witness_program\", HexStr(id.program, id.program + id.length));\n return obj;\n }\n};\n\nUniValue DescribeAddress(const CTxDestination& dest)\n{\n return boost::apply_visitor(DescribeAddressVisitor(), dest);\n}\n\nstruct Section {\n Section(const std::string& left, const std::string& right)\n : m_left{left}, m_right{right} {}\n const std::string m_left;\n const std::string m_right;\n};\n\nstruct Sections {\n std::vector
m_sections;\n size_t m_max_pad{0};\n\n void PushSection(const Section& s)\n {\n m_max_pad = std::max(m_max_pad, s.m_left.size());\n m_sections.push_back(s);\n }\n\n enum class OuterType {\n ARR,\n OBJ,\n NAMED_ARG, \/\/ Only set on first recursion\n };\n\n void Push(const RPCArg& arg, const size_t current_indent = 5, const OuterType outer_type = OuterType::NAMED_ARG)\n {\n const auto indent = std::string(current_indent, ' ');\n const auto indent_next = std::string(current_indent + 2, ' ');\n switch (arg.m_type) {\n case RPCArg::Type::STR_HEX:\n case RPCArg::Type::STR:\n case RPCArg::Type::NUM:\n case RPCArg::Type::AMOUNT:\n case RPCArg::Type::BOOL: {\n if (outer_type == OuterType::NAMED_ARG) return; \/\/ Nothing more to do for non-recursive types on first recursion\n auto left = indent;\n if (arg.m_type_str.size() != 0 && outer_type == OuterType::OBJ) {\n left += \"\\\"\" + arg.m_name + \"\\\": \" + arg.m_type_str.at(0);\n } else {\n left += outer_type == OuterType::OBJ ? arg.ToStringObj(\/* oneline *\/ false) : arg.ToString(\/* oneline *\/ false);\n }\n left += \",\";\n PushSection({left, arg.ToDescriptionString(\/* implicitly_required *\/ outer_type == OuterType::ARR)});\n break;\n }\n case RPCArg::Type::OBJ:\n case RPCArg::Type::OBJ_USER_KEYS: {\n const auto right = outer_type == OuterType::NAMED_ARG ? \"\" : arg.ToDescriptionString(\/* implicitly_required *\/ outer_type == OuterType::ARR);\n PushSection({indent + \"{\", right});\n for (const auto& arg_inner : arg.m_inner) {\n Push(arg_inner, current_indent + 2, OuterType::OBJ);\n }\n if (arg.m_type != RPCArg::Type::OBJ) {\n PushSection({indent_next + \"...\", \"\"});\n }\n PushSection({indent + \"}\" + (outer_type != OuterType::NAMED_ARG ? \",\" : \"\"), \"\"});\n break;\n }\n case RPCArg::Type::ARR: {\n auto left = indent;\n left += outer_type == OuterType::OBJ ? \"\\\"\" + arg.m_name + \"\\\": \" : \"\";\n left += \"[\";\n const auto right = outer_type == OuterType::NAMED_ARG ? \"\" : arg.ToDescriptionString(\/* implicitly_required *\/ outer_type == OuterType::ARR);\n PushSection({left, right});\n for (const auto& arg_inner : arg.m_inner) {\n Push(arg_inner, current_indent + 2, OuterType::ARR);\n }\n PushSection({indent_next + \"...\", \"\"});\n PushSection({indent + \"]\" + (outer_type != OuterType::NAMED_ARG ? \",\" : \"\"), \"\"});\n break;\n }\n\n \/\/ no default case, so the compiler can warn about missing cases\n }\n }\n\n std::string ToString() const\n {\n std::string ret;\n const size_t pad = m_max_pad + 4;\n for (const auto& s : m_sections) {\n if (s.m_right.empty()) {\n ret += s.m_left;\n ret += \"\\n\";\n continue;\n }\n\n std::string left = s.m_left;\n left.resize(pad, ' ');\n ret += left;\n\n \/\/ Properly pad after newlines\n std::string right;\n size_t begin = 0;\n size_t new_line_pos = s.m_right.find_first_of('\\n');\n while (true) {\n right += s.m_right.substr(begin, new_line_pos - begin);\n if (new_line_pos == std::string::npos) {\n break; \/\/No new line\n }\n right += \"\\n\" + std::string(pad, ' ');\n begin = s.m_right.find_first_not_of(' ', new_line_pos + 1);\n if (begin == std::string::npos) {\n break; \/\/ Empty line\n }\n new_line_pos = s.m_right.find_first_of('\\n', begin + 1);\n }\n ret += right;\n ret += \"\\n\";\n }\n return ret;\n }\n};\n\nRPCHelpMan::RPCHelpMan(const std::string& name, const std::string& description, const std::vector& args)\n : m_name{name}, m_description{description}, m_args{args}\n{\n std::set named_args;\n for (const auto& arg : m_args) {\n \/\/ Should have unique named arguments\n assert(named_args.insert(arg.m_name).second);\n }\n}\n\nstd::string RPCHelpMan::ToString() const\n{\n std::string ret;\n\n \/\/ Oneline summary\n ret += m_name;\n bool is_optional{false};\n for (const auto& arg : m_args) {\n ret += \" \";\n if (arg.m_optional) {\n if (!is_optional) ret += \"( \";\n is_optional = true;\n } else {\n \/\/ Currently we still support unnamed arguments, so any argument following an optional argument must also be optional\n \/\/ If support for positional arguments is deprecated in the future, remove this line\n assert(!is_optional);\n }\n ret += arg.ToString(\/* oneline *\/ true);\n }\n if (is_optional) ret += \" )\";\n ret += \"\\n\";\n\n \/\/ Description\n ret += m_description;\n\n \/\/ Arguments\n Sections sections;\n for (size_t i{0}; i < m_args.size(); ++i) {\n const auto& arg = m_args.at(i);\n\n if (i == 0) ret += \"\\nArguments:\\n\";\n\n \/\/ Push named argument name and description\n const auto str_wrapper = (arg.m_type == RPCArg::Type::STR || arg.m_type == RPCArg::Type::STR_HEX) ? \"\\\"\" : \"\";\n sections.m_sections.emplace_back(std::to_string(i + 1) + \". \" + str_wrapper + arg.m_name + str_wrapper, arg.ToDescriptionString());\n sections.m_max_pad = std::max(sections.m_max_pad, sections.m_sections.back().m_left.size());\n\n \/\/ Recursively push nested args\n sections.Push(arg);\n }\n ret += sections.ToString();\n\n return ret;\n}\n\nstd::string RPCArg::ToDescriptionString(const bool implicitly_required) const\n{\n std::string ret;\n ret += \"(\";\n if (m_type_str.size() != 0) {\n ret += m_type_str.at(1);\n } else {\n switch (m_type) {\n case Type::STR_HEX:\n case Type::STR: {\n ret += \"string\";\n break;\n }\n case Type::NUM: {\n ret += \"numeric\";\n break;\n }\n case Type::AMOUNT: {\n ret += \"numeric or string\";\n break;\n }\n case Type::BOOL: {\n ret += \"boolean\";\n break;\n }\n case Type::OBJ:\n case Type::OBJ_USER_KEYS: {\n ret += \"json object\";\n break;\n }\n case Type::ARR: {\n ret += \"json array\";\n break;\n }\n\n \/\/ no default case, so the compiler can warn about missing cases\n }\n }\n if (!implicitly_required) {\n ret += \", \";\n if (m_optional) {\n ret += \"optional\";\n if (!m_default_value.empty()) {\n ret += \", default=\" + m_default_value;\n } else {\n \/\/ TODO enable this assert, when all optional parameters have their default value documented\n \/\/assert(false);\n }\n } else {\n ret += \"required\";\n assert(m_default_value.empty()); \/\/ Default value is ignored, and must not be present\n }\n }\n ret += \")\";\n ret += m_description.empty() ? \"\" : \" \" + m_description;\n return ret;\n}\n\nstd::string RPCArg::ToStringObj(const bool oneline) const\n{\n std::string res;\n res += \"\\\"\";\n res += m_name;\n if (oneline) {\n res += \"\\\":\";\n } else {\n res += \"\\\": \";\n }\n switch (m_type) {\n case Type::STR:\n return res + \"\\\"str\\\"\";\n case Type::STR_HEX:\n return res + \"\\\"hex\\\"\";\n case Type::NUM:\n return res + \"n\";\n case Type::AMOUNT:\n return res + \"amount\";\n case Type::BOOL:\n return res + \"bool\";\n case Type::ARR:\n res += \"[\";\n for (const auto& i : m_inner) {\n res += i.ToString(oneline) + \",\";\n }\n return res + \"...]\";\n case Type::OBJ:\n case Type::OBJ_USER_KEYS:\n \/\/ Currently unused, so avoid writing dead code\n assert(false);\n\n \/\/ no default case, so the compiler can warn about missing cases\n }\n assert(false);\n}\n\nstd::string RPCArg::ToString(const bool oneline) const\n{\n if (oneline && !m_oneline_description.empty()) return m_oneline_description;\n\n switch (m_type) {\n case Type::STR_HEX:\n case Type::STR: {\n return \"\\\"\" + m_name + \"\\\"\";\n }\n case Type::NUM:\n case Type::AMOUNT:\n case Type::BOOL: {\n return m_name;\n }\n case Type::OBJ:\n case Type::OBJ_USER_KEYS: {\n std::string res;\n for (size_t i = 0; i < m_inner.size();) {\n res += m_inner[i].ToStringObj(oneline);\n if (++i < m_inner.size()) res += \",\";\n }\n if (m_type == Type::OBJ) {\n return \"{\" + res + \"}\";\n } else {\n return \"{\" + res + \",...}\";\n }\n }\n case Type::ARR: {\n std::string res;\n for (const auto& i : m_inner) {\n res += i.ToString(oneline) + \",\";\n }\n return \"[\" + res + \"...]\";\n }\n\n \/\/ no default case, so the compiler can warn about missing cases\n }\n assert(false);\n}\nRPCHelpMan: Support required arguments after optional ones\/\/ Copyright (c) 2017-2018 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nInitInterfaces* g_rpc_interfaces = nullptr;\n\n\/\/ Converts a hex string to a public key if possible\nCPubKey HexToPubKey(const std::string& hex_in)\n{\n if (!IsHex(hex_in)) {\n throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Invalid public key: \" + hex_in);\n }\n CPubKey vchPubKey(ParseHex(hex_in));\n if (!vchPubKey.IsFullyValid()) {\n throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Invalid public key: \" + hex_in);\n }\n return vchPubKey;\n}\n\n\/\/ Retrieves a public key for an address from the given CKeyStore\nCPubKey AddrToPubKey(CKeyStore* const keystore, const std::string& addr_in)\n{\n CTxDestination dest = DecodeDestination(addr_in);\n if (!IsValidDestination(dest)) {\n throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, \"Invalid address: \" + addr_in);\n }\n CKeyID key = GetKeyForDestination(*keystore, dest);\n if (key.IsNull()) {\n throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf(\"%s does not refer to a key\", addr_in));\n }\n CPubKey vchPubKey;\n if (!keystore->GetPubKey(key, vchPubKey)) {\n throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf(\"no full public key for address %s\", addr_in));\n }\n if (!vchPubKey.IsFullyValid()) {\n throw JSONRPCError(RPC_INTERNAL_ERROR, \"Wallet contains an invalid public key\");\n }\n return vchPubKey;\n}\n\n\/\/ Creates a multisig redeemscript from a given list of public keys and number required.\nCScript CreateMultisigRedeemscript(const int required, const std::vector& pubkeys)\n{\n \/\/ Gather public keys\n if (required < 1) {\n throw JSONRPCError(RPC_INVALID_PARAMETER, \"a multisignature address must require at least one key to redeem\");\n }\n if ((int)pubkeys.size() < required) {\n throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf(\"not enough keys supplied (got %u keys, but need at least %d to redeem)\", pubkeys.size(), required));\n }\n if (pubkeys.size() > 16) {\n throw JSONRPCError(RPC_INVALID_PARAMETER, \"Number of keys involved in the multisignature address creation > 16\\nReduce the number\");\n }\n\n CScript result = GetScriptForMultisig(required, pubkeys);\n\n if (result.size() > MAX_SCRIPT_ELEMENT_SIZE) {\n throw JSONRPCError(RPC_INVALID_PARAMETER, (strprintf(\"redeemScript exceeds size limit: %d > %d\", result.size(), MAX_SCRIPT_ELEMENT_SIZE)));\n }\n\n return result;\n}\n\nclass DescribeAddressVisitor : public boost::static_visitor\n{\npublic:\n explicit DescribeAddressVisitor() {}\n\n UniValue operator()(const CNoDestination& dest) const\n {\n return UniValue(UniValue::VOBJ);\n }\n\n UniValue operator()(const CKeyID& keyID) const\n {\n UniValue obj(UniValue::VOBJ);\n obj.pushKV(\"isscript\", false);\n obj.pushKV(\"iswitness\", false);\n return obj;\n }\n\n UniValue operator()(const CScriptID& scriptID) const\n {\n UniValue obj(UniValue::VOBJ);\n obj.pushKV(\"isscript\", true);\n obj.pushKV(\"iswitness\", false);\n return obj;\n }\n\n UniValue operator()(const WitnessV0KeyHash& id) const\n {\n UniValue obj(UniValue::VOBJ);\n obj.pushKV(\"isscript\", false);\n obj.pushKV(\"iswitness\", true);\n obj.pushKV(\"witness_version\", 0);\n obj.pushKV(\"witness_program\", HexStr(id.begin(), id.end()));\n return obj;\n }\n\n UniValue operator()(const WitnessV0ScriptHash& id) const\n {\n UniValue obj(UniValue::VOBJ);\n obj.pushKV(\"isscript\", true);\n obj.pushKV(\"iswitness\", true);\n obj.pushKV(\"witness_version\", 0);\n obj.pushKV(\"witness_program\", HexStr(id.begin(), id.end()));\n return obj;\n }\n\n UniValue operator()(const WitnessUnknown& id) const\n {\n UniValue obj(UniValue::VOBJ);\n obj.pushKV(\"iswitness\", true);\n obj.pushKV(\"witness_version\", (int)id.version);\n obj.pushKV(\"witness_program\", HexStr(id.program, id.program + id.length));\n return obj;\n }\n};\n\nUniValue DescribeAddress(const CTxDestination& dest)\n{\n return boost::apply_visitor(DescribeAddressVisitor(), dest);\n}\n\nstruct Section {\n Section(const std::string& left, const std::string& right)\n : m_left{left}, m_right{right} {}\n const std::string m_left;\n const std::string m_right;\n};\n\nstruct Sections {\n std::vector
m_sections;\n size_t m_max_pad{0};\n\n void PushSection(const Section& s)\n {\n m_max_pad = std::max(m_max_pad, s.m_left.size());\n m_sections.push_back(s);\n }\n\n enum class OuterType {\n ARR,\n OBJ,\n NAMED_ARG, \/\/ Only set on first recursion\n };\n\n void Push(const RPCArg& arg, const size_t current_indent = 5, const OuterType outer_type = OuterType::NAMED_ARG)\n {\n const auto indent = std::string(current_indent, ' ');\n const auto indent_next = std::string(current_indent + 2, ' ');\n switch (arg.m_type) {\n case RPCArg::Type::STR_HEX:\n case RPCArg::Type::STR:\n case RPCArg::Type::NUM:\n case RPCArg::Type::AMOUNT:\n case RPCArg::Type::BOOL: {\n if (outer_type == OuterType::NAMED_ARG) return; \/\/ Nothing more to do for non-recursive types on first recursion\n auto left = indent;\n if (arg.m_type_str.size() != 0 && outer_type == OuterType::OBJ) {\n left += \"\\\"\" + arg.m_name + \"\\\": \" + arg.m_type_str.at(0);\n } else {\n left += outer_type == OuterType::OBJ ? arg.ToStringObj(\/* oneline *\/ false) : arg.ToString(\/* oneline *\/ false);\n }\n left += \",\";\n PushSection({left, arg.ToDescriptionString(\/* implicitly_required *\/ outer_type == OuterType::ARR)});\n break;\n }\n case RPCArg::Type::OBJ:\n case RPCArg::Type::OBJ_USER_KEYS: {\n const auto right = outer_type == OuterType::NAMED_ARG ? \"\" : arg.ToDescriptionString(\/* implicitly_required *\/ outer_type == OuterType::ARR);\n PushSection({indent + \"{\", right});\n for (const auto& arg_inner : arg.m_inner) {\n Push(arg_inner, current_indent + 2, OuterType::OBJ);\n }\n if (arg.m_type != RPCArg::Type::OBJ) {\n PushSection({indent_next + \"...\", \"\"});\n }\n PushSection({indent + \"}\" + (outer_type != OuterType::NAMED_ARG ? \",\" : \"\"), \"\"});\n break;\n }\n case RPCArg::Type::ARR: {\n auto left = indent;\n left += outer_type == OuterType::OBJ ? \"\\\"\" + arg.m_name + \"\\\": \" : \"\";\n left += \"[\";\n const auto right = outer_type == OuterType::NAMED_ARG ? \"\" : arg.ToDescriptionString(\/* implicitly_required *\/ outer_type == OuterType::ARR);\n PushSection({left, right});\n for (const auto& arg_inner : arg.m_inner) {\n Push(arg_inner, current_indent + 2, OuterType::ARR);\n }\n PushSection({indent_next + \"...\", \"\"});\n PushSection({indent + \"]\" + (outer_type != OuterType::NAMED_ARG ? \",\" : \"\"), \"\"});\n break;\n }\n\n \/\/ no default case, so the compiler can warn about missing cases\n }\n }\n\n std::string ToString() const\n {\n std::string ret;\n const size_t pad = m_max_pad + 4;\n for (const auto& s : m_sections) {\n if (s.m_right.empty()) {\n ret += s.m_left;\n ret += \"\\n\";\n continue;\n }\n\n std::string left = s.m_left;\n left.resize(pad, ' ');\n ret += left;\n\n \/\/ Properly pad after newlines\n std::string right;\n size_t begin = 0;\n size_t new_line_pos = s.m_right.find_first_of('\\n');\n while (true) {\n right += s.m_right.substr(begin, new_line_pos - begin);\n if (new_line_pos == std::string::npos) {\n break; \/\/No new line\n }\n right += \"\\n\" + std::string(pad, ' ');\n begin = s.m_right.find_first_not_of(' ', new_line_pos + 1);\n if (begin == std::string::npos) {\n break; \/\/ Empty line\n }\n new_line_pos = s.m_right.find_first_of('\\n', begin + 1);\n }\n ret += right;\n ret += \"\\n\";\n }\n return ret;\n }\n};\n\nRPCHelpMan::RPCHelpMan(const std::string& name, const std::string& description, const std::vector& args)\n : m_name{name}, m_description{description}, m_args{args}\n{\n std::set named_args;\n for (const auto& arg : m_args) {\n \/\/ Should have unique named arguments\n assert(named_args.insert(arg.m_name).second);\n }\n}\n\nstd::string RPCHelpMan::ToString() const\n{\n std::string ret;\n\n \/\/ Oneline summary\n ret += m_name;\n bool was_optional{false};\n for (const auto& arg : m_args) {\n ret += \" \";\n if (arg.m_optional) {\n if (!was_optional) ret += \"( \";\n was_optional = true;\n } else {\n if (was_optional) ret += \") \";\n was_optional = false;\n }\n ret += arg.ToString(\/* oneline *\/ true);\n }\n if (was_optional) ret += \" )\";\n ret += \"\\n\";\n\n \/\/ Description\n ret += m_description;\n\n \/\/ Arguments\n Sections sections;\n for (size_t i{0}; i < m_args.size(); ++i) {\n const auto& arg = m_args.at(i);\n\n if (i == 0) ret += \"\\nArguments:\\n\";\n\n \/\/ Push named argument name and description\n sections.m_sections.emplace_back(std::to_string(i + 1) + \". \" + arg.m_name, arg.ToDescriptionString());\n sections.m_max_pad = std::max(sections.m_max_pad, sections.m_sections.back().m_left.size());\n\n \/\/ Recursively push nested args\n sections.Push(arg);\n }\n ret += sections.ToString();\n\n return ret;\n}\n\nstd::string RPCArg::ToDescriptionString(const bool implicitly_required) const\n{\n std::string ret;\n ret += \"(\";\n if (m_type_str.size() != 0) {\n ret += m_type_str.at(1);\n } else {\n switch (m_type) {\n case Type::STR_HEX:\n case Type::STR: {\n ret += \"string\";\n break;\n }\n case Type::NUM: {\n ret += \"numeric\";\n break;\n }\n case Type::AMOUNT: {\n ret += \"numeric or string\";\n break;\n }\n case Type::BOOL: {\n ret += \"boolean\";\n break;\n }\n case Type::OBJ:\n case Type::OBJ_USER_KEYS: {\n ret += \"json object\";\n break;\n }\n case Type::ARR: {\n ret += \"json array\";\n break;\n }\n\n \/\/ no default case, so the compiler can warn about missing cases\n }\n }\n if (!implicitly_required) {\n ret += \", \";\n if (m_optional) {\n ret += \"optional\";\n if (!m_default_value.empty()) {\n ret += \", default=\" + m_default_value;\n } else {\n \/\/ TODO enable this assert, when all optional parameters have their default value documented\n \/\/assert(false);\n }\n } else {\n ret += \"required\";\n assert(m_default_value.empty()); \/\/ Default value is ignored, and must not be present\n }\n }\n ret += \")\";\n ret += m_description.empty() ? \"\" : \" \" + m_description;\n return ret;\n}\n\nstd::string RPCArg::ToStringObj(const bool oneline) const\n{\n std::string res;\n res += \"\\\"\";\n res += m_name;\n if (oneline) {\n res += \"\\\":\";\n } else {\n res += \"\\\": \";\n }\n switch (m_type) {\n case Type::STR:\n return res + \"\\\"str\\\"\";\n case Type::STR_HEX:\n return res + \"\\\"hex\\\"\";\n case Type::NUM:\n return res + \"n\";\n case Type::AMOUNT:\n return res + \"amount\";\n case Type::BOOL:\n return res + \"bool\";\n case Type::ARR:\n res += \"[\";\n for (const auto& i : m_inner) {\n res += i.ToString(oneline) + \",\";\n }\n return res + \"...]\";\n case Type::OBJ:\n case Type::OBJ_USER_KEYS:\n \/\/ Currently unused, so avoid writing dead code\n assert(false);\n\n \/\/ no default case, so the compiler can warn about missing cases\n }\n assert(false);\n}\n\nstd::string RPCArg::ToString(const bool oneline) const\n{\n if (oneline && !m_oneline_description.empty()) return m_oneline_description;\n\n switch (m_type) {\n case Type::STR_HEX:\n case Type::STR: {\n return \"\\\"\" + m_name + \"\\\"\";\n }\n case Type::NUM:\n case Type::AMOUNT:\n case Type::BOOL: {\n return m_name;\n }\n case Type::OBJ:\n case Type::OBJ_USER_KEYS: {\n std::string res;\n for (size_t i = 0; i < m_inner.size();) {\n res += m_inner[i].ToStringObj(oneline);\n if (++i < m_inner.size()) res += \",\";\n }\n if (m_type == Type::OBJ) {\n return \"{\" + res + \"}\";\n } else {\n return \"{\" + res + \",...}\";\n }\n }\n case Type::ARR: {\n std::string res;\n for (const auto& i : m_inner) {\n res += i.ToString(oneline) + \",\";\n }\n return \"[\" + res + \"...]\";\n }\n\n \/\/ no default case, so the compiler can warn about missing cases\n }\n assert(false);\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ui\/gfx\/gtk_preserve_window.h\"\n\n#include \n#include \n#include \n#include \n\nG_BEGIN_DECLS\n\n#define GTK_PRESERVE_WINDOW_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), \\\n GTK_TYPE_PRESERVE_WINDOW, \\\n GtkPreserveWindowPrivate))\n\ntypedef struct _GtkPreserveWindowPrivate GtkPreserveWindowPrivate;\n\nstruct _GtkPreserveWindowPrivate {\n \/\/ If true, don't create\/destroy windows on realize\/unrealize.\n gboolean preserve_window;\n\n \/\/ Whether or not we delegate the resize of the GdkWindow\n \/\/ to someone else.\n gboolean delegate_resize;\n};\n\nG_DEFINE_TYPE(GtkPreserveWindow, gtk_preserve_window, GTK_TYPE_FIXED)\n\nstatic void gtk_preserve_window_destroy(GtkObject* object);\nstatic void gtk_preserve_window_realize(GtkWidget* widget);\nstatic void gtk_preserve_window_unrealize(GtkWidget* widget);\nstatic void gtk_preserve_window_size_allocate(GtkWidget* widget,\n GtkAllocation* allocation);\n\nstatic void gtk_preserve_window_class_init(GtkPreserveWindowClass *klass) {\n GtkWidgetClass* widget_class = reinterpret_cast(klass);\n widget_class->realize = gtk_preserve_window_realize;\n widget_class->unrealize = gtk_preserve_window_unrealize;\n widget_class->size_allocate = gtk_preserve_window_size_allocate;\n\n GtkObjectClass* object_class = reinterpret_cast(klass);\n object_class->destroy = gtk_preserve_window_destroy;\n\n GObjectClass* gobject_class = G_OBJECT_CLASS(klass);\n g_type_class_add_private(gobject_class, sizeof(GtkPreserveWindowPrivate));\n}\n\nstatic void gtk_preserve_window_init(GtkPreserveWindow* widget) {\n GtkPreserveWindowPrivate* priv = GTK_PRESERVE_WINDOW_GET_PRIVATE(widget);\n priv->preserve_window = FALSE;\n\n \/\/ These widgets always have their own window.\n gtk_fixed_set_has_window(GTK_FIXED(widget), TRUE);\n}\n\nGtkWidget* gtk_preserve_window_new() {\n return GTK_WIDGET(g_object_new(GTK_TYPE_PRESERVE_WINDOW, NULL));\n}\n\nstatic void gtk_preserve_window_destroy(GtkObject* object) {\n GtkWidget* widget = reinterpret_cast(object);\n GtkPreserveWindowPrivate* priv = GTK_PRESERVE_WINDOW_GET_PRIVATE(widget);\n\n if (widget->window) {\n gdk_window_set_user_data(widget->window, NULL);\n \/\/ If the window is preserved, someone else must destroy it.\n if (!priv->preserve_window)\n gdk_window_destroy(widget->window);\n widget->window = NULL;\n }\n\n GTK_OBJECT_CLASS(gtk_preserve_window_parent_class)->destroy(object);\n}\n\nstatic void gtk_preserve_window_realize(GtkWidget* widget) {\n g_return_if_fail(GTK_IS_PRESERVE_WINDOW(widget));\n\n if (widget->window) {\n gdk_window_reparent(widget->window,\n gtk_widget_get_parent_window(widget),\n widget->allocation.x,\n widget->allocation.y);\n widget->style = gtk_style_attach(widget->style, widget->window);\n gtk_style_set_background(widget->style, widget->window, GTK_STATE_NORMAL);\n\n gint event_mask = gtk_widget_get_events(widget);\n event_mask |= GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK;\n gdk_window_set_events(widget->window, (GdkEventMask) event_mask);\n gdk_window_set_user_data(widget->window, widget);\n\n \/\/ Deprecated as of GTK 2.22. Used for compatibility.\n \/\/ It should be: gtk_widget_set_realized(widget, TRUE)\n GTK_WIDGET_SET_FLAGS(widget, GTK_REALIZED);\n } else {\n GTK_WIDGET_CLASS(gtk_preserve_window_parent_class)->realize(widget);\n }\n}\n\nstatic void gtk_preserve_window_unrealize(GtkWidget* widget) {\n g_return_if_fail(GTK_IS_PRESERVE_WINDOW(widget));\n\n GtkPreserveWindowPrivate* priv = GTK_PRESERVE_WINDOW_GET_PRIVATE(widget);\n if (priv->preserve_window) {\n GtkWidgetClass* widget_class =\n GTK_WIDGET_CLASS(gtk_preserve_window_parent_class);\n GtkContainerClass* container_class =\n GTK_CONTAINER_CLASS(gtk_preserve_window_parent_class);\n\n \/\/ Deprecated as of GTK 2.22. Used for compatibility.\n \/\/ It should be: gtk_widget_get_mapped()\n if (GTK_WIDGET_MAPPED(widget)) {\n widget_class->unmap(widget);\n\n \/\/ Deprecated as of GTK 2.22. Used for compatibility.\n \/\/ It should be: gtk_widget_set_mapped(widget, FALSE)\n GTK_WIDGET_UNSET_FLAGS(widget, GTK_MAPPED);\n }\n\n \/\/ This is the behavior from GtkWidget, inherited by GtkFixed.\n \/\/ It is unclear why we should not call the potentially overridden\n \/\/ unrealize method (via the callback), but doing so causes errors.\n container_class->forall(\n GTK_CONTAINER(widget), FALSE,\n reinterpret_cast(gtk_widget_unrealize), NULL);\n\n gtk_style_detach(widget->style);\n gdk_window_reparent(widget->window, gdk_get_default_root_window(), 0, 0);\n gtk_selection_remove_all(widget);\n gdk_window_set_user_data(widget->window, NULL);\n\n \/\/ Deprecated as of GTK 2.22. Used for compatibility.\n \/\/ It should be: gtk_widget_set_realized(widget, FALSE)\n GTK_WIDGET_UNSET_FLAGS(widget, GTK_REALIZED);\n } else {\n GTK_WIDGET_CLASS(gtk_preserve_window_parent_class)->unrealize(widget);\n }\n}\n\ngboolean gtk_preserve_window_get_preserve(GtkPreserveWindow* window) {\n g_return_val_if_fail(GTK_IS_PRESERVE_WINDOW(window), FALSE);\n GtkPreserveWindowPrivate* priv = GTK_PRESERVE_WINDOW_GET_PRIVATE(window);\n\n return priv->preserve_window;\n}\n\nvoid gtk_preserve_window_set_preserve(GtkPreserveWindow* window,\n gboolean value) {\n g_return_if_fail(GTK_IS_PRESERVE_WINDOW(window));\n GtkPreserveWindowPrivate* priv = GTK_PRESERVE_WINDOW_GET_PRIVATE(window);\n priv->preserve_window = value;\n\n GtkWidget* widget = GTK_WIDGET(window);\n if (value && !widget->window) {\n GdkWindowAttr attributes;\n gint attributes_mask;\n\n \/\/ We may not know the width and height, so we rely on the fact\n \/\/ that a size-allocation will resize it later.\n attributes.width = 1;\n attributes.height = 1;\n\n attributes.window_type = GDK_WINDOW_CHILD;\n attributes.wclass = GDK_INPUT_OUTPUT;\n\n attributes.visual = gtk_widget_get_visual(widget);\n attributes.colormap = gtk_widget_get_colormap(widget);\n\n attributes_mask = GDK_WA_VISUAL | GDK_WA_COLORMAP;\n widget->window = gdk_window_new(\n gdk_get_default_root_window(), &attributes, attributes_mask);\n } else if (!value && widget->window && !GTK_WIDGET_REALIZED(widget)) {\n gdk_window_destroy(widget->window);\n widget->window = NULL;\n }\n}\n\nvoid gtk_preserve_window_size_allocate(GtkWidget* widget,\n GtkAllocation* allocation) {\n g_return_if_fail(GTK_IS_PRESERVE_WINDOW(widget));\n GtkPreserveWindowPrivate* priv = GTK_PRESERVE_WINDOW_GET_PRIVATE(widget);\n\n if (priv->delegate_resize) {\n \/\/ Just update the state. Someone else will gdk_window_resize the\n \/\/ associated GdkWindow.\n widget->allocation = *allocation;\n } else {\n GTK_WIDGET_CLASS(gtk_preserve_window_parent_class)->size_allocate(\n widget, allocation);\n }\n}\n\nvoid gtk_preserve_window_delegate_resize(GtkPreserveWindow* widget,\n gboolean delegate) {\n GtkPreserveWindowPrivate* priv = GTK_PRESERVE_WINDOW_GET_PRIVATE(widget);\n priv->delegate_resize = delegate;\n}\n\nG_END_DECLS\nTo prevent damage to the back-buffer, it's only necessary to defer resize.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ui\/gfx\/gtk_preserve_window.h\"\n\n#include \n#include \n#include \n#include \n\nG_BEGIN_DECLS\n\n#define GTK_PRESERVE_WINDOW_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), \\\n GTK_TYPE_PRESERVE_WINDOW, \\\n GtkPreserveWindowPrivate))\n\ntypedef struct _GtkPreserveWindowPrivate GtkPreserveWindowPrivate;\n\nstruct _GtkPreserveWindowPrivate {\n \/\/ If true, don't create\/destroy windows on realize\/unrealize.\n gboolean preserve_window;\n\n \/\/ Whether or not we delegate the resize of the GdkWindow\n \/\/ to someone else.\n gboolean delegate_resize;\n};\n\nG_DEFINE_TYPE(GtkPreserveWindow, gtk_preserve_window, GTK_TYPE_FIXED)\n\nstatic void gtk_preserve_window_destroy(GtkObject* object);\nstatic void gtk_preserve_window_realize(GtkWidget* widget);\nstatic void gtk_preserve_window_unrealize(GtkWidget* widget);\nstatic void gtk_preserve_window_size_allocate(GtkWidget* widget,\n GtkAllocation* allocation);\n\nstatic void gtk_preserve_window_class_init(GtkPreserveWindowClass *klass) {\n GtkWidgetClass* widget_class = reinterpret_cast(klass);\n widget_class->realize = gtk_preserve_window_realize;\n widget_class->unrealize = gtk_preserve_window_unrealize;\n widget_class->size_allocate = gtk_preserve_window_size_allocate;\n\n GtkObjectClass* object_class = reinterpret_cast(klass);\n object_class->destroy = gtk_preserve_window_destroy;\n\n GObjectClass* gobject_class = G_OBJECT_CLASS(klass);\n g_type_class_add_private(gobject_class, sizeof(GtkPreserveWindowPrivate));\n}\n\nstatic void gtk_preserve_window_init(GtkPreserveWindow* widget) {\n GtkPreserveWindowPrivate* priv = GTK_PRESERVE_WINDOW_GET_PRIVATE(widget);\n priv->preserve_window = FALSE;\n\n \/\/ These widgets always have their own window.\n gtk_fixed_set_has_window(GTK_FIXED(widget), TRUE);\n}\n\nGtkWidget* gtk_preserve_window_new() {\n return GTK_WIDGET(g_object_new(GTK_TYPE_PRESERVE_WINDOW, NULL));\n}\n\nstatic void gtk_preserve_window_destroy(GtkObject* object) {\n GtkWidget* widget = reinterpret_cast(object);\n GtkPreserveWindowPrivate* priv = GTK_PRESERVE_WINDOW_GET_PRIVATE(widget);\n\n if (widget->window) {\n gdk_window_set_user_data(widget->window, NULL);\n \/\/ If the window is preserved, someone else must destroy it.\n if (!priv->preserve_window)\n gdk_window_destroy(widget->window);\n widget->window = NULL;\n }\n\n GTK_OBJECT_CLASS(gtk_preserve_window_parent_class)->destroy(object);\n}\n\nstatic void gtk_preserve_window_realize(GtkWidget* widget) {\n g_return_if_fail(GTK_IS_PRESERVE_WINDOW(widget));\n\n if (widget->window) {\n gdk_window_reparent(widget->window,\n gtk_widget_get_parent_window(widget),\n widget->allocation.x,\n widget->allocation.y);\n widget->style = gtk_style_attach(widget->style, widget->window);\n gtk_style_set_background(widget->style, widget->window, GTK_STATE_NORMAL);\n\n gint event_mask = gtk_widget_get_events(widget);\n event_mask |= GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK;\n gdk_window_set_events(widget->window, (GdkEventMask) event_mask);\n gdk_window_set_user_data(widget->window, widget);\n\n \/\/ Deprecated as of GTK 2.22. Used for compatibility.\n \/\/ It should be: gtk_widget_set_realized(widget, TRUE)\n GTK_WIDGET_SET_FLAGS(widget, GTK_REALIZED);\n } else {\n GTK_WIDGET_CLASS(gtk_preserve_window_parent_class)->realize(widget);\n }\n}\n\nstatic void gtk_preserve_window_unrealize(GtkWidget* widget) {\n g_return_if_fail(GTK_IS_PRESERVE_WINDOW(widget));\n\n GtkPreserveWindowPrivate* priv = GTK_PRESERVE_WINDOW_GET_PRIVATE(widget);\n if (priv->preserve_window) {\n GtkWidgetClass* widget_class =\n GTK_WIDGET_CLASS(gtk_preserve_window_parent_class);\n GtkContainerClass* container_class =\n GTK_CONTAINER_CLASS(gtk_preserve_window_parent_class);\n\n \/\/ Deprecated as of GTK 2.22. Used for compatibility.\n \/\/ It should be: gtk_widget_get_mapped()\n if (GTK_WIDGET_MAPPED(widget)) {\n widget_class->unmap(widget);\n\n \/\/ Deprecated as of GTK 2.22. Used for compatibility.\n \/\/ It should be: gtk_widget_set_mapped(widget, FALSE)\n GTK_WIDGET_UNSET_FLAGS(widget, GTK_MAPPED);\n }\n\n \/\/ This is the behavior from GtkWidget, inherited by GtkFixed.\n \/\/ It is unclear why we should not call the potentially overridden\n \/\/ unrealize method (via the callback), but doing so causes errors.\n container_class->forall(\n GTK_CONTAINER(widget), FALSE,\n reinterpret_cast(gtk_widget_unrealize), NULL);\n\n gtk_style_detach(widget->style);\n gdk_window_reparent(widget->window, gdk_get_default_root_window(), 0, 0);\n gtk_selection_remove_all(widget);\n gdk_window_set_user_data(widget->window, NULL);\n\n \/\/ Deprecated as of GTK 2.22. Used for compatibility.\n \/\/ It should be: gtk_widget_set_realized(widget, FALSE)\n GTK_WIDGET_UNSET_FLAGS(widget, GTK_REALIZED);\n } else {\n GTK_WIDGET_CLASS(gtk_preserve_window_parent_class)->unrealize(widget);\n }\n}\n\ngboolean gtk_preserve_window_get_preserve(GtkPreserveWindow* window) {\n g_return_val_if_fail(GTK_IS_PRESERVE_WINDOW(window), FALSE);\n GtkPreserveWindowPrivate* priv = GTK_PRESERVE_WINDOW_GET_PRIVATE(window);\n\n return priv->preserve_window;\n}\n\nvoid gtk_preserve_window_set_preserve(GtkPreserveWindow* window,\n gboolean value) {\n g_return_if_fail(GTK_IS_PRESERVE_WINDOW(window));\n GtkPreserveWindowPrivate* priv = GTK_PRESERVE_WINDOW_GET_PRIVATE(window);\n priv->preserve_window = value;\n\n GtkWidget* widget = GTK_WIDGET(window);\n if (value && !widget->window) {\n GdkWindowAttr attributes;\n gint attributes_mask;\n\n \/\/ We may not know the width and height, so we rely on the fact\n \/\/ that a size-allocation will resize it later.\n attributes.width = 1;\n attributes.height = 1;\n\n attributes.window_type = GDK_WINDOW_CHILD;\n attributes.wclass = GDK_INPUT_OUTPUT;\n\n attributes.visual = gtk_widget_get_visual(widget);\n attributes.colormap = gtk_widget_get_colormap(widget);\n\n attributes_mask = GDK_WA_VISUAL | GDK_WA_COLORMAP;\n widget->window = gdk_window_new(\n gdk_get_default_root_window(), &attributes, attributes_mask);\n } else if (!value && widget->window && !GTK_WIDGET_REALIZED(widget)) {\n gdk_window_destroy(widget->window);\n widget->window = NULL;\n }\n}\n\nvoid gtk_preserve_window_size_allocate(GtkWidget* widget,\n GtkAllocation* allocation) {\n g_return_if_fail(GTK_IS_PRESERVE_WINDOW(widget));\n GtkPreserveWindowPrivate* priv = GTK_PRESERVE_WINDOW_GET_PRIVATE(widget);\n\n if (priv->delegate_resize) {\n widget->allocation = *allocation;\n \/\/ Only update the position. Someone else will call gdk_window_resize.\n if (GTK_WIDGET_REALIZED(widget)) {\n gdk_window_move(widget->window, allocation->x, allocation->y);\n }\n } else {\n GTK_WIDGET_CLASS(gtk_preserve_window_parent_class)->size_allocate(\n widget, allocation);\n }\n}\n\nvoid gtk_preserve_window_delegate_resize(GtkPreserveWindow* widget,\n gboolean delegate) {\n GtkPreserveWindowPrivate* priv = GTK_PRESERVE_WINDOW_GET_PRIVATE(widget);\n priv->delegate_resize = delegate;\n}\n\nG_END_DECLS\n<|endoftext|>"} {"text":"\/*=============================================================================\n\tCopyright (c) 2012-2014 Richard Otis\n\n Distributed under the Boost Software License, Version 1.0. (See accompanying\n file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n=============================================================================*\/\n\n\/\/ subroutines for EZD global minimization\n\/\/ Reference: Maria Emelianenko, Zi-Kui Liu, and Qiang Du.\n\/\/ \"A new algorithm for the automation of phase diagram calculation.\" Computational Materials Science 35.1 (2006): 61-74.\n\n#include \"libgibbs\/include\/libgibbs_pch.hpp\"\n#include \"libgibbs\/include\/optimizer\/utils\/ezd_minimization.hpp\"\n#include \"libgibbs\/include\/compositionset.hpp\"\n#include \"libgibbs\/include\/constraint.hpp\"\n#include \"libgibbs\/include\/models.hpp\"\n#include \"libgibbs\/include\/optimizer\/halton.hpp\"\n#include \"libgibbs\/include\/optimizer\/utils\/ndsimplex.hpp\"\n#include \"libgibbs\/include\/utils\/cholesky.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Optimizer {\n\n\/\/ TODO: Should this be a member function of GibbsOpt?\n\/\/ The function calling LocateMinima definitely should be at least (needs access to all CompositionSets)\n\/\/ LocateMinima finds all of the minima for a given phase's Gibbs energy\n\/\/ In addition to allowing us to choose a better starting point, this will allow for automatic miscibility gap detection\nvoid LocateMinima(\n\t\tCompositionSet const &phase,\n\t\tsublattice_set const &sublset,\n\t\tevalconditions const& conditions,\n\t\tconst std::size_t depth \/\/ depth tracking for recursion\n\t\t) {\n\tconstexpr const std::size_t grid_points_per_axis = 10; \/\/ TODO: make this user-configurable\n\tusing namespace boost::numeric::ublas;\n\ttypedef std::vector PointType;\n\t\n\tconst std::size_t k = 2;\n\tconst std::size_t d = 2;\n\tboost::numeric::ublas::vector vertices(k);\n\tfor (auto i = 0; i < k; ++i) {\n\t vertices(i) = 1.0 \/ (double)k;\n\t vertices(i) \/= (double)k;\n\t}\n\tauto colorscheme = color_schemes(k,d);\n\tfor (auto i = colorscheme.begin(); i != colorscheme.end(); ++i) {\n\t std::cout << \"n = \" << std::distance(colorscheme.begin(),i) << std::endl;\n\t std::cout << *i << std::endl;\n\t std::cout << prod(vertices,trans(*i)) << std::endl;\n\t}\n\treturn;\n\n\t\/\/ EZD Global Minimization (Emelianenko et al., 2006)\n\t\/\/ For depth = 1: FIND CONCAVITY REGIONS\n\tif (depth == 1) {\n\t\tstd::vector points;\n\t\tstd::vector components_in_sublattice;\n\n\t\t\/\/ Get the first sublattice for this phase\n\t\tboost::multi_index::index::type::iterator ic0,ic1;\n\t\tint sublindex = 0;\n\t\tic0 = boost::multi_index::get(sublset).lower_bound(boost::make_tuple(phase.name(), sublindex));\n\t\tic1 = boost::multi_index::get(sublset).upper_bound(boost::make_tuple(phase.name(), sublindex));;\n\n\t\t\/\/ (1) Sample some points on the domain using NDSimplex\n\t\t\/\/ Because the grid is uniform, we can assume that each point is the center of an N-simplex\n\n\t\t\/\/ Determine number of components in each sublattice\n\t\twhile (ic0 != ic1) {\n\t\t\tconst std::size_t number_of_species = std::distance(ic0,ic1);\n\t\t\tif (number_of_species > 0) components_in_sublattice.push_back(number_of_species);\n\t\t\t\/\/ Next sublattice\n\t\t\t++sublindex;\n\t\t\tic0 = boost::multi_index::get(sublset).lower_bound(boost::make_tuple(phase.name(), sublindex));\n\t\t\tic1 = boost::multi_index::get(sublset).end();\n\t\t}\n\n\t\tpoints = NDSimplex::lattice_complex(components_in_sublattice, 20);\n\n\n\t\tfor (auto pt : points) {\n\t\t\tstd::cout << \"(\";\n\t\t\tfor (auto i = pt.begin(); i != pt.end(); ++i) {\n\t\t\t\tstd::cout << *i;\n\t\t\t\tif (std::distance(i,pt.end()) > 1) std::cout << \",\";\n\t\t\t}\n\t\t\tstd::cout << \")\" << std::endl;\n\t\t}\n\n\t\tPointType minpoint (points[0].size());\n\t\tdouble gradient_magnitude = std::numeric_limits::max();\n\t\t\/\/ (2) Calculate the Lagrangian Hessian for all sampled points\n\t\tfor (auto pt : points) {\n\t\t\tif (pt.size() == 0) continue; \/\/ skip empty (invalid) points\n\t\t\tsymmetric_matrix Hessian(zero_matrix(pt.size(),pt.size()));\n\t\t\ttry {\n\t\t\t\tHessian = phase.evaluate_objective_hessian_matrix(conditions, phase.get_variable_map(), pt);\n\t\t\t}\n\t\t\tcatch (boost::exception &e) {\n\t\t\t\tstd::cout << boost::diagnostic_information(e);\n\t\t\t\tthrow;\n\t\t\t}\n\t\t\tcatch (std::exception &e) {\n\t\t\t\tstd::cout << e.what();\n\t\t\t\tthrow;\n\t\t\t}\n\t\t\t\/\/std::cout << \"Hessian: \" << Hessian << std::endl;\n\t\t\t\/\/ NOTE: For this calculation we consider only the linear constraints for an isolated phase (e.g., site fraction balances)\n\t\t\t\/\/ (3) Save all points for which the Lagrangian Hessian is positive definite in the null space of the constraint gradient matrix\n\t\t\t\/\/ NOTE: This is the projected Hessian method (Nocedal and Wright, 2006, ch. 12.4, p.349)\n\t\t\t\/\/ But how do I choose the Lagrange multipliers for all the constraints? Can I calculate them?\n\t\t\t\/\/ The answer is that, because the constraints are linear, there is no constraint contribution to the Hessian.\n\t\t\t\/\/ That means that the Hessian of the Lagrangian is just the Hessian of the objective function.\n\t\t\tconst std::size_t Zcolumns = pt.size() - phase.get_constraints().size();\n\t\t\t\/\/ Z is the constraint null space matrix = phase.get_constraint_null_space_matrix()\n\t\t\t\/\/ (a) Set Hproj = transpose(Z)*(L'')*Z\n\t\t\tmatrix Hproj(pt.size(), Zcolumns);\n\t\t\tHproj = prod(trans(phase.get_constraint_null_space_matrix()),\n\t\t\t\t\tmatrix(prod(Hessian,phase.get_constraint_null_space_matrix())));\n\t\t\t\/\/std::cout << \"Hproj: \" << Hproj << std::endl;\n\t\t\t\/\/ (b) Verify that all diagonal elements of Hproj are strictly positive; if not, remove this point from consideration\n\t\t\t\/\/ NOTE: This is a necessary but not sufficient condition that a matrix be positive definite, and it's easy to check\n\t\t\t\/\/ Reference: Carlen and Carvalho, 2007, p. 148, Eq. 5.12\n\t\t\t\/\/ (c) Attempt a Cholesky factorization of Hproj; will only succeed if matrix is positive definite\n\t\t\tconst bool is_positive_definite = cholesky_factorize(Hproj);\n\t\t\t\/\/ (d) If it succeeds, save this point; else, remove it\n\t\t\tif (is_positive_definite) {\n\t\t\t\tstd::cout << pt[0] << \" \";\n\t\t\t\tdouble obj = phase.evaluate_objective(conditions, phase.get_variable_map(), &pt[0]);\n\t\t\t\tstd::cout << obj << std::endl;\n\t\t\t\tstd::vector gradient = phase.evaluate_internal_objective_gradient(conditions, &pt[0]);\n\t\t\t\tdouble mag = 0;\n\t\t\t\tfor (auto i = gradient.begin(); i != gradient.end(); ++i) {\n\t\t\t\t\t\/\/std::cout << \"gradient[\" << std::distance(gradient.begin(),i) << \"] = \" << *i << std::endl;\n\t\t\t\t\tmag += pow(*i,2);\n\t\t\t\t}\n\t\t\t\tif (mag < gradient_magnitude) {\n\t\t\t\t\tgradient_magnitude = mag;\n\t\t\t\t\tminpoint = pt;\n\t\t\t\t\tstd::cout << \"new minpoint: \";\n\t\t\t\t\tfor (auto i = minpoint.begin(); i != minpoint.end(); ++i) {\n\t\t\t\t\t\tstd::cout << *i;\n\t\t\t\t\t\tif (std::distance(i,minpoint.end()) > 1) std::cout << \",\";\n\t\t\t\t\t}\n\t\t\t\t\tstd::cout << \" gradient sq: \" << gradient_magnitude << std::endl;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\n\t\t\t}\n\t\t\t\/\/ (4) For each saved point, send to next depth\n\t\t}\n\t}\n\t\/\/ For depth > 1: FIND MINIMA\n\telse if (depth > 1) {\n\t\t\/\/ (1) Sample some points on the domain using NDGrid (probably separate function)\n\t\t\/\/ (2) Calculate the objective gradient (f') for all sampled points\n\t\t\/\/ Note: This can be done by making use of the first-order KKT conditions to estimate the Lagrange multipliers.\n\t\t\/\/ (3) Find the point (z) with the minimum magnitude of L'\n\t\t\/\/ (4) If that magnitude is less than some defined epsilon, or we've hit max_depth, return z as a minimum\n\t\t\/\/ Else use N-cube assumption to define new domain around z and send to next depth (return minima from that)\n\t}\n\telse {\n\t\t\/\/ invalid depth; throw exception\n\t}\n}\n\n}\nTest code for calculating simplex subdivision from given vertices. Works for a simple case. Now all of this needs to get properly wrapped into objects.\/*=============================================================================\n\tCopyright (c) 2012-2014 Richard Otis\n\n Distributed under the Boost Software License, Version 1.0. (See accompanying\n file LICENSE_1_0.txt or copy at http:\/\/www.boost.org\/LICENSE_1_0.txt)\n=============================================================================*\/\n\n\/\/ subroutines for EZD global minimization\n\/\/ Reference: Maria Emelianenko, Zi-Kui Liu, and Qiang Du.\n\/\/ \"A new algorithm for the automation of phase diagram calculation.\" Computational Materials Science 35.1 (2006): 61-74.\n\n#include \"libgibbs\/include\/libgibbs_pch.hpp\"\n#include \"libgibbs\/include\/optimizer\/utils\/ezd_minimization.hpp\"\n#include \"libgibbs\/include\/compositionset.hpp\"\n#include \"libgibbs\/include\/constraint.hpp\"\n#include \"libgibbs\/include\/models.hpp\"\n#include \"libgibbs\/include\/optimizer\/halton.hpp\"\n#include \"libgibbs\/include\/optimizer\/utils\/ndsimplex.hpp\"\n#include \"libgibbs\/include\/utils\/cholesky.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Optimizer {\n\n\/\/ TODO: Should this be a member function of GibbsOpt?\n\/\/ The function calling LocateMinima definitely should be at least (needs access to all CompositionSets)\n\/\/ LocateMinima finds all of the minima for a given phase's Gibbs energy\n\/\/ In addition to allowing us to choose a better starting point, this will allow for automatic miscibility gap detection\nvoid LocateMinima(\n\t\tCompositionSet const &phase,\n\t\tsublattice_set const &sublset,\n\t\tevalconditions const& conditions,\n\t\tconst std::size_t depth \/\/ depth tracking for recursion\n\t\t) {\n\tconstexpr const std::size_t grid_points_per_axis = 10; \/\/ TODO: make this user-configurable\n\tusing namespace boost::numeric::ublas;\n\ttypedef std::vector PointType;\n\t\n\tconst std::size_t k = 2;\n\tconst std::size_t d = 2;\n\tboost::numeric::ublas::matrix vertex_coords(d,d+1);\n\t\/\/ test specifically for 2^2 subdivision of the 2-simplex (unit simplex)\n\t\/\/ NOTE: Will need to modify to handle automatic calculation of the dependent component\n\tvertex_coords(0,0) = 0;\n\tvertex_coords(1,0) = 0;\n\tvertex_coords(0,1) = 0;\n\tvertex_coords(1,1) = 1;\n\tvertex_coords(0,2) = 1;\n\tvertex_coords(1,2) = 0;\n\tconst auto colorscheme = color_schemes(k,d);\n\tfor (auto i = colorscheme.begin(); i != colorscheme.end(); ++i) {\n\t std::cout << \"n = \" << std::distance(colorscheme.begin(),i) << std::endl;\n\t boost::numeric::ublas::matrix simplex_coords = zero_matrix(d,d+1);\n\t for (auto j = 0; j < d+1; ++j) {\n\t std::cout << \"j = \" << j << std::endl;\n\t matrix_column> p (simplex_coords,j);\n\t for (auto m = 0; m < k; ++m) {\n\t std::cout << \"m = \" << m << std::endl;\n\t const matrix_column> s(vertex_coords,(*i)(m,j));\n\t p += (s \/ (double) k);\n\t }\n\t }\n\t std::cout << *i << std::endl;\n\t std::cout << simplex_coords << std::endl;\n\t}\n\treturn;\n\n\t\/\/ EZD Global Minimization (Emelianenko et al., 2006)\n\t\/\/ For depth = 1: FIND CONCAVITY REGIONS\n\tif (depth == 1) {\n\t\tstd::vector points;\n\t\tstd::vector components_in_sublattice;\n\n\t\t\/\/ Get the first sublattice for this phase\n\t\tboost::multi_index::index::type::iterator ic0,ic1;\n\t\tint sublindex = 0;\n\t\tic0 = boost::multi_index::get(sublset).lower_bound(boost::make_tuple(phase.name(), sublindex));\n\t\tic1 = boost::multi_index::get(sublset).upper_bound(boost::make_tuple(phase.name(), sublindex));;\n\n\t\t\/\/ (1) Sample some points on the domain using NDSimplex\n\t\t\/\/ Because the grid is uniform, we can assume that each point is the center of an N-simplex\n\n\t\t\/\/ Determine number of components in each sublattice\n\t\twhile (ic0 != ic1) {\n\t\t\tconst std::size_t number_of_species = std::distance(ic0,ic1);\n\t\t\tif (number_of_species > 0) components_in_sublattice.push_back(number_of_species);\n\t\t\t\/\/ Next sublattice\n\t\t\t++sublindex;\n\t\t\tic0 = boost::multi_index::get(sublset).lower_bound(boost::make_tuple(phase.name(), sublindex));\n\t\t\tic1 = boost::multi_index::get(sublset).end();\n\t\t}\n\n\t\tpoints = NDSimplex::lattice_complex(components_in_sublattice, 20);\n\n\n\t\tfor (auto pt : points) {\n\t\t\tstd::cout << \"(\";\n\t\t\tfor (auto i = pt.begin(); i != pt.end(); ++i) {\n\t\t\t\tstd::cout << *i;\n\t\t\t\tif (std::distance(i,pt.end()) > 1) std::cout << \",\";\n\t\t\t}\n\t\t\tstd::cout << \")\" << std::endl;\n\t\t}\n\n\t\tPointType minpoint (points[0].size());\n\t\tdouble gradient_magnitude = std::numeric_limits::max();\n\t\t\/\/ (2) Calculate the Lagrangian Hessian for all sampled points\n\t\tfor (auto pt : points) {\n\t\t\tif (pt.size() == 0) continue; \/\/ skip empty (invalid) points\n\t\t\tsymmetric_matrix Hessian(zero_matrix(pt.size(),pt.size()));\n\t\t\ttry {\n\t\t\t\tHessian = phase.evaluate_objective_hessian_matrix(conditions, phase.get_variable_map(), pt);\n\t\t\t}\n\t\t\tcatch (boost::exception &e) {\n\t\t\t\tstd::cout << boost::diagnostic_information(e);\n\t\t\t\tthrow;\n\t\t\t}\n\t\t\tcatch (std::exception &e) {\n\t\t\t\tstd::cout << e.what();\n\t\t\t\tthrow;\n\t\t\t}\n\t\t\t\/\/std::cout << \"Hessian: \" << Hessian << std::endl;\n\t\t\t\/\/ NOTE: For this calculation we consider only the linear constraints for an isolated phase (e.g., site fraction balances)\n\t\t\t\/\/ (3) Save all points for which the Lagrangian Hessian is positive definite in the null space of the constraint gradient matrix\n\t\t\t\/\/ NOTE: This is the projected Hessian method (Nocedal and Wright, 2006, ch. 12.4, p.349)\n\t\t\t\/\/ But how do I choose the Lagrange multipliers for all the constraints? Can I calculate them?\n\t\t\t\/\/ The answer is that, because the constraints are linear, there is no constraint contribution to the Hessian.\n\t\t\t\/\/ That means that the Hessian of the Lagrangian is just the Hessian of the objective function.\n\t\t\tconst std::size_t Zcolumns = pt.size() - phase.get_constraints().size();\n\t\t\t\/\/ Z is the constraint null space matrix = phase.get_constraint_null_space_matrix()\n\t\t\t\/\/ (a) Set Hproj = transpose(Z)*(L'')*Z\n\t\t\tmatrix Hproj(pt.size(), Zcolumns);\n\t\t\tHproj = prod(trans(phase.get_constraint_null_space_matrix()),\n\t\t\t\t\tmatrix(prod(Hessian,phase.get_constraint_null_space_matrix())));\n\t\t\t\/\/std::cout << \"Hproj: \" << Hproj << std::endl;\n\t\t\t\/\/ (b) Verify that all diagonal elements of Hproj are strictly positive; if not, remove this point from consideration\n\t\t\t\/\/ NOTE: This is a necessary but not sufficient condition that a matrix be positive definite, and it's easy to check\n\t\t\t\/\/ Reference: Carlen and Carvalho, 2007, p. 148, Eq. 5.12\n\t\t\t\/\/ (c) Attempt a Cholesky factorization of Hproj; will only succeed if matrix is positive definite\n\t\t\tconst bool is_positive_definite = cholesky_factorize(Hproj);\n\t\t\t\/\/ (d) If it succeeds, save this point; else, remove it\n\t\t\tif (is_positive_definite) {\n\t\t\t\tstd::cout << pt[0] << \" \";\n\t\t\t\tdouble obj = phase.evaluate_objective(conditions, phase.get_variable_map(), &pt[0]);\n\t\t\t\tstd::cout << obj << std::endl;\n\t\t\t\tstd::vector gradient = phase.evaluate_internal_objective_gradient(conditions, &pt[0]);\n\t\t\t\tdouble mag = 0;\n\t\t\t\tfor (auto i = gradient.begin(); i != gradient.end(); ++i) {\n\t\t\t\t\t\/\/std::cout << \"gradient[\" << std::distance(gradient.begin(),i) << \"] = \" << *i << std::endl;\n\t\t\t\t\tmag += pow(*i,2);\n\t\t\t\t}\n\t\t\t\tif (mag < gradient_magnitude) {\n\t\t\t\t\tgradient_magnitude = mag;\n\t\t\t\t\tminpoint = pt;\n\t\t\t\t\tstd::cout << \"new minpoint: \";\n\t\t\t\t\tfor (auto i = minpoint.begin(); i != minpoint.end(); ++i) {\n\t\t\t\t\t\tstd::cout << *i;\n\t\t\t\t\t\tif (std::distance(i,minpoint.end()) > 1) std::cout << \",\";\n\t\t\t\t\t}\n\t\t\t\t\tstd::cout << \" gradient sq: \" << gradient_magnitude << std::endl;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\n\t\t\t}\n\t\t\t\/\/ (4) For each saved point, send to next depth\n\t\t}\n\t}\n\t\/\/ For depth > 1: FIND MINIMA\n\telse if (depth > 1) {\n\t\t\/\/ (1) Sample some points on the domain using NDGrid (probably separate function)\n\t\t\/\/ (2) Calculate the objective gradient (f') for all sampled points\n\t\t\/\/ Note: This can be done by making use of the first-order KKT conditions to estimate the Lagrange multipliers.\n\t\t\/\/ (3) Find the point (z) with the minimum magnitude of L'\n\t\t\/\/ (4) If that magnitude is less than some defined epsilon, or we've hit max_depth, return z as a minimum\n\t\t\/\/ Else use N-cube assumption to define new domain around z and send to next depth (return minima from that)\n\t}\n\telse {\n\t\t\/\/ invalid depth; throw exception\n\t}\n}\n\n}\n<|endoftext|>"} {"text":"\/* Copyright 2014 Jonas Platte\n *\n * This file is part of Cyvasse Online.\n *\n * Cyvasse Online is free software: you can redistribute it and\/or modify it under the\n * terms of the GNU Affero General Public License as published by the Free Software Foundation,\n * either version 3 of the License, or (at your option) any later version.\n *\n * Cyvasse Online is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\n * PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License along with this program.\n * If not, see .\n *\/\n\n#include \"worker.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"b64.hpp\"\n#include \"client_data.hpp\"\n#include \"match_data.hpp\"\n\nusing namespace cyvmath;\nusing namespace cyvws;\n\nusing namespace std;\nusing namespace std::chrono;\nusing namespace websocketpp;\n\nWorker::Worker(SharedServerData& data, send_func_type sendFunc)\n\t: m_data{data}\n\t, m_sendFunc{sendFunc}\n\t, m_thread{bind(&Worker::processMessages, this)}\n{ }\n\nWorker::~Worker()\n{\n\tm_thread.join();\n}\n\nvoid Worker::send(connection_hdl hdl, const string& data)\n{\n\tm_sendFunc(hdl, data, frame::opcode::text);\n}\n\nvoid Worker::send(connection_hdl hdl, const Json::Value& data)\n{\n\tsend(hdl, Json::FastWriter().write(data));\n}\n\nvoid Worker::sendCommErr(connection_hdl hdl, const string& errMsg)\n{\n\tJson::Value data;\n\tdata[\"msgType\"] = \"notification\";\n\tdata[\"notificationData\"][\"type\"] = \"commError\";\n\tdata[\"notificationData\"][\"errMsg\"] = errMsg;\n\n\tsend(hdl, data);\n}\n\nvoid Worker::processMessages()\n{\n\tJson::Reader reader;\n\n\twhile(m_data.running)\n\t{\n\t\tunique_lock jobLock(m_data.jobMtx);\n\n\t\twhile(m_data.running && m_data.jobQueue.empty())\n\t\t\tm_data.jobCond.wait(jobLock);\n\n\t\tif(!m_data.running)\n\t\t\tbreak;\n\n\t\tauto job = m_data.jobQueue.front();\n\t\tm_data.jobQueue.pop();\n\n\t\tjobLock.unlock();\n\n\t\ttry\n\t\t{\n\t\t\t\/\/ Process job\n\t\t\tJson::Value recvdJson;\n\t\t\tif(!reader.parse(job.msg_ptr->get_payload(), recvdJson, false))\n\t\t\t{\n\t\t\t\tsendCommErr(job.conn_hdl, \"Received message is no valid JSON\");\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tset> otherClients;\n\n\t\t\tshared_ptr clientData;\n\n\t\t\tunique_lock matchDataLock(m_data.matchDataMtx, defer_lock); \/\/ don't lock yet\n\t\t\tunique_lock clientDataLock(m_data.clientDataMtx);\n\n\t\t\tauto it1 = m_data.clientData.find(job.conn_hdl);\n\t\t\tif(it1 != m_data.clientData.end())\n\t\t\t{\n\t\t\t\tclientData = it1->second;\n\t\t\t\tclientDataLock.unlock();\n\n\t\t\t\tfor(auto it2 : clientData->getMatchData().getClientDataSets())\n\t\t\t\t\tif(*it2 != *clientData)\n\t\t\t\t\t\totherClients.insert(it2->getConnHdl());\n\t\t\t}\n\t\t\telse clientDataLock.unlock();\n\n\t\t\tswitch(StrToMsgType(recvdJson[\"msgType\"].asString()))\n\t\t\t{\n\t\t\t\tcase MsgType::CHAT_MSG:\n\t\t\t\tcase MsgType::CHAT_MSG_ACK:\n\t\t\t\tcase MsgType::GAME_MSG:\n\t\t\t\tcase MsgType::GAME_MSG_ACK:\n\t\t\t\tcase MsgType::GAME_MSG_ERR:\n\t\t\t\t{\n\t\t\t\t\t\/\/ TODO: Does re-creating the Json string\n\t\t\t\t\t\/\/ from the Json::Value make sense or should\n\t\t\t\t\t\/\/ we just resend the original Json string?\n\t\t\t\t\tstring json = Json::FastWriter().write(recvdJson);\n\n\t\t\t\t\tfor(auto hdl : otherClients)\n\t\t\t\t\t\tsend(hdl, json);\n\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase MsgType::SERVER_REQUEST:\n\t\t\t\t{\n\t\t\t\t\tconst auto& requestData = recvdJson[\"requestData\"];\n\t\t\t\t\tconst auto& param = requestData[\"param\"];\n\n\t\t\t\t\tJson::Value reply;\n\t\t\t\t\treply[\"msgType\"] = MsgTypeToStr(MsgType::SERVER_REPLY);\n\t\t\t\t\t\/\/ cast to int and back to not allow any non-numeral data\n\t\t\t\t\treply[\"msgID\"] = recvdJson[\"msgID\"].asInt();\n\n\t\t\t\t\tauto& replyData = reply[\"replyData\"];\n\t\t\t\t\treplyData[\"success\"] = true;\n\n\t\t\t\t\t\/\/ g++ warns about the default argument for the lambda with -pedantic,\n\t\t\t\t\t\/\/ maybe change how serverReply errors are sent to fix that?\n\t\t\t\t\tauto setError = [&replyData](const string& error, const string& errorDetails = {}) {\n\t\t\t\t\t\treplyData[\"success\"] = false;\n\t\t\t\t\t\treplyData[\"error\"] = error;\n\t\t\t\t\t\treplyData[\"errorDetails\"] = errorDetails;\n\t\t\t\t\t};\n\n\t\t\t\t\tswitch(StrToServerRequestAction(requestData[\"action\"].asString()))\n\t\t\t\t\t{\n\t\t\t\t\t\tcase ServerRequestAction::INIT_COMM:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\/\/ TODO: move to somewhere else (probably cyvws)\n\t\t\t\t\t\t\tconstexpr unsigned short protocolVersionMajor = 1;\n\n\t\t\t\t\t\t\tconst auto& versionStr = requestData[\"param\"][\"protocolVersion\"].asString();\n\n\t\t\t\t\t\t\tif(versionStr.empty())\n\t\t\t\t\t\t\t\tsendCommErr(job.conn_hdl, \"Expected non-empty string value as protocolVersion in initComm\");\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif(stoi(versionStr.substr(0, versionStr.find('.'))) != protocolVersionMajor)\n\t\t\t\t\t\t\t\t\tsetError(\"differingMajorProtVersion\", \"Expected major protocol version \" + to_string(protocolVersionMajor));\n\n\t\t\t\t\t\t\t\tsend(job.conn_hdl, reply);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase ServerRequestAction::CREATE_GAME:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(clientData)\n\t\t\t\t\t\t\t\tsetError(\"This connection is already in use for a running match\");\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tauto ruleSet = StrToRuleSet(param[\"ruleSet\"].asString());\n\t\t\t\t\t\t\t\tauto color = StrToPlayersColor(param[\"color\"].asString());\n\t\t\t\t\t\t\t\tauto random = param[\"random\"].asBool();\n\t\t\t\t\t\t\t\tauto _public = param[\"public\"].asBool();\n\n\t\t\t\t\t\t\t\tauto matchID = newMatchID();\n\t\t\t\t\t\t\t\tauto playerID = newPlayerID();\n\n\t\t\t\t\t\t\t\tauto newMatchData = make_shared(createMatch(ruleSet, matchID));\n\t\t\t\t\t\t\t\tauto newClientData = make_shared(\n\t\t\t\t\t\t\t\t\tcreatePlayer(newMatchData->getMatch(), color, playerID),\n\t\t\t\t\t\t\t\t\tjob.conn_hdl, *newMatchData\n\t\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\t\tnewMatchData->getClientDataSets().insert(newClientData);\n\n\t\t\t\t\t\t\t\tclientDataLock.lock();\n\t\t\t\t\t\t\t\tauto tmp1 = m_data.clientData.emplace(job.conn_hdl, newClientData);\n\t\t\t\t\t\t\t\tclientDataLock.unlock();\n\t\t\t\t\t\t\t\tassert(tmp1.second);\n\n\t\t\t\t\t\t\t\tmatchDataLock.lock();\n\t\t\t\t\t\t\t\tauto tmp2 = m_data.matchData.emplace(matchID, newMatchData);\n\t\t\t\t\t\t\t\tmatchDataLock.unlock();\n\t\t\t\t\t\t\t\tassert(tmp2.second);\n\n\t\t\t\t\t\t\t\treplyData[\"matchID\"] = matchID;\n\t\t\t\t\t\t\t\treplyData[\"playerID\"] = playerID;\n\n\t\t\t\t\t\t\t\t\/\/ TODO\n\t\t\t\t\t\t\t\tthread([=] {\n\t\t\t\t\t\t\t\t\tthis_thread::sleep_for(milliseconds(50));\n\n\t\t\t\t\t\t\t\t\tauto match = createMatch(ruleSet, matchID, random, _public);\n\t\t\t\t\t\t\t\t\tauto player = createPlayer(*match, color, playerID);\n\n\t\t\t\t\t\t\t\t\tcyvdb::MatchManager().addMatch(move(match));\n\t\t\t\t\t\t\t\t\tcyvdb::PlayerManager().addPlayer(move(player));\n\t\t\t\t\t\t\t\t}).detach();\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tsend(job.conn_hdl, reply);\n\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase ServerRequestAction::JOIN_GAME:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmatchDataLock.lock();\n\n\t\t\t\t\t\t\tauto matchIt = m_data.matchData.find(requestData[\"matchID\"].asString());\n\n\t\t\t\t\t\t\tif(clientData)\n\t\t\t\t\t\t\t\tsetError(\"This connection is already in use for a running match\");\n\t\t\t\t\t\t\telse if(matchIt == m_data.matchData.end())\n\t\t\t\t\t\t\t\tsetError(\"Game not found\");\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tauto matchData = matchIt->second;\n\t\t\t\t\t\t\t\tauto matchClients = matchData->getClientDataSets();\n\n\t\t\t\t\t\t\t\tif(matchClients.size() == 0)\n\t\t\t\t\t\t\t\t\tsetError(\"You tried to join a game without an active player, this doesn't work yet\");\n\t\t\t\t\t\t\t\telse if(matchClients.size() > 1)\n\t\t\t\t\t\t\t\t\tsetError(\"This game already has two players\");\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tauto ruleSet = matchData->getMatch().getRuleSet();\n\t\t\t\t\t\t\t\t\tauto color = !(*matchClients.begin())->getPlayer().getColor();\n\t\t\t\t\t\t\t\t\tauto matchID = requestData[\"matchID\"].asString();\n\t\t\t\t\t\t\t\t\tauto playerID = newPlayerID();\n\n\t\t\t\t\t\t\t\t\tauto newClientData = make_shared(\n\t\t\t\t\t\t\t\t\t\tcreatePlayer(matchData->getMatch(), color, playerID),\n\t\t\t\t\t\t\t\t\t\tjob.conn_hdl, *matchData\n\t\t\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\t\t\tmatchData->getClientDataSets().insert(newClientData);\n\n\t\t\t\t\t\t\t\t\tclientDataLock.lock();\n\t\t\t\t\t\t\t\t\tauto tmp = m_data.clientData.emplace(job.conn_hdl, newClientData);\n\t\t\t\t\t\t\t\t\tclientDataLock.unlock();\n\t\t\t\t\t\t\t\t\tassert(tmp.second);\n\n\t\t\t\t\t\t\t\t\treplyData[\"success\"] = true;\n\t\t\t\t\t\t\t\t\treplyData[\"color\"] = PlayersColorToStr(color);\n\t\t\t\t\t\t\t\t\treplyData[\"playerID\"] = playerID;\n\t\t\t\t\t\t\t\t\treplyData[\"ruleSet\"] = RuleSetToStr(ruleSet);\n\n\t\t\t\t\t\t\t\t\tJson::Value notification;\n\t\t\t\t\t\t\t\t\tnotification[\"msgType\"] = \"notification\";\n\n\t\t\t\t\t\t\t\t\tauto& notificationData = notification[\"notificationData\"];\n\t\t\t\t\t\t\t\t\tnotificationData[\"type\"] = NotificationTypeToStr(NotificationType::USER_JOINED);\n\t\t\t\t\t\t\t\t\t\/\/notificationData[\"screenName\"] =\n\t\t\t\t\t\t\t\t\t\/\/notificationData[\"registered\"] =\n\t\t\t\t\t\t\t\t\t\/\/notificationData[\"role\"] =\n\n\t\t\t\t\t\t\t\t\tauto&& msg = Json::FastWriter().write(notification);\n\n\t\t\t\t\t\t\t\t\tfor(auto& clientIt : matchClients)\n\t\t\t\t\t\t\t\t\t\tsend(clientIt->getConnHdl(), msg);\n\n\t\t\t\t\t\t\t\t\tsend(job.conn_hdl, reply);\n\n\t\t\t\t\t\t\t\t\tthread([=] {\n\t\t\t\t\t\t\t\t\t\tthis_thread::sleep_for(milliseconds(50));\n\n\t\t\t\t\t\t\t\t\t\t\/\/ TODO\n\t\t\t\t\t\t\t\t\t\tauto match = createMatch(ruleSet, matchID);\n\t\t\t\t\t\t\t\t\t\tcyvdb::PlayerManager().addPlayer(createPlayer(*match, color, playerID));\n\t\t\t\t\t\t\t\t\t}).detach();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tmatchDataLock.unlock();\n\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase ServerRequestAction::SUBSCR_GAME_LIST_UPDATES:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\/\/ ignore param[\"ruleSet\"] for now\n\t\t\t\t\t\t\tfor (const auto& list : param[\"lists\"])\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tconst auto& listName = list.asString();\n\n\t\t\t\t\t\t\t\tif (listName == \"openRandomGames\")\n\t\t\t\t\t\t\t\t\tm_data.randomGamesSubscribers.insert(job.conn_hdl);\n\t\t\t\t\t\t\t\telse if (listName == \"runningPublicGames\")\n\t\t\t\t\t\t\t\t\tm_data.publicGamesSubscribers.insert(job.conn_hdl);\n\t\t\t\t\t\t\t\t\/\/else\n\t\t\t\t\t\t\t\t\t\/\/ send error message\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase ServerRequestAction::UNSUBSCR_GAME_LIST_UPDATES:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\/\/ ignore param[\"ruleSet\"] for now\n\t\t\t\t\t\t\tfor (const auto& list : param[\"lists\"])\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tconst auto& listName = list.asString();\n\n\t\t\t\t\t\t\t\tif (listName == \"openRandomGames\")\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tconst auto& it = m_data.randomGamesSubscribers.find(job.conn_hdl);\n\n\t\t\t\t\t\t\t\t\tif(it != m_data.randomGamesSubscribers.end())\n\t\t\t\t\t\t\t\t\t\tm_data.randomGamesSubscribers.erase(job.conn_hdl);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse if (listName == \"runningPublicGames\")\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tconst auto& it = m_data.publicGamesSubscribers.find(job.conn_hdl);\n\n\t\t\t\t\t\t\t\t\tif(it != m_data.publicGamesSubscribers.end())\n\t\t\t\t\t\t\t\t\t\tm_data.publicGamesSubscribers.erase(job.conn_hdl);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\/\/else\n\t\t\t\t\t\t\t\t\/\/{\n\t\t\t\t\t\t\t\t\/\/\tsend error message\n\t\t\t\t\t\t\t\t\/\/}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tsendCommErr(job.conn_hdl, \"Unrecognized server request action\");\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase MsgType::NOTIFICATION:\n\t\t\t\tcase MsgType::SERVER_REPLY:\n\t\t\t\t\tsendCommErr(job.conn_hdl, \"This msgType is not intended for client-to-server messages\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase MsgType::UNDEFINED:\n\t\t\t\t\tsendCommErr(job.conn_hdl, \"No valid msgType found\");\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\t\/\/ MsgType enum value valid, implementation lacks support for some feature\n\t\t\t\t\tassert(0);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tcatch(std::error_code& e)\n\t\t{\n\t\t\tcerr << \"Caught a std::error_code\\n-----\\n\" << e << '\\n' << e.message() << endl;\n\t\t}\n\t\tcatch(std::exception& e)\n\t\t{\n\t\t\tcerr << \"Caught a std::exception: \" << e.what() << endl;\n\t\t}\n\t\tcatch(...)\n\t\t{\n\t\t\tcerr << \"Caught an unrecognized error (not derived from either exception or error_code)\" << endl;\n\t\t}\n\t}\n}\n\nstring Worker::newMatchID()\n{\n\tstatic ranlux24 int24Generator(system_clock::now().time_since_epoch().count());\n\n\tstring res;\n\tunique_lock matchDataLock(m_data.matchDataMtx);\n\n\tdo\n\t{\n\t\tres = int24ToB64ID(int24Generator());\n\t}\n\twhile(m_data.matchData.find(res) != m_data.matchData.end());\n\n\tmatchDataLock.unlock();\n\n\treturn res;\n}\n\nstring Worker::newPlayerID()\n{\n\tstatic ranlux48 int48Generator(system_clock::now().time_since_epoch().count());\n\n\t\/\/ TODO\n\treturn int48ToB64ID(int48Generator());\n}\nSome work on the serverRequest error reporting, fixed joinGame requests not getting replies\/* Copyright 2014 Jonas Platte\n *\n * This file is part of Cyvasse Online.\n *\n * Cyvasse Online is free software: you can redistribute it and\/or modify it under the\n * terms of the GNU Affero General Public License as published by the Free Software Foundation,\n * either version 3 of the License, or (at your option) any later version.\n *\n * Cyvasse Online is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\n * PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License along with this program.\n * If not, see .\n *\/\n\n#include \"worker.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"b64.hpp\"\n#include \"client_data.hpp\"\n#include \"match_data.hpp\"\n\nusing namespace cyvmath;\nusing namespace cyvws;\n\nusing namespace std;\nusing namespace std::chrono;\nusing namespace websocketpp;\n\nWorker::Worker(SharedServerData& data, send_func_type sendFunc)\n\t: m_data{data}\n\t, m_sendFunc{sendFunc}\n\t, m_thread{bind(&Worker::processMessages, this)}\n{ }\n\nWorker::~Worker()\n{\n\tm_thread.join();\n}\n\nvoid Worker::send(connection_hdl hdl, const string& data)\n{\n\tm_sendFunc(hdl, data, frame::opcode::text);\n}\n\nvoid Worker::send(connection_hdl hdl, const Json::Value& data)\n{\n\tsend(hdl, Json::FastWriter().write(data));\n}\n\nvoid Worker::sendCommErr(connection_hdl hdl, const string& errMsg)\n{\n\tJson::Value data;\n\tdata[\"msgType\"] = \"notification\";\n\tdata[\"notificationData\"][\"type\"] = \"commError\";\n\tdata[\"notificationData\"][\"errMsg\"] = errMsg;\n\n\tsend(hdl, data);\n}\n\nvoid Worker::processMessages()\n{\n\tJson::Reader reader;\n\n\twhile(m_data.running)\n\t{\n\t\tunique_lock jobLock(m_data.jobMtx);\n\n\t\twhile(m_data.running && m_data.jobQueue.empty())\n\t\t\tm_data.jobCond.wait(jobLock);\n\n\t\tif(!m_data.running)\n\t\t\tbreak;\n\n\t\tauto job = m_data.jobQueue.front();\n\t\tm_data.jobQueue.pop();\n\n\t\tjobLock.unlock();\n\n\t\ttry\n\t\t{\n\t\t\t\/\/ Process job\n\t\t\tJson::Value recvdJson;\n\t\t\tif(!reader.parse(job.msg_ptr->get_payload(), recvdJson, false))\n\t\t\t{\n\t\t\t\tsendCommErr(job.conn_hdl, \"Received message is no valid JSON\");\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tset> otherClients;\n\n\t\t\tshared_ptr clientData;\n\n\t\t\tunique_lock matchDataLock(m_data.matchDataMtx, defer_lock); \/\/ don't lock yet\n\t\t\tunique_lock clientDataLock(m_data.clientDataMtx);\n\n\t\t\tauto it1 = m_data.clientData.find(job.conn_hdl);\n\t\t\tif(it1 != m_data.clientData.end())\n\t\t\t{\n\t\t\t\tclientData = it1->second;\n\t\t\t\tclientDataLock.unlock();\n\n\t\t\t\tfor(auto it2 : clientData->getMatchData().getClientDataSets())\n\t\t\t\t\tif(*it2 != *clientData)\n\t\t\t\t\t\totherClients.insert(it2->getConnHdl());\n\t\t\t}\n\t\t\telse clientDataLock.unlock();\n\n\t\t\tswitch(StrToMsgType(recvdJson[\"msgType\"].asString()))\n\t\t\t{\n\t\t\t\tcase MsgType::CHAT_MSG:\n\t\t\t\tcase MsgType::CHAT_MSG_ACK:\n\t\t\t\tcase MsgType::GAME_MSG:\n\t\t\t\tcase MsgType::GAME_MSG_ACK:\n\t\t\t\tcase MsgType::GAME_MSG_ERR:\n\t\t\t\t{\n\t\t\t\t\t\/\/ TODO: Does re-creating the Json string\n\t\t\t\t\t\/\/ from the Json::Value make sense or should\n\t\t\t\t\t\/\/ we just resend the original Json string?\n\t\t\t\t\tstring json = Json::FastWriter().write(recvdJson);\n\n\t\t\t\t\tfor(auto hdl : otherClients)\n\t\t\t\t\t\tsend(hdl, json);\n\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase MsgType::SERVER_REQUEST:\n\t\t\t\t{\n\t\t\t\t\tconst auto& requestData = recvdJson[\"requestData\"];\n\t\t\t\t\tconst auto& param = requestData[\"param\"];\n\n\t\t\t\t\tJson::Value reply;\n\t\t\t\t\treply[\"msgType\"] = MsgTypeToStr(MsgType::SERVER_REPLY);\n\t\t\t\t\t\/\/ cast to int and back to not allow any non-numeral data\n\t\t\t\t\treply[\"msgID\"] = recvdJson[\"msgID\"].asInt();\n\n\t\t\t\t\tauto& replyData = reply[\"replyData\"];\n\t\t\t\t\treplyData[\"success\"] = true;\n\n\t\t\t\t\t\/\/ g++ warns about the default argument for the lambda with -pedantic,\n\t\t\t\t\t\/\/ maybe change how serverReply errors are sent to fix that?\n\t\t\t\t\tauto setError = [&replyData](const string& error, const string& errorDetails = {}) {\n\t\t\t\t\t\treplyData[\"success\"] = false;\n\t\t\t\t\t\treplyData[\"error\"] = error;\n\n\t\t\t\t\t\tif(!errorDetails.empty())\n\t\t\t\t\t\t\treplyData[\"errorDetails\"] = errorDetails;\n\t\t\t\t\t};\n\n\t\t\t\t\tswitch(StrToServerRequestAction(requestData[\"action\"].asString()))\n\t\t\t\t\t{\n\t\t\t\t\t\tcase ServerRequestAction::INIT_COMM:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\/\/ TODO: move to somewhere else (probably cyvws)\n\t\t\t\t\t\t\tconstexpr unsigned short protocolVersionMajor = 1;\n\n\t\t\t\t\t\t\tconst auto& versionStr = requestData[\"param\"][\"protocolVersion\"].asString();\n\n\t\t\t\t\t\t\tif(versionStr.empty())\n\t\t\t\t\t\t\t\tsendCommErr(job.conn_hdl, \"Expected non-empty string value as protocolVersion in initComm\");\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif(stoi(versionStr.substr(0, versionStr.find('.'))) != protocolVersionMajor)\n\t\t\t\t\t\t\t\t\tsetError(\"differingMajorProtVersion\", \"Expected major protocol version \" + to_string(protocolVersionMajor));\n\n\t\t\t\t\t\t\t\tsend(job.conn_hdl, reply);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase ServerRequestAction::CREATE_GAME:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif(clientData)\n\t\t\t\t\t\t\t\tsetError(\"connInUse\");\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tauto ruleSet = StrToRuleSet(param[\"ruleSet\"].asString());\n\t\t\t\t\t\t\t\tauto color = StrToPlayersColor(param[\"color\"].asString());\n\t\t\t\t\t\t\t\tauto random = param[\"random\"].asBool();\n\t\t\t\t\t\t\t\tauto _public = param[\"public\"].asBool();\n\n\t\t\t\t\t\t\t\tauto matchID = newMatchID();\n\t\t\t\t\t\t\t\tauto playerID = newPlayerID();\n\n\t\t\t\t\t\t\t\tauto newMatchData = make_shared(createMatch(ruleSet, matchID));\n\t\t\t\t\t\t\t\tauto newClientData = make_shared(\n\t\t\t\t\t\t\t\t\tcreatePlayer(newMatchData->getMatch(), color, playerID),\n\t\t\t\t\t\t\t\t\tjob.conn_hdl, *newMatchData\n\t\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\t\tnewMatchData->getClientDataSets().insert(newClientData);\n\n\t\t\t\t\t\t\t\tclientDataLock.lock();\n\t\t\t\t\t\t\t\tauto tmp1 = m_data.clientData.emplace(job.conn_hdl, newClientData);\n\t\t\t\t\t\t\t\tclientDataLock.unlock();\n\t\t\t\t\t\t\t\tassert(tmp1.second);\n\n\t\t\t\t\t\t\t\tmatchDataLock.lock();\n\t\t\t\t\t\t\t\tauto tmp2 = m_data.matchData.emplace(matchID, newMatchData);\n\t\t\t\t\t\t\t\tmatchDataLock.unlock();\n\t\t\t\t\t\t\t\tassert(tmp2.second);\n\n\t\t\t\t\t\t\t\treplyData[\"matchID\"] = matchID;\n\t\t\t\t\t\t\t\treplyData[\"playerID\"] = playerID;\n\n\t\t\t\t\t\t\t\t\/\/ TODO\n\t\t\t\t\t\t\t\tthread([=] {\n\t\t\t\t\t\t\t\t\tthis_thread::sleep_for(milliseconds(50));\n\n\t\t\t\t\t\t\t\t\tauto match = createMatch(ruleSet, matchID, random, _public);\n\t\t\t\t\t\t\t\t\tauto player = createPlayer(*match, color, playerID);\n\n\t\t\t\t\t\t\t\t\tcyvdb::MatchManager().addMatch(move(match));\n\t\t\t\t\t\t\t\t\tcyvdb::PlayerManager().addPlayer(move(player));\n\t\t\t\t\t\t\t\t}).detach();\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tsend(job.conn_hdl, reply);\n\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase ServerRequestAction::JOIN_GAME:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tmatchDataLock.lock();\n\n\t\t\t\t\t\t\tauto matchIt = m_data.matchData.find(requestData[\"matchID\"].asString());\n\n\t\t\t\t\t\t\tif(clientData)\n\t\t\t\t\t\t\t\tsetError(\"connInUse\");\n\t\t\t\t\t\t\telse if(matchIt == m_data.matchData.end())\n\t\t\t\t\t\t\t\tsetError(\"gameNotFound\");\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tauto matchData = matchIt->second;\n\t\t\t\t\t\t\t\tauto matchClients = matchData->getClientDataSets();\n\n\t\t\t\t\t\t\t\tif(matchClients.size() == 0)\n\t\t\t\t\t\t\t\t\tsetError(\"gameEmpty\");\n\t\t\t\t\t\t\t\telse if(matchClients.size() > 1)\n\t\t\t\t\t\t\t\t\tsetError(\"gameFull\");\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tauto ruleSet = matchData->getMatch().getRuleSet();\n\t\t\t\t\t\t\t\t\tauto color = !(*matchClients.begin())->getPlayer().getColor();\n\t\t\t\t\t\t\t\t\tauto matchID = requestData[\"matchID\"].asString();\n\t\t\t\t\t\t\t\t\tauto playerID = newPlayerID();\n\n\t\t\t\t\t\t\t\t\tauto newClientData = make_shared(\n\t\t\t\t\t\t\t\t\t\tcreatePlayer(matchData->getMatch(), color, playerID),\n\t\t\t\t\t\t\t\t\t\tjob.conn_hdl, *matchData\n\t\t\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\t\t\tmatchData->getClientDataSets().insert(newClientData);\n\n\t\t\t\t\t\t\t\t\tclientDataLock.lock();\n\t\t\t\t\t\t\t\t\tauto tmp = m_data.clientData.emplace(job.conn_hdl, newClientData);\n\t\t\t\t\t\t\t\t\tclientDataLock.unlock();\n\t\t\t\t\t\t\t\t\tassert(tmp.second);\n\n\t\t\t\t\t\t\t\t\treplyData[\"success\"] = true;\n\t\t\t\t\t\t\t\t\treplyData[\"color\"] = PlayersColorToStr(color);\n\t\t\t\t\t\t\t\t\treplyData[\"playerID\"] = playerID;\n\t\t\t\t\t\t\t\t\treplyData[\"ruleSet\"] = RuleSetToStr(ruleSet);\n\n\t\t\t\t\t\t\t\t\tJson::Value notification;\n\t\t\t\t\t\t\t\t\tnotification[\"msgType\"] = \"notification\";\n\n\t\t\t\t\t\t\t\t\tauto& notificationData = notification[\"notificationData\"];\n\t\t\t\t\t\t\t\t\tnotificationData[\"type\"] = NotificationTypeToStr(NotificationType::USER_JOINED);\n\t\t\t\t\t\t\t\t\t\/\/notificationData[\"screenName\"] =\n\t\t\t\t\t\t\t\t\t\/\/notificationData[\"registered\"] =\n\t\t\t\t\t\t\t\t\t\/\/notificationData[\"role\"] =\n\n\t\t\t\t\t\t\t\t\tauto&& msg = Json::FastWriter().write(notification);\n\n\t\t\t\t\t\t\t\t\tfor(auto& clientIt : matchClients)\n\t\t\t\t\t\t\t\t\t\tsend(clientIt->getConnHdl(), msg);\n\n\t\t\t\t\t\t\t\t\tsend(job.conn_hdl, reply);\n\n\t\t\t\t\t\t\t\t\tthread([=] {\n\t\t\t\t\t\t\t\t\t\tthis_thread::sleep_for(milliseconds(50));\n\n\t\t\t\t\t\t\t\t\t\t\/\/ TODO\n\t\t\t\t\t\t\t\t\t\tauto match = createMatch(ruleSet, matchID);\n\t\t\t\t\t\t\t\t\t\tcyvdb::PlayerManager().addPlayer(createPlayer(*match, color, playerID));\n\t\t\t\t\t\t\t\t\t}).detach();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tmatchDataLock.unlock();\n\n\t\t\t\t\t\t\tsend(job.conn_hdl, reply);\n\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase ServerRequestAction::SUBSCR_GAME_LIST_UPDATES:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\/\/ ignore param[\"ruleSet\"] for now\n\t\t\t\t\t\t\tfor (const auto& list : param[\"lists\"])\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tconst auto& listName = list.asString();\n\n\t\t\t\t\t\t\t\tif (listName == \"openRandomGames\")\n\t\t\t\t\t\t\t\t\tm_data.randomGamesSubscribers.insert(job.conn_hdl);\n\t\t\t\t\t\t\t\telse if (listName == \"runningPublicGames\")\n\t\t\t\t\t\t\t\t\tm_data.publicGamesSubscribers.insert(job.conn_hdl);\n\t\t\t\t\t\t\t\t\/\/else\n\t\t\t\t\t\t\t\t\t\/\/ send error message\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase ServerRequestAction::UNSUBSCR_GAME_LIST_UPDATES:\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\/\/ ignore param[\"ruleSet\"] for now\n\t\t\t\t\t\t\tfor (const auto& list : param[\"lists\"])\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tconst auto& listName = list.asString();\n\n\t\t\t\t\t\t\t\tif (listName == \"openRandomGames\")\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tconst auto& it = m_data.randomGamesSubscribers.find(job.conn_hdl);\n\n\t\t\t\t\t\t\t\t\tif(it != m_data.randomGamesSubscribers.end())\n\t\t\t\t\t\t\t\t\t\tm_data.randomGamesSubscribers.erase(job.conn_hdl);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse if (listName == \"runningPublicGames\")\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tconst auto& it = m_data.publicGamesSubscribers.find(job.conn_hdl);\n\n\t\t\t\t\t\t\t\t\tif(it != m_data.publicGamesSubscribers.end())\n\t\t\t\t\t\t\t\t\t\tm_data.publicGamesSubscribers.erase(job.conn_hdl);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\/\/else\n\t\t\t\t\t\t\t\t\/\/{\n\t\t\t\t\t\t\t\t\/\/\tsend error message\n\t\t\t\t\t\t\t\t\/\/}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tsendCommErr(job.conn_hdl, \"Unrecognized server request action\");\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase MsgType::NOTIFICATION:\n\t\t\t\tcase MsgType::SERVER_REPLY:\n\t\t\t\t\tsendCommErr(job.conn_hdl, \"This msgType is not intended for client-to-server messages\");\n\t\t\t\t\tbreak;\n\t\t\t\tcase MsgType::UNDEFINED:\n\t\t\t\t\tsendCommErr(job.conn_hdl, \"No valid msgType found\");\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\t\/\/ MsgType enum value valid, implementation lacks support for some feature\n\t\t\t\t\tassert(0);\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tcatch(std::error_code& e)\n\t\t{\n\t\t\tcerr << \"Caught a std::error_code\\n-----\\n\" << e << '\\n' << e.message() << endl;\n\t\t}\n\t\tcatch(std::exception& e)\n\t\t{\n\t\t\tcerr << \"Caught a std::exception: \" << e.what() << endl;\n\t\t}\n\t\tcatch(...)\n\t\t{\n\t\t\tcerr << \"Caught an unrecognized error (not derived from either exception or error_code)\" << endl;\n\t\t}\n\t}\n}\n\nstring Worker::newMatchID()\n{\n\tstatic ranlux24 int24Generator(system_clock::now().time_since_epoch().count());\n\n\tstring res;\n\tunique_lock matchDataLock(m_data.matchDataMtx);\n\n\tdo\n\t{\n\t\tres = int24ToB64ID(int24Generator());\n\t}\n\twhile(m_data.matchData.find(res) != m_data.matchData.end());\n\n\tmatchDataLock.unlock();\n\n\treturn res;\n}\n\nstring Worker::newPlayerID()\n{\n\tstatic ranlux48 int48Generator(system_clock::now().time_since_epoch().count());\n\n\t\/\/ TODO\n\treturn int48ToB64ID(int48Generator());\n}\n<|endoftext|>"} {"text":"#include \"xml.h\"\n\n#include \n#include \n#include \n\n#include \"..\/leanify.h\"\n#include \"..\/utils.h\"\n#include \"base64.h\"\n\nusing std::cout;\nusing std::endl;\nusing std::string;\n\n\nXml::Xml(void *p, size_t s \/*= 0*\/) : Format(p, s)\n{\n pugi::xml_parse_result result = doc_.load_buffer(fp_, size_, pugi::parse_default | pugi::parse_declaration | pugi::parse_doctype | pugi::parse_ws_pcdata_single);\n is_valid_ = result;\n encoding_ = result.encoding;\n}\n\n\nnamespace\n{\n\nvoid TraverseElements(pugi::xml_node node, std::function callback)\n{\n \/\/ cannot use ranged loop here because we need to store the next_sibling before recursion so that if child was removed the loop won't be terminated\n for (pugi::xml_node child = node.first_child(), next; child; child = next)\n {\n next = child.next_sibling();\n TraverseElements(child, callback);\n }\n\n callback(node);\n}\n\nstruct xml_memory_writer : pugi::xml_writer\n{\n uint8_t *p_write;\n\n virtual void write(const void* data, size_t size) override\n {\n memcpy(p_write, data, size);\n p_write += size;\n }\n};\n\n} \/\/ namespace\n\n\nsize_t Xml::Leanify(size_t size_leanified \/*= 0*\/)\n{\n\n \/\/ if the XML is fb2 file\n if (doc_.child(\"FictionBook\"))\n {\n if (is_verbose)\n {\n cout << \"FB2 detected.\" << endl;\n }\n if (depth < max_depth)\n {\n depth++;\n\n pugi::xml_node root = doc_.child(\"FictionBook\");\n\n \/\/ iterate through all binary element\n for (pugi::xml_node binary = root.child(\"binary\"), next; binary; binary = next)\n {\n next = binary.next_sibling(\"binary\");\n pugi::xml_attribute id = binary.attribute(\"id\");\n if (id == nullptr || id.value() == nullptr || id.value()[0] == 0)\n {\n root.remove_child(binary);\n continue;\n }\n\n PrintFileName(id.value());\n\n const char *base64_data = binary.child_value();\n if (base64_data == nullptr)\n {\n cout << \"No data found.\" << endl;\n continue;\n }\n size_t base64_len = strlen(base64_data);\n \/\/ copy to a new location because base64_data is const\n char *new_base64_data = new char[base64_len + 1];\n memcpy(new_base64_data, base64_data, base64_len);\n\n Base64 b64(new_base64_data, base64_len);\n size_t new_base64_len = b64.Leanify();\n\n if (new_base64_len < base64_len)\n {\n new_base64_data[new_base64_len] = 0;\n binary.text() = new_base64_data;\n }\n\n delete[] new_base64_data;\n }\n depth--;\n }\n }\n else if (doc_.child(\"svg\"))\n {\n if (is_verbose)\n {\n cout << \"SVG detected.\" << endl;\n }\n\n \/\/ remove XML declaration and doctype\n for (pugi::xml_node child = doc_.first_child(), next; child; child = next)\n {\n next = child.next_sibling();\n if (child.type() == pugi::node_declaration || child.type() == pugi::node_doctype)\n {\n doc_.remove_child(child);\n }\n }\n\n TraverseElements(doc_.child(\"svg\"), [](pugi::xml_node node)\n {\n for (pugi::xml_attribute attr = node.first_attribute(), next; attr; attr = next)\n {\n next = attr.next_attribute();\n const char* value = attr.value();\n \/\/ remove empty attribute\n if (value == nullptr || *value == 0)\n {\n node.remove_attribute(attr);\n continue;\n }\n\n \/\/ shrink spaces and newlines in attribute\n \/\/ also removes preceding and trailing spaces\n string new_value;\n while (*value)\n {\n if (*value == ' ' || *value == '\\n' || *value == '\\t')\n {\n do\n {\n value++;\n }\n while (*value == ' ' || *value == '\\n' || *value == '\\t');\n if (*value == 0)\n {\n break;\n }\n new_value += ' ';\n }\n new_value += *value++;\n }\n attr = new_value.c_str() + (new_value[0] == ' ' ? 1 : 0);\n }\n\n \/\/ remove empty text element and container element\n const char* name = node.name();\n if (node.first_child() == nullptr)\n {\n if (strcmp(name, \"text\") == 0 ||\n strcmp(name, \"tspan\") == 0 ||\n strcmp(name, \"a\") == 0 ||\n strcmp(name, \"defs\") == 0 ||\n strcmp(name, \"g\") == 0 ||\n strcmp(name, \"marker\") == 0 ||\n strcmp(name, \"mask\") == 0 ||\n strcmp(name, \"missing-glyph\") == 0 ||\n strcmp(name, \"pattern\") == 0 ||\n strcmp(name, \"switch\") == 0 ||\n strcmp(name, \"symbol\") == 0)\n {\n node.parent().remove_child(node);\n return;\n }\n }\n\n if (strcmp(name, \"tref\") == 0 && node.attribute(\"xlink:href\") == nullptr)\n {\n node.parent().remove_child(node);\n return;\n }\n\n if (strcmp(name, \"metadata\") == 0)\n {\n node.parent().remove_child(node);\n return;\n }\n });\n }\n\n \/\/ print leanified XML to memory\n xml_memory_writer writer;\n fp_ -= size_leanified;\n writer.p_write = fp_;\n doc_.save(writer, nullptr, pugi::format_raw | pugi::format_no_declaration, encoding_);\n size_ = writer.p_write - fp_;\n return size_;\n}\nXML: remove redundant virtual#include \"xml.h\"\n\n#include \n#include \n#include \n\n#include \"..\/leanify.h\"\n#include \"..\/utils.h\"\n#include \"base64.h\"\n\nusing std::cout;\nusing std::endl;\nusing std::string;\n\n\nXml::Xml(void *p, size_t s \/*= 0*\/) : Format(p, s)\n{\n pugi::xml_parse_result result = doc_.load_buffer(fp_, size_, pugi::parse_default | pugi::parse_declaration | pugi::parse_doctype | pugi::parse_ws_pcdata_single);\n is_valid_ = result;\n encoding_ = result.encoding;\n}\n\n\nnamespace\n{\n\nvoid TraverseElements(pugi::xml_node node, std::function callback)\n{\n \/\/ cannot use ranged loop here because we need to store the next_sibling before recursion so that if child was removed the loop won't be terminated\n for (pugi::xml_node child = node.first_child(), next; child; child = next)\n {\n next = child.next_sibling();\n TraverseElements(child, callback);\n }\n\n callback(node);\n}\n\nstruct xml_memory_writer : pugi::xml_writer\n{\n uint8_t *p_write;\n\n void write(const void* data, size_t size) override\n {\n memcpy(p_write, data, size);\n p_write += size;\n }\n};\n\n} \/\/ namespace\n\n\nsize_t Xml::Leanify(size_t size_leanified \/*= 0*\/)\n{\n\n \/\/ if the XML is fb2 file\n if (doc_.child(\"FictionBook\"))\n {\n if (is_verbose)\n {\n cout << \"FB2 detected.\" << endl;\n }\n if (depth < max_depth)\n {\n depth++;\n\n pugi::xml_node root = doc_.child(\"FictionBook\");\n\n \/\/ iterate through all binary element\n for (pugi::xml_node binary = root.child(\"binary\"), next; binary; binary = next)\n {\n next = binary.next_sibling(\"binary\");\n pugi::xml_attribute id = binary.attribute(\"id\");\n if (id == nullptr || id.value() == nullptr || id.value()[0] == 0)\n {\n root.remove_child(binary);\n continue;\n }\n\n PrintFileName(id.value());\n\n const char *base64_data = binary.child_value();\n if (base64_data == nullptr)\n {\n cout << \"No data found.\" << endl;\n continue;\n }\n size_t base64_len = strlen(base64_data);\n \/\/ copy to a new location because base64_data is const\n char *new_base64_data = new char[base64_len + 1];\n memcpy(new_base64_data, base64_data, base64_len);\n\n Base64 b64(new_base64_data, base64_len);\n size_t new_base64_len = b64.Leanify();\n\n if (new_base64_len < base64_len)\n {\n new_base64_data[new_base64_len] = 0;\n binary.text() = new_base64_data;\n }\n\n delete[] new_base64_data;\n }\n depth--;\n }\n }\n else if (doc_.child(\"svg\"))\n {\n if (is_verbose)\n {\n cout << \"SVG detected.\" << endl;\n }\n\n \/\/ remove XML declaration and doctype\n for (pugi::xml_node child = doc_.first_child(), next; child; child = next)\n {\n next = child.next_sibling();\n if (child.type() == pugi::node_declaration || child.type() == pugi::node_doctype)\n {\n doc_.remove_child(child);\n }\n }\n\n TraverseElements(doc_.child(\"svg\"), [](pugi::xml_node node)\n {\n for (pugi::xml_attribute attr = node.first_attribute(), next; attr; attr = next)\n {\n next = attr.next_attribute();\n const char* value = attr.value();\n \/\/ remove empty attribute\n if (value == nullptr || *value == 0)\n {\n node.remove_attribute(attr);\n continue;\n }\n\n \/\/ shrink spaces and newlines in attribute\n \/\/ also removes preceding and trailing spaces\n string new_value;\n while (*value)\n {\n if (*value == ' ' || *value == '\\n' || *value == '\\t')\n {\n do\n {\n value++;\n }\n while (*value == ' ' || *value == '\\n' || *value == '\\t');\n if (*value == 0)\n {\n break;\n }\n new_value += ' ';\n }\n new_value += *value++;\n }\n attr = new_value.c_str() + (new_value[0] == ' ' ? 1 : 0);\n }\n\n \/\/ remove empty text element and container element\n const char* name = node.name();\n if (node.first_child() == nullptr)\n {\n if (strcmp(name, \"text\") == 0 ||\n strcmp(name, \"tspan\") == 0 ||\n strcmp(name, \"a\") == 0 ||\n strcmp(name, \"defs\") == 0 ||\n strcmp(name, \"g\") == 0 ||\n strcmp(name, \"marker\") == 0 ||\n strcmp(name, \"mask\") == 0 ||\n strcmp(name, \"missing-glyph\") == 0 ||\n strcmp(name, \"pattern\") == 0 ||\n strcmp(name, \"switch\") == 0 ||\n strcmp(name, \"symbol\") == 0)\n {\n node.parent().remove_child(node);\n return;\n }\n }\n\n if (strcmp(name, \"tref\") == 0 && node.attribute(\"xlink:href\") == nullptr)\n {\n node.parent().remove_child(node);\n return;\n }\n\n if (strcmp(name, \"metadata\") == 0)\n {\n node.parent().remove_child(node);\n return;\n }\n });\n }\n\n \/\/ print leanified XML to memory\n xml_memory_writer writer;\n fp_ -= size_leanified;\n writer.p_write = fp_;\n doc_.save(writer, nullptr, pugi::format_raw | pugi::format_no_declaration, encoding_);\n size_ = writer.p_write - fp_;\n return size_;\n}\n<|endoftext|>"} {"text":"\/\/ SwiftShader Software Renderer\n\/\/\n\/\/ Copyright(c) 2005-2013 TransGaming Inc.\n\/\/\n\/\/ All rights reserved. No part of this software may be copied, distributed, transmitted,\n\/\/ transcribed, stored in a retrieval system, translated into any human or computer\n\/\/ language by any means, or disclosed to third parties without the explicit written\n\/\/ agreement of TransGaming Inc. Without such an agreement, no rights or licenses, express\n\/\/ or implied, including but not limited to any patent rights, are granted to you.\n\/\/\n\n\/\/ Config.cpp: Implements the egl::Config class, describing the format, type\n\/\/ and size for an egl::Surface. Implements EGLConfig and related functionality.\n\/\/ [EGL 1.4] section 3.4 page 15.\n\n#include \"Config.h\"\n\n#include \"common\/debug.h\"\n\n#define EGLAPI\n#include \n\n#include \n#include \n\nusing namespace std;\n\nnamespace egl\n{\nConfig::Config(const DisplayMode &displayMode, EGLint minInterval, EGLint maxInterval, sw::Format renderTargetFormat, sw::Format depthStencilFormat, EGLint multiSample)\n : mDisplayMode(displayMode), mRenderTargetFormat(renderTargetFormat), mDepthStencilFormat(depthStencilFormat), mMultiSample(multiSample)\n{\n mBindToTextureRGB = EGL_FALSE;\n mBindToTextureRGBA = EGL_FALSE;\n\n switch (renderTargetFormat)\n {\n case sw::FORMAT_A1R5G5B5:\n mBufferSize = 16;\n mRedSize = 5;\n mGreenSize = 5;\n mBlueSize = 5;\n mAlphaSize = 1;\n break;\n case sw::FORMAT_A2R10G10B10:\n mBufferSize = 32;\n mRedSize = 10;\n mGreenSize = 10;\n mBlueSize = 10;\n mAlphaSize = 2;\n break;\n case sw::FORMAT_A8R8G8B8:\n mBufferSize = 32;\n mRedSize = 8;\n mGreenSize = 8;\n mBlueSize = 8;\n mAlphaSize = 8;\n mBindToTextureRGBA = true;\n break;\n case sw::FORMAT_R5G6B5:\n mBufferSize = 16;\n mRedSize = 5;\n mGreenSize = 6;\n mBlueSize = 5;\n mAlphaSize = 0;\n break;\n case sw::FORMAT_X8R8G8B8:\n mBufferSize = 32;\n mRedSize = 8;\n mGreenSize = 8;\n mBlueSize = 8;\n mAlphaSize = 0;\n mBindToTextureRGB = true;\n break;\n default:\n UNREACHABLE(); \/\/ Other formats should not be valid\n }\n\n mLuminanceSize = 0;\n mAlphaMaskSize = 0;\n mColorBufferType = EGL_RGB_BUFFER;\n mConfigCaveat = isSlowConfig() ? EGL_SLOW_CONFIG : EGL_NONE;\n mConfigID = 0;\n mConformant = EGL_OPENGL_ES_BIT | EGL_OPENGL_ES2_BIT | EGL_OPENGL_ES3_BIT;\n\n\tswitch (depthStencilFormat)\n\t{\n\tcase sw::FORMAT_NULL:\n\t\tmDepthSize = 0;\n\t\tmStencilSize = 0;\n\t\tbreak;\n\/\/ case sw::FORMAT_D16_LOCKABLE:\n\/\/ mDepthSize = 16;\n\/\/ mStencilSize = 0;\n\/\/ break;\n\tcase sw::FORMAT_D32:\n\t\tmDepthSize = 32;\n\t\tmStencilSize = 0;\n\t\tbreak;\n\/\/\tcase sw::FORMAT_D15S1:\n\/\/\t\tmDepthSize = 15;\n\/\/\t\tmStencilSize = 1;\n\/\/\t\tbreak;\n\tcase sw::FORMAT_D24S8:\n\t\tmDepthSize = 24;\n\t\tmStencilSize = 8;\n\t\tbreak;\n\tcase sw::FORMAT_D24X8:\n\t\tmDepthSize = 24;\n\t\tmStencilSize = 0;\n\t\tbreak;\n\/\/\tcase sw::FORMAT_D24X4S4:\n\/\/\t\tmDepthSize = 24;\n\/\/\t\tmStencilSize = 4;\n\/\/\t\tbreak;\n\tcase sw::FORMAT_D16:\n\t\tmDepthSize = 16;\n\t\tmStencilSize = 0;\n\t\tbreak;\n\/\/ case sw::FORMAT_D32F_LOCKABLE:\n\/\/ mDepthSize = 32;\n\/\/ mStencilSize = 0;\n\/\/ break;\n\/\/ case sw::FORMAT_D24FS8:\n\/\/ mDepthSize = 24;\n\/\/ mStencilSize = 8;\n\/\/ break;\n\t default:\n\t\tUNREACHABLE();\n\t}\n\n mLevel = 0;\n mMatchNativePixmap = EGL_NONE;\n mMaxPBufferWidth = 4096;\n mMaxPBufferHeight = 4096;\n mMaxPBufferPixels = mMaxPBufferWidth * mMaxPBufferHeight;\n mMaxSwapInterval = maxInterval;\n mMinSwapInterval = minInterval;\n mNativeRenderable = EGL_FALSE;\n mNativeVisualID = 0;\n mNativeVisualType = 0;\n mRenderableType = EGL_OPENGL_ES_BIT | EGL_OPENGL_ES2_BIT | EGL_OPENGL_ES3_BIT;\n mSampleBuffers = multiSample ? 1 : 0;\n mSamples = multiSample;\n mSurfaceType = EGL_PBUFFER_BIT | EGL_WINDOW_BIT | EGL_SWAP_BEHAVIOR_PRESERVED_BIT;\n mTransparentType = EGL_NONE;\n mTransparentRedValue = 0;\n mTransparentGreenValue = 0;\n mTransparentBlueValue = 0;\n}\n\nEGLConfig Config::getHandle() const\n{\n return (EGLConfig)(size_t)mConfigID;\n}\n\nbool Config::isSlowConfig() const\n{\n\treturn mRenderTargetFormat != sw::FORMAT_X8R8G8B8 && mRenderTargetFormat != sw::FORMAT_A8R8G8B8;\n}\n\nSortConfig::SortConfig(const EGLint *attribList)\n : mWantRed(false), mWantGreen(false), mWantBlue(false), mWantAlpha(false), mWantLuminance(false)\n{\n scanForWantedComponents(attribList);\n}\n\nvoid SortConfig::scanForWantedComponents(const EGLint *attribList)\n{\n \/\/ [EGL] section 3.4.1 page 24\n \/\/ Sorting rule #3: by larger total number of color bits, not considering\n \/\/ components that are 0 or don't-care.\n for(const EGLint *attr = attribList; attr[0] != EGL_NONE; attr += 2)\n {\n if(attr[1] != 0 && attr[1] != EGL_DONT_CARE)\n {\n switch (attr[0])\n {\n case EGL_RED_SIZE: mWantRed = true; break;\n case EGL_GREEN_SIZE: mWantGreen = true; break;\n case EGL_BLUE_SIZE: mWantBlue = true; break;\n case EGL_ALPHA_SIZE: mWantAlpha = true; break;\n case EGL_LUMINANCE_SIZE: mWantLuminance = true; break;\n }\n }\n }\n}\n\nEGLint SortConfig::wantedComponentsSize(const Config &config) const\n{\n EGLint total = 0;\n\n if(mWantRed) total += config.mRedSize;\n if(mWantGreen) total += config.mGreenSize;\n if(mWantBlue) total += config.mBlueSize;\n if(mWantAlpha) total += config.mAlphaSize;\n if(mWantLuminance) total += config.mLuminanceSize;\n\n return total;\n}\n\nbool SortConfig::operator()(const Config *x, const Config *y) const\n{\n return (*this)(*x, *y);\n}\n\nbool SortConfig::operator()(const Config &x, const Config &y) const\n{\n #define SORT(attribute) \\\n if(x.attribute != y.attribute) \\\n { \\\n return x.attribute < y.attribute; \\\n }\n\n META_ASSERT(EGL_NONE < EGL_SLOW_CONFIG && EGL_SLOW_CONFIG < EGL_NON_CONFORMANT_CONFIG);\n SORT(mConfigCaveat);\n\n META_ASSERT(EGL_RGB_BUFFER < EGL_LUMINANCE_BUFFER);\n SORT(mColorBufferType);\n\n \/\/ By larger total number of color bits, only considering those that are requested to be > 0.\n EGLint xComponentsSize = wantedComponentsSize(x);\n EGLint yComponentsSize = wantedComponentsSize(y);\n if(xComponentsSize != yComponentsSize)\n {\n return xComponentsSize > yComponentsSize;\n }\n\n SORT(mBufferSize);\n SORT(mSampleBuffers);\n SORT(mSamples);\n SORT(mDepthSize);\n SORT(mStencilSize);\n SORT(mAlphaMaskSize);\n SORT(mNativeVisualType);\n SORT(mConfigID);\n\n #undef SORT\n\n return false;\n}\n\n\/\/ We'd like to use SortConfig to also eliminate duplicate configs.\n\/\/ This works as long as we never have two configs with different per-RGB-component layouts,\n\/\/ but the same total.\n\/\/ 5551 and 565 are different because R+G+B is different.\n\/\/ 5551 and 555 are different because bufferSize is different.\nconst EGLint ConfigSet::mSortAttribs[] =\n{\n EGL_RED_SIZE, 1,\n EGL_GREEN_SIZE, 1,\n EGL_BLUE_SIZE, 1,\n EGL_LUMINANCE_SIZE, 1,\n \/\/ BUT NOT ALPHA\n EGL_NONE\n};\n\nConfigSet::ConfigSet()\n : mSet(SortConfig(mSortAttribs))\n{\n}\n\nvoid ConfigSet::add(const DisplayMode &displayMode, EGLint minSwapInterval, EGLint maxSwapInterval, sw::Format renderTargetFormat, sw::Format depthStencilFormat, EGLint multiSample)\n{\n Config config(displayMode, minSwapInterval, maxSwapInterval, renderTargetFormat, depthStencilFormat, multiSample);\n\n mSet.insert(config);\n}\n\nsize_t ConfigSet::size() const\n{\n return mSet.size();\n}\n\nbool ConfigSet::getConfigs(EGLConfig *configs, const EGLint *attribList, EGLint configSize, EGLint *numConfig)\n{\n vector passed;\n passed.reserve(mSet.size());\n\n for(Iterator config = mSet.begin(); config != mSet.end(); config++)\n {\n bool match = true;\n const EGLint *attribute = attribList;\n\n while(attribute[0] != EGL_NONE)\n {\n switch(attribute[0])\n {\n case EGL_BUFFER_SIZE: match = config->mBufferSize >= attribute[1]; break;\n case EGL_ALPHA_SIZE: match = config->mAlphaSize >= attribute[1]; break;\n case EGL_BLUE_SIZE: match = config->mBlueSize >= attribute[1]; break;\n case EGL_GREEN_SIZE: match = config->mGreenSize >= attribute[1]; break;\n case EGL_RED_SIZE: match = config->mRedSize >= attribute[1]; break;\n case EGL_DEPTH_SIZE: match = config->mDepthSize >= attribute[1]; break;\n case EGL_STENCIL_SIZE: match = config->mStencilSize >= attribute[1]; break;\n case EGL_CONFIG_CAVEAT: match = config->mConfigCaveat == attribute[1]; break;\n case EGL_CONFIG_ID: match = config->mConfigID == attribute[1]; break;\n case EGL_LEVEL: match = config->mLevel >= attribute[1]; break;\n case EGL_NATIVE_RENDERABLE: match = config->mNativeRenderable == attribute[1]; break;\n case EGL_NATIVE_VISUAL_ID: match = config->mNativeVisualID == attribute[1]; break;\n case EGL_NATIVE_VISUAL_TYPE: match = config->mNativeVisualType == attribute[1]; break;\n case EGL_SAMPLES: match = config->mSamples >= attribute[1]; break;\n case EGL_SAMPLE_BUFFERS: match = config->mSampleBuffers >= attribute[1]; break;\n case EGL_SURFACE_TYPE: match = (config->mSurfaceType & attribute[1]) == attribute[1]; break;\n case EGL_TRANSPARENT_TYPE: match = config->mTransparentType == attribute[1]; break;\n case EGL_TRANSPARENT_BLUE_VALUE: match = config->mTransparentBlueValue == attribute[1]; break;\n case EGL_TRANSPARENT_GREEN_VALUE: match = config->mTransparentGreenValue == attribute[1]; break;\n case EGL_TRANSPARENT_RED_VALUE: match = config->mTransparentRedValue == attribute[1]; break;\n case EGL_BIND_TO_TEXTURE_RGB: match = config->mBindToTextureRGB == attribute[1]; break;\n case EGL_BIND_TO_TEXTURE_RGBA: match = config->mBindToTextureRGBA == attribute[1]; break;\n case EGL_MIN_SWAP_INTERVAL: match = config->mMinSwapInterval == attribute[1]; break;\n case EGL_MAX_SWAP_INTERVAL: match = config->mMaxSwapInterval == attribute[1]; break;\n case EGL_LUMINANCE_SIZE: match = config->mLuminanceSize >= attribute[1]; break;\n case EGL_ALPHA_MASK_SIZE: match = config->mAlphaMaskSize >= attribute[1]; break;\n case EGL_COLOR_BUFFER_TYPE: match = config->mColorBufferType == attribute[1]; break;\n case EGL_RENDERABLE_TYPE: match = (config->mRenderableType & attribute[1]) == attribute[1]; break;\n case EGL_MATCH_NATIVE_PIXMAP: match = false; UNIMPLEMENTED(); break;\n case EGL_CONFORMANT: match = (config->mConformant & attribute[1]) == attribute[1]; break;\n case EGL_MAX_PBUFFER_WIDTH: match = config->mMaxPBufferWidth >= attribute[1]; break;\n case EGL_MAX_PBUFFER_HEIGHT: match = config->mMaxPBufferHeight >= attribute[1]; break;\n case EGL_MAX_PBUFFER_PIXELS: match = config->mMaxPBufferPixels >= attribute[1]; break;\n\t\t\tcase EGL_RECORDABLE_ANDROID: match = false; \/* UNIMPLEMENTED(); *\/ break;\n\t\t\tcase EGL_FRAMEBUFFER_TARGET_ANDROID: match = false; \/* UNIMPLEMENTED(); *\/ break;\n\t\t\tdefault:\n\t\t\t\tUNIMPLEMENTED();\n\t\t\t\tmatch = false;\n }\n\n if(!match)\n {\n break;\n }\n\n attribute += 2;\n }\n\n if(match)\n {\n passed.push_back(&*config);\n }\n }\n\n if(configs)\n {\n sort(passed.begin(), passed.end(), SortConfig(attribList));\n\n EGLint index;\n for(index = 0; index < configSize && index < static_cast(passed.size()); index++)\n {\n configs[index] = passed[index]->getHandle();\n }\n\n *numConfig = index;\n }\n else\n {\n *numConfig = static_cast(passed.size());\n }\n\n return true;\n}\n\nconst egl::Config *ConfigSet::get(EGLConfig configHandle)\n{\n for(Iterator config = mSet.begin(); config != mSet.end(); config++)\n {\n if(config->getHandle() == configHandle)\n {\n return &(*config);\n }\n }\n\n return NULL;\n}\n}\nIndicate support for Android EGL surface config attributes.\/\/ SwiftShader Software Renderer\n\/\/\n\/\/ Copyright(c) 2005-2013 TransGaming Inc.\n\/\/\n\/\/ All rights reserved. No part of this software may be copied, distributed, transmitted,\n\/\/ transcribed, stored in a retrieval system, translated into any human or computer\n\/\/ language by any means, or disclosed to third parties without the explicit written\n\/\/ agreement of TransGaming Inc. Without such an agreement, no rights or licenses, express\n\/\/ or implied, including but not limited to any patent rights, are granted to you.\n\/\/\n\n\/\/ Config.cpp: Implements the egl::Config class, describing the format, type\n\/\/ and size for an egl::Surface. Implements EGLConfig and related functionality.\n\/\/ [EGL 1.4] section 3.4 page 15.\n\n#include \"Config.h\"\n\n#include \"common\/debug.h\"\n\n#define EGLAPI\n#include \n\n#include \n#include \n\nusing namespace std;\n\nnamespace egl\n{\nConfig::Config(const DisplayMode &displayMode, EGLint minInterval, EGLint maxInterval, sw::Format renderTargetFormat, sw::Format depthStencilFormat, EGLint multiSample)\n : mDisplayMode(displayMode), mRenderTargetFormat(renderTargetFormat), mDepthStencilFormat(depthStencilFormat), mMultiSample(multiSample)\n{\n mBindToTextureRGB = EGL_FALSE;\n mBindToTextureRGBA = EGL_FALSE;\n\n switch (renderTargetFormat)\n {\n case sw::FORMAT_A1R5G5B5:\n mBufferSize = 16;\n mRedSize = 5;\n mGreenSize = 5;\n mBlueSize = 5;\n mAlphaSize = 1;\n break;\n case sw::FORMAT_A2R10G10B10:\n mBufferSize = 32;\n mRedSize = 10;\n mGreenSize = 10;\n mBlueSize = 10;\n mAlphaSize = 2;\n break;\n case sw::FORMAT_A8R8G8B8:\n mBufferSize = 32;\n mRedSize = 8;\n mGreenSize = 8;\n mBlueSize = 8;\n mAlphaSize = 8;\n mBindToTextureRGBA = true;\n break;\n case sw::FORMAT_R5G6B5:\n mBufferSize = 16;\n mRedSize = 5;\n mGreenSize = 6;\n mBlueSize = 5;\n mAlphaSize = 0;\n break;\n case sw::FORMAT_X8R8G8B8:\n mBufferSize = 32;\n mRedSize = 8;\n mGreenSize = 8;\n mBlueSize = 8;\n mAlphaSize = 0;\n mBindToTextureRGB = true;\n break;\n default:\n UNREACHABLE(); \/\/ Other formats should not be valid\n }\n\n mLuminanceSize = 0;\n mAlphaMaskSize = 0;\n mColorBufferType = EGL_RGB_BUFFER;\n mConfigCaveat = isSlowConfig() ? EGL_SLOW_CONFIG : EGL_NONE;\n mConfigID = 0;\n mConformant = EGL_OPENGL_ES_BIT | EGL_OPENGL_ES2_BIT | EGL_OPENGL_ES3_BIT;\n\n\tswitch (depthStencilFormat)\n\t{\n\tcase sw::FORMAT_NULL:\n\t\tmDepthSize = 0;\n\t\tmStencilSize = 0;\n\t\tbreak;\n\/\/ case sw::FORMAT_D16_LOCKABLE:\n\/\/ mDepthSize = 16;\n\/\/ mStencilSize = 0;\n\/\/ break;\n\tcase sw::FORMAT_D32:\n\t\tmDepthSize = 32;\n\t\tmStencilSize = 0;\n\t\tbreak;\n\/\/\tcase sw::FORMAT_D15S1:\n\/\/\t\tmDepthSize = 15;\n\/\/\t\tmStencilSize = 1;\n\/\/\t\tbreak;\n\tcase sw::FORMAT_D24S8:\n\t\tmDepthSize = 24;\n\t\tmStencilSize = 8;\n\t\tbreak;\n\tcase sw::FORMAT_D24X8:\n\t\tmDepthSize = 24;\n\t\tmStencilSize = 0;\n\t\tbreak;\n\/\/\tcase sw::FORMAT_D24X4S4:\n\/\/\t\tmDepthSize = 24;\n\/\/\t\tmStencilSize = 4;\n\/\/\t\tbreak;\n\tcase sw::FORMAT_D16:\n\t\tmDepthSize = 16;\n\t\tmStencilSize = 0;\n\t\tbreak;\n\/\/ case sw::FORMAT_D32F_LOCKABLE:\n\/\/ mDepthSize = 32;\n\/\/ mStencilSize = 0;\n\/\/ break;\n\/\/ case sw::FORMAT_D24FS8:\n\/\/ mDepthSize = 24;\n\/\/ mStencilSize = 8;\n\/\/ break;\n\t default:\n\t\tUNREACHABLE();\n\t}\n\n mLevel = 0;\n mMatchNativePixmap = EGL_NONE;\n mMaxPBufferWidth = 4096;\n mMaxPBufferHeight = 4096;\n mMaxPBufferPixels = mMaxPBufferWidth * mMaxPBufferHeight;\n mMaxSwapInterval = maxInterval;\n mMinSwapInterval = minInterval;\n mNativeRenderable = EGL_FALSE;\n mNativeVisualID = 0;\n mNativeVisualType = 0;\n mRenderableType = EGL_OPENGL_ES_BIT | EGL_OPENGL_ES2_BIT | EGL_OPENGL_ES3_BIT;\n mSampleBuffers = multiSample ? 1 : 0;\n mSamples = multiSample;\n mSurfaceType = EGL_PBUFFER_BIT | EGL_WINDOW_BIT | EGL_SWAP_BEHAVIOR_PRESERVED_BIT;\n mTransparentType = EGL_NONE;\n mTransparentRedValue = 0;\n mTransparentGreenValue = 0;\n mTransparentBlueValue = 0;\n}\n\nEGLConfig Config::getHandle() const\n{\n return (EGLConfig)(size_t)mConfigID;\n}\n\nbool Config::isSlowConfig() const\n{\n\treturn mRenderTargetFormat != sw::FORMAT_X8R8G8B8 && mRenderTargetFormat != sw::FORMAT_A8R8G8B8;\n}\n\nSortConfig::SortConfig(const EGLint *attribList)\n : mWantRed(false), mWantGreen(false), mWantBlue(false), mWantAlpha(false), mWantLuminance(false)\n{\n scanForWantedComponents(attribList);\n}\n\nvoid SortConfig::scanForWantedComponents(const EGLint *attribList)\n{\n \/\/ [EGL] section 3.4.1 page 24\n \/\/ Sorting rule #3: by larger total number of color bits, not considering\n \/\/ components that are 0 or don't-care.\n for(const EGLint *attr = attribList; attr[0] != EGL_NONE; attr += 2)\n {\n if(attr[1] != 0 && attr[1] != EGL_DONT_CARE)\n {\n switch (attr[0])\n {\n case EGL_RED_SIZE: mWantRed = true; break;\n case EGL_GREEN_SIZE: mWantGreen = true; break;\n case EGL_BLUE_SIZE: mWantBlue = true; break;\n case EGL_ALPHA_SIZE: mWantAlpha = true; break;\n case EGL_LUMINANCE_SIZE: mWantLuminance = true; break;\n }\n }\n }\n}\n\nEGLint SortConfig::wantedComponentsSize(const Config &config) const\n{\n EGLint total = 0;\n\n if(mWantRed) total += config.mRedSize;\n if(mWantGreen) total += config.mGreenSize;\n if(mWantBlue) total += config.mBlueSize;\n if(mWantAlpha) total += config.mAlphaSize;\n if(mWantLuminance) total += config.mLuminanceSize;\n\n return total;\n}\n\nbool SortConfig::operator()(const Config *x, const Config *y) const\n{\n return (*this)(*x, *y);\n}\n\nbool SortConfig::operator()(const Config &x, const Config &y) const\n{\n #define SORT(attribute) \\\n if(x.attribute != y.attribute) \\\n { \\\n return x.attribute < y.attribute; \\\n }\n\n META_ASSERT(EGL_NONE < EGL_SLOW_CONFIG && EGL_SLOW_CONFIG < EGL_NON_CONFORMANT_CONFIG);\n SORT(mConfigCaveat);\n\n META_ASSERT(EGL_RGB_BUFFER < EGL_LUMINANCE_BUFFER);\n SORT(mColorBufferType);\n\n \/\/ By larger total number of color bits, only considering those that are requested to be > 0.\n EGLint xComponentsSize = wantedComponentsSize(x);\n EGLint yComponentsSize = wantedComponentsSize(y);\n if(xComponentsSize != yComponentsSize)\n {\n return xComponentsSize > yComponentsSize;\n }\n\n SORT(mBufferSize);\n SORT(mSampleBuffers);\n SORT(mSamples);\n SORT(mDepthSize);\n SORT(mStencilSize);\n SORT(mAlphaMaskSize);\n SORT(mNativeVisualType);\n SORT(mConfigID);\n\n #undef SORT\n\n return false;\n}\n\n\/\/ We'd like to use SortConfig to also eliminate duplicate configs.\n\/\/ This works as long as we never have two configs with different per-RGB-component layouts,\n\/\/ but the same total.\n\/\/ 5551 and 565 are different because R+G+B is different.\n\/\/ 5551 and 555 are different because bufferSize is different.\nconst EGLint ConfigSet::mSortAttribs[] =\n{\n EGL_RED_SIZE, 1,\n EGL_GREEN_SIZE, 1,\n EGL_BLUE_SIZE, 1,\n EGL_LUMINANCE_SIZE, 1,\n \/\/ BUT NOT ALPHA\n EGL_NONE\n};\n\nConfigSet::ConfigSet()\n : mSet(SortConfig(mSortAttribs))\n{\n}\n\nvoid ConfigSet::add(const DisplayMode &displayMode, EGLint minSwapInterval, EGLint maxSwapInterval, sw::Format renderTargetFormat, sw::Format depthStencilFormat, EGLint multiSample)\n{\n Config config(displayMode, minSwapInterval, maxSwapInterval, renderTargetFormat, depthStencilFormat, multiSample);\n\n mSet.insert(config);\n}\n\nsize_t ConfigSet::size() const\n{\n return mSet.size();\n}\n\nbool ConfigSet::getConfigs(EGLConfig *configs, const EGLint *attribList, EGLint configSize, EGLint *numConfig)\n{\n vector passed;\n passed.reserve(mSet.size());\n\n for(Iterator config = mSet.begin(); config != mSet.end(); config++)\n {\n bool match = true;\n const EGLint *attribute = attribList;\n\n while(attribute[0] != EGL_NONE)\n {\n switch(attribute[0])\n {\n case EGL_BUFFER_SIZE: match = config->mBufferSize >= attribute[1]; break;\n case EGL_ALPHA_SIZE: match = config->mAlphaSize >= attribute[1]; break;\n case EGL_BLUE_SIZE: match = config->mBlueSize >= attribute[1]; break;\n case EGL_GREEN_SIZE: match = config->mGreenSize >= attribute[1]; break;\n case EGL_RED_SIZE: match = config->mRedSize >= attribute[1]; break;\n case EGL_DEPTH_SIZE: match = config->mDepthSize >= attribute[1]; break;\n case EGL_STENCIL_SIZE: match = config->mStencilSize >= attribute[1]; break;\n case EGL_CONFIG_CAVEAT: match = config->mConfigCaveat == attribute[1]; break;\n case EGL_CONFIG_ID: match = config->mConfigID == attribute[1]; break;\n case EGL_LEVEL: match = config->mLevel >= attribute[1]; break;\n case EGL_NATIVE_RENDERABLE: match = config->mNativeRenderable == attribute[1]; break;\n case EGL_NATIVE_VISUAL_ID: match = config->mNativeVisualID == attribute[1]; break;\n case EGL_NATIVE_VISUAL_TYPE: match = config->mNativeVisualType == attribute[1]; break;\n case EGL_SAMPLES: match = config->mSamples >= attribute[1]; break;\n case EGL_SAMPLE_BUFFERS: match = config->mSampleBuffers >= attribute[1]; break;\n case EGL_SURFACE_TYPE: match = (config->mSurfaceType & attribute[1]) == attribute[1]; break;\n case EGL_TRANSPARENT_TYPE: match = config->mTransparentType == attribute[1]; break;\n case EGL_TRANSPARENT_BLUE_VALUE: match = config->mTransparentBlueValue == attribute[1]; break;\n case EGL_TRANSPARENT_GREEN_VALUE: match = config->mTransparentGreenValue == attribute[1]; break;\n case EGL_TRANSPARENT_RED_VALUE: match = config->mTransparentRedValue == attribute[1]; break;\n case EGL_BIND_TO_TEXTURE_RGB: match = config->mBindToTextureRGB == attribute[1]; break;\n case EGL_BIND_TO_TEXTURE_RGBA: match = config->mBindToTextureRGBA == attribute[1]; break;\n case EGL_MIN_SWAP_INTERVAL: match = config->mMinSwapInterval == attribute[1]; break;\n case EGL_MAX_SWAP_INTERVAL: match = config->mMaxSwapInterval == attribute[1]; break;\n case EGL_LUMINANCE_SIZE: match = config->mLuminanceSize >= attribute[1]; break;\n case EGL_ALPHA_MASK_SIZE: match = config->mAlphaMaskSize >= attribute[1]; break;\n case EGL_COLOR_BUFFER_TYPE: match = config->mColorBufferType == attribute[1]; break;\n case EGL_RENDERABLE_TYPE: match = (config->mRenderableType & attribute[1]) == attribute[1]; break;\n case EGL_MATCH_NATIVE_PIXMAP: match = false; UNIMPLEMENTED(); break;\n case EGL_CONFORMANT: match = (config->mConformant & attribute[1]) == attribute[1]; break;\n case EGL_MAX_PBUFFER_WIDTH: match = config->mMaxPBufferWidth >= attribute[1]; break;\n case EGL_MAX_PBUFFER_HEIGHT: match = config->mMaxPBufferHeight >= attribute[1]; break;\n case EGL_MAX_PBUFFER_PIXELS: match = config->mMaxPBufferPixels >= attribute[1]; break;\n case EGL_RECORDABLE_ANDROID: match = true; \/* UNIMPLEMENTED(); EGL_ANDROID_recordable *\/ break;\n case EGL_FRAMEBUFFER_TARGET_ANDROID: match = true; \/* UNIMPLEMENTED(); EGL_ANDROID_framebuffer_target *\/ break;\n\t\t\tdefault:\n\t\t\t\tUNIMPLEMENTED();\n\t\t\t\tmatch = false;\n }\n\n if(!match)\n {\n break;\n }\n\n attribute += 2;\n }\n\n if(match)\n {\n passed.push_back(&*config);\n }\n }\n\n if(configs)\n {\n sort(passed.begin(), passed.end(), SortConfig(attribList));\n\n EGLint index;\n for(index = 0; index < configSize && index < static_cast(passed.size()); index++)\n {\n configs[index] = passed[index]->getHandle();\n }\n\n *numConfig = index;\n }\n else\n {\n *numConfig = static_cast(passed.size());\n }\n\n return true;\n}\n\nconst egl::Config *ConfigSet::get(EGLConfig configHandle)\n{\n for(Iterator config = mSet.begin(); config != mSet.end(); config++)\n {\n if(config->getHandle() == configHandle)\n {\n return &(*config);\n }\n }\n\n return NULL;\n}\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2007-2020 Content Management AG\n * All rights reserved.\n *\n * author: Max Kellermann \n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#pragma once\n\n#include \"util\/Compiler.h\"\n#include \"util\/Expiry.hxx\"\n\n#include \n\n#include \n\n\/**\n * Pick an address using a #sticky_hash_t module the list size. If\n * that address is failed, pick the next one.\n *\/\ntemplate\ngcc_pure\nconst auto &\nPickModulo(Expiry now, const List &list, sticky_hash_t sticky_hash) noexcept\n{\n\tconst size_t n = std::size(list);\n\tassert(n >= 2);\n\n\tconst size_t modulo = sticky_hash % n;\n\tbool allow_fade = true;\n\n\tconst auto selected = std::next(std::begin(list), modulo);\n\tconst auto end = std::end(list);\n\n\tauto i = selected;\n\tdo {\n\t\tif (list.Check(now, *i, allow_fade))\n\t\t\tbreak;\n\n\t\t\/* only the first iteration is allowed to override\n\t\t FAILURE_FADE *\/\n\t\tallow_fade = false;\n\n\t\t++i;\n\t\tif (i == end)\n\t\t\ti = std::begin(list);\n\t} while (i != selected);\n\n\t\/* all addresses failed: *\/\n\treturn *i;\n}\ncluster\/PickModulo: add missing include\/*\n * Copyright 2007-2020 Content Management AG\n * All rights reserved.\n *\n * author: Max Kellermann \n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#pragma once\n\n#include \"StickyHash.hxx\"\n#include \"util\/Compiler.h\"\n#include \"util\/Expiry.hxx\"\n\n#include \n\n#include \n\n\/**\n * Pick an address using a #sticky_hash_t module the list size. If\n * that address is failed, pick the next one.\n *\/\ntemplate\ngcc_pure\nconst auto &\nPickModulo(Expiry now, const List &list, sticky_hash_t sticky_hash) noexcept\n{\n\tconst size_t n = std::size(list);\n\tassert(n >= 2);\n\n\tconst size_t modulo = sticky_hash % n;\n\tbool allow_fade = true;\n\n\tconst auto selected = std::next(std::begin(list), modulo);\n\tconst auto end = std::end(list);\n\n\tauto i = selected;\n\tdo {\n\t\tif (list.Check(now, *i, allow_fade))\n\t\t\tbreak;\n\n\t\t\/* only the first iteration is allowed to override\n\t\t FAILURE_FADE *\/\n\t\tallow_fade = false;\n\n\t\t++i;\n\t\tif (i == end)\n\t\t\ti = std::begin(list);\n\t} while (i != selected);\n\n\t\/* all addresses failed: *\/\n\treturn *i;\n}\n<|endoftext|>"} {"text":"#include \"enginesync.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"lib_json\/json.h\"\n\n#include \"processinfo.h\"\n#include \"common.h\"\n#include \"qutils.h\"\n#include \"tempfiles.h\"\n\nusing namespace boost::interprocess;\nusing namespace std;\n\nEngineSync::EngineSync(Analyses *analyses, QObject *parent = 0)\n\t: QObject(parent)\n{\n\t_analyses = analyses;\n\t_engineStarted = false;\n\n\t_log = NULL;\n\t_ppi = 96;\n\n\tconnect(_analyses, SIGNAL(analysisAdded(Analysis*)), this, SLOT(sendMessages()));\n\tconnect(_analyses, SIGNAL(analysisOptionsChanged(Analysis*)), this, SLOT(sendMessages()));\n\n\t\/\/ delay start so as not to increase program start up time\n\tQTimer::singleShot(100, this, SLOT(deleteOrphanedTempFiles()));\n}\n\nEngineSync::~EngineSync()\n{\n\tif (_engineStarted)\n\t{\n\t\tfor (int i = 0; i < _slaveProcesses.size(); i++)\n\t\t{\n\t\t\t_slaveProcesses[i]->terminate();\n\t\t\t_slaveProcesses[i]->kill();\n\t\t}\n\n\t\ttempfiles_deleteAll();\n\t}\n\n\tshared_memory_object::remove(_memoryName.c_str());\n}\n\nvoid EngineSync::start()\n{\n\tif (_engineStarted)\n\t\treturn;\n\n\t_engineStarted = true;\n\n\ttry {\n\n\t\tunsigned long pid = ProcessInfo::currentPID();\n\n\t\tstringstream ss;\n\t\tss << \"JASP-IPC-\" << pid;\n\n\t\t_memoryName = ss.str();\n\n\t\t_channels.push_back(new IPCChannel(_memoryName, 0));\n\n#ifdef QT_NO_DEBUG\n\t\t_channels.push_back(new IPCChannel(_memoryName, 1));\n\t\t_channels.push_back(new IPCChannel(_memoryName, 2));\n\t\t_channels.push_back(new IPCChannel(_memoryName, 3));\n#endif\n\n\t}\n\tcatch (interprocess_exception e)\n\t{\n\t\tqDebug() << \"interprocess exception! \" << e.what() << \"\\n\";\n\t\tthrow e;\n\t}\n\n\tfor (uint i = 0; i < _channels.size(); i++)\n\t{\n\t\t_analysesInProgress.push_back(NULL);\n\t\tstartSlaveProcess(i);\n\t}\n\n\tQTimer *timer;\n\n\ttimer = new QTimer(this);\n\tconnect(timer, SIGNAL(timeout()), this, SLOT(process()));\n\ttimer->start(50);\n\n\ttimer = new QTimer(this);\n\tconnect(timer, SIGNAL(timeout()), this, SLOT(heartbeatTempFiles()));\n\ttimer->start(30000);\n}\n\nbool EngineSync::engineStarted()\n{\n\treturn _engineStarted;\n}\n\nvoid EngineSync::setLog(ActivityLog *log)\n{\n\t_log = log;\n}\n\nvoid EngineSync::setPPI(int ppi)\n{\n\t_ppi = ppi;\n}\n\nvoid EngineSync::sendToProcess(int processNo, Analysis *analysis)\n{\n#ifdef QT_DEBUG\n\tstd::cout << \"send \" << analysis->id() << \" to process \" << processNo << \"\\n\";\n\tstd::cout.flush();\n#endif\n\n\tstring perform;\n\n\tif (analysis->status() == Analysis::Empty)\n\t{\n\t\tperform = \"init\";\n\t\tanalysis->setStatus(Analysis::Initing);\n\t}\n\telse if (analysis->status() == Analysis::Aborting)\n\t{\n\t\tperform = \"abort\";\n\t\tanalysis->setStatus(Analysis::Aborted);\n\t}\n\telse\n\t{\n\t\tperform = \"run\";\n\t\tanalysis->setStatus(Analysis::Running);\n\t}\n\n\t_analysesInProgress[processNo] = analysis;\n\n\tJson::Value json = Json::Value(Json::objectValue);\n\n\tjson[\"id\"] = analysis->id();\n\tjson[\"perform\"] = perform;\n\n\tif (analysis->status() != Analysis::Aborted)\n\t{\n\t\tjson[\"name\"] = analysis->name();\n\t\tjson[\"options\"] = analysis->options()->asJSON();\n\n\t\tJson::Value settings;\n\t\tsettings[\"ppi\"] = _ppi;\n\n\t\tjson[\"settings\"] = settings;\n\t}\n\n\tstring str = json.toStyledString();\n\n\t_channels[processNo]->send(str);\n\n#ifndef QT_NO_DEBUG\n\tcout << str << \"\\n\";\n\tcout.flush();\n#endif\n\n}\n\nvoid EngineSync::process()\n{\n\tfor (int i = 0; i < _channels.size(); i++)\n\t{\n\t\tAnalysis *analysis = _analysesInProgress[i];\n\n\t\tif (analysis == NULL)\n\t\t\tcontinue;\n\n\t\tIPCChannel *channel = _channels[i];\n\t\tstring data;\n\n\t\tif (channel->receive(data))\n\t\t{\n#ifdef QT_DEBUG\n\t\t\tstd::cout << \"message received\\n\";\n\t\t\tstd::cout << data << \"\\n\";\n\t\t\tstd::cout.flush();\n#endif\n\n\t\t\tJson::Reader reader;\n\t\t\tJson::Value json;\n\t\t\treader.parse(data, json);\n\n\t\t\tint id = json.get(\"id\", -1).asInt();\n\t\t\tJson::Value results = json.get(\"results\", Json::nullValue);\n\t\t\tstring status = json.get(\"status\", \"error\").asString();\n\n\t\t\tif (status == \"error\")\n\t\t\t{\n\t\t\t\tanalysis->setStatus(Analysis::Complete);\n\t\t\t\tanalysis->setResults(results);\n\t\t\t\t_analysesInProgress[i] = NULL;\n\t\t\t\tsendMessages();\n\n\t\t\t\tif (_log != NULL)\n\t\t\t\t{\n\t\t\t\t\tQString errorMessage = tq(results.get(\"errorMessage\", \"\").asString());\n\t\t\t\t\tQString info = QString(\"%1,%2\").arg(id).arg(errorMessage);\n\t\t\t\t\t_log->log(\"Analysis Error\", info);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (status == \"complete\")\n\t\t\t{\n\t\t\t\tanalysis->setStatus(Analysis::Complete);\n\t\t\t\tanalysis->setResults(results);\n\t\t\t\t_analysesInProgress[i] = NULL;\n\t\t\t\tsendMessages();\n\t\t\t}\n\t\t\telse if (status == \"running\" && analysis->status() == Analysis::Initing)\n\t\t\t{\n\t\t\t\tanalysis->setStatus(Analysis::Running);\n\t\t\t\tanalysis->setResults(results);\n\t\t\t}\n\t\t\telse if (analysis->status() == Analysis::Running)\n\t\t\t{\n\t\t\t\tanalysis->setResults(results);\n\t\t\t}\n\t\t\telse if (analysis->status() == Analysis::Initing)\n\t\t\t{\n\t\t\t\tif (analysis->isAutorun())\n\t\t\t\t\tanalysis->setStatus(Analysis::Inited);\n\t\t\t\telse\n\t\t\t\t\tanalysis->setStatus(Analysis::InitedAndWaiting);\n\n\t\t\t\tanalysis->setResults(results);\n\t\t\t\t_analysesInProgress[i] = NULL;\n\t\t\t\tsendMessages();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tsendMessages();\n\t\t\t}\n\t\t}\n\n\t}\n}\n\nvoid EngineSync::sendMessages()\n{\n#ifdef QT_DEBUG\n\tstd::cout << \"send messages\\n\";\n\tstd::cout.flush();\n#endif\n\n\tfor (int i = 0; i < _analysesInProgress.size(); i++) \/\/ this loop handles changes in running analyses\n\t{\n\t\tAnalysis *analysis = _analysesInProgress[i];\n\t\tif (analysis != NULL)\n\t\t{\n\t\t\tif (analysis->status() == Analysis::Empty)\n\t\t\t{\n\t\t\t\tsendToProcess(i, analysis);\n\t\t\t}\n\t\t\telse if (analysis->status() == Analysis::Aborting)\n\t\t\t{\n\t\t\t\tsendToProcess(i, analysis);\n\t\t\t\t_analysesInProgress[i] = NULL;\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (Analyses::iterator itr = _analyses->begin(); itr != _analyses->end(); itr++)\n\t{\n\t\tAnalysis *analysis = *itr;\n\t\tif (analysis == NULL)\n\t\t\tcontinue;\n\n\t\tif (analysis->status() == Analysis::Empty)\n\t\t{\n\t\t\tbool sent = false;\n\n\t\t\tfor (int i = 0; i < _analysesInProgress.size(); i++)\n\t\t\t{\n\t\t\t\tif (_analysesInProgress[i] == NULL)\n\t\t\t\t{\n\t\t\t\t\tsendToProcess(i, analysis);\n\t\t\t\t\tsent = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (sent == false) \/\/ no free processes left\n\t\t\t\treturn;\n\t\t}\n\t\telse if (analysis->status() == Analysis::Inited)\n\t\t{\n#ifndef QT_DEBUG\n\t\t\tfor (int i = 1; i < _analysesInProgress.size(); i++) \/\/ don't perform 'runs' on process 0, only inits.\n#else\n\t\t\tfor (int i = 0; i < _analysesInProgress.size(); i++)\n#endif\n\t\t\t{\n\t\t\t\tif (_analysesInProgress[i] == NULL)\n\t\t\t\t{\n\t\t\t\t\tsendToProcess(i, analysis);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n}\n\nvoid EngineSync::startSlaveProcess(int no)\n{\n\tQDir programDir = QFileInfo( QCoreApplication::applicationFilePath() ).absoluteDir();\n\tQProcessEnvironment env = QProcessEnvironment::systemEnvironment();\n\tQString engineExe = QFileInfo( QCoreApplication::applicationFilePath() ).absoluteDir().absoluteFilePath(\"JASPEngine\");\n\n\tQStringList args;\n\targs << QString::number(no);\n\n#ifdef __WIN32__\n\n#if defined(ARCH_32)\n#define ARCH_SUBPATH \"i386\"\n#else\n#define ARCH_SUBPATH \"x64\"\n#endif\n\n\tenv.insert(\"PATH\", programDir.absoluteFilePath(\"R\\\\library\\\\RInside\\\\libs\\\\\" ARCH_SUBPATH) + \";\" + programDir.absoluteFilePath(\"R\\\\library\\\\Rcpp\\\\libs\\\\\" ARCH_SUBPATH) + \";\" + programDir.absoluteFilePath(\"R\\\\bin\\\\\" ARCH_SUBPATH));\n\tenv.insert(\"R_HOME\", programDir.absoluteFilePath(\"R\"));\n\n\tunsigned long processId = ProcessInfo::currentPID();\n args << QString::number(processId);\n\n#undef ARCH_SUBPATH\n\n#elif __APPLE__\n\tenv.insert(\"R_HOME\", programDir.absoluteFilePath(\"..\/Frameworks\/R.framework\/Versions\/3.1\/Resources\"));\n#else\n env.insert(\"LD_LIBRARY_PATH\", programDir.absoluteFilePath(\"R\/lib\") + \";\" + programDir.absoluteFilePath(\"R\/library\/RInside\/lib\") + \";\" + programDir.absoluteFilePath(\"R\/library\/Rcpp\/lib\"));\n\tenv.insert(\"R_HOME\", programDir.absoluteFilePath(\"R\"));\n#endif\n\n\n\tQProcess *slave = new QProcess(this);\n\tslave->setProcessEnvironment(env);\n\tslave->start(engineExe, args);\n\n\t_slaveProcesses.push_back(slave);\n\n\tconnect(slave, SIGNAL(readyReadStandardOutput()), this, SLOT(subProcessStandardOutput()));\n\tconnect(slave, SIGNAL(readyReadStandardError()), this, SLOT(subProcessStandardError()));\n\tconnect(slave, SIGNAL(error(QProcess::ProcessError)), this, SLOT(subProcessError(QProcess::ProcessError)));\n\tconnect(slave, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(subprocessFinished(int,QProcess::ExitStatus)));\n\tconnect(slave, SIGNAL(started()), this, SLOT(subProcessStarted()));\n}\n\nvoid EngineSync::deleteOrphanedTempFiles()\n{\n\ttempfiles_deleteOrphans();\n}\n\nvoid EngineSync::heartbeatTempFiles()\n{\n\ttempfiles_heartbeat();\n}\n\nvoid EngineSync::subProcessStandardOutput()\n{\n\tQProcess *process = qobject_cast(this->sender());\n\tQByteArray data = process->readAllStandardOutput();\n\tqDebug() << QString(data);\n}\n\nvoid EngineSync::subProcessStandardError()\n{\n\tQProcess *process = qobject_cast(this->sender());\n\tqDebug() << process->readAllStandardError();\n}\n\nvoid EngineSync::subProcessStarted()\n{\n\tqDebug() << \"subprocess started\";\n}\n\nvoid EngineSync::subProcessError(QProcess::ProcessError error)\n{\n\temit engineTerminated();\n\n\tqDebug() << \"subprocess error\" << error;\n}\n\nvoid EngineSync::subprocessFinished(int exitCode, QProcess::ExitStatus exitStatus)\n{\n\tqDebug() << \"subprocess finished\" << exitCode;\n}\n\nFix to analysis status transition#include \"enginesync.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"lib_json\/json.h\"\n\n#include \"processinfo.h\"\n#include \"common.h\"\n#include \"qutils.h\"\n#include \"tempfiles.h\"\n\nusing namespace boost::interprocess;\nusing namespace std;\n\nEngineSync::EngineSync(Analyses *analyses, QObject *parent = 0)\n\t: QObject(parent)\n{\n\t_analyses = analyses;\n\t_engineStarted = false;\n\n\t_log = NULL;\n\t_ppi = 96;\n\n\tconnect(_analyses, SIGNAL(analysisAdded(Analysis*)), this, SLOT(sendMessages()));\n\tconnect(_analyses, SIGNAL(analysisOptionsChanged(Analysis*)), this, SLOT(sendMessages()));\n\n\t\/\/ delay start so as not to increase program start up time\n\tQTimer::singleShot(100, this, SLOT(deleteOrphanedTempFiles()));\n}\n\nEngineSync::~EngineSync()\n{\n\tif (_engineStarted)\n\t{\n\t\tfor (int i = 0; i < _slaveProcesses.size(); i++)\n\t\t{\n\t\t\t_slaveProcesses[i]->terminate();\n\t\t\t_slaveProcesses[i]->kill();\n\t\t}\n\n\t\ttempfiles_deleteAll();\n\t}\n\n\tshared_memory_object::remove(_memoryName.c_str());\n}\n\nvoid EngineSync::start()\n{\n\tif (_engineStarted)\n\t\treturn;\n\n\t_engineStarted = true;\n\n\ttry {\n\n\t\tunsigned long pid = ProcessInfo::currentPID();\n\n\t\tstringstream ss;\n\t\tss << \"JASP-IPC-\" << pid;\n\n\t\t_memoryName = ss.str();\n\n\t\t_channels.push_back(new IPCChannel(_memoryName, 0));\n\n#ifdef QT_NO_DEBUG\n\t\t_channels.push_back(new IPCChannel(_memoryName, 1));\n\t\t_channels.push_back(new IPCChannel(_memoryName, 2));\n\t\t_channels.push_back(new IPCChannel(_memoryName, 3));\n#endif\n\n\t}\n\tcatch (interprocess_exception e)\n\t{\n\t\tqDebug() << \"interprocess exception! \" << e.what() << \"\\n\";\n\t\tthrow e;\n\t}\n\n\tfor (uint i = 0; i < _channels.size(); i++)\n\t{\n\t\t_analysesInProgress.push_back(NULL);\n\t\tstartSlaveProcess(i);\n\t}\n\n\tQTimer *timer;\n\n\ttimer = new QTimer(this);\n\tconnect(timer, SIGNAL(timeout()), this, SLOT(process()));\n\ttimer->start(50);\n\n\ttimer = new QTimer(this);\n\tconnect(timer, SIGNAL(timeout()), this, SLOT(heartbeatTempFiles()));\n\ttimer->start(30000);\n}\n\nbool EngineSync::engineStarted()\n{\n\treturn _engineStarted;\n}\n\nvoid EngineSync::setLog(ActivityLog *log)\n{\n\t_log = log;\n}\n\nvoid EngineSync::setPPI(int ppi)\n{\n\t_ppi = ppi;\n}\n\nvoid EngineSync::sendToProcess(int processNo, Analysis *analysis)\n{\n#ifdef QT_DEBUG\n\tstd::cout << \"send \" << analysis->id() << \" to process \" << processNo << \"\\n\";\n\tstd::cout.flush();\n#endif\n\n\tstring perform;\n\n\tif (analysis->status() == Analysis::Empty)\n\t{\n\t\tperform = \"init\";\n\t\tanalysis->setStatus(Analysis::Initing);\n\t}\n\telse if (analysis->status() == Analysis::Aborting)\n\t{\n\t\tperform = \"abort\";\n\t\tanalysis->setStatus(Analysis::Aborted);\n\t}\n\telse\n\t{\n\t\tperform = \"run\";\n\t\tanalysis->setStatus(Analysis::Running);\n\t}\n\n\t_analysesInProgress[processNo] = analysis;\n\n\tJson::Value json = Json::Value(Json::objectValue);\n\n\tjson[\"id\"] = analysis->id();\n\tjson[\"perform\"] = perform;\n\n\tif (analysis->status() != Analysis::Aborted)\n\t{\n\t\tjson[\"name\"] = analysis->name();\n\t\tjson[\"options\"] = analysis->options()->asJSON();\n\n\t\tJson::Value settings;\n\t\tsettings[\"ppi\"] = _ppi;\n\n\t\tjson[\"settings\"] = settings;\n\t}\n\n\tstring str = json.toStyledString();\n\n\t_channels[processNo]->send(str);\n\n#ifndef QT_NO_DEBUG\n\tcout << str << \"\\n\";\n\tcout.flush();\n#endif\n\n}\n\nvoid EngineSync::process()\n{\n\tfor (int i = 0; i < _channels.size(); i++)\n\t{\n\t\tAnalysis *analysis = _analysesInProgress[i];\n\n\t\tif (analysis == NULL)\n\t\t\tcontinue;\n\n\t\tIPCChannel *channel = _channels[i];\n\t\tstring data;\n\n\t\tif (channel->receive(data))\n\t\t{\n#ifdef QT_DEBUG\n\t\t\tstd::cout << \"message received\\n\";\n\t\t\tstd::cout << data << \"\\n\";\n\t\t\tstd::cout.flush();\n#endif\n\n\t\t\tJson::Reader reader;\n\t\t\tJson::Value json;\n\t\t\treader.parse(data, json);\n\n\t\t\tint id = json.get(\"id\", -1).asInt();\n\t\t\tJson::Value results = json.get(\"results\", Json::nullValue);\n\t\t\tstring status = json.get(\"status\", \"error\").asString();\n\n\t\t\tif (status == \"error\")\n\t\t\t{\n\t\t\t\tanalysis->setStatus(Analysis::Complete);\n\t\t\t\tanalysis->setResults(results);\n\t\t\t\t_analysesInProgress[i] = NULL;\n\t\t\t\tsendMessages();\n\n\t\t\t\tif (_log != NULL)\n\t\t\t\t{\n\t\t\t\t\tQString errorMessage = tq(results.get(\"errorMessage\", \"\").asString());\n\t\t\t\t\tQString info = QString(\"%1,%2\").arg(id).arg(errorMessage);\n\t\t\t\t\t_log->log(\"Analysis Error\", info);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (status == \"complete\")\n\t\t\t{\n\t\t\t\tanalysis->setStatus(Analysis::Complete);\n\t\t\t\tanalysis->setResults(results);\n\t\t\t\t_analysesInProgress[i] = NULL;\n\t\t\t\tsendMessages();\n\t\t\t}\n\t\t\telse if (status == \"inited\")\n\t\t\t{\n\t\t\t\tif (analysis->isAutorun())\n\t\t\t\t\tanalysis->setStatus(Analysis::Inited);\n\t\t\t\telse\n\t\t\t\t\tanalysis->setStatus(Analysis::InitedAndWaiting);\n\n\t\t\t\tanalysis->setResults(results);\n\t\t\t\t_analysesInProgress[i] = NULL;\n\t\t\t\tsendMessages();\n\t\t\t}\n\t\t\telse if (status == \"running\" && analysis->status() == Analysis::Initing)\n\t\t\t{\n\t\t\t\tanalysis->setStatus(Analysis::Running);\n\t\t\t\tanalysis->setResults(results);\n\t\t\t}\n\t\t\telse if (analysis->status() == Analysis::Running)\n\t\t\t{\n\t\t\t\tanalysis->setResults(results);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tsendMessages();\n\t\t\t}\n\t\t}\n\n\t}\n}\n\nvoid EngineSync::sendMessages()\n{\n#ifdef QT_DEBUG\n\tstd::cout << \"send messages\\n\";\n\tstd::cout.flush();\n#endif\n\n\tfor (int i = 0; i < _analysesInProgress.size(); i++) \/\/ this loop handles changes in running analyses\n\t{\n\t\tAnalysis *analysis = _analysesInProgress[i];\n\t\tif (analysis != NULL)\n\t\t{\n\t\t\tif (analysis->status() == Analysis::Empty)\n\t\t\t{\n\t\t\t\tsendToProcess(i, analysis);\n\t\t\t}\n\t\t\telse if (analysis->status() == Analysis::Aborting)\n\t\t\t{\n\t\t\t\tsendToProcess(i, analysis);\n\t\t\t\t_analysesInProgress[i] = NULL;\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (Analyses::iterator itr = _analyses->begin(); itr != _analyses->end(); itr++)\n\t{\n\t\tAnalysis *analysis = *itr;\n\t\tif (analysis == NULL)\n\t\t\tcontinue;\n\n\t\tif (analysis->status() == Analysis::Empty)\n\t\t{\n\t\t\tbool sent = false;\n\n\t\t\tfor (int i = 0; i < _analysesInProgress.size(); i++)\n\t\t\t{\n\t\t\t\tif (_analysesInProgress[i] == NULL)\n\t\t\t\t{\n\t\t\t\t\tsendToProcess(i, analysis);\n\t\t\t\t\tsent = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (sent == false) \/\/ no free processes left\n\t\t\t\treturn;\n\t\t}\n\t\telse if (analysis->status() == Analysis::Inited)\n\t\t{\n#ifndef QT_DEBUG\n\t\t\tfor (int i = 1; i < _analysesInProgress.size(); i++) \/\/ don't perform 'runs' on process 0, only inits.\n#else\n\t\t\tfor (int i = 0; i < _analysesInProgress.size(); i++)\n#endif\n\t\t\t{\n\t\t\t\tif (_analysesInProgress[i] == NULL)\n\t\t\t\t{\n\t\t\t\t\tsendToProcess(i, analysis);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n}\n\nvoid EngineSync::startSlaveProcess(int no)\n{\n\tQDir programDir = QFileInfo( QCoreApplication::applicationFilePath() ).absoluteDir();\n\tQProcessEnvironment env = QProcessEnvironment::systemEnvironment();\n\tQString engineExe = QFileInfo( QCoreApplication::applicationFilePath() ).absoluteDir().absoluteFilePath(\"JASPEngine\");\n\n\tQStringList args;\n\targs << QString::number(no);\n\n#ifdef __WIN32__\n\n#if defined(ARCH_32)\n#define ARCH_SUBPATH \"i386\"\n#else\n#define ARCH_SUBPATH \"x64\"\n#endif\n\n\tenv.insert(\"PATH\", programDir.absoluteFilePath(\"R\\\\library\\\\RInside\\\\libs\\\\\" ARCH_SUBPATH) + \";\" + programDir.absoluteFilePath(\"R\\\\library\\\\Rcpp\\\\libs\\\\\" ARCH_SUBPATH) + \";\" + programDir.absoluteFilePath(\"R\\\\bin\\\\\" ARCH_SUBPATH));\n\tenv.insert(\"R_HOME\", programDir.absoluteFilePath(\"R\"));\n\n\tunsigned long processId = ProcessInfo::currentPID();\n args << QString::number(processId);\n\n#undef ARCH_SUBPATH\n\n#elif __APPLE__\n\tenv.insert(\"R_HOME\", programDir.absoluteFilePath(\"..\/Frameworks\/R.framework\/Versions\/3.1\/Resources\"));\n#else\n env.insert(\"LD_LIBRARY_PATH\", programDir.absoluteFilePath(\"R\/lib\") + \";\" + programDir.absoluteFilePath(\"R\/library\/RInside\/lib\") + \";\" + programDir.absoluteFilePath(\"R\/library\/Rcpp\/lib\"));\n\tenv.insert(\"R_HOME\", programDir.absoluteFilePath(\"R\"));\n#endif\n\n\n\tQProcess *slave = new QProcess(this);\n\tslave->setProcessEnvironment(env);\n\tslave->start(engineExe, args);\n\n\t_slaveProcesses.push_back(slave);\n\n\tconnect(slave, SIGNAL(readyReadStandardOutput()), this, SLOT(subProcessStandardOutput()));\n\tconnect(slave, SIGNAL(readyReadStandardError()), this, SLOT(subProcessStandardError()));\n\tconnect(slave, SIGNAL(error(QProcess::ProcessError)), this, SLOT(subProcessError(QProcess::ProcessError)));\n\tconnect(slave, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(subprocessFinished(int,QProcess::ExitStatus)));\n\tconnect(slave, SIGNAL(started()), this, SLOT(subProcessStarted()));\n}\n\nvoid EngineSync::deleteOrphanedTempFiles()\n{\n\ttempfiles_deleteOrphans();\n}\n\nvoid EngineSync::heartbeatTempFiles()\n{\n\ttempfiles_heartbeat();\n}\n\nvoid EngineSync::subProcessStandardOutput()\n{\n\tQProcess *process = qobject_cast(this->sender());\n\tQByteArray data = process->readAllStandardOutput();\n\tqDebug() << QString(data);\n}\n\nvoid EngineSync::subProcessStandardError()\n{\n\tQProcess *process = qobject_cast(this->sender());\n\tqDebug() << process->readAllStandardError();\n}\n\nvoid EngineSync::subProcessStarted()\n{\n\tqDebug() << \"subprocess started\";\n}\n\nvoid EngineSync::subProcessError(QProcess::ProcessError error)\n{\n\temit engineTerminated();\n\n\tqDebug() << \"subprocess error\" << error;\n}\n\nvoid EngineSync::subprocessFinished(int exitCode, QProcess::ExitStatus exitStatus)\n{\n\tqDebug() << \"subprocess finished\" << exitCode;\n}\n\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \"syntax.hpp\"\n\n\nnamespace popo {\nnamespace semantic {\n\n enum struct function_numbers{\n \/\/special form\n DEFINE = -1,\n LAMBDA = -2,\n QUOTA = -3,\n IF = -4,\n\n \/\/built in function\n PLUS = -5,\n MINUS = -6,\n MULTIPLY = -7,\n DIVIDE = -8,\n };\n\n \/\/ symbol table\n enum struct entry_type { value, function, not_found};\n struct symbol_table_entry {\n\n public:\n symbol_table_entry(entry_type t) : type_(t){};\n symbol_table_entry() : type_(entry_type::not_found){};\n\n public:\n entry_type type_;\n };\n\n struct function_entry : public symbol_table_entry {\n\n public:\n function_entry(int arg_num, int entry_num)\n : symbol_table_entry(entry_type::function),\n argument_num_(arg_num),\n table_entry_num_(entry_num) {};\n\n function_entry(int arg_num, function_numbers num)\n : function_entry(arg_num, static_cast(num)){};\n\n public:\n int argument_num_;\n int table_entry_num_;\n };\n\n struct value_entry : public symbol_table_entry {\n\n public:\n enum struct value_type { INT, STRING, SYMBOL, };\n\n public:\n value_entry(std::string n, value_type t)\n : symbol_table_entry(entry_type::value), type_(t)\n {\n if (t == value_type::STRING) {\n v_string = n;\n } else if (t == value_type::SYMBOL) {\n v_symbol = n;\n }\n };\n\n value_entry(int n, value_type t)\n : symbol_table_entry(entry_type::value), type_(t)\n {\n v_int = n;\n };\n\n private:\n union {\n int v_int;\n std::string v_string;\n std::string v_symbol;\n };\n value_type type_;\n };\n\n const std::pair special_form[] = {\n std::pair(\n \"define\", function_entry(2, function_numbers::DEFINE)),\n \/\/ (define symbol atom | list | function)\n std::pair(\n \"lambda\", function_entry(2, function_numbers::LAMBDA)),\n \/\/ (lambda list list) -> function\n std::pair(\n \"quota\", function_entry(1, function_numbers::QUOTA)),\n \/\/ (quota list) -> list\n std::pair(\n \"if\", function_entry(2, function_numbers::IF))\n \/\/ (if t | nil | function function)\n };\n\n const std::pair built_in_function[] = {\n std::pair(\n \"+\", function_entry(2, function_numbers::PLUS)),\n\n std::pair(\n \"-\", function_entry(2, function_numbers::MINUS)),\n\n std::pair(\n \"*\", function_entry(2, function_numbers::MULTIPLY)),\n\n std::pair(\n \"\/\", function_entry(2, function_numbers::DIVIDE))\n };\n\n template \n class semantic_analyser {\n\n public:\n semantic_analyser(const Iteratable& itr)\n : parser_(itr), symbol_table(), function_table()\n {\n for (auto&& sf : special_form) {\n symbol_table.table_stack.push_front(sf);\n }\n\n for (auto&& bf : built_in_function) {\n symbol_table.table_stack.push_front(bf);\n }\n\n analyse();\n };\n\n private:\n auto analyse() -> void\n {\n auto function_name =\n static_cast(\n static_cast(parser_.s_exp_parse().get())\n ->car.get())->val;\n\n\n auto pair = search_function(function_name);\n assert(entry_type::not_found != pair.second.type_);\n\n \/\/TODO: \n }\n\n\n auto search_function(std::string func_name)\n -> std::pair\n {\n for(auto& data: symbol_table.table_stack){\n std::cout << data.first << std::endl;\n if(data.first == func_name){\n return data;\n }\n }\n\n return std::make_pair(\"\", symbol_table_entry());\n }\n\n\n private:\n syntax::s_expression_parser parser_;\n\n struct symbol_table_stack\n {\n public:\n symbol_table_stack() : table_stack(), local_symbol_num(0) {};\n\n public:\n std::list> table_stack;\n int local_symbol_num;\n } symbol_table;\n\n std::vector> function_table;\n };\n\n\n} \/\/ namespace semantic\n} \/\/ namespace popo\nfix analyser#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \"syntax.hpp\"\n\n\nnamespace popo {\nnamespace semantic {\n\n enum struct function_numbers{\n \/\/special form\n DEFINE = -1,\n LAMBDA = -2,\n QUOTA = -3,\n IF = -4,\n\n \/\/built in function\n PLUS = -5,\n MINUS = -6,\n MULTIPLY = -7,\n DIVIDE = -8,\n };\n\n \/\/ symbol table\n enum struct entry_type { value, function, not_found};\n struct symbol_table_entry {\n\n public:\n symbol_table_entry(entry_type t) : type_(t){};\n symbol_table_entry() : type_(entry_type::not_found){};\n virtual ~symbol_table_entry() {};\n\n public:\n entry_type type_;\n };\n\n struct function_entry : public symbol_table_entry {\n\n public:\n function_entry(int arg_num, int entry_num)\n : symbol_table_entry(entry_type::function),\n argument_num_(arg_num),\n table_entry_num_(entry_num) {};\n\n function_entry(int arg_num, function_numbers num)\n : function_entry(arg_num, static_cast(num)){};\n\n virtual ~function_entry(){};\n\n public:\n int argument_num_;\n int table_entry_num_;\n };\n\n struct value_entry : public symbol_table_entry {\n\n public:\n enum struct value_type { INT, STRING, SYMBOL, };\n\n public:\n value_entry(std::string n, value_type t)\n : symbol_table_entry(entry_type::value), type_(t)\n {\n if (t == value_type::STRING) {\n v_string = n;\n } else if (t == value_type::SYMBOL) {\n v_symbol = n;\n }\n };\n\n value_entry(int n, value_type t)\n : symbol_table_entry(entry_type::value), type_(t)\n {\n v_int = n;\n };\n\n virtual ~value_entry() {};\n\n private:\n union {\n int v_int;\n std::string v_string;\n std::string v_symbol;\n };\n value_type type_;\n };\n\n const std::pair special_form[] = {\n std::pair(\n \"define\", function_entry(2, function_numbers::DEFINE)),\n \/\/ (define symbol atom | list | function)\n std::pair(\n \"lambda\", function_entry(2, function_numbers::LAMBDA)),\n \/\/ (lambda list list) -> function\n std::pair(\n \"quota\", function_entry(1, function_numbers::QUOTA)),\n \/\/ (quota list) -> list\n std::pair(\n \"if\", function_entry(2, function_numbers::IF))\n \/\/ (if t | nil | function function)\n };\n\n const std::pair built_in_function[] = {\n std::pair(\n \"+\", function_entry(2, function_numbers::PLUS)),\n\n std::pair(\n \"-\", function_entry(2, function_numbers::MINUS)),\n\n std::pair(\n \"*\", function_entry(2, function_numbers::MULTIPLY)),\n\n std::pair(\n \"\/\", function_entry(2, function_numbers::DIVIDE))\n };\n\n template \n class semantic_analyser {\n\n public:\n semantic_analyser(const Iteratable& itr)\n : parser_(itr), symbol_table(), function_table()\n {\n for (auto&& sf : special_form) {\n symbol_table.table_stack.push_front(sf);\n }\n\n for (auto&& bf : built_in_function) {\n symbol_table.table_stack.push_front(bf);\n }\n\n analyse();\n };\n\n private:\n\n auto check_argument_num(const syntax::expr_node* cons, int argc)\n -> bool\n {\n if (syntax::node_type::nil == cons->type && 0 == argc) {\n return true;\n } else if (argc < 0) {\n return false;\n }\n\n if(syntax::node_type::nil == cons->type){\n\n if(argc == 0){\n return true;\n }\n else {\n return false;\n }\n }\n else if(argc < 0){\n return false;\n }\n\n return check_argument_num(static_cast(cons)->cdr.get(), argc--);\n }\n\n auto analyse() -> void\n {\n\n std::unique_ptr cons(\n static_cast(\n parser_.s_exp_parse().release()));\n\n \/\/ type check\n assert(syntax::node_type::string == cons->car->type);\n\n auto function_name =\n static_cast(cons->car.get())->val;\n\n auto pair = search_function(function_name);\n \/\/ check function definition\n assert(entry_type::function == pair.second.type_);\n\n \/\/TODO しらべる below code\n\/\/ auto arg_num = dynamic_cast(pair.second).argument_num_;\n\/\/ std::cout << \"arg: \" << arg_num << std::endl;\n \/\/ argument check of number\n\/\/ assert(check_argument_num(cons.get(), arg_num));\n\n\n \/\/ TODO:\n }\n\n\n auto search_function(std::string func_name)\n -> std::pair\n {\n for(auto& data: symbol_table.table_stack){\n\/\/ std::cout << data.second.argument_num_ << std::endl;\n if(data.first == func_name){\n return data;\n }\n }\n\n return std::make_pair(\"\", symbol_table_entry());\n }\n\n\n private:\n syntax::s_expression_parser parser_;\n\n struct symbol_table_stack\n {\n public:\n symbol_table_stack() : table_stack(), local_symbol_num(0) {};\n\n public:\n std::list> table_stack;\n int local_symbol_num;\n } symbol_table;\n\n std::vector> function_table;\n };\n\n\n} \/\/ namespace semantic\n} \/\/ namespace popo\n<|endoftext|>"} {"text":"\/\/ Copyright 2012 Alessio Sclocco \n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n\n#ifndef READ_DATA_HPP\n#define READ_DATA_HPP\n\nnamespace AstroData {\n\ntemplate< typename T > void readSIGPROC(Observation & observation, const unsigned int bytestoSkip, std::string inputFilename, std::vector< std::vector< T > * > & data, unsigned int firstSecond = 0);\ntemplate< typename T > void readLOFAR(std::string headerFilename, std::string rawFilename, Observation & observation, std::vector< std::vector< T > * > & data, unsigned int nrSeconds = 0, unsigned int firstSecond = 0);\n\n\n\/\/ Implementation\n\ntemplate< typename T > void readSIGPROC(Observation & observation, unsigned int bytesToSkip, std::string inputFilename, std::vector< std::vector< T > * > & data, unsigned int firstSecond) {\n\tstd::ifstream inputFile;\n\tconst unsigned int BUFFER_DIM = 4;\n\tchar * buffer = new char [BUFFER_DIM];\n\n\tinputFile.open(inputFilename.c_str(), std::ios::binary);\n\tinputFile.sync_with_stdio(false);\n\tinputFile.seekg(bytesToSkip, std::ios::beg);\n\tfor ( unsigned int second = 0; second < observation.getNrSeconds(); second++ ) {\n\t\tdata.at(second) = new std::vector< T >(observation.getNrSamplesPerPaddedSecond() * observation.getNrChannels());\n\n\t\tfor ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {\n\t\t\tfor ( unsigned int channel = observation.getNrChannels(); channel > 0; channel-- ) {\n\t\t\t\tinputFile.read(buffer, BUFFER_DIM);\n data.at(second)[(static_cast< long long unsigned int >(channel - 1) * observation.getNrSamplesPerPaddedSecond()) + sample] = *(reinterpret_cast< T * >(buffer));\n\t\t\t}\n\t\t}\n\t}\n\tinputFile.close();\n\n\tdelete [] buffer;\n}\n\n\ntemplate< typename T > void readLOFAR(std::string headerFilename, std::string rawFilename, Observation & observation, std::vector< std::vector< T > * > & data, unsigned int nrSeconds, unsigned int firstSecond) {\n unsigned int nrSubbands, nrChannels;\n float minFreq, channelBandwidth;\n\t\/\/ Read the HDF5 file with the metadata\n\tH5::H5File headerFile = H5::H5File(headerFilename, H5F_ACC_RDONLY);\n\tH5::FloatType typeDouble = H5::FloatType(H5::PredType::NATIVE_DOUBLE);\n\tdouble valueDouble = 0.0;\n\tH5::IntType typeUInt = H5::IntType(H5::PredType::NATIVE_UINT);\n\tunsigned int valueUInt = 0;\n\n\tH5::Group currentNode = headerFile.openGroup(\"\/\");\n\tcurrentNode.openAttribute(\"OBSERVATION_FREQUENCY_MIN\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n minFreq = valueDouble;\n\tcurrentNode = currentNode.openGroup(currentNode.getObjnameByIdx(0));\n\tcurrentNode.openAttribute(\"TOTAL_INTEGRATION_TIME\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n\tdouble totalIntegrationTime = valueDouble;\n\tcurrentNode.openAttribute(\"NOF_BEAMS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tobservation.setNrBeams(valueUInt);\n\tcurrentNode = currentNode.openGroup(currentNode.getObjnameByIdx(0));\n\tcurrentNode.openAttribute(\"NOF_SAMPLES\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tunsigned int totalSamples = valueUInt;\n\tcurrentNode.openAttribute(\"NOF_STATIONS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tobservation.setNrStations(valueUInt);\n\tcurrentNode.openAttribute(\"CHANNELS_PER_SUBBAND\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tnrChannels = valueUInt;\n\tcurrentNode.openAttribute(\"CHANNEL_WIDTH\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n channelBandwidth = valueDouble \/ 1000000;\n\tH5::DataSet currentData = currentNode.openDataSet(\"STOKES_0\");\n\tcurrentData.openAttribute(\"NOF_SUBBANDS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tnrSubbands = valueUInt;\n\theaderFile.close();\n\n\tobservation.setNrSamplesPerSecond(static_cast< unsigned int >(totalSamples \/ totalIntegrationTime));\n\tif ( nrSeconds == 0 ) {\n\t\tobservation.setNrSeconds(static_cast< unsigned int >(totalIntegrationTime));\n\t} else {\n\t\tif ( static_cast< unsigned int >(totalIntegrationTime) >= (firstSecond + nrSeconds) ) {\n\t\t\tobservation.setNrSeconds(nrSeconds);\n\t\t} else {\n\t\t\tobservation.setNrSeconds(static_cast< unsigned int >(totalIntegrationTime) - firstSecond);\n\t\t}\n\t}\n observation.setFrequencyRange(nrSubbands * nrChannels, minFreq, channelBandwidth);\n\n\t\/\/ Read the raw file with the actual data\n\tstd::ifstream rawFile;\n\trawFile.open(rawFilename.c_str(), std::ios::binary);\n\trawFile.sync_with_stdio(false);\n\tif ( firstSecond > 0 ) {\n\t\trawFile.seekg(firstSecond * observation.getNrSamplesPerSecond() * nrSubbands * nrChannels, std::ios::beg);\n\t}\n\tdata.resize(observation.getNrSeconds());\n\n\tchar * word = new char [4];\n\tfor ( unsigned int second = 0; second < observation.getNrSeconds(); second++ ) {\n\t\tdata.at(second) = new std::vector< T >(observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond());\n\t\tfor ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {\n\t\t\tfor ( unsigned int subband = 0; subband < nrSubbands; subband++ ) {\n\t\t\t\tfor ( unsigned int channel = 0; channel < nrChannels; channel++ ) {\n\t\t\t\t\trawFile.read(word, 4);\n isa::utils::bigEndianToLittleEndian(word);\n data.at(second)[(static_cast< long long unsigned int >(second) * observation.getNrSamplesPerSecond()) + sample] = *(reinterpret_cast< T * >(word));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\trawFile.close();\n\tdelete [] word;\n}\n\n} \/\/ AstroData\n\n#endif \/\/ READ_DATA_HPP\n\nConvert the pointer to an object for the assignments.\/\/ Copyright 2012 Alessio Sclocco \n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n\n#ifndef READ_DATA_HPP\n#define READ_DATA_HPP\n\nnamespace AstroData {\n\ntemplate< typename T > void readSIGPROC(Observation & observation, const unsigned int bytestoSkip, std::string inputFilename, std::vector< std::vector< T > * > & data, unsigned int firstSecond = 0);\ntemplate< typename T > void readLOFAR(std::string headerFilename, std::string rawFilename, Observation & observation, std::vector< std::vector< T > * > & data, unsigned int nrSeconds = 0, unsigned int firstSecond = 0);\n\n\n\/\/ Implementation\n\ntemplate< typename T > void readSIGPROC(Observation & observation, unsigned int bytesToSkip, std::string inputFilename, std::vector< std::vector< T > * > & data, unsigned int firstSecond) {\n\tstd::ifstream inputFile;\n\tconst unsigned int BUFFER_DIM = 4;\n\tchar * buffer = new char [BUFFER_DIM];\n\n\tinputFile.open(inputFilename.c_str(), std::ios::binary);\n\tinputFile.sync_with_stdio(false);\n\tinputFile.seekg(bytesToSkip, std::ios::beg);\n\tfor ( unsigned int second = 0; second < observation.getNrSeconds(); second++ ) {\n\t\tdata.at(second) = new std::vector< T >(observation.getNrSamplesPerPaddedSecond() * observation.getNrChannels());\n\n\t\tfor ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {\n\t\t\tfor ( unsigned int channel = observation.getNrChannels(); channel > 0; channel-- ) {\n\t\t\t\tinputFile.read(buffer, BUFFER_DIM);\n *(data.at(second))[(static_cast< long long unsigned int >(channel - 1) * observation.getNrSamplesPerPaddedSecond()) + sample] = *(reinterpret_cast< T * >(buffer));\n\t\t\t}\n\t\t}\n\t}\n\tinputFile.close();\n\n\tdelete [] buffer;\n}\n\n\ntemplate< typename T > void readLOFAR(std::string headerFilename, std::string rawFilename, Observation & observation, std::vector< std::vector< T > * > & data, unsigned int nrSeconds, unsigned int firstSecond) {\n unsigned int nrSubbands, nrChannels;\n float minFreq, channelBandwidth;\n\t\/\/ Read the HDF5 file with the metadata\n\tH5::H5File headerFile = H5::H5File(headerFilename, H5F_ACC_RDONLY);\n\tH5::FloatType typeDouble = H5::FloatType(H5::PredType::NATIVE_DOUBLE);\n\tdouble valueDouble = 0.0;\n\tH5::IntType typeUInt = H5::IntType(H5::PredType::NATIVE_UINT);\n\tunsigned int valueUInt = 0;\n\n\tH5::Group currentNode = headerFile.openGroup(\"\/\");\n\tcurrentNode.openAttribute(\"OBSERVATION_FREQUENCY_MIN\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n minFreq = valueDouble;\n\tcurrentNode = currentNode.openGroup(currentNode.getObjnameByIdx(0));\n\tcurrentNode.openAttribute(\"TOTAL_INTEGRATION_TIME\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n\tdouble totalIntegrationTime = valueDouble;\n\tcurrentNode.openAttribute(\"NOF_BEAMS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tobservation.setNrBeams(valueUInt);\n\tcurrentNode = currentNode.openGroup(currentNode.getObjnameByIdx(0));\n\tcurrentNode.openAttribute(\"NOF_SAMPLES\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tunsigned int totalSamples = valueUInt;\n\tcurrentNode.openAttribute(\"NOF_STATIONS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tobservation.setNrStations(valueUInt);\n\tcurrentNode.openAttribute(\"CHANNELS_PER_SUBBAND\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tnrChannels = valueUInt;\n\tcurrentNode.openAttribute(\"CHANNEL_WIDTH\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n channelBandwidth = valueDouble \/ 1000000;\n\tH5::DataSet currentData = currentNode.openDataSet(\"STOKES_0\");\n\tcurrentData.openAttribute(\"NOF_SUBBANDS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n\tnrSubbands = valueUInt;\n\theaderFile.close();\n\n\tobservation.setNrSamplesPerSecond(static_cast< unsigned int >(totalSamples \/ totalIntegrationTime));\n\tif ( nrSeconds == 0 ) {\n\t\tobservation.setNrSeconds(static_cast< unsigned int >(totalIntegrationTime));\n\t} else {\n\t\tif ( static_cast< unsigned int >(totalIntegrationTime) >= (firstSecond + nrSeconds) ) {\n\t\t\tobservation.setNrSeconds(nrSeconds);\n\t\t} else {\n\t\t\tobservation.setNrSeconds(static_cast< unsigned int >(totalIntegrationTime) - firstSecond);\n\t\t}\n\t}\n observation.setFrequencyRange(nrSubbands * nrChannels, minFreq, channelBandwidth);\n\n\t\/\/ Read the raw file with the actual data\n\tstd::ifstream rawFile;\n\trawFile.open(rawFilename.c_str(), std::ios::binary);\n\trawFile.sync_with_stdio(false);\n\tif ( firstSecond > 0 ) {\n\t\trawFile.seekg(firstSecond * observation.getNrSamplesPerSecond() * nrSubbands * nrChannels, std::ios::beg);\n\t}\n\tdata.resize(observation.getNrSeconds());\n\n\tchar * word = new char [4];\n\tfor ( unsigned int second = 0; second < observation.getNrSeconds(); second++ ) {\n\t\tdata.at(second) = new std::vector< T >(observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond());\n\t\tfor ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {\n\t\t\tfor ( unsigned int subband = 0; subband < nrSubbands; subband++ ) {\n\t\t\t\tfor ( unsigned int channel = 0; channel < nrChannels; channel++ ) {\n\t\t\t\t\trawFile.read(word, 4);\n isa::utils::bigEndianToLittleEndian(word);\n *(data.at(second))[(static_cast< long long unsigned int >(second) * observation.getNrSamplesPerSecond()) + sample] = *(reinterpret_cast< T * >(word));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\trawFile.close();\n\tdelete [] word;\n}\n\n} \/\/ AstroData\n\n#endif \/\/ READ_DATA_HPP\n\n<|endoftext|>"} {"text":"\/*\n\tFlexisip, a flexible SIP proxy server with media capabilities.\n\tCopyright (C) 2010-2015 Belledonne Communications SARL, All rights reserved.\n\n\tThis program is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU Affero General Public License as\n\tpublished by the Free Software Foundation, either version 3 of the\n\tLicense, or (at your option) any later version.\n\n\tThis program is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU Affero General Public License for more details.\n\n\tYou should have received a copy of the GNU Affero General Public License\n\talong with this program. If not, see .\n*\/\n\n#ifndef eventlogs_hh\n#define eventlogs_hh\n\n#include \n#include \n\n#include \"..\/common.hh\"\n#include \n#include \n#include \n#include \n\nclass EventLog {\n\tfriend class FilesystemEventLogWriter;\n\tfriend class DataBaseEventLogWriter;\n\tfriend class EventLogDb;\n\npublic:\n\n\tEventLog(const sip_t *sip);\n\tvirtual ~EventLog();\n\tvoid setCompleted();\n\tvoid setStatusCode(int sip_status, const char *reason);\n\tbool isCompleted() const {\n\t\treturn mCompleted;\n\t}\n\nprotected:\n\n\tsu_home_t mHome;\n\tsip_from_t *mFrom;\n\tsip_to_t *mTo;\n\tsip_user_agent_t *mUA;\n\ttime_t mDate;\n\tint mStatusCode;\n\tstd::string mReason;\n\tbool mCompleted;\n\tstd::string mCallId;\n\tclass Init {\n\tpublic:\n\t\tInit();\n\t};\n\tstatic Init evStaticInit;\n};\n\nclass RegistrationLog : public EventLog {\n\tfriend class FilesystemEventLogWriter;\n\tfriend class DataBaseEventLogWriter;\n\tfriend class RegistrationLogDb;\n\npublic:\n\n\t\/\/ Explicit values are necessary for soci. Do not change this.\n\tenum Type {\n\t\tRegister = 0,\n\t\tUnregister = 1,\n\t\tExpired = 2\n\t};\n\n\tRegistrationLog(const sip_t *sip, const sip_contact_t *contacts);\n\nprivate:\n\tType mType;\n\tsip_contact_t *mContacts;\n};\n\nclass CallLog : public EventLog {\n\tfriend class FilesystemEventLogWriter;\n\tfriend class DataBaseEventLogWriter;\n\tfriend class CallLogDb;\n\npublic:\n\tCallLog(const sip_t *sip);\n\tvoid setCancelled();\n\nprivate:\n\tbool mCancelled;\n};\n\nclass MessageLog : public EventLog {\n\tfriend class FilesystemEventLogWriter;\n\tfriend class DataBaseEventLogWriter;\n\tfriend class MessageLogDb;\n\npublic:\n\n\t\/\/ Explicit values is necessary for soci. Do not change this.\n\tenum ReportType {\n\t\tReceivedFromUser = 0,\n\t\tDeliveredToUser = 1\n\t};\n\n\tMessageLog(const sip_t *sip, ReportType report);\n\tvoid setDestination(const url_t *dest);\n\nprivate:\n\n\tReportType mReportType;\n\turl_t *mUri; \/\/ destination uri of message\n};\n\nclass AuthLog: public EventLog {\n\tfriend class FilesystemEventLogWriter;\n\tfriend class DataBaseEventLogWriter;\n\tfriend class AuthLogDb;\n\npublic:\n\n\tAuthLog(const sip_t *sip, bool userExists);\n\nprivate:\n\n\tvoid setOrigin(const sip_via_t *via);\n\n\turl_t *mOrigin;\n\tstd::string mMethod;\n\tbool mUserExists;\n};\n\nclass CallQualityStatisticsLog: public EventLog {\n\tfriend class FilesystemEventLogWriter;\n\tfriend class DataBaseEventLogWriter;\n\tfriend class CallQualityStatisticsLogDb;\n\npublic:\n\n\tCallQualityStatisticsLog(const sip_t *sip);\n\nprivate:\n\n\t\/\/ Note on `soci`: The `char *` support is dead since 2008...\n\t\/\/ See: https:\/\/github.com\/SOCI\/soci\/commit\/25c704ac4cb7bb0135dabc2421a1281fb868a511\n\t\/\/ It's necessary to create a hard copy with a `string`.\n\tstd::string mReport;\n};\n\nclass EventLogWriter {\npublic:\n\n\tvirtual void write(const std::shared_ptr &evlog) = 0;\n\tvirtual ~EventLogWriter();\n};\n\nclass FilesystemEventLogWriter: public EventLogWriter {\npublic:\n\n\tFilesystemEventLogWriter(const std::string &rootpath);\n\tvirtual void write(const std::shared_ptr &evlog);\n\tbool isReady() const;\n\nprivate:\n\n\tint openPath(const url_t *uri, const char *kind, time_t curtime, int errorcode = 0);\n\tvoid writeRegistrationLog(const std::shared_ptr &evlog);\n\tvoid writeCallLog(const std::shared_ptr &clog);\n\tvoid writeCallQualityStatisticsLog(const std::shared_ptr &mlog);\n\tvoid writeMessageLog(const std::shared_ptr &mlog);\n\tvoid writeAuthLog(const std::shared_ptr &alog);\n\tvoid writeErrorLog(const std::shared_ptr &log, const char *kind, const std::string &logstr);\n\tstd::string mRootPath;\n\tbool mIsReady;\n};\n\n#if ENABLE_SOCI\n\n#include \n#include \"utils\/threadpool.hh\"\n\nclass DataBaseEventLogWriter: public EventLogWriter {\npublic:\n\n\tenum Backend {\n\t\tMysql = 0,\n\t\tSqlite3 = 1,\n\t\tPostgresql = 2\n\t};\n\n\tDataBaseEventLogWriter(\n\t\tconst std::string &backendString, const std::string &connectionString,\n\t\tint maxQueueSize, int nbThreadsMax\n\t);\n\t~DataBaseEventLogWriter();\n\n\tvirtual void write(const std::shared_ptr &evlog);\n\tbool isReady() const;\n\nprivate:\n\n\tvoid initTables(Backend backend);\n\n\tstatic void writeEventLog(const std::shared_ptr &evlog, int typeId, soci::session &sql);\n\n\tvoid writeRegistrationLog(const std::shared_ptr &evlog);\n\tvoid writeCallLog(const std::shared_ptr &evlog);\n\tvoid writeMessageLog(const std::shared_ptr &evlog);\n\tvoid writeAuthLog(const std::shared_ptr &evlog);\n\tvoid writeCallQualityStatisticsLog(const std::shared_ptr &evlog);\n\n\tvoid writeEventFromQueue();\n\n\tbool mIsReady;\n\tstd::mutex mMutex;\n\tstd::queue> mListLogs;\n\n\tsoci::connection_pool *mConnectionPool;\n\tThreadPool *mThreadPool;\n\n\tsize_t mMaxQueueSize;\n\n\tstd::string mInsertReq[5];\n};\n\n#endif\n\n#endif\nDisable deprecation warnings while including soci.h with GCC\/*\n\tFlexisip, a flexible SIP proxy server with media capabilities.\n\tCopyright (C) 2010-2015 Belledonne Communications SARL, All rights reserved.\n\n\tThis program is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU Affero General Public License as\n\tpublished by the Free Software Foundation, either version 3 of the\n\tLicense, or (at your option) any later version.\n\n\tThis program is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU Affero General Public License for more details.\n\n\tYou should have received a copy of the GNU Affero General Public License\n\talong with this program. If not, see .\n*\/\n\n#ifndef eventlogs_hh\n#define eventlogs_hh\n\n#include \n#include \n\n#include \"..\/common.hh\"\n#include \n#include \n#include \n#include \n\nclass EventLog {\n\tfriend class FilesystemEventLogWriter;\n\tfriend class DataBaseEventLogWriter;\n\tfriend class EventLogDb;\n\npublic:\n\n\tEventLog(const sip_t *sip);\n\tvirtual ~EventLog();\n\tvoid setCompleted();\n\tvoid setStatusCode(int sip_status, const char *reason);\n\tbool isCompleted() const {\n\t\treturn mCompleted;\n\t}\n\nprotected:\n\n\tsu_home_t mHome;\n\tsip_from_t *mFrom;\n\tsip_to_t *mTo;\n\tsip_user_agent_t *mUA;\n\ttime_t mDate;\n\tint mStatusCode;\n\tstd::string mReason;\n\tbool mCompleted;\n\tstd::string mCallId;\n\tclass Init {\n\tpublic:\n\t\tInit();\n\t};\n\tstatic Init evStaticInit;\n};\n\nclass RegistrationLog : public EventLog {\n\tfriend class FilesystemEventLogWriter;\n\tfriend class DataBaseEventLogWriter;\n\tfriend class RegistrationLogDb;\n\npublic:\n\n\t\/\/ Explicit values are necessary for soci. Do not change this.\n\tenum Type {\n\t\tRegister = 0,\n\t\tUnregister = 1,\n\t\tExpired = 2\n\t};\n\n\tRegistrationLog(const sip_t *sip, const sip_contact_t *contacts);\n\nprivate:\n\tType mType;\n\tsip_contact_t *mContacts;\n};\n\nclass CallLog : public EventLog {\n\tfriend class FilesystemEventLogWriter;\n\tfriend class DataBaseEventLogWriter;\n\tfriend class CallLogDb;\n\npublic:\n\tCallLog(const sip_t *sip);\n\tvoid setCancelled();\n\nprivate:\n\tbool mCancelled;\n};\n\nclass MessageLog : public EventLog {\n\tfriend class FilesystemEventLogWriter;\n\tfriend class DataBaseEventLogWriter;\n\tfriend class MessageLogDb;\n\npublic:\n\n\t\/\/ Explicit values is necessary for soci. Do not change this.\n\tenum ReportType {\n\t\tReceivedFromUser = 0,\n\t\tDeliveredToUser = 1\n\t};\n\n\tMessageLog(const sip_t *sip, ReportType report);\n\tvoid setDestination(const url_t *dest);\n\nprivate:\n\n\tReportType mReportType;\n\turl_t *mUri; \/\/ destination uri of message\n};\n\nclass AuthLog: public EventLog {\n\tfriend class FilesystemEventLogWriter;\n\tfriend class DataBaseEventLogWriter;\n\tfriend class AuthLogDb;\n\npublic:\n\n\tAuthLog(const sip_t *sip, bool userExists);\n\nprivate:\n\n\tvoid setOrigin(const sip_via_t *via);\n\n\turl_t *mOrigin;\n\tstd::string mMethod;\n\tbool mUserExists;\n};\n\nclass CallQualityStatisticsLog: public EventLog {\n\tfriend class FilesystemEventLogWriter;\n\tfriend class DataBaseEventLogWriter;\n\tfriend class CallQualityStatisticsLogDb;\n\npublic:\n\n\tCallQualityStatisticsLog(const sip_t *sip);\n\nprivate:\n\n\t\/\/ Note on `soci`: The `char *` support is dead since 2008...\n\t\/\/ See: https:\/\/github.com\/SOCI\/soci\/commit\/25c704ac4cb7bb0135dabc2421a1281fb868a511\n\t\/\/ It's necessary to create a hard copy with a `string`.\n\tstd::string mReport;\n};\n\nclass EventLogWriter {\npublic:\n\n\tvirtual void write(const std::shared_ptr &evlog) = 0;\n\tvirtual ~EventLogWriter();\n};\n\nclass FilesystemEventLogWriter: public EventLogWriter {\npublic:\n\n\tFilesystemEventLogWriter(const std::string &rootpath);\n\tvirtual void write(const std::shared_ptr &evlog);\n\tbool isReady() const;\n\nprivate:\n\n\tint openPath(const url_t *uri, const char *kind, time_t curtime, int errorcode = 0);\n\tvoid writeRegistrationLog(const std::shared_ptr &evlog);\n\tvoid writeCallLog(const std::shared_ptr &clog);\n\tvoid writeCallQualityStatisticsLog(const std::shared_ptr &mlog);\n\tvoid writeMessageLog(const std::shared_ptr &mlog);\n\tvoid writeAuthLog(const std::shared_ptr &alog);\n\tvoid writeErrorLog(const std::shared_ptr &log, const char *kind, const std::string &logstr);\n\tstd::string mRootPath;\n\tbool mIsReady;\n};\n\n#if ENABLE_SOCI\n\n#ifdef __GNUG__\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wdeprecated-declarations\"\n#endif\n#include \n#ifdef __GNUG__\n#pragma GCC diagnostic pop\n#endif\n\n#include \"utils\/threadpool.hh\"\n\nclass DataBaseEventLogWriter: public EventLogWriter {\npublic:\n\n\tenum Backend {\n\t\tMysql = 0,\n\t\tSqlite3 = 1,\n\t\tPostgresql = 2\n\t};\n\n\tDataBaseEventLogWriter(\n\t\tconst std::string &backendString, const std::string &connectionString,\n\t\tint maxQueueSize, int nbThreadsMax\n\t);\n\t~DataBaseEventLogWriter();\n\n\tvirtual void write(const std::shared_ptr &evlog);\n\tbool isReady() const;\n\nprivate:\n\n\tvoid initTables(Backend backend);\n\n\tstatic void writeEventLog(const std::shared_ptr &evlog, int typeId, soci::session &sql);\n\n\tvoid writeRegistrationLog(const std::shared_ptr &evlog);\n\tvoid writeCallLog(const std::shared_ptr &evlog);\n\tvoid writeMessageLog(const std::shared_ptr &evlog);\n\tvoid writeAuthLog(const std::shared_ptr &evlog);\n\tvoid writeCallQualityStatisticsLog(const std::shared_ptr &evlog);\n\n\tvoid writeEventFromQueue();\n\n\tbool mIsReady;\n\tstd::mutex mMutex;\n\tstd::queue> mListLogs;\n\n\tsoci::connection_pool *mConnectionPool;\n\tThreadPool *mThreadPool;\n\n\tsize_t mMaxQueueSize;\n\n\tstd::string mInsertReq[5];\n};\n\n#endif\n\n#endif\n<|endoftext|>"} {"text":"\/**\n@file\tStreaming.cpp\n@brief\tSoapy SDR + IConnection streaming interfaces.\n@author Lime Microsystems (www.limemicro.com)\n*\/\n\n#include \"SoapyLMS7.h\"\n#include \n#include \n#include \n#include \"ErrorReporting.h\"\n\nusing namespace lime;\n\n\/*******************************************************************\n * Stream data structure\n ******************************************************************\/\nstruct IConnectionStream\n{\n std::vector streamID;\n int direction;\n};\n\n\/*******************************************************************\n * Stream information\n ******************************************************************\/\nstd::vector SoapyLMS7::getStreamFormats(const int direction, const size_t channel) const\n{\n std::vector formats;\n formats.push_back(SOAPY_SDR_CF32);\n formats.push_back(SOAPY_SDR_CS12);\n formats.push_back(SOAPY_SDR_CS16);\n return formats;\n}\n\nstd::string SoapyLMS7::getNativeStreamFormat(const int direction, const size_t channel, double &fullScale) const\n{\n fullScale = 2048;\n return SOAPY_SDR_CS16;\n}\n\nSoapySDR::ArgInfoList SoapyLMS7::getStreamArgsInfo(const int direction, const size_t channel) const\n{\n SoapySDR::ArgInfoList argInfos;\n\n \/\/buffer length\n {\n SoapySDR::ArgInfo info;\n info.key = \"bufferLength\";\n info.name = \"Buffer Length\";\n info.description = \"The buffer transfer size over the link.\";\n info.units = \"samples\";\n info.type = SoapySDR::ArgInfo::INT;\n argInfos.push_back(info);\n }\n\n \/\/link format\n {\n SoapySDR::ArgInfo info;\n info.key = \"linkFormat\";\n info.name = \"Link Format\";\n info.description = \"The format of the samples over the link.\";\n info.type = SoapySDR::ArgInfo::STRING;\n info.options.push_back(SOAPY_SDR_CS16);\n info.options.push_back(SOAPY_SDR_CS12);\n info.optionNames.push_back(\"Complex int16\");\n info.optionNames.push_back(\"Complex int12\");\n argInfos.push_back(info);\n }\n\n return argInfos;\n}\n\n\/*******************************************************************\n * Stream config\n ******************************************************************\/\nSoapySDR::Stream *SoapyLMS7::setupStream(\n const int direction,\n const std::string &format,\n const std::vector &channels,\n const SoapySDR::Kwargs &args)\n{\n std::unique_lock lock(_accessMutex);\n\n \/\/store result into opaque stream object\n auto stream = new IConnectionStream;\n stream->direction = direction;\n\n StreamConfig config;\n config.isTx = (direction == SOAPY_SDR_TX);\n\n \/\/default to channel 0, if none were specified\n const std::vector &channelIDs = channels.empty() ? std::vector{0} : channels;\n\n for(size_t i=0; iSetupStream(streamID, config);\n if (status != 0)\n throw std::runtime_error(\"SoapyLMS7::setupStream() failed: \" + std::string(GetLastErrorMessage()));\n stream->streamID.push_back(streamID);\n }\n return (SoapySDR::Stream *)stream;\n}\n\nvoid SoapyLMS7::closeStream(SoapySDR::Stream *stream)\n{\n std::unique_lock lock(_accessMutex);\n auto icstream = (IConnectionStream *)stream;\n auto streamID = icstream->streamID;\n\n for(auto i : streamID)\n _conn->CloseStream(i);\n}\n\nsize_t SoapyLMS7::getStreamMTU(SoapySDR::Stream *stream) const\n{\n auto icstream = (IConnectionStream *)stream;\n auto streamID = icstream->streamID;\n for(auto i : streamID)\n {\n return _conn->GetStreamSize(i);\n }\n return 0;\n}\n\nint SoapyLMS7::activateStream(\n SoapySDR::Stream *stream,\n const int flags,\n const long long timeNs,\n const size_t numElems)\n{\n auto icstream = (IConnectionStream *)stream;\n auto streamID = icstream->streamID;\n\n if (_conn->GetHardwareTimestampRate() == 0.0)\n throw std::runtime_error(\"SoapyLMS7::activateStream() - the sample rate has not been configured!\");\n\n StreamMetadata metadata;\n metadata.timestamp = SoapySDR::timeNsToTicks(timeNs, _conn->GetHardwareTimestampRate());\n metadata.hasTimestamp = (flags & SOAPY_SDR_HAS_TIME) != 0;\n metadata.endOfBurst = (flags & SOAPY_SDR_END_BURST) != 0;\n for(auto i : streamID)\n {\n int status = _conn->ControlStream(i, true);\n if(status != 0)\n return SOAPY_SDR_STREAM_ERROR;\n }\n return 0;\n}\n\nint SoapyLMS7::deactivateStream(\n SoapySDR::Stream *stream,\n const int flags,\n const long long timeNs)\n{\n auto icstream = (IConnectionStream *)stream;\n auto streamID = icstream->streamID;\n\n StreamMetadata metadata;\n metadata.timestamp = SoapySDR::timeNsToTicks(timeNs, _conn->GetHardwareTimestampRate());\n metadata.hasTimestamp = (flags & SOAPY_SDR_HAS_TIME) != 0;\n metadata.endOfBurst = (flags & SOAPY_SDR_END_BURST) != 0;\n for(auto i : streamID)\n {\n int status = _conn->ControlStream(i, false);\n if(status != 0)\n return SOAPY_SDR_STREAM_ERROR;\n }\n return 0;\n}\n\n\/*******************************************************************\n * Stream API\n ******************************************************************\/\nint SoapyLMS7::readStream(\n SoapySDR::Stream *stream,\n void * const *buffs,\n const size_t numElems,\n int &flags,\n long long &timeNs,\n const long timeoutUs)\n{\n auto icstream = (IConnectionStream *)stream;\n auto streamID = icstream->streamID;\n\n StreamMetadata metadata;\n int status = 0;\n int bufIndex = 0;\n for(auto i : streamID)\n {\n status = _conn->ReadStream(i, buffs[bufIndex++], numElems, timeoutUs\/1000, metadata);\n if(status == 0) return SOAPY_SDR_TIMEOUT;\n if(status < 0) return SOAPY_SDR_STREAM_ERROR;\n }\n \/\/output metadata\n flags = 0;\n if (metadata.endOfBurst) flags |= SOAPY_SDR_END_BURST;\n if (metadata.hasTimestamp) flags |= SOAPY_SDR_HAS_TIME;\n timeNs = SoapySDR::ticksToTimeNs(metadata.timestamp, _conn->GetHardwareTimestampRate());\n \/\/return num read or error code\n return (status >= 0) ? status : SOAPY_SDR_STREAM_ERROR;\n}\n\nint SoapyLMS7::writeStream(\n SoapySDR::Stream *stream,\n const void * const *buffs,\n const size_t numElems,\n int &flags,\n const long long timeNs,\n const long timeoutUs)\n{\n auto icstream = (IConnectionStream *)stream;\n auto streamID = icstream->streamID;\n\n \/\/input metadata\n StreamMetadata metadata;\n metadata.timestamp = SoapySDR::timeNsToTicks(timeNs, _conn->GetHardwareTimestampRate());\n metadata.hasTimestamp = (flags & SOAPY_SDR_HAS_TIME) != 0;\n metadata.endOfBurst = (flags & SOAPY_SDR_END_BURST) != 0;\n\n int ret = 0;\n int bufIndex = 0;\n for(auto i : streamID)\n {\n ret = _conn->WriteStream(i, buffs[bufIndex++], numElems, timeoutUs\/1000, metadata);\n if(ret == 0) return SOAPY_SDR_TIMEOUT;\n if(ret < 0) return SOAPY_SDR_STREAM_ERROR;\n }\n\n \/\/return num written or error code\n return (ret > 0)? ret : SOAPY_SDR_STREAM_ERROR;\n}\n\nint SoapyLMS7::readStreamStatus(\n SoapySDR::Stream *stream,\n size_t &chanMask,\n int &flags,\n long long &timeNs,\n const long timeoutUs)\n{\n auto icstream = (IConnectionStream *)stream;\n auto streamID = icstream->streamID;\n\n StreamMetadata metadata;\n for(auto i : streamID)\n {\n int ret = _conn->ReadStreamStatus(i, timeoutUs\/1000, metadata);\n if (ret != 0)\n return SOAPY_SDR_TIMEOUT;\n }\n\n \/\/output metadata\n flags = 0;\n if (metadata.endOfBurst) flags |= SOAPY_SDR_END_BURST;\n if (metadata.hasTimestamp) flags |= SOAPY_SDR_HAS_TIME;\n timeNs = SoapySDR::ticksToTimeNs(metadata.timestamp, _conn->GetHardwareTimestampRate());\n\n if (metadata.lateTimestamp) return SOAPY_SDR_TIME_ERROR;\n if (metadata.packetDropped) return SOAPY_SDR_OVERFLOW;\n return 0;\n}\nreadStreamStatus - handle not implemented case\/**\n@file\tStreaming.cpp\n@brief\tSoapy SDR + IConnection streaming interfaces.\n@author Lime Microsystems (www.limemicro.com)\n*\/\n\n#include \"SoapyLMS7.h\"\n#include \n#include \n#include \n#include \"ErrorReporting.h\"\n\nusing namespace lime;\n\n\/*******************************************************************\n * Stream data structure\n ******************************************************************\/\nstruct IConnectionStream\n{\n std::vector streamID;\n int direction;\n};\n\n\/*******************************************************************\n * Stream information\n ******************************************************************\/\nstd::vector SoapyLMS7::getStreamFormats(const int direction, const size_t channel) const\n{\n std::vector formats;\n formats.push_back(SOAPY_SDR_CF32);\n formats.push_back(SOAPY_SDR_CS12);\n formats.push_back(SOAPY_SDR_CS16);\n return formats;\n}\n\nstd::string SoapyLMS7::getNativeStreamFormat(const int direction, const size_t channel, double &fullScale) const\n{\n fullScale = 2048;\n return SOAPY_SDR_CS16;\n}\n\nSoapySDR::ArgInfoList SoapyLMS7::getStreamArgsInfo(const int direction, const size_t channel) const\n{\n SoapySDR::ArgInfoList argInfos;\n\n \/\/buffer length\n {\n SoapySDR::ArgInfo info;\n info.key = \"bufferLength\";\n info.name = \"Buffer Length\";\n info.description = \"The buffer transfer size over the link.\";\n info.units = \"samples\";\n info.type = SoapySDR::ArgInfo::INT;\n argInfos.push_back(info);\n }\n\n \/\/link format\n {\n SoapySDR::ArgInfo info;\n info.key = \"linkFormat\";\n info.name = \"Link Format\";\n info.description = \"The format of the samples over the link.\";\n info.type = SoapySDR::ArgInfo::STRING;\n info.options.push_back(SOAPY_SDR_CS16);\n info.options.push_back(SOAPY_SDR_CS12);\n info.optionNames.push_back(\"Complex int16\");\n info.optionNames.push_back(\"Complex int12\");\n argInfos.push_back(info);\n }\n\n return argInfos;\n}\n\n\/*******************************************************************\n * Stream config\n ******************************************************************\/\nSoapySDR::Stream *SoapyLMS7::setupStream(\n const int direction,\n const std::string &format,\n const std::vector &channels,\n const SoapySDR::Kwargs &args)\n{\n std::unique_lock lock(_accessMutex);\n\n \/\/store result into opaque stream object\n auto stream = new IConnectionStream;\n stream->direction = direction;\n\n StreamConfig config;\n config.isTx = (direction == SOAPY_SDR_TX);\n\n \/\/default to channel 0, if none were specified\n const std::vector &channelIDs = channels.empty() ? std::vector{0} : channels;\n\n for(size_t i=0; iSetupStream(streamID, config);\n if (status != 0)\n throw std::runtime_error(\"SoapyLMS7::setupStream() failed: \" + std::string(GetLastErrorMessage()));\n stream->streamID.push_back(streamID);\n }\n return (SoapySDR::Stream *)stream;\n}\n\nvoid SoapyLMS7::closeStream(SoapySDR::Stream *stream)\n{\n std::unique_lock lock(_accessMutex);\n auto icstream = (IConnectionStream *)stream;\n auto streamID = icstream->streamID;\n\n for(auto i : streamID)\n _conn->CloseStream(i);\n}\n\nsize_t SoapyLMS7::getStreamMTU(SoapySDR::Stream *stream) const\n{\n auto icstream = (IConnectionStream *)stream;\n auto streamID = icstream->streamID;\n for(auto i : streamID)\n {\n return _conn->GetStreamSize(i);\n }\n return 0;\n}\n\nint SoapyLMS7::activateStream(\n SoapySDR::Stream *stream,\n const int flags,\n const long long timeNs,\n const size_t numElems)\n{\n auto icstream = (IConnectionStream *)stream;\n auto streamID = icstream->streamID;\n\n if (_conn->GetHardwareTimestampRate() == 0.0)\n throw std::runtime_error(\"SoapyLMS7::activateStream() - the sample rate has not been configured!\");\n\n StreamMetadata metadata;\n metadata.timestamp = SoapySDR::timeNsToTicks(timeNs, _conn->GetHardwareTimestampRate());\n metadata.hasTimestamp = (flags & SOAPY_SDR_HAS_TIME) != 0;\n metadata.endOfBurst = (flags & SOAPY_SDR_END_BURST) != 0;\n for(auto i : streamID)\n {\n int status = _conn->ControlStream(i, true);\n if(status != 0)\n return SOAPY_SDR_STREAM_ERROR;\n }\n return 0;\n}\n\nint SoapyLMS7::deactivateStream(\n SoapySDR::Stream *stream,\n const int flags,\n const long long timeNs)\n{\n auto icstream = (IConnectionStream *)stream;\n auto streamID = icstream->streamID;\n\n StreamMetadata metadata;\n metadata.timestamp = SoapySDR::timeNsToTicks(timeNs, _conn->GetHardwareTimestampRate());\n metadata.hasTimestamp = (flags & SOAPY_SDR_HAS_TIME) != 0;\n metadata.endOfBurst = (flags & SOAPY_SDR_END_BURST) != 0;\n for(auto i : streamID)\n {\n int status = _conn->ControlStream(i, false);\n if(status != 0)\n return SOAPY_SDR_STREAM_ERROR;\n }\n return 0;\n}\n\n\/*******************************************************************\n * Stream API\n ******************************************************************\/\nint SoapyLMS7::readStream(\n SoapySDR::Stream *stream,\n void * const *buffs,\n const size_t numElems,\n int &flags,\n long long &timeNs,\n const long timeoutUs)\n{\n auto icstream = (IConnectionStream *)stream;\n auto streamID = icstream->streamID;\n\n StreamMetadata metadata;\n int status = 0;\n int bufIndex = 0;\n for(auto i : streamID)\n {\n status = _conn->ReadStream(i, buffs[bufIndex++], numElems, timeoutUs\/1000, metadata);\n if(status == 0) return SOAPY_SDR_TIMEOUT;\n if(status < 0) return SOAPY_SDR_STREAM_ERROR;\n }\n \/\/output metadata\n flags = 0;\n if (metadata.endOfBurst) flags |= SOAPY_SDR_END_BURST;\n if (metadata.hasTimestamp) flags |= SOAPY_SDR_HAS_TIME;\n timeNs = SoapySDR::ticksToTimeNs(metadata.timestamp, _conn->GetHardwareTimestampRate());\n \/\/return num read or error code\n return (status >= 0) ? status : SOAPY_SDR_STREAM_ERROR;\n}\n\nint SoapyLMS7::writeStream(\n SoapySDR::Stream *stream,\n const void * const *buffs,\n const size_t numElems,\n int &flags,\n const long long timeNs,\n const long timeoutUs)\n{\n auto icstream = (IConnectionStream *)stream;\n auto streamID = icstream->streamID;\n\n \/\/input metadata\n StreamMetadata metadata;\n metadata.timestamp = SoapySDR::timeNsToTicks(timeNs, _conn->GetHardwareTimestampRate());\n metadata.hasTimestamp = (flags & SOAPY_SDR_HAS_TIME) != 0;\n metadata.endOfBurst = (flags & SOAPY_SDR_END_BURST) != 0;\n\n int ret = 0;\n int bufIndex = 0;\n for(auto i : streamID)\n {\n ret = _conn->WriteStream(i, buffs[bufIndex++], numElems, timeoutUs\/1000, metadata);\n if(ret == 0) return SOAPY_SDR_TIMEOUT;\n if(ret < 0) return SOAPY_SDR_STREAM_ERROR;\n }\n\n \/\/return num written or error code\n return (ret > 0)? ret : SOAPY_SDR_STREAM_ERROR;\n}\n\nint SoapyLMS7::readStreamStatus(\n SoapySDR::Stream *stream,\n size_t &chanMask,\n int &flags,\n long long &timeNs,\n const long timeoutUs)\n{\n auto icstream = (IConnectionStream *)stream;\n auto streamID = icstream->streamID;\n\n StreamMetadata metadata;\n for(auto i : streamID)\n {\n int ret = _conn->ReadStreamStatus(i, timeoutUs\/1000, metadata);\n if (ret != 0)\n {\n \/\/handle the default not implemented case and return not supported\n if (GetLastError() == EPERM) return SOAPY_SDR_NOT_SUPPORTED;\n return SOAPY_SDR_TIMEOUT;\n }\n }\n\n \/\/output metadata\n flags = 0;\n if (metadata.endOfBurst) flags |= SOAPY_SDR_END_BURST;\n if (metadata.hasTimestamp) flags |= SOAPY_SDR_HAS_TIME;\n timeNs = SoapySDR::ticksToTimeNs(metadata.timestamp, _conn->GetHardwareTimestampRate());\n\n if (metadata.lateTimestamp) return SOAPY_SDR_TIME_ERROR;\n if (metadata.packetDropped) return SOAPY_SDR_OVERFLOW;\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ CassandraScene.cpp\n\/\/ show\n\/\/\n\/\/ Created by Chris Mullany on 05\/09\/2015.\n\/\/\n\/\/\n\n#include \"CassandraScene.h\"\nusing namespace ofxCv;\nusing namespace cv;\n\n#define DIR_CASSANDRA \"recordings\/cassandra\/\"\n#define DIR_MAIN \"recordings\/main\/\"\n\n#define CASSANDRA_DURATION 120 \/\/ Cassandra recording lasts for 2 minutes\n#define MAIN_DURATION 300 \/\/ main recording lasts for 5 minutes\n\n\nCassandraScene::CassandraScene() {\n name = \"Cassandra\";\n}\n\nvoid CassandraScene::setup() {\n \/\/ subscenes\n subsceneStart = 77;\n subsceneEnd = 82;\n timer.setup(\"fonts\/Arial Black.ttf\", 140);\n timer.colour.set(255);\n SceneBase::setup();\n}\n\nvoid CassandraScene::update() {\n if (isWindow()) {\n if (mode == RECORD_CASSANDRA) {\n auto image = vision->ipcamCassandra.grabber->getFrame();\n if (image->isAllocated() && image->height > 1) {\n stringstream stream;\n stream << DIR_CASSANDRA << setw(10) << setfill('0') << cassandraFileCount << \".jpg\";\n string filename = stream.str();\n image->saveImage(filename, OF_IMAGE_QUALITY_HIGH);\n \/\/fileCount++;\n cassandraFileCount++;\n }\n }\n else if (mode == RECORD_MAIN) {\n auto image = vision->ipcam.grabber->getFrame();\n if (image->isAllocated() && image->height > 1) {\n stringstream stream;\n stream << DIR_MAIN << setw(10) << setfill('0') << mainFileCount << \".jpg\";\n string filename = stream.str();\n image->saveImage(filename, OF_IMAGE_QUALITY_HIGH);\n \/\/filecount++;\n mainFileCount++;\n }\n }\n timer.update();\n }\n SceneBase::update();\n}\n\nvoid CassandraScene::draw() {\n if (isWindow()) {\n vision->isEnabled = true;\n if (mode == PLAYBACK) {\n playbackTime += ofGetLastFrameTime();\n \n \/\/ draw the image sequences next to each other\n \/\/ if only main is drawing, set the scale to fill the screen\n ofTexture& main = sequenceMain.getTextureForTime(playbackTime);\n float scale = ofGetWidth() \/ main.getWidth();\n float x = 0;\n float y = (ofGetHeight()\/2) - (main.getHeight()*scale*0.5);\n \/\/ draw cassandra if it's still playing\n if (playbackTime < timerCassandra) {\n ofTexture& cassandra = sequenceCassandra.getTextureForTime(playbackTime);\n scale = (ofGetWidth()\/2) \/ cassandra.getWidth();\n x = cassandra.getWidth()*scale;\n y = (ofGetHeight()\/2) - (main.getHeight()*scale*0.5);\n cassandra.draw(0, y, cassandra.getWidth()*scale, cassandra.getHeight()*scale);\n }\n main.draw(x, y, main.getWidth()*scale, main.getHeight()*scale);\n \n if (sequenceMain.getCurrentFrame() >= sequenceMain.getTotalFrames() - 1 || (playbackTime > timerMain && sequenceMain.getCurrentFrame() < 20)) {\n \/\/ sequence is over\n mode == IDLE;\n }\n \n }\n \n if (subsceneI == 80) {\n windowTimer += ofGetLastFrameTime();\n int secondsLeft = timerMain - windowTimer;\n if (secondsLeft > 0) {\n int mins = floor(secondsLeft \/ 60);\n string secs = ofToString( (secondsLeft % 60) );\n if (secs.length() == 1) secs = \"0\" + secs;\n timer.messageString = ofToString(mins) + \":\" + secs;\n timer.maxWidth = ofGetWidth() * 0.9;\n int stringH = timer.getHeight();\n timer.draw(ofGetWidth()\/2, ofGetHeight()*.45 - stringH\/2);\n }\n }\n \n if (isDebugMode) {\n if (mode == RECORD_CASSANDRA) {\n auto image = vision->ipcamCassandra.grabber->getFrame();\n image->draw(0, 0);\n ofSetColor(200,0,0);\n ofCircle(ofGetWidth()\/2, ofGetHeight()\/2, 20);\n ofSetColor(255);\n }\n else if (mode == RECORD_MAIN) {\n vision->ipcam.grabber->getFrame()->draw(0, 0);\n ofSetColor(200,0,0);\n ofCircle(ofGetWidth()\/2, ofGetHeight()\/2, 20);\n ofSetColor(255);\n }\n else if (mode == PLAYBACK) {\n ofDrawBitmapStringHighlight(\"playback time: \" + ofToString(playbackTime), 10, ofGetHeight()\/2);\n ofDrawBitmapStringHighlight(\"cassandra: \" + ofToString(sequenceCassandra.getCurrentFrame()) + \"\/\" + ofToString(sequenceCassandra.getTotalFrames()), 10, ofGetHeight()\/2 + 20);\n ofDrawBitmapStringHighlight(\"main: \" + ofToString(sequenceMain.getCurrentFrame()) + \"\/\" + ofToString(sequenceMain.getTotalFrames()), 10, ofGetHeight()\/2 + 40);\n }\n }\n }\n SceneBase::draw();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ public\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid CassandraScene::play(int i){\n switch (i) {\n case 77:\n \/\/ title, timed\n if (isSlave()) {\n led->show(\"5. SOMEONE\");\n }\n if (isMaster()) {\n countdown->start(timerIntro.get());\n osc->sendSoundCue(soundCueIntro);\n }\n if (isWindow()) setMode(IDLE);\n break;\n \n case 78:\n \/\/ audience name, manual cue\n if (isSlave()) {\n led->show(audience.get());\n }\n if (isMaster()) {\n osc->sendLightingCue(lxCueIntro);\n osc->sendSoundCue(soundCueName);\n }\n if (isWindow()) setMode(IDLE);\n break;\n \n case 79:\n \/\/ welcome, all windows record cassandra room, timed\n if (isSlave()) {\n led->hide();\n led->show(\"5. \" + ofToUpper(audience.get()) + \" KNOWS\");\n \/\/led->playQueue();\n }\n if (isWindow()) {\n timer.hide();\n setMode(RECORD_CASSANDRA);\n }\n if (isMaster()) {\n countdown->start(timerCassandra.get());\n osc->sendSoundCue(75);\n }\n break;\n \n case 80:\n \/\/ welcome, all windows stop recording cassandra, start recording main room, timed\n if (isSlave()) {\n led->hide();\n \/\/led->queue(LedDisplay::Params(welcome.get(), 1, 5, 1, true)); old replaced with line below\n \/\/led->playQueue();\n \/\/led->show(\"5. SOMEONE KNOWS\");\n led->hide();\n \n }\n if (isWindow()) {\n windowTimer = 0;\n timer.show(\"\", 1, -1, 1);\n setMode(RECORD_MAIN);\n }\n if (isMaster()) {\n countdown->start(timerMain.get());\n osc->sendSoundCue(soundCueTimePassing);\n }\n break;\n \n case 81:\n \/\/ all windows stop recording main room, playback both videos split screen, timed\n if (isWindow()) {\n timer.hide();\n setMode(PLAYBACK);\n }\n if (isSlave()) {\n led->hide();\n led->queue(LedDisplay::Params(\"5. SOMEONE KNOWS NOTHING\", 0, 1, 5, false, 0));\n led->playQueue();\n \/\/led->show(\"5. SOMEONE KNOWS NOTHING\");\n }\n if (isMaster()) {\n countdown->start(timerMain.get());\n osc->sendSoundCue(soundCuePlayback);\n osc->sendLightingCue(lxCuePlayback);\n }\n break;\n case 82:\n \/\/ rabbit angry, etc, timed\n if (isSlave()) {\n led->hide();\n led->queue(LedDisplay::Params(rabbitDisappointed.get(), 0, 2, 0, false));\n led->queue(LedDisplay::Params(rabbitBoss.get(), 0, 1, 0, false, timerOutro.get()));\n led->queue(LedDisplay::Params(boss.get(), 0, 1, 0));\n led->queue(LedDisplay::Params(boss.get(), 0, 1, 0));\n led->queue(LedDisplay::Params(boss.get(), 0, 1, 0));\n led->queue(LedDisplay::Params(boss.get(), 0, 1, 0));\n led->playQueue();\n }\n if (isMaster()) {\n countdown->start(7);\n osc->sendSoundCue(80);\n osc->sendLightingCue(lxCueOutro);\n }\n if (isWindow()) setMode(IDLE);\n break;\n default:\n break;\n }\n SceneBase::play(i);\n}\n\nvoid CassandraScene::stop(){\n \/\/ stop\/unload\/clear things\n SceneBase::stop();\n}\n\nvoid CassandraScene::setupGui() {\n guiName = \"Cassandra\";\n panel.setup(guiName, \"settings\/cassandra.xml\");\n \n titleGroup.setName(\"Titles\");\n titleGroup.add(title.set(\"title1\", \"5. ALL THINK FIB LENS\"));\n titleGroup.add(audience.set(\"title2\", \"Clare\"));\n titleGroup.add(welcome.set(\"title3\", \"Welcome\"));\n titleGroup.add(rabbitDisappointed.set(\"title4\", \"He is disappointed\"));\n titleGroup.add(rabbitBoss.set(\"title5\", \"He is pleased\"));\n titleGroup.add(boss.set(\"title6\", \"He is boss\"));\n \n timerGroup.setName(\"Timers\");\n timerGroup.add(timerIntro.set(\"intro\", 5, 1, 10));\n timerGroup.add(timerCassandra.set(\"cassandra\", 2*60, 1, 10*60));\n timerGroup.add(timerMain.set(\"main\", 5*60, 1, 10*60));\n timerGroup.add(timerOutro.set(\"outro\", 5, 1, 10));\n panel.add(titleGroup);\n panel.add(timerGroup);\n \n \/\/ LX cues\n lxCueGroup.setName(\"LX Cues\");\n lxCueGroup.add(lxCueIntro.set(\"intro\", 34, 0, 100));\n lxCueGroup.add(lxCuePlayback.set(\"playback\", 35, 0, 100));\n lxCueGroup.add(lxCueOutro.set(\"outro\", 0, 0, 100));\n panel.add(lxCueGroup);\n \n \/\/ Sound cues\n soundCueGroup.setName(\"Sound Cues\");\n soundCueGroup.add(soundCueIntro.set(\"intro\", 0, 0, 100));\n soundCueGroup.add(soundCueName.set(\"name\", 0, 0, 100));\n soundCueGroup.add(soundCueCassandra.set(\"cassandra\", 0, 0, 100));\n soundCueGroup.add(soundCueTimePassing.set(\"time passing\", 0, 0, 100));\n soundCueGroup.add(soundCuePlayback.set(\"playback\", 0, 0, 100));\n soundCueGroup.add(soundCueOutro.set(\"outro\", 0, 0, 100));\n panel.add(soundCueGroup);\n \n panel.loadFromFile(\"settings\/cassandra.xml\");\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ protected\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ private\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid CassandraScene::setMode(Mode mode) {\n this->mode = mode;\n if (mode == PLAYBACK) {\n indexCassandra = 0;\n indexMain = 0;\n playbackTime = 0;\n sequenceCassandra.setExtension(\"jpg\");\n sequenceCassandra.loadSequence(DIR_CASSANDRA);\n sequenceCassandra.setFrameRate(cassandraFileCount\/CASSANDRA_DURATION);\n sequenceMain.setExtension(\"jpg\");\n sequenceMain.loadSequence(DIR_MAIN);\n sequenceMain.setFrameRate(mainFileCount\/MAIN_DURATION);\n }\n else {\n sequenceCassandra.unloadSequence();\n sequenceMain.unloadSequence();\n }\n if (mode == RECORD_CASSANDRA) {\n prepareRecordingDir(DIR_CASSANDRA);\n vision->setToIPCamCassandra();\n }\n else if (mode == RECORD_MAIN) {\n prepareRecordingDir(DIR_MAIN);\n vision->setToIPCamMain();\n }\n}\n\nvoid CassandraScene::prepareRecordingDir(string path) {\n \/\/ remove existing recordings\n if (ofDirectory::doesDirectoryExist(path)) {\n ofDirectory::removeDirectory(path, true);\n }\n ofDirectory::createDirectory(path);\n if(path == DIR_CASSANDRA) cassandraFileCount = 0;\n else mainFileCount = 0;\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ custom event handlers\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ oF event handlers\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nChanged cassandra display issue\/\/\n\/\/ CassandraScene.cpp\n\/\/ show\n\/\/\n\/\/ Created by Chris Mullany on 05\/09\/2015.\n\/\/\n\/\/\n\n#include \"CassandraScene.h\"\nusing namespace ofxCv;\nusing namespace cv;\n\n#define DIR_CASSANDRA \"recordings\/cassandra\/\"\n#define DIR_MAIN \"recordings\/main\/\"\n\n#define CASSANDRA_DURATION 120 \/\/ Cassandra recording lasts for 2 minutes\n#define MAIN_DURATION 300 \/\/ main recording lasts for 5 minutes\n\n\nCassandraScene::CassandraScene() {\n name = \"Cassandra\";\n}\n\nvoid CassandraScene::setup() {\n \/\/ subscenes\n subsceneStart = 77;\n subsceneEnd = 82;\n timer.setup(\"fonts\/Arial Black.ttf\", 140);\n timer.colour.set(255);\n SceneBase::setup();\n}\n\nvoid CassandraScene::update() {\n if (isWindow()) {\n if (mode == RECORD_CASSANDRA) {\n auto image = vision->ipcamCassandra.grabber->getFrame();\n if (image->isAllocated() && image->height > 1) {\n stringstream stream;\n stream << DIR_CASSANDRA << setw(10) << setfill('0') << cassandraFileCount << \".jpg\";\n string filename = stream.str();\n image->saveImage(filename, OF_IMAGE_QUALITY_HIGH);\n \/\/fileCount++;\n cassandraFileCount++;\n }\n }\n else if (mode == RECORD_MAIN) {\n auto image = vision->ipcam.grabber->getFrame();\n if (image->isAllocated() && image->height > 1) {\n stringstream stream;\n stream << DIR_MAIN << setw(10) << setfill('0') << mainFileCount << \".jpg\";\n string filename = stream.str();\n image->saveImage(filename, OF_IMAGE_QUALITY_HIGH);\n \/\/filecount++;\n mainFileCount++;\n }\n }\n timer.update();\n }\n SceneBase::update();\n}\n\nvoid CassandraScene::draw() {\n if (isWindow()) {\n vision->isEnabled = true;\n if (mode == PLAYBACK) {\n playbackTime += ofGetLastFrameTime();\n \n \/\/ draw the image sequences next to each other\n \/\/ if only main is drawing, set the scale to fill the screen\n ofTexture& main = sequenceMain.getTextureForTime(playbackTime);\n float scale = ofGetWidth() \/ main.getWidth();\n float x = 0;\n float y = (ofGetHeight()\/2) - (main.getHeight()*scale*0.5);\n \/\/ draw cassandra if it's still playing\n if (playbackTime < timerCassandra) {\n ofTexture& cassandra = sequenceCassandra.getTextureForTime(playbackTime);\n scale = (ofGetWidth()\/2) \/ cassandra.getWidth();\n x = cassandra.getWidth()*scale;\n y = (ofGetHeight()\/2) - (main.getHeight()*scale*0.5);\n cassandra.draw(0, y, cassandra.getWidth()*scale, cassandra.getHeight()*scale);\n }\n main.draw(x, y, main.getWidth()*scale, main.getHeight()*scale);\n \n if (sequenceMain.getCurrentFrame() >= sequenceMain.getTotalFrames() - 1 || (playbackTime > timerMain && sequenceMain.getCurrentFrame() < 20)) {\n \/\/ sequence is over\n mode == IDLE;\n }\n \n }\n \n if (subsceneI == 80) {\n windowTimer += ofGetLastFrameTime();\n int secondsLeft = timerMain - windowTimer;\n if (secondsLeft > 0) {\n int mins = floor(secondsLeft \/ 60);\n string secs = ofToString( (secondsLeft % 60) );\n if (secs.length() == 1) secs = \"0\" + secs;\n timer.messageString = ofToString(mins) + \":\" + secs;\n timer.maxWidth = ofGetWidth() * 0.9;\n int stringH = timer.getHeight();\n timer.draw(ofGetWidth()\/2, ofGetHeight()*.45 - stringH\/2);\n }\n }\n \n if (isDebugMode) {\n if (mode == RECORD_CASSANDRA) {\n auto image = vision->ipcamCassandra.grabber->getFrame();\n image->draw(0, 0);\n ofSetColor(200,0,0);\n ofCircle(ofGetWidth()\/2, ofGetHeight()\/2, 20);\n ofSetColor(255);\n }\n else if (mode == RECORD_MAIN) {\n vision->ipcam.grabber->getFrame()->draw(0, 0);\n ofSetColor(200,0,0);\n ofCircle(ofGetWidth()\/2, ofGetHeight()\/2, 20);\n ofSetColor(255);\n }\n else if (mode == PLAYBACK) {\n ofDrawBitmapStringHighlight(\"playback time: \" + ofToString(playbackTime), 10, ofGetHeight()\/2);\n ofDrawBitmapStringHighlight(\"cassandra: \" + ofToString(sequenceCassandra.getCurrentFrame()) + \"\/\" + ofToString(sequenceCassandra.getTotalFrames()), 10, ofGetHeight()\/2 + 20);\n ofDrawBitmapStringHighlight(\"main: \" + ofToString(sequenceMain.getCurrentFrame()) + \"\/\" + ofToString(sequenceMain.getTotalFrames()), 10, ofGetHeight()\/2 + 40);\n }\n }\n }\n SceneBase::draw();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ public\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid CassandraScene::play(int i){\n switch (i) {\n case 77:\n \/\/ title, timed\n if (isSlave()) {\n led->show(\"5. SOMEONE\");\n }\n if (isMaster()) {\n countdown->start(timerIntro.get());\n osc->sendSoundCue(soundCueIntro);\n }\n if (isWindow()) setMode(IDLE);\n break;\n \n case 78:\n \/\/ audience name, manual cue\n if (isSlave()) {\n led->show(audience.get());\n }\n if (isMaster()) {\n osc->sendLightingCue(lxCueIntro);\n osc->sendSoundCue(soundCueName);\n }\n if (isWindow()) setMode(IDLE);\n break;\n \n case 79:\n \/\/ welcome, all windows record cassandra room, timed\n if (isSlave()) {\n led->hide();\n led->show(\"5. \" + ofToUpper(audience.get()) + \" KNOWS\");\n \/\/led->playQueue();\n }\n if (isWindow()) {\n timer.hide();\n setMode(RECORD_CASSANDRA);\n }\n if (isMaster()) {\n countdown->start(timerCassandra.get());\n osc->sendSoundCue(75);\n }\n break;\n \n case 80:\n \/\/ welcome, all windows stop recording cassandra, start recording main room, timed\n if (isSlave()) {\n led->hide();\n \/\/led->queue(LedDisplay::Params(welcome.get(), 1, 5, 1, true)); old replaced with line below\n \/\/led->playQueue();\n \/\/led->show(\"5. SOMEONE KNOWS\");\n }\n if (isWindow()) {\n windowTimer = 0;\n timer.show(\"\", 1, -1, 1);\n setMode(RECORD_MAIN);\n }\n if (isMaster()) {\n countdown->start(timerMain.get());\n osc->sendSoundCue(soundCueTimePassing);\n }\n break;\n \n case 81:\n \/\/ all windows stop recording main room, playback both videos split screen, timed\n if (isWindow()) {\n timer.hide();\n setMode(PLAYBACK);\n }\n if (isSlave()) {\n led->hide();\n led->queue(LedDisplay::Params(\"5. SOMEONE KNOWS NOTHING\", 0, 1, 5, false, 0));\n led->playQueue();\n \/\/led->show(\"5. SOMEONE KNOWS NOTHING\");\n }\n if (isMaster()) {\n countdown->start(timerMain.get());\n osc->sendSoundCue(soundCuePlayback);\n osc->sendLightingCue(lxCuePlayback);\n }\n break;\n case 82:\n \/\/ rabbit angry, etc, timed\n if (isSlave()) {\n led->hide();\n led->queue(LedDisplay::Params(rabbitDisappointed.get(), 0, 2, 0, false));\n led->queue(LedDisplay::Params(rabbitBoss.get(), 0, 1, 0, false, timerOutro.get()));\n led->queue(LedDisplay::Params(boss.get(), 0, 1, 0));\n led->queue(LedDisplay::Params(boss.get(), 0, 1, 0));\n led->queue(LedDisplay::Params(boss.get(), 0, 1, 0));\n led->queue(LedDisplay::Params(boss.get(), 0, 1, 0));\n led->playQueue();\n }\n if (isMaster()) {\n countdown->start(7);\n osc->sendSoundCue(80);\n osc->sendLightingCue(lxCueOutro);\n }\n if (isWindow()) setMode(IDLE);\n break;\n default:\n break;\n }\n SceneBase::play(i);\n}\n\nvoid CassandraScene::stop(){\n \/\/ stop\/unload\/clear things\n SceneBase::stop();\n}\n\nvoid CassandraScene::setupGui() {\n guiName = \"Cassandra\";\n panel.setup(guiName, \"settings\/cassandra.xml\");\n \n titleGroup.setName(\"Titles\");\n titleGroup.add(title.set(\"title1\", \"5. ALL THINK FIB LENS\"));\n titleGroup.add(audience.set(\"title2\", \"Clare\"));\n titleGroup.add(welcome.set(\"title3\", \"Welcome\"));\n titleGroup.add(rabbitDisappointed.set(\"title4\", \"He is disappointed\"));\n titleGroup.add(rabbitBoss.set(\"title5\", \"He is pleased\"));\n titleGroup.add(boss.set(\"title6\", \"He is boss\"));\n \n timerGroup.setName(\"Timers\");\n timerGroup.add(timerIntro.set(\"intro\", 5, 1, 10));\n timerGroup.add(timerCassandra.set(\"cassandra\", 2*60, 1, 10*60));\n timerGroup.add(timerMain.set(\"main\", 5*60, 1, 10*60));\n timerGroup.add(timerOutro.set(\"outro\", 5, 1, 10));\n panel.add(titleGroup);\n panel.add(timerGroup);\n \n \/\/ LX cues\n lxCueGroup.setName(\"LX Cues\");\n lxCueGroup.add(lxCueIntro.set(\"intro\", 34, 0, 100));\n lxCueGroup.add(lxCuePlayback.set(\"playback\", 35, 0, 100));\n lxCueGroup.add(lxCueOutro.set(\"outro\", 0, 0, 100));\n panel.add(lxCueGroup);\n \n \/\/ Sound cues\n soundCueGroup.setName(\"Sound Cues\");\n soundCueGroup.add(soundCueIntro.set(\"intro\", 0, 0, 100));\n soundCueGroup.add(soundCueName.set(\"name\", 0, 0, 100));\n soundCueGroup.add(soundCueCassandra.set(\"cassandra\", 0, 0, 100));\n soundCueGroup.add(soundCueTimePassing.set(\"time passing\", 0, 0, 100));\n soundCueGroup.add(soundCuePlayback.set(\"playback\", 0, 0, 100));\n soundCueGroup.add(soundCueOutro.set(\"outro\", 0, 0, 100));\n panel.add(soundCueGroup);\n \n panel.loadFromFile(\"settings\/cassandra.xml\");\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ protected\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ private\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid CassandraScene::setMode(Mode mode) {\n this->mode = mode;\n if (mode == PLAYBACK) {\n indexCassandra = 0;\n indexMain = 0;\n playbackTime = 0;\n sequenceCassandra.setExtension(\"jpg\");\n sequenceCassandra.loadSequence(DIR_CASSANDRA);\n sequenceCassandra.setFrameRate(cassandraFileCount\/CASSANDRA_DURATION);\n sequenceMain.setExtension(\"jpg\");\n sequenceMain.loadSequence(DIR_MAIN);\n sequenceMain.setFrameRate(mainFileCount\/MAIN_DURATION);\n }\n else {\n sequenceCassandra.unloadSequence();\n sequenceMain.unloadSequence();\n }\n if (mode == RECORD_CASSANDRA) {\n prepareRecordingDir(DIR_CASSANDRA);\n vision->setToIPCamCassandra();\n }\n else if (mode == RECORD_MAIN) {\n prepareRecordingDir(DIR_MAIN);\n vision->setToIPCamMain();\n }\n}\n\nvoid CassandraScene::prepareRecordingDir(string path) {\n \/\/ remove existing recordings\n if (ofDirectory::doesDirectoryExist(path)) {\n ofDirectory::removeDirectory(path, true);\n }\n ofDirectory::createDirectory(path);\n if(path == DIR_CASSANDRA) cassandraFileCount = 0;\n else mainFileCount = 0;\n}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ custom event handlers\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ oF event handlers\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n<|endoftext|>"} {"text":"\/\/ Copyright 2012 Alessio Sclocco \n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#ifdef HAVE_PSRDADA\n#include \n#endif\n#include \n\n#include \n#include \n\n\n#ifndef READ_DATA_HPP\n#define READ_DATA_HPP\n\nnamespace AstroData {\n\n\/\/ Exception: the PSRDADA ring buffer does not work\nclass RingBufferError : public std::exception {\npublic:\n explicit RingBufferError(std::string message);\n ~RingBufferError() throw ();\n\n const char * what() const throw ();\nprivate:\n std::string message;\n};\n\n\/\/ Zapped channels (excluded from computation)\nvoid readZappedChannels(Observation & observation, const std::string & inputFileName, std::vector< uint8_t > & zappedChannels);\n\/\/ Integration steps\nvoid readIntegrationSteps(const Observation & observation, const std::string & inputFileName, std::set< unsigned int > & integrationSteps);\n\/\/ SIGPROC data\ntemplate< typename T > void readSIGPROC(const Observation & observation, const unsigned int padding, const uint8_t inputBits, const unsigned int bytesToSkip, const std::string & inputFilename, std::vector< std::vector< T > * > & data, const unsigned int firstBatch = 0);\n\/\/ LOFAR data\ntemplate< typename T > void readLOFAR(std::string headerFilename, std::string rawFilename, Observation & observation, const unsigned int padding, std::vector< std::vector< T > * > & data, unsigned int nrBatches = 0, unsigned int firstBatch = 0);\n#ifdef HAVE_PSRDADA\n\/\/ PSRDADA buffer\nvoid readPSRDADAHeader(Observation & observation, dada_hdu_t & ringBuffer) throw(RingBufferError);\ntemplate< typename T > inline void readPSRDADA(dada_hdu_t & ringBuffer, std::vector< T > * data) throw(RingBufferError);\n#endif\n\n\/\/ Implementations\n\ntemplate< typename T > void readSIGPROC(const Observation & observation, const unsigned int padding, const uint8_t inputBits, const unsigned int bytesToSkip, const std::string & inputFilename, std::vector< std::vector< T > * > & data, const unsigned int firstBatch) {\n std::ifstream inputFile;\n const unsigned int BUFFER_DIM = sizeof(T);\n char * buffer = new char [BUFFER_DIM];\n\n inputFile.open(inputFilename.c_str(), std::ios::binary);\n inputFile.sync_with_stdio(false);\n inputFile.seekg(bytesToSkip, std::ios::beg);\n for ( unsigned int batch = 0; batch < observation.getNrBatches(); batch++ ) {\n if ( inputBits >= 8 ) {\n data.at(batch) = new std::vector< T >(observation.getNrChannels() * observation.getNrSamplesPerPaddedBatch(padding \/ sizeof(T)));\n for ( unsigned int sample = 0; sample < observation.getNrSamplesPerBatch(); sample++ ) {\n for ( unsigned int channel = observation.getNrChannels(); channel > 0; channel-- ) {\n inputFile.read(buffer, BUFFER_DIM);\n data.at(batch)->at((static_cast< uint64_t >(channel - 1) * observation.getNrSamplesPerPaddedBatch(padding \/ sizeof(T))) + sample) = *(reinterpret_cast< T * >(buffer));\n }\n }\n } else {\n uint64_t bytesToRead = static_cast< uint64_t >(observation.getNrSamplesPerBatch() * (observation.getNrChannels() \/ (8.0 \/ inputBits)));\n\n data.at(batch) = new std::vector< T >(observation.getNrChannels() * isa::utils::pad(observation.getNrSamplesPerBatch() \/ (8 \/ inputBits), padding \/ sizeof(T)));\n for ( uint64_t byte = 0; byte < bytesToRead; byte++ ) {\n unsigned int channel = (observation.getNrChannels() - 1) - ((byte * (8 \/ inputBits)) % observation.getNrChannels());\n unsigned int sample = (byte * (8 \/ inputBits)) \/ observation.getNrChannels();\n unsigned int sampleByte = sample \/ (8 \/ inputBits);\n uint8_t sampleFirstBit = (sample % (8 \/ inputBits)) * inputBits;\n\n inputFile.read(buffer, BUFFER_DIM);\n for ( unsigned int item = 0; item < 8 \/ inputBits; item++ ) {\n uint8_t channelFirstBit = item * inputBits;\n uint8_t sampleBuffer = 0;\n\n if ( item > channel ) {\n \/\/ All channels read, the remaining elements are from the next sample\n unsigned int channelOffset = 0;\n channel = (observation.getNrChannels() - 1);\n sample += 1;\n sampleByte = sample \/ (8 \/ inputBits);\n sampleFirstBit = (sample % (8 \/ inputBits)) * inputBits;\n\n while ( item < (8 \/ inputBits) ) {\n channelFirstBit = item * inputBits;\n sampleBuffer = data.at(batch)->at((static_cast< uint64_t >(channel - channelOffset) * isa::utils::pad(observation.getNrSamplesPerBatch() \/ (8 \/ inputBits), padding \/ sizeof(T))) + sampleByte);\n for ( uint8_t bit = 0; bit < inputBits; bit++ ) {\n isa::utils::setBit(sampleBuffer, isa::utils::getBit(*buffer, channelFirstBit + bit), sampleFirstBit + bit);\n }\n data.at(batch)->at((static_cast< uint64_t >(channel - channelOffset) * isa::utils::pad(observation.getNrSamplesPerBatch() \/ (8 \/ inputBits), padding \/ sizeof(T))) + sampleByte) = sampleBuffer;\n item++;\n channelOffset++;\n }\n\n break;\n }\n sampleBuffer = data.at(batch)->at((static_cast< uint64_t >(channel - item) * isa::utils::pad(observation.getNrSamplesPerBatch() \/ (8 \/ inputBits), padding \/ sizeof(T))) + sampleByte);\n for ( uint8_t bit = 0; bit < inputBits; bit++ ) {\n isa::utils::setBit(sampleBuffer, isa::utils::getBit(*buffer, channelFirstBit + bit), sampleFirstBit + bit);\n }\n data.at(batch)->at((static_cast< uint64_t >(channel - item) * isa::utils::pad(observation.getNrSamplesPerBatch() \/ (8 \/ inputBits), padding \/ sizeof(T))) + sampleByte) = sampleBuffer;\n }\n }\n }\n }\n inputFile.close();\n\n delete [] buffer;\n}\n\ntemplate< typename T > void readLOFAR(std::string headerFilename, std::string rawFilename, Observation & observation, const unsigned int padding, std::vector< std::vector< T > * > & data, unsigned int nrBatches, unsigned int firstBatch) {\n unsigned int nrSubbands, nrChannels;\n float minFreq, channelBandwidth;\n \/\/ Read the HDF5 file with the metadata\n H5::H5File headerFile = H5::H5File(headerFilename, H5F_ACC_RDONLY);\n H5::FloatType typeDouble = H5::FloatType(H5::PredType::NATIVE_DOUBLE);\n double valueDouble = 0.0;\n H5::IntType typeUInt = H5::IntType(H5::PredType::NATIVE_UINT);\n unsigned int valueUInt = 0;\n\n H5::Group currentNode = headerFile.openGroup(\"\/\");\n currentNode.openAttribute(\"OBSERVATION_FREQUENCY_MIN\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n minFreq = valueDouble;\n currentNode = currentNode.openGroup(currentNode.getObjnameByIdx(0));\n currentNode.openAttribute(\"TOTAL_INTEGRATION_TIME\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n double totalIntegrationTime = valueDouble;\n currentNode.openAttribute(\"NOF_BEAMS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n observation.setNrBeams(valueUInt);\n currentNode = currentNode.openGroup(currentNode.getObjnameByIdx(0));\n currentNode.openAttribute(\"NOF_SAMPLES\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n unsigned int totalSamples = valueUInt;\n currentNode.openAttribute(\"NOF_STATIONS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n observation.setNrStations(valueUInt);\n currentNode.openAttribute(\"CHANNELS_PER_SUBBAND\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n nrChannels = valueUInt;\n currentNode.openAttribute(\"CHANNEL_WIDTH\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n channelBandwidth = valueDouble \/ 1000000;\n H5::DataSet currentData = currentNode.openDataSet(\"STOKES_0\");\n currentData.openAttribute(\"NOF_SUBBANDS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n nrSubbands = valueUInt;\n headerFile.close();\n\n observation.setNrSamplesPerBatch(static_cast< unsigned int >(totalSamples \/ totalIntegrationTime));\n if ( nrBatches == 0 ) {\n observation.setNrBatches(static_cast< unsigned int >(totalIntegrationTime));\n } else {\n if ( static_cast< unsigned int >(totalIntegrationTime) >= (firstBatch + nrBatches) ) {\n observation.setNrBatches(nrBatches);\n } else {\n observation.setNrBatches(static_cast< unsigned int >(totalIntegrationTime) - firstBatch);\n }\n }\n observation.setFrequencyRange(1, nrSubbands * nrChannels, minFreq, channelBandwidth);\n\n \/\/ Read the raw file with the actual data\n std::ifstream rawFile;\n rawFile.open(rawFilename.c_str(), std::ios::binary);\n rawFile.sync_with_stdio(false);\n if ( firstBatch > 0 ) {\n rawFile.seekg(firstBatch * observation.getNrSamplesPerBatch() * nrSubbands * nrChannels, std::ios::beg);\n }\n data.resize(observation.getNrBatches());\n\n char * word = new char [4];\n for ( unsigned int batch = 0; batch < observation.getNrBatches(); batch++ ) {\n data.at(batch) = new std::vector< T >(observation.getNrChannels() * observation.getNrSamplesPerPaddedBatch(padding \/ sizeof(T)));\n for ( unsigned int sample = 0; sample < observation.getNrSamplesPerBatch(); sample++ ) {\n for ( unsigned int subband = 0; subband < nrSubbands; subband++ ) {\n for ( unsigned int channel = 0; channel < nrChannels; channel++ ) {\n unsigned int globalChannel = (subband * nrChannels) + channel;\n\n rawFile.read(word, 4);\n isa::utils::bigEndianToLittleEndian(word);\n data.at(batch)->at((globalChannel * observation.getNrSamplesPerPaddedBatch(padding \/ sizeof(T))) + sample) = *(reinterpret_cast< T * >(word));\n }\n }\n }\n }\n rawFile.close();\n delete [] word;\n}\n\n#ifdef HAVE_PSRDADA\ntemplate< typename T > inline void readPSRDADA(dada_hdu_t & ringBuffer, std::vector< T > * data) throw(RingBufferError) {\n char * buffer = 0;\n uint64_t bufferBytes = 0;\n\n buffer = ipcbuf_get_next_read(reinterpret_cast< ipcbuf_t * >(ringBuffer.data_block), &bufferBytes);\n if ( (buffer == 0) || (bufferBytes == 0) ) {\n throw RingBufferError(\"Impossible to read the PSRDADA buffer.\");\n }\n std::memcpy(reinterpret_cast< void * >(data->data()), reinterpret_cast< const void * >(buffer), data->size() * sizeof(T));\n if ( ipcbuf_mark_cleared(reinterpret_cast< ipcbuf_t * >(ringBuffer.data_block)) < 0 ) {\n throw RingBufferError(\"Impossible to mark the PSRDADA buffer as cleared.\");\n }\n}\n#endif\n} \/\/ AstroData\n\n#endif \/\/ READ_DATA_HPP\n\nBUGFIX: make psrdada header file optional\/\/ Copyright 2012 Alessio Sclocco \n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#ifdef HAVE_PSRDADA\n#include \n#include \n#endif\n\n#include \n#include \n\n\n#ifndef READ_DATA_HPP\n#define READ_DATA_HPP\n\nnamespace AstroData {\n\n\/\/ Exception: the PSRDADA ring buffer does not work\nclass RingBufferError : public std::exception {\npublic:\n explicit RingBufferError(std::string message);\n ~RingBufferError() throw ();\n\n const char * what() const throw ();\nprivate:\n std::string message;\n};\n\n\/\/ Zapped channels (excluded from computation)\nvoid readZappedChannels(Observation & observation, const std::string & inputFileName, std::vector< uint8_t > & zappedChannels);\n\/\/ Integration steps\nvoid readIntegrationSteps(const Observation & observation, const std::string & inputFileName, std::set< unsigned int > & integrationSteps);\n\/\/ SIGPROC data\ntemplate< typename T > void readSIGPROC(const Observation & observation, const unsigned int padding, const uint8_t inputBits, const unsigned int bytesToSkip, const std::string & inputFilename, std::vector< std::vector< T > * > & data, const unsigned int firstBatch = 0);\n\/\/ LOFAR data\ntemplate< typename T > void readLOFAR(std::string headerFilename, std::string rawFilename, Observation & observation, const unsigned int padding, std::vector< std::vector< T > * > & data, unsigned int nrBatches = 0, unsigned int firstBatch = 0);\n#ifdef HAVE_PSRDADA\n\/\/ PSRDADA buffer\nvoid readPSRDADAHeader(Observation & observation, dada_hdu_t & ringBuffer) throw(RingBufferError);\ntemplate< typename T > inline void readPSRDADA(dada_hdu_t & ringBuffer, std::vector< T > * data) throw(RingBufferError);\n#endif\n\n\/\/ Implementations\n\ntemplate< typename T > void readSIGPROC(const Observation & observation, const unsigned int padding, const uint8_t inputBits, const unsigned int bytesToSkip, const std::string & inputFilename, std::vector< std::vector< T > * > & data, const unsigned int firstBatch) {\n std::ifstream inputFile;\n const unsigned int BUFFER_DIM = sizeof(T);\n char * buffer = new char [BUFFER_DIM];\n\n inputFile.open(inputFilename.c_str(), std::ios::binary);\n inputFile.sync_with_stdio(false);\n inputFile.seekg(bytesToSkip, std::ios::beg);\n for ( unsigned int batch = 0; batch < observation.getNrBatches(); batch++ ) {\n if ( inputBits >= 8 ) {\n data.at(batch) = new std::vector< T >(observation.getNrChannels() * observation.getNrSamplesPerPaddedBatch(padding \/ sizeof(T)));\n for ( unsigned int sample = 0; sample < observation.getNrSamplesPerBatch(); sample++ ) {\n for ( unsigned int channel = observation.getNrChannels(); channel > 0; channel-- ) {\n inputFile.read(buffer, BUFFER_DIM);\n data.at(batch)->at((static_cast< uint64_t >(channel - 1) * observation.getNrSamplesPerPaddedBatch(padding \/ sizeof(T))) + sample) = *(reinterpret_cast< T * >(buffer));\n }\n }\n } else {\n uint64_t bytesToRead = static_cast< uint64_t >(observation.getNrSamplesPerBatch() * (observation.getNrChannels() \/ (8.0 \/ inputBits)));\n\n data.at(batch) = new std::vector< T >(observation.getNrChannels() * isa::utils::pad(observation.getNrSamplesPerBatch() \/ (8 \/ inputBits), padding \/ sizeof(T)));\n for ( uint64_t byte = 0; byte < bytesToRead; byte++ ) {\n unsigned int channel = (observation.getNrChannels() - 1) - ((byte * (8 \/ inputBits)) % observation.getNrChannels());\n unsigned int sample = (byte * (8 \/ inputBits)) \/ observation.getNrChannels();\n unsigned int sampleByte = sample \/ (8 \/ inputBits);\n uint8_t sampleFirstBit = (sample % (8 \/ inputBits)) * inputBits;\n\n inputFile.read(buffer, BUFFER_DIM);\n for ( unsigned int item = 0; item < 8 \/ inputBits; item++ ) {\n uint8_t channelFirstBit = item * inputBits;\n uint8_t sampleBuffer = 0;\n\n if ( item > channel ) {\n \/\/ All channels read, the remaining elements are from the next sample\n unsigned int channelOffset = 0;\n channel = (observation.getNrChannels() - 1);\n sample += 1;\n sampleByte = sample \/ (8 \/ inputBits);\n sampleFirstBit = (sample % (8 \/ inputBits)) * inputBits;\n\n while ( item < (8 \/ inputBits) ) {\n channelFirstBit = item * inputBits;\n sampleBuffer = data.at(batch)->at((static_cast< uint64_t >(channel - channelOffset) * isa::utils::pad(observation.getNrSamplesPerBatch() \/ (8 \/ inputBits), padding \/ sizeof(T))) + sampleByte);\n for ( uint8_t bit = 0; bit < inputBits; bit++ ) {\n isa::utils::setBit(sampleBuffer, isa::utils::getBit(*buffer, channelFirstBit + bit), sampleFirstBit + bit);\n }\n data.at(batch)->at((static_cast< uint64_t >(channel - channelOffset) * isa::utils::pad(observation.getNrSamplesPerBatch() \/ (8 \/ inputBits), padding \/ sizeof(T))) + sampleByte) = sampleBuffer;\n item++;\n channelOffset++;\n }\n\n break;\n }\n sampleBuffer = data.at(batch)->at((static_cast< uint64_t >(channel - item) * isa::utils::pad(observation.getNrSamplesPerBatch() \/ (8 \/ inputBits), padding \/ sizeof(T))) + sampleByte);\n for ( uint8_t bit = 0; bit < inputBits; bit++ ) {\n isa::utils::setBit(sampleBuffer, isa::utils::getBit(*buffer, channelFirstBit + bit), sampleFirstBit + bit);\n }\n data.at(batch)->at((static_cast< uint64_t >(channel - item) * isa::utils::pad(observation.getNrSamplesPerBatch() \/ (8 \/ inputBits), padding \/ sizeof(T))) + sampleByte) = sampleBuffer;\n }\n }\n }\n }\n inputFile.close();\n\n delete [] buffer;\n}\n\ntemplate< typename T > void readLOFAR(std::string headerFilename, std::string rawFilename, Observation & observation, const unsigned int padding, std::vector< std::vector< T > * > & data, unsigned int nrBatches, unsigned int firstBatch) {\n unsigned int nrSubbands, nrChannels;\n float minFreq, channelBandwidth;\n \/\/ Read the HDF5 file with the metadata\n H5::H5File headerFile = H5::H5File(headerFilename, H5F_ACC_RDONLY);\n H5::FloatType typeDouble = H5::FloatType(H5::PredType::NATIVE_DOUBLE);\n double valueDouble = 0.0;\n H5::IntType typeUInt = H5::IntType(H5::PredType::NATIVE_UINT);\n unsigned int valueUInt = 0;\n\n H5::Group currentNode = headerFile.openGroup(\"\/\");\n currentNode.openAttribute(\"OBSERVATION_FREQUENCY_MIN\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n minFreq = valueDouble;\n currentNode = currentNode.openGroup(currentNode.getObjnameByIdx(0));\n currentNode.openAttribute(\"TOTAL_INTEGRATION_TIME\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n double totalIntegrationTime = valueDouble;\n currentNode.openAttribute(\"NOF_BEAMS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n observation.setNrBeams(valueUInt);\n currentNode = currentNode.openGroup(currentNode.getObjnameByIdx(0));\n currentNode.openAttribute(\"NOF_SAMPLES\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n unsigned int totalSamples = valueUInt;\n currentNode.openAttribute(\"NOF_STATIONS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n observation.setNrStations(valueUInt);\n currentNode.openAttribute(\"CHANNELS_PER_SUBBAND\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n nrChannels = valueUInt;\n currentNode.openAttribute(\"CHANNEL_WIDTH\").read(typeDouble, reinterpret_cast< void * >(&valueDouble));\n channelBandwidth = valueDouble \/ 1000000;\n H5::DataSet currentData = currentNode.openDataSet(\"STOKES_0\");\n currentData.openAttribute(\"NOF_SUBBANDS\").read(typeUInt, reinterpret_cast< void * >(&valueUInt));\n nrSubbands = valueUInt;\n headerFile.close();\n\n observation.setNrSamplesPerBatch(static_cast< unsigned int >(totalSamples \/ totalIntegrationTime));\n if ( nrBatches == 0 ) {\n observation.setNrBatches(static_cast< unsigned int >(totalIntegrationTime));\n } else {\n if ( static_cast< unsigned int >(totalIntegrationTime) >= (firstBatch + nrBatches) ) {\n observation.setNrBatches(nrBatches);\n } else {\n observation.setNrBatches(static_cast< unsigned int >(totalIntegrationTime) - firstBatch);\n }\n }\n observation.setFrequencyRange(1, nrSubbands * nrChannels, minFreq, channelBandwidth);\n\n \/\/ Read the raw file with the actual data\n std::ifstream rawFile;\n rawFile.open(rawFilename.c_str(), std::ios::binary);\n rawFile.sync_with_stdio(false);\n if ( firstBatch > 0 ) {\n rawFile.seekg(firstBatch * observation.getNrSamplesPerBatch() * nrSubbands * nrChannels, std::ios::beg);\n }\n data.resize(observation.getNrBatches());\n\n char * word = new char [4];\n for ( unsigned int batch = 0; batch < observation.getNrBatches(); batch++ ) {\n data.at(batch) = new std::vector< T >(observation.getNrChannels() * observation.getNrSamplesPerPaddedBatch(padding \/ sizeof(T)));\n for ( unsigned int sample = 0; sample < observation.getNrSamplesPerBatch(); sample++ ) {\n for ( unsigned int subband = 0; subband < nrSubbands; subband++ ) {\n for ( unsigned int channel = 0; channel < nrChannels; channel++ ) {\n unsigned int globalChannel = (subband * nrChannels) + channel;\n\n rawFile.read(word, 4);\n isa::utils::bigEndianToLittleEndian(word);\n data.at(batch)->at((globalChannel * observation.getNrSamplesPerPaddedBatch(padding \/ sizeof(T))) + sample) = *(reinterpret_cast< T * >(word));\n }\n }\n }\n }\n rawFile.close();\n delete [] word;\n}\n\n#ifdef HAVE_PSRDADA\ntemplate< typename T > inline void readPSRDADA(dada_hdu_t & ringBuffer, std::vector< T > * data) throw(RingBufferError) {\n char * buffer = 0;\n uint64_t bufferBytes = 0;\n\n buffer = ipcbuf_get_next_read(reinterpret_cast< ipcbuf_t * >(ringBuffer.data_block), &bufferBytes);\n if ( (buffer == 0) || (bufferBytes == 0) ) {\n throw RingBufferError(\"Impossible to read the PSRDADA buffer.\");\n }\n std::memcpy(reinterpret_cast< void * >(data->data()), reinterpret_cast< const void * >(buffer), data->size() * sizeof(T));\n if ( ipcbuf_mark_cleared(reinterpret_cast< ipcbuf_t * >(ringBuffer.data_block)) < 0 ) {\n throw RingBufferError(\"Impossible to mark the PSRDADA buffer as cleared.\");\n }\n}\n#endif\n} \/\/ AstroData\n\n#endif \/\/ READ_DATA_HPP\n\n<|endoftext|>"} {"text":"#ifdef _WIN32\n#include \n#include \n#include \n#include \"winargs.h\"\n#include \"winglob.h\"\n\nstatic bool is_unc(const std::wstring &argw) {\n\tif (argw.length() > 4) {\n\t\treturn argw[0] == '\\\\' && argw[1] == '\\\\' && argw[2] == '?' && argw[3] == '\\\\';\n\t}\n\treturn false;\n}\n\n\/\/ Translate a path into components, i.e. { \"C:\", \"Users\", \"Me\", \"Doc*\", \"*.foo\" }\nstatic std::vector split_components(const std::wstring &argw) {\n\tstd::vector components;\n\tif (is_unc(argw)) {\n\t\t\/\/ This tells us specifically not to perform wildcard expansion.\n\t\tcomponents.push_back(argw);\n\t\treturn components;\n\t}\n\n\tsize_t pos = 0;\n\twhile (pos != argw.npos) {\n\t\tsize_t next = argw.find_first_of(L\"\/\\\\\", pos);\n\t\tif (next == pos) {\n\t\t\tif (pos != 0) {\n\t\t\t\t\/\/ Ignore doubled up slashes, i.e. C:\\\\Users\\\\\\\\Me.\n\t\t\t\t++pos;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tnext = argw.find_first_of(L\"\/\\\\\", pos + 1);\n\t\t}\n\n\t\tif (next == argw.npos) {\n\t\t\tcomponents.push_back(argw.substr(pos));\n\t\t} else {\n\t\t\tcomponents.push_back(argw.substr(pos, next - pos));\n\t\t}\n\t\tpos = next;\n\t}\n\n\treturn components;\n}\n\nstatic std::wstring find_base_context(std::vector &components) {\n\tif (components[0].length() == 2 && components[0][1] == ':') {\n\t\t\/\/ Is the first thing a drive letter?\n\t\tstd::wstring context = components[0] + L\"\\\\\";\n\t\tcomponents.erase(components.begin());\n\t\treturn context;\n\t} else if (components[0].length() == 0) {\n\t\tcomponents.erase(components.begin());\n\t\treturn L\"\\\\\";\n\t} else if (components.size() == 1 && is_unc(components[0])) {\n\t\t\/\/ UNC path, use it as a context directly to avoid any wildcard parsing.\n\t\tstd::wstring context = components[0];\n\t\tcomponents.clear();\n\t\treturn context;\n\t}\n\n\treturn L\"\";\n}\n\n\/\/ Expand the wildcard component against each context folder in input, and return the full list.\nstatic std::vector next_contexts(const std::vector &input, std::wstring component) {\n\tstd::vector output;\n\n\t\/\/ Special case for . or .. as the component.\n\tif (component == L\".\" || component == L\"..\") {\n\t\tfor (const std::wstring &context : input) {\n\t\t\tstd::wstring base = context.empty() ? L\"\" : (context + L\"\\\\\");\n\t\t\toutput.push_back(base + component);\n\t\t}\n\t\treturn output;\n\t}\n\n\tfor (const std::wstring &context : input) {\n\t\tstd::wstring base = context.empty() ? L\"\" : (context + L\"\\\\\");\n\t\tstd::wstring search = base + component;\n\n\t\tWIN32_FIND_DATA data;\n\t\tHANDLE finder = FindFirstFile(search.c_str(), &data);\n\t\tif (finder == INVALID_HANDLE_VALUE) {\n\t\t\toutput.push_back(search);\n\t\t\tcontinue;\n\t\t}\n\t\tdo {\n\t\t\tstd::wstring filename(data.cFileName, wcsnlen(data.cFileName, MAX_PATH));\n\t\t\tif (filename == L\".\" || filename == L\"..\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\toutput.push_back(base + filename);\n\t\t} while (FindNextFile(finder, &data) != 0);\n\t\tFindClose(finder);\n\t}\n\n\treturn output;\n}\n\nvoid winargs_get_wildcard(const char *arg, std::vector &files) {\n\tstd::wstring argw;\n\tstr_to_utf16z(arg, argw);\n\tif (argw.empty()) {\n\t\treturn;\n\t}\n\targw.resize(argw.size() - 1);\n\n\t\/\/ We need to process each component, one at a time.\n\tstd::vector components = split_components(argw);\n\tstd::vector contexts;\n\tcontexts.push_back(find_base_context(components));\n\n\tfor (const std::wstring &component : components) {\n\t\tcontexts = next_contexts(contexts, component);\n\t}\n\n\t\/\/ Now we have all the expanded files, so convert to utf8.\n\tfor (const std::wstring &wfilename : contexts) {\n\t\tstd::string filename;\n\t\tstr_to_utf8z(wfilename.c_str(), filename);\n\t\t\/\/ Now truncate off the null - we don't need it here.\n\t\tif (!filename.empty()) {\n\t\t\tfilename.resize(filename.size() - 1);\n\t\t}\n\t\tfiles.push_back(filename);\n\t}\n}\n#endif\nAlways use Unicode file finding funcs.#ifdef _WIN32\n#include \n#include \n#include \n#include \"winargs.h\"\n#include \"winglob.h\"\n\nstatic bool is_unc(const std::wstring &argw) {\n\tif (argw.length() > 4) {\n\t\treturn argw[0] == '\\\\' && argw[1] == '\\\\' && argw[2] == '?' && argw[3] == '\\\\';\n\t}\n\treturn false;\n}\n\n\/\/ Translate a path into components, i.e. { \"C:\", \"Users\", \"Me\", \"Doc*\", \"*.foo\" }\nstatic std::vector split_components(const std::wstring &argw) {\n\tstd::vector components;\n\tif (is_unc(argw)) {\n\t\t\/\/ This tells us specifically not to perform wildcard expansion.\n\t\tcomponents.push_back(argw);\n\t\treturn components;\n\t}\n\n\tsize_t pos = 0;\n\twhile (pos != argw.npos) {\n\t\tsize_t next = argw.find_first_of(L\"\/\\\\\", pos);\n\t\tif (next == pos) {\n\t\t\tif (pos != 0) {\n\t\t\t\t\/\/ Ignore doubled up slashes, i.e. C:\\\\Users\\\\\\\\Me.\n\t\t\t\t++pos;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tnext = argw.find_first_of(L\"\/\\\\\", pos + 1);\n\t\t}\n\n\t\tif (next == argw.npos) {\n\t\t\tcomponents.push_back(argw.substr(pos));\n\t\t} else {\n\t\t\tcomponents.push_back(argw.substr(pos, next - pos));\n\t\t}\n\t\tpos = next;\n\t}\n\n\treturn components;\n}\n\nstatic std::wstring find_base_context(std::vector &components) {\n\tif (components[0].length() == 2 && components[0][1] == ':') {\n\t\t\/\/ Is the first thing a drive letter?\n\t\tstd::wstring context = components[0] + L\"\\\\\";\n\t\tcomponents.erase(components.begin());\n\t\treturn context;\n\t} else if (components[0].length() == 0) {\n\t\tcomponents.erase(components.begin());\n\t\treturn L\"\\\\\";\n\t} else if (components.size() == 1 && is_unc(components[0])) {\n\t\t\/\/ UNC path, use it as a context directly to avoid any wildcard parsing.\n\t\tstd::wstring context = components[0];\n\t\tcomponents.clear();\n\t\treturn context;\n\t}\n\n\treturn L\"\";\n}\n\n\/\/ Expand the wildcard component against each context folder in input, and return the full list.\nstatic std::vector next_contexts(const std::vector &input, std::wstring component) {\n\tstd::vector output;\n\n\t\/\/ Special case for . or .. as the component.\n\tif (component == L\".\" || component == L\"..\") {\n\t\tfor (const std::wstring &context : input) {\n\t\t\tstd::wstring base = context.empty() ? L\"\" : (context + L\"\\\\\");\n\t\t\toutput.push_back(base + component);\n\t\t}\n\t\treturn output;\n\t}\n\n\tfor (const std::wstring &context : input) {\n\t\tstd::wstring base = context.empty() ? L\"\" : (context + L\"\\\\\");\n\t\tstd::wstring search = base + component;\n\n\t\tWIN32_FIND_DATAW data;\n\t\tHANDLE finder = FindFirstFileW(search.c_str(), &data);\n\t\tif (finder == INVALID_HANDLE_VALUE) {\n\t\t\toutput.push_back(search);\n\t\t\tcontinue;\n\t\t}\n\t\tdo {\n\t\t\tstd::wstring filename(data.cFileName, wcsnlen(data.cFileName, MAX_PATH));\n\t\t\tif (filename == L\".\" || filename == L\"..\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\toutput.push_back(base + filename);\n\t\t} while (FindNextFileW(finder, &data) != 0);\n\t\tFindClose(finder);\n\t}\n\n\treturn output;\n}\n\nvoid winargs_get_wildcard(const char *arg, std::vector &files) {\n\tstd::wstring argw;\n\tstr_to_utf16z(arg, argw);\n\tif (argw.empty()) {\n\t\treturn;\n\t}\n\targw.resize(argw.size() - 1);\n\n\t\/\/ We need to process each component, one at a time.\n\tstd::vector components = split_components(argw);\n\tstd::vector contexts;\n\tcontexts.push_back(find_base_context(components));\n\n\tfor (const std::wstring &component : components) {\n\t\tcontexts = next_contexts(contexts, component);\n\t}\n\n\t\/\/ Now we have all the expanded files, so convert to utf8.\n\tfor (const std::wstring &wfilename : contexts) {\n\t\tstd::string filename;\n\t\tstr_to_utf8z(wfilename.c_str(), filename);\n\t\t\/\/ Now truncate off the null - we don't need it here.\n\t\tif (!filename.empty()) {\n\t\t\tfilename.resize(filename.size() - 1);\n\t\t}\n\t\tfiles.push_back(filename);\n\t}\n}\n#endif\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2012 Nokia Corporation and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/\n**\n** This file is part of the QtLocation module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** GNU Lesser General Public License Usage\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this\n** file. Please review the following information to ensure the GNU Lesser\n** General Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU General\n** Public License version 3.0 as published by the Free Software Foundation\n** and appearing in the file LICENSE.GPL included in the packaging of this\n** file. Please review the following information to ensure the GNU General\n** Public License version 3.0 requirements will be met:\n** http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** Other Usage\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n** This file is part of the Ovi services plugin for the Maps and\n** Navigation API. The use of these services, whether by use of the\n** plugin or by other means, is governed by the terms and conditions\n** described by the file OVI_SERVICES_TERMS_AND_CONDITIONS.txt in\n** this package, located in the directory containing the Ovi services\n** plugin source code.\n**\n****************************************************************************\/\n\n#include \"qgeomappingmanagerengine_nokia.h\"\n#include \"qgeomapreply_nokia.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#ifdef USE_CHINA_NETWORK_REGISTRATION\n#include \n#endif\n\n#define LARGE_TILE_DIMENSION 256\n\n#define DISK_CACHE_MAX_SIZE 50*1024*1024 \/\/50MB\n\n#if defined(Q_OS_WINCE_WM) || defined(Q_WS_MAEMO_5) || defined(Q_WS_MAEMO_6)\n#undef DISK_CACHE_ENABLED\n#else\n#define DISK_CACHE_ENABLED 1\n#endif\n\n#undef DISK_CACHE_ENABLED\n\nQT_BEGIN_NAMESPACE\n\nconst char* MAPTILES_HOST = \"1-4.maptile.lbs.ovi.com\";\nconst char* MAPTILES_HOST_CN = \"a-k.maptile.maps.svc.nokia.com.cn\";\n\nQGeoMappingManagerEngineNokia::QGeoMappingManagerEngineNokia(const QMap ¶meters, QGeoServiceProvider::Error *error, QString *errorString)\n : QGeoMappingManagerEngine(parameters),\n m_cache(0),\n m_token(QGeoServiceProviderFactoryNokia::defaultToken),\n m_referer(QGeoServiceProviderFactoryNokia::defaultReferer),\n m_firstSubdomain(QChar::Null),\n m_maxSubdomains(0)\n{\n Q_UNUSED(error)\n Q_UNUSED(errorString)\n\n setHost(MAPTILES_HOST);\n setMinimumZoomLevel(0.0);\n setMaximumZoomLevel(20.0);\n\n#ifdef USE_CHINA_NETWORK_REGISTRATION\n m_networkInfo = 0;\n#endif\n}\n\nQGeoMappingManagerEngineNokia::~QGeoMappingManagerEngineNokia() {}\n\nvoid QGeoMappingManagerEngineNokia::init()\n{\n setTileSize(256);\n\n QList types;\n types << QGeoMapType(QGeoMapType::StreetMap,tr(\"Street Map\"),tr(\"Nokia Street Map\"), false, 1);\n types << QGeoMapType(QGeoMapType::SatelliteMapDay,tr(\"Satellite Map(day)\"),tr(\"Nokia Satellite Map (day)\"), false, 2);\n types << QGeoMapType(QGeoMapType::TerrainMap,tr(\"Terrain Map\"),tr(\"Nokia Terrain Map\"), false, 3);\n types << QGeoMapType(QGeoMapType::HybridMap,tr(\"Hybrid Map\"),tr(\"Nokia Hybrid Map\"), false, 4);\n types << QGeoMapType(QGeoMapType::TransitMap,tr(\"Transit Map\"),tr(\"Nokia Transit Map\"), false, 5);\n types << QGeoMapType(QGeoMapType::GrayStreetMap,tr(\"Gray Street Map\"),tr(\"Nokia Gray Street Map\"), false, 6);\n types << QGeoMapType(QGeoMapType::StreetMap,tr(\"Mobile Street Map\"),tr(\"Nokia Mobile Street Map\"), true, 7);\n types << QGeoMapType(QGeoMapType::TerrainMap,tr(\"Mobile Terrain Map\"),tr(\"Nokia Mobile Terrain Map\"), true, 8);\n types << QGeoMapType(QGeoMapType::HybridMap,tr(\"Mobile Hybrid Map\"),tr(\"Nokia Mobile Hybrid Map\"), true, 9);\n types << QGeoMapType(QGeoMapType::TransitMap,tr(\"Mobile Transit Map\"),tr(\"Nokia Mobile Transit Map\"), true, 10);\n types << QGeoMapType(QGeoMapType::GrayStreetMap,tr(\"Mobile Gray Street Map\"),tr(\"Nokia Mobile Gray Street Map\"), true, 11);\n setSupportedMapTypes(types);\n\n\/\/ QList modes;\n\/\/ modes << QGraphicsGeoMap::OnlineMode;\n\/\/ setSupportedConnectivityModes(modes);\n\n m_networkManager = new QNetworkAccessManager(this);\n\n QMap parameters = this->parameters();\n\n if (parameters.contains(\"mapping.proxy\")) {\n QString proxy = parameters.value(\"mapping.proxy\").toString();\n if (!proxy.isEmpty()) {\n QUrl proxyUrl(proxy);\n if (proxyUrl.isValid()) {\n m_networkManager->setProxy(QNetworkProxy(QNetworkProxy::HttpProxy,\n proxyUrl.host(),\n proxyUrl.port(8080),\n proxyUrl.userName(),\n proxyUrl.password()));\n }\n }\n }\n\n if (parameters.contains(\"mapping.host\")) {\n QString host = parameters.value(\"mapping.host\").toString();\n if (!host.isEmpty())\n setHost(host);\n }\n\n if (parameters.contains(\"mapping.referer\")) {\n m_referer = parameters.value(\"mapping.referer\").toString();\n }\n\n if (parameters.contains(\"mapping.app_id\")) {\n m_applicationId = parameters.value(\"mapping.app_id\").toString();\n }\n else if (parameters.contains(\"app_id\")) {\n m_applicationId = parameters.value(\"app_id\").toString();\n }\n\n if (parameters.contains(\"mapping.token\")) {\n m_token = parameters.value(\"mapping.token\").toString();\n }\n else if (parameters.contains(\"token\")) {\n m_token = parameters.value(\"token\").toString();\n }\n#ifdef DISK_CACHE_ENABLED\n QString cacheDir;\n if (parameters.contains(\"mapping.cache.directory\"))\n cacheDir = parameters.value(\"mapping.cache.directory\").toString();\n\n if (cacheDir.isEmpty()) {\n cacheDir = QDir::temp().path()+\"\/maptiles\";\n }\n if (!cacheDir.isEmpty()) {\n m_cache = new QNetworkDiskCache(this);\n QDir dir;\n dir.mkpath(cacheDir);\n dir.setPath(cacheDir);\n\n m_cache->setCacheDirectory(dir.path());\n\n if (parameters.contains(\"mapping.cache.size\")) {\n bool ok = false;\n qint64 cacheSize = parameters.value(\"mapping.cache.size\").toString().toLongLong(&ok);\n if (ok)\n m_cache->setMaximumCacheSize(cacheSize);\n }\n\n if (m_cache->maximumCacheSize() > DISK_CACHE_MAX_SIZE)\n m_cache->setMaximumCacheSize(DISK_CACHE_MAX_SIZE);\n\n m_networkManager->setCache(m_cache);\n }\n#endif\n\n#ifdef USE_CHINA_NETWORK_REGISTRATION\n m_networkInfo = new QNetworkInfo(this);\n connect(m_networkInfo, SIGNAL(currentMobileCountryCodeChanged(int, const QString&)),\n SLOT(currentMobileCountryCodeChanged(int, const QString&)));\n currentMobileCountryCodeChanged(0, m_networkInfo->currentMobileCountryCode(0));\n#endif\n\n if (!isValidParameter(m_applicationId) || !isValidParameter(m_referer)) {\n qWarning() << \"Qt Location requires usage of app_id and token parameters obtained from:\";\n qWarning() << \"https:\/\/api.forum.nokia.com\/ovi-api\/ui\/registration\";\n }\n\n \/\/ Temporary testing aid for setting China maptile server\n QFile file(\"\/.enable_china_maptile_server\");\n if (file.exists()) {\n qDebug() << \"CHINA MAPTILE SERVER SET FOR TESTING PURPOSES.\";\n setHost(MAPTILES_HOST_CN);\n }\n\n QGeoMappingManagerEngine::init();\n}\n\nQGeoTiledMapReply* QGeoMappingManagerEngineNokia::getTileImage(const QGeoTileSpec &spec)\n{\n \/\/ TODO add error detection for if request.connectivityMode() != QGraphicsGeoMap::OnlineMode\n QString rawRequest = getRequestString(spec);\n\n QNetworkRequest netRequest((QUrl(rawRequest))); \/\/ The extra pair of parens disambiguates this from a function declaration\n netRequest.setAttribute(QNetworkRequest::HttpPipeliningAllowedAttribute, true);\n\n#ifdef DISK_CACHE_ENABLED\n netRequest.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache);\n#endif\n\n QNetworkReply* netReply = m_networkManager->get(netRequest);\n\n QGeoTiledMapReply* mapReply = new QGeoMapReplyNokia(netReply, spec);\n\n \/\/ TODO goes badly on linux\n \/\/qDebug() << \"request: \" << QString::number(reinterpret_cast(mapReply), 16) << \" \" << request.row() << \",\" << request.column();\n \/\/ this one might work better. It follows defined behaviour, unlike reinterpret_cast\n \/\/qDebug(\"request: %p %i,%i @ %i\", mapReply, request.row(), request.column(), request.zoomLevel());\n return mapReply;\n}\n\nQString QGeoMappingManagerEngineNokia::getRequestString(const QGeoTileSpec &spec) const\n{\n const char subdomain = m_maxSubdomains ? m_firstSubdomain.toAscii() +\n (spec.x() + spec.y()) % m_maxSubdomains : 0;\n static const QString http(\"http:\/\/\");\n static const QString path(\"\/maptiler\/v2\/maptile\/newest\/\");\n static const QChar dot('.');\n static const QChar slash('\/');\n\n QString requestString = http;\n if (subdomain != 0) {\n requestString += subdomain;\n requestString += dot;\n }\n requestString += m_host;\n requestString += path;\n\n requestString += mapIdToStr(spec.mapId());\n requestString += slash;\n requestString += QString::number(spec.zoom());\n requestString += slash;\n requestString += QString::number(spec.x());\n requestString += slash;\n requestString += QString::number(spec.y());\n requestString += slash;\n requestString += sizeToStr(tileSize());\n static const QString slashpng(\"\/png8\");\n requestString += slashpng;\n\n if (!m_token.isEmpty()) {\n requestString += \"?token=\";\n requestString += m_token;\n\n if (!m_referer.isEmpty()) {\n requestString += \"&referer=\";\n requestString += m_referer;\n }\n } else if (!m_referer.isEmpty()) {\n requestString += \"?referer=\";\n requestString += m_referer;\n }\n if (!m_applicationId.isEmpty()) {\n requestString += \"&app_id=\";\n requestString += m_applicationId;\n }\n return requestString;\n}\n\nQString QGeoMappingManagerEngineNokia::sizeToStr(int size)\n{\n static const QString s256(\"256\");\n static const QString s128(\"128\");\n if (size >= LARGE_TILE_DIMENSION)\n return s256;\n else\n return s128;\n}\n\nQString QGeoMappingManagerEngineNokia::mapIdToStr(int mapId)\n{\n typedef std::map MapTypeRegistry;\n static MapTypeRegistry registeredTypes;\n if (registeredTypes.empty()) {\n registeredTypes[0] = \"normal.day\";\n registeredTypes[1] = \"normal.day\";\n registeredTypes[2] = \"satellite.day\";\n registeredTypes[3] = \"terrain.day\";\n registeredTypes[4] = \"hybrid.day\";\n registeredTypes[5] = \"normal.day.transit\";\n registeredTypes[6] = \"normal.day.grey\";\n registeredTypes[7] = \"normal.day.mobile\";\n registeredTypes[8] = \"terrain.day.mobile\";\n registeredTypes[9] = \"hybrid.day.mobile\";\n registeredTypes[10] = \"normal.day.transit.mobile\";\n registeredTypes[11] = \"normal.day.grey.mobile\";\n }\n\n MapTypeRegistry::const_iterator it = registeredTypes.find(mapId);\n if (it != registeredTypes.end()) {\n return it->second;\n }\n\n qWarning() << \"Unknown mapId: \" << mapId;\n return \"normal.day\";\n}\n\nconst QString & QGeoMappingManagerEngineNokia::referer() const\n{\n return m_referer;\n}\n\nconst QString & QGeoMappingManagerEngineNokia::token() const\n{\n return m_token;\n}\n\nconst QString & QGeoMappingManagerEngineNokia::host() const\n{\n return m_host;\n}\n\nconst QString & QGeoMappingManagerEngineNokia::applicationId() const\n{\n return m_applicationId;\n}\nQChar QGeoMappingManagerEngineNokia::firstSubdomain() const\n{\n return m_firstSubdomain;\n}\n\nunsigned char QGeoMappingManagerEngineNokia::maxSubdomains() const\n{\n return m_maxSubdomains;\n}\n\nvoid QGeoMappingManagerEngineNokia::setHost(const QString &host)\n{\n if (host.length() > 4 && host.at(1) == QChar('-') && host.at(3) == QChar('.')) {\n QString realHost = host.right(host.length() - 4);\n m_firstSubdomain = host.at(0);\n m_maxSubdomains = host.at(2).toAscii() - host.at(0).toAscii() + 1;\n m_host = realHost;\n } else {\n m_host = host;\n m_firstSubdomain = QChar::Null;\n m_maxSubdomains = 0;\n }\n}\n\n#ifdef USE_CHINA_NETWORK_REGISTRATION\nvoid QGeoMappingManagerEngineNokia::currentMobileCountryCodeChanged(int interface, const QString & mcc)\n{\n Q_UNUSED(interface)\n if (mcc == \"460\" || mcc == \"461\" || mcc == \"454\" || mcc == \"455\") {\n setHost(MAPTILES_HOST_CN);\n }\n}\n#endif\n\nbool QGeoMappingManagerEngineNokia::isValidParameter(const QString ¶m)\n{\n if (param.isEmpty())\n return false;\n\n if (param.length() > 512)\n return false;\n\n foreach (QChar c, param) {\n if (!c.isLetterOrNumber() || c.toAscii() != '%' || c.toAscii() != '-' ||\n c.toAscii() != '+' || c.toAscii() != '_') {\n return false;\n }\n }\n\n return true;\n}\n\nQT_END_NAMESPACE\nFix warning message for app_id and token.\/****************************************************************************\n**\n** Copyright (C) 2012 Nokia Corporation and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/\n**\n** This file is part of the QtLocation module of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** GNU Lesser General Public License Usage\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this\n** file. Please review the following information to ensure the GNU Lesser\n** General Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU General\n** Public License version 3.0 as published by the Free Software Foundation\n** and appearing in the file LICENSE.GPL included in the packaging of this\n** file. Please review the following information to ensure the GNU General\n** Public License version 3.0 requirements will be met:\n** http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** Other Usage\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n** This file is part of the Ovi services plugin for the Maps and\n** Navigation API. The use of these services, whether by use of the\n** plugin or by other means, is governed by the terms and conditions\n** described by the file OVI_SERVICES_TERMS_AND_CONDITIONS.txt in\n** this package, located in the directory containing the Ovi services\n** plugin source code.\n**\n****************************************************************************\/\n\n#include \"qgeomappingmanagerengine_nokia.h\"\n#include \"qgeomapreply_nokia.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#ifdef USE_CHINA_NETWORK_REGISTRATION\n#include \n#endif\n\n#define LARGE_TILE_DIMENSION 256\n\n#define DISK_CACHE_MAX_SIZE 50*1024*1024 \/\/50MB\n\n#if defined(Q_OS_WINCE_WM) || defined(Q_WS_MAEMO_5) || defined(Q_WS_MAEMO_6)\n#undef DISK_CACHE_ENABLED\n#else\n#define DISK_CACHE_ENABLED 1\n#endif\n\n#undef DISK_CACHE_ENABLED\n\nQT_BEGIN_NAMESPACE\n\nconst char* MAPTILES_HOST = \"1-4.maptile.lbs.ovi.com\";\nconst char* MAPTILES_HOST_CN = \"a-k.maptile.maps.svc.nokia.com.cn\";\n\nQGeoMappingManagerEngineNokia::QGeoMappingManagerEngineNokia(const QMap ¶meters, QGeoServiceProvider::Error *error, QString *errorString)\n : QGeoMappingManagerEngine(parameters),\n m_cache(0),\n m_token(QGeoServiceProviderFactoryNokia::defaultToken),\n m_referer(QGeoServiceProviderFactoryNokia::defaultReferer),\n m_firstSubdomain(QChar::Null),\n m_maxSubdomains(0)\n{\n Q_UNUSED(error)\n Q_UNUSED(errorString)\n\n setHost(MAPTILES_HOST);\n setMinimumZoomLevel(0.0);\n setMaximumZoomLevel(20.0);\n\n#ifdef USE_CHINA_NETWORK_REGISTRATION\n m_networkInfo = 0;\n#endif\n}\n\nQGeoMappingManagerEngineNokia::~QGeoMappingManagerEngineNokia() {}\n\nvoid QGeoMappingManagerEngineNokia::init()\n{\n setTileSize(256);\n\n QList types;\n types << QGeoMapType(QGeoMapType::StreetMap,tr(\"Street Map\"),tr(\"Nokia Street Map\"), false, 1);\n types << QGeoMapType(QGeoMapType::SatelliteMapDay,tr(\"Satellite Map(day)\"),tr(\"Nokia Satellite Map (day)\"), false, 2);\n types << QGeoMapType(QGeoMapType::TerrainMap,tr(\"Terrain Map\"),tr(\"Nokia Terrain Map\"), false, 3);\n types << QGeoMapType(QGeoMapType::HybridMap,tr(\"Hybrid Map\"),tr(\"Nokia Hybrid Map\"), false, 4);\n types << QGeoMapType(QGeoMapType::TransitMap,tr(\"Transit Map\"),tr(\"Nokia Transit Map\"), false, 5);\n types << QGeoMapType(QGeoMapType::GrayStreetMap,tr(\"Gray Street Map\"),tr(\"Nokia Gray Street Map\"), false, 6);\n types << QGeoMapType(QGeoMapType::StreetMap,tr(\"Mobile Street Map\"),tr(\"Nokia Mobile Street Map\"), true, 7);\n types << QGeoMapType(QGeoMapType::TerrainMap,tr(\"Mobile Terrain Map\"),tr(\"Nokia Mobile Terrain Map\"), true, 8);\n types << QGeoMapType(QGeoMapType::HybridMap,tr(\"Mobile Hybrid Map\"),tr(\"Nokia Mobile Hybrid Map\"), true, 9);\n types << QGeoMapType(QGeoMapType::TransitMap,tr(\"Mobile Transit Map\"),tr(\"Nokia Mobile Transit Map\"), true, 10);\n types << QGeoMapType(QGeoMapType::GrayStreetMap,tr(\"Mobile Gray Street Map\"),tr(\"Nokia Mobile Gray Street Map\"), true, 11);\n setSupportedMapTypes(types);\n\n\/\/ QList modes;\n\/\/ modes << QGraphicsGeoMap::OnlineMode;\n\/\/ setSupportedConnectivityModes(modes);\n\n m_networkManager = new QNetworkAccessManager(this);\n\n QMap parameters = this->parameters();\n\n if (parameters.contains(\"mapping.proxy\")) {\n QString proxy = parameters.value(\"mapping.proxy\").toString();\n if (!proxy.isEmpty()) {\n QUrl proxyUrl(proxy);\n if (proxyUrl.isValid()) {\n m_networkManager->setProxy(QNetworkProxy(QNetworkProxy::HttpProxy,\n proxyUrl.host(),\n proxyUrl.port(8080),\n proxyUrl.userName(),\n proxyUrl.password()));\n }\n }\n }\n\n if (parameters.contains(\"mapping.host\")) {\n QString host = parameters.value(\"mapping.host\").toString();\n if (!host.isEmpty())\n setHost(host);\n }\n\n if (parameters.contains(\"mapping.referer\")) {\n m_referer = parameters.value(\"mapping.referer\").toString();\n }\n\n if (parameters.contains(\"mapping.app_id\")) {\n m_applicationId = parameters.value(\"mapping.app_id\").toString();\n }\n else if (parameters.contains(\"app_id\")) {\n m_applicationId = parameters.value(\"app_id\").toString();\n }\n\n if (parameters.contains(\"mapping.token\")) {\n m_token = parameters.value(\"mapping.token\").toString();\n }\n else if (parameters.contains(\"token\")) {\n m_token = parameters.value(\"token\").toString();\n }\n#ifdef DISK_CACHE_ENABLED\n QString cacheDir;\n if (parameters.contains(\"mapping.cache.directory\"))\n cacheDir = parameters.value(\"mapping.cache.directory\").toString();\n\n if (cacheDir.isEmpty()) {\n cacheDir = QDir::temp().path()+\"\/maptiles\";\n }\n if (!cacheDir.isEmpty()) {\n m_cache = new QNetworkDiskCache(this);\n QDir dir;\n dir.mkpath(cacheDir);\n dir.setPath(cacheDir);\n\n m_cache->setCacheDirectory(dir.path());\n\n if (parameters.contains(\"mapping.cache.size\")) {\n bool ok = false;\n qint64 cacheSize = parameters.value(\"mapping.cache.size\").toString().toLongLong(&ok);\n if (ok)\n m_cache->setMaximumCacheSize(cacheSize);\n }\n\n if (m_cache->maximumCacheSize() > DISK_CACHE_MAX_SIZE)\n m_cache->setMaximumCacheSize(DISK_CACHE_MAX_SIZE);\n\n m_networkManager->setCache(m_cache);\n }\n#endif\n\n#ifdef USE_CHINA_NETWORK_REGISTRATION\n m_networkInfo = new QNetworkInfo(this);\n connect(m_networkInfo, SIGNAL(currentMobileCountryCodeChanged(int, const QString&)),\n SLOT(currentMobileCountryCodeChanged(int, const QString&)));\n currentMobileCountryCodeChanged(0, m_networkInfo->currentMobileCountryCode(0));\n#endif\n\n if (!isValidParameter(m_applicationId) || !isValidParameter(m_token)) {\n qWarning() << \"This plug in must have a valid \\\"app_id\\\" and \\\"token\\\".\";\n qWarning() << \"These may be obtained from:\";\n qWarning() << \"https:\/\/api.forum.nokia.com\/ovi-api\/ui\/registration\";\n }\n\n \/\/ Temporary testing aid for setting China maptile server\n QFile file(\"\/.enable_china_maptile_server\");\n if (file.exists()) {\n qDebug() << \"CHINA MAPTILE SERVER SET FOR TESTING PURPOSES.\";\n setHost(MAPTILES_HOST_CN);\n }\n\n QGeoMappingManagerEngine::init();\n}\n\nQGeoTiledMapReply* QGeoMappingManagerEngineNokia::getTileImage(const QGeoTileSpec &spec)\n{\n \/\/ TODO add error detection for if request.connectivityMode() != QGraphicsGeoMap::OnlineMode\n QString rawRequest = getRequestString(spec);\n\n QNetworkRequest netRequest((QUrl(rawRequest))); \/\/ The extra pair of parens disambiguates this from a function declaration\n netRequest.setAttribute(QNetworkRequest::HttpPipeliningAllowedAttribute, true);\n\n#ifdef DISK_CACHE_ENABLED\n netRequest.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache);\n#endif\n\n QNetworkReply* netReply = m_networkManager->get(netRequest);\n\n QGeoTiledMapReply* mapReply = new QGeoMapReplyNokia(netReply, spec);\n\n \/\/ TODO goes badly on linux\n \/\/qDebug() << \"request: \" << QString::number(reinterpret_cast(mapReply), 16) << \" \" << request.row() << \",\" << request.column();\n \/\/ this one might work better. It follows defined behaviour, unlike reinterpret_cast\n \/\/qDebug(\"request: %p %i,%i @ %i\", mapReply, request.row(), request.column(), request.zoomLevel());\n return mapReply;\n}\n\nQString QGeoMappingManagerEngineNokia::getRequestString(const QGeoTileSpec &spec) const\n{\n const char subdomain = m_maxSubdomains ? m_firstSubdomain.toAscii() +\n (spec.x() + spec.y()) % m_maxSubdomains : 0;\n static const QString http(\"http:\/\/\");\n static const QString path(\"\/maptiler\/v2\/maptile\/newest\/\");\n static const QChar dot('.');\n static const QChar slash('\/');\n\n QString requestString = http;\n if (subdomain != 0) {\n requestString += subdomain;\n requestString += dot;\n }\n requestString += m_host;\n requestString += path;\n\n requestString += mapIdToStr(spec.mapId());\n requestString += slash;\n requestString += QString::number(spec.zoom());\n requestString += slash;\n requestString += QString::number(spec.x());\n requestString += slash;\n requestString += QString::number(spec.y());\n requestString += slash;\n requestString += sizeToStr(tileSize());\n static const QString slashpng(\"\/png8\");\n requestString += slashpng;\n\n if (!m_token.isEmpty()) {\n requestString += \"?token=\";\n requestString += m_token;\n\n if (!m_referer.isEmpty()) {\n requestString += \"&referer=\";\n requestString += m_referer;\n }\n } else if (!m_referer.isEmpty()) {\n requestString += \"?referer=\";\n requestString += m_referer;\n }\n if (!m_applicationId.isEmpty()) {\n requestString += \"&app_id=\";\n requestString += m_applicationId;\n }\n return requestString;\n}\n\nQString QGeoMappingManagerEngineNokia::sizeToStr(int size)\n{\n static const QString s256(\"256\");\n static const QString s128(\"128\");\n if (size >= LARGE_TILE_DIMENSION)\n return s256;\n else\n return s128;\n}\n\nQString QGeoMappingManagerEngineNokia::mapIdToStr(int mapId)\n{\n typedef std::map MapTypeRegistry;\n static MapTypeRegistry registeredTypes;\n if (registeredTypes.empty()) {\n registeredTypes[0] = \"normal.day\";\n registeredTypes[1] = \"normal.day\";\n registeredTypes[2] = \"satellite.day\";\n registeredTypes[3] = \"terrain.day\";\n registeredTypes[4] = \"hybrid.day\";\n registeredTypes[5] = \"normal.day.transit\";\n registeredTypes[6] = \"normal.day.grey\";\n registeredTypes[7] = \"normal.day.mobile\";\n registeredTypes[8] = \"terrain.day.mobile\";\n registeredTypes[9] = \"hybrid.day.mobile\";\n registeredTypes[10] = \"normal.day.transit.mobile\";\n registeredTypes[11] = \"normal.day.grey.mobile\";\n }\n\n MapTypeRegistry::const_iterator it = registeredTypes.find(mapId);\n if (it != registeredTypes.end()) {\n return it->second;\n }\n\n qWarning() << \"Unknown mapId: \" << mapId;\n return \"normal.day\";\n}\n\nconst QString & QGeoMappingManagerEngineNokia::referer() const\n{\n return m_referer;\n}\n\nconst QString & QGeoMappingManagerEngineNokia::token() const\n{\n return m_token;\n}\n\nconst QString & QGeoMappingManagerEngineNokia::host() const\n{\n return m_host;\n}\n\nconst QString & QGeoMappingManagerEngineNokia::applicationId() const\n{\n return m_applicationId;\n}\nQChar QGeoMappingManagerEngineNokia::firstSubdomain() const\n{\n return m_firstSubdomain;\n}\n\nunsigned char QGeoMappingManagerEngineNokia::maxSubdomains() const\n{\n return m_maxSubdomains;\n}\n\nvoid QGeoMappingManagerEngineNokia::setHost(const QString &host)\n{\n if (host.length() > 4 && host.at(1) == QChar('-') && host.at(3) == QChar('.')) {\n QString realHost = host.right(host.length() - 4);\n m_firstSubdomain = host.at(0);\n m_maxSubdomains = host.at(2).toAscii() - host.at(0).toAscii() + 1;\n m_host = realHost;\n } else {\n m_host = host;\n m_firstSubdomain = QChar::Null;\n m_maxSubdomains = 0;\n }\n}\n\n#ifdef USE_CHINA_NETWORK_REGISTRATION\nvoid QGeoMappingManagerEngineNokia::currentMobileCountryCodeChanged(int interface, const QString & mcc)\n{\n Q_UNUSED(interface)\n if (mcc == \"460\" || mcc == \"461\" || mcc == \"454\" || mcc == \"455\") {\n setHost(MAPTILES_HOST_CN);\n }\n}\n#endif\n\nbool QGeoMappingManagerEngineNokia::isValidParameter(const QString ¶m)\n{\n if (param.isEmpty())\n return false;\n\n if (param.length() > 512)\n return false;\n\n foreach (QChar c, param) {\n if (!c.isLetterOrNumber() || c.toAscii() != '%' || c.toAscii() != '-' ||\n c.toAscii() != '+' || c.toAscii() != '_') {\n return false;\n }\n }\n\n return true;\n}\n\nQT_END_NAMESPACE\n<|endoftext|>"} {"text":"\/*************************************************************************** \n** \n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies). \n** All rights reserved. \n** Contact: Nokia Corporation (testabilitydriver@nokia.com) \n** \n** This file is part of Testability Driver Qt Agent\n** \n** If you have questions regarding the use of this file, please contact \n** Nokia at testabilitydriver@nokia.com . \n** \n** This library is free software; you can redistribute it and\/or \n** modify it under the terms of the GNU Lesser General Public \n** License version 2.1 as published by the Free Software Foundation \n** and appearing in the file LICENSE.LGPL included in the packaging \n** of this file. \n** \n****************************************************************************\/ \n \n\n#include \"tasnativeutils.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n\nint pidOfXWindow(Display* display, Window win) \n{\n int pid = -1;\n Atom atom;\n Atom actual_type;\n int actual_format;\n unsigned long nitems;\n unsigned long bytes_after;\n unsigned char *prop = 0;\n int status;\n if (win != None && win != 0) {\n atom = XInternAtom(display, \"_NET_WM_PID\", True);\n if (atom != None) {\n status = XGetWindowProperty(display, win, atom, 0, 1024,\n False, AnyPropertyType,\n &actual_type,\n &actual_format, &nitems,\n &bytes_after,\n &prop);\n if (status!=0 || !prop || actual_format == None) {\n \/\/NOP\n } else {\n pid = prop[1] * 256;\n pid += prop[0]; \n }\n }\n \n \n\n } \n if (prop) XFree(prop);\n return pid;\n}\n\n\/\/#include \n\n\/*!\n \\class TasNativeUtils\n \\brief Provides platform dependent operations. \n*\/\n\n\/\/ Window id of the currently active window\n\n\n\nbool dockWindow(Display* dpy, Window window) \n{\n unsigned long nitems, after;\n int format;\n Atom type = None;\n unsigned char* data = NULL;\n Atom _NET_WM_WINDOW_TYPE_DOCK = XInternAtom(dpy, \"_NET_WM_WINDOW_TYPE_DOCK\",\n False);\n Atom WINDOW_TYPE = XInternAtom(dpy, \"_NET_WM_WINDOW_TYPE\", False); \n\n Atom curr_type;\n\n if (Success == XGetWindowProperty(dpy, window, WINDOW_TYPE, 0, 0x7FFFFFFF, False, AnyPropertyType,\n &type, &format, &nitems, &after, &data)) {\n if (!data) {\n return false;\n }\n for (int i = 0; i < (int)nitems; ++i) {\n curr_type = ((Atom*)data)[i];\n if (curr_type == _NET_WM_WINDOW_TYPE_DOCK) {\n XFree(data);\n return true;\n }\n }\n \n }\n\n if (data) XFree(data);\n return false;\n}\n\n\nlong getstate(Display* display, Window window)\n{\n static const long WM_STATE_ELEMENTS = 2L;\n \n unsigned long nitems;\n unsigned long leftover;\n Atom xa_WM_STATE, actual_type;\n int actual_format;\n int status;\n unsigned char* p = NULL;\n \n xa_WM_STATE = XInternAtom(display, \"WM_STATE\", True);\n\n if (window == None || window == 0) {\n return -1;\n }\n status = XGetWindowProperty(display, window,\n xa_WM_STATE, 0L, WM_STATE_ELEMENTS,\n False, xa_WM_STATE, &actual_type, &actual_format,\n &nitems, &leftover, &p);\n long value = -1;\n \n if (status == 0) {\n if (p != NULL) {\n \/\/ Take first 8 bits\n \/\/ Wonder if this is the same on a 64 bit system?\n value = * (const unsigned long *) p & 0xffffffff; \n XFree(p);\n }\n\n return value;\n }\n\n\n if (p) XFree(p);\n return -1;\n}\n\nWindow queryStack(Display* dpy, Window root, const QList& pids)\n{\n Atom STACK = XInternAtom(dpy, \"_NET_CLIENT_LIST_STACKING\", False);\n unsigned long nitems, after;\n int format;\n Atom type = None;\n unsigned char* data = NULL;\n Window child;\n int i;\n \n if (!STACK) {\n return root;\n }\n if (Success == XGetWindowProperty(dpy, root, STACK, 0, 0x7FFFFFFF, False, XA_WINDOW,\n &type, &format, &nitems, &after, &data)) {\n for (i = (nitems-1); i >= 0; --i) {\n child = ((Window*)data)[i];\n if (!dockWindow(dpy, child) && getstate(dpy, child) == 1 && \n pids.contains(QString::number(pidOfXWindow(dpy, child)))) {\n\n if (data) XFree(data);\n return child;\n }\n }\n \n }\n if (data) XFree(data);\n return None;\n \n}\n\nWindow tryChildren(Display *dpy, Window win)\n{\n Window root, parent;\n Window *children;\n unsigned int nchildren;\n int i;\n Window inf = 0;\n Window child;\n if (!XQueryTree(dpy, win, &root, &parent, &children, &nchildren)) {\n return 0;\n }\n \/\/ Traverse bottom-up direction\n\/\/ for (i = 0; !inf && (i < nchildren); i++) {\n for (i = nchildren-1; !inf && (i >= 0); i--) {\n \/\/ NormalState per ICCM\n if (getstate(dpy, children[i]) == 1) {\n inf = children[i];\n } else {\n child = tryChildren(dpy, children[i]);\n if (child) {\n inf = child;\n }\n }\n }\n if (children) {\n XFree(children);\n }\n\n return inf;\n}\n\nWindow findActiveWindow(Display *dpy, Window win)\n{\n Window inf;\n if (getstate(dpy, win) == 1) {\n return win;\n }\n inf = tryChildren(dpy, win);\n if (!inf)\n inf = win;\n return inf;\n}\n\n\/\/ Ignore errors related to the Window calls (of course, the pid is not resolved)\nint errorHandler(Display*, XErrorEvent* e) \n{\n TasLogger::logger()->warning(\"TasNativeUtils::errorHandler received X Error during request\");\n if (e->error_code == BadWindow) {\n \/\/ More verbose on the most common one\n TasLogger::logger()->warning(\"TasNativeUtils::errorHandler BadWindow\");\n } else {\n TasLogger::logger()->warning(\"TasNativeUtils::errorHandler code \" + \n QString::number(e->error_code));\n }\n \/\/ XGetErrorText contains more info, if necessary\n return 0;\n}\n\n\n\nint TasNativeUtils::pidOfActiveWindow(const QHash clients)\n{\n const QList& pids = clients.keys();\n TasLogger::logger()->debug(\"TasNativeUtils::pidOfActiveWindow Querying for active window\");\n int pid = -1;\n Display* display = 0;\n display = XOpenDisplay(0); \n XSetErrorHandler(errorHandler);\n if (!display) return -1;\n\n int screen = XDefaultScreen(display);\n int window = RootWindow(display, screen);\n Window win = queryStack(display, window, pids);\n pid = pidOfXWindow(display, win);\n XCloseDisplay(display); \n\n TasLogger::logger()->debug(\"TasNativeUtils::pidOfActiveWindow Resolved \" + QString::number(pid));\n return pid;\n}\n\nint TasNativeUtils::bringAppToForeground(TasClient& app)\n{\n Q_UNUSED(app);\n return -1;\n}\n\nvoid TasNativeUtils::changeOrientation(QString)\n{}\n\nbool TasNativeUtils::killProcess(quint64 pid)\n{ \n printf(\"killing %d \\n\", int(pid));\n kill(pid, 9);\n return true;\n}\n\n\nbool TasNativeUtils::verifyProcess(quint64 pid)\n{\n \/\/ kill(pid,0) ?\n char path[256];\n sprintf(path, \"\/proc\/%d\", int(pid));\n return access(path, F_OK) != -1;\n}\n\n\nbool TasNativeUtils::processExitStatus(quint64 pid, int &status)\n{\n return true;\n}\n\nunix impl of exit status\/*************************************************************************** \n** \n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies). \n** All rights reserved. \n** Contact: Nokia Corporation (testabilitydriver@nokia.com) \n** \n** This file is part of Testability Driver Qt Agent\n** \n** If you have questions regarding the use of this file, please contact \n** Nokia at testabilitydriver@nokia.com . \n** \n** This library is free software; you can redistribute it and\/or \n** modify it under the terms of the GNU Lesser General Public \n** License version 2.1 as published by the Free Software Foundation \n** and appearing in the file LICENSE.LGPL included in the packaging \n** of this file. \n** \n****************************************************************************\/ \n \n\n#include \"tasnativeutils.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n\nint pidOfXWindow(Display* display, Window win) \n{\n int pid = -1;\n Atom atom;\n Atom actual_type;\n int actual_format;\n unsigned long nitems;\n unsigned long bytes_after;\n unsigned char *prop = 0;\n int status;\n if (win != None && win != 0) {\n atom = XInternAtom(display, \"_NET_WM_PID\", True);\n if (atom != None) {\n status = XGetWindowProperty(display, win, atom, 0, 1024,\n False, AnyPropertyType,\n &actual_type,\n &actual_format, &nitems,\n &bytes_after,\n &prop);\n if (status!=0 || !prop || actual_format == None) {\n \/\/NOP\n } else {\n pid = prop[1] * 256;\n pid += prop[0]; \n }\n }\n \n \n\n } \n if (prop) XFree(prop);\n return pid;\n}\n\n\/\/#include \n\n\/*!\n \\class TasNativeUtils\n \\brief Provides platform dependent operations. \n*\/\n\n\/\/ Window id of the currently active window\n\n\n\nbool dockWindow(Display* dpy, Window window) \n{\n unsigned long nitems, after;\n int format;\n Atom type = None;\n unsigned char* data = NULL;\n Atom _NET_WM_WINDOW_TYPE_DOCK = XInternAtom(dpy, \"_NET_WM_WINDOW_TYPE_DOCK\",\n False);\n Atom WINDOW_TYPE = XInternAtom(dpy, \"_NET_WM_WINDOW_TYPE\", False); \n\n Atom curr_type;\n\n if (Success == XGetWindowProperty(dpy, window, WINDOW_TYPE, 0, 0x7FFFFFFF, False, AnyPropertyType,\n &type, &format, &nitems, &after, &data)) {\n if (!data) {\n return false;\n }\n for (int i = 0; i < (int)nitems; ++i) {\n curr_type = ((Atom*)data)[i];\n if (curr_type == _NET_WM_WINDOW_TYPE_DOCK) {\n XFree(data);\n return true;\n }\n }\n \n }\n\n if (data) XFree(data);\n return false;\n}\n\n\nlong getstate(Display* display, Window window)\n{\n static const long WM_STATE_ELEMENTS = 2L;\n \n unsigned long nitems;\n unsigned long leftover;\n Atom xa_WM_STATE, actual_type;\n int actual_format;\n int status;\n unsigned char* p = NULL;\n \n xa_WM_STATE = XInternAtom(display, \"WM_STATE\", True);\n\n if (window == None || window == 0) {\n return -1;\n }\n status = XGetWindowProperty(display, window,\n xa_WM_STATE, 0L, WM_STATE_ELEMENTS,\n False, xa_WM_STATE, &actual_type, &actual_format,\n &nitems, &leftover, &p);\n long value = -1;\n \n if (status == 0) {\n if (p != NULL) {\n \/\/ Take first 8 bits\n \/\/ Wonder if this is the same on a 64 bit system?\n value = * (const unsigned long *) p & 0xffffffff; \n XFree(p);\n }\n\n return value;\n }\n\n\n if (p) XFree(p);\n return -1;\n}\n\nWindow queryStack(Display* dpy, Window root, const QList& pids)\n{\n Atom STACK = XInternAtom(dpy, \"_NET_CLIENT_LIST_STACKING\", False);\n unsigned long nitems, after;\n int format;\n Atom type = None;\n unsigned char* data = NULL;\n Window child;\n int i;\n \n if (!STACK) {\n return root;\n }\n if (Success == XGetWindowProperty(dpy, root, STACK, 0, 0x7FFFFFFF, False, XA_WINDOW,\n &type, &format, &nitems, &after, &data)) {\n for (i = (nitems-1); i >= 0; --i) {\n child = ((Window*)data)[i];\n if (!dockWindow(dpy, child) && getstate(dpy, child) == 1 && \n pids.contains(QString::number(pidOfXWindow(dpy, child)))) {\n\n if (data) XFree(data);\n return child;\n }\n }\n \n }\n if (data) XFree(data);\n return None;\n \n}\n\nWindow tryChildren(Display *dpy, Window win)\n{\n Window root, parent;\n Window *children;\n unsigned int nchildren;\n int i;\n Window inf = 0;\n Window child;\n if (!XQueryTree(dpy, win, &root, &parent, &children, &nchildren)) {\n return 0;\n }\n \/\/ Traverse bottom-up direction\n\/\/ for (i = 0; !inf && (i < nchildren); i++) {\n for (i = nchildren-1; !inf && (i >= 0); i--) {\n \/\/ NormalState per ICCM\n if (getstate(dpy, children[i]) == 1) {\n inf = children[i];\n } else {\n child = tryChildren(dpy, children[i]);\n if (child) {\n inf = child;\n }\n }\n }\n if (children) {\n XFree(children);\n }\n\n return inf;\n}\n\nWindow findActiveWindow(Display *dpy, Window win)\n{\n Window inf;\n if (getstate(dpy, win) == 1) {\n return win;\n }\n inf = tryChildren(dpy, win);\n if (!inf)\n inf = win;\n return inf;\n}\n\n\/\/ Ignore errors related to the Window calls (of course, the pid is not resolved)\nint errorHandler(Display*, XErrorEvent* e) \n{\n TasLogger::logger()->warning(\"TasNativeUtils::errorHandler received X Error during request\");\n if (e->error_code == BadWindow) {\n \/\/ More verbose on the most common one\n TasLogger::logger()->warning(\"TasNativeUtils::errorHandler BadWindow\");\n } else {\n TasLogger::logger()->warning(\"TasNativeUtils::errorHandler code \" + \n QString::number(e->error_code));\n }\n \/\/ XGetErrorText contains more info, if necessary\n return 0;\n}\n\n\n\nint TasNativeUtils::pidOfActiveWindow(const QHash clients)\n{\n const QList& pids = clients.keys();\n TasLogger::logger()->debug(\"TasNativeUtils::pidOfActiveWindow Querying for active window\");\n int pid = -1;\n Display* display = 0;\n display = XOpenDisplay(0); \n XSetErrorHandler(errorHandler);\n if (!display) return -1;\n\n int screen = XDefaultScreen(display);\n int window = RootWindow(display, screen);\n Window win = queryStack(display, window, pids);\n pid = pidOfXWindow(display, win);\n XCloseDisplay(display); \n\n TasLogger::logger()->debug(\"TasNativeUtils::pidOfActiveWindow Resolved \" + QString::number(pid));\n return pid;\n}\n\nint TasNativeUtils::bringAppToForeground(TasClient& app)\n{\n Q_UNUSED(app);\n return -1;\n}\n\nvoid TasNativeUtils::changeOrientation(QString)\n{}\n\nbool TasNativeUtils::killProcess(quint64 pid)\n{ \n kill(pid, 9);\n return true;\n}\n\n\nbool TasNativeUtils::verifyProcess(quint64 pid)\n{\n \/\/ kill(pid,0) ?\n char path[256];\n sprintf(path, \"\/proc\/%d\", int(pid));\n return access(path, F_OK) != -1;\n}\n\n\nbool TasNativeUtils::processExitStatus(quint64 pid, int &status)\n{\n if (verifyProcess) return false;\n status = 0;\n return true;\n}\n\n<|endoftext|>"} {"text":"\/*\nCopyright (c) 2012 Carsten Burstedde, Donna Calhoun\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation\nand\/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#if defined(_OPENMP)\n#include \n#endif\n\n#ifdef __cplusplus\nextern \"C\"\n{\n#if 0\n}\n#endif\n#endif\n\n\n\/* -----------------------------------------------------------------\n Initial grid\n ----------------------------------------------------------------- *\/\nstatic\nvoid cb_initialize (fclaw2d_domain_t *domain,\n fclaw2d_patch_t *this_patch,\n int this_block_idx,\n int this_patch_idx,\n void *user)\n{\n fclaw2d_vtable_t vt;\n fclaw2d_build_mode_t build_mode = FCLAW2D_BUILD_FOR_UPDATE;\n\n fclaw2d_patch_data_new(domain,this_patch);\n fclaw2d_clawpatch_build(domain,this_patch,\n this_block_idx,\n this_patch_idx,\n (void*) &build_mode);\n\n vt = fclaw2d_get_vtable(domain);\n FCLAW_ASSERT(vt.patch_initialize != NULL);\n vt.patch_initialize(domain,this_patch,this_block_idx,this_patch_idx);\n}\n\n\n\n\/* -----------------------------------------------------------------\n Public interface\n ----------------------------------------------------------------- *\/\n\nvoid fclaw2d_initialize (fclaw2d_domain_t **domain)\n{\n int time_interp = 0;\n char basename[BUFSIZ];\n const fclaw2d_vtable_t vt = fclaw2d_get_vtable(*domain);\n const amr_options_t *gparms = get_domain_parms(*domain);\n\n fclaw2d_domain_data_t* ddata = fclaw2d_domain_get_data(*domain);\n\n \/* This mapping context is needed by fortran mapping functions *\/\n fclaw2d_map_context_t *cont = fclaw2d_domain_get_map_context(*domain);\n SET_CONTEXT(&cont);\n\n int maxthreads = 0;\n#if defined(_OPENMP)\n maxthreads = omp_get_max_threads();\n#endif\n fclaw_global_essentialf(\"Max threads set to %d\\n\",maxthreads);\n\n int minlevel = gparms->minlevel;\n int maxlevel = gparms->maxlevel;\n\n \/* Initialize all timers *\/\n ddata->is_latest_domain = 1;\n for (int i = 0; i < FCLAW2D_TIMER_COUNT; ++i) {\n fclaw2d_timer_init (&ddata->timers[i]);\n }\n\n \/* start timing *\/\n fclaw2d_domain_barrier (*domain);\n fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_WALLTIME]);\n fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_INIT]);\n\n \/* User defined problem setup *\/\n if (vt.problem_setup != NULL)\n {\n vt.problem_setup(*domain);\n }\n\n \/* set specific refinement strategy *\/\n fclaw2d_domain_set_refinement\n (*domain, gparms->smooth_refine, gparms->smooth_refine_level,\n gparms->coarsen_delay);\n\n\n \/* ------------------------------------------------\n Set up initial domain.\n\n This needs to be set as if it were going to be used\n for updating.\n ------------------------------------------------ *\/\n\n \/* Get an initial domain *\/\n fclaw2d_domain_setup(NULL,*domain);\n\n \/* Initialize patches on uniformly refined level minlevel *\/\n fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_REGRID_BUILD]);\n fclaw2d_domain_iterate_level(*domain, minlevel, cb_initialize,\n (void *) NULL);\n fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_REGRID_BUILD]);\n\n \/* Set up ghost patches *\/\n fclaw2d_exchange_setup(*domain,FCLAW2D_TIMER_INIT);\n\n \/* This is normally called from regrid *\/\n fclaw2d_regrid_set_neighbor_types(*domain);\n\n \/* We need a user option here to set ghost values after initialization *\/\n if (gparms->init_ghostcell){\n fclaw2d_ghost_update(*domain,minlevel,maxlevel,0.0,time_interp,FCLAW2D_TIMER_INIT);\n fclaw2d_physical_set_bc(*domain,minlevel,0.0,time_interp);\n }\n\n \/\/ VTK output during amrinit\n if (gparms->vtkout & 1) {\n \/\/ into timer\n fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_INIT]);\n fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_OUTPUT]);\n\n \/\/ output\n snprintf (basename, BUFSIZ, \"%s_init_level_%02d\",\n gparms->prefix, minlevel);\n fclaw2d_output_write_vtk (*domain, basename);\n\n \/\/ out of timer\n fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_OUTPUT]);\n fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_INIT]);\n }\n \/* ------------------------------------------------\n Done with initial setup.\n ------------------------------------------------ *\/\n\n\n \/* ------------------------------------------------\n Build up an initial refinement.\n ------------------------------------------------ *\/\n if (minlevel < maxlevel)\n {\n int domain_init = 1;\n for (int level = minlevel; level < maxlevel; level++)\n {\n fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_REGRID_TAGGING]);\n fclaw2d_domain_iterate_level(*domain, level,\n cb_fclaw2d_regrid_tag4refinement,\n (void *) &domain_init);\n fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_REGRID_TAGGING]);\n\n \/\/ Construct new domain based on tagged patches.\n fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_INIT]);\n fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_ADAPT_COMM]);\n fclaw2d_domain_t *new_domain = fclaw2d_domain_adapt(*domain);\n\n int have_new_refinement = new_domain != NULL;\n\n if (have_new_refinement)\n {\n \/* Have to get a new ddata *\/\n fclaw2d_domain_setup(*domain,new_domain);\n ddata = fclaw2d_domain_get_data(new_domain);\n }\n\n fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_ADAPT_COMM]);\n fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_INIT]);\n\n if (have_new_refinement)\n {\n fclaw_global_infof(\" -- Have new initial refinement\\n\");\n\n \/* Re-initialize new grids. Ghost cell values needed for\n interpolation have already been set by initialization *\/\n fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_REGRID_BUILD]);\n fclaw2d_domain_iterate_adapted(*domain, new_domain,\n cb_fclaw2d_regrid_repopulate,\n (void *) &domain_init);\n\n fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_REGRID_BUILD]);\n\n \/\/ free all memory associated with old domain\n fclaw2d_domain_reset(domain);\n *domain = new_domain;\n new_domain = NULL;\n\n \/\/ VTK output during amrinit\n if (gparms->vtkout & 1) {\n \/\/ into timer\n ddata = fclaw2d_domain_get_data (*domain);\n fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_INIT]);\n fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_OUTPUT]);\n\n \/\/ output\n snprintf (basename, BUFSIZ, \"%s_init_level_%02d_adapt\",\n gparms->prefix, level);\n fclaw2d_output_write_vtk (*domain, basename);\n\n \/* out of timer *\/\n fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_OUTPUT]);\n fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_INIT]);\n ddata = NULL;\n }\n\n \/* Repartition domain to new processors. Second arg is the\n mode for VTK output *\/\n fclaw2d_partition_domain(domain,level,FCLAW2D_TIMER_INIT);\n\n \/* Need a new timer *\/\n ddata = fclaw2d_domain_get_data(*domain);\n\n \/* Set up ghost patches. This probably doesn't need to be done\n each time we add a new level. *\/\n fclaw2d_exchange_setup(*domain,FCLAW2D_TIMER_INIT);\n\n \/* This is normally called from regrid, once the initial domain\n has been set up *\/\n fclaw2d_regrid_set_neighbor_types(*domain);\n\n\/\/ #if 0\n \/* We only need to update the physical ghost cells because we\n assume the initialization procedure handles all internal\n boundaries. *\/\n int new_level = level + 1;\n\n \/* Add 2016\/07\/26, need to update ghost cell value here. If \n didn't and there is a refinement, the refined grids' ghost\n cells will not be initialized *\/\n if (gparms->init_ghostcell){\n fclaw2d_ghost_update(*domain,minlevel,maxlevel,0.0,time_interp,FCLAW2D_TIMER_INIT);\n fclaw2d_physical_set_bc(*domain,new_level,0.0,time_interp);\n }\n \/\/ fclaw2d_physical_set_bc(*domain,new_level,time_interp);\n\/\/ #endif\n }\n else\n {\n \/* We don't have a new refinement, and so can break out of level loop *\/\n break;\n }\n } \/* Level loop (minlevel --> maxlevel) *\/\n }\n\n \/* Print global minimum and maximum levels *\/\n fclaw_global_infof(\"Global minlevel %d maxlevel %d\\n\",\n (*domain)->global_minlevel, (*domain)->global_maxlevel);\n\n \/* Stop timer *\/\n ddata = fclaw2d_domain_get_data(*domain);\n fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_INIT]);\n}\n\n#ifdef __cplusplus\n#if 0\n{\n#endif\n}\n#endif\n(geoclaw\/fillghostcell) change fclaw2d_physical_set_bc place\/*\nCopyright (c) 2012 Carsten Burstedde, Donna Calhoun\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation\nand\/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#if defined(_OPENMP)\n#include \n#endif\n\n#ifdef __cplusplus\nextern \"C\"\n{\n#if 0\n}\n#endif\n#endif\n\n\n\/* -----------------------------------------------------------------\n Initial grid\n ----------------------------------------------------------------- *\/\nstatic\nvoid cb_initialize (fclaw2d_domain_t *domain,\n fclaw2d_patch_t *this_patch,\n int this_block_idx,\n int this_patch_idx,\n void *user)\n{\n fclaw2d_vtable_t vt;\n fclaw2d_build_mode_t build_mode = FCLAW2D_BUILD_FOR_UPDATE;\n\n fclaw2d_patch_data_new(domain,this_patch);\n fclaw2d_clawpatch_build(domain,this_patch,\n this_block_idx,\n this_patch_idx,\n (void*) &build_mode);\n\n vt = fclaw2d_get_vtable(domain);\n FCLAW_ASSERT(vt.patch_initialize != NULL);\n vt.patch_initialize(domain,this_patch,this_block_idx,this_patch_idx);\n}\n\n\n\n\/* -----------------------------------------------------------------\n Public interface\n ----------------------------------------------------------------- *\/\n\nvoid fclaw2d_initialize (fclaw2d_domain_t **domain)\n{\n int time_interp = 0;\n char basename[BUFSIZ];\n const fclaw2d_vtable_t vt = fclaw2d_get_vtable(*domain);\n const amr_options_t *gparms = get_domain_parms(*domain);\n\n fclaw2d_domain_data_t* ddata = fclaw2d_domain_get_data(*domain);\n\n \/* This mapping context is needed by fortran mapping functions *\/\n fclaw2d_map_context_t *cont = fclaw2d_domain_get_map_context(*domain);\n SET_CONTEXT(&cont);\n\n int maxthreads = 0;\n#if defined(_OPENMP)\n maxthreads = omp_get_max_threads();\n#endif\n fclaw_global_essentialf(\"Max threads set to %d\\n\",maxthreads);\n\n int minlevel = gparms->minlevel;\n int maxlevel = gparms->maxlevel;\n\n \/* Initialize all timers *\/\n ddata->is_latest_domain = 1;\n for (int i = 0; i < FCLAW2D_TIMER_COUNT; ++i) {\n fclaw2d_timer_init (&ddata->timers[i]);\n }\n\n \/* start timing *\/\n fclaw2d_domain_barrier (*domain);\n fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_WALLTIME]);\n fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_INIT]);\n\n \/* User defined problem setup *\/\n if (vt.problem_setup != NULL)\n {\n vt.problem_setup(*domain);\n }\n\n \/* set specific refinement strategy *\/\n fclaw2d_domain_set_refinement\n (*domain, gparms->smooth_refine, gparms->smooth_refine_level,\n gparms->coarsen_delay);\n\n\n \/* ------------------------------------------------\n Set up initial domain.\n\n This needs to be set as if it were going to be used\n for updating.\n ------------------------------------------------ *\/\n\n \/* Get an initial domain *\/\n fclaw2d_domain_setup(NULL,*domain);\n\n \/* Initialize patches on uniformly refined level minlevel *\/\n fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_REGRID_BUILD]);\n fclaw2d_domain_iterate_level(*domain, minlevel, cb_initialize,\n (void *) NULL);\n fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_REGRID_BUILD]);\n\n \/* Set up ghost patches *\/\n fclaw2d_exchange_setup(*domain,FCLAW2D_TIMER_INIT);\n\n \/* This is normally called from regrid *\/\n fclaw2d_regrid_set_neighbor_types(*domain);\n\n \/* We need a user option here to set ghost values after initialization *\/\n if (gparms->init_ghostcell){\n fclaw2d_ghost_update(*domain,minlevel,maxlevel,0.0,time_interp,FCLAW2D_TIMER_INIT);\n }\n fclaw2d_physical_set_bc(*domain,minlevel,0.0,time_interp);\n\n \/\/ VTK output during amrinit\n if (gparms->vtkout & 1) {\n \/\/ into timer\n fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_INIT]);\n fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_OUTPUT]);\n\n \/\/ output\n snprintf (basename, BUFSIZ, \"%s_init_level_%02d\",\n gparms->prefix, minlevel);\n fclaw2d_output_write_vtk (*domain, basename);\n\n \/\/ out of timer\n fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_OUTPUT]);\n fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_INIT]);\n }\n \/* ------------------------------------------------\n Done with initial setup.\n ------------------------------------------------ *\/\n\n\n \/* ------------------------------------------------\n Build up an initial refinement.\n ------------------------------------------------ *\/\n if (minlevel < maxlevel)\n {\n int domain_init = 1;\n for (int level = minlevel; level < maxlevel; level++)\n {\n fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_REGRID_TAGGING]);\n fclaw2d_domain_iterate_level(*domain, level,\n cb_fclaw2d_regrid_tag4refinement,\n (void *) &domain_init);\n fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_REGRID_TAGGING]);\n\n \/\/ Construct new domain based on tagged patches.\n fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_INIT]);\n fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_ADAPT_COMM]);\n fclaw2d_domain_t *new_domain = fclaw2d_domain_adapt(*domain);\n\n int have_new_refinement = new_domain != NULL;\n\n if (have_new_refinement)\n {\n \/* Have to get a new ddata *\/\n fclaw2d_domain_setup(*domain,new_domain);\n ddata = fclaw2d_domain_get_data(new_domain);\n }\n\n fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_ADAPT_COMM]);\n fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_INIT]);\n\n if (have_new_refinement)\n {\n fclaw_global_infof(\" -- Have new initial refinement\\n\");\n\n \/* Re-initialize new grids. Ghost cell values needed for\n interpolation have already been set by initialization *\/\n fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_REGRID_BUILD]);\n fclaw2d_domain_iterate_adapted(*domain, new_domain,\n cb_fclaw2d_regrid_repopulate,\n (void *) &domain_init);\n\n fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_REGRID_BUILD]);\n\n \/\/ free all memory associated with old domain\n fclaw2d_domain_reset(domain);\n *domain = new_domain;\n new_domain = NULL;\n\n \/\/ VTK output during amrinit\n if (gparms->vtkout & 1) {\n \/\/ into timer\n ddata = fclaw2d_domain_get_data (*domain);\n fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_INIT]);\n fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_OUTPUT]);\n\n \/\/ output\n snprintf (basename, BUFSIZ, \"%s_init_level_%02d_adapt\",\n gparms->prefix, level);\n fclaw2d_output_write_vtk (*domain, basename);\n\n \/* out of timer *\/\n fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_OUTPUT]);\n fclaw2d_timer_start (&ddata->timers[FCLAW2D_TIMER_INIT]);\n ddata = NULL;\n }\n\n \/* Repartition domain to new processors. Second arg is the\n mode for VTK output *\/\n fclaw2d_partition_domain(domain,level,FCLAW2D_TIMER_INIT);\n\n \/* Need a new timer *\/\n ddata = fclaw2d_domain_get_data(*domain);\n\n \/* Set up ghost patches. This probably doesn't need to be done\n each time we add a new level. *\/\n fclaw2d_exchange_setup(*domain,FCLAW2D_TIMER_INIT);\n\n \/* This is normally called from regrid, once the initial domain\n has been set up *\/\n fclaw2d_regrid_set_neighbor_types(*domain);\n\n\/\/ #if 0\n \/* We only need to update the physical ghost cells because we\n assume the initialization procedure handles all internal\n boundaries. *\/\n int new_level = level + 1;\n\n \/* Add 2016\/07\/26, need here???*\/\n if (gparms->init_ghostcell){\n fclaw2d_ghost_update(*domain,minlevel,new_level,0.0,time_interp,FCLAW2D_TIMER_INIT);\n }\n fclaw2d_physical_set_bc(*domain,new_level,0.0,time_interp);\n \/\/ fclaw2d_physical_set_bc(*domain,new_level,time_interp);\n\/\/ #endif\n }\n else\n {\n \/* We don't have a new refinement, and so can break out of level loop *\/\n break;\n }\n } \/* Level loop (minlevel --> maxlevel) *\/\n }\n\n \/* Print global minimum and maximum levels *\/\n fclaw_global_infof(\"Global minlevel %d maxlevel %d\\n\",\n (*domain)->global_minlevel, (*domain)->global_maxlevel);\n\n \/* Stop timer *\/\n ddata = fclaw2d_domain_get_data(*domain);\n fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_INIT]);\n}\n\n#ifdef __cplusplus\n#if 0\n{\n#endif\n}\n#endif\n<|endoftext|>"} {"text":"\/* bzflag\n * Copyright (c) 1993 - 2005 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/\/ class interface header\n#include \"cURLManager.h\"\n\n\/\/ common implementation headers\n#include \"bzfio.h\"\n\nbool cURLManager::inited = false;\nCURLM *cURLManager::multiHandle = NULL;\nstd::map cURLManager::cURLMap;\n\ncURLManager::cURLManager()\n{\n CURLcode result;\n\n theData = NULL;\n theLen = 0;\n errorCode = CURLE_OK;\n added = false;\n\n if (!inited)\n setup();\n\n easyHandle = curl_easy_init();\n if (!easyHandle) {\n DEBUG1(\"Something wrong with CURL\\n\");\n return;\n }\n#if LIBCURL_VERSION_NUM >= 0x070a00\n result = curl_easy_setopt(easyHandle, CURLOPT_NOSIGNAL, true);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_NOSIGNAL error: %d\\n\", result);\n }\n#endif\n\n result = curl_easy_setopt(easyHandle, CURLOPT_WRITEFUNCTION,\n\t\t\t cURLManager::writeFunction);\n if (result != CURLE_OK)\n DEBUG1(\"CURLOPT_WRITEFUNCTION error: %d\\n\", result);\n\n result = curl_easy_setopt(easyHandle, CURLOPT_WRITEDATA, this);\n if (result != CURLE_OK)\n DEBUG1(\"CURLOPT_FILE error: %d\\n\", result);\n\n}\n\ncURLManager::~cURLManager()\n{\n if (added)\n removeHandle();\n curl_easy_cleanup(easyHandle);\n free(theData);\n}\n\nvoid cURLManager::setup()\n{\n CURLcode result;\n\n DEBUG1(\"LIBCURL: %s\\n\", curl_version());\n#if LIBCURL_VERSION_NUM >= 0x070a00\n if ((result = curl_global_init(CURL_GLOBAL_NOTHING)))\n DEBUG1(\"Unexpected error from libcurl; Error: %d\\n\", result);\n#endif\n multiHandle = curl_multi_init();\n if (!multiHandle)\n DEBUG1(\"Unexpected error creating multi handle from libcurl \\n\");\n inited = true;\n}\n\nsize_t cURLManager::writeFunction(void *ptr, size_t size, size_t nmemb,\n\t\t\t\t void *stream)\n{\n int len = size * nmemb;\n ((cURLManager*)stream)->collectData((char*)ptr, len);\n return len;\n}\n\nvoid cURLManager::setTimeout(long timeout)\n{\n CURLcode result;\n\n result = curl_easy_setopt(easyHandle, CURLOPT_TIMEOUT, timeout);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_TIMEOUT error: %d\\n\", result);\n }\n}\n\nvoid cURLManager::setNoBody()\n{\n CURLcode result;\n long nobody = 1;\n\n result = curl_easy_setopt(easyHandle, CURLOPT_NOBODY, nobody);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_NOBODY error: %d\\n\", result);\n }\n}\n\nvoid cURLManager::setGetMode()\n{\n CURLcode result;\n long get = 1;\n\n result = curl_easy_setopt(easyHandle, CURLOPT_HTTPGET, get);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_GET error: %d\\n\", result);\n }\n}\n\nvoid cURLManager::setURL(std::string url)\n{\n CURLcode result;\n\n if (url == \"\")\n result = curl_easy_setopt(easyHandle, CURLOPT_URL, NULL);\n else\n result = curl_easy_setopt(easyHandle, CURLOPT_URL, url.c_str());\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_URL error: %d\\n\", result);\n }\n}\n\nvoid cURLManager::setProgressFunction(curl_progress_callback func, void* data)\n{\n CURLcode result;\n if (func != NULL) {\n result = curl_easy_setopt(easyHandle, CURLOPT_PROGRESSFUNCTION, func);\n if (result == CURLE_OK)\n result = curl_easy_setopt(easyHandle, CURLOPT_PROGRESSDATA, data);\n if (result == CURLE_OK)\n result = curl_easy_setopt(easyHandle, CURLOPT_NOPROGRESS, 0);\n } else {\n result = curl_easy_setopt(easyHandle, CURLOPT_NOPROGRESS, 1);\n }\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_SET_PROGRESS error: %d\\n\", result);\n }\n}\n\nvoid cURLManager::setRequestFileTime(bool request)\n{\n CURLcode result;\n long requestFileTime = request ? 1 : 0;\n result = curl_easy_setopt(easyHandle, CURLOPT_FILETIME, requestFileTime);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_FILETIME error: %d\\n\", result);\n }\n}\n\nvoid cURLManager::addHandle()\n{\n CURLMcode result = curl_multi_add_handle(multiHandle, easyHandle);\n if (result != CURLM_OK)\n DEBUG1(\"Unexpected error from libcurl; Error: %d\\n\", result);\n cURLMap[easyHandle] = this;\n added = true;\n}\n\nvoid cURLManager::removeHandle()\n{\n if (!added)\n return;\n cURLMap.erase(easyHandle);\n CURLMcode result = curl_multi_remove_handle(multiHandle, easyHandle);\n if (result != CURLM_OK)\n DEBUG1(\"Unexpected error from libcurl; Error: %d\\n\", result);\n added = false;\n}\n\nvoid cURLManager::finalization(char *, unsigned int, bool)\n{\n}\n\nvoid cURLManager::collectData(char* ptr, int len)\n{\n unsigned char *newData = (unsigned char *)realloc(theData, theLen + len);\n if (!newData) {\n DEBUG1(\"memory exhausted\\n\");\n } else {\n memcpy(newData + theLen, ptr, len);\n theLen += len;\n theData = newData;\n }\n}\n\nint cURLManager::perform()\n{\n if (!inited)\n setup();\n\n int activeTransfers = 0;\n CURLMcode result;\n while (true) {\n result = curl_multi_perform(multiHandle, &activeTransfers);\n if (result != CURLM_CALL_MULTI_PERFORM)\n break;\n }\n if (result != CURLM_OK)\n DEBUG1(\"Unexpected error from libcurl; Error: %d\\n\", result);\n\n int msgs_in_queue;\n CURLMsg *pendingMsg;\n CURL *easy;\n\n\n while (true) {\n pendingMsg = curl_multi_info_read(multiHandle, &msgs_in_queue);\n if (!pendingMsg)\n break;\n\n easy = pendingMsg->easy_handle;\n\n cURLMap[easy]->infoComplete(pendingMsg->data.result);\n\n if (msgs_in_queue <= 0)\n break;\n }\n\n return activeTransfers;\n}\n\nvoid cURLManager::infoComplete(CURLcode result)\n{\n if (result != CURLE_OK)\n DEBUG1(\"Unexpected error from libcurl; Error: %d\\n\", result);\n finalization((char *)theData, theLen, result == CURLE_OK);\n free(theData);\n removeHandle();\n theData = NULL;\n theLen = 0;\n}\n\nbool cURLManager::getFileTime(time_t &t)\n{\n long filetime;\n CURLcode result;\n result = curl_easy_getinfo(easyHandle, CURLINFO_FILETIME, &filetime);\n if (result) {\n DEBUG1(\"CURLINFO_FILETIME error: %d\\n\", result);\n return false;\n }\n t = (time_t)filetime;\n return true;\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\nDifferent diagnostic for each point of error\/* bzflag\n * Copyright (c) 1993 - 2005 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/\/ class interface header\n#include \"cURLManager.h\"\n\n\/\/ common implementation headers\n#include \"bzfio.h\"\n\nbool cURLManager::inited = false;\nCURLM *cURLManager::multiHandle = NULL;\nstd::map cURLManager::cURLMap;\n\ncURLManager::cURLManager()\n{\n CURLcode result;\n\n theData = NULL;\n theLen = 0;\n errorCode = CURLE_OK;\n added = false;\n\n if (!inited)\n setup();\n\n easyHandle = curl_easy_init();\n if (!easyHandle) {\n DEBUG1(\"Something wrong with CURL\\n\");\n return;\n }\n#if LIBCURL_VERSION_NUM >= 0x070a00\n result = curl_easy_setopt(easyHandle, CURLOPT_NOSIGNAL, true);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_NOSIGNAL error: %d\\n\", result);\n }\n#endif\n\n result = curl_easy_setopt(easyHandle, CURLOPT_WRITEFUNCTION,\n\t\t\t cURLManager::writeFunction);\n if (result != CURLE_OK)\n DEBUG1(\"CURLOPT_WRITEFUNCTION error: %d\\n\", result);\n\n result = curl_easy_setopt(easyHandle, CURLOPT_WRITEDATA, this);\n if (result != CURLE_OK)\n DEBUG1(\"CURLOPT_WRITEDATA error: %d\\n\", result);\n\n}\n\ncURLManager::~cURLManager()\n{\n if (added)\n removeHandle();\n curl_easy_cleanup(easyHandle);\n free(theData);\n}\n\nvoid cURLManager::setup()\n{\n CURLcode result;\n\n DEBUG1(\"LIBCURL: %s\\n\", curl_version());\n#if LIBCURL_VERSION_NUM >= 0x070a00\n if ((result = curl_global_init(CURL_GLOBAL_NOTHING)))\n DEBUG1(\"cURL Global init Error: %d\\n\", result);\n#endif\n multiHandle = curl_multi_init();\n if (!multiHandle)\n DEBUG1(\"Unexpected error creating multi handle from libcurl \\n\");\n inited = true;\n}\n\nsize_t cURLManager::writeFunction(void *ptr, size_t size, size_t nmemb,\n\t\t\t\t void *stream)\n{\n int len = size * nmemb;\n ((cURLManager*)stream)->collectData((char*)ptr, len);\n return len;\n}\n\nvoid cURLManager::setTimeout(long timeout)\n{\n CURLcode result;\n\n result = curl_easy_setopt(easyHandle, CURLOPT_TIMEOUT, timeout);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_TIMEOUT error: %d\\n\", result);\n }\n}\n\nvoid cURLManager::setNoBody()\n{\n CURLcode result;\n long nobody = 1;\n\n result = curl_easy_setopt(easyHandle, CURLOPT_NOBODY, nobody);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_NOBODY error: %d\\n\", result);\n }\n}\n\nvoid cURLManager::setGetMode()\n{\n CURLcode result;\n long get = 1;\n\n result = curl_easy_setopt(easyHandle, CURLOPT_HTTPGET, get);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_GET error: %d\\n\", result);\n }\n}\n\nvoid cURLManager::setURL(std::string url)\n{\n CURLcode result;\n\n if (url == \"\")\n result = curl_easy_setopt(easyHandle, CURLOPT_URL, NULL);\n else\n result = curl_easy_setopt(easyHandle, CURLOPT_URL, url.c_str());\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_URL error: %d\\n\", result);\n }\n}\n\nvoid cURLManager::setProgressFunction(curl_progress_callback func, void* data)\n{\n CURLcode result;\n if (func != NULL) {\n result = curl_easy_setopt(easyHandle, CURLOPT_PROGRESSFUNCTION, func);\n if (result == CURLE_OK)\n result = curl_easy_setopt(easyHandle, CURLOPT_PROGRESSDATA, data);\n if (result == CURLE_OK)\n result = curl_easy_setopt(easyHandle, CURLOPT_NOPROGRESS, 0);\n } else {\n result = curl_easy_setopt(easyHandle, CURLOPT_NOPROGRESS, 1);\n }\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_SET_PROGRESS error: %d\\n\", result);\n }\n}\n\nvoid cURLManager::setRequestFileTime(bool request)\n{\n CURLcode result;\n long requestFileTime = request ? 1 : 0;\n result = curl_easy_setopt(easyHandle, CURLOPT_FILETIME, requestFileTime);\n if (result != CURLE_OK) {\n errorCode = result;\n DEBUG1(\"CURLOPT_FILETIME error: %d\\n\", result);\n }\n}\n\nvoid cURLManager::addHandle()\n{\n CURLMcode result = curl_multi_add_handle(multiHandle, easyHandle);\n if (result != CURLM_OK)\n DEBUG1(\"Error while adding easy handle from libcurl; Error: %d\\n\", result);\n cURLMap[easyHandle] = this;\n added = true;\n}\n\nvoid cURLManager::removeHandle()\n{\n if (!added)\n return;\n cURLMap.erase(easyHandle);\n CURLMcode result = curl_multi_remove_handle(multiHandle, easyHandle);\n if (result != CURLM_OK)\n DEBUG1(\"Error while removing easy handle from libcurl; Error: %d\\n\", result);\n added = false;\n}\n\nvoid cURLManager::finalization(char *, unsigned int, bool)\n{\n}\n\nvoid cURLManager::collectData(char* ptr, int len)\n{\n unsigned char *newData = (unsigned char *)realloc(theData, theLen + len);\n if (!newData) {\n DEBUG1(\"memory exhausted\\n\");\n } else {\n memcpy(newData + theLen, ptr, len);\n theLen += len;\n theData = newData;\n }\n}\n\nint cURLManager::perform()\n{\n if (!inited)\n setup();\n\n int activeTransfers = 0;\n CURLMcode result;\n while (true) {\n result = curl_multi_perform(multiHandle, &activeTransfers);\n if (result != CURLM_CALL_MULTI_PERFORM)\n break;\n }\n if (result != CURLM_OK)\n DEBUG1(\"Error while doing multi_perform from libcurl; Error: %d\\n\", result);\n\n int msgs_in_queue;\n CURLMsg *pendingMsg;\n CURL *easy;\n\n\n while (true) {\n pendingMsg = curl_multi_info_read(multiHandle, &msgs_in_queue);\n if (!pendingMsg)\n break;\n\n easy = pendingMsg->easy_handle;\n\n cURLMap[easy]->infoComplete(pendingMsg->data.result);\n\n if (msgs_in_queue <= 0)\n break;\n }\n\n return activeTransfers;\n}\n\nvoid cURLManager::infoComplete(CURLcode result)\n{\n if (result != CURLE_OK)\n DEBUG1(\"File transfer terminated with error from libcurl; Error: %d\\n\", result);\n finalization((char *)theData, theLen, result == CURLE_OK);\n free(theData);\n removeHandle();\n theData = NULL;\n theLen = 0;\n}\n\nbool cURLManager::getFileTime(time_t &t)\n{\n long filetime;\n CURLcode result;\n result = curl_easy_getinfo(easyHandle, CURLINFO_FILETIME, &filetime);\n if (result) {\n DEBUG1(\"CURLINFO_FILETIME error: %d\\n\", result);\n return false;\n }\n t = (time_t)filetime;\n return true;\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"} {"text":"\/**\n * \\file vtkFbxHelper.cpp\n * 2012-04-24 LB Initial implementation\n *\n *\/\n\n\/\/ ** INCLUDES **\n#include \"VtkFbxHelper.h\"\n\n#include \n#include \n #include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nvoid replaceExt(string& s, const string& newExt)\n{\n string::size_type i = s.rfind('.', s.length());\n if (i != string::npos)\n s.replace(i + 1, newExt.length(), newExt);\n}\n\nstring getFileExt(const string& s)\n{\n size_t i = s.rfind('.', s.length());\n if (i != string::npos)\n return s.substr(i + 1, s.length() - i);\n return \"\";\n}\n\nstring getFilename(const string& s)\n{\n\tchar sep = '\/';\n#ifdef _WIN32\n\tsep = '\\\\';\n#endif\n\n\tsize_t i = s.rfind(sep, s.length());\n\tif (i != string::npos)\n\t\treturn (s.substr(i + 1, s.length() - 1));\n\n\treturn (\"\");\n}\n\nvtkActor* readVtkFile(const string& filename)\n{\n cout << \"Opening file \" << filename << \" ... \" << endl << flush;\n string fileExt = getFileExt(filename);\n\n vtkPolyDataMapper* mapper = vtkPolyDataMapper::New();\n vtkXMLDataReader* reader = NULL;\n vtkGenericDataObjectReader* oldStyleReader = NULL;\n if (fileExt.find(\"vti\") != string::npos)\n {\n reader = vtkXMLImageDataReader::New();\n reader->SetFileName(filename.c_str());\n reader->Update();\n vtkSmartPointer geoFilter =\n vtkSmartPointer::New();\n geoFilter->SetInputConnection(reader->GetOutputPort());\n mapper->SetInputConnection(geoFilter->GetOutputPort());\n }\n if (fileExt.find(\"vtr\") != string::npos)\n {\n reader = vtkXMLRectilinearGridReader::New();\n reader->SetFileName(filename.c_str());\n reader->Update();\n vtkSmartPointer geoFilter =\n vtkSmartPointer::New();\n geoFilter->SetInputConnection(reader->GetOutputPort());\n mapper->SetInputConnection(geoFilter->GetOutputPort());\n }\n else if (fileExt.find(\"vts\") != string::npos)\n {\n reader = vtkXMLStructuredGridReader::New();\n reader->SetFileName(filename.c_str());\n reader->Update();\n vtkSmartPointer geoFilter =\n vtkSmartPointer::New();\n geoFilter->SetInputConnection(reader->GetOutputPort());\n mapper->SetInputConnection(geoFilter->GetOutputPort());\n }\n else if (fileExt.find(\"vtp\") != string::npos)\n {\n reader = vtkXMLPolyDataReader::New();\n reader->SetFileName(filename.c_str());\n reader->Update();\n mapper->SetInputConnection(reader->GetOutputPort());\n }\n else if (fileExt.find(\"vtu\") != string::npos)\n {\n reader = vtkXMLUnstructuredGridReader::New();\n reader->SetFileName(filename.c_str());\n reader->Update();\n\n vtkSmartPointer geoFilter =\n vtkSmartPointer::New();\n geoFilter->MergingOff();\n geoFilter->SetInputConnection(reader->GetOutputPort());\n geoFilter->Update();\n\n if(!GetPointNormals(geoFilter->GetOutput()))\n {\n \/\/ Generate normals\n std::cout << \"Generating normals ...\" << std::endl;\n vtkSmartPointer normalGenerator =\n vtkSmartPointer::New();\n normalGenerator->SetInputConnection(geoFilter->GetOutputPort());\n normalGenerator->ComputePointNormalsOn();\n normalGenerator->ComputeCellNormalsOff();\n \/\/normalGenerator->Update();\n mapper->SetInputConnection(normalGenerator->GetOutputPort());\n }\n else\n mapper->SetInputConnection(geoFilter->GetOutputPort());\n }\n else if (fileExt.find(\"vtk\") != string::npos)\n {\n oldStyleReader = vtkGenericDataObjectReader::New();\n oldStyleReader->SetFileName(filename.c_str());\n oldStyleReader->Update();\n if(oldStyleReader->IsFilePolyData())\n mapper->SetInputConnection(oldStyleReader->GetOutputPort());\n else\n {\n vtkSmartPointer geoFilter =\n vtkSmartPointer::New();\n geoFilter->SetInputConnection(oldStyleReader->GetOutputPort());\n mapper->SetInputConnection(geoFilter->GetOutputPort());\n }\n }\n else\n {\n cout << \"Not a valid vtk file ending (vti, vtr, vts, vtp, vtu, vtk)\" <<\n endl;\n return NULL;\n }\n\n vtkActor* actor = vtkActor::New();\n mapper->Update();\n actor->SetMapper(mapper);\n\n if (reader)\n reader->Delete();\n if (oldStyleReader)\n oldStyleReader->Delete();\n\n return actor;\n}\n\nvoid TestPointNormals(vtkPolyData* polydata)\n{\n std::cout << \"In TestPointNormals: \" << polydata->GetNumberOfPoints() << std::endl;\n \/\/ Try to read normals directly\n bool hasPointNormals = GetPointNormals(polydata);\n \n if(!hasPointNormals)\n {\n std::cout << \"No point normals were found. Computing normals...\" << std::endl;\n \n \/\/ Generate normals\n vtkSmartPointer normalGenerator = vtkSmartPointer::New();\n#if VTK_MAJOR_VERSION <= 5\n normalGenerator->SetInput(polydata);\n#else\n normalGenerator->SetInputData(polydata);\n#endif\n normalGenerator->ComputePointNormalsOn();\n normalGenerator->ComputeCellNormalsOff();\n normalGenerator->Update();\n \/*\n \/\/ Optional settings\n normalGenerator->SetFeatureAngle(0.1);\n normalGenerator->SetSplitting(1);\n normalGenerator->SetConsistency(0);\n normalGenerator->SetAutoOrientNormals(0);\n normalGenerator->SetComputePointNormals(1);\n normalGenerator->SetComputeCellNormals(0);\n normalGenerator->SetFlipNormals(0);\n normalGenerator->SetNonManifoldTraversal(1);\n *\/\n \n polydata = normalGenerator->GetOutput();\n \n \/\/ Try to read normals again\n hasPointNormals = GetPointNormals(polydata);\n \n std::cout << \"On the second try, has point normals? \" << hasPointNormals << std::endl;\n \n }\n else\n {\n std::cout << \"Point normals were found!\" << std::endl;\n }\n}\n \nvoid TestCellNormals(vtkPolyData* polydata)\n{\n \/\/ Try to read normals directly\n bool hasCellNormals = GetCellNormals(polydata);\n \n if(!hasCellNormals)\n {\n std::cout << \"No cell normals were found. Computing normals...\" << std::endl;\n \n \/\/ Generate normals\n vtkSmartPointer normalGenerator = vtkSmartPointer::New();\n#if VTK_MAJOR_VERSION <= 5\n normalGenerator->SetInput(polydata);\n#else\n normalGenerator->SetInputData(polydata);\n#endif\n normalGenerator->ComputePointNormalsOff();\n normalGenerator->ComputeCellNormalsOn();\n normalGenerator->Update();\n \/*\n \/\/ Optional settings\n normalGenerator->SetFeatureAngle(0.1);\n normalGenerator->SetSplitting(1);\n normalGenerator->SetConsistency(0);\n normalGenerator->SetAutoOrientNormals(0);\n normalGenerator->SetComputePointNormals(1);\n normalGenerator->SetComputeCellNormals(0);\n normalGenerator->SetFlipNormals(0);\n normalGenerator->SetNonManifoldTraversal(1);\n *\/\n \n polydata = normalGenerator->GetOutput();\n \n \/\/ Try to read normals again\n hasCellNormals = GetCellNormals(polydata);\n \n std::cout << \"On the second try, has cell normals? \" << hasCellNormals << std::endl;\n \n }\n else\n {\n std::cout << \"Cell normals were found!\" << std::endl;\n }\n}\n \n \n \nbool GetPointNormals(vtkPolyData* polydata)\n{\n std::cout << \"In GetPointNormals: \" << polydata->GetNumberOfPoints() << std::endl;\n std::cout << \"Looking for point normals...\" << std::endl;\n \n \/\/ Count points\n vtkIdType numPoints = polydata->GetNumberOfPoints();\n std::cout << \"There are \" << numPoints << \" points.\" << std::endl;\n \n \/\/ Count triangles\n vtkIdType numPolys = polydata->GetNumberOfPolys();\n std::cout << \"There are \" << numPolys << \" polys.\" << std::endl;\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Double normals in an array\n vtkDoubleArray* normalDataDouble =\n vtkDoubleArray::SafeDownCast(polydata->GetPointData()->GetArray(\"Normals\"));\n \n if(normalDataDouble)\n {\n int nc = normalDataDouble->GetNumberOfTuples();\n std::cout << \"There are \" << nc\n << \" components in normalDataDouble\" << std::endl;\n return true;\n }\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Double normals in an array\n vtkFloatArray* normalDataFloat =\n vtkFloatArray::SafeDownCast(polydata->GetPointData()->GetArray(\"Normals\"));\n \n if(normalDataFloat)\n {\n int nc = normalDataFloat->GetNumberOfTuples();\n std::cout << \"There are \" << nc\n << \" components in normalDataFloat\" << std::endl;\n return true;\n }\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Point normals\n vtkDoubleArray* normalsDouble =\n vtkDoubleArray::SafeDownCast(polydata->GetPointData()->GetNormals());\n \n if(normalsDouble)\n {\n std::cout << \"There are \" << normalsDouble->GetNumberOfComponents()\n << \" components in normalsDouble\" << std::endl;\n return true;\n }\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Point normals\n vtkFloatArray* normalsFloat =\n vtkFloatArray::SafeDownCast(polydata->GetPointData()->GetNormals());\n \n if(normalsFloat)\n {\n std::cout << \"There are \" << normalsFloat->GetNumberOfComponents()\n << \" components in normalsFloat\" << std::endl;\n return true;\n }\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Generic type point normals\n vtkDataArray* normalsGeneric = polydata->GetPointData()->GetNormals(); \/\/works\n if(normalsGeneric)\n {\n std::cout << \"There are \" << normalsGeneric->GetNumberOfTuples()\n << \" normals in normalsGeneric\" << std::endl;\n \n double testDouble[3];\n normalsGeneric->GetTuple(0, testDouble);\n \n std::cout << \"Double: \" << testDouble[0] << \" \"\n << testDouble[1] << \" \" << testDouble[2] << std::endl;\n \n \/\/ Can't do this:\n \/*\n float testFloat[3];\n normalsGeneric->GetTuple(0, testFloat);\n \n std::cout << \"Float: \" << testFloat[0] << \" \"\n << testFloat[1] << \" \" << testFloat[2] << std::endl;\n *\/\n return true;\n }\n \n \n \/\/ If the function has not yet quit, there were none of these types of normals\n std::cout << \"Normals not found!\" << std::endl;\n return false;\n \n}\n \n \nbool GetCellNormals(vtkPolyData* polydata)\n{\n std::cout << \"Looking for cell normals...\" << std::endl;\n \n \/\/ Count points\n vtkIdType numCells = polydata->GetNumberOfCells();\n std::cout << \"There are \" << numCells << \" cells.\" << std::endl;\n \n \/\/ Count triangles\n vtkIdType numPolys = polydata->GetNumberOfPolys();\n std::cout << \"There are \" << numPolys << \" polys.\" << std::endl;\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Double normals in an array\n vtkDoubleArray* normalDataDouble =\n vtkDoubleArray::SafeDownCast(polydata->GetCellData()->GetArray(\"Normals\"));\n \n if(normalDataDouble)\n {\n int nc = normalDataDouble->GetNumberOfTuples();\n std::cout << \"There are \" << nc\n << \" components in normalDataDouble\" << std::endl;\n return true;\n }\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Double normals in an array\n vtkFloatArray* normalDataFloat =\n vtkFloatArray::SafeDownCast(polydata->GetCellData()->GetArray(\"Normals\"));\n \n if(normalDataFloat)\n {\n int nc = normalDataFloat->GetNumberOfTuples();\n std::cout << \"There are \" << nc\n << \" components in normalDataFloat\" << std::endl;\n return true;\n }\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Point normals\n vtkDoubleArray* normalsDouble =\n vtkDoubleArray::SafeDownCast(polydata->GetCellData()->GetNormals());\n \n if(normalsDouble)\n {\n std::cout << \"There are \" << normalsDouble->GetNumberOfComponents()\n << \" components in normalsDouble\" << std::endl;\n return true;\n }\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Point normals\n vtkFloatArray* normalsFloat =\n vtkFloatArray::SafeDownCast(polydata->GetCellData()->GetNormals());\n \n if(normalsFloat)\n {\n std::cout << \"There are \" << normalsFloat->GetNumberOfComponents()\n << \" components in normalsFloat\" << std::endl;\n return true;\n }\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Generic type point normals\n vtkDataArray* normalsGeneric = polydata->GetCellData()->GetNormals(); \/\/works\n if(normalsGeneric)\n {\n std::cout << \"There are \" << normalsGeneric->GetNumberOfTuples()\n << \" normals in normalsGeneric\" << std::endl;\n \n double testDouble[3];\n normalsGeneric->GetTuple(0, testDouble);\n \n std::cout << \"Double: \" << testDouble[0] << \" \"\n << testDouble[1] << \" \" << testDouble[2] << std::endl;\n \n \/\/ Can't do this:\n \/*\n float testFloat[3];\n normalsGeneric->GetTuple(0, testFloat);\n \n std::cout << \"Float: \" << testFloat[0] << \" \"\n << testFloat[1] << \" \" << testFloat[2] << std::endl;\n *\/\n return true;\n }\n \n \n \/\/ If the function has not yet quit, there were none of these types of normals\n std::cout << \"Normals not found!\" << std::endl;\n return false;\n \n}\nNormals must be flipped?\/**\n * \\file vtkFbxHelper.cpp\n * 2012-04-24 LB Initial implementation\n *\n *\/\n\n\/\/ ** INCLUDES **\n#include \"VtkFbxHelper.h\"\n\n#include \n#include \n #include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nvoid replaceExt(string& s, const string& newExt)\n{\n string::size_type i = s.rfind('.', s.length());\n if (i != string::npos)\n s.replace(i + 1, newExt.length(), newExt);\n}\n\nstring getFileExt(const string& s)\n{\n size_t i = s.rfind('.', s.length());\n if (i != string::npos)\n return s.substr(i + 1, s.length() - i);\n return \"\";\n}\n\nstring getFilename(const string& s)\n{\n\tchar sep = '\/';\n#ifdef _WIN32\n\tsep = '\\\\';\n#endif\n\n\tsize_t i = s.rfind(sep, s.length());\n\tif (i != string::npos)\n\t\treturn (s.substr(i + 1, s.length() - 1));\n\n\treturn (\"\");\n}\n\nvtkActor* readVtkFile(const string& filename)\n{\n cout << \"Opening file \" << filename << \" ... \" << endl << flush;\n string fileExt = getFileExt(filename);\n\n vtkPolyDataMapper* mapper = vtkPolyDataMapper::New();\n vtkXMLDataReader* reader = NULL;\n vtkGenericDataObjectReader* oldStyleReader = NULL;\n if (fileExt.find(\"vti\") != string::npos)\n {\n reader = vtkXMLImageDataReader::New();\n reader->SetFileName(filename.c_str());\n reader->Update();\n vtkSmartPointer geoFilter =\n vtkSmartPointer::New();\n geoFilter->SetInputConnection(reader->GetOutputPort());\n mapper->SetInputConnection(geoFilter->GetOutputPort());\n }\n if (fileExt.find(\"vtr\") != string::npos)\n {\n reader = vtkXMLRectilinearGridReader::New();\n reader->SetFileName(filename.c_str());\n reader->Update();\n vtkSmartPointer geoFilter =\n vtkSmartPointer::New();\n geoFilter->SetInputConnection(reader->GetOutputPort());\n mapper->SetInputConnection(geoFilter->GetOutputPort());\n }\n else if (fileExt.find(\"vts\") != string::npos)\n {\n reader = vtkXMLStructuredGridReader::New();\n reader->SetFileName(filename.c_str());\n reader->Update();\n vtkSmartPointer geoFilter =\n vtkSmartPointer::New();\n geoFilter->SetInputConnection(reader->GetOutputPort());\n mapper->SetInputConnection(geoFilter->GetOutputPort());\n }\n else if (fileExt.find(\"vtp\") != string::npos)\n {\n reader = vtkXMLPolyDataReader::New();\n reader->SetFileName(filename.c_str());\n reader->Update();\n mapper->SetInputConnection(reader->GetOutputPort());\n }\n else if (fileExt.find(\"vtu\") != string::npos)\n {\n reader = vtkXMLUnstructuredGridReader::New();\n reader->SetFileName(filename.c_str());\n reader->Update();\n\n vtkSmartPointer geoFilter =\n vtkSmartPointer::New();\n geoFilter->MergingOff();\n geoFilter->SetInputConnection(reader->GetOutputPort());\n geoFilter->Update();\n\n if(!GetPointNormals(geoFilter->GetOutput()))\n {\n \/\/ Generate normals\n std::cout << \"Generating normals ...\" << std::endl;\n vtkSmartPointer normalGenerator =\n vtkSmartPointer::New();\n normalGenerator->SetInputConnection(geoFilter->GetOutputPort());\n normalGenerator->ComputePointNormalsOn();\n normalGenerator->ComputeCellNormalsOff();\n normalGenerator->FlipNormalsOn();\n \/\/normalGenerator->Update();\n mapper->SetInputConnection(normalGenerator->GetOutputPort());\n }\n else\n mapper->SetInputConnection(geoFilter->GetOutputPort());\n }\n else if (fileExt.find(\"vtk\") != string::npos)\n {\n oldStyleReader = vtkGenericDataObjectReader::New();\n oldStyleReader->SetFileName(filename.c_str());\n oldStyleReader->Update();\n if(oldStyleReader->IsFilePolyData())\n mapper->SetInputConnection(oldStyleReader->GetOutputPort());\n else\n {\n vtkSmartPointer geoFilter =\n vtkSmartPointer::New();\n geoFilter->SetInputConnection(oldStyleReader->GetOutputPort());\n mapper->SetInputConnection(geoFilter->GetOutputPort());\n }\n }\n else\n {\n cout << \"Not a valid vtk file ending (vti, vtr, vts, vtp, vtu, vtk)\" <<\n endl;\n return NULL;\n }\n\n vtkActor* actor = vtkActor::New();\n mapper->Update();\n actor->SetMapper(mapper);\n\n if (reader)\n reader->Delete();\n if (oldStyleReader)\n oldStyleReader->Delete();\n\n return actor;\n}\n\nvoid TestPointNormals(vtkPolyData* polydata)\n{\n std::cout << \"In TestPointNormals: \" << polydata->GetNumberOfPoints() << std::endl;\n \/\/ Try to read normals directly\n bool hasPointNormals = GetPointNormals(polydata);\n \n if(!hasPointNormals)\n {\n std::cout << \"No point normals were found. Computing normals...\" << std::endl;\n \n \/\/ Generate normals\n vtkSmartPointer normalGenerator = vtkSmartPointer::New();\n#if VTK_MAJOR_VERSION <= 5\n normalGenerator->SetInput(polydata);\n#else\n normalGenerator->SetInputData(polydata);\n#endif\n normalGenerator->ComputePointNormalsOn();\n normalGenerator->ComputeCellNormalsOff();\n normalGenerator->Update();\n \/*\n \/\/ Optional settings\n normalGenerator->SetFeatureAngle(0.1);\n normalGenerator->SetSplitting(1);\n normalGenerator->SetConsistency(0);\n normalGenerator->SetAutoOrientNormals(0);\n normalGenerator->SetComputePointNormals(1);\n normalGenerator->SetComputeCellNormals(0);\n normalGenerator->SetFlipNormals(0);\n normalGenerator->SetNonManifoldTraversal(1);\n *\/\n \n polydata = normalGenerator->GetOutput();\n \n \/\/ Try to read normals again\n hasPointNormals = GetPointNormals(polydata);\n \n std::cout << \"On the second try, has point normals? \" << hasPointNormals << std::endl;\n \n }\n else\n {\n std::cout << \"Point normals were found!\" << std::endl;\n }\n}\n \nvoid TestCellNormals(vtkPolyData* polydata)\n{\n \/\/ Try to read normals directly\n bool hasCellNormals = GetCellNormals(polydata);\n \n if(!hasCellNormals)\n {\n std::cout << \"No cell normals were found. Computing normals...\" << std::endl;\n \n \/\/ Generate normals\n vtkSmartPointer normalGenerator = vtkSmartPointer::New();\n#if VTK_MAJOR_VERSION <= 5\n normalGenerator->SetInput(polydata);\n#else\n normalGenerator->SetInputData(polydata);\n#endif\n normalGenerator->ComputePointNormalsOff();\n normalGenerator->ComputeCellNormalsOn();\n normalGenerator->Update();\n \/*\n \/\/ Optional settings\n normalGenerator->SetFeatureAngle(0.1);\n normalGenerator->SetSplitting(1);\n normalGenerator->SetConsistency(0);\n normalGenerator->SetAutoOrientNormals(0);\n normalGenerator->SetComputePointNormals(1);\n normalGenerator->SetComputeCellNormals(0);\n normalGenerator->SetFlipNormals(0);\n normalGenerator->SetNonManifoldTraversal(1);\n *\/\n \n polydata = normalGenerator->GetOutput();\n \n \/\/ Try to read normals again\n hasCellNormals = GetCellNormals(polydata);\n \n std::cout << \"On the second try, has cell normals? \" << hasCellNormals << std::endl;\n \n }\n else\n {\n std::cout << \"Cell normals were found!\" << std::endl;\n }\n}\n \n \n \nbool GetPointNormals(vtkPolyData* polydata)\n{\n std::cout << \"In GetPointNormals: \" << polydata->GetNumberOfPoints() << std::endl;\n std::cout << \"Looking for point normals...\" << std::endl;\n \n \/\/ Count points\n vtkIdType numPoints = polydata->GetNumberOfPoints();\n std::cout << \"There are \" << numPoints << \" points.\" << std::endl;\n \n \/\/ Count triangles\n vtkIdType numPolys = polydata->GetNumberOfPolys();\n std::cout << \"There are \" << numPolys << \" polys.\" << std::endl;\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Double normals in an array\n vtkDoubleArray* normalDataDouble =\n vtkDoubleArray::SafeDownCast(polydata->GetPointData()->GetArray(\"Normals\"));\n \n if(normalDataDouble)\n {\n int nc = normalDataDouble->GetNumberOfTuples();\n std::cout << \"There are \" << nc\n << \" components in normalDataDouble\" << std::endl;\n return true;\n }\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Double normals in an array\n vtkFloatArray* normalDataFloat =\n vtkFloatArray::SafeDownCast(polydata->GetPointData()->GetArray(\"Normals\"));\n \n if(normalDataFloat)\n {\n int nc = normalDataFloat->GetNumberOfTuples();\n std::cout << \"There are \" << nc\n << \" components in normalDataFloat\" << std::endl;\n return true;\n }\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Point normals\n vtkDoubleArray* normalsDouble =\n vtkDoubleArray::SafeDownCast(polydata->GetPointData()->GetNormals());\n \n if(normalsDouble)\n {\n std::cout << \"There are \" << normalsDouble->GetNumberOfComponents()\n << \" components in normalsDouble\" << std::endl;\n return true;\n }\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Point normals\n vtkFloatArray* normalsFloat =\n vtkFloatArray::SafeDownCast(polydata->GetPointData()->GetNormals());\n \n if(normalsFloat)\n {\n std::cout << \"There are \" << normalsFloat->GetNumberOfComponents()\n << \" components in normalsFloat\" << std::endl;\n return true;\n }\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Generic type point normals\n vtkDataArray* normalsGeneric = polydata->GetPointData()->GetNormals(); \/\/works\n if(normalsGeneric)\n {\n std::cout << \"There are \" << normalsGeneric->GetNumberOfTuples()\n << \" normals in normalsGeneric\" << std::endl;\n \n double testDouble[3];\n normalsGeneric->GetTuple(0, testDouble);\n \n std::cout << \"Double: \" << testDouble[0] << \" \"\n << testDouble[1] << \" \" << testDouble[2] << std::endl;\n \n \/\/ Can't do this:\n \/*\n float testFloat[3];\n normalsGeneric->GetTuple(0, testFloat);\n \n std::cout << \"Float: \" << testFloat[0] << \" \"\n << testFloat[1] << \" \" << testFloat[2] << std::endl;\n *\/\n return true;\n }\n \n \n \/\/ If the function has not yet quit, there were none of these types of normals\n std::cout << \"Normals not found!\" << std::endl;\n return false;\n \n}\n \n \nbool GetCellNormals(vtkPolyData* polydata)\n{\n std::cout << \"Looking for cell normals...\" << std::endl;\n \n \/\/ Count points\n vtkIdType numCells = polydata->GetNumberOfCells();\n std::cout << \"There are \" << numCells << \" cells.\" << std::endl;\n \n \/\/ Count triangles\n vtkIdType numPolys = polydata->GetNumberOfPolys();\n std::cout << \"There are \" << numPolys << \" polys.\" << std::endl;\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Double normals in an array\n vtkDoubleArray* normalDataDouble =\n vtkDoubleArray::SafeDownCast(polydata->GetCellData()->GetArray(\"Normals\"));\n \n if(normalDataDouble)\n {\n int nc = normalDataDouble->GetNumberOfTuples();\n std::cout << \"There are \" << nc\n << \" components in normalDataDouble\" << std::endl;\n return true;\n }\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Double normals in an array\n vtkFloatArray* normalDataFloat =\n vtkFloatArray::SafeDownCast(polydata->GetCellData()->GetArray(\"Normals\"));\n \n if(normalDataFloat)\n {\n int nc = normalDataFloat->GetNumberOfTuples();\n std::cout << \"There are \" << nc\n << \" components in normalDataFloat\" << std::endl;\n return true;\n }\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Point normals\n vtkDoubleArray* normalsDouble =\n vtkDoubleArray::SafeDownCast(polydata->GetCellData()->GetNormals());\n \n if(normalsDouble)\n {\n std::cout << \"There are \" << normalsDouble->GetNumberOfComponents()\n << \" components in normalsDouble\" << std::endl;\n return true;\n }\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Point normals\n vtkFloatArray* normalsFloat =\n vtkFloatArray::SafeDownCast(polydata->GetCellData()->GetNormals());\n \n if(normalsFloat)\n {\n std::cout << \"There are \" << normalsFloat->GetNumberOfComponents()\n << \" components in normalsFloat\" << std::endl;\n return true;\n }\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Generic type point normals\n vtkDataArray* normalsGeneric = polydata->GetCellData()->GetNormals(); \/\/works\n if(normalsGeneric)\n {\n std::cout << \"There are \" << normalsGeneric->GetNumberOfTuples()\n << \" normals in normalsGeneric\" << std::endl;\n \n double testDouble[3];\n normalsGeneric->GetTuple(0, testDouble);\n \n std::cout << \"Double: \" << testDouble[0] << \" \"\n << testDouble[1] << \" \" << testDouble[2] << std::endl;\n \n \/\/ Can't do this:\n \/*\n float testFloat[3];\n normalsGeneric->GetTuple(0, testFloat);\n \n std::cout << \"Float: \" << testFloat[0] << \" \"\n << testFloat[1] << \" \" << testFloat[2] << std::endl;\n *\/\n return true;\n }\n \n \n \/\/ If the function has not yet quit, there were none of these types of normals\n std::cout << \"Normals not found!\" << std::endl;\n return false;\n \n}\n<|endoftext|>"} {"text":"#include \"Players\/UCI_Mediator.h\"\n\n#include \n#include \n#include \n#include \n\n#include \"Players\/Player.h\"\n#include \"Game\/Board.h\"\n#include \"Game\/Clock.h\"\n#include \"Game\/Game_Result.h\"\n#include \"Moves\/Move.h\"\n\n#include \"Utility\/String.h\"\n\nUCI_Mediator::UCI_Mediator(const Player& player)\n{\n send_command(\"id name \" + player.name());\n send_command(\"id author \" + player.author());\n send_command(\"uciok\");\n}\n\nvoid UCI_Mediator::setup_turn(Board& board, Clock& clock)\n{\n while(true)\n {\n auto command = receive_uci_command(board, clock, false);\n if(command == \"ucinewgame\")\n {\n log(\"stopping thinking and clocks\");\n board.pick_move_now();\n clock.stop();\n }\n else if(String::starts_with(command, \"position \"))\n {\n auto parse = String::split(command);\n if(parse.at(1) == \"startpos\")\n {\n board = Board();\n }\n else if(parse.at(1) == \"fen\")\n {\n auto fen = std::accumulate(std::next(parse.begin(), 3), std::next(parse.begin(), 8),\n parse.at(2),\n [](const auto& so_far, const auto& next)\n {\n return so_far + \" \" + next;\n });\n board = Board(fen);\n }\n\n auto moves_iter = std::find(parse.begin(), parse.end(), \"moves\");\n if(moves_iter != parse.end())\n {\n std::for_each(std::next(moves_iter), parse.end(),\n [&board](const auto& move)\n {\n board.submit_move(board.create_move(move));\n });\n log(\"All moves applied\");\n }\n\n log(\"Board ready for play\");\n board.set_thinking_mode(UCI);\n }\n else if(String::starts_with(command, \"go\"))\n {\n if(board.whose_turn() == WHITE)\n {\n indent = \"\\t\\t\";\n }\n else\n {\n indent = \"\\t\\t\\t\";\n }\n\n auto go_parse = String::split(command);\n for(size_t i = 1; i < go_parse.size(); ++i)\n {\n auto option = go_parse.at(i);\n double new_time = 0.0;\n if(String::ends_with(option, \"time\") || String::ends_with(option, \"inc\"))\n {\n \/\/ All times received are in milliseconds\n new_time = std::stod(go_parse.at(++i))\/1000;\n }\n\n if(option == \"wtime\")\n {\n log(\"Setting White's time to \" + std::to_string(new_time));\n clock.set_time(WHITE, new_time);\n }\n else if(option == \"btime\")\n {\n log(\"Setting Black's time to \" + std::to_string(new_time));\n clock.set_time(BLACK, new_time);\n }\n else if(option == \"winc\")\n {\n log(\"Setting White's increment time to \" + std::to_string(new_time));\n clock.set_increment(WHITE, new_time);\n }\n else if(option == \"binc\")\n {\n log(\"Setting Black's increment time to \" + std::to_string(new_time));\n clock.set_increment(BLACK, new_time);\n }\n else if(option == \"movestogo\")\n {\n auto moves_to_reset = String::string_to_size_t(go_parse.at(++i));\n log(\"Next time control in \" + std::to_string(moves_to_reset));\n clock.set_next_time_reset(moves_to_reset);\n }\n else if(option == \"movetime\")\n {\n clock.set_time(board.whose_turn(), new_time);\n clock.set_next_time_reset(1);\n }\n else\n {\n log(\"Ignoring go command: \" + option);\n }\n }\n\n log(\"Telling AI to choose a move at leisure\");\n board.choose_move_at_leisure();\n return;\n }\n }\n}\n\nvoid UCI_Mediator::listen(Board& board, Clock& clock)\n{\n last_listening_result = std::async(std::launch::async, &UCI_Mediator::listener, this, std::ref(board), std::ref(clock));\n}\n\nvoid UCI_Mediator::handle_move(Board& board, const Move& move)\n{\n board.submit_move(move);\n send_command(\"bestmove \" + move.coordinate_move());\n}\n\nbool UCI_Mediator::pondering_allowed() const\n{\n return true;\n}\n\nstd::string UCI_Mediator::listener(Board& board, Clock& clock)\n{\n return receive_uci_command(board, clock, true);\n}\n\nstd::string UCI_Mediator::receive_uci_command(Board& board, Clock& clock, bool while_listening)\n{\n clock.do_not_stop_game();\n\n while(true)\n {\n std::string command;\n if(while_listening)\n {\n command = receive_command();\n }\n else\n {\n command = last_listening_result.valid() ? last_listening_result.get() : receive_command();\n }\n\n if(command == \"isready\")\n {\n send_command(\"readyok\");\n }\n else if(command == \"stop\")\n {\n log(\"Stopping local AI thinking\");\n board.pick_move_now();\n }\n else\n {\n return command;\n }\n }\n}\nFix indentation#include \"Players\/UCI_Mediator.h\"\n\n#include \n#include \n#include \n#include \n\n#include \"Players\/Player.h\"\n#include \"Game\/Board.h\"\n#include \"Game\/Clock.h\"\n#include \"Game\/Game_Result.h\"\n#include \"Moves\/Move.h\"\n\n#include \"Utility\/String.h\"\n\nUCI_Mediator::UCI_Mediator(const Player& player)\n{\n send_command(\"id name \" + player.name());\n send_command(\"id author \" + player.author());\n send_command(\"uciok\");\n}\n\nvoid UCI_Mediator::setup_turn(Board& board, Clock& clock)\n{\n while(true)\n {\n auto command = receive_uci_command(board, clock, false);\n if(command == \"ucinewgame\")\n {\n log(\"stopping thinking and clocks\");\n board.pick_move_now();\n clock.stop();\n }\n else if(String::starts_with(command, \"position \"))\n {\n auto parse = String::split(command);\n if(parse.at(1) == \"startpos\")\n {\n board = Board();\n }\n else if(parse.at(1) == \"fen\")\n {\n auto fen = std::accumulate(std::next(parse.begin(), 3), std::next(parse.begin(), 8),\n parse.at(2),\n [](const auto& so_far, const auto& next)\n {\n return so_far + \" \" + next;\n });\n board = Board(fen);\n }\n\n auto moves_iter = std::find(parse.begin(), parse.end(), \"moves\");\n if(moves_iter != parse.end())\n {\n std::for_each(std::next(moves_iter), parse.end(),\n [&board](const auto& move)\n {\n board.submit_move(board.create_move(move));\n });\n log(\"All moves applied\");\n }\n\n log(\"Board ready for play\");\n board.set_thinking_mode(UCI);\n }\n else if(String::starts_with(command, \"go\"))\n {\n if(board.whose_turn() == WHITE)\n {\n indent = \"\\t\\t\";\n }\n else\n {\n indent = \"\\t\\t\\t\";\n }\n\n auto go_parse = String::split(command);\n for(size_t i = 1; i < go_parse.size(); ++i)\n {\n auto option = go_parse.at(i);\n double new_time = 0.0;\n if(String::ends_with(option, \"time\") || String::ends_with(option, \"inc\"))\n {\n \/\/ All times received are in milliseconds\n new_time = std::stod(go_parse.at(++i))\/1000;\n }\n\n if(option == \"wtime\")\n {\n log(\"Setting White's time to \" + std::to_string(new_time));\n clock.set_time(WHITE, new_time);\n }\n else if(option == \"btime\")\n {\n log(\"Setting Black's time to \" + std::to_string(new_time));\n clock.set_time(BLACK, new_time);\n }\n else if(option == \"winc\")\n {\n log(\"Setting White's increment time to \" + std::to_string(new_time));\n clock.set_increment(WHITE, new_time);\n }\n else if(option == \"binc\")\n {\n log(\"Setting Black's increment time to \" + std::to_string(new_time));\n clock.set_increment(BLACK, new_time);\n }\n else if(option == \"movestogo\")\n {\n auto moves_to_reset = String::string_to_size_t(go_parse.at(++i));\n log(\"Next time control in \" + std::to_string(moves_to_reset));\n clock.set_next_time_reset(moves_to_reset);\n }\n else if(option == \"movetime\")\n {\n clock.set_time(board.whose_turn(), new_time);\n clock.set_next_time_reset(1);\n }\n else\n {\n log(\"Ignoring go command: \" + option);\n }\n }\n\n log(\"Telling AI to choose a move at leisure\");\n board.choose_move_at_leisure();\n return;\n }\n }\n}\n\nvoid UCI_Mediator::listen(Board& board, Clock& clock)\n{\n last_listening_result = std::async(std::launch::async, &UCI_Mediator::listener, this, std::ref(board), std::ref(clock));\n}\n\nvoid UCI_Mediator::handle_move(Board& board, const Move& move)\n{\n board.submit_move(move);\n send_command(\"bestmove \" + move.coordinate_move());\n}\n\nbool UCI_Mediator::pondering_allowed() const\n{\n return true;\n}\n\nstd::string UCI_Mediator::listener(Board& board, Clock& clock)\n{\n return receive_uci_command(board, clock, true);\n}\n\nstd::string UCI_Mediator::receive_uci_command(Board& board, Clock& clock, bool while_listening)\n{\n clock.do_not_stop_game();\n\n while(true)\n {\n std::string command;\n if(while_listening)\n {\n command = receive_command();\n }\n else\n {\n command = last_listening_result.valid() ? last_listening_result.get() : receive_command();\n }\n\n if(command == \"isready\")\n {\n send_command(\"readyok\");\n }\n else if(command == \"stop\")\n {\n log(\"Stopping local AI thinking\");\n board.pick_move_now();\n }\n else\n {\n return command;\n }\n }\n}\n<|endoftext|>"} {"text":"\/\/ Scintilla source code edit control\n\/** @file XPM.cxx\n ** Define a class that holds data in the X Pixmap (XPM) format.\n **\/\n\/\/ Copyright 1998-2003 by Neil Hodgson \n\/\/ The License.txt file describes the conditions under which this software may be distributed.\n\n#include \n#include \n\n#include \"Platform.h\"\n\n#include \"XPM.h\"\n\nstatic const char *NextField(const char *s) {\n\twhile (*s && *s != ' ') {\n\t\ts++;\n\t}\n\twhile (*s && *s == ' ') {\n\t\ts++;\n\t}\n\treturn s;\n}\n\n\/\/ Data lines in XPM can be terminated either with NUL or \"\nstatic size_t MeasureLength(const char *s) {\n\tsize_t i = 0;\n\twhile (s[i] && (s[i] != '\\\"'))\n\t\ti++;\n\treturn i;\n}\n\nColourAllocated XPM::ColourFromCode(int ch) {\n\treturn colourCodeTable[ch]->allocated;\n#ifdef SLOW\n\tfor (int i=0; iFillRectangle(rc, ColourFromCode(code));\n\t}\n}\n\nXPM::XPM(const char *textForm) :\n\tdata(0), codes(0), colours(0), lines(0) {\n\tInit(textForm);\n}\n\nXPM::XPM(const char * const *linesForm) :\n\tdata(0), codes(0), colours(0), lines(0) {\n\tInit(linesForm);\n}\n\nXPM::~XPM() {\n\tClear();\n}\n\nvoid XPM::Init(const char *textForm) {\n\tClear();\n\t\/\/ Test done is two parts to avoid possibility of overstepping the memory\n\t\/\/ if memcmp implemented strangely. Must be 4 bytes at least at destination.\n\tif ((0 == memcmp(textForm, \"\/* X\", 4)) && (0 == memcmp(textForm, \"\/* XPM *\/\", 9))) {\n\t\t\/\/ Build the lines form out of the text form\n\t\tconst char **linesForm = LinesFormFromTextForm(textForm);\n\t\tInit(linesForm);\n\t\tdelete []linesForm;\n\t} else {\n\t\t\/\/ It is really in line form\n\t\tInit(reinterpret_cast(textForm));\n\t}\n}\n\nvoid XPM::Init(const char * const *linesForm) {\n\tClear();\n\theight = 1;\n\twidth = 1;\n\tnColours = 1;\n\tdata = NULL;\n\tcodeTransparent = ' ';\n\tcodes = NULL;\n\tcolours = NULL;\n\tlines = NULL;\n\tif (!linesForm)\n\t\treturn;\n\n\tconst char *line0 = linesForm[0];\n\twidth = atoi(line0);\n\tline0 = NextField(line0);\n\theight = atoi(line0);\n\tline0 = NextField(line0);\n\tnColours = atoi(line0);\n\tcodes = new char[nColours];\n\tcolours = new ColourPair[nColours];\n\n\tint strings = 1+height+nColours;\n\tlines = new char *[strings];\n\tsize_t allocation = 0;\n\tfor (int i=0; i(codes[c])] = &(colours[c]);\n\t}\n}\n\nvoid XPM::Clear() {\n\tdelete []data;\n\tdata = 0;\n\tdelete []codes;\n\tcodes = 0;\n\tdelete []colours;\n\tcolours = 0;\n\tdelete []lines;\n\tlines = 0;\n}\n\nvoid XPM::RefreshColourPalette(Palette &pal, bool want) {\n\tif (!data || !codes || !colours || !lines) {\n\t\treturn;\n\t}\n\tfor (int i=0; iGetId() == id) {\n\t\t\tset[i]->Init(textForm);\n\t\t\treturn;\n\t\t}\n\t}\n\n\t\/\/ Not present, so add to end\n\tXPM *pxpm = new XPM(textForm);\n\tif (pxpm) {\n\t\tpxpm->SetId(id);\n\t\tpxpm->CopyDesiredColours();\n\t\tif (len == maximum) {\n\t\t\tmaximum += 64;\n\t\t\tXPM **setNew = new XPM *[maximum];\n\t\t\tfor (int i = 0; i < len; i++) {\n\t\t\t\tsetNew[i] = set[i];\n\t\t\t}\n\t\t\tdelete []set;\n\t\t\tset = setNew;\n\t\t}\n\t\tset[len] = pxpm;\n\t\tlen++;\n\t}\n}\n\nXPM *XPMSet::Get(int id) {\n\tfor (int i = 0; i < len; i++) {\n\t\tif (set[i]->GetId() == id) {\n\t\t\treturn set[i];\n\t\t}\n\t}\n\treturn 0;\n}\n\nint XPMSet::GetHeight() {\n\tif (height < 0) {\n\t\tfor (int i = 0; i < len; i++) {\n\t\t\tif (height < set[i]->GetHeight()) {\n\t\t\t\theight = set[i]->GetHeight();\n\t\t\t}\n\t\t}\n\t}\n\treturn (height > 0) ? height : 0;\n}\n\nint XPMSet::GetWidth() {\n\tif (width < 0) {\n\t\tfor (int i = 0; i < len; i++) {\n\t\t\tif (width < set[i]->GetWidth()) {\n\t\t\t\twidth = set[i]->GetWidth();\n\t\t\t}\n\t\t}\n\t}\n\treturn (width > 0) ? width : 0;\n}\nPatch from Philippe to make decoding safer.\/\/ Scintilla source code edit control\n\/** @file XPM.cxx\n ** Define a class that holds data in the X Pixmap (XPM) format.\n **\/\n\/\/ Copyright 1998-2003 by Neil Hodgson \n\/\/ The License.txt file describes the conditions under which this software may be distributed.\n\n#include \n#include \n\n#include \"Platform.h\"\n\n#include \"XPM.h\"\n\nstatic const char *NextField(const char *s) {\n\t\/\/ In case there are leading spaces in the string\n\twhile (*s && *s == ' ') {\n\t\ts++;\n\t}\n\twhile (*s && *s != ' ') {\n\t\ts++;\n\t}\n\twhile (*s && *s == ' ') {\n\t\ts++;\n\t}\n\treturn s;\n}\n\n\/\/ Data lines in XPM can be terminated either with NUL or \"\nstatic size_t MeasureLength(const char *s) {\n\tsize_t i = 0;\n\twhile (s[i] && (s[i] != '\\\"'))\n\t\ti++;\n\treturn i;\n}\n\nColourAllocated XPM::ColourFromCode(int ch) {\n\treturn colourCodeTable[ch]->allocated;\n#ifdef SLOW\n\tfor (int i=0; iFillRectangle(rc, ColourFromCode(code));\n\t}\n}\n\nXPM::XPM(const char *textForm) :\n\tdata(0), codes(0), colours(0), lines(0) {\n\tInit(textForm);\n}\n\nXPM::XPM(const char * const *linesForm) :\n\tdata(0), codes(0), colours(0), lines(0) {\n\tInit(linesForm);\n}\n\nXPM::~XPM() {\n\tClear();\n}\n\nvoid XPM::Init(const char *textForm) {\n\tClear();\n\t\/\/ Test done is two parts to avoid possibility of overstepping the memory\n\t\/\/ if memcmp implemented strangely. Must be 4 bytes at least at destination.\n\tif ((0 == memcmp(textForm, \"\/* X\", 4)) && (0 == memcmp(textForm, \"\/* XPM *\/\", 9))) {\n\t\t\/\/ Build the lines form out of the text form\n\t\tconst char **linesForm = LinesFormFromTextForm(textForm);\n\t\tif (linesForm != 0) {\n\t\t\tInit(linesForm);\n\t\t\tdelete []linesForm;\n\t\t}\n\t} else {\n\t\t\/\/ It is really in line form\n\t\tInit(reinterpret_cast(textForm));\n\t}\n}\n\nvoid XPM::Init(const char * const *linesForm) {\n\tClear();\n\theight = 1;\n\twidth = 1;\n\tnColours = 1;\n\tdata = NULL;\n\tcodeTransparent = ' ';\n\tcodes = NULL;\n\tcolours = NULL;\n\tlines = NULL;\n\tif (!linesForm)\n\t\treturn;\n\n\tconst char *line0 = linesForm[0];\n\twidth = atoi(line0);\n\tline0 = NextField(line0);\n\theight = atoi(line0);\n\tline0 = NextField(line0);\n\tnColours = atoi(line0);\n\tcodes = new char[nColours];\n\tcolours = new ColourPair[nColours];\n\n\tint strings = 1+height+nColours;\n\tlines = new char *[strings];\n\tsize_t allocation = 0;\n\tfor (int i=0; i(codes[c])] = &(colours[c]);\n\t}\n}\n\nvoid XPM::Clear() {\n\tdelete []data;\n\tdata = 0;\n\tdelete []codes;\n\tcodes = 0;\n\tdelete []colours;\n\tcolours = 0;\n\tdelete []lines;\n\tlines = 0;\n}\n\nvoid XPM::RefreshColourPalette(Palette &pal, bool want) {\n\tif (!data || !codes || !colours || !lines) {\n\t\treturn;\n\t}\n\tfor (int i=0; i= strings) {\n\t\t\t\tbreak;\t\/\/ Bad height or number of colors!\n\t\t\t}\n\t\t\tif ((countQuotes & 1) == 0) {\n\t\t\t\tlinesForm[countQuotes \/ 2] = textForm + j + 1;\n\t\t\t}\n\t\t\tcountQuotes++;\n\t\t}\n\t}\n\tif (textForm[j] == '\\0' || countQuotes \/ 2 > strings) {\n\t\t\/\/ Malformed XPM! Height + number of colors too high or too low\n\t\tdelete []linesForm;\n\t\tlinesForm = 0;\n\t}\n\treturn linesForm;\n}\n\n\/\/ In future, may want to minimize search time by sorting and using a binary search.\n\nXPMSet::XPMSet() : set(0), len(0), maximum(0), height(-1), width(-1) {\n}\n\nXPMSet::~XPMSet() {\n\tClear();\n}\n\nvoid XPMSet::Clear() {\n\tfor (int i = 0; i < len; i++) {\n\t\tdelete set[i];\n\t}\n\tdelete []set;\n\tset = 0;\n\tlen = 0;\n\tmaximum = 0;\n\theight = -1;\n\twidth = -1;\n}\n\nvoid XPMSet::Add(int id, const char *textForm) {\n\t\/\/ Invalidate cached dimensions\n\theight = -1;\n\twidth = -1;\n\n\t\/\/ Replace if this id already present\n\tfor (int i = 0; i < len; i++) {\n\t\tif (set[i]->GetId() == id) {\n\t\t\tset[i]->Init(textForm);\n\t\t\treturn;\n\t\t}\n\t}\n\n\t\/\/ Not present, so add to end\n\tXPM *pxpm = new XPM(textForm);\n\tif (pxpm) {\n\t\tpxpm->SetId(id);\n\t\tpxpm->CopyDesiredColours();\n\t\tif (len == maximum) {\n\t\t\tmaximum += 64;\n\t\t\tXPM **setNew = new XPM *[maximum];\n\t\t\tfor (int i = 0; i < len; i++) {\n\t\t\t\tsetNew[i] = set[i];\n\t\t\t}\n\t\t\tdelete []set;\n\t\t\tset = setNew;\n\t\t}\n\t\tset[len] = pxpm;\n\t\tlen++;\n\t}\n}\n\nXPM *XPMSet::Get(int id) {\n\tfor (int i = 0; i < len; i++) {\n\t\tif (set[i]->GetId() == id) {\n\t\t\treturn set[i];\n\t\t}\n\t}\n\treturn 0;\n}\n\nint XPMSet::GetHeight() {\n\tif (height < 0) {\n\t\tfor (int i = 0; i < len; i++) {\n\t\t\tif (height < set[i]->GetHeight()) {\n\t\t\t\theight = set[i]->GetHeight();\n\t\t\t}\n\t\t}\n\t}\n\treturn (height > 0) ? height : 0;\n}\n\nint XPMSet::GetWidth() {\n\tif (width < 0) {\n\t\tfor (int i = 0; i < len; i++) {\n\t\t\tif (width < set[i]->GetWidth()) {\n\t\t\t\twidth = set[i]->GetWidth();\n\t\t\t}\n\t\t}\n\t}\n\treturn (width > 0) ? width : 0;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file\n\/\/ for details. All rights reserved. Use of this source code is governed by a\n\/\/ BSD-style license that can be found in the LICENSE file.\n\n#if defined(DART_PRECOMPILER)\n\n#include \"vm\/v8_snapshot_writer.h\"\n\n#include \"vm\/dart.h\"\n#include \"vm\/os.h\"\n\nnamespace dart {\n\nconst char* ZoneString(Zone* Z, const char* str) {\n const intptr_t len = strlen(str) + 1;\n char* dest = Z->Alloc(len);\n snprintf(dest, len, \"%s\", str);\n return dest;\n}\n\nV8SnapshotProfileWriter::V8SnapshotProfileWriter(Zone* zone)\n : zone_(zone),\n node_types_(zone_),\n edge_types_(zone_),\n strings_(zone),\n roots_(zone_, 100) {\n node_types_.Insert({\"Unknown\", kUnknown});\n node_types_.Insert({\"ArtificialRoot\", kArtificialRoot});\n\n edge_types_.Insert({\"context\", kContext});\n edge_types_.Insert({\"element\", kElement});\n edge_types_.Insert({\"property\", kProperty});\n edge_types_.Insert({\"internal\", kInternal});\n edge_types_.Insert({\"hidden\", kHidden});\n edge_types_.Insert({\"shortcut\", kShortcut});\n edge_types_.Insert({\"weak\", kWeak});\n edge_types_.Insert({\"extra\", kExtra});\n\n strings_.Insert({\"\", kUnknownString});\n strings_.Insert({\"\", kObjectString});\n strings_.Insert({\"\", kPropertyString});\n strings_.Insert({\"\", kArtificialRootString});\n}\n\nvoid V8SnapshotProfileWriter::SetObjectTypeAndName(ObjectId object_id,\n const char* type,\n const char* name) {\n ASSERT(type != nullptr);\n NodeInfo* info = EnsureId(object_id);\n\n if (!node_types_.HasKey(type)) {\n node_types_.Insert({ZoneString(zone_, type), node_types_.Size()});\n }\n\n intptr_t type_id = node_types_.LookupValue(type);\n ASSERT(info->type == kUnknown || info->type == type_id);\n info->type = type_id;\n\n if (name != nullptr) {\n info->name = EnsureString(OS::SCreate(zone_, \"[%s] %s\", type, name));\n } else {\n info->name = EnsureString(type);\n }\n}\n\nvoid V8SnapshotProfileWriter::AttributeBytesTo(ObjectId object_id,\n size_t num_bytes) {\n EnsureId(object_id)->self_size += num_bytes;\n}\n\nvoid V8SnapshotProfileWriter::AttributeReferenceTo(ObjectId object_id,\n Reference reference) {\n EnsureId(reference.to_object_id);\n NodeInfo* info = EnsureId(object_id);\n\n ASSERT(reference.offset_or_name >= 0);\n info->edges->Add({\n reference.reference_type == Reference::kElement ? kElement : kProperty,\n reference.offset_or_name,\n reference.to_object_id,\n });\n ++edge_count_;\n}\n\nV8SnapshotProfileWriter::NodeInfo V8SnapshotProfileWriter::DefaultNode(\n ObjectId object_id) {\n return {\n kUnknown,\n kUnknownString,\n object_id,\n 0,\n new (zone_) ZoneGrowableArray(zone_, 0),\n -1,\n };\n}\n\nV8SnapshotProfileWriter::NodeInfo V8SnapshotProfileWriter::ArtificialRoot() {\n return {\n kArtificialRoot, kArtificialRootString, {kArtificial, 0}, 0, nullptr, 0,\n };\n}\n\nV8SnapshotProfileWriter::NodeInfo* V8SnapshotProfileWriter::EnsureId(\n ObjectId object_id) {\n if (!nodes_.HasKey(object_id)) {\n NodeInfo info = DefaultNode(object_id);\n nodes_.Insert({object_id, info});\n }\n return &nodes_.Lookup(object_id)->value;\n}\n\nintptr_t V8SnapshotProfileWriter::EnsureString(const char* str) {\n if (!strings_.HasKey(str)) {\n strings_.Insert({ZoneString(zone_, str), strings_.Size()});\n return strings_.Size() - 1;\n }\n return strings_.LookupValue(str);\n}\n\nvoid V8SnapshotProfileWriter::WriteNodeInfo(JSONWriter* writer,\n const NodeInfo& info) {\n writer->PrintValue(info.type);\n writer->PrintValue(info.name);\n writer->PrintValue(NodeIdFor(info.id));\n writer->PrintValue(info.self_size);\n \/\/ The artificial root has 'nullptr' edges, it actually points to all the\n \/\/ roots.\n writer->PrintValue64(info.edges != nullptr ? info.edges->length()\n : roots_.length());\n writer->PrintNewline();\n}\n\nvoid V8SnapshotProfileWriter::WriteEdgeInfo(JSONWriter* writer,\n const EdgeInfo& info) {\n writer->PrintValue64(info.type);\n writer->PrintValue64(info.name_or_index);\n writer->PrintValue64(nodes_.LookupValue(info.to_node).offset);\n writer->PrintNewline();\n}\n\nvoid V8SnapshotProfileWriter::AddRoot(ObjectId object_id) {\n EnsureId(object_id);\n roots_.Add(object_id);\n}\n\nvoid V8SnapshotProfileWriter::WriteStringsTable(\n JSONWriter* writer,\n const DirectChainedHashMap& map) {\n const char** strings = zone_->Alloc(map.Size());\n StringToIntMapTraits::Pair* pair = nullptr;\n auto it = map.GetIterator();\n while ((pair = it.Next()) != nullptr) {\n ASSERT(pair->value >= 0 && pair->value < map.Size());\n strings[pair->value] = pair->key;\n }\n for (intptr_t i = 0; i < map.Size(); ++i) {\n writer->PrintValue(strings[i]);\n writer->PrintNewline();\n }\n}\n\nvoid V8SnapshotProfileWriter::Write(JSONWriter* writer) {\n writer->OpenObject();\n\n writer->OpenObject(\"snapshot\");\n {\n writer->OpenObject(\"meta\");\n\n {\n writer->OpenArray(\"node_fields\");\n writer->PrintValue(\"type\");\n writer->PrintValue(\"name\");\n writer->PrintValue(\"id\");\n writer->PrintValue(\"self_size\");\n writer->PrintValue(\"edge_count\");\n writer->CloseArray();\n }\n\n {\n writer->OpenArray(\"node_types\");\n {\n writer->OpenArray();\n WriteStringsTable(writer, node_types_);\n writer->CloseArray();\n }\n writer->CloseArray();\n }\n\n {\n writer->OpenArray(\"edge_fields\");\n writer->PrintValue(\"type\");\n writer->PrintValue(\"name_or_index\");\n writer->PrintValue(\"to_node\");\n writer->CloseArray();\n }\n\n {\n writer->OpenArray(\"edge_types\");\n {\n writer->OpenArray();\n WriteStringsTable(writer, edge_types_);\n writer->CloseArray();\n }\n writer->CloseArray();\n }\n\n writer->CloseObject();\n\n writer->PrintProperty64(\"node_count\",\n nodes_.Size() + 1 \/* artificial root *\/);\n writer->PrintProperty64(\"edge_count\", edge_count_ + roots_.length());\n }\n writer->CloseObject();\n\n {\n writer->OpenArray(\"nodes\");\n \/\/ Write the artificial root node.\n WriteNodeInfo(writer, ArtificialRoot());\n intptr_t offset = kNumNodeFields;\n ObjectIdToNodeInfoTraits::Pair* entry = nullptr;\n auto it = nodes_.GetIterator();\n while ((entry = it.Next()) != nullptr) {\n ASSERT(entry->key == entry->value.id);\n entry->value.offset = offset;\n WriteNodeInfo(writer, entry->value);\n offset += kNumNodeFields;\n }\n writer->CloseArray();\n }\n\n {\n writer->OpenArray(\"edges\");\n\n \/\/ Write references from the artificial root to the actual roots.\n for (intptr_t i = 0; i < roots_.length(); ++i) {\n WriteEdgeInfo(writer, {kElement, i, roots_[i]});\n }\n\n ObjectIdToNodeInfoTraits::Pair* entry = nullptr;\n auto it = nodes_.GetIterator();\n while ((entry = it.Next()) != nullptr) {\n for (intptr_t i = 0; i < entry->value.edges->length(); ++i) {\n WriteEdgeInfo(writer, entry->value.edges->At(i));\n }\n }\n\n writer->CloseArray();\n }\n\n {\n writer->OpenArray(\"strings\");\n WriteStringsTable(writer, strings_);\n writer->CloseArray();\n }\n\n writer->CloseObject();\n}\n\nvoid V8SnapshotProfileWriter::Write(const char* filename) {\n JSONWriter json;\n Write(&json);\n\n auto file_open = Dart::file_open_callback();\n auto file_write = Dart::file_write_callback();\n auto file_close = Dart::file_close_callback();\n if ((file_open == nullptr) || (file_write == nullptr) ||\n (file_close == nullptr)) {\n OS::PrintErr(\"Could not access file callbacks to write snapshot profile.\");\n return;\n }\n\n auto file = file_open(filename, \/*write=*\/true);\n if (file == nullptr) {\n OS::PrintErr(\"Failed to open file %s\\n\", filename);\n } else {\n char* output = nullptr;\n intptr_t output_length = 0;\n json.Steal(&output, &output_length);\n file_write(output, output_length, file);\n free(output);\n file_close(file);\n }\n}\n\n} \/\/ namespace dart\n\n#endif\nFix SDK build on Mac.\/\/ Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file\n\/\/ for details. All rights reserved. Use of this source code is governed by a\n\/\/ BSD-style license that can be found in the LICENSE file.\n\n#if defined(DART_PRECOMPILER)\n\n#include \"vm\/v8_snapshot_writer.h\"\n\n#include \"vm\/dart.h\"\n#include \"vm\/os.h\"\n\nnamespace dart {\n\nconst char* ZoneString(Zone* Z, const char* str) {\n const intptr_t len = strlen(str) + 1;\n char* dest = Z->Alloc(len);\n snprintf(dest, len, \"%s\", str);\n return dest;\n}\n\nV8SnapshotProfileWriter::V8SnapshotProfileWriter(Zone* zone)\n : zone_(zone),\n node_types_(zone_),\n edge_types_(zone_),\n strings_(zone),\n roots_(zone_, 100) {\n node_types_.Insert({\"Unknown\", kUnknown});\n node_types_.Insert({\"ArtificialRoot\", kArtificialRoot});\n\n edge_types_.Insert({\"context\", kContext});\n edge_types_.Insert({\"element\", kElement});\n edge_types_.Insert({\"property\", kProperty});\n edge_types_.Insert({\"internal\", kInternal});\n edge_types_.Insert({\"hidden\", kHidden});\n edge_types_.Insert({\"shortcut\", kShortcut});\n edge_types_.Insert({\"weak\", kWeak});\n edge_types_.Insert({\"extra\", kExtra});\n\n strings_.Insert({\"\", kUnknownString});\n strings_.Insert({\"\", kObjectString});\n strings_.Insert({\"\", kPropertyString});\n strings_.Insert({\"\", kArtificialRootString});\n}\n\nvoid V8SnapshotProfileWriter::SetObjectTypeAndName(ObjectId object_id,\n const char* type,\n const char* name) {\n ASSERT(type != nullptr);\n NodeInfo* info = EnsureId(object_id);\n\n if (!node_types_.HasKey(type)) {\n node_types_.Insert({ZoneString(zone_, type), node_types_.Size()});\n }\n\n intptr_t type_id = node_types_.LookupValue(type);\n ASSERT(info->type == kUnknown || info->type == type_id);\n info->type = type_id;\n\n if (name != nullptr) {\n info->name = EnsureString(OS::SCreate(zone_, \"[%s] %s\", type, name));\n } else {\n info->name = EnsureString(type);\n }\n}\n\nvoid V8SnapshotProfileWriter::AttributeBytesTo(ObjectId object_id,\n size_t num_bytes) {\n EnsureId(object_id)->self_size += num_bytes;\n}\n\nvoid V8SnapshotProfileWriter::AttributeReferenceTo(ObjectId object_id,\n Reference reference) {\n EnsureId(reference.to_object_id);\n NodeInfo* info = EnsureId(object_id);\n\n ASSERT(reference.offset_or_name >= 0);\n info->edges->Add({\n static_cast(reference.reference_type == Reference::kElement\n ? kElement\n : kProperty),\n reference.offset_or_name,\n reference.to_object_id,\n });\n ++edge_count_;\n}\n\nV8SnapshotProfileWriter::NodeInfo V8SnapshotProfileWriter::DefaultNode(\n ObjectId object_id) {\n return {\n kUnknown,\n kUnknownString,\n object_id,\n 0,\n new (zone_) ZoneGrowableArray(zone_, 0),\n -1,\n };\n}\n\nV8SnapshotProfileWriter::NodeInfo V8SnapshotProfileWriter::ArtificialRoot() {\n return {\n kArtificialRoot, kArtificialRootString, {kArtificial, 0}, 0, nullptr, 0,\n };\n}\n\nV8SnapshotProfileWriter::NodeInfo* V8SnapshotProfileWriter::EnsureId(\n ObjectId object_id) {\n if (!nodes_.HasKey(object_id)) {\n NodeInfo info = DefaultNode(object_id);\n nodes_.Insert({object_id, info});\n }\n return &nodes_.Lookup(object_id)->value;\n}\n\nintptr_t V8SnapshotProfileWriter::EnsureString(const char* str) {\n if (!strings_.HasKey(str)) {\n strings_.Insert({ZoneString(zone_, str), strings_.Size()});\n return strings_.Size() - 1;\n }\n return strings_.LookupValue(str);\n}\n\nvoid V8SnapshotProfileWriter::WriteNodeInfo(JSONWriter* writer,\n const NodeInfo& info) {\n writer->PrintValue(info.type);\n writer->PrintValue(info.name);\n writer->PrintValue(NodeIdFor(info.id));\n writer->PrintValue(info.self_size);\n \/\/ The artificial root has 'nullptr' edges, it actually points to all the\n \/\/ roots.\n writer->PrintValue64(info.edges != nullptr ? info.edges->length()\n : roots_.length());\n writer->PrintNewline();\n}\n\nvoid V8SnapshotProfileWriter::WriteEdgeInfo(JSONWriter* writer,\n const EdgeInfo& info) {\n writer->PrintValue64(info.type);\n writer->PrintValue64(info.name_or_index);\n writer->PrintValue64(nodes_.LookupValue(info.to_node).offset);\n writer->PrintNewline();\n}\n\nvoid V8SnapshotProfileWriter::AddRoot(ObjectId object_id) {\n EnsureId(object_id);\n roots_.Add(object_id);\n}\n\nvoid V8SnapshotProfileWriter::WriteStringsTable(\n JSONWriter* writer,\n const DirectChainedHashMap& map) {\n const char** strings = zone_->Alloc(map.Size());\n StringToIntMapTraits::Pair* pair = nullptr;\n auto it = map.GetIterator();\n while ((pair = it.Next()) != nullptr) {\n ASSERT(pair->value >= 0 && pair->value < map.Size());\n strings[pair->value] = pair->key;\n }\n for (intptr_t i = 0; i < map.Size(); ++i) {\n writer->PrintValue(strings[i]);\n writer->PrintNewline();\n }\n}\n\nvoid V8SnapshotProfileWriter::Write(JSONWriter* writer) {\n writer->OpenObject();\n\n writer->OpenObject(\"snapshot\");\n {\n writer->OpenObject(\"meta\");\n\n {\n writer->OpenArray(\"node_fields\");\n writer->PrintValue(\"type\");\n writer->PrintValue(\"name\");\n writer->PrintValue(\"id\");\n writer->PrintValue(\"self_size\");\n writer->PrintValue(\"edge_count\");\n writer->CloseArray();\n }\n\n {\n writer->OpenArray(\"node_types\");\n {\n writer->OpenArray();\n WriteStringsTable(writer, node_types_);\n writer->CloseArray();\n }\n writer->CloseArray();\n }\n\n {\n writer->OpenArray(\"edge_fields\");\n writer->PrintValue(\"type\");\n writer->PrintValue(\"name_or_index\");\n writer->PrintValue(\"to_node\");\n writer->CloseArray();\n }\n\n {\n writer->OpenArray(\"edge_types\");\n {\n writer->OpenArray();\n WriteStringsTable(writer, edge_types_);\n writer->CloseArray();\n }\n writer->CloseArray();\n }\n\n writer->CloseObject();\n\n writer->PrintProperty64(\"node_count\",\n nodes_.Size() + 1 \/* artificial root *\/);\n writer->PrintProperty64(\"edge_count\", edge_count_ + roots_.length());\n }\n writer->CloseObject();\n\n {\n writer->OpenArray(\"nodes\");\n \/\/ Write the artificial root node.\n WriteNodeInfo(writer, ArtificialRoot());\n intptr_t offset = kNumNodeFields;\n ObjectIdToNodeInfoTraits::Pair* entry = nullptr;\n auto it = nodes_.GetIterator();\n while ((entry = it.Next()) != nullptr) {\n ASSERT(entry->key == entry->value.id);\n entry->value.offset = offset;\n WriteNodeInfo(writer, entry->value);\n offset += kNumNodeFields;\n }\n writer->CloseArray();\n }\n\n {\n writer->OpenArray(\"edges\");\n\n \/\/ Write references from the artificial root to the actual roots.\n for (intptr_t i = 0; i < roots_.length(); ++i) {\n WriteEdgeInfo(writer, {kElement, i, roots_[i]});\n }\n\n ObjectIdToNodeInfoTraits::Pair* entry = nullptr;\n auto it = nodes_.GetIterator();\n while ((entry = it.Next()) != nullptr) {\n for (intptr_t i = 0; i < entry->value.edges->length(); ++i) {\n WriteEdgeInfo(writer, entry->value.edges->At(i));\n }\n }\n\n writer->CloseArray();\n }\n\n {\n writer->OpenArray(\"strings\");\n WriteStringsTable(writer, strings_);\n writer->CloseArray();\n }\n\n writer->CloseObject();\n}\n\nvoid V8SnapshotProfileWriter::Write(const char* filename) {\n JSONWriter json;\n Write(&json);\n\n auto file_open = Dart::file_open_callback();\n auto file_write = Dart::file_write_callback();\n auto file_close = Dart::file_close_callback();\n if ((file_open == nullptr) || (file_write == nullptr) ||\n (file_close == nullptr)) {\n OS::PrintErr(\"Could not access file callbacks to write snapshot profile.\");\n return;\n }\n\n auto file = file_open(filename, \/*write=*\/true);\n if (file == nullptr) {\n OS::PrintErr(\"Failed to open file %s\\n\", filename);\n } else {\n char* output = nullptr;\n intptr_t output_length = 0;\n json.Steal(&output, &output_length);\n file_write(output, output_length, file);\n free(output);\n file_close(file);\n }\n}\n\n} \/\/ namespace dart\n\n#endif\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"History.hpp\"\n#include \"TerminalInfo.hpp\"\n\n#define cursor_forward(x) printf(\"\\033[%dC\", static_cast(x))\n#define cursor_backward(x) printf(\"\\033[%dD\", static_cast(x))\n\n\/\/ https:\/\/www.akkadia.org\/drepper\/tls.pdf\n\nthread_local std::array lineBuffer;\nthread_local auto lineBufferPos = lineBuffer.begin();\n\nthread_local std::string printBuffer;\nthread_local std::string::iterator printBufferPos;\n\nusing namespace yb;\nthread_local History history;\nthread_local History::const_iterator historyPos;\n\nstatic char arrowIndicator = 0;\n\nusing ReadSignature = ssize_t (*)(int, void*, size_t);\nusing Char = unsigned char;\nusing CharOpt = std::experimental::optional;\n\nCharOpt newlineHandler(Char);\nCharOpt tabHandler(Char);\nCharOpt backspaceHandler(Char);\nCharOpt regularCHarHandler(Char);\nCharOpt arrowHandler1(Char);\nCharOpt arrowHandler2(Char);\nCharOpt arrowHandler3(Char);\n\nthread_local std::map> handlers = {\n {0x06, tabHandler},\n {0x0d, newlineHandler},\n {0x17, newlineHandler}, \/\/ TODO: this should delete one word\n {0x1b, arrowHandler1},\n {0x5b, arrowHandler2},\n {0x43, arrowHandler3},\n {0x7f, backspaceHandler}\n};\n\nvoid clearTerminalLine() {\n int pos, width;\n if (!(pos = TerminalInfo::getCursorPosition())) return;\n width = TerminalInfo::getWidth();\n for (int i = 0; i < width - pos; i++)\n printf(\" \");\n fflush(stdout);\n for (int i = 0; i < width - pos; i++)\n cursor_backward(1);\n}\n\nstd::string findCompletion(History::const_iterator start, const std::string &pattern) {\n for (auto it = start - 1; it > history.begin(); it--) {\n if (it->compare(0, pattern.length(), pattern) == 0) {\n historyPos = it;\n return *it;\n }\n }\n\n historyPos = history.end();\n return pattern;\n}\n\n\nvoid printCompletion(History::const_iterator startIterator, int offset) {\n std::string pattern(lineBuffer.data());\n auto completion = findCompletion(startIterator, pattern);\n\n clearTerminalLine();\n\n if (offset)\n cursor_forward(offset);\n printf(\"\\e[1;30m%s\\e[0m\", completion.c_str() + pattern.length());\n\n cursor_backward(completion.length() - pattern.length() + offset);\n fflush(stdout);\n}\n\n\nCharOpt newlineHandler(Char) {\n lineBuffer.fill(0);\n lineBufferPos = lineBuffer.begin();\n return {};\n}\n\nCharOpt backspaceHandler(Char) {\n if (lineBufferPos != lineBuffer.begin()) {\n *(--lineBufferPos) = 0;\n }\n\n return {};\n}\n\nCharOpt regularCharHandler(Char c) {\n *lineBufferPos = c;\n lineBufferPos++;\n\n printCompletion(history.end(), 1);\n\n return {};\n}\n\nCharOpt tabHandler(Char) {\n printCompletion(historyPos, 0);\n return Char{0}; \/\/ TODO: this does not seem to work.\n}\n\nCharOpt arrowHandler1(Char) {\n arrowIndicator = 1;\n return {};\n}\n\nCharOpt arrowHandler2(Char c) {\n if (arrowIndicator == 1) {\n arrowIndicator = 2;\n return {};\n }\n else {\n return regularCharHandler(c);\n }\n}\n\nCharOpt arrowHandler3(Char c) {\n CharOpt return_value = {};\n if (arrowIndicator == 2) {\n arrowIndicator = 0;\n }\n else {\n return_value = regularCharHandler(c);\n }\n try {\n printBuffer = historyPos->substr(lineBufferPos - lineBuffer.begin());\n printBufferPos = printBuffer.begin();\n } catch (...) {\n \/\/ FIXME:\n }\n\n return return_value;\n}\n\nstatic unsigned char yebash(unsigned char c) {\n\n \/\/ TODO: uncomment later\n \/\/if (!getenv(\"YEBASH\"))\n \/\/ return;\n history.read(std::string{getenv(\"HOME\")} + \"\/.bash_history\");\n\n auto handler = handlers[c];\n\n \/\/ TODO(Mrokkk): There would be a problem with processing all escape codes\n \/\/ that bash is using (e.g. ctrl+r for history searching, arrows for moving, etc.).\n \/\/ It would be thoughtful if we just disable our yebash if any of these codes would\n \/\/ occur and reenable it after a newline\n CharOpt cReturned;\n\n if (handler) {\n cReturned = handler(c);\n }\n else {\n if (c < 0x20) {\n newlineHandler(c);\n }\n else {\n regularCharHandler(c);\n }\n }\n\n return cReturned.value_or(c);\n\n}\n\nssize_t read(int fd, void *buf, size_t count) {\n\n ssize_t returnValue;\n static thread_local ReadSignature realRead = nullptr;\n\n if (fd == 0) { \/\/ TODO: make it look good\n if (printBuffer.length()) {\n \/\/ Return printBuffer to bash one char at time\n *reinterpret_cast(buf) = *printBufferPos;\n *lineBufferPos++ = *printBufferPos++;\n if (printBufferPos == printBuffer.end()) {\n printBuffer.erase(printBuffer.begin(), printBuffer.end());\n }\n return 1;\n }\n }\n\n if (!realRead)\n realRead = reinterpret_cast(dlsym(RTLD_NEXT, \"read\"));\n\n returnValue = realRead(fd, buf, count);\n\n if (fd == 0 && isatty(fileno(stdin)))\n *reinterpret_cast(buf) = yebash(*reinterpret_cast(buf));\n\n return returnValue;\n}\n\n\nSome minor changes#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"History.hpp\"\n#include \"TerminalInfo.hpp\"\n\n#define cursor_forward(x) printf(\"\\033[%dC\", static_cast(x))\n#define cursor_backward(x) printf(\"\\033[%dD\", static_cast(x))\n\n\/\/ https:\/\/www.akkadia.org\/drepper\/tls.pdf\n\nusing namespace yb;\n\nthread_local std::array lineBuffer;\nthread_local auto lineBufferPos = lineBuffer.begin();\n\nthread_local std::string printBuffer;\nthread_local std::string::iterator printBufferPos;\n\nthread_local History history;\nthread_local History::const_iterator historyPos;\n\nstatic char arrowIndicator = 0;\n\nusing ReadSignature = ssize_t (*)(int, void*, size_t);\nusing Char = unsigned char;\nusing CharOpt = std::experimental::optional;\n\nCharOpt newlineHandler(Char);\nCharOpt tabHandler(Char);\nCharOpt backspaceHandler(Char);\nCharOpt regularCHarHandler(Char);\nCharOpt arrowHandler1(Char);\nCharOpt arrowHandler2(Char);\nCharOpt arrowHandler3(Char);\n\nthread_local std::map> handlers = {\n {0x06, tabHandler},\n {0x0d, newlineHandler},\n {0x17, newlineHandler}, \/\/ TODO: this should delete one word\n {0x1b, arrowHandler1},\n {0x5b, arrowHandler2},\n {0x43, arrowHandler3},\n {0x7f, backspaceHandler}\n};\n\nvoid clearTerminalLine() {\n int pos, width;\n if (!(pos = TerminalInfo::getCursorPosition())) return;\n width = TerminalInfo::getWidth();\n for (int i = 0; i < width - pos; i++)\n printf(\" \");\n fflush(stdout);\n for (int i = 0; i < width - pos; i++)\n cursor_backward(1);\n}\n\nstd::string findCompletion(History::const_iterator start, const std::string &pattern) {\n for (auto it = start - 1; it > history.begin(); it--) {\n if (it->compare(0, pattern.length(), pattern) == 0) {\n historyPos = it;\n return *it;\n }\n }\n\n historyPos = history.end();\n return pattern;\n}\n\nvoid printCompletion(History::const_iterator startIterator, int offset) {\n std::string pattern(lineBuffer.data());\n auto completion = findCompletion(startIterator, pattern);\n\n clearTerminalLine();\n\n if (offset)\n cursor_forward(offset);\n printf(\"\\e[1;30m%s\\e[0m\", completion.c_str() + pattern.length());\n\n cursor_backward(completion.length() - pattern.length() + offset);\n fflush(stdout);\n}\n\nCharOpt newlineHandler(Char) {\n lineBuffer.fill(0);\n lineBufferPos = lineBuffer.begin();\n return {};\n}\n\nCharOpt backspaceHandler(Char) {\n if (lineBufferPos != lineBuffer.begin()) {\n *(--lineBufferPos) = 0;\n }\n\n return {};\n}\n\nCharOpt regularCharHandler(Char c) {\n *lineBufferPos = c;\n lineBufferPos++;\n\n printCompletion(history.end(), 1);\n\n return {};\n}\n\nCharOpt tabHandler(Char) {\n printCompletion(historyPos, 0);\n return Char{0}; \/\/ TODO: this does not seem to work.\n}\n\nCharOpt arrowHandler1(Char) {\n arrowIndicator = 1;\n return {};\n}\n\nCharOpt arrowHandler2(Char c) {\n if (arrowIndicator == 1) {\n arrowIndicator = 2;\n return {};\n }\n else {\n return regularCharHandler(c);\n }\n}\n\nCharOpt arrowHandler3(Char c) {\n CharOpt return_value = {};\n if (arrowIndicator == 2) {\n arrowIndicator = 0;\n }\n else {\n return_value = regularCharHandler(c);\n }\n try {\n printBuffer = historyPos->substr(lineBufferPos - lineBuffer.begin());\n printBufferPos = printBuffer.begin();\n } catch (...) {\n \/\/ FIXME:\n }\n\n return return_value;\n}\n\nstatic unsigned char yebash(unsigned char c) {\n\n \/\/ TODO: uncomment later\n \/\/if (!getenv(\"YEBASH\"))\n \/\/ return;\n history.read(std::string{getenv(\"HOME\")} + \"\/.bash_history\");\n\n auto handler = handlers[c];\n\n \/\/ TODO(Mrokkk): There would be a problem with processing all escape codes\n \/\/ that bash is using (e.g. ctrl+r for history searching, arrows for moving, etc.).\n \/\/ It would be thoughtful if we just disable our yebash if any of these codes would\n \/\/ occur and reenable it after a newline\n CharOpt cReturned;\n\n if (handler) {\n cReturned = handler(c);\n }\n else {\n if (c < 0x20) {\n newlineHandler(c);\n }\n else {\n regularCharHandler(c);\n }\n }\n\n return cReturned.value_or(c);\n\n}\n\nssize_t read(int fd, void *buf, size_t count) {\n\n ssize_t returnValue;\n static thread_local ReadSignature realRead = nullptr;\n\n if (fd == 0) { \/\/ TODO: make it look good\n if (printBuffer.length()) {\n \/\/ Return printBuffer to bash one char at time\n *reinterpret_cast(buf) = *printBufferPos;\n *lineBufferPos++ = *printBufferPos++;\n if (printBufferPos == printBuffer.end()) {\n printBuffer.erase(printBuffer.begin(), printBuffer.end());\n }\n return 1;\n }\n }\n\n if (!realRead)\n realRead = reinterpret_cast(dlsym(RTLD_NEXT, \"read\"));\n\n returnValue = realRead(fd, buf, count);\n\n if (fd == 0 && isatty(fileno(stdin)))\n *reinterpret_cast(buf) = yebash(*reinterpret_cast(buf));\n\n return returnValue;\n}\n\n\n<|endoftext|>"} {"text":"#include \n#include \"robot_utils\/ros_thread_image.h\"\n\n\nclass ROSThreadImageTester\n{\n ros::NodeHandle nh;\n std::string name;\n\n image_transport::ImageTransport it;\n image_transport::Publisher image_pub;\n\npublic:\n explicit ROSThreadImageTester(std::string _name = \"test\") : name(_name), it(nh)\n {\n image_pub = it.advertise(\"\/\"+name+\"\/image\", 1);\n }\n\n void sendTestImage()\n {\n \/\/ Let's create a 200x200 black image with a red circle in the center\n cv::Mat img(200, 200, CV_8UC3, cv::Scalar(0,0,0));\n cv::circle(img, cv::Point(100, 100), 20, CV_RGB(255,0,0), -1);\n\n \/\/ Publish the image\n sensor_msgs::ImagePtr msg = cv_bridge::CvImage(std_msgs::Header(), \"bgr8\", img).toImageMsg();\n image_pub.publish(msg);\n }\n\n ~ROSThreadImageTester() {}\n};\n\nclass ROSImageInstance: public ROSThreadImage\n{\nprivate:\n cv::Point avg_coords;\n\npublic:\n explicit ROSImageInstance(std::string _name): ROSThreadImage(_name)\n {\n avg_coords = cv::Point(-1,-1);\n startThread();\n }\n\n void InternalThreadEntry()\n {\n while(ros::ok() && not isClosing())\n {\n cv::Mat img_in;\n\n if (not _img_empty)\n {\n \/\/ ROS_INFO(\"Processing image\");\n {\n std::lock_guard lock(mutex_img);\n img_in=_curr_img;\n }\n\n \/\/ Convert image to black and white\n cv::Mat gray;\n cv::cvtColor(img_in, gray, CV_BGR2GRAY);\n\n \/\/ Find contours\n std::vector> contours;\n findContours(gray, contours, CV_RETR_TREE, CV_CHAIN_APPROX_NONE, cv::Point(0,0));\n\n \/\/ Finds the moments\n std::vector mu(contours.size() );\n for(size_t i = 0; i < contours.size(); i++ )\n {\n mu[i] = moments(contours[i], false );\n }\n\n \/\/ Finds the centroid\n std::vector mc(contours.size());\n for( size_t i = 0; i < contours.size(); i++ )\n {\n mc[i] = cv::Point2f( mu[i].m10\/mu[i].m00 , mu[i].m01\/mu[i].m00 );\n avg_coords.x = mu[i].m10\/mu[i].m00;\n avg_coords.y = mu[i].m01\/mu[i].m00;\n }\n\n break;\n }\n r.sleep();\n }\n }\n\n \/\/Self explaining return methods\n cv::Point centroid() {return avg_coords; }\n\n};\n\n\nTEST(rosimagetest, testinternalthreadentry)\n{\n \/\/ Creates an object that sends a 200x200 black image with a red circle overlaid\n ROSThreadImageTester rtit(\"test\");\n\n \/\/ Creates an object responsible for receiving an image\n \/\/ and finding the centroid of a contour\n ROSImageInstance rtii(\"test\");\n\n \/\/ Sends a 200x200 image with a red circle overlayed in the middle\n rtit.sendTestImage();\n\n \/\/ Waits so that threads can finish\n ros::Rate rate(100);\n\n while(ros::ok() && (rtii.centroid() == cv::Point(-1,-1)))\n {\n \/\/ ROS_INFO(\"Waiting for ROSThreadImage loop. [x y]: [%i %i]\",\n \/\/ rtii.centroid().x, rtii.centroid(),y);\n rate.sleep();\n }\n\n \/\/ Checks that x and y coordinates are correct against expected values\n EXPECT_EQ(rtii.centroid(), cv::Point(100, 100));\n}\n\n\/\/ Run all the tests that were declared with TEST()\nint main(int argc, char **argv)\n{\n ros::init(argc, argv, \"ros_thread_test\");\n testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\nMinor#include \n#include \"robot_utils\/ros_thread_image.h\"\n\n\nclass ROSThreadImageTester\n{\n ros::NodeHandle nh;\n std::string name;\n\n image_transport::ImageTransport it;\n image_transport::Publisher image_pub;\n\npublic:\n explicit ROSThreadImageTester(std::string _name = \"test\") : name(_name), it(nh)\n {\n image_pub = it.advertise(\"\/\"+name+\"\/image\", 1);\n }\n\n void sendTestImage()\n {\n \/\/ Let's create a 200x200 black image with a red circle in the center\n cv::Mat img(200, 200, CV_8UC3, cv::Scalar(0,0,0));\n cv::circle(img, cv::Point(100, 100), 20, CV_RGB(255,0,0), -1);\n\n \/\/ Publish the image\n sensor_msgs::ImagePtr msg = cv_bridge::CvImage(std_msgs::Header(), \"bgr8\", img).toImageMsg();\n image_pub.publish(msg);\n }\n\n ~ROSThreadImageTester() {}\n};\n\nclass ROSThreadImageInstance: public ROSThreadImage\n{\nprivate:\n cv::Point avg_coords;\n\npublic:\n explicit ROSThreadImageInstance(std::string _name): ROSThreadImage(_name)\n {\n avg_coords = cv::Point(-1,-1);\n startThread();\n }\n\n void InternalThreadEntry()\n {\n while(ros::ok() && not isClosing())\n {\n cv::Mat img_in;\n\n if (not _img_empty)\n {\n \/\/ ROS_INFO(\"Processing image\");\n {\n std::lock_guard lock(mutex_img);\n img_in=_curr_img;\n }\n\n \/\/ Convert image to black and white\n cv::Mat gray;\n cv::cvtColor(img_in, gray, CV_BGR2GRAY);\n\n \/\/ Find contours\n std::vector> contours;\n findContours(gray, contours, CV_RETR_TREE, CV_CHAIN_APPROX_NONE, cv::Point(0,0));\n\n \/\/ Finds the moments\n std::vector mu(contours.size() );\n for(size_t i = 0; i < contours.size(); i++ )\n {\n mu[i] = moments(contours[i], false );\n }\n\n \/\/ Finds the centroid\n std::vector mc(contours.size());\n for( size_t i = 0; i < contours.size(); i++ )\n {\n mc[i] = cv::Point2f( mu[i].m10\/mu[i].m00 , mu[i].m01\/mu[i].m00 );\n avg_coords.x = mu[i].m10\/mu[i].m00;\n avg_coords.y = mu[i].m01\/mu[i].m00;\n }\n\n break;\n }\n r.sleep();\n }\n }\n\n \/\/Self explaining return methods\n cv::Point centroid() {return avg_coords; }\n\n};\n\n\nTEST(rosimagetest, testinternalthreadentry)\n{\n \/\/ Creates an object that sends a 200x200 black image with a red circle overlaid\n ROSThreadImageTester rtit(\"test\");\n\n \/\/ Creates an object responsible for receiving an image\n \/\/ and finding the centroid of a contour\n ROSThreadImageInstance rtii(\"test\");\n\n \/\/ Sends a 200x200 image with a red circle overlayed in the middle\n rtit.sendTestImage();\n\n \/\/ Waits so that threads can finish\n ros::Rate rate(100);\n\n while(ros::ok() && (rtii.centroid() == cv::Point(-1,-1)))\n {\n \/\/ ROS_INFO(\"Waiting for ROSThreadImage loop. [x y]: [%i %i]\",\n \/\/ rtii.centroid().x, rtii.centroid(),y);\n rate.sleep();\n }\n\n \/\/ Checks that x and y coordinates are correct against expected values\n EXPECT_EQ(rtii.centroid(), cv::Point(100, 100));\n}\n\n\/\/ Run all the tests that were declared with TEST()\nint main(int argc, char **argv)\n{\n ros::init(argc, argv, \"ros_thread_test\");\n testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2011, Blender Foundation.\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 2\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\n#include \n\n#include \"blender_sync.h\"\n#include \"blender_session.h\"\n\n#include \"util_opengl.h\"\n#include \"util_path.h\"\n\nCCL_NAMESPACE_BEGIN\n\nstatic PyObject *init_func(PyObject *self, PyObject *args)\n{\n\tconst char *path;\n\n\tif(!PyArg_ParseTuple(args, \"s\", &path))\n\t\treturn NULL;\n\t\n\tpath_init(path);\n\n\tPy_INCREF(Py_None);\n\treturn Py_None;\n}\n\nstatic PyObject *create_func(PyObject *self, PyObject *args)\n{\n\tPyObject *pyengine, *pydata, *pyscene, *pyregion, *pyv3d, *pyrv3d;\n\n\tif(!PyArg_ParseTuple(args, \"OOOOOO\", &pyengine, &pydata, &pyscene, &pyregion, &pyv3d, &pyrv3d))\n\t\treturn NULL;\n\n\t\/* RNA *\/\n\tPointerRNA engineptr;\n\tRNA_pointer_create(NULL, &RNA_RenderEngine, (void*)PyLong_AsVoidPtr(pyengine), &engineptr);\n\tBL::RenderEngine engine(engineptr);\n\n\tPointerRNA dataptr;\n\tRNA_id_pointer_create((ID*)PyLong_AsVoidPtr(pydata), &dataptr);\n\tBL::BlendData data(dataptr);\n\n\tPointerRNA sceneptr;\n\tRNA_id_pointer_create((ID*)PyLong_AsVoidPtr(pyscene), &sceneptr);\n\tBL::Scene scene(sceneptr);\n\n\tPointerRNA regionptr;\n\tRNA_id_pointer_create((ID*)PyLong_AsVoidPtr(pyregion), ®ionptr);\n\tBL::Region region(regionptr);\n\n\tPointerRNA v3dptr;\n\tRNA_id_pointer_create((ID*)PyLong_AsVoidPtr(pyv3d), &v3dptr);\n\tBL::SpaceView3D v3d(v3dptr);\n\n\tPointerRNA rv3dptr;\n\tRNA_id_pointer_create((ID*)PyLong_AsVoidPtr(pyrv3d), &rv3dptr);\n\tBL::RegionView3D rv3d(rv3dptr);\n\n\t\/* create session *\/\n\tBlenderSession *session;\n\n\tif(rv3d) {\n\t\t\/* interactive session *\/\n\t\tint width = region.width();\n\t\tint height = region.height();\n\n\t\tsession = new BlenderSession(engine, data, scene, v3d, rv3d, width, height);\n\t}\n\telse {\n\t\t\/* offline session *\/\n\t\tsession = new BlenderSession(engine, data, scene);\n\t}\n\t\n\treturn PyLong_FromVoidPtr(session);\n}\n\nstatic PyObject *free_func(PyObject *self, PyObject *args)\n{\n\tPyObject *pysession;\n\n\tif(!PyArg_ParseTuple(args, \"O\", &pysession))\n\t\treturn NULL;\n\n\tdelete (BlenderSession*)PyLong_AsVoidPtr(pysession);\n\n\tPy_INCREF(Py_None);\n\treturn Py_None;\n}\n\nstatic PyObject *render_func(PyObject *self, PyObject *args)\n{\n\tPyObject *pysession;\n\n\tif(!PyArg_ParseTuple(args, \"O\", &pysession))\n\t\treturn NULL;\n\t\n\tPy_BEGIN_ALLOW_THREADS\n\n\tBlenderSession *session = (BlenderSession*)PyLong_AsVoidPtr(pysession);\n\tsession->render();\n\n\tPy_END_ALLOW_THREADS\n\n\tPy_INCREF(Py_None);\n\treturn Py_None;\n}\n\nstatic PyObject *draw_func(PyObject *self, PyObject *args)\n{\n\tPyObject *pysession, *pyv3d, *pyrv3d;\n\n\tif(!PyArg_ParseTuple(args, \"OOO\", &pysession, &pyv3d, &pyrv3d))\n\t\treturn NULL;\n\t\n\tBlenderSession *session = (BlenderSession*)PyLong_AsVoidPtr(pysession);\n\n\tbool draw_text = false;\n\n\tif(PyLong_AsVoidPtr(pyrv3d)) {\n\t\t\/* 3d view drawing *\/\n\t\tint viewport[4];\n\t\tglGetIntegerv(GL_VIEWPORT, viewport);\n\n\t\tdraw_text = session->draw(viewport[2], viewport[3]);\n\t}\n\telse {\n\t\t\/* image editor drawing *\/\n\t\tdraw_text = session->draw();\n\t}\n\n\t\/* draw *\/\n\tPyObject *ret = PyTuple_New(2);\n\n\tif(!draw_text) {\n\t\tPyTuple_SetItem(ret, 0, PyUnicode_FromString(\"\"));\n\t\tPyTuple_SetItem(ret, 1, PyUnicode_FromString(\"\"));\n\t}\n\telse {\n\t\tstring status, substatus;\n\n\t\tsession->get_status(status, substatus);\n\n\t\tPyTuple_SetItem(ret, 0, PyUnicode_FromString(status.c_str()));\n\t\tPyTuple_SetItem(ret, 1, PyUnicode_FromString(substatus.c_str()));\n\t}\n\n\treturn ret;\n}\n\nstatic PyObject *sync_func(PyObject *self, PyObject *args)\n{\n\tPyObject *pysession;\n\n\tif(!PyArg_ParseTuple(args, \"O\", &pysession))\n\t\treturn NULL;\n\n\tBlenderSession *session = (BlenderSession*)PyLong_AsVoidPtr(pysession);\n\tsession->synchronize();\n\n\tPy_INCREF(Py_None);\n\treturn Py_None;\n}\n\nstatic PyObject *available_devices_func(PyObject *self, PyObject *args)\n{\n\tvector types = Device::available_types();\n\n\tPyObject *ret = PyTuple_New(types.size());\n\n\tfor(size_t i = 0; i < types.size(); i++) {\n\t\tstring name = Device::string_from_type(types[i]);\n\t\tPyTuple_SetItem(ret, i, PyUnicode_FromString(name.c_str()));\n\t}\n\n\treturn ret;\n}\n\nstatic PyObject *with_osl_func(PyObject *self, PyObject *args)\n{\n#ifdef WITH_OSL\n\tPyObject *ret = Py_True;\n#else\n\tPyObject *ret = Py_False;\n#endif\n\n\treturn Py_INCREF(ret), ret;\n}\n\nstatic PyMethodDef methods[] = {\n\t{\"init\", init_func, METH_VARARGS, \"\"},\n\t{\"create\", create_func, METH_VARARGS, \"\"},\n\t{\"free\", free_func, METH_VARARGS, \"\"},\n\t{\"render\", render_func, METH_VARARGS, \"\"},\n\t{\"draw\", draw_func, METH_VARARGS, \"\"},\n\t{\"sync\", sync_func, METH_VARARGS, \"\"},\n\t{\"available_devices\", available_devices_func, METH_NOARGS, \"\"},\n\t{\"with_osl\", with_osl_func, METH_NOARGS, \"\"},\n\t{NULL, NULL},\n};\n\nstatic struct PyModuleDef module = {\n\tPyModuleDef_HEAD_INIT,\n\t\"libcycles_blender\",\n\t\"Blender RNA to render exporter\",\n\t-1,\n\tmethods\n};\n\nCCL_NAMESPACE_END\n\nPyMODINIT_FUNC PyInit_libcycles_blender() \n{\n\treturn PyModule_Create(&ccl::module);\n}\n\nCycles: compile warning fixes.\/*\n * Copyright 2011, Blender Foundation.\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 2\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\n#include \n\n#include \"blender_sync.h\"\n#include \"blender_session.h\"\n\n#include \"util_opengl.h\"\n#include \"util_path.h\"\n\nCCL_NAMESPACE_BEGIN\n\nstatic PyObject *init_func(PyObject *self, PyObject *args)\n{\n\tconst char *path;\n\n\tif(!PyArg_ParseTuple(args, \"s\", &path))\n\t\treturn NULL;\n\t\n\tpath_init(path);\n\n\tPy_INCREF(Py_None);\n\treturn Py_None;\n}\n\nstatic PyObject *create_func(PyObject *self, PyObject *args)\n{\n\tPyObject *pyengine, *pydata, *pyscene, *pyregion, *pyv3d, *pyrv3d;\n\n\tif(!PyArg_ParseTuple(args, \"OOOOOO\", &pyengine, &pydata, &pyscene, &pyregion, &pyv3d, &pyrv3d))\n\t\treturn NULL;\n\n\t\/* RNA *\/\n\tPointerRNA engineptr;\n\tRNA_pointer_create(NULL, &RNA_RenderEngine, (void*)PyLong_AsVoidPtr(pyengine), &engineptr);\n\tBL::RenderEngine engine(engineptr);\n\n\tPointerRNA dataptr;\n\tRNA_id_pointer_create((ID*)PyLong_AsVoidPtr(pydata), &dataptr);\n\tBL::BlendData data(dataptr);\n\n\tPointerRNA sceneptr;\n\tRNA_id_pointer_create((ID*)PyLong_AsVoidPtr(pyscene), &sceneptr);\n\tBL::Scene scene(sceneptr);\n\n\tPointerRNA regionptr;\n\tRNA_id_pointer_create((ID*)PyLong_AsVoidPtr(pyregion), ®ionptr);\n\tBL::Region region(regionptr);\n\n\tPointerRNA v3dptr;\n\tRNA_id_pointer_create((ID*)PyLong_AsVoidPtr(pyv3d), &v3dptr);\n\tBL::SpaceView3D v3d(v3dptr);\n\n\tPointerRNA rv3dptr;\n\tRNA_id_pointer_create((ID*)PyLong_AsVoidPtr(pyrv3d), &rv3dptr);\n\tBL::RegionView3D rv3d(rv3dptr);\n\n\t\/* create session *\/\n\tBlenderSession *session;\n\n\tif(rv3d) {\n\t\t\/* interactive session *\/\n\t\tint width = region.width();\n\t\tint height = region.height();\n\n\t\tsession = new BlenderSession(engine, data, scene, v3d, rv3d, width, height);\n\t}\n\telse {\n\t\t\/* offline session *\/\n\t\tsession = new BlenderSession(engine, data, scene);\n\t}\n\t\n\treturn PyLong_FromVoidPtr(session);\n}\n\nstatic PyObject *free_func(PyObject *self, PyObject *args)\n{\n\tPyObject *pysession;\n\n\tif(!PyArg_ParseTuple(args, \"O\", &pysession))\n\t\treturn NULL;\n\n\tdelete (BlenderSession*)PyLong_AsVoidPtr(pysession);\n\n\tPy_INCREF(Py_None);\n\treturn Py_None;\n}\n\nstatic PyObject *render_func(PyObject *self, PyObject *args)\n{\n\tPyObject *pysession;\n\n\tif(!PyArg_ParseTuple(args, \"O\", &pysession))\n\t\treturn NULL;\n\t\n\tPy_BEGIN_ALLOW_THREADS\n\n\tBlenderSession *session = (BlenderSession*)PyLong_AsVoidPtr(pysession);\n\tsession->render();\n\n\tPy_END_ALLOW_THREADS\n\n\tPy_INCREF(Py_None);\n\treturn Py_None;\n}\n\nstatic PyObject *draw_func(PyObject *self, PyObject *args)\n{\n\tPyObject *pysession, *pyv3d, *pyrv3d;\n\n\tif(!PyArg_ParseTuple(args, \"OOO\", &pysession, &pyv3d, &pyrv3d))\n\t\treturn NULL;\n\t\n\tBlenderSession *session = (BlenderSession*)PyLong_AsVoidPtr(pysession);\n\n\tbool draw_text = false;\n\n\tif(PyLong_AsVoidPtr(pyrv3d)) {\n\t\t\/* 3d view drawing *\/\n\t\tint viewport[4];\n\t\tglGetIntegerv(GL_VIEWPORT, viewport);\n\n\t\tdraw_text = session->draw(viewport[2], viewport[3]);\n\t}\n\telse {\n\t\t\/* image editor drawing *\/\n\t\tdraw_text = session->draw();\n\t}\n\n\t\/* draw *\/\n\tPyObject *ret = PyTuple_New(2);\n\n\tif(!draw_text) {\n\t\tPyTuple_SetItem(ret, 0, PyUnicode_FromString(\"\"));\n\t\tPyTuple_SetItem(ret, 1, PyUnicode_FromString(\"\"));\n\t}\n\telse {\n\t\tstring status, substatus;\n\n\t\tsession->get_status(status, substatus);\n\n\t\tPyTuple_SetItem(ret, 0, PyUnicode_FromString(status.c_str()));\n\t\tPyTuple_SetItem(ret, 1, PyUnicode_FromString(substatus.c_str()));\n\t}\n\n\treturn ret;\n}\n\nstatic PyObject *sync_func(PyObject *self, PyObject *args)\n{\n\tPyObject *pysession;\n\n\tif(!PyArg_ParseTuple(args, \"O\", &pysession))\n\t\treturn NULL;\n\n\tBlenderSession *session = (BlenderSession*)PyLong_AsVoidPtr(pysession);\n\tsession->synchronize();\n\n\tPy_INCREF(Py_None);\n\treturn Py_None;\n}\n\nstatic PyObject *available_devices_func(PyObject *self, PyObject *args)\n{\n\tvector types = Device::available_types();\n\n\tPyObject *ret = PyTuple_New(types.size());\n\n\tfor(size_t i = 0; i < types.size(); i++) {\n\t\tstring name = Device::string_from_type(types[i]);\n\t\tPyTuple_SetItem(ret, i, PyUnicode_FromString(name.c_str()));\n\t}\n\n\treturn ret;\n}\n\nstatic PyObject *with_osl_func(PyObject *self, PyObject *args)\n{\n#ifdef WITH_OSL\n\tPyObject *ret = Py_True;\n#else\n\tPyObject *ret = Py_False;\n#endif\n\n\treturn Py_INCREF(ret), ret;\n}\n\nstatic PyMethodDef methods[] = {\n\t{\"init\", init_func, METH_VARARGS, \"\"},\n\t{\"create\", create_func, METH_VARARGS, \"\"},\n\t{\"free\", free_func, METH_VARARGS, \"\"},\n\t{\"render\", render_func, METH_VARARGS, \"\"},\n\t{\"draw\", draw_func, METH_VARARGS, \"\"},\n\t{\"sync\", sync_func, METH_VARARGS, \"\"},\n\t{\"available_devices\", available_devices_func, METH_NOARGS, \"\"},\n\t{\"with_osl\", with_osl_func, METH_NOARGS, \"\"},\n\t{NULL, NULL, 0, NULL},\n};\n\nstatic struct PyModuleDef module = {\n\tPyModuleDef_HEAD_INIT,\n\t\"libcycles_blender\",\n\t\"Blender RNA to render exporter\",\n\t-1,\n\tmethods,\n\tNULL, NULL, NULL, NULL\n};\n\nCCL_NAMESPACE_END\n\nPyMODINIT_FUNC PyInit_libcycles_blender() \n{\n\treturn PyModule_Create(&ccl::module);\n}\n\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"util\/Startup.h\"\n\nusing namespace std;\nusing namespace Poco;\nusing namespace Poco::Util;\nusing namespace BeeeOn;\n\nstatic Option optConfig(\"config\", \"c\",\n\t\t\"general configuration file to be used (xml, ini, properties)\",\n\t\tfalse,\n\t\t\"\",\n\t\ttrue);\nstatic Option optServices(\"services\", \"s\",\n\t\t\"services configuration file to be used (xml, ini, properties)\",\n\t\tfalse,\n\t\t\"\",\n\t\ttrue);\nstatic Option optLogging(\"logging\", \"l\",\n\t\t\"logging configuration file to be used (xml, ini, properties)\",\n\t\tfalse,\n\t\t\"\",\n\t\ttrue);\nstatic Option optLogLevel(\"log-level\", \"L\",\n\t\t\"change startup log-level (trace, debug, [info],\"\n\t\t\" notice, warn, error, fatal, trace)\",\n\t\tfalse,\n\t\t\"\",\n\t\ttrue);\nstatic Option optPort(\"port\", \"p\",\n\t\t\"server port to listen on\",\n\t\tfalse,\n\t\t\"\",\n\t\ttrue);\nstatic Option optDefine(\"define\", \"D\",\n\t\t\"define configuration options (to override configuration files)\",\n\t\tfalse,\n\t\t\"=\",\n\t\ttrue);\nstatic Option optHelp(\"help\", \"h\", \"print help\");\n\nint ServerStartup::parseLogLevel(const string &level)\n{\n\tif (icompare(level, \"info\") == 0)\n\t\treturn Message::PRIO_INFORMATION;\n\tif (icompare(level, \"warn\") == 0)\n\t\treturn Message::PRIO_WARNING;\n\tif (icompare(level, \"err\") == 0)\n\t\treturn Message::PRIO_ERROR;\n\tif (icompare(level, \"crit\") == 0)\n\t\treturn Message::PRIO_CRITICAL;\n\n\treturn Logger::parseLevel(level);\n}\n\nvoid ServerStartup::overrideConfig(const string text)\n{\n\tStringTokenizer tokenizer(text, \"=\", StringTokenizer::TOK_TRIM);\n\tif (tokenizer.count() != 2)\n\t\tthrow InvalidArgumentException(\"-D option requires a = pair\");\n\n\tlogger().debug(\"overriding \" + tokenizer[0] + \" = \" + tokenizer[1],\n\t\t\t__FILE__, __LINE__);\n\tconfig().setString(tokenizer[0], tokenizer[1]);\n}\n\nvoid ServerStartup::handleOption(const string &name, const string &value)\n{\n\tif (name == \"services\")\n\t\tm_userServices = value;\n\tif (name == \"logging\")\n\t\tm_userLogging = value;\n\tif (name == \"config\")\n\t\tm_userConfig = value;\n\tif (name == \"help\")\n\t\tm_printHelp = true;\n\tif (name == \"log-level\")\n\t\tlogger().setLevel(parseLogLevel(value));\n\tif (name == \"port\")\n\t\tm_serverPort = stoi(value);\n\tif (name == \"define\")\n\t\toverrideConfig(value);\n\n\tif (m_printHelp)\n\t\tstopOptionsProcessing();\n\n\tApplication::handleOption(name, value);\n}\n\nvoid ServerStartup::loadAllConfiguration()\n{\n\tfindAndLoadConfig();\n\tfindAndLoadLogging();\n\tfindAndLoadServices();\n}\n\nstring ServerStartup::parentPath(const File &file)\n{\n\tPath path(file.path());\n\treturn path.parent().toString();\n}\n\nbool ServerStartup::readConfiguration(const File &file)\n{\n\tif (!file.exists()) {\n\t\tlogger().debug(\"configuration file \"\n\t\t\t\t+ file.path() + \" not found\");\n\t\treturn false;\n\t}\n\n\tloadConfiguration(file.path());\n\tlogger().notice(\"configuration file \"\n\t\t\t+ file.path() + \" loaded\");\n\treturn true;\n}\n\nvoid ServerStartup::findAndLoadConfig()\n{\n\tFile user(m_userConfig);\n\tFile system(defaultConfigFile());\n\n\tconfig().setString(\"config.dir\",\n\t\tconfig().getString(\"application.dir\"));\n\n\tif (!m_userConfig.empty() && readConfiguration(user))\n\t\tconfig().setString(\"config.dir\", parentPath(user));\n\telse if (readConfiguration(system))\n\t\tconfig().setString(\"config.dir\", parentPath(system));\n\telse\n\t\tlogger().warning(\"no main configration found\");\n}\n\nvoid ServerStartup::findAndLoadLogging()\n{\n\tFile user(m_userLogging);\n\tFile system(config().getString(\n\t\t\t\"ui.config.logging\", defaultLoggingFile()));\n\n\tif (!m_userLogging.empty() && readConfiguration(user))\n\t\treturn;\n\telse if (!readConfiguration(system.path()))\n\t\tlogger().warning(\"no logging configuration found\");\n}\n\nvoid ServerStartup::findAndLoadServices()\n{\n\tFile user(m_userServices);\n\tFile system(config().getString(\n\t\t\t\"ui.config.services\", defaultServicesFile()));\n\n\tif (!m_userServices.empty() && readConfiguration(user))\n\t\treturn;\n\telse if (!readConfiguration(system))\n\t\tlogger().warning(\"no services configuration found\");\n}\n\nvoid ServerStartup::initialize(Application &app)\n{\n\tif (m_printHelp)\n\t\treturn;\n\n\tloadAllConfiguration();\n\tApplication::initialize(app);\n}\n\nvoid ServerStartup::defineOptions(OptionSet &options)\n{\n\toptions.addOption(optConfig);\n\toptions.addOption(optServices);\n\toptions.addOption(optLogging);\n\toptions.addOption(optLogLevel);\n\toptions.addOption(optPort);\n\toptDefine.repeatable(true);\n\toptions.addOption(optDefine);\n\toptions.addOption(optHelp);\n\tApplication::defineOptions(options);\n}\n\nint ServerStartup::printHelp()\n{\n\tHelpFormatter help(options());\n\thelp.setCommand(config().getString(\"application.baseName\"));\n\thelp.setUnixStyle(true);\n\thelp.setWidth(80);\n\thelp.setUsage(\"[-h] ...\");\n\thelp.format(cout);\n\n\treturn 0;\n}\n\nstring ServerStartup::defaultLoggingFile() const\n{\n\tstring path(\"\/etc\");\n\treturn path + \"\/\" + m_appGroup + \"\/\" + m_appName + \"\/logging.ini\";\n}\n\nstring ServerStartup::defaultConfigFile() const\n{\n\tstring path(\"\/etc\");\n\treturn path + \"\/\" + m_appGroup + \"\/\" + m_appName + \"\/server.ini\";\n}\n\nstring ServerStartup::defaultServicesFile() const\n{\n\tstring path(\"\/etc\");\n\treturn path + \"\/\" + m_appGroup + \"\/\" + m_appName + \"\/services.xml\";\n}\n\nstatic string pocoVersion(unsigned long version = 0)\n{\n\tversion = version == 0? Environment::libraryVersion() : version;\n\n\tunsigned int major = (version >> 24) & 0xff;\n\tunsigned int minor = (version >> 16) & 0xff;\n\tunsigned int alpha = (version >> 8) & 0xff;\n\tunsigned int beta = (version >> 0) & 0xff;\n\n\treturn to_string(major) + \".\" + to_string(minor) + \".\" + to_string(alpha) + \"-\" + to_string(beta);\n}\n\nstatic string pocoLinkedVersion(void)\n{\n\treturn pocoVersion(POCO_VERSION);\n}\n\nint ServerStartup::main(const vector &args)\n{\n\tlogger().notice(\"Poco library \" + pocoVersion() + \" (headers \" + pocoLinkedVersion() + \")\");\n\n\tlogger().notice(\"OS \" + Environment::osDisplayName()\n\t\t+ \" (\" + Environment::osName() + \" \" + Environment::osVersion() + \")\");\n\tlogger().notice(\"Machine \" + Environment::osArchitecture() + \" (cores: \" + to_string(Environment::processorCount()) + \")\");\n\tlogger().debug(\"Node \" + Environment::nodeName() + \" (\" + Environment::nodeId() + \")\");\n\n\tif (m_printHelp)\n\t\treturn printHelp();\n\n\treturn execute();\n}\n\n\nint BeeeOn::generic_main(int argc, char **argv, ServerApplication &app)\n{\n\ttry {\n\t\tpoco_throw_on_signal;\n\n\t\tapp.setUnixOptions(true);\n\t\treturn app.run(argc, argv);\n\t} catch(Exception &e) {\n\t\tcerr << e.displayText() << endl;\n\t} catch(exception &e) {\n\t\tcerr << e.what() << endl;\n\t} catch(const char *s) {\n\t\tcerr << s << endl;\n\t}\n\n\treturn -1;\n}\nStartup: warn about Poco library older then recommended#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"util\/Startup.h\"\n#include \"util\/PocoVersion.h\"\n\nusing namespace std;\nusing namespace Poco;\nusing namespace Poco::Util;\nusing namespace BeeeOn;\n\nstatic Option optConfig(\"config\", \"c\",\n\t\t\"general configuration file to be used (xml, ini, properties)\",\n\t\tfalse,\n\t\t\"\",\n\t\ttrue);\nstatic Option optServices(\"services\", \"s\",\n\t\t\"services configuration file to be used (xml, ini, properties)\",\n\t\tfalse,\n\t\t\"\",\n\t\ttrue);\nstatic Option optLogging(\"logging\", \"l\",\n\t\t\"logging configuration file to be used (xml, ini, properties)\",\n\t\tfalse,\n\t\t\"\",\n\t\ttrue);\nstatic Option optLogLevel(\"log-level\", \"L\",\n\t\t\"change startup log-level (trace, debug, [info],\"\n\t\t\" notice, warn, error, fatal, trace)\",\n\t\tfalse,\n\t\t\"\",\n\t\ttrue);\nstatic Option optPort(\"port\", \"p\",\n\t\t\"server port to listen on\",\n\t\tfalse,\n\t\t\"\",\n\t\ttrue);\nstatic Option optDefine(\"define\", \"D\",\n\t\t\"define configuration options (to override configuration files)\",\n\t\tfalse,\n\t\t\"=\",\n\t\ttrue);\nstatic Option optHelp(\"help\", \"h\", \"print help\");\n\nint ServerStartup::parseLogLevel(const string &level)\n{\n\tif (icompare(level, \"info\") == 0)\n\t\treturn Message::PRIO_INFORMATION;\n\tif (icompare(level, \"warn\") == 0)\n\t\treturn Message::PRIO_WARNING;\n\tif (icompare(level, \"err\") == 0)\n\t\treturn Message::PRIO_ERROR;\n\tif (icompare(level, \"crit\") == 0)\n\t\treturn Message::PRIO_CRITICAL;\n\n\treturn Logger::parseLevel(level);\n}\n\nvoid ServerStartup::overrideConfig(const string text)\n{\n\tStringTokenizer tokenizer(text, \"=\", StringTokenizer::TOK_TRIM);\n\tif (tokenizer.count() != 2)\n\t\tthrow InvalidArgumentException(\"-D option requires a = pair\");\n\n\tlogger().debug(\"overriding \" + tokenizer[0] + \" = \" + tokenizer[1],\n\t\t\t__FILE__, __LINE__);\n\tconfig().setString(tokenizer[0], tokenizer[1]);\n}\n\nvoid ServerStartup::handleOption(const string &name, const string &value)\n{\n\tif (name == \"services\")\n\t\tm_userServices = value;\n\tif (name == \"logging\")\n\t\tm_userLogging = value;\n\tif (name == \"config\")\n\t\tm_userConfig = value;\n\tif (name == \"help\")\n\t\tm_printHelp = true;\n\tif (name == \"log-level\")\n\t\tlogger().setLevel(parseLogLevel(value));\n\tif (name == \"port\")\n\t\tm_serverPort = stoi(value);\n\tif (name == \"define\")\n\t\toverrideConfig(value);\n\n\tif (m_printHelp)\n\t\tstopOptionsProcessing();\n\n\tApplication::handleOption(name, value);\n}\n\nvoid ServerStartup::loadAllConfiguration()\n{\n\tfindAndLoadConfig();\n\tfindAndLoadLogging();\n\tfindAndLoadServices();\n}\n\nstring ServerStartup::parentPath(const File &file)\n{\n\tPath path(file.path());\n\treturn path.parent().toString();\n}\n\nbool ServerStartup::readConfiguration(const File &file)\n{\n\tif (!file.exists()) {\n\t\tlogger().debug(\"configuration file \"\n\t\t\t\t+ file.path() + \" not found\");\n\t\treturn false;\n\t}\n\n\tloadConfiguration(file.path());\n\tlogger().notice(\"configuration file \"\n\t\t\t+ file.path() + \" loaded\");\n\treturn true;\n}\n\nvoid ServerStartup::findAndLoadConfig()\n{\n\tFile user(m_userConfig);\n\tFile system(defaultConfigFile());\n\n\tconfig().setString(\"config.dir\",\n\t\tconfig().getString(\"application.dir\"));\n\n\tif (!m_userConfig.empty() && readConfiguration(user))\n\t\tconfig().setString(\"config.dir\", parentPath(user));\n\telse if (readConfiguration(system))\n\t\tconfig().setString(\"config.dir\", parentPath(system));\n\telse\n\t\tlogger().warning(\"no main configration found\");\n}\n\nvoid ServerStartup::findAndLoadLogging()\n{\n\tFile user(m_userLogging);\n\tFile system(config().getString(\n\t\t\t\"ui.config.logging\", defaultLoggingFile()));\n\n\tif (!m_userLogging.empty() && readConfiguration(user))\n\t\treturn;\n\telse if (!readConfiguration(system.path()))\n\t\tlogger().warning(\"no logging configuration found\");\n}\n\nvoid ServerStartup::findAndLoadServices()\n{\n\tFile user(m_userServices);\n\tFile system(config().getString(\n\t\t\t\"ui.config.services\", defaultServicesFile()));\n\n\tif (!m_userServices.empty() && readConfiguration(user))\n\t\treturn;\n\telse if (!readConfiguration(system))\n\t\tlogger().warning(\"no services configuration found\");\n}\n\nvoid ServerStartup::initialize(Application &app)\n{\n\tif (m_printHelp)\n\t\treturn;\n\n\tloadAllConfiguration();\n\tApplication::initialize(app);\n}\n\nvoid ServerStartup::defineOptions(OptionSet &options)\n{\n\toptions.addOption(optConfig);\n\toptions.addOption(optServices);\n\toptions.addOption(optLogging);\n\toptions.addOption(optLogLevel);\n\toptions.addOption(optPort);\n\toptDefine.repeatable(true);\n\toptions.addOption(optDefine);\n\toptions.addOption(optHelp);\n\tApplication::defineOptions(options);\n}\n\nint ServerStartup::printHelp()\n{\n\tHelpFormatter help(options());\n\thelp.setCommand(config().getString(\"application.baseName\"));\n\thelp.setUnixStyle(true);\n\thelp.setWidth(80);\n\thelp.setUsage(\"[-h] ...\");\n\thelp.format(cout);\n\n\treturn 0;\n}\n\nstring ServerStartup::defaultLoggingFile() const\n{\n\tstring path(\"\/etc\");\n\treturn path + \"\/\" + m_appGroup + \"\/\" + m_appName + \"\/logging.ini\";\n}\n\nstring ServerStartup::defaultConfigFile() const\n{\n\tstring path(\"\/etc\");\n\treturn path + \"\/\" + m_appGroup + \"\/\" + m_appName + \"\/server.ini\";\n}\n\nstring ServerStartup::defaultServicesFile() const\n{\n\tstring path(\"\/etc\");\n\treturn path + \"\/\" + m_appGroup + \"\/\" + m_appName + \"\/services.xml\";\n}\n\nstatic string pocoVersion(unsigned long version = 0)\n{\n\tversion = version == 0? Environment::libraryVersion() : version;\n\n\tunsigned int major = (version >> 24) & 0xff;\n\tunsigned int minor = (version >> 16) & 0xff;\n\tunsigned int alpha = (version >> 8) & 0xff;\n\tunsigned int beta = (version >> 0) & 0xff;\n\n\treturn to_string(major) + \".\" + to_string(minor) + \".\" + to_string(alpha) + \"-\" + to_string(beta);\n}\n\nstatic string pocoLinkedVersion(void)\n{\n\treturn pocoVersion(POCO_VERSION);\n}\n\nstatic void warnAboutPocoVersion(Logger &logger)\n{\n\tbool upgrade = false;\n\n\tif (Environment::libraryVersion() > POCO_VERSION)\n\t\tlogger.warning(\"runtime Poco library is newer than built-in headers\", __FILE__, __LINE__);\n\n\tif (POCO_VERSION < RECOMMENDED_POCO_VERSION) {\n\t\tlogger.warning(\"Poco library headers are older then recommended\",\n\t\t\t\t__FILE__, __LINE__);\n\t\tupgrade = true;\n\t}\n\n\tif (Environment::libraryVersion() < RECOMMENDED_POCO_VERSION) {\n\t\tlogger.warning(\"runtime Poco library is older then recommended\",\n\t\t\t\t__FILE__, __LINE__);\n\t\tupgrade = true;\n\t}\n\n\tif (upgrade) {\n\t\tlogger.warning(\"recommended to upgrade to Poco library \"\n\t\t\t\t+ pocoVersion(RECOMMENDED_POCO_VERSION) + \" or newer\",\n\t\t\t\t__FILE__, __LINE__);\n\t}\n}\n\nint ServerStartup::main(const vector &args)\n{\n\tlogger().notice(\"Poco library \" + pocoVersion() + \" (headers \" + pocoLinkedVersion() + \")\");\n\twarnAboutPocoVersion(logger());\n\n\tlogger().notice(\"OS \" + Environment::osDisplayName()\n\t\t+ \" (\" + Environment::osName() + \" \" + Environment::osVersion() + \")\");\n\tlogger().notice(\"Machine \" + Environment::osArchitecture() + \" (cores: \" + to_string(Environment::processorCount()) + \")\");\n\tlogger().debug(\"Node \" + Environment::nodeName() + \" (\" + Environment::nodeId() + \")\");\n\n\tif (m_printHelp)\n\t\treturn printHelp();\n\n\treturn execute();\n}\n\n\nint BeeeOn::generic_main(int argc, char **argv, ServerApplication &app)\n{\n\ttry {\n\t\tpoco_throw_on_signal;\n\n\t\tapp.setUnixOptions(true);\n\t\treturn app.run(argc, argv);\n\t} catch(Exception &e) {\n\t\tcerr << e.displayText() << endl;\n\t} catch(exception &e) {\n\t\tcerr << e.what() << endl;\n\t} catch(const char *s) {\n\t\tcerr << s << endl;\n\t}\n\n\treturn -1;\n}\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sal.hxx\"\n\/\/ autogenerated file with codegen.pl\n\n#include \n#include \n#include \n\nnamespace rtl_locale\n{\n \/\/ default locale for test purpose\n void setDefaultLocale()\n {\n rtl::OLocale::setDefault(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"de\")), rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"DE\")), \/* rtl::OUString() *\/ rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"hochdeutsch\")) );\n }\n\nclass getDefault : public CppUnit::TestFixture\n{\npublic:\n \/\/ initialise your test code values here.\n void setUp()\n {\n }\n\n void tearDown()\n {\n }\n\n \/\/ insert your test code here.\n void getDefault_000()\n {\n \/\/ this is demonstration code\n \/\/ CPPUNIT_ASSERT_MESSAGE(\"a message\", 1 == 1);\n\n \/\/ due to the fact, we set the default locale at first, this test is no longer possible\n \/\/ ::rtl::OLocale aLocale = ::rtl::OLocale::getDefault();\n \/\/ CPPUNIT_ASSERT_MESSAGE(\"locale must be null\", aLocale.getData() == NULL);\n\n }\n\n void getDefault_001()\n {\n \/\/ rtl::OLocale::setDefault(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"de\")), rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"DE\")), rtl::OUString());\n rtl::OLocale aLocale = ::rtl::OLocale::getDefault();\n CPPUNIT_ASSERT_MESSAGE(\"locale must not null\", aLocale.getData() != NULL);\n }\n\n \/\/ Change the following lines only, if you add, remove or rename\n \/\/ member functions of the current class,\n \/\/ because these macros are need by auto register mechanism.\n\n CPPUNIT_TEST_SUITE(getDefault);\n CPPUNIT_TEST(getDefault_000);\n CPPUNIT_TEST(getDefault_001);\n CPPUNIT_TEST_SUITE_END();\n}; \/\/ class getDefault\n\n\nclass setDefault : public CppUnit::TestFixture\n{\npublic:\n \/\/ initialise your test code values here.\n void setUp()\n {\n }\n\n void tearDown()\n {\n setDefaultLocale();\n }\n\n \/\/ insert your test code here.\n void setDefault_001()\n {\n rtl::OLocale::setDefault(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"en\")), rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"US\")), rtl::OUString());\n rtl::OLocale aLocale = ::rtl::OLocale::getDefault();\n CPPUNIT_ASSERT_MESSAGE(\"locale must not null\", aLocale.getData() != NULL);\n\n \/\/ be sure to not GPF\n }\n\n \/\/ Change the following lines only, if you add, remove or rename\n \/\/ member functions of the current class,\n \/\/ because these macros are need by auto register mechanism.\n\n CPPUNIT_TEST_SUITE(setDefault);\n CPPUNIT_TEST(setDefault_001);\n CPPUNIT_TEST_SUITE_END();\n}; \/\/ class setDefault\n\n\nclass getLanguage : public CppUnit::TestFixture\n{\npublic:\n \/\/ initialise your test code values here.\n void setUp()\n {\n }\n\n void tearDown()\n {\n }\n\n \/\/ insert your test code here.\n void getLanguage_001()\n {\n rtl::OLocale aLocale = ::rtl::OLocale::getDefault();\n rtl::OUString suLanguage = aLocale.getLanguage();\n t_print(\"Language: %s\\n\", rtl::OUStringToOString(suLanguage, osl_getThreadTextEncoding()).getStr());\n CPPUNIT_ASSERT_MESSAGE(\"locale language must be 'de'\", suLanguage.equals(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"de\"))));\n }\n void getLanguage_002()\n {\n rtl::OLocale aLocale = ::rtl::OLocale::getDefault();\n rtl::OUString suLanguage = rtl_locale_getLanguage(aLocale.getData());\n t_print(\"Language: %s\\n\", rtl::OUStringToOString(suLanguage, osl_getThreadTextEncoding()).getStr());\n CPPUNIT_ASSERT_MESSAGE(\"locale language must be 'de'\", suLanguage.equals(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"de\"))));\n }\n\n \/\/ Change the following lines only, if you add, remove or rename\n \/\/ member functions of the current class,\n \/\/ because these macros are need by auto register mechanism.\n\n CPPUNIT_TEST_SUITE(getLanguage);\n CPPUNIT_TEST(getLanguage_001);\n CPPUNIT_TEST(getLanguage_002);\n CPPUNIT_TEST_SUITE_END();\n}; \/\/ class getLanguage\n\n\nclass getCountry : public CppUnit::TestFixture\n{\npublic:\n \/\/ initialise your test code values here.\n void setUp()\n {\n }\n\n void tearDown()\n {\n }\n\n \/\/ insert your test code here.\n void getCountry_001()\n {\n rtl::OLocale aLocale = ::rtl::OLocale::getDefault();\n rtl::OUString suCountry = aLocale.getCountry();\n t_print(\"Country: %s\\n\", rtl::OUStringToOString(suCountry, osl_getThreadTextEncoding()).getStr());\n CPPUNIT_ASSERT_MESSAGE(\"locale country must be 'DE'\", suCountry.equals(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"DE\"))));\n }\n void getCountry_002()\n {\n rtl::OLocale aLocale = ::rtl::OLocale::getDefault();\n rtl::OUString suCountry = rtl_locale_getCountry(aLocale.getData());\n t_print(\"Country: %s\\n\", rtl::OUStringToOString(suCountry, osl_getThreadTextEncoding()).getStr());\n CPPUNIT_ASSERT_MESSAGE(\"locale country must be 'DE'\", suCountry.equals(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"DE\"))));\n }\n\n \/\/ Change the following lines only, if you add, remove or rename\n \/\/ member functions of the current class,\n \/\/ because these macros are need by auto register mechanism.\n\n CPPUNIT_TEST_SUITE(getCountry);\n CPPUNIT_TEST(getCountry_001);\n CPPUNIT_TEST(getCountry_002);\n CPPUNIT_TEST_SUITE_END();\n}; \/\/ class getCountry\n\n\nclass getVariant : public CppUnit::TestFixture\n{\npublic:\n \/\/ initialise your test code values here.\n void setUp()\n {\n }\n\n void tearDown()\n {\n }\n\n \/\/ insert your test code here.\n void getVariant_001()\n {\n rtl::OLocale aLocale = ::rtl::OLocale::getDefault();\n rtl::OUString suVariant = aLocale.getVariant();\n t_print(\"Variant: %s\\n\", rtl::OUStringToOString(suVariant, osl_getThreadTextEncoding()).getStr());\n CPPUNIT_ASSERT_MESSAGE(\"locale variant must be 'hochdeutsch'\", suVariant.equals(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"hochdeutsch\"))));\n }\n void getVariant_002()\n {\n rtl::OLocale aLocale = ::rtl::OLocale::getDefault();\n rtl::OUString suVariant = rtl_locale_getVariant(aLocale.getData());\n t_print(\"Variant: %s\\n\", rtl::OUStringToOString(suVariant, osl_getThreadTextEncoding()).getStr());\n CPPUNIT_ASSERT_MESSAGE(\"locale variant must be 'hochdeutsch'\", suVariant.equals(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"hochdeutsch\"))));\n }\n\n \/\/ Change the following lines only, if you add, remove or rename\n \/\/ member functions of the current class,\n \/\/ because these macros are need by auto register mechanism.\n\n CPPUNIT_TEST_SUITE(getVariant);\n CPPUNIT_TEST(getVariant_001);\n CPPUNIT_TEST(getVariant_002);\n CPPUNIT_TEST_SUITE_END();\n}; \/\/ class getVariant\n\n\nclass hashCode : public CppUnit::TestFixture\n{\npublic:\n \/\/ initialise your test code values here.\n void setUp()\n {\n }\n\n void tearDown()\n {\n }\n\n \/\/ insert your test code here.\n void hashCode_001()\n {\n rtl::OLocale aLocale = ::rtl::OLocale::getDefault();\n sal_Int32 nHashCode = aLocale.hashCode();\n t_print(\"Hashcode: %d\\n\", nHashCode);\n CPPUNIT_ASSERT_MESSAGE(\"locale hashcode must be 3831\", nHashCode != 0);\n }\n void hashCode_002()\n {\n rtl::OLocale aLocale = ::rtl::OLocale::getDefault();\n sal_Int32 nHashCode = rtl_locale_hashCode(aLocale.getData());\n t_print(\"Hashcode: %d\\n\", nHashCode);\n CPPUNIT_ASSERT_MESSAGE(\"locale hashcode must be 3831\", nHashCode != 0);\n }\n\n \/\/ Change the following lines only, if you add, remove or rename\n \/\/ member functions of the current class,\n \/\/ because these macros are need by auto register mechanism.\n\n CPPUNIT_TEST_SUITE(hashCode);\n CPPUNIT_TEST(hashCode_001);\n CPPUNIT_TEST(hashCode_002);\n CPPUNIT_TEST_SUITE_END();\n}; \/\/ class hashCode\n\n\nclass equals : public CppUnit::TestFixture\n{\npublic:\n \/\/ initialise your test code values here.\n void setUp()\n {\n }\n\n void tearDown()\n {\n }\n\n \/\/ insert your test code here.\n void equals_001()\n {\n rtl::OLocale aLocale1 = rtl::OLocale::registerLocale(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"en\")), rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"US\")), rtl::OUString());\n rtl::OLocale aLocale2 = rtl::OLocale::registerLocale(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"en\")), rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"US\")));\n\n sal_Bool bLocaleAreEqual = sal_False;\n bLocaleAreEqual = (aLocale1 == aLocale2);\n\n CPPUNIT_ASSERT_MESSAGE(\"check operator ==()\", bLocaleAreEqual == sal_True);\n }\n\n void equals_002()\n {\n rtl::OLocale aLocale1 = rtl::OLocale::registerLocale(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"en\")), rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"US\")), rtl::OUString());\n rtl::OLocale aLocale2 = rtl::OLocale::registerLocale(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"en\")), rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"US\")));\n\n sal_Int32 nEqual = rtl_locale_equals(aLocale1.getData(), aLocale2.getData());\n t_print(\"rtl_locale_equals() result: %d\\n\", nEqual);\n CPPUNIT_ASSERT(nEqual != 0);\n }\n\n \/\/ Change the following lines only, if you add, remove or rename\n \/\/ member functions of the current class,\n \/\/ because these macros are need by auto register mechanism.\n\n CPPUNIT_TEST_SUITE(equals);\n CPPUNIT_TEST(equals_001);\n CPPUNIT_TEST(equals_002);\n CPPUNIT_TEST_SUITE_END();\n}; \/\/ class equals\n\n\/\/ -----------------------------------------------------------------------------\nCPPUNIT_TEST_SUITE_NAMED_REGISTRATION(rtl_locale::getDefault, \"rtl_locale\");\nCPPUNIT_TEST_SUITE_NAMED_REGISTRATION(rtl_locale::setDefault, \"rtl_locale\");\nCPPUNIT_TEST_SUITE_NAMED_REGISTRATION(rtl_locale::getLanguage, \"rtl_locale\");\nCPPUNIT_TEST_SUITE_NAMED_REGISTRATION(rtl_locale::getCountry, \"rtl_locale\");\nCPPUNIT_TEST_SUITE_NAMED_REGISTRATION(rtl_locale::getVariant, \"rtl_locale\");\nCPPUNIT_TEST_SUITE_NAMED_REGISTRATION(rtl_locale::hashCode, \"rtl_locale\");\nCPPUNIT_TEST_SUITE_NAMED_REGISTRATION(rtl_locale::equals, \"rtl_locale\");\n} \/\/ namespace rtl_locale\n\n\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ this macro creates an empty function, which will called by the RegisterAllFunctions()\n\/\/ to let the user the possibility to also register some functions by hand.\n\/\/ NOADDITIONAL;\n\nvoid RegisterAdditionalFunctions(FktRegFuncPtr)\n{\n \/\/ start message\n t_print(\"Initializing ...\\n\" );\n rtl_locale::setDefaultLocale();\n t_print(\"Initialization Done.\\n\" );\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\nMake the qa\/rtl\/rtl_locale test compile again.\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sal.hxx\"\n\/\/ autogenerated file with codegen.pl\n\n#include \n#include \n\n#include \n#include \n#include \n\nnamespace rtl_locale\n{\n \/\/ default locale for test purpose\n void setDefaultLocale()\n {\n rtl::OLocale::setDefault(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"de\")), rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"DE\")), \/* rtl::OUString() *\/ rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"hochdeutsch\")) );\n }\n\nclass getDefault : public CppUnit::TestFixture\n{\npublic:\n \/\/ initialise your test code values here.\n void setUp()\n {\n \/\/ start message\n rtl_locale::setDefaultLocale();\n }\n\n void tearDown()\n {\n }\n\n \/\/ insert your test code here.\n void getDefault_000()\n {\n \/\/ this is demonstration code\n \/\/ CPPUNIT_ASSERT_MESSAGE(\"a message\", 1 == 1);\n\n \/\/ due to the fact, we set the default locale at first, this test is no longer possible\n \/\/ ::rtl::OLocale aLocale = ::rtl::OLocale::getDefault();\n \/\/ CPPUNIT_ASSERT_MESSAGE(\"locale must be null\", aLocale.getData() == NULL);\n\n }\n\n void getDefault_001()\n {\n \/\/ rtl::OLocale::setDefault(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"de\")), rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"DE\")), rtl::OUString());\n rtl::OLocale aLocale = ::rtl::OLocale::getDefault();\n CPPUNIT_ASSERT_MESSAGE(\"locale must not null\", aLocale.getData() != NULL);\n }\n\n \/\/ Change the following lines only, if you add, remove or rename\n \/\/ member functions of the current class,\n \/\/ because these macros are need by auto register mechanism.\n\n CPPUNIT_TEST_SUITE(getDefault);\n CPPUNIT_TEST(getDefault_000);\n CPPUNIT_TEST(getDefault_001);\n CPPUNIT_TEST_SUITE_END();\n}; \/\/ class getDefault\n\n\nclass setDefault : public CppUnit::TestFixture\n{\npublic:\n \/\/ initialise your test code values here.\n void setUp()\n {\n \/\/ start message\n rtl_locale::setDefaultLocale();\n }\n\n void tearDown()\n {\n setDefaultLocale();\n }\n\n \/\/ insert your test code here.\n void setDefault_001()\n {\n rtl::OLocale::setDefault(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"en\")), rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"US\")), rtl::OUString());\n rtl::OLocale aLocale = ::rtl::OLocale::getDefault();\n CPPUNIT_ASSERT_MESSAGE(\"locale must not null\", aLocale.getData() != NULL);\n\n \/\/ be sure to not GPF\n }\n\n \/\/ Change the following lines only, if you add, remove or rename\n \/\/ member functions of the current class,\n \/\/ because these macros are need by auto register mechanism.\n\n CPPUNIT_TEST_SUITE(setDefault);\n CPPUNIT_TEST(setDefault_001);\n CPPUNIT_TEST_SUITE_END();\n}; \/\/ class setDefault\n\n\nclass getLanguage : public CppUnit::TestFixture\n{\npublic:\n \/\/ initialise your test code values here.\n void setUp()\n {\n \/\/ start message\n rtl_locale::setDefaultLocale();\n }\n\n void tearDown()\n {\n }\n\n \/\/ insert your test code here.\n void getLanguage_001()\n {\n rtl::OLocale aLocale = ::rtl::OLocale::getDefault();\n rtl::OUString suLanguage = aLocale.getLanguage();\n printf(\"Language: %s\\n\", rtl::OUStringToOString(suLanguage, osl_getThreadTextEncoding()).getStr());\n CPPUNIT_ASSERT_MESSAGE(\"locale language must be 'de'\", suLanguage.equals(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"de\"))));\n }\n void getLanguage_002()\n {\n rtl::OLocale aLocale = ::rtl::OLocale::getDefault();\n rtl::OUString suLanguage = rtl_locale_getLanguage(aLocale.getData());\n printf(\"Language: %s\\n\", rtl::OUStringToOString(suLanguage, osl_getThreadTextEncoding()).getStr());\n CPPUNIT_ASSERT_MESSAGE(\"locale language must be 'de'\", suLanguage.equals(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"de\"))));\n }\n\n \/\/ Change the following lines only, if you add, remove or rename\n \/\/ member functions of the current class,\n \/\/ because these macros are need by auto register mechanism.\n\n CPPUNIT_TEST_SUITE(getLanguage);\n CPPUNIT_TEST(getLanguage_001);\n CPPUNIT_TEST(getLanguage_002);\n CPPUNIT_TEST_SUITE_END();\n}; \/\/ class getLanguage\n\n\nclass getCountry : public CppUnit::TestFixture\n{\npublic:\n \/\/ initialise your test code values here.\n void setUp()\n {\n \/\/ start message\n rtl_locale::setDefaultLocale();\n }\n\n void tearDown()\n {\n }\n\n \/\/ insert your test code here.\n void getCountry_001()\n {\n rtl::OLocale aLocale = ::rtl::OLocale::getDefault();\n rtl::OUString suCountry = aLocale.getCountry();\n printf(\"Country: %s\\n\", rtl::OUStringToOString(suCountry, osl_getThreadTextEncoding()).getStr());\n CPPUNIT_ASSERT_MESSAGE(\"locale country must be 'DE'\", suCountry.equals(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"DE\"))));\n }\n void getCountry_002()\n {\n rtl::OLocale aLocale = ::rtl::OLocale::getDefault();\n rtl::OUString suCountry = rtl_locale_getCountry(aLocale.getData());\n printf(\"Country: %s\\n\", rtl::OUStringToOString(suCountry, osl_getThreadTextEncoding()).getStr());\n CPPUNIT_ASSERT_MESSAGE(\"locale country must be 'DE'\", suCountry.equals(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"DE\"))));\n }\n\n \/\/ Change the following lines only, if you add, remove or rename\n \/\/ member functions of the current class,\n \/\/ because these macros are need by auto register mechanism.\n\n CPPUNIT_TEST_SUITE(getCountry);\n CPPUNIT_TEST(getCountry_001);\n CPPUNIT_TEST(getCountry_002);\n CPPUNIT_TEST_SUITE_END();\n}; \/\/ class getCountry\n\n\nclass getVariant : public CppUnit::TestFixture\n{\npublic:\n \/\/ initialise your test code values here.\n void setUp()\n {\n \/\/ start message\n rtl_locale::setDefaultLocale();\n }\n\n void tearDown()\n {\n }\n\n \/\/ insert your test code here.\n void getVariant_001()\n {\n rtl::OLocale aLocale = ::rtl::OLocale::getDefault();\n rtl::OUString suVariant = aLocale.getVariant();\n printf(\"Variant: %s\\n\", rtl::OUStringToOString(suVariant, osl_getThreadTextEncoding()).getStr());\n CPPUNIT_ASSERT_MESSAGE(\"locale variant must be 'hochdeutsch'\", suVariant.equals(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"hochdeutsch\"))));\n }\n void getVariant_002()\n {\n rtl::OLocale aLocale = ::rtl::OLocale::getDefault();\n rtl::OUString suVariant = rtl_locale_getVariant(aLocale.getData());\n printf(\"Variant: %s\\n\", rtl::OUStringToOString(suVariant, osl_getThreadTextEncoding()).getStr());\n CPPUNIT_ASSERT_MESSAGE(\"locale variant must be 'hochdeutsch'\", suVariant.equals(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"hochdeutsch\"))));\n }\n\n \/\/ Change the following lines only, if you add, remove or rename\n \/\/ member functions of the current class,\n \/\/ because these macros are need by auto register mechanism.\n\n CPPUNIT_TEST_SUITE(getVariant);\n CPPUNIT_TEST(getVariant_001);\n CPPUNIT_TEST(getVariant_002);\n CPPUNIT_TEST_SUITE_END();\n}; \/\/ class getVariant\n\n\nclass hashCode : public CppUnit::TestFixture\n{\npublic:\n \/\/ initialise your test code values here.\n void setUp()\n {\n \/\/ start message\n rtl_locale::setDefaultLocale();\n }\n\n void tearDown()\n {\n }\n\n \/\/ insert your test code here.\n void hashCode_001()\n {\n rtl::OLocale aLocale = ::rtl::OLocale::getDefault();\n sal_Int32 nHashCode = aLocale.hashCode();\n printf(\"Hashcode: %d\\n\", nHashCode);\n CPPUNIT_ASSERT_MESSAGE(\"locale hashcode must be 3831\", nHashCode != 0);\n }\n void hashCode_002()\n {\n rtl::OLocale aLocale = ::rtl::OLocale::getDefault();\n sal_Int32 nHashCode = rtl_locale_hashCode(aLocale.getData());\n printf(\"Hashcode: %d\\n\", nHashCode);\n CPPUNIT_ASSERT_MESSAGE(\"locale hashcode must be 3831\", nHashCode != 0);\n }\n\n \/\/ Change the following lines only, if you add, remove or rename\n \/\/ member functions of the current class,\n \/\/ because these macros are need by auto register mechanism.\n\n CPPUNIT_TEST_SUITE(hashCode);\n CPPUNIT_TEST(hashCode_001);\n CPPUNIT_TEST(hashCode_002);\n CPPUNIT_TEST_SUITE_END();\n}; \/\/ class hashCode\n\n\nclass equals : public CppUnit::TestFixture\n{\npublic:\n \/\/ initialise your test code values here.\n void setUp()\n {\n \/\/ start message\n rtl_locale::setDefaultLocale();\n }\n\n void tearDown()\n {\n }\n\n \/\/ insert your test code here.\n void equals_001()\n {\n rtl::OLocale aLocale1 = rtl::OLocale::registerLocale(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"en\")), rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"US\")), rtl::OUString());\n rtl::OLocale aLocale2 = rtl::OLocale::registerLocale(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"en\")), rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"US\")));\n\n sal_Bool bLocaleAreEqual = sal_False;\n bLocaleAreEqual = (aLocale1 == aLocale2);\n\n CPPUNIT_ASSERT_MESSAGE(\"check operator ==()\", bLocaleAreEqual == sal_True);\n }\n\n void equals_002()\n {\n rtl::OLocale aLocale1 = rtl::OLocale::registerLocale(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"en\")), rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"US\")), rtl::OUString());\n rtl::OLocale aLocale2 = rtl::OLocale::registerLocale(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"en\")), rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(\"US\")));\n\n sal_Int32 nEqual = rtl_locale_equals(aLocale1.getData(), aLocale2.getData());\n printf(\"rtl_locale_equals() result: %d\\n\", nEqual);\n CPPUNIT_ASSERT(nEqual != 0);\n }\n\n \/\/ Change the following lines only, if you add, remove or rename\n \/\/ member functions of the current class,\n \/\/ because these macros are need by auto register mechanism.\n\n CPPUNIT_TEST_SUITE(equals);\n CPPUNIT_TEST(equals_001);\n CPPUNIT_TEST(equals_002);\n CPPUNIT_TEST_SUITE_END();\n}; \/\/ class equals\n\n\/\/ -----------------------------------------------------------------------------\nCPPUNIT_TEST_SUITE_REGISTRATION(rtl_locale::getDefault);\nCPPUNIT_TEST_SUITE_REGISTRATION(rtl_locale::setDefault);\nCPPUNIT_TEST_SUITE_REGISTRATION(rtl_locale::getLanguage);\nCPPUNIT_TEST_SUITE_REGISTRATION(rtl_locale::getCountry);\nCPPUNIT_TEST_SUITE_REGISTRATION(rtl_locale::getVariant);\nCPPUNIT_TEST_SUITE_REGISTRATION(rtl_locale::hashCode);\nCPPUNIT_TEST_SUITE_REGISTRATION(rtl_locale::equals);\n} \/\/ namespace rtl_locale\n\n\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ this macro creates an empty function, which will called by the RegisterAllFunctions()\n\/\/ to let the user the possibility to also register some functions by hand.\n\nCPPUNIT_PLUGIN_IMPLEMENT();\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"#ifndef PROCESSO_H \/\/include de guarda para evitar redefinicao da classe caso ela seja incluida em mais de um cpp\n#define PROCESSO_H\n#include \/\/para usar o std::cout e facilitar a impressao das informcoes na tela\n\/\/TODO: fazer metodo para calcular offset de memoria\nclass processo{\n\/\/Inicio da definicao das variaveis do processo\nprivate:\n\t\/\/Inicio da definicao da estrutura contida no arquivo processes.txt\n\tint tempo_inicializacao, tempo_processador;\n\tint prioridade;\n\tint blocos_em_memoria;\n\tbool requisicao_impressora,requisicao_scanner,requisicao_modem;\n\tint codigo_disco;\n\t\/\/Fim da definicao da estrutura contida no arquivo processes.txt\n\n\t\/\/Inicio da definicao de outras variaveis que devem aparecer na tela, mas nao estao no txt\n\t\tint Offset_da_memoria;\/\/uma variavel que pode ser calculada \n\t\/*\n\t\tObservacao: cada processo sera colocado em uma estrutura de vetor \n\t\t(std::vector). Logo, seu PID (ID do processo) pode ser entendido como\n\t\to indice atual do vetor + 1 (+ 1, pois o PID comeca em 1 ). Por esse motivo,\n\t\ta classe processo nao possui a variavel PID\n\t*\/\n\t\/\/Fim da definicao de outras variaveis que devem aparecer na tela, mas nao estao no txt\n\/\/Fim da definicao das variaveis do processo\n\n\/\/Inicio da definicao dos metodos do processo\n\npublic:\n\tprocesso();\/\/construtor sem argumentos de entrada permite nao precisar passar todos os argumentos da classe de uma vez \n\t\/\/Inicio da declaracao dos setters\n\tvoid set_tempos(int,int);\/\/tempos de inicializacao e de processador respectivamente\n\tvoid set_requisicoes(bool,bool,bool);\/\/requisicoes de impressora,scanner e modem respectivamente\n\tvoid set_prioridade(int);\n\tvoid set_blocos_memoria(int);\n\tvoid set_codigo_disco(int);\n\t\/\/Fim da declaracao dos setters\n\n\t\/\/Inicio da declaracao dos getters\n\tint get_tempo_inicializacao();\n\tint get_tempo_processador();\n\tbool get_requisicao_impressora();\n\tbool get_requisicao_scanner();\n\tbool get_requisicao_modem();\n\tint get_prioridade();\n\tint get_blocos_memoria();\n\tint get_codigo_disco();\n\t\/\/Fim da declaracao dos getters\n\tvoid imprime_infomacoes_processo(int);\/\/sera passado a ele o PID\n\/\/Fim da definicao dos metodos do processo\n};\n#endifAdição do atributo \"início\"#ifndef PROCESSO_H \/\/include de guarda para evitar redefinicao da classe caso ela seja incluida em mais de um cpp\n#define PROCESSO_H\n#include \/\/para usar o std::cout e facilitar a impressao das informcoes na tela\n\/\/TODO: fazer metodo para calcular offset de memoria\nclass processo{\n\/\/Inicio da definicao das variaveis do processo\nprivate:\n\t\/\/Inicio da definicao da estrutura contida no arquivo processes.txt\n\tint tempo_inicializacao, tempo_processador;\n\tint prioridade;\n\tint blocos_em_memoria;\n\tint inicio;\n\tbool requisicao_impressora,requisicao_scanner,requisicao_modem;\n\tint codigo_disco;\n\t\/\/Fim da definicao da estrutura contida no arquivo processes.txt\n\n\t\/\/Inicio da definicao de outras variaveis que devem aparecer na tela, mas nao estao no txt\n\t\tint Offset_da_memoria;\/\/uma variavel que pode ser calculada \n\t\/*\n\t\tObservacao: cada processo sera colocado em uma estrutura de vetor \n\t\t(std::vector). Logo, seu PID (ID do processo) pode ser entendido como\n\t\to indice atual do vetor + 1 (+ 1, pois o PID comeca em 1 ). Por esse motivo,\n\t\ta classe processo nao possui a variavel PID\n\t*\/\n\t\/\/Fim da definicao de outras variaveis que devem aparecer na tela, mas nao estao no txt\n\/\/Fim da definicao das variaveis do processo\n\n\/\/Inicio da definicao dos metodos do processo\n\npublic:\n\tprocesso();\/\/construtor sem argumentos de entrada permite nao precisar passar todos os argumentos da classe de uma vez \n\t\/\/Inicio da declaracao dos setters\n\tvoid set_tempos(int,int);\/\/tempos de inicializacao e de processador respectivamente\n\tvoid set_requisicoes(bool,bool,bool);\/\/requisicoes de impressora,scanner e modem respectivamente\n\tvoid set_prioridade(int);\n\tvoid set_blocos_memoria(int);\n\tvoid set_inicio(int);\n\tvoid set_codigo_disco(int);\n\t\/\/Fim da declaracao dos setters\n\n\t\/\/Inicio da declaracao dos getters\n\tint get_tempo_inicializacao();\n\tint get_tempo_processador();\n\tbool get_requisicao_impressora();\n\tbool get_requisicao_scanner();\n\tbool get_requisicao_modem();\n\tint get_prioridade();\n\tint get_blocos_memoria();\n\tint get_inicio();\n\tint get_codigo_disco();\n\t\/\/Fim da declaracao dos getters\n\tvoid imprime_infomacoes_processo(int);\/\/sera passado a ele o PID\n\/\/Fim da definicao dos metodos do processo\n};\n#endif\n<|endoftext|>"} {"text":"#include \"app.h\"\n\n#include \n#include \n#include \n\n#include \"platform.h\"\n#include \"view\/view.h\"\n\nstd::shared_ptr m_view;\n\nvoid initialize() {\n logMsg(\"%s\\n\", \"initialize\");\n\n \/\/ Create view\n m_view = std::make_shared();\n\n \/\/ \n \/\/\n \n \/\/ Set up openGL state\n glDisable(GL_BLEND);\n glDisable(GL_STENCIL_TEST);\n glEnable(GL_DEPTH_TEST);\n glClearDepthf(1.0);\n glDepthRangef(0.0, 1.0);\n glDepthMask(GL_TRUE);\n glDepthFunc(GL_LEQUAL);\n glEnable(GL_CULL_FACE);\n glFrontFace(GL_CCW);\n glCullFace(GL_BACK);\n glClearColor(0.3f, 0.3f, 0.3f, 1.0f);\n \n logMsg(\"%s\\n\", \"finish initialize\"); \n}\n\nvoid resize(int _newWidth, int _newHeight) {\n logMsg(\"%s\\n\", \"resize\");\n \n glViewport(0, 0, _newWidth, _newHeight);\n\n if (m_view) {\n m_view->setAspect(_newWidth, _newHeight);\n }\n}\n\nvoid update(float _dt) {\n \n}\n\nvoid render() {\n \/\/ Set up openGL for new frame\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n \n glm::dmat4 view = m_view->getViewMatrix();\n glm::dmat4 viewProj = m_view->getViewProjectionMatrix();\n\n \/\/\n \/\/\n\n \/\/ TODO: This error checking is incomplete and only marginally useful\n \/\/ 1. We need to continue calling glGetError until no error states remain\n \/\/ 2. Repeating an error message 60 times per second is not useful, try to consolidate\n GLenum glError = glGetError();\n if (glError) {\n logMsg(\"GL Error %d!!!\\n\", glError);\n }\n}\n\nvoid teardown() {\n \/\/ TODO: Release resources!\n}openGL include issue#include \"app.h\"\n\n#include \n#include \n#include \n\n#include \"platform.h\"\n#include \"view\/view.h\"\n\n#include \"GLES2\/gl2.h\"\n#include \"EGL\/egl.h\"\n#include \"EGL\/eglext.h\"\n\nstd::shared_ptr m_view;\n\nvoid initialize() {\n logMsg(\"%s\\n\", \"initialize\");\n\n \/\/ Create view\n m_view = std::make_shared();\n\n \/\/ \n \/\/\n \n \/\/ Set up openGL state\n glDisable(GL_BLEND);\n glDisable(GL_STENCIL_TEST);\n glEnable(GL_DEPTH_TEST);\n glClearDepthf(1.0);\n glDepthRangef(0.0, 1.0);\n glDepthMask(GL_TRUE);\n glDepthFunc(GL_LEQUAL);\n glEnable(GL_CULL_FACE);\n glFrontFace(GL_CCW);\n glCullFace(GL_BACK);\n glClearColor(0.3f, 0.3f, 0.3f, 1.0f);\n \n logMsg(\"%s\\n\", \"finish initialize\"); \n}\n\nvoid resize(int _newWidth, int _newHeight) {\n logMsg(\"%s\\n\", \"resize\");\n \n glViewport(0, 0, _newWidth, _newHeight);\n\n if (m_view) {\n m_view->setAspect(_newWidth, _newHeight);\n }\n}\n\nvoid update(float _dt) {\n \n}\n\nvoid render() {\n \/\/ Set up openGL for new frame\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n \n glm::dmat4 view = m_view->getViewMatrix();\n glm::dmat4 viewProj = m_view->getViewProjectionMatrix();\n\n \/\/\n \/\/\n\n \/\/ TODO: This error checking is incomplete and only marginally useful\n \/\/ 1. We need to continue calling glGetError until no error states remain\n \/\/ 2. Repeating an error message 60 times per second is not useful, try to consolidate\n GLenum glError = glGetError();\n if (glError) {\n logMsg(\"GL Error %d!!!\\n\", glError);\n }\n}\n\nvoid teardown() {\n \/\/ TODO: Release resources!\n}<|endoftext|>"} {"text":"\/*!\n \\copyright (c) RDO-Team, 2011\n \\file rdo_resource.cpp\n \\authors (rdo@rk9.bmstu.ru)\n \\authors (dluschan@rk9.bmstu.ru)\n \\date 16.04.2008\n \\brief RDOResource implementation\n \\indent 4T\n*\/\n\n\/\/ ---------------------------------------------------------------------------- PCH\n\/\/ ----------------------------------------------------------------------- INCLUDES\n\/\/ ----------------------------------------------------------------------- SYNOPSIS\n#include \"simulator\/runtime\/pch.h\"\n#include \"simulator\/runtime\/rdo_resource.h\"\n#include \"simulator\/runtime\/rdo_runtime.h\"\n\/\/ --------------------------------------------------------------------------------\n\nOPEN_RDO_RUNTIME_NAMESPACE\n\n\/\/ --------------------------------------------------------------------------------\n\/\/ -------------------- RDOResource\n\/\/ --------------------------------------------------------------------------------\nRDOResource::RDOResource(CREF(LPRDORuntime) pRuntime, CREF(ParamList) paramList, LPIResourceType pResType, ruint resID, ruint typeID, rbool trace, rbool temporary)\n\t: RDORuntimeObject ( )\n\t, RDOTraceableObject (trace, resID, rdo::toString(resID + 1))\n\t, m_state (RDOResource::CS_None )\n\t, m_type (typeID )\n\t, m_referenceCount (0 )\n\t, m_resType (pResType )\n\t, m_temporary (temporary )\n{\n\tappendParams(paramList.begin(), paramList.end());\n\tpRuntime->insertNewResource(this);\n}\n\n\/\/\/ @todo - ?\nRDOResource::RDOResource(CREF(LPRDORuntime) pRuntime, CREF(RDOResource) copy)\n\t: RDORuntimeObject ( )\n\t, RDOTraceableObject (copy.traceable(), copy.getTraceID(), copy.traceId())\n\t, m_type (copy.m_type )\n\t, m_state (copy.m_state )\n\t, m_typeId (copy.m_typeId )\n\t, m_paramList (copy.m_paramList )\n\t, m_referenceCount (0 )\n\t, m_resType (copy.m_resType )\n\t, m_temporary (copy.m_temporary )\n{\n\tappendParams(copy.m_paramList.begin(), copy.m_paramList.end());\n\tpRuntime->insertNewResource(this);\n\/\/\/ @todo history \n\/\/\tgetRuntime()->incrementResourceIdReference( getTraceID() );\n}\n\nRDOResource::~RDOResource()\n{\n\t\/\/\/ @todo , breakpoint this\n\t\/\/getRuntime()->notify().fireMessage(Notify::RO_BEFOREDELETE, (void*)getTraceID());\n\t\/\/getRuntime()->onResourceErase(this);\n}\n\nrbool RDOResource::operator!= (RDOResource &other)\n{\n\tif (m_type != other.m_type) return true;\n\tif (m_paramList.size() != other.m_paramList.size()) return true;\n\n\tint size = m_paramList.size();\n\tfor (int i = 0; i < size; ++i)\n\t{\n\t\tif (m_paramList.at(i) != other.m_paramList.at(i)) return true;\n\t}\n\treturn false;\n}\n\nLPRDOResource RDOResource::clone(CREF(LPRDORuntime) pRuntime) const\n{\n\treturn rdo::Factory::create(pRuntime, m_paramList, m_resType, getTraceID(), m_type, traceable(), m_temporary);\n}\n\ntstring RDOResource::getTypeId()\n{\n\tstd::ostringstream str;\n\tstr << m_type;\n\treturn str.str();\n}\n\ntstring RDOResource::traceParametersValue()\n{\n\tstd::ostringstream str;\n\tif(m_paramList.size() > 0)\n\t{\n\t\tParamList::iterator end = m_paramList.end();\n\t\tfor (ParamList::iterator it = m_paramList.begin();;)\n\t\t{\n#ifdef RDOSIM_COMPATIBLE\n\t\t\tstd::ostringstream _str;\n\t\t\t_str << *it;\n\t\t\ttstring::size_type pos = _str.str().find(\"e\");\n\t\t\tif (pos != tstring::npos)\n\t\t\t{\n\t\t\t\ttstring __str = _str.str();\n\t\t\t\t__str.erase(pos + 2, 1);\n\t\t\t\tstr << __str.c_str();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tstr << _str.str().c_str();\n\t\t\t}\n#else\n\t\t\tstr << *it;\n#endif\n\t\t\tif (++it == end)\n\t\t\t\tbreak;\n\t\t\tstr << \" \";\n\t\t}\n\t}\n\treturn str.str();\n}\n\ntstring RDOResource::traceResourceState(char prefix, CREF(LPRDORuntime) pRuntime)\n{\n\tstd::ostringstream res;\n\tif (traceable() || (prefix != '\\0'))\n\t{\n\t\tif (m_state == RDOResource::CS_NoChange || m_state == RDOResource::CS_NonExist)\n\t\t\treturn \"\";\n\n\t\tif (prefix != '\\0')\n\t\t\tres << prefix;\n\n\t\tswitch (m_state)\n\t\t{\n\t\tcase RDOResource::CS_Create:\n\t\t\tres << \"RC \";\n\t\t\tbreak;\n\t\tcase RDOResource::CS_Erase:\n\t\t\tres << \"RE \"\n#ifdef RDOSIM_COMPATIBLE\n\t\t\t\t<< pRuntime->getCurrentTime() << \" \"\n\t\t\t\t<< traceTypeId() << \" \"\n\t\t\t\t<< traceId() << std::endl;\n\t\t\treturn res.str();\n#else\n\t\t\t\t;\n#endif\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tres << \"RK \";\n\t\t\tbreak;\n\t\t}\n\n\t\tres << pRuntime->getCurrentTime() << \" \"\n\t\t\t<< traceTypeId() << \" \"\n\t\t\t<< traceId() << \" \"\n\t\t\t<< traceParametersValue() << std::endl;\n\t}\n\treturn res.str();\n}\n\nCLOSE_RDO_RUNTIME_NAMESPACE\n - удалено лишнее\/*!\n \\copyright (c) RDO-Team, 2011\n \\file rdo_resource.cpp\n \\authors (rdo@rk9.bmstu.ru)\n \\authors (dluschan@rk9.bmstu.ru)\n \\date 16.04.2008\n \\brief RDOResource implementation\n \\indent 4T\n*\/\n\n\/\/ ---------------------------------------------------------------------------- PCH\n\/\/ ----------------------------------------------------------------------- INCLUDES\n\/\/ ----------------------------------------------------------------------- SYNOPSIS\n#include \"simulator\/runtime\/pch.h\"\n#include \"simulator\/runtime\/rdo_resource.h\"\n#include \"simulator\/runtime\/rdo_runtime.h\"\n\/\/ --------------------------------------------------------------------------------\n\nOPEN_RDO_RUNTIME_NAMESPACE\n\n\/\/ --------------------------------------------------------------------------------\n\/\/ -------------------- RDOResource\n\/\/ --------------------------------------------------------------------------------\nRDOResource::RDOResource(CREF(LPRDORuntime) pRuntime, CREF(ParamList) paramList, LPIResourceType pResType, ruint resID, ruint typeID, rbool trace, rbool temporary)\n\t: RDORuntimeObject ( )\n\t, RDOTraceableObject (trace, resID, rdo::toString(resID + 1))\n\t, m_state (RDOResource::CS_None )\n\t, m_type (typeID )\n\t, m_referenceCount (0 )\n\t, m_resType (pResType )\n\t, m_temporary (temporary )\n{\n\tappendParams(paramList.begin(), paramList.end());\n\tpRuntime->insertNewResource(this);\n}\n\n\/\/\/ @todo - ?\nRDOResource::RDOResource(CREF(LPRDORuntime) pRuntime, CREF(RDOResource) copy)\n\t: RDORuntimeObject ( )\n\t, RDOTraceableObject (copy.traceable(), copy.getTraceID(), copy.traceId())\n\t, m_type (copy.m_type )\n\t, m_state (copy.m_state )\n\t, m_typeId (copy.m_typeId )\n\t, m_paramList (copy.m_paramList )\n\t, m_referenceCount (0 )\n\t, m_resType (copy.m_resType )\n\t, m_temporary (copy.m_temporary )\n{\n\tappendParams(copy.m_paramList.begin(), copy.m_paramList.end());\n\tpRuntime->insertNewResource(this);\n\/\/\/ @todo history \n\/\/\tgetRuntime()->incrementResourceIdReference( getTraceID() );\n}\n\nRDOResource::~RDOResource()\n{}\n\nrbool RDOResource::operator!= (RDOResource &other)\n{\n\tif (m_type != other.m_type) return true;\n\tif (m_paramList.size() != other.m_paramList.size()) return true;\n\n\tint size = m_paramList.size();\n\tfor (int i = 0; i < size; ++i)\n\t{\n\t\tif (m_paramList.at(i) != other.m_paramList.at(i)) return true;\n\t}\n\treturn false;\n}\n\nLPRDOResource RDOResource::clone(CREF(LPRDORuntime) pRuntime) const\n{\n\treturn rdo::Factory::create(pRuntime, m_paramList, m_resType, getTraceID(), m_type, traceable(), m_temporary);\n}\n\ntstring RDOResource::getTypeId()\n{\n\tstd::ostringstream str;\n\tstr << m_type;\n\treturn str.str();\n}\n\ntstring RDOResource::traceParametersValue()\n{\n\tstd::ostringstream str;\n\tif(m_paramList.size() > 0)\n\t{\n\t\tParamList::iterator end = m_paramList.end();\n\t\tfor (ParamList::iterator it = m_paramList.begin();;)\n\t\t{\n#ifdef RDOSIM_COMPATIBLE\n\t\t\tstd::ostringstream _str;\n\t\t\t_str << *it;\n\t\t\ttstring::size_type pos = _str.str().find(\"e\");\n\t\t\tif (pos != tstring::npos)\n\t\t\t{\n\t\t\t\ttstring __str = _str.str();\n\t\t\t\t__str.erase(pos + 2, 1);\n\t\t\t\tstr << __str.c_str();\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tstr << _str.str().c_str();\n\t\t\t}\n#else\n\t\t\tstr << *it;\n#endif\n\t\t\tif (++it == end)\n\t\t\t\tbreak;\n\t\t\tstr << \" \";\n\t\t}\n\t}\n\treturn str.str();\n}\n\ntstring RDOResource::traceResourceState(char prefix, CREF(LPRDORuntime) pRuntime)\n{\n\tstd::ostringstream res;\n\tif (traceable() || (prefix != '\\0'))\n\t{\n\t\tif (m_state == RDOResource::CS_NoChange || m_state == RDOResource::CS_NonExist)\n\t\t\treturn \"\";\n\n\t\tif (prefix != '\\0')\n\t\t\tres << prefix;\n\n\t\tswitch (m_state)\n\t\t{\n\t\tcase RDOResource::CS_Create:\n\t\t\tres << \"RC \";\n\t\t\tbreak;\n\t\tcase RDOResource::CS_Erase:\n\t\t\tres << \"RE \"\n#ifdef RDOSIM_COMPATIBLE\n\t\t\t\t<< pRuntime->getCurrentTime() << \" \"\n\t\t\t\t<< traceTypeId() << \" \"\n\t\t\t\t<< traceId() << std::endl;\n\t\t\treturn res.str();\n#else\n\t\t\t\t;\n#endif\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tres << \"RK \";\n\t\t\tbreak;\n\t\t}\n\n\t\tres << pRuntime->getCurrentTime() << \" \"\n\t\t\t<< traceTypeId() << \" \"\n\t\t\t<< traceId() << \" \"\n\t\t\t<< traceParametersValue() << std::endl;\n\t}\n\treturn res.str();\n}\n\nCLOSE_RDO_RUNTIME_NAMESPACE\n<|endoftext|>"} {"text":"\/*********************************************************************************\n * libskype - C++ library for interacting with a running skype instance.\n * Copyright (C) 2014 Søren Holm \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n ********************************************************************************\/\n\n#include \n\n#include \n\n#include \"libskype.h\"\n\nusing namespace std;\n\nclass MyCallbacks : public LibSkypeHandler {\n\npublic:\n\tvoid message_received(LibSkypeMessage* msg) {\n\t\tcout << \"New message received\" << endl;\n\t\tif (msg->editable() && msg->body() == \"ping\")\n\t\t\tmsg->set_body(\"pong\");\n\t}\n};\n\n\n\n\nint main() {\n\tMyCallbacks callbacks;\n\tLibSkype skype;\n\tskype.set_handler(&callbacks);\n\n\/\/\tLibSkypeContact* contact = skype.get_contact(\"testuser\");\n\/\/\tcout << contact->handle() << endl;\n\/\/\tcontact->transfer_file(\"uhadada.mp3\");\n\/\/\tcontact->send_message(\"uhadada.mp3\");\n\/\/\tcontact->call();\n\/\/\tusleep(100000);\n\twhile (1)\n\t\tusleep(1000000);\n}\nAdded commandline call and filetransfer.\/*********************************************************************************\n * libskype - C++ library for interacting with a running skype instance.\n * Copyright (C) 2014 Søren Holm \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n ********************************************************************************\/\n#include \"libskype.h\"\n\n#include \n#include \n\n#include \n\nusing namespace std;\n\nclass MyCallbacks : public LibSkypeHandler {\n\npublic:\n\tvoid message_received(LibSkypeMessage* msg) {\n\t\tcout << \"New message received\" << endl;\n\t\tif (msg->editable() && msg->body() == \"ping\")\n\t\t\tmsg->set_body(\"pong\");\n\t}\n};\n\n\nvoid print_usage() {\n\tcout << \"Usage: skypecli \" << endl;\n\tcout << \" -c - Call contact \" << endl;\n\tcout << \" -f - Send file to a contact\" << endl;\n\texit(EXIT_FAILURE);\n}\n\n\nint main(int argc, char* const argv[]) {\n\tint opt;\n\tstring call_handle;\n\tstring send_file;\n\n\twhile ((opt = getopt(argc, argv, \"c:f:h\")) != -1) {\n\t\tswitch (opt) {\n\t\t\tcase 'c':\n\t\t\t\tcall_handle = optarg;\n\t\t\t\tbreak;\n\t\t\tcase 'f':\n\t\t\t\tsend_file = optarg;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tprint_usage();\n\t\t}\n\t}\n\n\tif (argc < 2)\n\t\tprint_usage();\n\n\tMyCallbacks callbacks;\n\tLibSkype skype;\n\tskype.set_handler(&callbacks);\n\n\tif (!call_handle.empty()) {\n\t\tLibSkypeContact* contact = skype.get_contact(call_handle);\n\t\tif (!contact) {\n\t\t\tcout << \"Error, no such contact\" << endl;\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\tcout << \"Calling \" << contact->handle() << endl;\n\t\tcontact->call();\n\t} else\n\tif (!send_file.empty()) {\n\t\tstring handle;\n\t\tcout << \"Send file to: \" << flush;\n\t\tgetline(cin, handle);\n\t\tLibSkypeContact* contact = skype.get_contact(handle);\n\t\tif (!contact) {\n\t\t\tcout << \"Error, no such contact\" << endl;\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t\tcout << \"Sending file to \" << contact->handle() << endl;\n\t\tcontact->transfer_file(send_file);\n\n\t}\n\n\texit(EXIT_SUCCESS);\n}\n<|endoftext|>"} {"text":"#ifndef SOFA_COMPONENT_FORCEFIELD_VECTORSPRINGFORCEFIELD_INL\n#define SOFA_COMPONENT_FORCEFIELD_VECTORSPRINGFORCEFIELD_INL\n\n#include \"VectorSpringForceField.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nusing std::cerr;\nusing std::endl;\n\nnamespace sofa\n{\n\nnamespace component\n{\n\nnamespace forcefield\n{\n\ntemplate\nvoid springCreationFunction(int \/*index*\/,\n void* param, typename VectorSpringForceField::Spring& t,\n const topology::Edge& e,\n const std::vector< unsigned int > &ancestors,\n const std::vector< double >& coefs)\n{\n VectorSpringForceField *ff= static_cast *>(param);\n if (ff)\n {\n topology::EdgeSetTopology* topology = dynamic_cast*>(ff->getContext()->getMainTopology());\n if (topology)\n {\n \/\/EdgeSetGeometryAlgorithms *ga=topology->getEdgeSetGeometryAlgorithms();\n \/\/t.restLength=ga->computeRestEdgeLength(index);\n const typename DataTypes::VecCoord& x0 = *ff->getObject1()->getX0();\n t.restVector = x0[e.second] - x0[e.first];\n if (ancestors.size()>0)\n {\n t.kd=t.ks=0;\n const topology::EdgeData::Spring> &sa=ff->getSpringArray();\n unsigned int i;\n for (i=0; igetStiffness();\n t.ks=ff->getViscosity();\n }\n }\n }\n}\n\ntemplate \nclass VectorSpringForceField::Loader : public sofa::helper::io::MassSpringLoader\n{\npublic:\n typedef typename DataTypes::Real Real;\n typedef typename DataTypes::Coord Coord;\n VectorSpringForceField* dest;\n Loader(VectorSpringForceField* dest) : dest(dest) {}\n virtual void addVectorSpring(int m1, int m2, double ks, double kd, double initpos, double restx, double resty, double restz)\n {\n dest->addSpring(m1,m2,ks,kd,Coord((Real)restx,(Real)resty,(Real)restz));\n }\n virtual void setNumSprings(int \/*n*\/)\n {\n \/\/dest->resizeArray((unsigned int )n);\n }\n\n};\n\ntemplate \nbool VectorSpringForceField::load(const char *filename)\n{\n if (filename && filename[0])\n {\n Loader loader(this);\n return loader.load(filename);\n }\n else return false;\n}\n\ntemplate \nvoid VectorSpringForceField::resizeArray(unsigned int n)\n{\n springArray.resize(n);\n}\n\ntemplate \nvoid VectorSpringForceField::addSpring(int m1, int m2, double ks, double kd, Coord restVector)\n{\n if (useTopology && topology)\n {\n topology::EdgeSetTopologyContainer *container=topology->getEdgeSetTopologyContainer();\n\n int e=container->getEdgeIndex((unsigned int)m1,(unsigned int)m2);\n if (e>=0)\n springArray[e]=Spring((Real)ks,(Real)kd,restVector);\n }\n else\n {\n springArray.push_back(Spring((Real)ks, (Real)kd, restVector));\n edgeArray.push_back(topology::Edge(m1,m2));\n }\n}\n\ntemplate \nVectorSpringForceField::VectorSpringForceField(MechanicalState* _object)\n : object1(_object), object2(_object)\n , m_potentialEnergy( 0.0 ), useTopology( false ), topology ( NULL )\n , m_filename( dataField(&m_filename,std::string(\"\"),\"filename\",\"File name from which the spring informations are loaded\") )\n , m_stiffness( dataField(&m_stiffness,1.0,\"stiffness\",\"Default edge stiffness used in absence of file information\") )\n , m_viscosity( dataField(&m_viscosity,1.0,\"viscosity\",\"Default edge viscosity used in absence of file information\") )\n{\n springArray.setCreateFunction(springCreationFunction);\n springArray.setCreateParameter( (void *) this );\n}\n\ntemplate \nVectorSpringForceField::VectorSpringForceField(MechanicalState* _object1, MechanicalState* _object2)\n : object1(_object1), object2(_object2)\n , m_potentialEnergy( 0.0 ), useTopology( false ), topology ( NULL )\n , m_filename( dataField(&m_filename,std::string(\"\"),\"filename\",\"File name from which the spring informations are loaded\") )\n , m_stiffness( dataField(&m_stiffness,1.0,\"stiffness\",\"Default edge stiffness used in absence of file information\") )\n , m_viscosity( dataField(&m_viscosity,1.0,\"viscosity\",\"Default edge viscosity used in absence of file information\") )\n{\n springArray.setCreateFunction(springCreationFunction);\n springArray.setCreateParameter( (void *) this );\n}\n\ntemplate \nvoid VectorSpringForceField::init()\n{\n this->InteractionForceField::init();\n if( object1==NULL )\n {\n sofa::core::objectmodel::BaseObject* mstate = getContext()->getMechanicalState();\n assert(mstate!=NULL);\n MechanicalState* state = dynamic_cast(mstate );\n assert( state!= NULL );\n object1 = object2 = state;\n topology = dynamic_cast*>(getContext()->getMainTopology());\n }\n\n if (!m_filename.getValue().empty())\n {\n \/\/ load the springs from a file\n load(( const char *)(m_filename.getValue().c_str()));\n }\n else if (topology)\n {\n \/\/ create springs based on the mesh topology\n useTopology = true;\n createDefaultSprings();\n f_listening.setValue(true);\n }\n}\n\ntemplate \nvoid VectorSpringForceField::createDefaultSprings()\n{\n topology::EdgeSetTopologyContainer *container=topology->getEdgeSetTopologyContainer();\n const std::vector &ea=container->getEdgeArray();\n std::cout << \"Creating \"< *ga=topology->getEdgeSetGeometryAlgorithms();\n \/\/EdgeLengthArrayInterface elai(springArray);\n \/\/ga->computeEdgeLength(elai);\n const VecCoord& x0 = *this->object1->getX0();\n unsigned int i;\n for (i=0; i\nvoid VectorSpringForceField::handleEvent( Event* e )\n{\n if (useTopology)\n {\n if( sofa::core::objectmodel::KeypressedEvent* ke = dynamic_cast( e ) )\n {\n \/\/\/ handle ctrl+d key\n if (ke->getKey()=='D')\n {\n if (topology->getEdgeSetTopologyContainer()->getNumberOfEdges()>12)\n {\n topology::EdgeSetTopologyAlgorithms *esta=topology->getEdgeSetTopologyAlgorithms();\n std::vector edgeArray;\n edgeArray.push_back(12);\n esta->removeEdges(edgeArray);\n }\n \/\/ esta->splitEdges(edgeArray);\n }\n }\n else\n {\n sofa::component::topology::TopologyChangedEvent *tce=dynamic_cast(e);\n \/\/\/ test that the event is a change of topology and that it\n if ((tce) && (tce->getTopology()== topology))\n {\n std::list::const_iterator itBegin=topology->firstChange();\n std::list::const_iterator itEnd=topology->lastChange();\n \/\/\/ Topological events are handled by the EdgeData structure\n springArray.handleTopologyEvents(itBegin,itEnd);\n }\n }\n }\n}\n\ntemplate\n\/\/void VectorSpringForceField::addForce(VecDeriv& f, const VecCoord& p, const VecDeriv& v)\nvoid VectorSpringForceField::addForce()\n{\n \/\/assert(this->mstate);\n m_potentialEnergy = 0;\n const std::vector &ea=(useTopology)?topology->getEdgeSetTopologyContainer()->getEdgeArray() : edgeArray;\n Coord u;\n\n VecDeriv& f1 = *object1->getF();\n const VecCoord& p1 = *object1->getX();\n const VecDeriv& v1 = *object1->getV();\n\n VecDeriv& f2 = *object2->getF();\n const VecCoord& p2 = *object2->getX();\n const VecDeriv& v2 = *object2->getV();\n\n f1.resize(p1.size());\n f2.resize(p2.size());\n\n Deriv relativeVelocity,force;\n for (unsigned int i=0; i\n\/\/void VectorSpringForceField::addDForce(VecDeriv& df, const VecDeriv& dx)\nvoid VectorSpringForceField::addDForce()\n{\n const std::vector &ea=(useTopology)?topology->getEdgeSetTopologyContainer()->getEdgeArray() : edgeArray;\n Deriv dforce,d;\n unsigned int i;\n\n VecDeriv& df1 = *object1->getF();\n const VecCoord& dx1 = *object1->getDx();\n\n VecDeriv& df2 = *object2->getF();\n const VecCoord& dx2 = *object2->getDx();\n\n df1.resize(dx1.size());\n df2.resize(dx2.size());\n\n for ( i=0; i\nvoid VectorSpringForceField::draw()\n{\n if (getContext()->getShowForceFields()==false)\n return;\n \/\/const VecCoord& p = *this->mstate->getX();\n const VecCoord& p1 = *this->object1->getX();\n const VecCoord& p2 = *this->object2->getX();\n const std::vector &ea=(useTopology)?topology->getEdgeSetTopologyContainer()->getEdgeArray() : edgeArray;\n\n glDisable(GL_LIGHTING);\n\n glBegin(GL_LINES);\n for (unsigned int i=0; ir1237\/sofa-dev : BUGFIX: inversed addDForce in VectorSpringForceField, and crash when picking spheres.#ifndef SOFA_COMPONENT_FORCEFIELD_VECTORSPRINGFORCEFIELD_INL\n#define SOFA_COMPONENT_FORCEFIELD_VECTORSPRINGFORCEFIELD_INL\n\n#include \"VectorSpringForceField.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nusing std::cerr;\nusing std::endl;\n\nnamespace sofa\n{\n\nnamespace component\n{\n\nnamespace forcefield\n{\n\ntemplate\nvoid springCreationFunction(int \/*index*\/,\n void* param, typename VectorSpringForceField::Spring& t,\n const topology::Edge& e,\n const std::vector< unsigned int > &ancestors,\n const std::vector< double >& coefs)\n{\n VectorSpringForceField *ff= static_cast *>(param);\n if (ff)\n {\n topology::EdgeSetTopology* topology = dynamic_cast*>(ff->getContext()->getMainTopology());\n if (topology)\n {\n \/\/EdgeSetGeometryAlgorithms *ga=topology->getEdgeSetGeometryAlgorithms();\n \/\/t.restLength=ga->computeRestEdgeLength(index);\n const typename DataTypes::VecCoord& x0 = *ff->getObject1()->getX0();\n t.restVector = x0[e.second] - x0[e.first];\n if (ancestors.size()>0)\n {\n t.kd=t.ks=0;\n const topology::EdgeData::Spring> &sa=ff->getSpringArray();\n unsigned int i;\n for (i=0; igetStiffness();\n t.ks=ff->getViscosity();\n }\n }\n }\n}\n\ntemplate \nclass VectorSpringForceField::Loader : public sofa::helper::io::MassSpringLoader\n{\npublic:\n typedef typename DataTypes::Real Real;\n typedef typename DataTypes::Coord Coord;\n VectorSpringForceField* dest;\n Loader(VectorSpringForceField* dest) : dest(dest) {}\n virtual void addVectorSpring(int m1, int m2, double ks, double kd, double initpos, double restx, double resty, double restz)\n {\n dest->addSpring(m1,m2,ks,kd,Coord((Real)restx,(Real)resty,(Real)restz));\n }\n virtual void setNumSprings(int \/*n*\/)\n {\n \/\/dest->resizeArray((unsigned int )n);\n }\n\n};\n\ntemplate \nbool VectorSpringForceField::load(const char *filename)\n{\n if (filename && filename[0])\n {\n Loader loader(this);\n return loader.load(filename);\n }\n else return false;\n}\n\ntemplate \nvoid VectorSpringForceField::resizeArray(unsigned int n)\n{\n springArray.resize(n);\n}\n\ntemplate \nvoid VectorSpringForceField::addSpring(int m1, int m2, double ks, double kd, Coord restVector)\n{\n if (useTopology && topology)\n {\n topology::EdgeSetTopologyContainer *container=topology->getEdgeSetTopologyContainer();\n\n int e=container->getEdgeIndex((unsigned int)m1,(unsigned int)m2);\n if (e>=0)\n springArray[e]=Spring((Real)ks,(Real)kd,restVector);\n }\n else\n {\n springArray.push_back(Spring((Real)ks, (Real)kd, restVector));\n edgeArray.push_back(topology::Edge(m1,m2));\n }\n}\n\ntemplate \nVectorSpringForceField::VectorSpringForceField(MechanicalState* _object)\n : object1(_object), object2(_object)\n , m_potentialEnergy( 0.0 ), useTopology( false ), topology ( NULL )\n , m_filename( dataField(&m_filename,std::string(\"\"),\"filename\",\"File name from which the spring informations are loaded\") )\n , m_stiffness( dataField(&m_stiffness,1.0,\"stiffness\",\"Default edge stiffness used in absence of file information\") )\n , m_viscosity( dataField(&m_viscosity,1.0,\"viscosity\",\"Default edge viscosity used in absence of file information\") )\n{\n springArray.setCreateFunction(springCreationFunction);\n springArray.setCreateParameter( (void *) this );\n}\n\ntemplate \nVectorSpringForceField::VectorSpringForceField(MechanicalState* _object1, MechanicalState* _object2)\n : object1(_object1), object2(_object2)\n , m_potentialEnergy( 0.0 ), useTopology( false ), topology ( NULL )\n , m_filename( dataField(&m_filename,std::string(\"\"),\"filename\",\"File name from which the spring informations are loaded\") )\n , m_stiffness( dataField(&m_stiffness,1.0,\"stiffness\",\"Default edge stiffness used in absence of file information\") )\n , m_viscosity( dataField(&m_viscosity,1.0,\"viscosity\",\"Default edge viscosity used in absence of file information\") )\n{\n springArray.setCreateFunction(springCreationFunction);\n springArray.setCreateParameter( (void *) this );\n}\n\ntemplate \nvoid VectorSpringForceField::init()\n{\n this->InteractionForceField::init();\n if( object1==NULL )\n {\n sofa::core::objectmodel::BaseObject* mstate = getContext()->getMechanicalState();\n assert(mstate!=NULL);\n MechanicalState* state = dynamic_cast(mstate );\n assert( state!= NULL );\n object1 = object2 = state;\n topology = dynamic_cast*>(getContext()->getMainTopology());\n }\n\n if (!m_filename.getValue().empty())\n {\n \/\/ load the springs from a file\n load(( const char *)(m_filename.getValue().c_str()));\n }\n else if (topology)\n {\n \/\/ create springs based on the mesh topology\n useTopology = true;\n createDefaultSprings();\n f_listening.setValue(true);\n }\n}\n\ntemplate \nvoid VectorSpringForceField::createDefaultSprings()\n{\n topology::EdgeSetTopologyContainer *container=topology->getEdgeSetTopologyContainer();\n const std::vector &ea=container->getEdgeArray();\n std::cout << \"Creating \"< *ga=topology->getEdgeSetGeometryAlgorithms();\n \/\/EdgeLengthArrayInterface elai(springArray);\n \/\/ga->computeEdgeLength(elai);\n const VecCoord& x0 = *this->object1->getX0();\n unsigned int i;\n for (i=0; i\nvoid VectorSpringForceField::handleEvent( Event* e )\n{\n if (useTopology)\n {\n if( sofa::core::objectmodel::KeypressedEvent* ke = dynamic_cast( e ) )\n {\n \/\/\/ handle ctrl+d key\n if (ke->getKey()=='D')\n {\n if (topology->getEdgeSetTopologyContainer()->getNumberOfEdges()>12)\n {\n topology::EdgeSetTopologyAlgorithms *esta=topology->getEdgeSetTopologyAlgorithms();\n std::vector edgeArray;\n edgeArray.push_back(12);\n esta->removeEdges(edgeArray);\n }\n \/\/ esta->splitEdges(edgeArray);\n }\n }\n else\n {\n sofa::component::topology::TopologyChangedEvent *tce=dynamic_cast(e);\n \/\/\/ test that the event is a change of topology and that it\n if ((tce) && (tce->getTopology()== topology))\n {\n std::list::const_iterator itBegin=topology->firstChange();\n std::list::const_iterator itEnd=topology->lastChange();\n \/\/\/ Topological events are handled by the EdgeData structure\n springArray.handleTopologyEvents(itBegin,itEnd);\n }\n }\n }\n}\n\ntemplate\n\/\/void VectorSpringForceField::addForce(VecDeriv& f, const VecCoord& p, const VecDeriv& v)\nvoid VectorSpringForceField::addForce()\n{\n \/\/assert(this->mstate);\n m_potentialEnergy = 0;\n const std::vector &ea=(useTopology)?topology->getEdgeSetTopologyContainer()->getEdgeArray() : edgeArray;\n Coord u;\n\n VecDeriv& f1 = *object1->getF();\n const VecCoord& p1 = *object1->getX();\n const VecDeriv& v1 = *object1->getV();\n\n VecDeriv& f2 = *object2->getF();\n const VecCoord& p2 = *object2->getX();\n const VecDeriv& v2 = *object2->getV();\n\n f1.resize(p1.size());\n f2.resize(p2.size());\n\n Deriv relativeVelocity,force;\n for (unsigned int i=0; i\n\/\/void VectorSpringForceField::addDForce(VecDeriv& df, const VecDeriv& dx)\nvoid VectorSpringForceField::addDForce()\n{\n const std::vector &ea=(useTopology)?topology->getEdgeSetTopologyContainer()->getEdgeArray() : edgeArray;\n Deriv dforce,d;\n unsigned int i;\n\n VecDeriv& df1 = *object1->getF();\n const VecCoord& dx1 = *object1->getDx();\n\n VecDeriv& df2 = *object2->getF();\n const VecCoord& dx2 = *object2->getDx();\n\n df1.resize(dx1.size());\n df2.resize(dx2.size());\n\n for ( i=0; i\nvoid VectorSpringForceField::draw()\n{\n if (!((this->object1 == this->object2)?getContext()->getShowForceFields():getContext()->getShowInteractionForceFields()))\n return;\n \/\/const VecCoord& p = *this->mstate->getX();\n const VecCoord& p1 = *this->object1->getX();\n const VecCoord& p2 = *this->object2->getX();\n const std::vector &ea=(useTopology)?topology->getEdgeSetTopologyContainer()->getEdgeArray() : edgeArray;\n\n glDisable(GL_LIGHTING);\n\n glBegin(GL_LINES);\n for (unsigned int i=0; i"} {"text":"\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit https:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2016-2018 Esteban Tovagliari, The appleseedhq Organization\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/utility\/api\/apistring.h\"\n#include \"foundation\/utility\/searchpaths.h\"\n#include \"foundation\/utility\/test.h\"\n\n\/\/ Standard headers.\n#include \n#include \n#include \n\nusing namespace foundation;\nusing namespace std;\n\nTEST_SUITE(Foundation_Utility_SearchPaths)\n{\n static const char* TestEnvVarName = \"APPLESEED_TEST_SEARCHPATH\";\n\n#ifdef _WIN32\n\n void set_environment_var(const char* name, const char* value)\n {\n#ifndef NDEBUG\n const errno_t result =\n#endif\n _putenv_s(name, value);\n assert(result == 0);\n }\n\n TEST_CASE(Constructor_EmptyEnvironmentVariable)\n {\n set_environment_var(TestEnvVarName, \"\");\n\n const SearchPaths searchpaths(TestEnvVarName, ';');\n\n const APIString result = searchpaths.to_string(';');\n EXPECT_EQ(\"\", to_string(result));\n }\n\n TEST_CASE(Constructor_NonEmptyEnvironmentVariable)\n {\n set_environment_var(TestEnvVarName, \"C:\\\\Windows\\\\System32;C:\\\\Windows;C:\\\\Program Files\");\n\n const SearchPaths searchpaths(TestEnvVarName, ';');\n\n const APIString result = searchpaths.to_string(';');\n EXPECT_EQ(\"C:\\\\Windows\\\\System32;C:\\\\Windows;C:\\\\Program Files\", to_string(result));\n }\n\n TEST_CASE(ClearExplicitPaths)\n {\n set_environment_var(TestEnvVarName, \"C:\\\\Windows\\\\System32;C:\\\\Windows;C:\\\\Program Files\");\n\n SearchPaths searchpaths(TestEnvVarName, ';');\n searchpaths.set_root_path(\"C:\\\\Some\\\\Root\\\\Path\");\n searchpaths.push_back_explicit_path(\"C:\\\\Users\\\\UserName\\\\appleseed\");\n\n searchpaths.clear_explicit_paths();\n\n const APIString result = searchpaths.to_string(';');\n EXPECT_EQ(\"C:\\\\Some\\\\Root\\\\Path;C:\\\\Windows\\\\System32;C:\\\\Windows;C:\\\\Program Files\", to_string(result));\n }\n\n TEST_CASE(ToString)\n {\n SearchPaths searchpaths;\n searchpaths.push_back_explicit_path(\"C:\\\\Windows\\\\System32\");\n searchpaths.push_back_explicit_path(\"C:\\\\Windows\");\n searchpaths.push_back_explicit_path(\"C:\\\\Program Files\");\n\n const APIString result = searchpaths.to_string(';');\n\n EXPECT_EQ(\"C:\\\\Windows\\\\System32;C:\\\\Windows;C:\\\\Program Files\", to_string(result));\n }\n\n TEST_CASE(ToStringReversed)\n {\n SearchPaths searchpaths;\n searchpaths.push_back_explicit_path(\"C:\\\\Windows\\\\System32\");\n searchpaths.push_back_explicit_path(\"C:\\\\Windows\");\n searchpaths.push_back_explicit_path(\"C:\\\\Program Files\");\n\n const APIString result = searchpaths.to_string_reversed(';');\n\n EXPECT_EQ(\"C:\\\\Program Files;C:\\\\Windows;C:\\\\Windows\\\\System32\", to_string(result));\n }\n\n#else\n\n void set_environment_var(const char* name, const char* value)\n {\n#ifndef NDEBUG\n const int result =\n#endif\n setenv(name, value, 1);\n assert(result == 0);\n }\n\n TEST_CASE(Constructor_EmptyEnvironmentVariable)\n {\n set_environment_var(TestEnvVarName, \"\");\n\n const SearchPaths searchpaths(TestEnvVarName, ':');\n\n const APIString result = searchpaths.to_string(':');\n EXPECT_EQ(\"\", to_string(result));\n }\n\n TEST_CASE(Constructor_NonEmptyEnvironmentVariable)\n {\n set_environment_var(TestEnvVarName, \"\/tmp:\/usr\/tmp:\/var\/local\/tmp\");\n\n const SearchPaths searchpaths(TestEnvVarName, ':');\n\n const APIString result = searchpaths.to_string(':');\n EXPECT_EQ(\"\/tmp:\/usr\/tmp:\/var\/local\/tmp\", to_string(result));\n }\n\n TEST_CASE(ClearExplicitPaths)\n {\n set_environment_var(TestEnvVarName, \"\/tmp:\/usr\/tmp:\/var\/local\/tmp\");\n\n SearchPaths searchpaths(TestEnvVarName, ':');\n searchpaths.set_root_path(\"\/some\/root\/path\");\n searchpaths.push_back_explicit_path(\"\/home\/username\/appleseed\");\n\n searchpaths.clear_explicit_paths();\n\n const APIString result = searchpaths.to_string(':');\n EXPECT_EQ(\"\/some\/root\/path:\/tmp:\/usr\/tmp:\/var\/local\/tmp\", to_string(result));\n }\n\n TEST_CASE(ToString)\n {\n SearchPaths searchpaths;\n searchpaths.push_back_explicit_path(\"\/tmp\");\n searchpaths.push_back_explicit_path(\"\/usr\/tmp\");\n searchpaths.push_back_explicit_path(\"\/var\/local\/tmp\");\n\n const APIString result = searchpaths.to_string(':');\n\n EXPECT_EQ(\"\/tmp:\/usr\/tmp:\/var\/local\/tmp\", to_string(result));\n }\n\n TEST_CASE(ToStringReversed)\n {\n SearchPaths searchpaths;\n searchpaths.push_back_explicit_path(\"\/tmp\");\n searchpaths.push_back_explicit_path(\"\/usr\/tmp\");\n searchpaths.push_back_explicit_path(\"\/var\/local\/tmp\");\n\n const APIString result = searchpaths.to_string_reversed(':');\n\n EXPECT_EQ(\"\/var\/local\/tmp:\/usr\/tmp:\/tmp\", to_string(result));\n }\n\n#endif\n}\nRename variables to improve naming consistency\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit https:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2016-2018 Esteban Tovagliari, The appleseedhq Organization\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/utility\/api\/apistring.h\"\n#include \"foundation\/utility\/searchpaths.h\"\n#include \"foundation\/utility\/test.h\"\n\n\/\/ Standard headers.\n#include \n#include \n#include \n\nusing namespace foundation;\nusing namespace std;\n\nTEST_SUITE(Foundation_Utility_SearchPaths)\n{\n static const char* TestEnvVarName = \"APPLESEED_TEST_SEARCHPATH\";\n\n#ifdef _WIN32\n\n void set_environment_var(const char* name, const char* value)\n {\n#ifndef NDEBUG\n const errno_t result =\n#endif\n _putenv_s(name, value);\n assert(result == 0);\n }\n\n TEST_CASE(Constructor_EmptyEnvironmentVariable)\n {\n set_environment_var(TestEnvVarName, \"\");\n\n const SearchPaths search_paths(TestEnvVarName, ';');\n\n const APIString result = search_paths.to_string(';');\n EXPECT_EQ(\"\", to_string(result));\n }\n\n TEST_CASE(Constructor_NonEmptyEnvironmentVariable)\n {\n set_environment_var(TestEnvVarName, \"C:\\\\Windows\\\\System32;C:\\\\Windows;C:\\\\Program Files\");\n\n const SearchPaths search_paths(TestEnvVarName, ';');\n\n const APIString result = search_paths.to_string(';');\n EXPECT_EQ(\"C:\\\\Windows\\\\System32;C:\\\\Windows;C:\\\\Program Files\", to_string(result));\n }\n\n TEST_CASE(ClearExplicitPaths)\n {\n set_environment_var(TestEnvVarName, \"C:\\\\Windows\\\\System32;C:\\\\Windows;C:\\\\Program Files\");\n\n SearchPaths search_paths(TestEnvVarName, ';');\n search_paths.set_root_path(\"C:\\\\Some\\\\Root\\\\Path\");\n search_paths.push_back_explicit_path(\"C:\\\\Users\\\\UserName\\\\appleseed\");\n\n search_paths.clear_explicit_paths();\n\n const APIString result = search_paths.to_string(';');\n EXPECT_EQ(\"C:\\\\Some\\\\Root\\\\Path;C:\\\\Windows\\\\System32;C:\\\\Windows;C:\\\\Program Files\", to_string(result));\n }\n\n TEST_CASE(ToString)\n {\n SearchPaths search_paths;\n search_paths.push_back_explicit_path(\"C:\\\\Windows\\\\System32\");\n search_paths.push_back_explicit_path(\"C:\\\\Windows\");\n search_paths.push_back_explicit_path(\"C:\\\\Program Files\");\n\n const APIString result = search_paths.to_string(';');\n\n EXPECT_EQ(\"C:\\\\Windows\\\\System32;C:\\\\Windows;C:\\\\Program Files\", to_string(result));\n }\n\n TEST_CASE(ToStringReversed)\n {\n SearchPaths search_paths;\n search_paths.push_back_explicit_path(\"C:\\\\Windows\\\\System32\");\n search_paths.push_back_explicit_path(\"C:\\\\Windows\");\n search_paths.push_back_explicit_path(\"C:\\\\Program Files\");\n\n const APIString result = search_paths.to_string_reversed(';');\n\n EXPECT_EQ(\"C:\\\\Program Files;C:\\\\Windows;C:\\\\Windows\\\\System32\", to_string(result));\n }\n\n#else\n\n void set_environment_var(const char* name, const char* value)\n {\n#ifndef NDEBUG\n const int result =\n#endif\n setenv(name, value, 1);\n assert(result == 0);\n }\n\n TEST_CASE(Constructor_EmptyEnvironmentVariable)\n {\n set_environment_var(TestEnvVarName, \"\");\n\n const SearchPaths search_paths(TestEnvVarName, ':');\n\n const APIString result = search_paths.to_string(':');\n EXPECT_EQ(\"\", to_string(result));\n }\n\n TEST_CASE(Constructor_NonEmptyEnvironmentVariable)\n {\n set_environment_var(TestEnvVarName, \"\/tmp:\/usr\/tmp:\/var\/local\/tmp\");\n\n const SearchPaths search_paths(TestEnvVarName, ':');\n\n const APIString result = search_paths.to_string(':');\n EXPECT_EQ(\"\/tmp:\/usr\/tmp:\/var\/local\/tmp\", to_string(result));\n }\n\n TEST_CASE(ClearExplicitPaths)\n {\n set_environment_var(TestEnvVarName, \"\/tmp:\/usr\/tmp:\/var\/local\/tmp\");\n\n SearchPaths search_paths(TestEnvVarName, ':');\n search_paths.set_root_path(\"\/some\/root\/path\");\n search_paths.push_back_explicit_path(\"\/home\/username\/appleseed\");\n\n search_paths.clear_explicit_paths();\n\n const APIString result = search_paths.to_string(':');\n EXPECT_EQ(\"\/some\/root\/path:\/tmp:\/usr\/tmp:\/var\/local\/tmp\", to_string(result));\n }\n\n TEST_CASE(ToString)\n {\n SearchPaths search_paths;\n search_paths.push_back_explicit_path(\"\/tmp\");\n search_paths.push_back_explicit_path(\"\/usr\/tmp\");\n search_paths.push_back_explicit_path(\"\/var\/local\/tmp\");\n\n const APIString result = search_paths.to_string(':');\n\n EXPECT_EQ(\"\/tmp:\/usr\/tmp:\/var\/local\/tmp\", to_string(result));\n }\n\n TEST_CASE(ToStringReversed)\n {\n SearchPaths search_paths;\n search_paths.push_back_explicit_path(\"\/tmp\");\n search_paths.push_back_explicit_path(\"\/usr\/tmp\");\n search_paths.push_back_explicit_path(\"\/var\/local\/tmp\");\n\n const APIString result = search_paths.to_string_reversed(':');\n\n EXPECT_EQ(\"\/var\/local\/tmp:\/usr\/tmp:\/tmp\", to_string(result));\n }\n\n#endif\n}\n<|endoftext|>"} {"text":"\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2018-2021 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nnamespace inviwo {\n\nCEFInteractionHandler::CEFInteractionHandler(CefRefPtr host) : host_(host){};\n\nvoid CEFInteractionHandler::invokeEvent(Event* event) {\n switch (event->hash()) {\n case ResizeEvent::chash(): {\n if (renderHandler_) {\n auto resizeEvent = static_cast(event);\n renderHandler_->updateCanvasSize(host_->GetBrowser(), resizeEvent->size());\n host_->WasResized();\n }\n break;\n }\n case KeyboardEvent::chash(): {\n auto keyEvent = event->getAs();\n auto cefEvent = mapKeyEvent(keyEvent);\n host_->SendKeyEvent(cefEvent);\n \/\/ Send CHAR event for characters, but not non-char keys like arrows,\n \/\/ function keys or clear.\n auto isCharacter = std::iscntrl(cefEvent.character) == 0;\n if (isCharacter && (keyEvent->state() & KeyState::Press)) {\n cefEvent.type = KEYEVENT_CHAR;\n \/\/ Fixes 'Legacy' key codes for keypress events at\n \/\/ https:\/\/dvcs.w3.org\/hg\/d4e\/raw-file\/tip\/key-event-test.html\n cefEvent.windows_key_code = cefEvent.character;\n host_->SendKeyEvent(cefEvent);\n }\n event->markAsUsed();\n break;\n }\n }\n}\n\nvoid CEFInteractionHandler::handlePickingEvent(PickingEvent* p) {\n if (p->getEvent()->hash() == MouseEvent::chash()) {\n auto mouseEvent = p->getEventAs();\n updateMouseStates(mouseEvent);\n auto cefMouseEvent = mapMouseEvent(mouseEvent);\n if (mouseEvent->state() & MouseState::Move) {\n bool mouseLeave = false;\n host_->SendMouseMoveEvent(cefMouseEvent, mouseLeave);\n p->markAsUsed();\n } else if (mouseEvent->state() & MouseState::Press ||\n mouseEvent->state() & MouseState::Release) {\n CefBrowserHost::MouseButtonType type;\n\n if (mouseEvent->button() & MouseButton::Left) {\n type = MBT_LEFT;\n } else if (mouseEvent->button() & MouseButton::Middle) {\n type = MBT_MIDDLE;\n } else { \/\/ if (mouseEvent->button() & MouseButton::Right) {\n type = MBT_RIGHT;\n }\n bool mouseUp = MouseState::Release & mouseEvent->state() ? true : false;\n int clickCount = MouseState::DoubleClick & mouseEvent->state() ? 2 : 1;\n host_->SendMouseClickEvent(cefMouseEvent, type, mouseUp, clickCount);\n p->markAsUsed();\n }\n } else if (auto touchEvent = p->getEventAs()) {\n\n if (!touchEvent->hasTouchPoints()) {\n return;\n }\n TouchDevice::DeviceType type = touchEvent->getDevice()\n ? touchEvent->getDevice()->getType()\n : TouchDevice::DeviceType::TouchScreen;\n if (type == TouchDevice::DeviceType::TouchPad) {\n \/\/ Mouse events are emulated on touch pads for single touch point\n \/\/ but we need still need to consume multi-touch events if user pressed on\n p->markAsUsed();\n return;\n }\n const auto& touchPoints = touchEvent->touchPoints();\n for (auto touchPoint : touchPoints) {\n auto cefEvent = mapTouchEvent(&touchPoint, touchEvent->getDevice());\n host_->SendTouchEvent(cefEvent);\n }\n p->markAsUsed();\n\n } else if (auto wheelEvent = p->getEventAs()) {\n auto cefMouseEvent = mapMouseEvent(wheelEvent);\n host_->SendMouseWheelEvent(cefMouseEvent, static_cast(wheelEvent->delta().x),\n static_cast(wheelEvent->delta().y));\n p->markAsUsed();\n }\n}\n\nCefMouseEvent CEFInteractionHandler::mapMouseEvent(const MouseInteractionEvent* e) {\n CefMouseEvent cefEvent;\n cefEvent.x = static_cast(e->x());\n cefEvent.y = static_cast(e->canvasSize().y) - static_cast(e->y());\n cefEvent.modifiers = modifiers_;\n return cefEvent;\n}\n\nCefTouchEvent CEFInteractionHandler::mapTouchEvent(const TouchPoint* p, const TouchDevice* device) {\n CefTouchEvent cefEvent;\n cefEvent.id = p->id();\n \/\/ X coordinate relative to the left side of the view.\n cefEvent.x = static_cast(p->pos().x);\n \/\/ Y coordinate relative to the top side of the view.\n cefEvent.y = static_cast(p->canvasSize().y - p->pos().y);\n \/\/ Radius in pixels. Set to 0 if not applicable.\n cefEvent.radius_x = cefEvent.radius_y = 0;\n \/\/ Radius in pixels. Set to 0 if not applicable.\n cefEvent.rotation_angle = 0;\n \/\/ The normalized pressure of the pointer input in the range of [0,1].\n cefEvent.pressure = static_cast(p->pressure());\n \/\/ The state of the touch point. Touches begin with one CEF_TET_PRESSED event\n \/\/ followed by zero or more CEF_TET_MOVED events and finally one\n \/\/ CEF_TET_RELEASED or CEF_TET_CANCELLED event. Events not respecting this\n \/\/ order will be ignored.\n auto toCefEventType = [](auto state) -> cef_touch_event_type_t {\n switch (state) {\n case TouchState::None:\n return CEF_TET_CANCELLED;\n case TouchState::Started:\n return CEF_TET_PRESSED;\n case TouchState::Updated:\n case TouchState::Stationary:\n return CEF_TET_MOVED;\n case TouchState::Finished:\n return CEF_TET_RELEASED;\n default: \/\/ Incorrect usage or new state added (warnings if left out)\n assert(false);\n return CEF_TET_CANCELLED;\n }\n };\n\n cefEvent.type = toCefEventType(p->state());\n auto toCefPointerType = [](auto device) -> cef_pointer_type_t {\n switch (device.getType()) {\n case TouchDevice::DeviceType::TouchScreen:\n return CEF_POINTER_TYPE_TOUCH;\n case TouchDevice::DeviceType::TouchPad:\n return CEF_POINTER_TYPE_MOUSE;\n \/\/ No types for these ones yet\n \/\/ case TouchDevice::DeviceType::Pen:\n \/\/ return CEF_POINTER_TYPE_PEN;\n \/\/ case TouchDevice::DeviceType::Eraser:\n \/\/ return CEF_POINTER_TYPE_ERASER;\n default: \/\/ Incorrect usage or new state added (warnings if left out)\n assert(false);\n return CEF_POINTER_TYPE_TOUCH;\n }\n };\n cefEvent.pointer_type = toCefPointerType(*device);\n\n cefEvent.modifiers = modifiers_;\n return cefEvent;\n}\n\nCefKeyEvent CEFInteractionHandler::mapKeyEvent(const KeyboardEvent* e) {\n CefKeyEvent cefEvent;\n\n \/\/ TODO: Fix key code translation to match the ones used in CEF\n \/\/ cefEvent.type = e->state() & KeyState::Press ? KEYEVENT_RAWKEYDOWN : KEYEVENT_CHAR;\n cefEvent.type = e->state() & KeyState::Press ? KEYEVENT_KEYDOWN : KEYEVENT_KEYUP;\n \/\/ Convert character to UTF16\n#if _MSC_VER\n \/\/ Linker error when using char16_t in visual studio\n \/\/ https:\/\/social.msdn.microsoft.com\/Forums\/vstudio\/en-US\/8f40dcd8-c67f-4eba-9134-a19b9178e481\/vs-2015-rc-linker-stdcodecvt-error?forum=vcgeneral\n auto textUTF16 = std::wstring_convert, uint16_t>{}.from_bytes(\n e->text().data());\n#else\n auto textUTF16 = std::wstring_convert, char16_t>{}.from_bytes(\n e->text().data());\n#endif\n\n if (textUTF16.length() > 0) {\n cefEvent.character = textUTF16[0];\n } else {\n cefEvent.character = 0;\n }\n\n \/\/ Tested on Windows. You can test keys at\n \/\/ https:\/\/dvcs.w3.org\/hg\/d4e\/raw-file\/tip\/key-event-test.html\n \/\/ Compare the result with typing in Chrome\n cefEvent.windows_key_code = e->getNativeVirtualKey();\n \/\/ TODO: Get correct native_key_code, i.e. event LParam on Windows.\n \/\/ We might need the ScanCode sent by the system\/Qt to get this.\n \/\/ An alternative would be to convert our the KeyEvent according to the Java KeyEvent, which\n \/\/ seem to be used by Chromium. See\n \/\/ https:\/\/docs.oracle.com\/javase\/6\/docs\/api\/java\/awt\/event\/KeyEvent.html and\n \/\/ https:\/\/www.w3.org\/TR\/uievents-key\/#named-key-attribute-values\n \/\/\n \/\/ The native_key_code will be translated to DOM3 'code'\n \/\/ https:\/\/chromium.googlesource.com\/chromium\/src\/+\/master\/ui\/events\/keycodes\/dom\/keycode_converter.h\n \/\/ According to this:\n \/\/ https:\/\/chromium.googlesource.com\/chromium\/src\/+\/master\/ui\/events\/keycodes\/dom\/dom_key_data.inc\n \/\/ Note: native_key_code currently has no effect on text input fields, so text input will\n \/\/ display correctly.\n \/\/ cefEvent.native_key_code = TODO;\n\n#ifdef _WINDOWS\n \/\/ F10 or ALT\n \/\/ https:\/\/msdn.microsoft.com\/en-us\/library\/ms646286(VS.85).aspx\n cefEvent.is_system_key = (e->key() == IvwKey::F10) || (e->modifiers() & KeyModifier::Alt);\n#else\n \/\/ Always false on non-windows platforms\n cefEvent.is_system_key = false;\n#endif\n if (e->state() & KeyState::Press) {\n modifiers_ |= cef::keyModifiers(e->modifiers(), e->key());\n } else {\n modifiers_ &= ~cef::keyModifiers(e->modifiers(), e->key());\n }\n cefEvent.modifiers = modifiers_;\n return cefEvent;\n}\n\nvoid CEFInteractionHandler::updateMouseStates(MouseEvent* e) {\n if (e->state() & MouseState::Release) {\n \/\/ Remove modifiers\n modifiers_ &= ~(EVENTFLAG_LEFT_MOUSE_BUTTON | EVENTFLAG_MIDDLE_MOUSE_BUTTON |\n EVENTFLAG_MIDDLE_MOUSE_BUTTON);\n } else {\n \/\/ Add modifiers\n modifiers_ |= (e->button() & MouseButton::Left ? EVENTFLAG_LEFT_MOUSE_BUTTON : 0) |\n (e->button() & MouseButton::Middle ? EVENTFLAG_MIDDLE_MOUSE_BUTTON : 0) |\n (e->button() & MouseButton::Right ? EVENTFLAG_RIGHT_MOUSE_BUTTON : 0);\n }\n}\nvoid CEFInteractionHandler::updateMouseStates(TouchEvent* e) {\n if (e->touchPoints().front().state() & TouchState::Finished) {\n \/\/ Remove modifiers\n modifiers_ &= ~(EVENTFLAG_LEFT_MOUSE_BUTTON | EVENTFLAG_MIDDLE_MOUSE_BUTTON |\n EVENTFLAG_MIDDLE_MOUSE_BUTTON);\n } else {\n \/\/ Add modifiers\n modifiers_ |= (EVENTFLAG_LEFT_MOUSE_BUTTON);\n }\n}\n}; \/\/ namespace inviwo\nWebBrowser: mouse wheel fix, closes #1191\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2018-2021 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nnamespace inviwo {\n\nCEFInteractionHandler::CEFInteractionHandler(CefRefPtr host) : host_(host){};\n\nvoid CEFInteractionHandler::invokeEvent(Event* event) {\n switch (event->hash()) {\n case ResizeEvent::chash(): {\n if (renderHandler_) {\n auto resizeEvent = static_cast(event);\n renderHandler_->updateCanvasSize(host_->GetBrowser(), resizeEvent->size());\n host_->WasResized();\n }\n break;\n }\n case KeyboardEvent::chash(): {\n auto keyEvent = event->getAs();\n auto cefEvent = mapKeyEvent(keyEvent);\n host_->SendKeyEvent(cefEvent);\n \/\/ Send CHAR event for characters, but not non-char keys like arrows,\n \/\/ function keys or clear.\n auto isCharacter = std::iscntrl(cefEvent.character) == 0;\n if (isCharacter && (keyEvent->state() & KeyState::Press)) {\n cefEvent.type = KEYEVENT_CHAR;\n \/\/ Fixes 'Legacy' key codes for keypress events at\n \/\/ https:\/\/dvcs.w3.org\/hg\/d4e\/raw-file\/tip\/key-event-test.html\n cefEvent.windows_key_code = cefEvent.character;\n host_->SendKeyEvent(cefEvent);\n }\n event->markAsUsed();\n break;\n }\n }\n}\n\nvoid CEFInteractionHandler::handlePickingEvent(PickingEvent* p) {\n if (p->getEvent()->hash() == MouseEvent::chash()) {\n auto mouseEvent = p->getEventAs();\n updateMouseStates(mouseEvent);\n auto cefMouseEvent = mapMouseEvent(mouseEvent);\n if (mouseEvent->state() & MouseState::Move) {\n bool mouseLeave = false;\n host_->SendMouseMoveEvent(cefMouseEvent, mouseLeave);\n p->markAsUsed();\n } else if (mouseEvent->state() & MouseState::Press ||\n mouseEvent->state() & MouseState::Release) {\n CefBrowserHost::MouseButtonType type;\n\n if (mouseEvent->button() & MouseButton::Left) {\n type = MBT_LEFT;\n } else if (mouseEvent->button() & MouseButton::Middle) {\n type = MBT_MIDDLE;\n } else { \/\/ if (mouseEvent->button() & MouseButton::Right) {\n type = MBT_RIGHT;\n }\n bool mouseUp = MouseState::Release & mouseEvent->state() ? true : false;\n int clickCount = MouseState::DoubleClick & mouseEvent->state() ? 2 : 1;\n host_->SendMouseClickEvent(cefMouseEvent, type, mouseUp, clickCount);\n p->markAsUsed();\n }\n } else if (auto touchEvent = p->getEventAs()) {\n\n if (!touchEvent->hasTouchPoints()) {\n return;\n }\n TouchDevice::DeviceType type = touchEvent->getDevice()\n ? touchEvent->getDevice()->getType()\n : TouchDevice::DeviceType::TouchScreen;\n if (type == TouchDevice::DeviceType::TouchPad) {\n \/\/ Mouse events are emulated on touch pads for single touch point\n \/\/ but we need still need to consume multi-touch events if user pressed on\n p->markAsUsed();\n return;\n }\n const auto& touchPoints = touchEvent->touchPoints();\n for (auto touchPoint : touchPoints) {\n auto cefEvent = mapTouchEvent(&touchPoint, touchEvent->getDevice());\n host_->SendTouchEvent(cefEvent);\n }\n p->markAsUsed();\n\n } else if (auto wheelEvent = p->getEventAs()) {\n auto cefMouseEvent = mapMouseEvent(wheelEvent);\n \/\/ cef expects the wheel delta in multiples of 120\n \/\/ see https:\/\/magpcss.org\/ceforum\/viewtopic.php?f=6&t=18203\n host_->SendMouseWheelEvent(cefMouseEvent, static_cast(wheelEvent->delta().x * 120),\n static_cast(wheelEvent->delta().y * 120));\n p->markAsUsed();\n }\n}\n\nCefMouseEvent CEFInteractionHandler::mapMouseEvent(const MouseInteractionEvent* e) {\n CefMouseEvent cefEvent;\n cefEvent.x = static_cast(e->x());\n cefEvent.y = static_cast(e->canvasSize().y) - static_cast(e->y());\n cefEvent.modifiers = modifiers_;\n return cefEvent;\n}\n\nCefTouchEvent CEFInteractionHandler::mapTouchEvent(const TouchPoint* p, const TouchDevice* device) {\n CefTouchEvent cefEvent;\n cefEvent.id = p->id();\n \/\/ X coordinate relative to the left side of the view.\n cefEvent.x = static_cast(p->pos().x);\n \/\/ Y coordinate relative to the top side of the view.\n cefEvent.y = static_cast(p->canvasSize().y - p->pos().y);\n \/\/ Radius in pixels. Set to 0 if not applicable.\n cefEvent.radius_x = cefEvent.radius_y = 0;\n \/\/ Radius in pixels. Set to 0 if not applicable.\n cefEvent.rotation_angle = 0;\n \/\/ The normalized pressure of the pointer input in the range of [0,1].\n cefEvent.pressure = static_cast(p->pressure());\n \/\/ The state of the touch point. Touches begin with one CEF_TET_PRESSED event\n \/\/ followed by zero or more CEF_TET_MOVED events and finally one\n \/\/ CEF_TET_RELEASED or CEF_TET_CANCELLED event. Events not respecting this\n \/\/ order will be ignored.\n auto toCefEventType = [](auto state) -> cef_touch_event_type_t {\n switch (state) {\n case TouchState::None:\n return CEF_TET_CANCELLED;\n case TouchState::Started:\n return CEF_TET_PRESSED;\n case TouchState::Updated:\n case TouchState::Stationary:\n return CEF_TET_MOVED;\n case TouchState::Finished:\n return CEF_TET_RELEASED;\n default: \/\/ Incorrect usage or new state added (warnings if left out)\n assert(false);\n return CEF_TET_CANCELLED;\n }\n };\n\n cefEvent.type = toCefEventType(p->state());\n auto toCefPointerType = [](auto device) -> cef_pointer_type_t {\n switch (device.getType()) {\n case TouchDevice::DeviceType::TouchScreen:\n return CEF_POINTER_TYPE_TOUCH;\n case TouchDevice::DeviceType::TouchPad:\n return CEF_POINTER_TYPE_MOUSE;\n \/\/ No types for these ones yet\n \/\/ case TouchDevice::DeviceType::Pen:\n \/\/ return CEF_POINTER_TYPE_PEN;\n \/\/ case TouchDevice::DeviceType::Eraser:\n \/\/ return CEF_POINTER_TYPE_ERASER;\n default: \/\/ Incorrect usage or new state added (warnings if left out)\n assert(false);\n return CEF_POINTER_TYPE_TOUCH;\n }\n };\n cefEvent.pointer_type = toCefPointerType(*device);\n\n cefEvent.modifiers = modifiers_;\n return cefEvent;\n}\n\nCefKeyEvent CEFInteractionHandler::mapKeyEvent(const KeyboardEvent* e) {\n CefKeyEvent cefEvent;\n\n \/\/ TODO: Fix key code translation to match the ones used in CEF\n \/\/ cefEvent.type = e->state() & KeyState::Press ? KEYEVENT_RAWKEYDOWN : KEYEVENT_CHAR;\n cefEvent.type = e->state() & KeyState::Press ? KEYEVENT_KEYDOWN : KEYEVENT_KEYUP;\n \/\/ Convert character to UTF16\n#if _MSC_VER\n \/\/ Linker error when using char16_t in visual studio\n \/\/ https:\/\/social.msdn.microsoft.com\/Forums\/vstudio\/en-US\/8f40dcd8-c67f-4eba-9134-a19b9178e481\/vs-2015-rc-linker-stdcodecvt-error?forum=vcgeneral\n auto textUTF16 = std::wstring_convert, uint16_t>{}.from_bytes(\n e->text().data());\n#else\n auto textUTF16 = std::wstring_convert, char16_t>{}.from_bytes(\n e->text().data());\n#endif\n\n if (textUTF16.length() > 0) {\n cefEvent.character = textUTF16[0];\n } else {\n cefEvent.character = 0;\n }\n\n \/\/ Tested on Windows. You can test keys at\n \/\/ https:\/\/dvcs.w3.org\/hg\/d4e\/raw-file\/tip\/key-event-test.html\n \/\/ Compare the result with typing in Chrome\n cefEvent.windows_key_code = e->getNativeVirtualKey();\n \/\/ TODO: Get correct native_key_code, i.e. event LParam on Windows.\n \/\/ We might need the ScanCode sent by the system\/Qt to get this.\n \/\/ An alternative would be to convert our the KeyEvent according to the Java KeyEvent, which\n \/\/ seem to be used by Chromium. See\n \/\/ https:\/\/docs.oracle.com\/javase\/6\/docs\/api\/java\/awt\/event\/KeyEvent.html and\n \/\/ https:\/\/www.w3.org\/TR\/uievents-key\/#named-key-attribute-values\n \/\/\n \/\/ The native_key_code will be translated to DOM3 'code'\n \/\/ https:\/\/chromium.googlesource.com\/chromium\/src\/+\/master\/ui\/events\/keycodes\/dom\/keycode_converter.h\n \/\/ According to this:\n \/\/ https:\/\/chromium.googlesource.com\/chromium\/src\/+\/master\/ui\/events\/keycodes\/dom\/dom_key_data.inc\n \/\/ Note: native_key_code currently has no effect on text input fields, so text input will\n \/\/ display correctly.\n \/\/ cefEvent.native_key_code = TODO;\n\n#ifdef _WINDOWS\n \/\/ F10 or ALT\n \/\/ https:\/\/msdn.microsoft.com\/en-us\/library\/ms646286(VS.85).aspx\n cefEvent.is_system_key = (e->key() == IvwKey::F10) || (e->modifiers() & KeyModifier::Alt);\n#else\n \/\/ Always false on non-windows platforms\n cefEvent.is_system_key = false;\n#endif\n if (e->state() & KeyState::Press) {\n modifiers_ |= cef::keyModifiers(e->modifiers(), e->key());\n } else {\n modifiers_ &= ~cef::keyModifiers(e->modifiers(), e->key());\n }\n cefEvent.modifiers = modifiers_;\n return cefEvent;\n}\n\nvoid CEFInteractionHandler::updateMouseStates(MouseEvent* e) {\n if (e->state() & MouseState::Release) {\n \/\/ Remove modifiers\n modifiers_ &= ~(EVENTFLAG_LEFT_MOUSE_BUTTON | EVENTFLAG_MIDDLE_MOUSE_BUTTON |\n EVENTFLAG_MIDDLE_MOUSE_BUTTON);\n } else {\n \/\/ Add modifiers\n modifiers_ |= (e->button() & MouseButton::Left ? EVENTFLAG_LEFT_MOUSE_BUTTON : 0) |\n (e->button() & MouseButton::Middle ? EVENTFLAG_MIDDLE_MOUSE_BUTTON : 0) |\n (e->button() & MouseButton::Right ? EVENTFLAG_RIGHT_MOUSE_BUTTON : 0);\n }\n}\nvoid CEFInteractionHandler::updateMouseStates(TouchEvent* e) {\n if (e->touchPoints().front().state() & TouchState::Finished) {\n \/\/ Remove modifiers\n modifiers_ &= ~(EVENTFLAG_LEFT_MOUSE_BUTTON | EVENTFLAG_MIDDLE_MOUSE_BUTTON |\n EVENTFLAG_MIDDLE_MOUSE_BUTTON);\n } else {\n \/\/ Add modifiers\n modifiers_ |= (EVENTFLAG_LEFT_MOUSE_BUTTON);\n }\n}\n}; \/\/ namespace inviwo\n<|endoftext|>"} {"text":"\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2015-2016 Esteban Tovagliari, The appleseedhq Organization\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"baserenderer.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/global\/globallogger.h\"\n#ifdef APPLESEED_WITH_OIIO\n#include \"renderer\/kernel\/rendering\/oiioerrorhandler.h\"\n#endif\n#ifdef APPLESEED_WITH_OSL\n#include \"renderer\/kernel\/rendering\/rendererservices.h\"\n#include \"renderer\/kernel\/shading\/closures.h\"\n#endif\n#include \"renderer\/modeling\/project\/project.h\"\n#include \"renderer\/modeling\/scene\/scene.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/platform\/compiler.h\"\n\n\/\/ Standard headers.\n#include \n#include \n#include \n\nusing namespace foundation;\nusing namespace std;\n\nnamespace renderer\n{\n\n\/\/\n\/\/ BaseRenderer class implementation.\n\/\/\n\nBaseRenderer::BaseRenderer(\n Project& project,\n const ParamArray& params)\n : m_project(project)\n , m_params(params)\n{\n#ifdef APPLESEED_WITH_OIIO\n m_error_handler = new OIIOErrorHandler();\n\n#ifndef NDEBUG\n \/\/ While debugging, we want all possible outputs.\n m_error_handler->verbosity(OIIO::ErrorHandler::VERBOSE);\n#endif\n\n RENDERER_LOG_DEBUG(\"creating openimageio texture system...\");\n m_texture_system = OIIO::TextureSystem::create(false);\n\n m_texture_system->attribute(\"automip\", 0);\n m_texture_system->attribute(\"accept_untiled\", 1);\n m_texture_system->attribute(\"accept_unmipped\", 1);\n m_texture_system->attribute(\"gray_to_rgb\", 1);\n m_texture_system->attribute(\"latlong_up\", \"y\");\n#if OIIO_VERSION >= 10703\n m_texture_system->attribute(\"flip_t\", 1);\n#endif\n#endif\n\n#ifdef APPLESEED_WITH_OSL\n RENDERER_LOG_DEBUG(\"creating osl shading system...\");\n m_renderer_services = new RendererServices(m_project, *m_texture_system);\n\n#if OSL_LIBRARY_VERSION_CODE >= 10700\n m_shading_system = new OSL::ShadingSystem(\n#else\n m_shading_system = OSL::ShadingSystem::create(\n#endif\n m_renderer_services,\n m_texture_system,\n m_error_handler);\n\n m_shading_system->attribute(\"lockgeom\", 1);\n m_shading_system->attribute(\"colorspace\", \"Linear\");\n m_shading_system->attribute(\"commonspace\", \"world\");\n m_shading_system->attribute(\"statistics:level\", 1);\n\n m_shading_system->attribute(\n \"raytypes\",\n OSL::TypeDesc(\n OSL::TypeDesc::STRING,\n static_cast(VisibilityFlags::Count)),\n VisibilityFlags::Names);\n\n#ifndef NDEBUG\n \/\/ While debugging, we want all possible outputs.\n m_shading_system->attribute(\"debug\", 1);\n m_shading_system->attribute(\"compile_report\", 1);\n m_shading_system->attribute(\"countlayerexecs\", 1);\n m_shading_system->attribute(\"clearmemory\", 1);\n#endif\n\n \/\/ Register appleseed's closures into OSL's shading system.\n register_closures(*m_shading_system);\n#endif\n}\n\nBaseRenderer::~BaseRenderer()\n{\n#ifdef APPLESEED_WITH_OSL\n RENDERER_LOG_DEBUG(\"destroying osl shading system...\");\n m_project.get_scene()->release_optimized_osl_shader_groups();\n\n#if OSL_LIBRARY_VERSION_CODE >= 10700\n delete m_shading_system;\n#else\n OSL::ShadingSystem::destroy(m_shading_system);\n#endif\n\n delete m_renderer_services;\n#endif\n\n#ifdef APPLESEED_WITH_OIIO\n const string stats = m_texture_system->getstats();\n const string trimmed_stats = trim_right(stats, \"\\r\\n\");\n RENDERER_LOG_INFO(\"%s\", trimmed_stats.c_str());\n\n RENDERER_LOG_DEBUG(\"destroying openimageio texture system...\");\n OIIO::TextureSystem::destroy(m_texture_system);\n delete m_error_handler;\n#endif\n}\n\nParamArray& BaseRenderer::get_parameters()\n{\n return m_params;\n}\n\nconst ParamArray& BaseRenderer::get_parameters() const\n{\n return m_params;\n}\n\nbool BaseRenderer::initialize_shading_system(\n TextureStore& texture_store,\n IAbortSwitch& abort_switch)\n{\n#ifdef APPLESEED_WITH_OIIO\n initialize_oiio();\n#endif\n\n#ifdef APPLESEED_WITH_OSL\n return initialize_osl(texture_store, abort_switch);\n#else\n return true;\n#endif\n}\n\n#ifdef APPLESEED_WITH_OIIO\n\nvoid BaseRenderer::initialize_oiio()\n{\n const ParamArray& params = m_params.child(\"texture_store\");\n\n const size_t texture_cache_size_bytes =\n params.get_optional(\"max_size\", 256 * 1024 * 1024);\n\n RENDERER_LOG_INFO(\n \"setting openimageio texture cache size to %s.\",\n pretty_size(texture_cache_size_bytes).c_str());\n\n const float texture_cache_size_mb =\n static_cast(texture_cache_size_bytes) \/ (1024 * 1024);\n\n m_texture_system->attribute(\"max_memory_MB\", texture_cache_size_mb);\n\n \/\/ search paths\n string prev_search_path;\n m_texture_system->getattribute(\"searchpath\", prev_search_path);\n const string new_search_path = m_project.make_search_path_string();\n\n if (new_search_path != prev_search_path)\n {\n RENDERER_LOG_INFO(\n \"setting openimageio search path to %s.\",\n new_search_path.c_str());\n\n m_texture_system->clear();\n m_texture_system->attribute(\"searchpath\", new_search_path);\n }\n}\n\n#endif\n\n#ifdef APPLESEED_WITH_OSL\n\nbool BaseRenderer::initialize_osl(TextureStore& texture_store, IAbortSwitch& abort_switch)\n{\n m_renderer_services->initialize(texture_store);\n\n \/\/ search paths\n string prev_search_path;\n m_shading_system->getattribute(\"searchpath:shader\", prev_search_path);\n const string new_search_path = m_project.make_search_path_string();\n\n if (new_search_path != prev_search_path)\n {\n RENDERER_LOG_INFO(\n \"setting osl shader search path to %s.\",\n new_search_path.c_str());\n\n m_project.get_scene()->release_optimized_osl_shader_groups();\n m_shading_system->attribute(\"searchpath:shader\", new_search_path);\n }\n\n \/\/ Re-optimize the shader groups that need updating.\n return\n m_project.get_scene()->create_optimized_osl_shader_groups(\n *m_shading_system,\n &abort_switch);\n}\n\n#endif\n\n} \/\/ namespace renderer\nDisable high volume OSL logs in debug\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2015-2016 Esteban Tovagliari, The appleseedhq Organization\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"baserenderer.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/global\/globallogger.h\"\n#ifdef APPLESEED_WITH_OIIO\n#include \"renderer\/kernel\/rendering\/oiioerrorhandler.h\"\n#endif\n#ifdef APPLESEED_WITH_OSL\n#include \"renderer\/kernel\/rendering\/rendererservices.h\"\n#include \"renderer\/kernel\/shading\/closures.h\"\n#endif\n#include \"renderer\/modeling\/project\/project.h\"\n#include \"renderer\/modeling\/scene\/scene.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/platform\/compiler.h\"\n\n\/\/ Standard headers.\n#include \n#include \n#include \n\nusing namespace foundation;\nusing namespace std;\n\nnamespace renderer\n{\n\n\/\/\n\/\/ BaseRenderer class implementation.\n\/\/\n\nBaseRenderer::BaseRenderer(\n Project& project,\n const ParamArray& params)\n : m_project(project)\n , m_params(params)\n{\n#ifdef APPLESEED_WITH_OIIO\n m_error_handler = new OIIOErrorHandler();\n\n#ifndef NDEBUG\n \/\/ While debugging, we want all possible outputs.\n m_error_handler->verbosity(OIIO::ErrorHandler::VERBOSE);\n#endif\n\n RENDERER_LOG_DEBUG(\"creating openimageio texture system...\");\n m_texture_system = OIIO::TextureSystem::create(false);\n\n m_texture_system->attribute(\"automip\", 0);\n m_texture_system->attribute(\"accept_untiled\", 1);\n m_texture_system->attribute(\"accept_unmipped\", 1);\n m_texture_system->attribute(\"gray_to_rgb\", 1);\n m_texture_system->attribute(\"latlong_up\", \"y\");\n#if OIIO_VERSION >= 10703\n m_texture_system->attribute(\"flip_t\", 1);\n#endif\n#endif\n\n#ifdef APPLESEED_WITH_OSL\n RENDERER_LOG_DEBUG(\"creating osl shading system...\");\n m_renderer_services = new RendererServices(m_project, *m_texture_system);\n\n#if OSL_LIBRARY_VERSION_CODE >= 10700\n m_shading_system = new OSL::ShadingSystem(\n#else\n m_shading_system = OSL::ShadingSystem::create(\n#endif\n m_renderer_services,\n m_texture_system,\n m_error_handler);\n\n m_shading_system->attribute(\"lockgeom\", 1);\n m_shading_system->attribute(\"colorspace\", \"Linear\");\n m_shading_system->attribute(\"commonspace\", \"world\");\n m_shading_system->attribute(\"statistics:level\", 1);\n\n m_shading_system->attribute(\n \"raytypes\",\n OSL::TypeDesc(\n OSL::TypeDesc::STRING,\n static_cast(VisibilityFlags::Count)),\n VisibilityFlags::Names);\n\n#ifndef NDEBUG\n m_shading_system->attribute(\"compile_report\", 1);\n m_shading_system->attribute(\"countlayerexecs\", 1);\n m_shading_system->attribute(\"clearmemory\", 1);\n#endif\n\n \/\/ Register appleseed's closures into OSL's shading system.\n register_closures(*m_shading_system);\n#endif\n}\n\nBaseRenderer::~BaseRenderer()\n{\n#ifdef APPLESEED_WITH_OSL\n RENDERER_LOG_DEBUG(\"destroying osl shading system...\");\n m_project.get_scene()->release_optimized_osl_shader_groups();\n\n#if OSL_LIBRARY_VERSION_CODE >= 10700\n delete m_shading_system;\n#else\n OSL::ShadingSystem::destroy(m_shading_system);\n#endif\n\n delete m_renderer_services;\n#endif\n\n#ifdef APPLESEED_WITH_OIIO\n const string stats = m_texture_system->getstats();\n const string trimmed_stats = trim_right(stats, \"\\r\\n\");\n RENDERER_LOG_INFO(\"%s\", trimmed_stats.c_str());\n\n RENDERER_LOG_DEBUG(\"destroying openimageio texture system...\");\n OIIO::TextureSystem::destroy(m_texture_system);\n delete m_error_handler;\n#endif\n}\n\nParamArray& BaseRenderer::get_parameters()\n{\n return m_params;\n}\n\nconst ParamArray& BaseRenderer::get_parameters() const\n{\n return m_params;\n}\n\nbool BaseRenderer::initialize_shading_system(\n TextureStore& texture_store,\n IAbortSwitch& abort_switch)\n{\n#ifdef APPLESEED_WITH_OIIO\n initialize_oiio();\n#endif\n\n#ifdef APPLESEED_WITH_OSL\n return initialize_osl(texture_store, abort_switch);\n#else\n return true;\n#endif\n}\n\n#ifdef APPLESEED_WITH_OIIO\n\nvoid BaseRenderer::initialize_oiio()\n{\n const ParamArray& params = m_params.child(\"texture_store\");\n\n const size_t texture_cache_size_bytes =\n params.get_optional(\"max_size\", 256 * 1024 * 1024);\n\n RENDERER_LOG_INFO(\n \"setting openimageio texture cache size to %s.\",\n pretty_size(texture_cache_size_bytes).c_str());\n\n const float texture_cache_size_mb =\n static_cast(texture_cache_size_bytes) \/ (1024 * 1024);\n\n m_texture_system->attribute(\"max_memory_MB\", texture_cache_size_mb);\n\n \/\/ search paths\n string prev_search_path;\n m_texture_system->getattribute(\"searchpath\", prev_search_path);\n const string new_search_path = m_project.make_search_path_string();\n\n if (new_search_path != prev_search_path)\n {\n RENDERER_LOG_INFO(\n \"setting openimageio search path to %s.\",\n new_search_path.c_str());\n\n m_texture_system->clear();\n m_texture_system->attribute(\"searchpath\", new_search_path);\n }\n}\n\n#endif\n\n#ifdef APPLESEED_WITH_OSL\n\nbool BaseRenderer::initialize_osl(TextureStore& texture_store, IAbortSwitch& abort_switch)\n{\n m_renderer_services->initialize(texture_store);\n\n \/\/ search paths\n string prev_search_path;\n m_shading_system->getattribute(\"searchpath:shader\", prev_search_path);\n const string new_search_path = m_project.make_search_path_string();\n\n if (new_search_path != prev_search_path)\n {\n RENDERER_LOG_INFO(\n \"setting osl shader search path to %s.\",\n new_search_path.c_str());\n\n m_project.get_scene()->release_optimized_osl_shader_groups();\n m_shading_system->attribute(\"searchpath:shader\", new_search_path);\n }\n\n \/\/ Re-optimize the shader groups that need updating.\n return\n m_project.get_scene()->create_optimized_osl_shader_groups(\n *m_shading_system,\n &abort_switch);\n}\n\n#endif\n\n} \/\/ namespace renderer\n<|endoftext|>"} {"text":"\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \n#include \"mitkException.h\"\n#include \n#include \n\n#include \n#include \"mitkIOUtil.h\"\n#include \"mitkITKImageImport.h\"\n\n#include \"itksys\/SystemTools.hxx\"\n#include \n\n#include \n#include \n\n#ifdef WIN32\n#include \"process.h\"\n#else\n#include \n#endif\n\nclass mitkItkImageIOTestSuite : public mitk::TestFixture\n{\n CPPUNIT_TEST_SUITE(mitkItkImageIOTestSuite);\n MITK_TEST(TestImageWriterJpg);\n MITK_TEST(TestImageWriterPng1);\n MITK_TEST(TestImageWriterPng2);\n MITK_TEST(TestImageWriterPng3);\n MITK_TEST(TestImageWriterSimple);\n MITK_TEST(TestWrite3DImageWithOnePlane);\n MITK_TEST(TestWrite3DImageWithTwoPlanes);\n CPPUNIT_TEST_SUITE_END();\n\npublic:\n\n void setUp() override\n {\n\n }\n\n void tearDown() override\n {\n }\n\n\n void TestImageWriterJpg()\n {\n TestImageWriter(\"NrrdWritingTestImage.jpg\");\n }\n\n void TestImageWriterPng1()\n {\n TestImageWriter(\"Png2D-bw.png\");\n }\n\n void TestImageWriterPng2()\n {\n TestImageWriter(\"RenderingTestData\/rgbImage.png\");\n }\n\n void TestImageWriterPng3()\n {\n TestImageWriter(\"RenderingTestData\/rgbaImage.png\");\n }\n\n void TestImageWriterSimple()\n {\n \/\/ TODO\n }\n\n std::string AppendExtension(const std::string &filename, const char *extension)\n {\n std::string new_filename = filename;\n\n new_filename += extension;\n return new_filename;\n }\n\n bool CompareImageMetaData( mitk::Image::Pointer image, mitk::Image::Pointer reference, bool checkPixelType = true )\n {\n \/\/ switch to AreIdentical() methods as soon as Bug 11925 (Basic comparison operators) is fixed\n\n if( image->GetDimension() != reference->GetDimension() )\n {\n MITK_ERROR << \"The image dimension differs: IN (\" << image->GetDimension() << \") REF(\" << reference->GetDimension() << \")\";\n return false;\n }\n\n \/\/ pixel type\n if( checkPixelType &&\n ( image->GetPixelType() != reference->GetPixelType()\n && image->GetPixelType().GetBitsPerComponent() != reference->GetPixelType().GetBitsPerComponent() ) )\n {\n MITK_ERROR << \"Pixeltype differs ( image=\" << image->GetPixelType().GetPixelTypeAsString() << \"[\" << image->GetPixelType().GetBitsPerComponent() << \"]\" << \" reference=\" << reference->GetPixelType().GetPixelTypeAsString() << \"[\" << reference->GetPixelType().GetBitsPerComponent() << \"]\" << \" )\";\n return false;\n }\n\n return true;\n }\n\n\n \/*\n Test writing picture formats like *.bmp, *.png, *.tiff or *.jpg\n NOTE: Saving as picture format must ignore PixelType comparison - not all bits per components are supported (see specification of the format)\n *\/\n void TestPictureWriting(mitk::Image* image, const std::string& filename, const std::string& extension)\n {\n const std::string fullFileName = AppendExtension(filename, extension.c_str());\n\n mitk::Image::Pointer singleSliceImage = NULL;\n if( image->GetDimension() == 3 )\n {\n mitk::ExtractSliceFilter::Pointer extractFilter = mitk::ExtractSliceFilter::New();\n extractFilter->SetInput( image );\n extractFilter->SetWorldGeometry( image->GetSlicedGeometry()->GetPlaneGeometry(0) );\n\n extractFilter->Update();\n singleSliceImage = extractFilter->GetOutput();\n\n \/\/ test 3D writing in format supporting only 2D\n mitk::IOUtil::Save(image, fullFileName);\n\n \/\/ test images\n unsigned int foundImagesCount = 0;\n\n \/\/if the image only contains one sinlge slice the itkImageSeriesWriter won't add a number like filename.XX.extension\n if(image->GetDimension(2) == 1)\n {\n std::stringstream series_filenames;\n series_filenames << filename << extension;\n mitk::Image::Pointer compareImage = mitk::IOUtil::LoadImage( series_filenames.str() );\n if( compareImage.IsNotNull() )\n {\n foundImagesCount++;\n MITK_TEST_CONDITION(CompareImageMetaData( singleSliceImage, compareImage, false ), \"Image meta data unchanged after writing and loading again. \"); \/\/ignore bits per component\n }\n remove( series_filenames.str().c_str() );\n }\n else \/\/test the whole slice stack\n {\n for( unsigned int i=0; i< image->GetDimension(2); i++)\n {\n std::stringstream series_filenames;\n series_filenames << filename << \".\" << i+1 << extension;\n mitk::Image::Pointer compareImage = mitk::IOUtil::LoadImage( series_filenames.str() );\n if( compareImage.IsNotNull() )\n {\n foundImagesCount++;\n MITK_TEST_CONDITION(CompareImageMetaData( singleSliceImage, compareImage, false ), \"Image meta data unchanged after writing and loading again. \"); \/\/ignore bits per component\n }\n remove( series_filenames.str().c_str() );\n }\n }\n MITK_TEST_CONDITION( foundImagesCount == image->GetDimension(2), \"All 2D-Slices of a 3D image were stored correctly.\");\n }\n else if( image->GetDimension() == 2 )\n {\n singleSliceImage = image;\n }\n\n \/\/ test 2D writing\n if( singleSliceImage.IsNotNull() )\n {\n try\n {\n mitk::IOUtil::Save(singleSliceImage, fullFileName);\n\n mitk::Image::Pointer compareImage = mitk::IOUtil::LoadImage(fullFileName.c_str());\n MITK_TEST_CONDITION_REQUIRED( compareImage.IsNotNull(), \"Image stored was succesfully loaded again\");\n\n MITK_TEST_CONDITION_REQUIRED( CompareImageMetaData(singleSliceImage, compareImage, false ), \"Image meta data unchanged after writing and loading again. \");\/\/ignore bits per component\n remove(fullFileName.c_str());\n }\n catch(itk::ExceptionObject &e)\n {\n MITK_TEST_FAILED_MSG(<< \"Exception during file writing for .\" << extension << \": \" << e.what() );\n }\n\n }\n\n }\n\n \/**\n * test for \"ImageWriter\".\n *\n * argc and argv are the command line parameters which were passed to\n * the ADD_TEST command in the CMakeLists.txt file. For the automatic\n * tests, argv is either empty for the simple tests or contains the filename\n * of a test image for the image tests (see CMakeLists.txt).\n *\/\n void TestImageWriter(std::string sourcefile)\n {\n\n sourcefile = GetTestDataFilePath(sourcefile);\n\n \/\/ load image\n CPPUNIT_ASSERT_MESSAGE(\"Checking whether source image exists\", itksys::SystemTools::FileExists(sourcefile.c_str()));\n\n mitk::Image::Pointer image = NULL;\n\n try\n {\n image = mitk::IOUtil::LoadImage( sourcefile );\n }\n catch (...)\n {\n CPPUNIT_FAIL(\"Exception during file loading:\");\n }\n\n CPPUNIT_ASSERT_MESSAGE(\"loaded image not NULL\", image.IsNotNull());\n\n \/\/ write ITK .mhd image (2D and 3D only)\n if( image->GetDimension() <= 3 )\n {\n std::ofstream tmpStream;\n std::string tmpFilePath = mitk::IOUtil::CreateTemporaryFile(tmpStream, \"XXXXXX.mhd\");\n tmpStream.close();\n\n std::string tmpFilePathWithoutExt = tmpFilePath.substr(0, tmpFilePath.size() - 4);\n\n try\n {\n mitk::IOUtil::Save(image, tmpFilePath);\n\n mitk::Image::Pointer compareImage = mitk::IOUtil::LoadImage(tmpFilePath);\n CPPUNIT_ASSERT_MESSAGE(\"Image stored in MHD format was succesfully loaded again! \", compareImage.IsNotNull());\n\n\n CPPUNIT_ASSERT_MESSAGE(\".mhd file exists\", itksys::SystemTools::FileExists((tmpFilePathWithoutExt + \".mhd\").c_str()));\n CPPUNIT_ASSERT_MESSAGE(\".raw or .zraw exists\", itksys::SystemTools::FileExists((tmpFilePathWithoutExt + \".raw\").c_str()) ||\n itksys::SystemTools::FileExists((tmpFilePathWithoutExt + \".zraw\").c_str()));\n\n \/\/ delete\n remove(tmpFilePath.c_str());\n remove((tmpFilePathWithoutExt + \".raw\").c_str());\n remove((tmpFilePathWithoutExt + \".zraw\").c_str());\n }\n catch (...)\n {\n CPPUNIT_FAIL(\"Exception during.mhd file writing\");\n }\n }\n\n \/\/testing more component image writing as nrrd files\n\n {\n std::ofstream tmpStream;\n std::string tmpFilePath = mitk::IOUtil::CreateTemporaryFile(tmpStream, \"XXXXXX.nrrd\");\n tmpStream.close();\n\n try\n {\n mitk::IOUtil::Save(image, tmpFilePath);\n\n mitk::Image::Pointer compareImage = mitk::IOUtil::LoadImage(tmpFilePath);\n CPPUNIT_ASSERT_MESSAGE(\"Image stored in NRRD format was succesfully loaded again\", compareImage.IsNotNull());\n\n remove(tmpFilePath.c_str());\n }\n catch(...)\n {\n std::remove(tmpFilePath.c_str());\n CPPUNIT_FAIL(\"Exception during.mhd file writing\");\n }\n }\n\n std::ofstream tmpStream;\n std::string tmpFilePath = mitk::IOUtil::CreateTemporaryFile(tmpStream, \"XXXXXX\");\n tmpStream.close();\n\n TestPictureWriting(image, tmpFilePath, \".png\");\n TestPictureWriting(image, tmpFilePath, \".jpg\");\n TestPictureWriting(image, tmpFilePath, \".tiff\");\n TestPictureWriting(image, tmpFilePath, \".bmp\");\n \/\/ always end with this!\n\n }\n\n \/**\n * Try to write a 3D image with only one plane (a 2D images in disguise for all intents and purposes)\n *\/\n void TestWrite3DImageWithOnePlane(){\n typedef itk::Image ImageType;\n\n ImageType::Pointer itkImage = ImageType::New();\n\n ImageType::IndexType start;\n start.Fill(0);\n\n ImageType::SizeType size;\n size[0] = 100;\n size[1] = 100;\n size[2] = 1;\n\n ImageType::RegionType region;\n region.SetSize(size);\n region.SetIndex(start);\n itkImage->SetRegions(region);\n itkImage->Allocate();\n itkImage->FillBuffer(0);\n\n itk::ImageRegionIterator imageIterator(itkImage, itkImage->GetLargestPossibleRegion());\n\n \/\/ Make two squares\n while (!imageIterator.IsAtEnd())\n {\n if ((imageIterator.GetIndex()[0] > 5 && imageIterator.GetIndex()[0] < 20) &&\n (imageIterator.GetIndex()[1] > 5 && imageIterator.GetIndex()[1] < 20))\n {\n imageIterator.Set(255);\n }\n\n if ((imageIterator.GetIndex()[0] > 50 && imageIterator.GetIndex()[0] < 70) &&\n (imageIterator.GetIndex()[1] > 50 && imageIterator.GetIndex()[1] < 70))\n {\n imageIterator.Set(60);\n }\n ++imageIterator;\n }\n\n mitk::Image::Pointer image = mitk::ImportItkImage(itkImage);\n\n mitk::IOUtil::SaveImage(image, mitk::IOUtil::CreateTemporaryFile(\"3Dto2DTestImageXXXXXX.nrrd\"));\n mitk::IOUtil::SaveImage(image, mitk::IOUtil::CreateTemporaryFile(\"3Dto2DTestImageXXXXXX.png\"));\n\n }\n\n \/**\n * Try to write a 3D image with only one plane (a 2D images in disguise for all intents and purposes)\n *\/\n void TestWrite3DImageWithTwoPlanes(){\n typedef itk::Image ImageType;\n\n ImageType::Pointer itkImage = ImageType::New();\n\n ImageType::IndexType start;\n start.Fill(0);\n\n ImageType::SizeType size;\n size[0] = 100;\n size[1] = 100;\n size[2] = 2;\n\n ImageType::RegionType region;\n region.SetSize(size);\n region.SetIndex(start);\n itkImage->SetRegions(region);\n itkImage->Allocate();\n itkImage->FillBuffer(0);\n\n itk::ImageRegionIterator imageIterator(itkImage, itkImage->GetLargestPossibleRegion());\n\n \/\/ Make two squares\n while (!imageIterator.IsAtEnd())\n {\n if ((imageIterator.GetIndex()[0] > 5 && imageIterator.GetIndex()[0] < 20) &&\n (imageIterator.GetIndex()[1] > 5 && imageIterator.GetIndex()[1] < 20))\n {\n imageIterator.Set(255);\n }\n if ((imageIterator.GetIndex()[0] > 50 && imageIterator.GetIndex()[0] < 70) &&\n (imageIterator.GetIndex()[1] > 50 && imageIterator.GetIndex()[1] < 70))\n {\n imageIterator.Set(60);\n }\n ++imageIterator;\n }\n mitk::Image::Pointer image = mitk::ImportItkImage(itkImage);\n\n mitk::IOUtil::SaveImage(image, mitk::IOUtil::CreateTemporaryFile(\"3Dto2DTestImageXXXXXX.nrrd\"));\n\n CPPUNIT_ASSERT_THROW(mitk::IOUtil::SaveImage(image, mitk::IOUtil::CreateTemporaryFile(\"3Dto2DTestImageXXXXXX.png\")), mitk::Exception);\n\n }\n\n};\n\nMITK_TEST_SUITE_REGISTRATION(mitkItkImageIO)\nadded tests for mitkItkImageIoTest to check different geometry types.\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \n#include \"mitkException.h\"\n#include \n#include \n\n#include \n#include \"mitkIOUtil.h\"\n#include \"mitkITKImageImport.h\"\n\n#include \"itksys\/SystemTools.hxx\"\n#include \n\n#include \n#include \n\n#ifdef WIN32\n#include \"process.h\"\n#else\n#include \n#endif\n\nclass mitkItkImageIOTestSuite : public mitk::TestFixture\n{\n CPPUNIT_TEST_SUITE(mitkItkImageIOTestSuite);\n MITK_TEST(TestImageWriterJpg);\n MITK_TEST(TestImageWriterPng1);\n MITK_TEST(TestImageWriterPng2);\n MITK_TEST(TestImageWriterPng3);\n MITK_TEST(TestImageWriterSimple);\n MITK_TEST(TestWrite3DImageWithOnePlane);\n MITK_TEST(TestWrite3DImageWithTwoPlanes);\n MITK_TEST(TestWrite3DplusT_ArbitraryTG);\n MITK_TEST(TestWrite3DplusT_ProportionalTG);\n CPPUNIT_TEST_SUITE_END();\n\npublic:\n\n void setUp() override\n {\n\n }\n\n void tearDown() override\n {\n }\n\n\n void TestImageWriterJpg()\n {\n TestImageWriter(\"NrrdWritingTestImage.jpg\");\n }\n\n void TestImageWriterPng1()\n {\n TestImageWriter(\"Png2D-bw.png\");\n }\n\n void TestImageWriterPng2()\n {\n TestImageWriter(\"RenderingTestData\/rgbImage.png\");\n }\n\n void TestImageWriterPng3()\n {\n TestImageWriter(\"RenderingTestData\/rgbaImage.png\");\n }\n\n void TestWrite3DplusT_ArbitraryTG()\n {\n TestImageWriter(\"3D+t-ITKIO-TestData\/LinearModel_4D_arbitrary_time_geometry.nrrd\");\n }\n\n void TestWrite3DplusT_ProportionalTG()\n {\n TestImageWriter(\"3D+t-ITKIO-TestData\/LinearModel_4D_prop_time_geometry.nrrd\");\n }\n\n void TestImageWriterSimple()\n {\n \/\/ TODO\n }\n\n std::string AppendExtension(const std::string &filename, const char *extension)\n {\n std::string new_filename = filename;\n\n new_filename += extension;\n return new_filename;\n }\n\n bool CompareImageMetaData( mitk::Image::Pointer image, mitk::Image::Pointer reference, bool checkPixelType = true )\n {\n \/\/ switch to AreIdentical() methods as soon as Bug 11925 (Basic comparison operators) is fixed\n\n if( image->GetDimension() != reference->GetDimension() )\n {\n MITK_ERROR << \"The image dimension differs: IN (\" << image->GetDimension() << \") REF(\" << reference->GetDimension() << \")\";\n return false;\n }\n\n \/\/ pixel type\n if( checkPixelType &&\n ( image->GetPixelType() != reference->GetPixelType()\n && image->GetPixelType().GetBitsPerComponent() != reference->GetPixelType().GetBitsPerComponent() ) )\n {\n MITK_ERROR << \"Pixeltype differs ( image=\" << image->GetPixelType().GetPixelTypeAsString() << \"[\" << image->GetPixelType().GetBitsPerComponent() << \"]\" << \" reference=\" << reference->GetPixelType().GetPixelTypeAsString() << \"[\" << reference->GetPixelType().GetBitsPerComponent() << \"]\" << \" )\";\n return false;\n }\n\n return true;\n }\n\n\n \/*\n Test writing picture formats like *.bmp, *.png, *.tiff or *.jpg\n NOTE: Saving as picture format must ignore PixelType comparison - not all bits per components are supported (see specification of the format)\n *\/\n void TestPictureWriting(mitk::Image* image, const std::string& filename, const std::string& extension)\n {\n const std::string fullFileName = AppendExtension(filename, extension.c_str());\n\n mitk::Image::Pointer singleSliceImage = NULL;\n if( image->GetDimension() == 3 )\n {\n mitk::ExtractSliceFilter::Pointer extractFilter = mitk::ExtractSliceFilter::New();\n extractFilter->SetInput( image );\n extractFilter->SetWorldGeometry( image->GetSlicedGeometry()->GetPlaneGeometry(0) );\n\n extractFilter->Update();\n singleSliceImage = extractFilter->GetOutput();\n\n \/\/ test 3D writing in format supporting only 2D\n mitk::IOUtil::Save(image, fullFileName);\n\n \/\/ test images\n unsigned int foundImagesCount = 0;\n\n \/\/if the image only contains one sinlge slice the itkImageSeriesWriter won't add a number like filename.XX.extension\n if(image->GetDimension(2) == 1)\n {\n std::stringstream series_filenames;\n series_filenames << filename << extension;\n mitk::Image::Pointer compareImage = mitk::IOUtil::LoadImage( series_filenames.str() );\n if( compareImage.IsNotNull() )\n {\n foundImagesCount++;\n MITK_TEST_CONDITION(CompareImageMetaData( singleSliceImage, compareImage, false ), \"Image meta data unchanged after writing and loading again. \"); \/\/ignore bits per component\n }\n remove( series_filenames.str().c_str() );\n }\n else \/\/test the whole slice stack\n {\n for( unsigned int i=0; i< image->GetDimension(2); i++)\n {\n std::stringstream series_filenames;\n series_filenames << filename << \".\" << i+1 << extension;\n mitk::Image::Pointer compareImage = mitk::IOUtil::LoadImage( series_filenames.str() );\n if( compareImage.IsNotNull() )\n {\n foundImagesCount++;\n MITK_TEST_CONDITION(CompareImageMetaData( singleSliceImage, compareImage, false ), \"Image meta data unchanged after writing and loading again. \"); \/\/ignore bits per component\n }\n remove( series_filenames.str().c_str() );\n }\n }\n MITK_TEST_CONDITION( foundImagesCount == image->GetDimension(2), \"All 2D-Slices of a 3D image were stored correctly.\");\n }\n else if( image->GetDimension() == 2 )\n {\n singleSliceImage = image;\n }\n\n \/\/ test 2D writing\n if( singleSliceImage.IsNotNull() )\n {\n try\n {\n mitk::IOUtil::Save(singleSliceImage, fullFileName);\n\n mitk::Image::Pointer compareImage = mitk::IOUtil::LoadImage(fullFileName.c_str());\n MITK_TEST_CONDITION_REQUIRED( compareImage.IsNotNull(), \"Image stored was succesfully loaded again\");\n\n MITK_TEST_CONDITION_REQUIRED( CompareImageMetaData(singleSliceImage, compareImage, false ), \"Image meta data unchanged after writing and loading again. \");\/\/ignore bits per component\n remove(fullFileName.c_str());\n }\n catch(itk::ExceptionObject &e)\n {\n MITK_TEST_FAILED_MSG(<< \"Exception during file writing for .\" << extension << \": \" << e.what() );\n }\n\n }\n\n }\n\n \/**\n * test for \"ImageWriter\".\n *\n * argc and argv are the command line parameters which were passed to\n * the ADD_TEST command in the CMakeLists.txt file. For the automatic\n * tests, argv is either empty for the simple tests or contains the filename\n * of a test image for the image tests (see CMakeLists.txt).\n *\/\n void TestImageWriter(std::string sourcefile)\n {\n\n sourcefile = GetTestDataFilePath(sourcefile);\n\n \/\/ load image\n CPPUNIT_ASSERT_MESSAGE(\"Checking whether source image exists\", itksys::SystemTools::FileExists(sourcefile.c_str()));\n\n mitk::Image::Pointer image = NULL;\n\n try\n {\n image = mitk::IOUtil::LoadImage( sourcefile );\n }\n catch (...)\n {\n CPPUNIT_FAIL(\"Exception during file loading:\");\n }\n\n CPPUNIT_ASSERT_MESSAGE(\"loaded image not NULL\", image.IsNotNull());\n\n \/\/ write ITK .mhd image (2D and 3D only)\n if( image->GetDimension() <= 3 )\n {\n std::ofstream tmpStream;\n std::string tmpFilePath = mitk::IOUtil::CreateTemporaryFile(tmpStream, \"XXXXXX.mhd\");\n tmpStream.close();\n\n std::string tmpFilePathWithoutExt = tmpFilePath.substr(0, tmpFilePath.size() - 4);\n\n try\n {\n mitk::IOUtil::Save(image, tmpFilePath);\n\n mitk::Image::Pointer compareImage = mitk::IOUtil::LoadImage(tmpFilePath);\n CPPUNIT_ASSERT_MESSAGE(\"Image stored in MHD format was succesfully loaded again! \", compareImage.IsNotNull());\n\n\n CPPUNIT_ASSERT_MESSAGE(\".mhd file exists\", itksys::SystemTools::FileExists((tmpFilePathWithoutExt + \".mhd\").c_str()));\n CPPUNIT_ASSERT_MESSAGE(\".raw or .zraw exists\", itksys::SystemTools::FileExists((tmpFilePathWithoutExt + \".raw\").c_str()) ||\n itksys::SystemTools::FileExists((tmpFilePathWithoutExt + \".zraw\").c_str()));\n\n \/\/ delete\n remove(tmpFilePath.c_str());\n remove((tmpFilePathWithoutExt + \".raw\").c_str());\n remove((tmpFilePathWithoutExt + \".zraw\").c_str());\n }\n catch (...)\n {\n CPPUNIT_FAIL(\"Exception during.mhd file writing\");\n }\n }\n\n \/\/testing more component image writing as nrrd files\n\n {\n std::ofstream tmpStream;\n std::string tmpFilePath = mitk::IOUtil::CreateTemporaryFile(tmpStream, \"XXXXXX.nrrd\");\n tmpStream.close();\n\n try\n {\n mitk::IOUtil::Save(image, tmpFilePath);\n\n mitk::Image::Pointer compareImage = mitk::IOUtil::LoadImage(tmpFilePath);\n CPPUNIT_ASSERT_MESSAGE(\"Image stored in NRRD format was succesfully loaded again\", compareImage.IsNotNull());\n\n remove(tmpFilePath.c_str());\n }\n catch(...)\n {\n std::remove(tmpFilePath.c_str());\n CPPUNIT_FAIL(\"Exception during.mhd file writing\");\n }\n }\n\n std::ofstream tmpStream;\n std::string tmpFilePath = mitk::IOUtil::CreateTemporaryFile(tmpStream, \"XXXXXX\");\n tmpStream.close();\n\n TestPictureWriting(image, tmpFilePath, \".png\");\n TestPictureWriting(image, tmpFilePath, \".jpg\");\n TestPictureWriting(image, tmpFilePath, \".tiff\");\n TestPictureWriting(image, tmpFilePath, \".bmp\");\n \/\/ always end with this!\n\n }\n\n \/**\n * Try to write a 3D image with only one plane (a 2D images in disguise for all intents and purposes)\n *\/\n void TestWrite3DImageWithOnePlane(){\n typedef itk::Image ImageType;\n\n ImageType::Pointer itkImage = ImageType::New();\n\n ImageType::IndexType start;\n start.Fill(0);\n\n ImageType::SizeType size;\n size[0] = 100;\n size[1] = 100;\n size[2] = 1;\n\n ImageType::RegionType region;\n region.SetSize(size);\n region.SetIndex(start);\n itkImage->SetRegions(region);\n itkImage->Allocate();\n itkImage->FillBuffer(0);\n\n itk::ImageRegionIterator imageIterator(itkImage, itkImage->GetLargestPossibleRegion());\n\n \/\/ Make two squares\n while (!imageIterator.IsAtEnd())\n {\n if ((imageIterator.GetIndex()[0] > 5 && imageIterator.GetIndex()[0] < 20) &&\n (imageIterator.GetIndex()[1] > 5 && imageIterator.GetIndex()[1] < 20))\n {\n imageIterator.Set(255);\n }\n\n if ((imageIterator.GetIndex()[0] > 50 && imageIterator.GetIndex()[0] < 70) &&\n (imageIterator.GetIndex()[1] > 50 && imageIterator.GetIndex()[1] < 70))\n {\n imageIterator.Set(60);\n }\n ++imageIterator;\n }\n\n mitk::Image::Pointer image = mitk::ImportItkImage(itkImage);\n\n mitk::IOUtil::SaveImage(image, mitk::IOUtil::CreateTemporaryFile(\"3Dto2DTestImageXXXXXX.nrrd\"));\n mitk::IOUtil::SaveImage(image, mitk::IOUtil::CreateTemporaryFile(\"3Dto2DTestImageXXXXXX.png\"));\n\n }\n\n \/**\n * Try to write a 3D image with only one plane (a 2D images in disguise for all intents and purposes)\n *\/\n void TestWrite3DImageWithTwoPlanes(){\n typedef itk::Image ImageType;\n\n ImageType::Pointer itkImage = ImageType::New();\n\n ImageType::IndexType start;\n start.Fill(0);\n\n ImageType::SizeType size;\n size[0] = 100;\n size[1] = 100;\n size[2] = 2;\n\n ImageType::RegionType region;\n region.SetSize(size);\n region.SetIndex(start);\n itkImage->SetRegions(region);\n itkImage->Allocate();\n itkImage->FillBuffer(0);\n\n itk::ImageRegionIterator imageIterator(itkImage, itkImage->GetLargestPossibleRegion());\n\n \/\/ Make two squares\n while (!imageIterator.IsAtEnd())\n {\n if ((imageIterator.GetIndex()[0] > 5 && imageIterator.GetIndex()[0] < 20) &&\n (imageIterator.GetIndex()[1] > 5 && imageIterator.GetIndex()[1] < 20))\n {\n imageIterator.Set(255);\n }\n if ((imageIterator.GetIndex()[0] > 50 && imageIterator.GetIndex()[0] < 70) &&\n (imageIterator.GetIndex()[1] > 50 && imageIterator.GetIndex()[1] < 70))\n {\n imageIterator.Set(60);\n }\n ++imageIterator;\n }\n mitk::Image::Pointer image = mitk::ImportItkImage(itkImage);\n\n mitk::IOUtil::SaveImage(image, mitk::IOUtil::CreateTemporaryFile(\"3Dto2DTestImageXXXXXX.nrrd\"));\n\n CPPUNIT_ASSERT_THROW(mitk::IOUtil::SaveImage(image, mitk::IOUtil::CreateTemporaryFile(\"3Dto2DTestImageXXXXXX.png\")), mitk::Exception);\n\n }\n\n};\n\nMITK_TEST_SUITE_REGISTRATION(mitkItkImageIO)\n<|endoftext|>"} {"text":"\/*\n OpenDeck MIDI platform firmware\n Copyright (C) 2015-2018 Igor Petrovic\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see .\n*\/\n\n#include \"DigitalInput.h\"\n#include \"board\/Board.h\"\n#include \"Variables.h\"\n#include \"database\/Database.h\"\n\n\/\/\/\n\/\/\/ \\brief Used for buttonPCinc\/buttonPCdec messages when each button press\/encoder rotation sends incremented or decremented PC value.\n\/\/\/ 16 entries in array are used for 16 MIDI channels.\n\/\/\/\nuint8_t lastPCvalue[16];\n\n\/\/\/\n\/\/\/ \\brief Array holding state for all encoders (whether they're enabled or disabled).\n\/\/\/\nuint8_t encoderEnabled[MAX_NUMBER_OF_ENCODERS\/8+1];\n\n\n\/\/\/\n\/\/\/ \\brief Default constructor.\n\/\/\/\nDigitalInput::DigitalInput()\n{\n \n}\n\n\/\/\/\n\/\/\/ \\brief Used to store specific parameters from EEPROM to internal arrays for faster access.\n\/\/\/\nvoid DigitalInput::init()\n{\n \/\/store some parameters from eeprom to ram for faster access\n for (int i=0; iremove debug leftovers\/*\n OpenDeck MIDI platform firmware\n Copyright (C) 2015-2018 Igor Petrovic\n\n This program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see .\n*\/\n\n#include \"DigitalInput.h\"\n#include \"board\/Board.h\"\n#include \"Variables.h\"\n#include \"database\/Database.h\"\n\n\/\/\/\n\/\/\/ \\brief Used for buttonPCinc\/buttonPCdec messages when each button press\/encoder rotation sends incremented or decremented PC value.\n\/\/\/ 16 entries in array are used for 16 MIDI channels.\n\/\/\/\nuint8_t lastPCvalue[16];\n\n\/\/\/\n\/\/\/ \\brief Array holding state for all encoders (whether they're enabled or disabled).\n\/\/\/\nuint8_t encoderEnabled[MAX_NUMBER_OF_ENCODERS\/8+1];\n\n\n\/\/\/\n\/\/\/ \\brief Default constructor.\n\/\/\/\nDigitalInput::DigitalInput()\n{\n \n}\n\n\/\/\/\n\/\/\/ \\brief Used to store specific parameters from EEPROM to internal arrays for faster access.\n\/\/\/\nvoid DigitalInput::init()\n{\n \/\/store some parameters from eeprom to ram for faster access\n for (int i=0; i"} {"text":"\/*************************************************************************\n *\n * $RCSfile: rangeseq.cxx,v $\n *\n * $Revision: 1.1.1.1 $\n *\n * last change: $Author: hr $ $Date: 2000-09-19 00:16:18 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifdef PCH\n#include \"core_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n#include \n#include \n\n#include \n#include \n\n#include \"rangeseq.hxx\"\n#include \"document.hxx\"\n#include \"scmatrix.hxx\"\n\nusing namespace com::sun::star;\n\n\/\/------------------------------------------------------------------------\n\nlong lcl_DoubleToLong( double fVal )\n{\n double fInt = (fVal >= 0.0) ? SolarMath::ApproxFloor( fVal ) :\n SolarMath::ApproxCeil( fVal );\n if ( fInt >= LONG_MIN && fInt <= LONG_MAX )\n return (long)fInt;\n else\n return 0.0; \/\/ out of range\n}\n\nBOOL ScRangeToSequence::FillLongArray( uno::Any& rAny, ScDocument* pDoc, const ScRange& rRange )\n{\n USHORT nTab = rRange.aStart.Tab();\n USHORT nStartCol = rRange.aStart.Col();\n USHORT nStartRow = rRange.aStart.Row();\n long nColCount = rRange.aEnd.Col() + 1 - rRange.aStart.Col();\n long nRowCount = rRange.aEnd.Row() + 1 - rRange.aStart.Row();\n\n uno::Sequence< uno::Sequence > aRowSeq( nRowCount );\n uno::Sequence* pRowAry = aRowSeq.getArray();\n for (long nRow = 0; nRow < nRowCount; nRow++)\n {\n uno::Sequence aColSeq( nColCount );\n INT32* pColAry = aColSeq.getArray();\n for (long nCol = 0; nCol < nColCount; nCol++)\n pColAry[nCol] = lcl_DoubleToLong( pDoc->GetValue(\n ScAddress( (USHORT)(nStartCol+nCol), (USHORT)(nStartRow+nRow), nTab ) ) );\n\n pRowAry[nRow] = aColSeq;\n }\n\n rAny <<= aRowSeq;\n return TRUE; \/\/! check for errors\n}\n\n\nBOOL ScRangeToSequence::FillLongArray( uno::Any& rAny, const ScMatrix* pMatrix )\n{\n if (!pMatrix)\n return FALSE;\n\n USHORT nColCount, nRowCount;\n pMatrix->GetDimensions( nColCount, nRowCount );\n\n uno::Sequence< uno::Sequence > aRowSeq( nRowCount );\n uno::Sequence* pRowAry = aRowSeq.getArray();\n for (USHORT nRow = 0; nRow < nRowCount; nRow++)\n {\n uno::Sequence aColSeq( nColCount );\n INT32* pColAry = aColSeq.getArray();\n for (USHORT nCol = 0; nCol < nColCount; nCol++)\n if ( pMatrix->IsString( nCol, nRow ) )\n pColAry[nCol] = 0;\n else\n pColAry[nCol] = lcl_DoubleToLong( pMatrix->GetDouble( nCol, nRow ) );\n\n pRowAry[nRow] = aColSeq;\n }\n\n rAny <<= aRowSeq;\n return TRUE;\n}\n\n\/\/------------------------------------------------------------------------\n\nBOOL ScRangeToSequence::FillDoubleArray( uno::Any& rAny, ScDocument* pDoc, const ScRange& rRange )\n{\n USHORT nTab = rRange.aStart.Tab();\n USHORT nStartCol = rRange.aStart.Col();\n USHORT nStartRow = rRange.aStart.Row();\n long nColCount = rRange.aEnd.Col() + 1 - rRange.aStart.Col();\n long nRowCount = rRange.aEnd.Row() + 1 - rRange.aStart.Row();\n\n uno::Sequence< uno::Sequence > aRowSeq( nRowCount );\n uno::Sequence* pRowAry = aRowSeq.getArray();\n for (long nRow = 0; nRow < nRowCount; nRow++)\n {\n uno::Sequence aColSeq( nColCount );\n double* pColAry = aColSeq.getArray();\n for (long nCol = 0; nCol < nColCount; nCol++)\n pColAry[nCol] = pDoc->GetValue(\n ScAddress( (USHORT)(nStartCol+nCol), (USHORT)(nStartRow+nRow), nTab ) );\n\n pRowAry[nRow] = aColSeq;\n }\n\n rAny <<= aRowSeq;\n return TRUE; \/\/! check for errors\n}\n\n\nBOOL ScRangeToSequence::FillDoubleArray( uno::Any& rAny, const ScMatrix* pMatrix )\n{\n if (!pMatrix)\n return FALSE;\n\n USHORT nColCount, nRowCount;\n pMatrix->GetDimensions( nColCount, nRowCount );\n\n uno::Sequence< uno::Sequence > aRowSeq( nRowCount );\n uno::Sequence* pRowAry = aRowSeq.getArray();\n for (USHORT nRow = 0; nRow < nRowCount; nRow++)\n {\n uno::Sequence aColSeq( nColCount );\n double* pColAry = aColSeq.getArray();\n for (USHORT nCol = 0; nCol < nColCount; nCol++)\n if ( pMatrix->IsString( nCol, nRow ) )\n pColAry[nCol] = 0.0;\n else\n pColAry[nCol] = pMatrix->GetDouble( nCol, nRow );\n\n pRowAry[nRow] = aColSeq;\n }\n\n rAny <<= aRowSeq;\n return TRUE;\n}\n\n\/\/------------------------------------------------------------------------\n\nBOOL ScRangeToSequence::FillStringArray( uno::Any& rAny, ScDocument* pDoc, const ScRange& rRange )\n{\n USHORT nTab = rRange.aStart.Tab();\n USHORT nStartCol = rRange.aStart.Col();\n USHORT nStartRow = rRange.aStart.Row();\n long nColCount = rRange.aEnd.Col() + 1 - rRange.aStart.Col();\n long nRowCount = rRange.aEnd.Row() + 1 - rRange.aStart.Row();\n\n String aDocStr;\n\n uno::Sequence< uno::Sequence > aRowSeq( nRowCount );\n uno::Sequence* pRowAry = aRowSeq.getArray();\n for (long nRow = 0; nRow < nRowCount; nRow++)\n {\n uno::Sequence aColSeq( nColCount );\n rtl::OUString* pColAry = aColSeq.getArray();\n for (long nCol = 0; nCol < nColCount; nCol++)\n {\n pDoc->GetString( (USHORT)(nStartCol+nCol), (USHORT)(nStartRow+nRow), nTab, aDocStr );\n pColAry[nCol] = rtl::OUString( aDocStr );\n }\n pRowAry[nRow] = aColSeq;\n }\n\n rAny <<= aRowSeq;\n return TRUE; \/\/! check for errors\n}\n\n\nBOOL ScRangeToSequence::FillStringArray( uno::Any& rAny, const ScMatrix* pMatrix,\n SvNumberFormatter* pFormatter )\n{\n if (!pMatrix)\n return FALSE;\n\n USHORT nColCount, nRowCount;\n pMatrix->GetDimensions( nColCount, nRowCount );\n\n uno::Sequence< uno::Sequence > aRowSeq( nRowCount );\n uno::Sequence* pRowAry = aRowSeq.getArray();\n for (USHORT nRow = 0; nRow < nRowCount; nRow++)\n {\n uno::Sequence aColSeq( nColCount );\n rtl::OUString* pColAry = aColSeq.getArray();\n for (USHORT nCol = 0; nCol < nColCount; nCol++)\n {\n String aStr;\n if ( pMatrix->IsString( nCol, nRow ) )\n {\n if ( !pMatrix->IsEmpty( nCol, nRow ) )\n aStr = pMatrix->GetString( nCol, nRow );\n }\n else if ( pFormatter )\n {\n double fVal = pMatrix->GetDouble( nCol, nRow );\n Color* pColor;\n pFormatter->GetOutputString( fVal, 0, aStr, &pColor );\n }\n pColAry[nCol] = rtl::OUString( aStr );\n }\n\n pRowAry[nRow] = aColSeq;\n }\n\n rAny <<= aRowSeq;\n return TRUE;\n}\n\n\/\/------------------------------------------------------------------------\n\nBOOL ScRangeToSequence::FillMixedArray( uno::Any& rAny, ScDocument* pDoc, const ScRange& rRange )\n{\n USHORT nTab = rRange.aStart.Tab();\n USHORT nStartCol = rRange.aStart.Col();\n USHORT nStartRow = rRange.aStart.Row();\n long nColCount = rRange.aEnd.Col() + 1 - rRange.aStart.Col();\n long nRowCount = rRange.aEnd.Row() + 1 - rRange.aStart.Row();\n\n String aDocStr;\n\n uno::Sequence< uno::Sequence > aRowSeq( nRowCount );\n uno::Sequence* pRowAry = aRowSeq.getArray();\n for (long nRow = 0; nRow < nRowCount; nRow++)\n {\n uno::Sequence aColSeq( nColCount );\n uno::Any* pColAry = aColSeq.getArray();\n for (long nCol = 0; nCol < nColCount; nCol++)\n {\n if ( pDoc->HasValueData( (USHORT)(nStartCol+nCol), (USHORT)(nStartRow+nRow), nTab ) )\n pColAry[nCol] <<= (double) pDoc->GetValue(\n ScAddress( (USHORT)(nStartCol+nCol), (USHORT)(nStartRow+nRow), nTab ) );\n else\n {\n pDoc->GetString( (USHORT)(nStartCol+nCol), (USHORT)(nStartRow+nRow), nTab, aDocStr );\n pColAry[nCol] <<= rtl::OUString( aDocStr );\n }\n }\n pRowAry[nRow] = aColSeq;\n }\n\n rAny <<= aRowSeq;\n return TRUE; \/\/! check for errors\n}\n\n\nBOOL ScRangeToSequence::FillMixedArray( uno::Any& rAny, const ScMatrix* pMatrix )\n{\n if (!pMatrix)\n return FALSE;\n\n USHORT nColCount, nRowCount;\n pMatrix->GetDimensions( nColCount, nRowCount );\n\n uno::Sequence< uno::Sequence > aRowSeq( nRowCount );\n uno::Sequence* pRowAry = aRowSeq.getArray();\n for (USHORT nRow = 0; nRow < nRowCount; nRow++)\n {\n uno::Sequence aColSeq( nColCount );\n uno::Any* pColAry = aColSeq.getArray();\n for (USHORT nCol = 0; nCol < nColCount; nCol++)\n {\n if ( pMatrix->IsString( nCol, nRow ) )\n {\n String aStr;\n if ( !pMatrix->IsEmpty( nCol, nRow ) )\n aStr = pMatrix->GetString( nCol, nRow );\n pColAry[nCol] <<= rtl::OUString( aStr );\n }\n else\n pColAry[nCol] <<= (double) pMatrix->GetDouble( nCol, nRow );\n }\n\n pRowAry[nRow] = aColSeq;\n }\n\n rAny <<= aRowSeq;\n return TRUE;\n}\n\n\n\/\/------------------------------------------------------------------------\n\n\n\n#79625# FillMixedArray: handling of formula errors\/*************************************************************************\n *\n * $RCSfile: rangeseq.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: nn $ $Date: 2000-10-18 18:23:33 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifdef PCH\n#include \"core_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \"rangeseq.hxx\"\n#include \"document.hxx\"\n#include \"scmatrix.hxx\"\n#include \"cell.hxx\"\n\nusing namespace com::sun::star;\n\n\/\/------------------------------------------------------------------------\n\nlong lcl_DoubleToLong( double fVal )\n{\n double fInt = (fVal >= 0.0) ? SolarMath::ApproxFloor( fVal ) :\n SolarMath::ApproxCeil( fVal );\n if ( fInt >= LONG_MIN && fInt <= LONG_MAX )\n return (long)fInt;\n else\n return 0.0; \/\/ out of range\n}\n\nBOOL ScRangeToSequence::FillLongArray( uno::Any& rAny, ScDocument* pDoc, const ScRange& rRange )\n{\n USHORT nTab = rRange.aStart.Tab();\n USHORT nStartCol = rRange.aStart.Col();\n USHORT nStartRow = rRange.aStart.Row();\n long nColCount = rRange.aEnd.Col() + 1 - rRange.aStart.Col();\n long nRowCount = rRange.aEnd.Row() + 1 - rRange.aStart.Row();\n\n uno::Sequence< uno::Sequence > aRowSeq( nRowCount );\n uno::Sequence* pRowAry = aRowSeq.getArray();\n for (long nRow = 0; nRow < nRowCount; nRow++)\n {\n uno::Sequence aColSeq( nColCount );\n INT32* pColAry = aColSeq.getArray();\n for (long nCol = 0; nCol < nColCount; nCol++)\n pColAry[nCol] = lcl_DoubleToLong( pDoc->GetValue(\n ScAddress( (USHORT)(nStartCol+nCol), (USHORT)(nStartRow+nRow), nTab ) ) );\n\n pRowAry[nRow] = aColSeq;\n }\n\n rAny <<= aRowSeq;\n return TRUE; \/\/! check for errors\n}\n\n\nBOOL ScRangeToSequence::FillLongArray( uno::Any& rAny, const ScMatrix* pMatrix )\n{\n if (!pMatrix)\n return FALSE;\n\n USHORT nColCount, nRowCount;\n pMatrix->GetDimensions( nColCount, nRowCount );\n\n uno::Sequence< uno::Sequence > aRowSeq( nRowCount );\n uno::Sequence* pRowAry = aRowSeq.getArray();\n for (USHORT nRow = 0; nRow < nRowCount; nRow++)\n {\n uno::Sequence aColSeq( nColCount );\n INT32* pColAry = aColSeq.getArray();\n for (USHORT nCol = 0; nCol < nColCount; nCol++)\n if ( pMatrix->IsString( nCol, nRow ) )\n pColAry[nCol] = 0;\n else\n pColAry[nCol] = lcl_DoubleToLong( pMatrix->GetDouble( nCol, nRow ) );\n\n pRowAry[nRow] = aColSeq;\n }\n\n rAny <<= aRowSeq;\n return TRUE;\n}\n\n\/\/------------------------------------------------------------------------\n\nBOOL ScRangeToSequence::FillDoubleArray( uno::Any& rAny, ScDocument* pDoc, const ScRange& rRange )\n{\n USHORT nTab = rRange.aStart.Tab();\n USHORT nStartCol = rRange.aStart.Col();\n USHORT nStartRow = rRange.aStart.Row();\n long nColCount = rRange.aEnd.Col() + 1 - rRange.aStart.Col();\n long nRowCount = rRange.aEnd.Row() + 1 - rRange.aStart.Row();\n\n uno::Sequence< uno::Sequence > aRowSeq( nRowCount );\n uno::Sequence* pRowAry = aRowSeq.getArray();\n for (long nRow = 0; nRow < nRowCount; nRow++)\n {\n uno::Sequence aColSeq( nColCount );\n double* pColAry = aColSeq.getArray();\n for (long nCol = 0; nCol < nColCount; nCol++)\n pColAry[nCol] = pDoc->GetValue(\n ScAddress( (USHORT)(nStartCol+nCol), (USHORT)(nStartRow+nRow), nTab ) );\n\n pRowAry[nRow] = aColSeq;\n }\n\n rAny <<= aRowSeq;\n return TRUE; \/\/! check for errors\n}\n\n\nBOOL ScRangeToSequence::FillDoubleArray( uno::Any& rAny, const ScMatrix* pMatrix )\n{\n if (!pMatrix)\n return FALSE;\n\n USHORT nColCount, nRowCount;\n pMatrix->GetDimensions( nColCount, nRowCount );\n\n uno::Sequence< uno::Sequence > aRowSeq( nRowCount );\n uno::Sequence* pRowAry = aRowSeq.getArray();\n for (USHORT nRow = 0; nRow < nRowCount; nRow++)\n {\n uno::Sequence aColSeq( nColCount );\n double* pColAry = aColSeq.getArray();\n for (USHORT nCol = 0; nCol < nColCount; nCol++)\n if ( pMatrix->IsString( nCol, nRow ) )\n pColAry[nCol] = 0.0;\n else\n pColAry[nCol] = pMatrix->GetDouble( nCol, nRow );\n\n pRowAry[nRow] = aColSeq;\n }\n\n rAny <<= aRowSeq;\n return TRUE;\n}\n\n\/\/------------------------------------------------------------------------\n\nBOOL ScRangeToSequence::FillStringArray( uno::Any& rAny, ScDocument* pDoc, const ScRange& rRange )\n{\n USHORT nTab = rRange.aStart.Tab();\n USHORT nStartCol = rRange.aStart.Col();\n USHORT nStartRow = rRange.aStart.Row();\n long nColCount = rRange.aEnd.Col() + 1 - rRange.aStart.Col();\n long nRowCount = rRange.aEnd.Row() + 1 - rRange.aStart.Row();\n\n String aDocStr;\n\n uno::Sequence< uno::Sequence > aRowSeq( nRowCount );\n uno::Sequence* pRowAry = aRowSeq.getArray();\n for (long nRow = 0; nRow < nRowCount; nRow++)\n {\n uno::Sequence aColSeq( nColCount );\n rtl::OUString* pColAry = aColSeq.getArray();\n for (long nCol = 0; nCol < nColCount; nCol++)\n {\n pDoc->GetString( (USHORT)(nStartCol+nCol), (USHORT)(nStartRow+nRow), nTab, aDocStr );\n pColAry[nCol] = rtl::OUString( aDocStr );\n }\n pRowAry[nRow] = aColSeq;\n }\n\n rAny <<= aRowSeq;\n return TRUE; \/\/! check for errors\n}\n\n\nBOOL ScRangeToSequence::FillStringArray( uno::Any& rAny, const ScMatrix* pMatrix,\n SvNumberFormatter* pFormatter )\n{\n if (!pMatrix)\n return FALSE;\n\n USHORT nColCount, nRowCount;\n pMatrix->GetDimensions( nColCount, nRowCount );\n\n uno::Sequence< uno::Sequence > aRowSeq( nRowCount );\n uno::Sequence* pRowAry = aRowSeq.getArray();\n for (USHORT nRow = 0; nRow < nRowCount; nRow++)\n {\n uno::Sequence aColSeq( nColCount );\n rtl::OUString* pColAry = aColSeq.getArray();\n for (USHORT nCol = 0; nCol < nColCount; nCol++)\n {\n String aStr;\n if ( pMatrix->IsString( nCol, nRow ) )\n {\n if ( !pMatrix->IsEmpty( nCol, nRow ) )\n aStr = pMatrix->GetString( nCol, nRow );\n }\n else if ( pFormatter )\n {\n double fVal = pMatrix->GetDouble( nCol, nRow );\n Color* pColor;\n pFormatter->GetOutputString( fVal, 0, aStr, &pColor );\n }\n pColAry[nCol] = rtl::OUString( aStr );\n }\n\n pRowAry[nRow] = aColSeq;\n }\n\n rAny <<= aRowSeq;\n return TRUE;\n}\n\n\/\/------------------------------------------------------------------------\n\ndouble lcl_GetValueFromCell( ScBaseCell& rCell )\n{\n \/\/! ScBaseCell member function?\n\n CellType eType = rCell.GetCellType();\n if ( eType == CELLTYPE_VALUE )\n return ((ScValueCell&)rCell).GetValue();\n else if ( eType == CELLTYPE_FORMULA )\n return ((ScFormulaCell&)rCell).GetValue(); \/\/ called only if result is value\n\n DBG_ERROR( \"GetValueFromCell: wrong type\" );\n return 0;\n}\n\nBOOL ScRangeToSequence::FillMixedArray( uno::Any& rAny, ScDocument* pDoc, const ScRange& rRange,\n BOOL bAllowNV )\n{\n USHORT nTab = rRange.aStart.Tab();\n USHORT nStartCol = rRange.aStart.Col();\n USHORT nStartRow = rRange.aStart.Row();\n long nColCount = rRange.aEnd.Col() + 1 - rRange.aStart.Col();\n long nRowCount = rRange.aEnd.Row() + 1 - rRange.aStart.Row();\n\n String aDocStr;\n BOOL bHasErrors = FALSE;\n\n uno::Sequence< uno::Sequence > aRowSeq( nRowCount );\n uno::Sequence* pRowAry = aRowSeq.getArray();\n for (long nRow = 0; nRow < nRowCount; nRow++)\n {\n uno::Sequence aColSeq( nColCount );\n uno::Any* pColAry = aColSeq.getArray();\n for (long nCol = 0; nCol < nColCount; nCol++)\n {\n uno::Any& rElement = pColAry[nCol];\n\n ScAddress aPos( (USHORT)(nStartCol+nCol), (USHORT)(nStartRow+nRow), nTab );\n ScBaseCell* pCell = pDoc->GetCell( aPos );\n if ( pCell )\n {\n if ( pCell->GetCellType() == CELLTYPE_FORMULA &&\n ((ScFormulaCell*)pCell)->GetErrCode() != 0 )\n {\n \/\/ if NV is allowed, leave empty for errors\n bHasErrors = TRUE;\n }\n else if ( pCell->HasValueData() )\n rElement <<= (double) lcl_GetValueFromCell( *pCell );\n else\n rElement <<= rtl::OUString( pCell->GetStringData() );\n }\n else\n rElement <<= rtl::OUString(); \/\/ empty: empty string\n }\n pRowAry[nRow] = aColSeq;\n }\n\n rAny <<= aRowSeq;\n return bAllowNV || !bHasErrors;\n}\n\n\nBOOL ScRangeToSequence::FillMixedArray( uno::Any& rAny, const ScMatrix* pMatrix )\n{\n if (!pMatrix)\n return FALSE;\n\n USHORT nColCount, nRowCount;\n pMatrix->GetDimensions( nColCount, nRowCount );\n\n uno::Sequence< uno::Sequence > aRowSeq( nRowCount );\n uno::Sequence* pRowAry = aRowSeq.getArray();\n for (USHORT nRow = 0; nRow < nRowCount; nRow++)\n {\n uno::Sequence aColSeq( nColCount );\n uno::Any* pColAry = aColSeq.getArray();\n for (USHORT nCol = 0; nCol < nColCount; nCol++)\n {\n if ( pMatrix->IsString( nCol, nRow ) )\n {\n String aStr;\n if ( !pMatrix->IsEmpty( nCol, nRow ) )\n aStr = pMatrix->GetString( nCol, nRow );\n pColAry[nCol] <<= rtl::OUString( aStr );\n }\n else\n pColAry[nCol] <<= (double) pMatrix->GetDouble( nCol, nRow );\n }\n\n pRowAry[nRow] = aColSeq;\n }\n\n rAny <<= aRowSeq;\n return TRUE;\n}\n\n\n\/\/------------------------------------------------------------------------\n\n\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: userlist.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: ihi $ $Date: 2006-08-04 11:34:14 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sc.hxx\"\n\n\n\n\/\/------------------------------------------------------------------------\n\n#include \n#include \n\n#include \"global.hxx\"\n#include \"userlist.hxx\"\n\n#ifndef _UNOTOOLS_LOCALEDATAWRAPPER_HXX\n#include \n#endif\n#ifndef _UNOTOOLS_CALENDARWRAPPER_HXX\n#include \n#endif\n#ifndef _UNOTOOLS_TRANSLITERATIONWRAPPER_HXX\n#include \n#endif\n\n\/\/ STATIC DATA -----------------------------------------------------------\n\n\n\/\/------------------------------------------------------------------------\n\nvoid ScUserListData::InitTokens()\n{\n sal_Unicode cSep = ScGlobal::cListDelimiter;\n nTokenCount = (USHORT) aStr.GetTokenCount(cSep);\n if (nTokenCount)\n {\n pSubStrings = new String[nTokenCount];\n pUpperSub = new String[nTokenCount];\n for (USHORT i=0; itoUpper(pUpperSub[i]);\n }\n }\n else\n pSubStrings = pUpperSub = NULL;\n}\n\nScUserListData::ScUserListData(const String& rStr) :\n aStr(rStr)\n{\n InitTokens();\n}\n\nScUserListData::ScUserListData(const ScUserListData& rData) :\n aStr(rData.aStr)\n{\n InitTokens();\n}\n\n__EXPORT ScUserListData::~ScUserListData()\n{\n delete[] pSubStrings;\n delete[] pUpperSub;\n}\n\nScUserListData::ScUserListData( SvStream& rStream )\n{\n rStream.ReadByteString( aStr, rStream.GetStreamCharSet() );\n InitTokens();\n}\n\nBOOL ScUserListData::Store( SvStream& rStream ) const\n{\n rStream.WriteByteString( aStr, rStream.GetStreamCharSet() );\n return TRUE;\n}\n\nvoid ScUserListData::SetString( const String& rStr )\n{\n delete[] pSubStrings;\n delete[] pUpperSub;\n\n aStr = rStr;\n InitTokens();\n}\n\nUSHORT ScUserListData::GetSubCount() const\n{\n return nTokenCount;\n}\n\nBOOL ScUserListData::GetSubIndex(const String& rSubStr, USHORT& rIndex) const\n{\n USHORT i;\n for (i=0; itoUpper(aUpStr);\n for (i=0; i nIndex2)\n return COMPARE_GREATER;\n else\n return COMPARE_EQUAL;\n }\n else\n return COMPARE_LESS;\n }\n else if (bFound2)\n return COMPARE_GREATER;\n else\n return (StringCompare) ScGlobal::pCaseTransliteration->compareString( rSubStr1, rSubStr2 );\n}\n\nStringCompare ScUserListData::ICompare(const String& rSubStr1, const String& rSubStr2) const\n{\n USHORT nIndex1;\n USHORT nIndex2;\n BOOL bFound1 = GetSubIndex(rSubStr1, nIndex1);\n BOOL bFound2 = GetSubIndex(rSubStr2, nIndex2);\n if (bFound1)\n {\n if (bFound2)\n {\n if (nIndex1 < nIndex2)\n return COMPARE_LESS;\n else if (nIndex1 > nIndex2)\n return COMPARE_GREATER;\n else\n return COMPARE_EQUAL;\n }\n else\n return COMPARE_LESS;\n }\n else if (bFound2)\n return COMPARE_GREATER;\n else\n return (StringCompare) ScGlobal::pTransliteration->compareString( rSubStr1, rSubStr2 );\n}\n\nScUserList::ScUserList(USHORT nLim, USHORT nDel) :\n Collection ( nLim, nDel )\n{\n using namespace ::com::sun::star;\n\n sal_Unicode cDelimiter = ScGlobal::cListDelimiter;\n uno::Sequence< i18n::CalendarItem > xCal;\n\n uno::Sequence< i18n::Calendar > xCalendars(\n ScGlobal::pLocaleData->getAllCalendars() );\n\n for ( sal_Int32 j = 0; j < xCalendars.getLength(); ++j )\n {\n xCal = xCalendars[j].Days;\n if ( xCal.getLength() )\n {\n String sDayShort, sDayLong;\n sal_Int32 i;\n sal_Int32 nLen = xCal.getLength();\n rtl::OUString sStart = xCalendars[j].StartOfWeek;\n sal_Int16 nStart = nLen;\n while (nStart > 0)\n {\n if (xCal[--nStart].ID == sStart)\n break;\n }\n sal_Int16 nLast = (nStart + nLen - 1) % nLen;\n for (i = nStart; i != nLast; i = (i+1) % nLen)\n {\n sDayShort += String( xCal[i].AbbrevName );\n sDayShort += cDelimiter;\n sDayLong += String( xCal[i].FullName );\n sDayLong += cDelimiter;\n }\n sDayShort += String( xCal[i].AbbrevName );\n sDayLong += String( xCal[i].FullName );\n\n if ( !HasEntry( sDayShort ) )\n Insert( new ScUserListData( sDayShort ));\n if ( !HasEntry( sDayLong ) )\n Insert( new ScUserListData( sDayLong ));\n }\n\n xCal = xCalendars[j].Months;\n if ( xCal.getLength() )\n {\n String sMonthShort, sMonthLong;\n sal_Int32 i;\n sal_Int32 nLen = xCal.getLength() - 1;\n for (i = 0; i < nLen; i++)\n {\n sMonthShort += String( xCal[i].AbbrevName );\n sMonthShort += cDelimiter;\n sMonthLong += String( xCal[i].FullName );\n sMonthLong += cDelimiter;\n }\n sMonthShort += String( xCal[i].AbbrevName );\n sMonthLong += String( xCal[i].FullName );\n\n if ( !HasEntry( sMonthShort ) )\n Insert( new ScUserListData( sMonthShort ));\n if ( !HasEntry( sMonthLong ) )\n Insert( new ScUserListData( sMonthLong ));\n }\n }\n}\n\nBOOL ScUserList::Load( SvStream& rStream )\n{\n BOOL bSuccess = TRUE;\n USHORT nNewCount;\n\n while( nCount > 0 )\n AtFree(0); \/\/ alles loeschen\n\n rStream >> nNewCount;\n\n for ( USHORT i=0; iStore( rStream );\n\n return bSuccess;\n}\n\nDataObject* ScUserList::Clone() const\n{\n return ( new ScUserList( *this ) );\n}\n\nScUserListData* ScUserList::GetData(const String& rSubStr) const\n{\n USHORT nIndex;\n USHORT i = 0;\n for (i=0; i < nCount; i++)\n if (((ScUserListData*)pItems[i])->GetSubIndex(rSubStr, nIndex))\n return (ScUserListData*)pItems[i];\n return NULL;\n}\n\nBOOL ScUserList::operator==( const ScUserList& r ) const\n{\n BOOL bEqual = (nCount == r.nCount);\n\n if ( bEqual )\n {\n ScUserListData* pMyData = NULL;\n ScUserListData* pOtherData = NULL;\n\n for ( USHORT i=0; inTokenCount == pOtherData->nTokenCount)\n && (pMyData->aStr == pOtherData->aStr) );\n }\n }\n\n return bEqual;\n}\n\n\nBOOL ScUserList::HasEntry( const String& rStr ) const\n{\n for ( USHORT i=0; iaStr == rStr )\n return TRUE;\n }\n return FALSE;\n}\n\nINTEGRATION: CWS calcwarnings (1.9.88); FILE MERGED 2006\/12\/06 13:34:23 nn 1.9.88.2: #i69284# warning-free: core, unxlngi6 2006\/11\/28 13:24:50 nn 1.9.88.1: #i69284# warning-free: core, wntmsci10\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: userlist.cxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: vg $ $Date: 2007-02-27 12:20:03 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sc.hxx\"\n\n\n\n\/\/------------------------------------------------------------------------\n\n#include \n#include \n\n#include \"global.hxx\"\n#include \"userlist.hxx\"\n\n#ifndef _UNOTOOLS_LOCALEDATAWRAPPER_HXX\n#include \n#endif\n#ifndef _UNOTOOLS_CALENDARWRAPPER_HXX\n#include \n#endif\n#ifndef _UNOTOOLS_TRANSLITERATIONWRAPPER_HXX\n#include \n#endif\n\n\/\/ STATIC DATA -----------------------------------------------------------\n\n\n\/\/------------------------------------------------------------------------\n\nvoid ScUserListData::InitTokens()\n{\n sal_Unicode cSep = ScGlobal::cListDelimiter;\n nTokenCount = (USHORT) aStr.GetTokenCount(cSep);\n if (nTokenCount)\n {\n pSubStrings = new String[nTokenCount];\n pUpperSub = new String[nTokenCount];\n for (USHORT i=0; itoUpper(pUpperSub[i]);\n }\n }\n else\n pSubStrings = pUpperSub = NULL;\n}\n\nScUserListData::ScUserListData(const String& rStr) :\n aStr(rStr)\n{\n InitTokens();\n}\n\nScUserListData::ScUserListData(const ScUserListData& rData) :\n DataObject(),\n aStr(rData.aStr)\n{\n InitTokens();\n}\n\n__EXPORT ScUserListData::~ScUserListData()\n{\n delete[] pSubStrings;\n delete[] pUpperSub;\n}\n\nScUserListData::ScUserListData( SvStream& rStream )\n{\n rStream.ReadByteString( aStr, rStream.GetStreamCharSet() );\n InitTokens();\n}\n\nBOOL ScUserListData::Store( SvStream& rStream ) const\n{\n rStream.WriteByteString( aStr, rStream.GetStreamCharSet() );\n return TRUE;\n}\n\nvoid ScUserListData::SetString( const String& rStr )\n{\n delete[] pSubStrings;\n delete[] pUpperSub;\n\n aStr = rStr;\n InitTokens();\n}\n\nUSHORT ScUserListData::GetSubCount() const\n{\n return nTokenCount;\n}\n\nBOOL ScUserListData::GetSubIndex(const String& rSubStr, USHORT& rIndex) const\n{\n USHORT i;\n for (i=0; itoUpper(aUpStr);\n for (i=0; i nIndex2)\n return COMPARE_GREATER;\n else\n return COMPARE_EQUAL;\n }\n else\n return COMPARE_LESS;\n }\n else if (bFound2)\n return COMPARE_GREATER;\n else\n return (StringCompare) ScGlobal::pCaseTransliteration->compareString( rSubStr1, rSubStr2 );\n}\n\nStringCompare ScUserListData::ICompare(const String& rSubStr1, const String& rSubStr2) const\n{\n USHORT nIndex1;\n USHORT nIndex2;\n BOOL bFound1 = GetSubIndex(rSubStr1, nIndex1);\n BOOL bFound2 = GetSubIndex(rSubStr2, nIndex2);\n if (bFound1)\n {\n if (bFound2)\n {\n if (nIndex1 < nIndex2)\n return COMPARE_LESS;\n else if (nIndex1 > nIndex2)\n return COMPARE_GREATER;\n else\n return COMPARE_EQUAL;\n }\n else\n return COMPARE_LESS;\n }\n else if (bFound2)\n return COMPARE_GREATER;\n else\n return (StringCompare) ScGlobal::pTransliteration->compareString( rSubStr1, rSubStr2 );\n}\n\nScUserList::ScUserList(USHORT nLim, USHORT nDel) :\n Collection ( nLim, nDel )\n{\n using namespace ::com::sun::star;\n\n sal_Unicode cDelimiter = ScGlobal::cListDelimiter;\n uno::Sequence< i18n::CalendarItem > xCal;\n\n uno::Sequence< i18n::Calendar > xCalendars(\n ScGlobal::pLocaleData->getAllCalendars() );\n\n for ( sal_Int32 j = 0; j < xCalendars.getLength(); ++j )\n {\n xCal = xCalendars[j].Days;\n if ( xCal.getLength() )\n {\n String sDayShort, sDayLong;\n sal_Int32 i;\n sal_Int32 nLen = xCal.getLength();\n rtl::OUString sStart = xCalendars[j].StartOfWeek;\n sal_Int16 nStart = sal::static_int_cast(nLen);\n while (nStart > 0)\n {\n if (xCal[--nStart].ID == sStart)\n break;\n }\n sal_Int16 nLast = sal::static_int_cast( (nStart + nLen - 1) % nLen );\n for (i = nStart; i != nLast; i = (i+1) % nLen)\n {\n sDayShort += String( xCal[i].AbbrevName );\n sDayShort += cDelimiter;\n sDayLong += String( xCal[i].FullName );\n sDayLong += cDelimiter;\n }\n sDayShort += String( xCal[i].AbbrevName );\n sDayLong += String( xCal[i].FullName );\n\n if ( !HasEntry( sDayShort ) )\n Insert( new ScUserListData( sDayShort ));\n if ( !HasEntry( sDayLong ) )\n Insert( new ScUserListData( sDayLong ));\n }\n\n xCal = xCalendars[j].Months;\n if ( xCal.getLength() )\n {\n String sMonthShort, sMonthLong;\n sal_Int32 i;\n sal_Int32 nLen = xCal.getLength() - 1;\n for (i = 0; i < nLen; i++)\n {\n sMonthShort += String( xCal[i].AbbrevName );\n sMonthShort += cDelimiter;\n sMonthLong += String( xCal[i].FullName );\n sMonthLong += cDelimiter;\n }\n sMonthShort += String( xCal[i].AbbrevName );\n sMonthLong += String( xCal[i].FullName );\n\n if ( !HasEntry( sMonthShort ) )\n Insert( new ScUserListData( sMonthShort ));\n if ( !HasEntry( sMonthLong ) )\n Insert( new ScUserListData( sMonthLong ));\n }\n }\n}\n\nBOOL ScUserList::Load( SvStream& rStream )\n{\n BOOL bSuccess = TRUE;\n USHORT nNewCount;\n\n while( nCount > 0 )\n AtFree(0); \/\/ alles loeschen\n\n rStream >> nNewCount;\n\n for ( USHORT i=0; iStore( rStream );\n\n return bSuccess;\n}\n\nDataObject* ScUserList::Clone() const\n{\n return ( new ScUserList( *this ) );\n}\n\nScUserListData* ScUserList::GetData(const String& rSubStr) const\n{\n USHORT nIndex;\n USHORT i = 0;\n for (i=0; i < nCount; i++)\n if (((ScUserListData*)pItems[i])->GetSubIndex(rSubStr, nIndex))\n return (ScUserListData*)pItems[i];\n return NULL;\n}\n\nBOOL ScUserList::operator==( const ScUserList& r ) const\n{\n BOOL bEqual = (nCount == r.nCount);\n\n if ( bEqual )\n {\n ScUserListData* pMyData = NULL;\n ScUserListData* pOtherData = NULL;\n\n for ( USHORT i=0; inTokenCount == pOtherData->nTokenCount)\n && (pMyData->aStr == pOtherData->aStr) );\n }\n }\n\n return bEqual;\n}\n\n\nBOOL ScUserList::HasEntry( const String& rStr ) const\n{\n for ( USHORT i=0; iaStr == rStr )\n return TRUE;\n }\n return FALSE;\n}\n\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n#include \"couchbase.h\"\n#include \n#include \n#include \n\nusing namespace Couchnode;\nusing namespace std;\n\nstatic bool get_string(const v8::Handle &jv,\n char **strp,\n size_t *szp)\n{\n if (!jv->IsString()) {\n#ifdef COUCHNODE_DEBUG\n printf(\"Not a string..\\n\");\n#endif\n return false;\n }\n\n v8::Local s = jv->ToString();\n *szp = s->Length();\n if (!*szp) {\n return false;\n }\n\n *strp = new char[*szp];\n s->WriteAscii(*strp, 0, *szp, v8::String::NO_NULL_TERMINATION);\n return true;\n}\n\n#define GET_DPARAM(lval, bidx) \\\n if (!dict.IsEmpty()) { \\\n lval = dict->Get(NameMap::names[NameMap::##bidx]); \\\n }\n\nCommonArgs::CommonArgs(const v8::Arguments &argv, int pmax, int reqmax)\n : args(argv), key(NULL), params_max(pmax), required_max(reqmax), stale(false)\n{\n}\n\nbool CommonArgs::parse()\n{\n if (use_dictparams) {\n if (args.Length() < required_max + 2) {\n throw Couchnode::Exception(\"Bad arguments\");\n }\n if (args.Length() == required_max + 3) {\n if (!args[required_max + 2]->IsObject()) {\n throw Couchnode::Exception(\n \"Have last argument, but it's not an Object\",\n args[required_max + 2]);\n }\n dict = args[required_max + 2]->ToObject();\n }\n } else if (args.Length() < (params_max + 2)) {\n throw Couchnode::Exception(\"Bad arguments\");\n }\n\n if (!extractKey()) {\n return false;\n }\n\n if (!extractUdata()) {\n return false;\n }\n return true;\n}\n\nbool CommonArgs::extractKey()\n{\n if (!get_string(args[0], &key, &nkey)) {\n#ifdef COUCHNODE_DEBUG\n printf(\"Arg at pos %d\\n\", 0);\n#endif\n throw Couchnode::Exception(\"Couldn't extract string\");\n }\n return true;\n}\n\nbool CommonArgs::extractUdata()\n{\n \/\/ { \"key\", .. params_max ..., function() { .. }, \"Data\" }\n \/\/ Index should be 1 + params_max\n\n int ix;\n if (use_dictparams) {\n ix = required_max + 1;\n } else {\n ix = params_max + 1;\n }\n\n ucb = v8::Local::Cast(args[ix]);\n if (!ucb->IsFunction()) {\n#ifdef COUCHNODE_DEBUG\n printf(\"Not a function at index %d\\n\", ix);\n#endif\n throw Couchnode::Exception(\"Not a function\", args[ix]);\n }\n\n getParam(ix + 1, NameMap::DATA, &udata);\n return true;\n}\n\nvoid CommonArgs::extractCas(const v8::Handle &arg,\n libcouchbase_cas_t *cas)\n{\n if (arg.IsEmpty() || arg->IsUndefined()) {\n *cas = 0;\n } else if (arg->IsObject()) {\n *cas = Cas::GetCas(arg->ToObject());\n } else {\n throw Couchnode::Exception(\"Couldn't parse CAS\", arg);\n }\n}\n\nvoid CommonArgs::extractExpiry(const v8::Handle &arg, time_t *exp)\n{\n if (arg.IsEmpty() || arg->IsUndefined()) {\n *exp = 0;\n } else if (arg->IsNumber()) {\n *exp = arg->Uint32Value();\n } else {\n throw Couchnode::Exception(\"Couldn't extract expiration\", arg);\n }\n}\n\nCouchbaseCookie *CommonArgs::makeCookie()\n{\n return new CouchbaseCookie(args.This(), ucb, udata, 1);\n}\n\nvoid CommonArgs::bailout(CouchbaseCookie *cookie, libcouchbase_error_t err)\n{\n cookie->result(err, key, nkey);\n}\n\nCommonArgs::~CommonArgs()\n{\n if (stale) {\n return;\n }\n\n if (key) {\n delete[] key;\n key = NULL;\n }\n}\n\n\/\/ store(key, value, exp, cas, cb, data)\nStorageArgs::StorageArgs(const v8::Arguments &argv, int vparams)\n : CommonArgs(argv, vparams + 3, 1),\n\n data(NULL), ndata(0), exp(0), cas(0)\n{\n}\n\nbool StorageArgs::parse()\n{\n\n if (!CommonArgs::parse()) {\n return false;\n }\n\n if (!extractValue()) {\n return false;\n }\n\n v8::Local arg_exp, arg_cas;\n getParam(params_max, NameMap::CAS, &arg_cas);\n getParam(params_max - 1, NameMap::EXPIRY, &arg_exp);\n\n extractExpiry(arg_exp, &exp);\n extractCas(arg_cas, &cas);\n return true;\n}\n\nbool StorageArgs::extractValue()\n{\n if (!get_string(args[1], &data, &ndata)) {\n throw Couchnode::Exception(\"Bad value\", args[1]);\n }\n\n return true;\n}\n\nStorageArgs::~StorageArgs()\n{\n if (stale) {\n return;\n }\n\n if (data) {\n delete[] data;\n data = NULL;\n }\n}\n\nMGetArgs::MGetArgs(const v8::Arguments &args, int nkparams)\n : CommonArgs(args, nkparams),\n kcount(0), single_exp(0), keys(NULL), sizes(NULL), exps(NULL)\n{\n}\n\nbool MGetArgs::extractKey()\n{\n\n if (args[0]->IsString()) {\n if (!CommonArgs::extractKey()) {\n return false;\n }\n\n kcount = 1;\n v8::Local arg_exp;\n getParam(1, NameMap::EXPIRY, &arg_exp);\n\n extractExpiry(arg_exp, &single_exp);\n assert(key);\n\n keys = &key;\n sizes = &nkey;\n\n if (single_exp) {\n exps = &single_exp;\n }\n\n return true;\n }\n\n exps = NULL;\n\n if (!args[0]->IsArray()) {\n return false;\n }\n\n v8::Local karry = v8::Local::Cast(args[0]);\n kcount = karry->Length();\n\n keys = new char*[kcount];\n sizes = new size_t[kcount];\n\n memset(keys, 0, sizeof(char *) * kcount);\n memset(sizes, 0, sizeof(size_t) * kcount);\n\n for (unsigned ii = 0; ii < karry->Length(); ii++) {\n if (!get_string(karry->Get(ii), keys + ii, sizes + ii)) {\n return false;\n }\n }\n return true;\n}\n\nvoid MGetArgs::bailout(CouchbaseCookie *cookie, libcouchbase_error_t err)\n{\n for (unsigned ii = 0; ii < kcount; ii++) {\n cookie->result(err, keys[ii], sizes[ii]);\n }\n}\n\nMGetArgs::~MGetArgs()\n{\n if (stale) {\n return;\n }\n\n if (exps && exps != &single_exp) {\n delete[] exps;\n }\n\n if (sizes && sizes != &nkey) {\n delete[] sizes;\n }\n\n if (keys && keys != &key) {\n for (unsigned ii = 0; ii < kcount; ii++) {\n delete[] keys[ii];\n }\n delete[] keys;\n }\n\n exps = NULL;\n sizes = NULL;\n keys = NULL;\n}\n\nKeyopArgs::KeyopArgs(const v8::Arguments &args)\n : CommonArgs(args, 1), cas(0)\n{\n}\n\nbool KeyopArgs::parse()\n{\n if (!CommonArgs::parse()) {\n return false;\n }\n\n v8::Local arg_cas;\n getParam(1, NameMap::CAS, &arg_cas);\n\n extractCas(arg_cas, &cas);\n return true;\n}\n\n\/\/ arithmetic(key, delta, initial, exp, cas, ...)\nArithmeticArgs::ArithmeticArgs(const v8::Arguments &args)\n : StorageArgs(args, 1),\n delta(0), initial(0), create(false)\n{\n}\n\nbool ArithmeticArgs::extractValue()\n{\n if (args[1]->IsNumber() == false) {\n throw Couchnode::Exception(\"Delta must be numeric\", args[1]);\n }\n\n delta = args[1]->IntegerValue();\n\n v8::Local arg_initial;\n getParam(2, NameMap::INITIAL, &arg_initial);\n\n if (!arg_initial.IsEmpty()) {\n if (arg_initial->IsNumber()) {\n initial = arg_initial->IntegerValue();\n create = true;\n } else {\n if (!arg_initial->IsUndefined()) {\n throw Couchnode::Exception(\"Initial value must be numeric\",\n arg_initial);\n }\n create = false;\n }\n\n } else {\n create = false;\n }\n\n return true;\n}\nMake cas\/expiry parsing more tolerant of false-ish values\/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n#include \"couchbase.h\"\n#include \n#include \n#include \n\nusing namespace Couchnode;\nusing namespace std;\n\nstatic bool get_string(const v8::Handle &jv,\n char **strp,\n size_t *szp)\n{\n if (!jv->IsString()) {\n#ifdef COUCHNODE_DEBUG\n printf(\"Not a string..\\n\");\n#endif\n return false;\n }\n\n v8::Local s = jv->ToString();\n *szp = s->Length();\n if (!*szp) {\n return false;\n }\n\n *strp = new char[*szp];\n s->WriteAscii(*strp, 0, *szp, v8::String::NO_NULL_TERMINATION);\n return true;\n}\n\n#define GET_DPARAM(lval, bidx) \\\n if (!dict.IsEmpty()) { \\\n lval = dict->Get(NameMap::names[NameMap::##bidx]); \\\n }\n\n\nstatic inline bool isFalseValue(const v8::Handle &v)\n{\n return (v.IsEmpty() || v->BooleanValue() == false);\n}\n\nCommonArgs::CommonArgs(const v8::Arguments &argv, int pmax, int reqmax)\n : args(argv), key(NULL), params_max(pmax), required_max(reqmax), stale(false)\n{\n}\n\nbool CommonArgs::parse()\n{\n if (use_dictparams) {\n if (args.Length() < required_max + 2) {\n throw Couchnode::Exception(\"Bad arguments\");\n }\n if (args.Length() == required_max + 3) {\n if (!args[required_max + 2]->IsObject()) {\n throw Couchnode::Exception(\n \"Have last argument, but it's not an Object\",\n args[required_max + 2]);\n }\n dict = args[required_max + 2]->ToObject();\n }\n } else if (args.Length() < (params_max + 2)) {\n throw Couchnode::Exception(\"Bad arguments\");\n }\n\n if (!extractKey()) {\n return false;\n }\n\n if (!extractUdata()) {\n return false;\n }\n return true;\n}\n\nbool CommonArgs::extractKey()\n{\n if (!get_string(args[0], &key, &nkey)) {\n#ifdef COUCHNODE_DEBUG\n printf(\"Arg at pos %d\\n\", 0);\n#endif\n throw Couchnode::Exception(\"Couldn't extract string\");\n }\n return true;\n}\n\nbool CommonArgs::extractUdata()\n{\n \/\/ { \"key\", .. params_max ..., function() { .. }, \"Data\" }\n \/\/ Index should be 1 + params_max\n\n int ix;\n if (use_dictparams) {\n ix = required_max + 1;\n } else {\n ix = params_max + 1;\n }\n\n ucb = v8::Local::Cast(args[ix]);\n if (!ucb->IsFunction()) {\n#ifdef COUCHNODE_DEBUG\n printf(\"Not a function at index %d\\n\", ix);\n#endif\n throw Couchnode::Exception(\"Not a function\", args[ix]);\n }\n\n getParam(ix + 1, NameMap::DATA, &udata);\n return true;\n}\n\nvoid CommonArgs::extractCas(const v8::Handle &arg,\n libcouchbase_cas_t *cas)\n{\n if (isFalseValue(arg)) {\n *cas = 0;\n } else if (arg->IsObject()) {\n *cas = Cas::GetCas(arg->ToObject());\n } else {\n throw Couchnode::Exception(\"Couldn't parse CAS\", arg);\n }\n}\n\nvoid CommonArgs::extractExpiry(const v8::Handle &arg, time_t *exp)\n{\n if (isFalseValue(arg)) {\n *exp = 0;\n } else if (arg->IsNumber()) {\n *exp = arg->Uint32Value();\n } else {\n throw Couchnode::Exception(\"Couldn't extract expiration\", arg);\n }\n}\n\nCouchbaseCookie *CommonArgs::makeCookie()\n{\n return new CouchbaseCookie(args.This(), ucb, udata, 1);\n}\n\nvoid CommonArgs::bailout(CouchbaseCookie *cookie, libcouchbase_error_t err)\n{\n cookie->result(err, key, nkey);\n}\n\nCommonArgs::~CommonArgs()\n{\n if (stale) {\n return;\n }\n\n if (key) {\n delete[] key;\n key = NULL;\n }\n}\n\n\/\/ store(key, value, exp, cas, cb, data)\nStorageArgs::StorageArgs(const v8::Arguments &argv, int vparams)\n : CommonArgs(argv, vparams + 3, 1),\n\n data(NULL), ndata(0), exp(0), cas(0)\n{\n}\n\nbool StorageArgs::parse()\n{\n\n if (!CommonArgs::parse()) {\n return false;\n }\n\n if (!extractValue()) {\n return false;\n }\n\n v8::Local arg_exp, arg_cas;\n getParam(params_max, NameMap::CAS, &arg_cas);\n getParam(params_max - 1, NameMap::EXPIRY, &arg_exp);\n\n extractExpiry(arg_exp, &exp);\n extractCas(arg_cas, &cas);\n return true;\n}\n\nbool StorageArgs::extractValue()\n{\n if (!get_string(args[1], &data, &ndata)) {\n throw Couchnode::Exception(\"Bad value\", args[1]);\n }\n\n return true;\n}\n\nStorageArgs::~StorageArgs()\n{\n if (stale) {\n return;\n }\n\n if (data) {\n delete[] data;\n data = NULL;\n }\n}\n\nMGetArgs::MGetArgs(const v8::Arguments &args, int nkparams)\n : CommonArgs(args, nkparams),\n kcount(0), single_exp(0), keys(NULL), sizes(NULL), exps(NULL)\n{\n}\n\nbool MGetArgs::extractKey()\n{\n\n if (args[0]->IsString()) {\n if (!CommonArgs::extractKey()) {\n return false;\n }\n\n kcount = 1;\n v8::Local arg_exp;\n getParam(1, NameMap::EXPIRY, &arg_exp);\n\n extractExpiry(arg_exp, &single_exp);\n assert(key);\n\n keys = &key;\n sizes = &nkey;\n\n if (single_exp) {\n exps = &single_exp;\n }\n\n return true;\n }\n\n exps = NULL;\n\n if (!args[0]->IsArray()) {\n return false;\n }\n\n v8::Local karry = v8::Local::Cast(args[0]);\n kcount = karry->Length();\n\n keys = new char*[kcount];\n sizes = new size_t[kcount];\n\n memset(keys, 0, sizeof(char *) * kcount);\n memset(sizes, 0, sizeof(size_t) * kcount);\n\n for (unsigned ii = 0; ii < karry->Length(); ii++) {\n if (!get_string(karry->Get(ii), keys + ii, sizes + ii)) {\n return false;\n }\n }\n return true;\n}\n\nvoid MGetArgs::bailout(CouchbaseCookie *cookie, libcouchbase_error_t err)\n{\n for (unsigned ii = 0; ii < kcount; ii++) {\n cookie->result(err, keys[ii], sizes[ii]);\n }\n}\n\nMGetArgs::~MGetArgs()\n{\n if (stale) {\n return;\n }\n\n if (exps && exps != &single_exp) {\n delete[] exps;\n }\n\n if (sizes && sizes != &nkey) {\n delete[] sizes;\n }\n\n if (keys && keys != &key) {\n for (unsigned ii = 0; ii < kcount; ii++) {\n delete[] keys[ii];\n }\n delete[] keys;\n }\n\n exps = NULL;\n sizes = NULL;\n keys = NULL;\n}\n\nKeyopArgs::KeyopArgs(const v8::Arguments &args)\n : CommonArgs(args, 1), cas(0)\n{\n}\n\nbool KeyopArgs::parse()\n{\n if (!CommonArgs::parse()) {\n return false;\n }\n\n v8::Local arg_cas;\n getParam(1, NameMap::CAS, &arg_cas);\n\n extractCas(arg_cas, &cas);\n return true;\n}\n\n\/\/ arithmetic(key, delta, initial, exp, cas, ...)\nArithmeticArgs::ArithmeticArgs(const v8::Arguments &args)\n : StorageArgs(args, 1),\n delta(0), initial(0), create(false)\n{\n}\n\nbool ArithmeticArgs::extractValue()\n{\n if (args[1]->IsNumber() == false) {\n throw Couchnode::Exception(\"Delta must be numeric\", args[1]);\n }\n\n delta = args[1]->IntegerValue();\n\n v8::Local arg_initial;\n getParam(2, NameMap::INITIAL, &arg_initial);\n\n if (!arg_initial.IsEmpty()) {\n if (arg_initial->IsNumber()) {\n initial = arg_initial->IntegerValue();\n create = true;\n } else {\n if (!arg_initial->IsUndefined()) {\n throw Couchnode::Exception(\"Initial value must be numeric\",\n arg_initial);\n }\n create = false;\n }\n\n } else {\n create = false;\n }\n\n return true;\n}\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sc.hxx\"\n\n#undef SC_DLLIMPLEMENTATION\n\n\n\n\/\/------------------------------------------------------------------\n\n#include \n#include \n#include \n\n#include \"appoptio.hxx\"\n#include \"scmod.hxx\"\n#include \"scitems.hxx\"\n#include \"tpview.hxx\"\n#include \"global.hxx\"\n#include \"viewopti.hxx\"\n#include \"tabvwsh.hxx\"\n#include \"uiitems.hxx\"\n#include \"scresid.hxx\"\n#include \"docsh.hxx\"\n#include \"sc.hrc\" \/\/ -> Slot-IDs\n#include \"optdlg.hrc\"\n#include \"globstr.hrc\"\n\n#include \"opredlin.hxx\"\n#include \"opredlin.hrc\"\n\n\/\/------------------------------------------------------------------\n\nScRedlineOptionsTabPage::ScRedlineOptionsTabPage( Window* pParent,\n const SfxItemSet& rSet )\n : SfxTabPage(pParent, ScResId(RID_SCPAGE_OPREDLINE), rSet),\n aContentFT ( this, ScResId(FT_CONTENT )),\n aContentColorLB ( this, ScResId(CLB_CONTENT )),\n aRemoveFT ( this, ScResId(FT_REMOVE )),\n aRemoveColorLB ( this, ScResId(CLB_REMOVE )),\n aInsertFT ( this, ScResId(FT_INSERT )),\n aInsertColorLB ( this, ScResId(CLB_INSERT )),\n aMoveFT ( this, ScResId(FT_MOVE )),\n aMoveColorLB ( this, ScResId(CLB_MOVE )),\n aChangedGB ( this, ScResId(GB_COLORCHGS)),\n aAuthorStr (ScResId(STR_AUTHOR))\n{\n FreeResource();\n\n Link aLk = LINK(this, ScRedlineOptionsTabPage, ColorHdl);\n aContentColorLB.SetSelectHdl( aLk );\n aMoveColorLB.SetSelectHdl( aLk );\n aInsertColorLB.SetSelectHdl( aLk );\n aRemoveColorLB.SetSelectHdl( aLk );\n}\n\n\/*-----------------------------------------------------------------------\n Beschreibung:\n -----------------------------------------------------------------------*\/\n\n__EXPORT ScRedlineOptionsTabPage::~ScRedlineOptionsTabPage()\n{\n}\n\n\/*-----------------------------------------------------------------------\n Beschreibung:\n -----------------------------------------------------------------------*\/\n\nSfxTabPage* __EXPORT ScRedlineOptionsTabPage::Create( Window* pParent, const SfxItemSet& rSet )\n{\n return new ScRedlineOptionsTabPage( pParent, rSet );\n}\n\n\/*-----------------------------------------------------------------------\n Beschreibung:\n -----------------------------------------------------------------------*\/\n\nBOOL __EXPORT ScRedlineOptionsTabPage::FillItemSet( SfxItemSet& \/* rSet *\/ )\n{\n ScAppOptions aAppOptions=SC_MOD()->GetAppOptions();\n\n ULONG nNew=0;\n USHORT nPos=0;\n\n nPos = aContentColorLB.GetSelectEntryPos();\n if (nPos != LISTBOX_ENTRY_NOTFOUND)\n {\n nPos = aContentColorLB.GetSelectEntryPos();\n if (nPos!=0)\n nNew= aContentColorLB.GetEntryColor(nPos).GetColor();\n else\n nNew= COL_TRANSPARENT;\n\n aAppOptions.SetTrackContentColor(nNew);\n\n }\n nPos = aMoveColorLB.GetSelectEntryPos();\n if (nPos != LISTBOX_ENTRY_NOTFOUND)\n {\n nPos = aMoveColorLB.GetSelectEntryPos();\n if (nPos!=0)\n nNew= aMoveColorLB.GetEntryColor(nPos).GetColor();\n else\n nNew= COL_TRANSPARENT;\n\n aAppOptions.SetTrackMoveColor(nNew);\n\n }\n nPos = aInsertColorLB.GetSelectEntryPos();\n if (nPos != LISTBOX_ENTRY_NOTFOUND)\n {\n nPos = aInsertColorLB.GetSelectEntryPos();\n if (nPos!=0)\n nNew= aInsertColorLB.GetEntryColor(nPos).GetColor();\n else\n nNew= COL_TRANSPARENT;\n\n aAppOptions.SetTrackInsertColor(nNew);\n\n }\n nPos = aRemoveColorLB.GetSelectEntryPos();\n if (nPos != LISTBOX_ENTRY_NOTFOUND)\n {\n nPos = aRemoveColorLB.GetSelectEntryPos();\n if (nPos!=0)\n nNew= aRemoveColorLB.GetEntryColor(nPos).GetColor();\n else\n nNew= COL_TRANSPARENT;\n\n aAppOptions.SetTrackDeleteColor(nNew);\n\n }\n\n SC_MOD()->SetAppOptions(aAppOptions);\n\n \/\/ Repaint (wenn alles ueber Items laufen wuerde, wie es sich gehoert,\n \/\/ waere das nicht noetig...)\n ScDocShell* pDocSh = PTR_CAST(ScDocShell, SfxObjectShell::Current());\n if (pDocSh)\n pDocSh->PostPaintGridAll();\n\n return FALSE;\n}\n\n\/*-----------------------------------------------------------------------\n Beschreibung:\n -----------------------------------------------------------------------*\/\n\nvoid __EXPORT ScRedlineOptionsTabPage::Reset( const SfxItemSet& \/* rSet *\/ )\n{\n\n XColorTable* pColorTbl = XColorTable::GetStdColorTable();\n aContentColorLB.InsertEntry(aAuthorStr);\n aMoveColorLB.InsertEntry(aAuthorStr);\n aInsertColorLB.InsertEntry(aAuthorStr);\n aRemoveColorLB.InsertEntry(aAuthorStr);\n\n aContentColorLB.SetUpdateMode( FALSE);\n aMoveColorLB.SetUpdateMode( FALSE);\n aInsertColorLB.SetUpdateMode( FALSE);\n aRemoveColorLB.SetUpdateMode( FALSE);\n\n for( USHORT i = 0; i < pColorTbl->Count(); ++i )\n {\n XColorEntry* pEntry = pColorTbl->GetColor( i );\n Color aColor = pEntry->GetColor();\n String sName = pEntry->GetName();\n\n aContentColorLB.InsertEntry( aColor, sName );\n aMoveColorLB.InsertEntry( aColor, sName );\n aInsertColorLB.InsertEntry( aColor, sName );\n aRemoveColorLB.InsertEntry( aColor, sName );\n }\n aContentColorLB.SetUpdateMode( TRUE );\n aMoveColorLB.SetUpdateMode( TRUE );\n aInsertColorLB.SetUpdateMode( TRUE );\n aRemoveColorLB.SetUpdateMode( TRUE );\n\n\n ScAppOptions aAppOptions=SC_MOD()->GetAppOptions();\n\n ULONG nColor = aAppOptions.GetTrackContentColor();\n if (nColor == COL_TRANSPARENT)\n aContentColorLB.SelectEntryPos(0);\n else\n aContentColorLB.SelectEntry(Color(nColor));\n\n nColor = aAppOptions.GetTrackMoveColor();\n if (nColor == COL_TRANSPARENT)\n aMoveColorLB.SelectEntryPos(0);\n else\n aMoveColorLB.SelectEntry(Color(nColor));\n\n\n nColor = aAppOptions.GetTrackInsertColor();\n if (nColor == COL_TRANSPARENT)\n aInsertColorLB.SelectEntryPos(0);\n else\n aInsertColorLB.SelectEntry(Color(nColor));\n\n\n nColor = aAppOptions.GetTrackDeleteColor();\n if (nColor == COL_TRANSPARENT)\n aRemoveColorLB.SelectEntryPos(0);\n else\n aRemoveColorLB.SelectEntry(Color(nColor));\n\n}\n\n\nIMPL_LINK( ScRedlineOptionsTabPage, ColorHdl, ColorListBox *, EMPTYARG )\n{\n\/*\n SvxFontPrevWindow *pPrev;\n ListBox *pLB;\n\n if (pColorLB == &aInsertColorLB)\n {\n pPrev = &aInsertPreviewWN;\n pLB = &aInsertLB;\n }\n else\n {\n pPrev = &aDeletedPreviewWN;\n pLB = &aDeletedLB;\n }\n\n SvxFont& rFont = pPrev->GetFont();\n USHORT nPos = pLB->GetSelectEntryPos();\n if (nPos == LISTBOX_ENTRY_NOTFOUND)\n nPos = 0;\n\n CharAttr *pAttr = (CharAttr *)pLB->GetEntryData(nPos);\n\n if (pAttr->nItemId == SID_ATTR_BRUSH)\n {\n rFont.SetColor(Color(COL_BLACK));\n nPos = pColorLB->GetSelectEntryPos();\n if (nPos && nPos != LISTBOX_ENTRY_NOTFOUND)\n {\n Brush aBrush(Color(pColorLB->GetSelectEntryColor()));\n pPrev->SetBrush(aBrush);\n }\n else\n {\n Brush aBrush(Color(COL_LIGHTGRAY));\n pPrev->SetBrush(aBrush);\n }\n }\n else\n {\n nPos = pColorLB->GetSelectEntryPos();\n if (nPos && nPos != LISTBOX_ENTRY_NOTFOUND)\n rFont.SetColor(pColorLB->GetEntryColor(nPos));\n else\n rFont.SetColor(Color(COL_RED));\n }\n\n pPrev->Invalidate();\n*\/\n return 0;\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\nRemove empty Beschreibung (Description) comments\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sc.hxx\"\n\n#undef SC_DLLIMPLEMENTATION\n\n\n\n\/\/------------------------------------------------------------------\n\n#include \n#include \n#include \n\n#include \"appoptio.hxx\"\n#include \"scmod.hxx\"\n#include \"scitems.hxx\"\n#include \"tpview.hxx\"\n#include \"global.hxx\"\n#include \"viewopti.hxx\"\n#include \"tabvwsh.hxx\"\n#include \"uiitems.hxx\"\n#include \"scresid.hxx\"\n#include \"docsh.hxx\"\n#include \"sc.hrc\" \/\/ -> Slot-IDs\n#include \"optdlg.hrc\"\n#include \"globstr.hrc\"\n\n#include \"opredlin.hxx\"\n#include \"opredlin.hrc\"\n\n\/\/------------------------------------------------------------------\n\nScRedlineOptionsTabPage::ScRedlineOptionsTabPage( Window* pParent,\n const SfxItemSet& rSet )\n : SfxTabPage(pParent, ScResId(RID_SCPAGE_OPREDLINE), rSet),\n aContentFT ( this, ScResId(FT_CONTENT )),\n aContentColorLB ( this, ScResId(CLB_CONTENT )),\n aRemoveFT ( this, ScResId(FT_REMOVE )),\n aRemoveColorLB ( this, ScResId(CLB_REMOVE )),\n aInsertFT ( this, ScResId(FT_INSERT )),\n aInsertColorLB ( this, ScResId(CLB_INSERT )),\n aMoveFT ( this, ScResId(FT_MOVE )),\n aMoveColorLB ( this, ScResId(CLB_MOVE )),\n aChangedGB ( this, ScResId(GB_COLORCHGS)),\n aAuthorStr (ScResId(STR_AUTHOR))\n{\n FreeResource();\n\n Link aLk = LINK(this, ScRedlineOptionsTabPage, ColorHdl);\n aContentColorLB.SetSelectHdl( aLk );\n aMoveColorLB.SetSelectHdl( aLk );\n aInsertColorLB.SetSelectHdl( aLk );\n aRemoveColorLB.SetSelectHdl( aLk );\n}\n\n__EXPORT ScRedlineOptionsTabPage::~ScRedlineOptionsTabPage()\n{\n}\n\nSfxTabPage* __EXPORT ScRedlineOptionsTabPage::Create( Window* pParent, const SfxItemSet& rSet )\n{\n return new ScRedlineOptionsTabPage( pParent, rSet );\n}\n\nBOOL __EXPORT ScRedlineOptionsTabPage::FillItemSet( SfxItemSet& \/* rSet *\/ )\n{\n ScAppOptions aAppOptions=SC_MOD()->GetAppOptions();\n\n ULONG nNew=0;\n USHORT nPos=0;\n\n nPos = aContentColorLB.GetSelectEntryPos();\n if (nPos != LISTBOX_ENTRY_NOTFOUND)\n {\n nPos = aContentColorLB.GetSelectEntryPos();\n if (nPos!=0)\n nNew= aContentColorLB.GetEntryColor(nPos).GetColor();\n else\n nNew= COL_TRANSPARENT;\n\n aAppOptions.SetTrackContentColor(nNew);\n\n }\n nPos = aMoveColorLB.GetSelectEntryPos();\n if (nPos != LISTBOX_ENTRY_NOTFOUND)\n {\n nPos = aMoveColorLB.GetSelectEntryPos();\n if (nPos!=0)\n nNew= aMoveColorLB.GetEntryColor(nPos).GetColor();\n else\n nNew= COL_TRANSPARENT;\n\n aAppOptions.SetTrackMoveColor(nNew);\n\n }\n nPos = aInsertColorLB.GetSelectEntryPos();\n if (nPos != LISTBOX_ENTRY_NOTFOUND)\n {\n nPos = aInsertColorLB.GetSelectEntryPos();\n if (nPos!=0)\n nNew= aInsertColorLB.GetEntryColor(nPos).GetColor();\n else\n nNew= COL_TRANSPARENT;\n\n aAppOptions.SetTrackInsertColor(nNew);\n\n }\n nPos = aRemoveColorLB.GetSelectEntryPos();\n if (nPos != LISTBOX_ENTRY_NOTFOUND)\n {\n nPos = aRemoveColorLB.GetSelectEntryPos();\n if (nPos!=0)\n nNew= aRemoveColorLB.GetEntryColor(nPos).GetColor();\n else\n nNew= COL_TRANSPARENT;\n\n aAppOptions.SetTrackDeleteColor(nNew);\n\n }\n\n SC_MOD()->SetAppOptions(aAppOptions);\n\n \/\/ Repaint (wenn alles ueber Items laufen wuerde, wie es sich gehoert,\n \/\/ waere das nicht noetig...)\n ScDocShell* pDocSh = PTR_CAST(ScDocShell, SfxObjectShell::Current());\n if (pDocSh)\n pDocSh->PostPaintGridAll();\n\n return FALSE;\n}\n\nvoid __EXPORT ScRedlineOptionsTabPage::Reset( const SfxItemSet& \/* rSet *\/ )\n{\n\n XColorTable* pColorTbl = XColorTable::GetStdColorTable();\n aContentColorLB.InsertEntry(aAuthorStr);\n aMoveColorLB.InsertEntry(aAuthorStr);\n aInsertColorLB.InsertEntry(aAuthorStr);\n aRemoveColorLB.InsertEntry(aAuthorStr);\n\n aContentColorLB.SetUpdateMode( FALSE);\n aMoveColorLB.SetUpdateMode( FALSE);\n aInsertColorLB.SetUpdateMode( FALSE);\n aRemoveColorLB.SetUpdateMode( FALSE);\n\n for( USHORT i = 0; i < pColorTbl->Count(); ++i )\n {\n XColorEntry* pEntry = pColorTbl->GetColor( i );\n Color aColor = pEntry->GetColor();\n String sName = pEntry->GetName();\n\n aContentColorLB.InsertEntry( aColor, sName );\n aMoveColorLB.InsertEntry( aColor, sName );\n aInsertColorLB.InsertEntry( aColor, sName );\n aRemoveColorLB.InsertEntry( aColor, sName );\n }\n aContentColorLB.SetUpdateMode( TRUE );\n aMoveColorLB.SetUpdateMode( TRUE );\n aInsertColorLB.SetUpdateMode( TRUE );\n aRemoveColorLB.SetUpdateMode( TRUE );\n\n\n ScAppOptions aAppOptions=SC_MOD()->GetAppOptions();\n\n ULONG nColor = aAppOptions.GetTrackContentColor();\n if (nColor == COL_TRANSPARENT)\n aContentColorLB.SelectEntryPos(0);\n else\n aContentColorLB.SelectEntry(Color(nColor));\n\n nColor = aAppOptions.GetTrackMoveColor();\n if (nColor == COL_TRANSPARENT)\n aMoveColorLB.SelectEntryPos(0);\n else\n aMoveColorLB.SelectEntry(Color(nColor));\n\n\n nColor = aAppOptions.GetTrackInsertColor();\n if (nColor == COL_TRANSPARENT)\n aInsertColorLB.SelectEntryPos(0);\n else\n aInsertColorLB.SelectEntry(Color(nColor));\n\n\n nColor = aAppOptions.GetTrackDeleteColor();\n if (nColor == COL_TRANSPARENT)\n aRemoveColorLB.SelectEntryPos(0);\n else\n aRemoveColorLB.SelectEntry(Color(nColor));\n\n}\n\n\nIMPL_LINK( ScRedlineOptionsTabPage, ColorHdl, ColorListBox *, EMPTYARG )\n{\n\/*\n SvxFontPrevWindow *pPrev;\n ListBox *pLB;\n\n if (pColorLB == &aInsertColorLB)\n {\n pPrev = &aInsertPreviewWN;\n pLB = &aInsertLB;\n }\n else\n {\n pPrev = &aDeletedPreviewWN;\n pLB = &aDeletedLB;\n }\n\n SvxFont& rFont = pPrev->GetFont();\n USHORT nPos = pLB->GetSelectEntryPos();\n if (nPos == LISTBOX_ENTRY_NOTFOUND)\n nPos = 0;\n\n CharAttr *pAttr = (CharAttr *)pLB->GetEntryData(nPos);\n\n if (pAttr->nItemId == SID_ATTR_BRUSH)\n {\n rFont.SetColor(Color(COL_BLACK));\n nPos = pColorLB->GetSelectEntryPos();\n if (nPos && nPos != LISTBOX_ENTRY_NOTFOUND)\n {\n Brush aBrush(Color(pColorLB->GetSelectEntryColor()));\n pPrev->SetBrush(aBrush);\n }\n else\n {\n Brush aBrush(Color(COL_LIGHTGRAY));\n pPrev->SetBrush(aBrush);\n }\n }\n else\n {\n nPos = pColorLB->GetSelectEntryPos();\n if (nPos && nPos != LISTBOX_ENTRY_NOTFOUND)\n rFont.SetColor(pColorLB->GetEntryColor(nPos));\n else\n rFont.SetColor(Color(COL_RED));\n }\n\n pPrev->Invalidate();\n*\/\n return 0;\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"#include \n\n#include \n\n#include \n\n#include \"model_library.h\"\n#include \"network.h\"\n#include \"robot_impl.h\"\n\nusing namespace std::string_literals; \/\/ NOLINT (google-build-using-namespace)\n\nnamespace franka {\n\nModel::Model(Network& network) : library_{new ModelLibrary(network)} {}\n\n\/\/ Has to be declared here, as the ModelLibrary type is incomplete in the\n\/\/ header\nModel::~Model() noexcept = default;\n\nstd::array Model::jointPose(Frame joint, const franka::RobotState& robot_state) const {\n std::array output;\n\n std::array::const_pointer q = robot_state.q.data();\n std::array::const_pointer end_effector = robot_state.O_T_EE.data();\n\n switch (joint) {\n case Frame::kJoint1:\n library_->joint1(q, end_effector, output.data());\n break;\n case Frame::kJoint2:\n library_->joint2(q, end_effector, output.data());\n break;\n case Frame::kJoint3:\n library_->joint3(q, end_effector, output.data());\n break;\n case Frame::kJoint4:\n library_->joint4(q, end_effector, output.data());\n break;\n case Frame::kJoint5:\n library_->joint5(q, end_effector, output.data());\n break;\n case Frame::kJoint6:\n library_->joint6(q, end_effector, output.data());\n break;\n case Frame::kJoint7:\n library_->joint7(q, end_effector, output.data());\n break;\n case Frame::kFlange:\n library_->flange(q, end_effector, output.data());\n break;\n case Frame::kEndEffector:\n library_->ee(q, end_effector, output.data());\n break;\n default:\n throw std::invalid_argument(\"Invalid joint given.\");\n }\n\n return output;\n}\n\nstd::array franka::Model::mass(\n const franka::RobotState& robot_state,\n const std::array& load_inertia,\n double load_mass,\n const std::array& F_x_Cload) \/\/ NOLINT (readability-identifier-naming)\n const noexcept {\n std::array output;\n library_->mass(robot_state.q.data(), load_inertia.data(), load_mass, F_x_Cload.data(),\n output.data());\n\n return output;\n}\n\nstd::array franka::Model::coriolis(\n const franka::RobotState& robot_state,\n const std::array& load_inertia,\n double load_mass,\n const std::array& F_x_Cload) \/\/ NOLINT (readability-identifier-naming)\n const noexcept {\n std::array output;\n library_->coriolis(robot_state.q.data(), robot_state.dq.data(), load_inertia.data(), load_mass,\n F_x_Cload.data(), output.data());\n\n return output;\n}\n\nstd::array franka::Model::gravity(\n const franka::RobotState& robot_state,\n double load_mass,\n const std::array& F_x_Cload, \/\/ NOLINT (readability-identifier-naming)\n const std::array& gravity_earth) const noexcept {\n std::array output;\n library_->gravity(robot_state.q.data(), gravity_earth.data(), load_mass, F_x_Cload.data(),\n output.data());\n\n return output;\n}\n\n} \/\/ namespace franka\nremove redundant robot_impl.h include#include \n\n#include \n\n#include \n\n#include \"model_library.h\"\n#include \"network.h\"\n\nusing namespace std::string_literals; \/\/ NOLINT (google-build-using-namespace)\n\nnamespace franka {\n\nModel::Model(Network& network) : library_{new ModelLibrary(network)} {}\n\n\/\/ Has to be declared here, as the ModelLibrary type is incomplete in the\n\/\/ header\nModel::~Model() noexcept = default;\n\nstd::array Model::jointPose(Frame joint, const franka::RobotState& robot_state) const {\n std::array output;\n\n std::array::const_pointer q = robot_state.q.data();\n std::array::const_pointer end_effector = robot_state.O_T_EE.data();\n\n switch (joint) {\n case Frame::kJoint1:\n library_->joint1(q, end_effector, output.data());\n break;\n case Frame::kJoint2:\n library_->joint2(q, end_effector, output.data());\n break;\n case Frame::kJoint3:\n library_->joint3(q, end_effector, output.data());\n break;\n case Frame::kJoint4:\n library_->joint4(q, end_effector, output.data());\n break;\n case Frame::kJoint5:\n library_->joint5(q, end_effector, output.data());\n break;\n case Frame::kJoint6:\n library_->joint6(q, end_effector, output.data());\n break;\n case Frame::kJoint7:\n library_->joint7(q, end_effector, output.data());\n break;\n case Frame::kFlange:\n library_->flange(q, end_effector, output.data());\n break;\n case Frame::kEndEffector:\n library_->ee(q, end_effector, output.data());\n break;\n default:\n throw std::invalid_argument(\"Invalid joint given.\");\n }\n\n return output;\n}\n\nstd::array franka::Model::mass(\n const franka::RobotState& robot_state,\n const std::array& load_inertia,\n double load_mass,\n const std::array& F_x_Cload) \/\/ NOLINT (readability-identifier-naming)\n const noexcept {\n std::array output;\n library_->mass(robot_state.q.data(), load_inertia.data(), load_mass, F_x_Cload.data(),\n output.data());\n\n return output;\n}\n\nstd::array franka::Model::coriolis(\n const franka::RobotState& robot_state,\n const std::array& load_inertia,\n double load_mass,\n const std::array& F_x_Cload) \/\/ NOLINT (readability-identifier-naming)\n const noexcept {\n std::array output;\n library_->coriolis(robot_state.q.data(), robot_state.dq.data(), load_inertia.data(), load_mass,\n F_x_Cload.data(), output.data());\n\n return output;\n}\n\nstd::array franka::Model::gravity(\n const franka::RobotState& robot_state,\n double load_mass,\n const std::array& F_x_Cload, \/\/ NOLINT (readability-identifier-naming)\n const std::array& gravity_earth) const noexcept {\n std::array output;\n library_->gravity(robot_state.q.data(), gravity_earth.data(), load_mass, F_x_Cload.data(),\n output.data());\n\n return output;\n}\n\n} \/\/ namespace franka\n<|endoftext|>"} {"text":"\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2014 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\n\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\/\/ System Includes\n#include \n#include \n\n\/\/ Local Includes\n#include \"libmesh\/libmesh_common.h\"\n#include \"libmesh\/parallel.h\"\n#include \"libmesh\/parallel_hilbert.h\"\n#include \"libmesh\/parallel_sort.h\"\n#include \"libmesh\/parallel_bin_sorter.h\"\n#ifdef LIBMESH_HAVE_LIBHILBERT\n# include \"hilbert.h\"\n#endif\n\nnamespace libMesh\n{\n\n\nnamespace Parallel {\n\n\/\/ The Constructor sorts the local data using\n\/\/ std::sort(). Therefore, the construction of\n\/\/ a Parallel::Sort object takes O(nlogn) time,\n\/\/ where n is the length of _data.\ntemplate \nSort::Sort(const Parallel::Communicator &comm_in,\n std::vector& d) :\n ParallelObject(comm_in),\n _n_procs(cast_int(comm_in.size())),\n _proc_id(cast_int(comm_in.rank())),\n _bin_is_sorted(false),\n _data(d)\n{\n std::sort(_data.begin(), _data.end());\n\n \/\/ Allocate storage\n _local_bin_sizes.resize(_n_procs);\n}\n\n\n\ntemplate \nvoid Sort::sort()\n{\n \/\/ Find the global data size. The sorting\n \/\/ algorithms assume they have a range to\n \/\/ work with, so catch the degenerate cases here\n IdxType global_data_size = cast_int(_data.size());\n\n this->comm().sum (global_data_size);\n\n if (global_data_size < 2)\n {\n \/\/ the entire global range is either empty\n \/\/ or contains only one element\n _my_bin = _data;\n\n this->comm().allgather (static_cast(_my_bin.size()),\n _local_bin_sizes);\n }\n else\n {\n if (this->n_processors() > 1)\n {\n this->binsort();\n this->communicate_bins();\n }\n else\n _my_bin = _data;\n\n this->sort_local_bin();\n }\n\n \/\/ Set sorted flag to true\n _bin_is_sorted = true;\n}\n\n\n\ntemplate \nvoid Sort::binsort()\n{\n \/\/ Find the global min and max from all the\n \/\/ processors.\n std::vector global_min_max(2);\n\n \/\/ Insert the local min and max for this processor\n global_min_max[0] = -_data.front();\n global_min_max[1] = _data.back();\n\n \/\/ Communicate to determine the global\n \/\/ min and max for all processors.\n this->comm().max(global_min_max);\n\n \/\/ Multiply the min by -1 to obtain the true min\n global_min_max[0] *= -1;\n\n \/\/ Bin-Sort based on the global min and max\n Parallel::BinSorter bs(this->comm(), _data);\n bs.binsort(_n_procs, global_min_max[1], global_min_max[0]);\n\n \/\/ Now save the local bin sizes in a vector so\n \/\/ we don't have to keep around the BinSorter.\n for (processor_id_type i=0; i<_n_procs; ++i)\n _local_bin_sizes[i] = bs.sizeof_bin(i);\n}\n\n\n\n#if defined(LIBMESH_HAVE_LIBHILBERT) && defined(LIBMESH_HAVE_MPI)\n\/\/ Full specialization for HilbertIndices, there is a fair amount of\n\/\/ code duplication here that could potentially be consolidated with the\n\/\/ above method\ntemplate <>\nvoid Sort::binsort()\n{\n \/\/ Find the global min and max from all the\n \/\/ processors. Do this using MPI_Allreduce.\n Hilbert::HilbertIndices\n local_min, local_max,\n global_min, global_max;\n\n if (_data.empty())\n {\n local_min.rack0 = local_min.rack1 = local_min.rack2 = static_cast(-1);\n local_max.rack0 = local_max.rack1 = local_max.rack2 = 0;\n }\n else\n {\n local_min = _data.front();\n local_max = _data.back();\n }\n\n MPI_Op hilbert_max, hilbert_min;\n\n MPI_Op_create ((MPI_User_function*)__hilbert_max_op, true, &hilbert_max);\n MPI_Op_create ((MPI_User_function*)__hilbert_min_op, true, &hilbert_min);\n\n \/\/ Communicate to determine the global\n \/\/ min and max for all processors.\n MPI_Allreduce(&local_min,\n &global_min,\n 1,\n Parallel::StandardType(),\n hilbert_min,\n this->comm().get());\n\n MPI_Allreduce(&local_max,\n &global_max,\n 1,\n Parallel::StandardType(),\n hilbert_max,\n this->comm().get());\n\n MPI_Op_free (&hilbert_max);\n MPI_Op_free (&hilbert_min);\n\n \/\/ Bin-Sort based on the global min and max\n Parallel::BinSorter bs(this->comm(),_data);\n bs.binsort(_n_procs, global_max, global_min);\n\n \/\/ Now save the local bin sizes in a vector so\n \/\/ we don't have to keep around the BinSorter.\n for (processor_id_type i=0; i<_n_procs; ++i)\n _local_bin_sizes[i] = bs.sizeof_bin(i);\n}\n\n#endif \/\/ #ifdef LIBMESH_HAVE_LIBHILBERT\n\n\ntemplate \nvoid Sort::communicate_bins()\n{\n#ifdef LIBMESH_HAVE_MPI\n \/\/ Create storage for the global bin sizes. This\n \/\/ is the number of keys which will be held in\n \/\/ each bin over all processors.\n std::vector global_bin_sizes = _local_bin_sizes;\n\n \/\/ Sum to find the total number of entries in each bin.\n this->comm().sum(global_bin_sizes);\n\n \/\/ Create a vector to temporarily hold the results of MPI_Gatherv\n \/\/ calls. The vector dest may be saved away to _my_bin depending on which\n \/\/ processor is being MPI_Gatherv'd.\n std::vector dest;\n\n IdxType local_offset = 0;\n\n for (processor_id_type i=0; i<_n_procs; ++i)\n {\n \/\/ Vector to receive the total bin size for each\n \/\/ processor. Processor i's bin size will be\n \/\/ held in proc_bin_size[i]\n std::vector proc_bin_size;\n\n \/\/ Find the number of contributions coming from each\n \/\/ processor for this bin. Note: allgather combines\n \/\/ the MPI_Gather and MPI_Bcast operations into one.\n this->comm().allgather(static_cast(_local_bin_sizes[i]),\n proc_bin_size);\n\n \/\/ Compute the offsets into my_bin for each processor's\n \/\/ portion of the bin. These are basically partial sums\n \/\/ of the proc_bin_size vector.\n std::vector displacements(_n_procs);\n for (processor_id_type j=1; j<_n_procs; ++j)\n displacements[j] = proc_bin_size[j-1] + displacements[j-1];\n\n \/\/ Resize the destination buffer\n dest.resize (global_bin_sizes[i]);\n\n MPI_Gatherv((_data.size() > local_offset) ?\n &_data[local_offset] :\n NULL, \/\/ Points to the beginning of the bin to be sent\n _local_bin_sizes[i], \/\/ How much data is in the bin being sent.\n Parallel::StandardType(), \/\/ The data type we are sorting\n (dest.empty()) ?\n NULL :\n &dest[0], \/\/ Enough storage to hold all bin contributions\n &proc_bin_size[0], \/\/ How much is to be received from each processor\n &displacements[0], \/\/ Offsets into the receive buffer\n Parallel::StandardType(), \/\/ The data type we are sorting\n i, \/\/ The root process (we do this once for each proc)\n this->comm().get());\n\n \/\/ Copy the destination buffer if it\n \/\/ corresponds to the bin for this processor\n if (i == _proc_id)\n _my_bin = dest;\n\n \/\/ Increment the local offset counter\n local_offset += _local_bin_sizes[i];\n }\n#endif \/\/ LIBMESH_HAVE_MPI\n}\n\n\n\n#if defined(LIBMESH_HAVE_LIBHILBERT) && defined(LIBMESH_HAVE_MPI)\n\/\/ Full specialization for HilbertIndices, there is a fair amount of\n\/\/ code duplication here that could potentially be consolidated with the\n\/\/ above method\ntemplate <>\nvoid Sort::communicate_bins()\n{\n \/\/ Create storage for the global bin sizes. This\n \/\/ is the number of keys which will be held in\n \/\/ each bin over all processors.\n std::vector global_bin_sizes(_n_procs);\n\n libmesh_assert_equal_to (_local_bin_sizes.size(), global_bin_sizes.size());\n\n \/\/ Sum to find the total number of entries in each bin.\n \/\/ This is stored in global_bin_sizes. Note, we\n \/\/ explicitly know that we are communicating MPI_UNSIGNED's here.\n MPI_Allreduce(&_local_bin_sizes[0],\n &global_bin_sizes[0],\n _n_procs,\n MPI_UNSIGNED,\n MPI_SUM,\n this->comm().get());\n\n \/\/ Create a vector to temporarily hold the results of MPI_Gatherv\n \/\/ calls. The vector dest may be saved away to _my_bin depending on which\n \/\/ processor is being MPI_Gatherv'd.\n std::vector dest;\n\n unsigned int local_offset = 0;\n\n for (unsigned int i=0; i<_n_procs; ++i)\n {\n \/\/ Vector to receive the total bin size for each\n \/\/ processor. Processor i's bin size will be\n \/\/ held in proc_bin_size[i]\n std::vector proc_bin_size(_n_procs);\n\n \/\/ Find the number of contributions coming from each\n \/\/ processor for this bin. Note: Allgather combines\n \/\/ the MPI_Gather and MPI_Bcast operations into one.\n \/\/ Note: Here again we know that we are communicating\n \/\/ MPI_UNSIGNED's so there is no need to check the MPI_traits.\n MPI_Allgather(&_local_bin_sizes[i], \/\/ Source: # of entries on this proc in bin i\n 1, \/\/ Number of items to gather\n MPI_UNSIGNED,\n &proc_bin_size[0], \/\/ Destination: Total # of entries in bin i\n 1,\n MPI_INT,\n this->comm().get());\n\n \/\/ Compute the offsets into my_bin for each processor's\n \/\/ portion of the bin. These are basically partial sums\n \/\/ of the proc_bin_size vector.\n std::vector displacements(_n_procs);\n for (unsigned int j=1; j<_n_procs; ++j)\n displacements[j] = proc_bin_size[j-1] + displacements[j-1];\n\n \/\/ Resize the destination buffer\n dest.resize (global_bin_sizes[i]);\n\n MPI_Gatherv((_data.size() > local_offset) ?\n &_data[local_offset] :\n NULL, \/\/ Points to the beginning of the bin to be sent\n _local_bin_sizes[i], \/\/ How much data is in the bin being sent.\n Parallel::StandardType(), \/\/ The data type we are sorting\n (dest.empty()) ?\n NULL :\n &dest[0], \/\/ Enough storage to hold all bin contributions\n &proc_bin_size[0], \/\/ How much is to be received from each processor\n &displacements[0], \/\/ Offsets into the receive buffer\n Parallel::StandardType(), \/\/ The data type we are sorting\n i, \/\/ The root process (we do this once for each proc)\n this->comm().get());\n\n \/\/ Copy the destination buffer if it\n \/\/ corresponds to the bin for this processor\n if (i == _proc_id)\n _my_bin = dest;\n\n \/\/ Increment the local offset counter\n local_offset += _local_bin_sizes[i];\n }\n}\n\n#endif \/\/ #if defined(LIBMESH_HAVE_LIBHILBERT) && defined(LIBMESH_HAVE_MPI)\n\n\n\ntemplate \nvoid Sort::sort_local_bin()\n{\n std::sort(_my_bin.begin(), _my_bin.end());\n}\n\n\n\ntemplate \nconst std::vector& Sort::bin()\n{\n if (!_bin_is_sorted)\n {\n libMesh::out << \"Warning! Bin is not yet sorted!\" << std::endl;\n }\n\n return _my_bin;\n}\n\n}\n\n\n\n\/\/ Explicitly instantiate for int, double\ntemplate class Parallel::Sort;\ntemplate class Parallel::Sort;\n#if defined(LIBMESH_HAVE_LIBHILBERT) && defined(LIBMESH_HAVE_MPI)\ntemplate class Parallel::Sort;\n#endif\n\n} \/\/ namespace libMesh\nConstruct the sendbuf\/recvbuf pointers separately to simplify debugging.\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2014 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\n\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\/\/ System Includes\n#include \n#include \n\n\/\/ Local Includes\n#include \"libmesh\/libmesh_common.h\"\n#include \"libmesh\/parallel.h\"\n#include \"libmesh\/parallel_hilbert.h\"\n#include \"libmesh\/parallel_sort.h\"\n#include \"libmesh\/parallel_bin_sorter.h\"\n#ifdef LIBMESH_HAVE_LIBHILBERT\n# include \"hilbert.h\"\n#endif\n\nnamespace libMesh\n{\n\n\nnamespace Parallel {\n\n\/\/ The Constructor sorts the local data using\n\/\/ std::sort(). Therefore, the construction of\n\/\/ a Parallel::Sort object takes O(nlogn) time,\n\/\/ where n is the length of _data.\ntemplate \nSort::Sort(const Parallel::Communicator &comm_in,\n std::vector& d) :\n ParallelObject(comm_in),\n _n_procs(cast_int(comm_in.size())),\n _proc_id(cast_int(comm_in.rank())),\n _bin_is_sorted(false),\n _data(d)\n{\n std::sort(_data.begin(), _data.end());\n\n \/\/ Allocate storage\n _local_bin_sizes.resize(_n_procs);\n}\n\n\n\ntemplate \nvoid Sort::sort()\n{\n \/\/ Find the global data size. The sorting\n \/\/ algorithms assume they have a range to\n \/\/ work with, so catch the degenerate cases here\n IdxType global_data_size = cast_int(_data.size());\n\n this->comm().sum (global_data_size);\n\n if (global_data_size < 2)\n {\n \/\/ the entire global range is either empty\n \/\/ or contains only one element\n _my_bin = _data;\n\n this->comm().allgather (static_cast(_my_bin.size()),\n _local_bin_sizes);\n }\n else\n {\n if (this->n_processors() > 1)\n {\n this->binsort();\n this->communicate_bins();\n }\n else\n _my_bin = _data;\n\n this->sort_local_bin();\n }\n\n \/\/ Set sorted flag to true\n _bin_is_sorted = true;\n}\n\n\n\ntemplate \nvoid Sort::binsort()\n{\n \/\/ Find the global min and max from all the\n \/\/ processors.\n std::vector global_min_max(2);\n\n \/\/ Insert the local min and max for this processor\n global_min_max[0] = -_data.front();\n global_min_max[1] = _data.back();\n\n \/\/ Communicate to determine the global\n \/\/ min and max for all processors.\n this->comm().max(global_min_max);\n\n \/\/ Multiply the min by -1 to obtain the true min\n global_min_max[0] *= -1;\n\n \/\/ Bin-Sort based on the global min and max\n Parallel::BinSorter bs(this->comm(), _data);\n bs.binsort(_n_procs, global_min_max[1], global_min_max[0]);\n\n \/\/ Now save the local bin sizes in a vector so\n \/\/ we don't have to keep around the BinSorter.\n for (processor_id_type i=0; i<_n_procs; ++i)\n _local_bin_sizes[i] = bs.sizeof_bin(i);\n}\n\n\n\n#if defined(LIBMESH_HAVE_LIBHILBERT) && defined(LIBMESH_HAVE_MPI)\n\/\/ Full specialization for HilbertIndices, there is a fair amount of\n\/\/ code duplication here that could potentially be consolidated with the\n\/\/ above method\ntemplate <>\nvoid Sort::binsort()\n{\n \/\/ Find the global min and max from all the\n \/\/ processors. Do this using MPI_Allreduce.\n Hilbert::HilbertIndices\n local_min, local_max,\n global_min, global_max;\n\n if (_data.empty())\n {\n local_min.rack0 = local_min.rack1 = local_min.rack2 = static_cast(-1);\n local_max.rack0 = local_max.rack1 = local_max.rack2 = 0;\n }\n else\n {\n local_min = _data.front();\n local_max = _data.back();\n }\n\n MPI_Op hilbert_max, hilbert_min;\n\n MPI_Op_create ((MPI_User_function*)__hilbert_max_op, true, &hilbert_max);\n MPI_Op_create ((MPI_User_function*)__hilbert_min_op, true, &hilbert_min);\n\n \/\/ Communicate to determine the global\n \/\/ min and max for all processors.\n MPI_Allreduce(&local_min,\n &global_min,\n 1,\n Parallel::StandardType(),\n hilbert_min,\n this->comm().get());\n\n MPI_Allreduce(&local_max,\n &global_max,\n 1,\n Parallel::StandardType(),\n hilbert_max,\n this->comm().get());\n\n MPI_Op_free (&hilbert_max);\n MPI_Op_free (&hilbert_min);\n\n \/\/ Bin-Sort based on the global min and max\n Parallel::BinSorter bs(this->comm(),_data);\n bs.binsort(_n_procs, global_max, global_min);\n\n \/\/ Now save the local bin sizes in a vector so\n \/\/ we don't have to keep around the BinSorter.\n for (processor_id_type i=0; i<_n_procs; ++i)\n _local_bin_sizes[i] = bs.sizeof_bin(i);\n}\n\n#endif \/\/ #ifdef LIBMESH_HAVE_LIBHILBERT\n\n\ntemplate \nvoid Sort::communicate_bins()\n{\n#ifdef LIBMESH_HAVE_MPI\n \/\/ Create storage for the global bin sizes. This\n \/\/ is the number of keys which will be held in\n \/\/ each bin over all processors.\n std::vector global_bin_sizes = _local_bin_sizes;\n\n \/\/ Sum to find the total number of entries in each bin.\n this->comm().sum(global_bin_sizes);\n\n \/\/ Create a vector to temporarily hold the results of MPI_Gatherv\n \/\/ calls. The vector dest may be saved away to _my_bin depending on which\n \/\/ processor is being MPI_Gatherv'd.\n std::vector dest;\n\n IdxType local_offset = 0;\n\n for (processor_id_type i=0; i<_n_procs; ++i)\n {\n \/\/ Vector to receive the total bin size for each\n \/\/ processor. Processor i's bin size will be\n \/\/ held in proc_bin_size[i]\n std::vector proc_bin_size;\n\n \/\/ Find the number of contributions coming from each\n \/\/ processor for this bin. Note: allgather combines\n \/\/ the MPI_Gather and MPI_Bcast operations into one.\n this->comm().allgather(static_cast(_local_bin_sizes[i]),\n proc_bin_size);\n\n \/\/ Compute the offsets into my_bin for each processor's\n \/\/ portion of the bin. These are basically partial sums\n \/\/ of the proc_bin_size vector.\n std::vector displacements(_n_procs);\n for (processor_id_type j=1; j<_n_procs; ++j)\n displacements[j] = proc_bin_size[j-1] + displacements[j-1];\n\n \/\/ Resize the destination buffer\n dest.resize (global_bin_sizes[i]);\n\n \/\/ Points to the beginning of the bin to be sent\n void * sendbuf = (_data.size() > local_offset) ? &_data[local_offset] : NULL;\n\n \/\/ Enough storage to hold all bin contributions\n void * recvbuf = (dest.empty()) ? NULL : &dest[0];\n\n \/\/ If the sendbuf is NULL, make sure we aren't claiming to send something.\n if (sendbuf == NULL && _local_bin_sizes[i] != 0)\n libmesh_error_msg(\"Error: invalid MPI_Gatherv call constructed!\");\n\n MPI_Gatherv(sendbuf,\n _local_bin_sizes[i], \/\/ How much data is in the bin being sent.\n Parallel::StandardType(), \/\/ The data type we are sorting\n recvbuf,\n &proc_bin_size[0], \/\/ How much is to be received from each processor\n &displacements[0], \/\/ Offsets into the receive buffer\n Parallel::StandardType(), \/\/ The data type we are sorting\n i, \/\/ The root process (we do this once for each proc)\n this->comm().get());\n\n \/\/ Copy the destination buffer if it\n \/\/ corresponds to the bin for this processor\n if (i == _proc_id)\n _my_bin = dest;\n\n \/\/ Increment the local offset counter\n local_offset += _local_bin_sizes[i];\n }\n#endif \/\/ LIBMESH_HAVE_MPI\n}\n\n\n\n#if defined(LIBMESH_HAVE_LIBHILBERT) && defined(LIBMESH_HAVE_MPI)\n\/\/ Full specialization for HilbertIndices, there is a fair amount of\n\/\/ code duplication here that could potentially be consolidated with the\n\/\/ above method\ntemplate <>\nvoid Sort::communicate_bins()\n{\n \/\/ Create storage for the global bin sizes. This\n \/\/ is the number of keys which will be held in\n \/\/ each bin over all processors.\n std::vector global_bin_sizes(_n_procs);\n\n libmesh_assert_equal_to (_local_bin_sizes.size(), global_bin_sizes.size());\n\n \/\/ Sum to find the total number of entries in each bin.\n \/\/ This is stored in global_bin_sizes. Note, we\n \/\/ explicitly know that we are communicating MPI_UNSIGNED's here.\n MPI_Allreduce(&_local_bin_sizes[0],\n &global_bin_sizes[0],\n _n_procs,\n MPI_UNSIGNED,\n MPI_SUM,\n this->comm().get());\n\n \/\/ Create a vector to temporarily hold the results of MPI_Gatherv\n \/\/ calls. The vector dest may be saved away to _my_bin depending on which\n \/\/ processor is being MPI_Gatherv'd.\n std::vector dest;\n\n unsigned int local_offset = 0;\n\n for (unsigned int i=0; i<_n_procs; ++i)\n {\n \/\/ Vector to receive the total bin size for each\n \/\/ processor. Processor i's bin size will be\n \/\/ held in proc_bin_size[i]\n std::vector proc_bin_size(_n_procs);\n\n \/\/ Find the number of contributions coming from each\n \/\/ processor for this bin. Note: Allgather combines\n \/\/ the MPI_Gather and MPI_Bcast operations into one.\n \/\/ Note: Here again we know that we are communicating\n \/\/ MPI_UNSIGNED's so there is no need to check the MPI_traits.\n MPI_Allgather(&_local_bin_sizes[i], \/\/ Source: # of entries on this proc in bin i\n 1, \/\/ Number of items to gather\n MPI_UNSIGNED,\n &proc_bin_size[0], \/\/ Destination: Total # of entries in bin i\n 1,\n MPI_INT,\n this->comm().get());\n\n \/\/ Compute the offsets into my_bin for each processor's\n \/\/ portion of the bin. These are basically partial sums\n \/\/ of the proc_bin_size vector.\n std::vector displacements(_n_procs);\n for (unsigned int j=1; j<_n_procs; ++j)\n displacements[j] = proc_bin_size[j-1] + displacements[j-1];\n\n \/\/ Resize the destination buffer\n dest.resize (global_bin_sizes[i]);\n\n \/\/ Points to the beginning of the bin to be sent\n void * sendbuf = (_data.size() > local_offset) ? &_data[local_offset] : NULL;\n\n \/\/ Enough storage to hold all bin contributions\n void * recvbuf = (dest.empty()) ? NULL : &dest[0];\n\n \/\/ If the sendbuf is NULL, make sure we aren't claiming to send something.\n if (sendbuf == NULL && _local_bin_sizes[i] != 0)\n libmesh_error_msg(\"Error: invalid MPI_Gatherv call constructed!\");\n\n MPI_Gatherv(sendbuf,\n _local_bin_sizes[i], \/\/ How much data is in the bin being sent.\n Parallel::StandardType(), \/\/ The data type we are sorting\n recvbuf,\n &proc_bin_size[0], \/\/ How much is to be received from each processor\n &displacements[0], \/\/ Offsets into the receive buffer\n Parallel::StandardType(), \/\/ The data type we are sorting\n i, \/\/ The root process (we do this once for each proc)\n this->comm().get());\n\n \/\/ Copy the destination buffer if it\n \/\/ corresponds to the bin for this processor\n if (i == _proc_id)\n _my_bin = dest;\n\n \/\/ Increment the local offset counter\n local_offset += _local_bin_sizes[i];\n }\n}\n\n#endif \/\/ #if defined(LIBMESH_HAVE_LIBHILBERT) && defined(LIBMESH_HAVE_MPI)\n\n\n\ntemplate \nvoid Sort::sort_local_bin()\n{\n std::sort(_my_bin.begin(), _my_bin.end());\n}\n\n\n\ntemplate \nconst std::vector& Sort::bin()\n{\n if (!_bin_is_sorted)\n {\n libMesh::out << \"Warning! Bin is not yet sorted!\" << std::endl;\n }\n\n return _my_bin;\n}\n\n}\n\n\n\n\/\/ Explicitly instantiate for int, double\ntemplate class Parallel::Sort;\ntemplate class Parallel::Sort;\n#if defined(LIBMESH_HAVE_LIBHILBERT) && defined(LIBMESH_HAVE_MPI)\ntemplate class Parallel::Sort;\n#endif\n\n} \/\/ namespace libMesh\n<|endoftext|>"} {"text":"#include \"cnn\/training.h\"\n\n\/\/ #include \"cnn\/gpu-ops.h\"\n#include \"cnn\/param-nodes.h\"\n#include \"cnn\/weight-decay.h\"\n\n\/\/ Macros for defining parameter update functions\n#ifdef __CUDACC__\n#define CNN_TRAINER_INST_DEV_IMPL(MyTrainer) \\\n template void MyTrainer::update_rule_dev(const Device_GPU & dev, real scale, real gscale, const std::vector & values);\n#elif defined(HAVE_CUDA)\n#define CNN_TRAINER_INST_DEV_IMPL(MyTrainer) \\\n extern template void MyTrainer::update_rule_dev(const Device_GPU & dev, real scale, real gscale, const std::vector & values); \\\n template void MyTrainer::update_rule_dev(const Device_CPU & dev, real scale, real gscale, const std::vector & values); \\\n void MyTrainer::update_rule(real scale, real gscale, const std::vector & values) { \\\n if(values[0]->device->type == DeviceType::CPU) { update_rule_dev(*(Device_CPU*)values[0]->device,scale,gscale,values); } \\\n else if(values[0]->device->type == DeviceType::GPU) { update_rule_dev(*(Device_GPU*)values[0]->device,scale,gscale,values); } \\\n else { abort(); } \\\n }\n#else\n#define CNN_TRAINER_INST_DEV_IMPL(MyTrainer) \\\n template void MyTrainer::update_rule_dev(const Device_CPU & dev, real scale, real gscale, const std::vector & values); \\\n void MyTrainer::update_rule(real scale, real gscale, const std::vector & values) { \\\n if(values[0]->device->type == DeviceType::CPU) { update_rule_dev(*(Device_CPU*)values[0]->device,scale,gscale,values); } \\\n else { abort(); } \\\n }\n#endif\n\nnamespace cnn {\n\nusing namespace std;\n\ntemplate \nbool is_valid(const Eigen::MatrixBase& x) {\n return ((x - x).array() == (x - x).array()).all();\n}\n\n\/\/ --- The actual update code for each operation, implemented on various devices\n\n\/\/ Trainer base class is run on CPUs\n#ifndef __CUDACC__\n\nTrainer::~Trainer() {}\n\nvoid Trainer::rescale_and_reset_weight_decay() {\n const float weight_decay = global_weight_decay.CurrentWeightDecay();\n for (auto p : model->parameters_list())\n p->scale_parameters(weight_decay);\n global_weight_decay.ResetWeightDecay();\n}\n\nfloat Trainer::clip_gradients() {\n float gscale = 1;\n if (clipping_enabled) {\n float gg = model->gradient_l2_norm();\n if (isnan(gg) || isinf(gg)) {\n cerr << \"Magnitude of gradient is bad: \" << gg << endl;\n abort();\n }\n if (gg > clip_threshold) {\n ++clips;\n gscale = clip_threshold \/ gg;\n }\n }\n return gscale;\n}\n\n\/\/ this calls the rule-specific\nvoid Trainer::update(real scale) {\n \/\/ Allocate if necessary\n if(!aux_allocated) {\n alloc_impl();\n aux_allocated = true;\n }\n\n \/\/ Perform gradient clipping and cycle through parameters\n const float gscale = clip_gradients();\n const auto & params = model->parameters_list();\n for(size_t i = 0; i < params.size(); ++i) {\n update_params(scale, gscale, i);\n params[i]->clear();\n }\n const auto & lookup_params = model->lookup_parameters_list();\n for(size_t i = 0; i < lookup_params.size(); ++i) {\n for (auto j : lookup_params[i]->non_zero_grads)\n update_lookup_params(scale, gscale, i, j);\n lookup_params[i]->clear();\n }\n ++updates;\n\n global_weight_decay.UpdateWeightDecay(); \/\/ update global weight scale\n if (global_weight_decay.ParametersNeedRescaled())\n rescale_and_reset_weight_decay(); \/\/ if wdscale is getting to small multiply all weights by wdscale, and set wdscale to 1\n}\n\n#endif\n\n\/\/ --- SimpleSGDTrainer\n\n\/\/ Perform update of ts[0]=parameters, ts[1]=gradients\ntemplate \nvoid SimpleSGDTrainer::update_rule_dev(const MyDevice & dev, real scale, real gscale, const std::vector & ts) {\n ts[0]->tvec().device(*dev.edevice) -= ts[1]->tvec() * (eta * scale * gscale \/ global_weight_decay.CurrentWeightDecay());\n}\nCNN_TRAINER_INST_DEV_IMPL(SimpleSGDTrainer)\n\n#ifndef __CUDACC__\nvoid SimpleSGDTrainer::update_params(real scale, real gscale, size_t idx) {\n auto & p = model->parameters_list()[idx];\n update_rule(scale, gscale, {&p->values, &p->g});\n}\nvoid SimpleSGDTrainer::update_lookup_params(real scale, real gscale, size_t idx, size_t lidx) {\n auto & p = model->lookup_parameters_list()[idx];\n update_rule(scale, gscale, {&p->values[lidx], &p->grads[lidx]});\n}\n#endif\n\n\/\/ --- MomentumSGDTrainer\n\n\/\/ Perform update of ts[0]=parameters, ts[1]=gradients, ts[2]=momentum\ntemplate \nvoid MomentumSGDTrainer::update_rule_dev(const MyDevice & dev, real scale, real gscale, const std::vector & ts) {\n ts[2]->tvec().device(*dev.edevice) = ts[2]->tvec() * momentum - ts[1]->tvec() * (eta * scale * gscale);\n ts[0]->tvec().device(*dev.edevice) += ts[2]->tvec() \/ global_weight_decay.CurrentWeightDecay();\n}\nCNN_TRAINER_INST_DEV_IMPL(MomentumSGDTrainer)\n\n#ifndef __CUDACC__\nvoid MomentumSGDTrainer::update_params(real scale, real gscale, size_t idx) {\n auto & p = model->parameters_list()[idx];\n update_rule(scale, gscale, {&p->values, &p->g, &vp[idx].h});\n}\nvoid MomentumSGDTrainer::update_lookup_params(real scale, real gscale, size_t idx, size_t lidx) {\n auto & p = model->lookup_parameters_list()[idx];\n update_rule(scale, gscale, {&p->values[lidx], &p->grads[lidx], &vlp[idx].h[lidx]});\n}\nvoid MomentumSGDTrainer::alloc_impl() {\n vp = AllocateShadowParameters(*model);\n vlp = AllocateShadowLookupParameters(*model);\n}\n#endif\n\n\/\/ --- AdagradTrainer\n\n\/\/ Perform update of ts[0]=parameters, ts[1]=gradients, ts[2]=stddev\ntemplate \nvoid AdagradTrainer::update_rule_dev(const MyDevice & dev, real scale, real gscale, const std::vector & ts) {\n ts[1]->tvec().device(*dev.edevice) = ts[1]->tvec() * (scale * gscale);\n ts[2]->tvec().device(*dev.edevice) += ts[1]->tvec().square();\n ts[0]->tvec().device(*dev.edevice) += ts[1]->tvec() \/ (ts[2]->tvec() + epsilon).sqrt() * (-eta \/ global_weight_decay.CurrentWeightDecay());\n}\nCNN_TRAINER_INST_DEV_IMPL(AdagradTrainer)\n\n#ifndef __CUDACC__\nvoid AdagradTrainer::update_params(real scale, real gscale, size_t idx) {\n auto & p = model->parameters_list()[idx];\n update_rule(scale, gscale, {&p->values, &p->g, &vp[idx].h});\n}\nvoid AdagradTrainer::update_lookup_params(real scale, real gscale, size_t idx, size_t lidx) {\n auto & p = model->lookup_parameters_list()[idx];\n update_rule(scale, gscale, {&p->values[lidx], &p->grads[lidx], &vlp[idx].h[lidx]});\n}\nvoid AdagradTrainer::alloc_impl() {\n vp = AllocateShadowParameters(*model);\n vlp = AllocateShadowLookupParameters(*model);\n}\n#endif\n\n\/\/ --- AdadeltaTrainer\n\n\/\/ Perform update of ts[0]=parameters, ts[1]=gradients, ts[2]=hg, ts[3]=hd\ntemplate \nvoid AdadeltaTrainer::update_rule_dev(const MyDevice & dev, real scale, real gscale, const std::vector & ts) {\n ts[1]->tvec().device(*dev.edevice) = ts[1]->tvec() * (scale * gscale);\n ts[2]->tvec().device(*dev.edevice) = ts[2]->tvec() * rho + ts[1]->tvec().square() * (1.f - rho);\n ts[1]->tvec().device(*dev.edevice) = - ts[1]->tvec() * (ts[3]->tvec() + epsilon).sqrt() \/ (ts[2]->tvec() + epsilon).sqrt();\n ts[3]->tvec().device(*dev.edevice) = ts[3]->tvec() * rho + ts[1]->tvec().square() * (1.f - rho);\n ts[0]->tvec().device(*dev.edevice) += ts[1]->tvec() \/ global_weight_decay.CurrentWeightDecay();\n}\nCNN_TRAINER_INST_DEV_IMPL(AdadeltaTrainer)\n\n#ifndef __CUDACC__\nvoid AdadeltaTrainer::update_params(real scale, real gscale, size_t idx) {\n auto & p = model->parameters_list()[idx];\n update_rule(scale, gscale, {&p->values, &p->g, &hg[idx].h, &hd[idx].h});\n}\nvoid AdadeltaTrainer::update_lookup_params(real scale, real gscale, size_t idx, size_t lidx) {\n auto & p = model->lookup_parameters_list()[idx];\n update_rule(scale, gscale, {&p->values[lidx], &p->grads[lidx], &hlg[idx].h[lidx], &hld[idx].h[lidx]});\n}\nvoid AdadeltaTrainer::alloc_impl() {\n hg = AllocateShadowParameters(*model);\n hlg = AllocateShadowLookupParameters(*model);\n hd = AllocateShadowParameters(*model);\n hld = AllocateShadowLookupParameters(*model);\n}\n#endif\n\n\/\/ --- RmsPropTrainer\n\/\/ TODO: This is not finished yet, because it memorizes a scalar for each set of parameters, not each parameter itself.\n\/\/ We could implement this with one tensor for each scalar, but this is pretty wasteful\n\n\/\/ Perform update of ts[0]=parameters, ts[1]=gradients\ntemplate \nvoid RmsPropTrainer::update_rule_dev(const MyDevice & dev, real scale, real gscale, const std::vector & ts) {\n throw std::runtime_error(\"RMSProp optimization not implemented yet.\");\n \/\/ real& d2 = hg[pi++];\n \/\/ real g2 = p->g.vec().squaredNorm();\n \/\/ d2 = rho * d2 + (1.f - rho) * g2;\n \/\/ p->values.vec() -= ((eta * scale * gscale \/ sqrt(d2 + epsilon)) * p->g.vec()) \/ global_weight_decay.CurrentWeightDecay();\n}\nCNN_TRAINER_INST_DEV_IMPL(RmsPropTrainer)\n\n#ifndef __CUDACC__\nvoid RmsPropTrainer::update_params(real scale, real gscale, size_t idx) {\n throw std::runtime_error(\"RMSProp optimization not implemented yet.\");\n \/\/ auto & p = model->parameters_list()[idx];\n \/\/ update_rule(scale, gscale, {&p->values, &p->g, &hg[idx].h, &hd[idx].h});\n}\nvoid RmsPropTrainer::update_lookup_params(real scale, real gscale, size_t idx, size_t lidx) {\n throw std::runtime_error(\"RMSProp optimization not implemented yet.\");\n \/\/ auto & p = model->lookup_parameters_list()[idx];\n \/\/ update_rule(scale, gscale, {&p->values[lidx], &p->grads[lidx], &hlg[idx].h[lidx], &hld[idx].h[lidx]});\n}\nvoid RmsPropTrainer::alloc_impl() {\n throw std::runtime_error(\"RMSProp optimization not implemented yet.\");\n \/\/ hg.resize(model->parameters_list().size());\n \/\/ unsigned pi = 0;\n \/\/ hlg.resize(model->lookup_parameters_list().size());\n \/\/ for (auto p : model->lookup_parameters_list()) {\n \/\/ hlg[pi++].resize(p->size());\n \/\/ }\n}\n#endif\n\n\/\/ --- AdamTrainer\n\n\/\/ Perform update of ts[0]=parameters, ts[1]=gradients, ts[2]=mean, ts[3]=variance\ntemplate \nvoid AdamTrainer::update_rule_dev(const MyDevice & dev, real scale, real gscale, const std::vector & ts) {\n ts[1]->tvec().device(*dev.edevice) = ts[1]->tvec() * (scale * gscale);\n ts[2]->tvec().device(*dev.edevice) = ts[2]->tvec() * beta_1 + ts[1]->tvec() * (1.f - beta_1);\n ts[3]->tvec().device(*dev.edevice) = ts[3]->tvec() * beta_2 + ts[1]->tvec().square() * (1.f - beta_2);\n float s1 = 1 - pow(beta_1, updates+1);\n float s2 = 1 - pow(beta_2, updates+1);\n ts[0]->tvec().device(*dev.edevice) += ts[2]->tvec() \/ ((ts[3]->tvec() \/ s2).sqrt() + epsilon) * (-eta \/ s1 \/ global_weight_decay.CurrentWeightDecay());\n}\nCNN_TRAINER_INST_DEV_IMPL(AdamTrainer)\n\n#ifndef __CUDACC__\nvoid AdamTrainer::update_params(real scale, real gscale, size_t idx) {\n auto & p = model->parameters_list()[idx];\n update_rule(scale, gscale, {&p->values, &p->g, &m[idx].h, &v[idx].h});\n}\nvoid AdamTrainer::update_lookup_params(real scale, real gscale, size_t idx, size_t lidx) {\n auto & p = model->lookup_parameters_list()[idx];\n update_rule(scale, gscale, {&p->values[lidx], &p->grads[lidx], &lm[idx].h[lidx], &lv[idx].h[lidx]});\n}\nvoid AdamTrainer::alloc_impl() {\n m = AllocateShadowParameters(*model);\n lm = AllocateShadowLookupParameters(*model);\n v = AllocateShadowParameters(*model);\n lv = AllocateShadowLookupParameters(*model);\n}\n#endif\n\n} \/\/ namespace cnn\nTemporary fix of segfaults when training loaded models#include \"cnn\/training.h\"\n\n\/\/ #include \"cnn\/gpu-ops.h\"\n#include \"cnn\/param-nodes.h\"\n#include \"cnn\/weight-decay.h\"\n\n\/\/ Macros for defining parameter update functions\n#ifdef __CUDACC__\n#define CNN_TRAINER_INST_DEV_IMPL(MyTrainer) \\\n template void MyTrainer::update_rule_dev(const Device_GPU & dev, real scale, real gscale, const std::vector & values);\n#elif defined(HAVE_CUDA)\n\/\/ This is correct, but dying when models are read and written.\n\/\/ if(values[0]->device->type == DeviceType::CPU) { update_rule_dev(*(Device_CPU*)values[0]->device,scale,gscale,values); } \n\/\/ else if(values[0]->device->type == DeviceType::GPU) { update_rule_dev(*(Device_GPU*)values[0]->device,scale,gscale,values); } \n\/\/ else { abort(); }\n#define CNN_TRAINER_INST_DEV_IMPL(MyTrainer) \\\n extern template void MyTrainer::update_rule_dev(const Device_GPU & dev, real scale, real gscale, const std::vector & values); \\\n template void MyTrainer::update_rule_dev(const Device_CPU & dev, real scale, real gscale, const std::vector & values); \\\n void MyTrainer::update_rule(real scale, real gscale, const std::vector & values) { \\\n if(default_device->type == DeviceType::CPU) { update_rule_dev(*(Device_CPU*)default_device,scale,gscale,values); } \\\n else if(default_device->type == DeviceType::GPU) { update_rule_dev(*(Device_GPU*)default_device,scale,gscale,values); } \\\n else { abort(); } \\\n }\n#else\n#define CNN_TRAINER_INST_DEV_IMPL(MyTrainer) \\\n template void MyTrainer::update_rule_dev(const Device_CPU & dev, real scale, real gscale, const std::vector & values); \\\n void MyTrainer::update_rule(real scale, real gscale, const std::vector & values) { \\\n if(default_device->type == DeviceType::CPU) { update_rule_dev(*(Device_CPU*)default_device,scale,gscale,values); } \\\n else { abort(); } \\\n }\n#endif\n\nnamespace cnn {\n\nusing namespace std;\n\ntemplate \nbool is_valid(const Eigen::MatrixBase& x) {\n return ((x - x).array() == (x - x).array()).all();\n}\n\n\/\/ --- The actual update code for each operation, implemented on various devices\n\n\/\/ Trainer base class is run on CPUs\n#ifndef __CUDACC__\n\nTrainer::~Trainer() {}\n\nvoid Trainer::rescale_and_reset_weight_decay() {\n const float weight_decay = global_weight_decay.CurrentWeightDecay();\n for (auto p : model->parameters_list())\n p->scale_parameters(weight_decay);\n global_weight_decay.ResetWeightDecay();\n}\n\nfloat Trainer::clip_gradients() {\n float gscale = 1;\n if (clipping_enabled) {\n float gg = model->gradient_l2_norm();\n if (isnan(gg) || isinf(gg)) {\n cerr << \"Magnitude of gradient is bad: \" << gg << endl;\n abort();\n }\n if (gg > clip_threshold) {\n ++clips;\n gscale = clip_threshold \/ gg;\n }\n }\n return gscale;\n}\n\n\/\/ this calls the rule-specific\nvoid Trainer::update(real scale) {\n \/\/ Allocate if necessary\n if(!aux_allocated) {\n alloc_impl();\n aux_allocated = true;\n }\n\n \/\/ Perform gradient clipping and cycle through parameters\n const float gscale = clip_gradients();\n const auto & params = model->parameters_list();\n for(size_t i = 0; i < params.size(); ++i) {\n update_params(scale, gscale, i);\n params[i]->clear();\n }\n const auto & lookup_params = model->lookup_parameters_list();\n for(size_t i = 0; i < lookup_params.size(); ++i) {\n for (auto j : lookup_params[i]->non_zero_grads)\n update_lookup_params(scale, gscale, i, j);\n lookup_params[i]->clear();\n }\n ++updates;\n\n global_weight_decay.UpdateWeightDecay(); \/\/ update global weight scale\n if (global_weight_decay.ParametersNeedRescaled())\n rescale_and_reset_weight_decay(); \/\/ if wdscale is getting to small multiply all weights by wdscale, and set wdscale to 1\n}\n\n#endif\n\n\/\/ --- SimpleSGDTrainer\n\n\/\/ Perform update of ts[0]=parameters, ts[1]=gradients\ntemplate \nvoid SimpleSGDTrainer::update_rule_dev(const MyDevice & dev, real scale, real gscale, const std::vector & ts) {\n ts[0]->tvec().device(*dev.edevice) -= ts[1]->tvec() * (eta * scale * gscale \/ global_weight_decay.CurrentWeightDecay());\n}\nCNN_TRAINER_INST_DEV_IMPL(SimpleSGDTrainer)\n\n#ifndef __CUDACC__\nvoid SimpleSGDTrainer::update_params(real scale, real gscale, size_t idx) {\n auto & p = model->parameters_list()[idx];\n update_rule(scale, gscale, {&p->values, &p->g});\n}\nvoid SimpleSGDTrainer::update_lookup_params(real scale, real gscale, size_t idx, size_t lidx) {\n auto & p = model->lookup_parameters_list()[idx];\n update_rule(scale, gscale, {&p->values[lidx], &p->grads[lidx]});\n}\n#endif\n\n\/\/ --- MomentumSGDTrainer\n\n\/\/ Perform update of ts[0]=parameters, ts[1]=gradients, ts[2]=momentum\ntemplate \nvoid MomentumSGDTrainer::update_rule_dev(const MyDevice & dev, real scale, real gscale, const std::vector & ts) {\n ts[2]->tvec().device(*dev.edevice) = ts[2]->tvec() * momentum - ts[1]->tvec() * (eta * scale * gscale);\n ts[0]->tvec().device(*dev.edevice) += ts[2]->tvec() \/ global_weight_decay.CurrentWeightDecay();\n}\nCNN_TRAINER_INST_DEV_IMPL(MomentumSGDTrainer)\n\n#ifndef __CUDACC__\nvoid MomentumSGDTrainer::update_params(real scale, real gscale, size_t idx) {\n auto & p = model->parameters_list()[idx];\n update_rule(scale, gscale, {&p->values, &p->g, &vp[idx].h});\n}\nvoid MomentumSGDTrainer::update_lookup_params(real scale, real gscale, size_t idx, size_t lidx) {\n auto & p = model->lookup_parameters_list()[idx];\n update_rule(scale, gscale, {&p->values[lidx], &p->grads[lidx], &vlp[idx].h[lidx]});\n}\nvoid MomentumSGDTrainer::alloc_impl() {\n vp = AllocateShadowParameters(*model);\n vlp = AllocateShadowLookupParameters(*model);\n}\n#endif\n\n\/\/ --- AdagradTrainer\n\n\/\/ Perform update of ts[0]=parameters, ts[1]=gradients, ts[2]=stddev\ntemplate \nvoid AdagradTrainer::update_rule_dev(const MyDevice & dev, real scale, real gscale, const std::vector & ts) {\n ts[1]->tvec().device(*dev.edevice) = ts[1]->tvec() * (scale * gscale);\n ts[2]->tvec().device(*dev.edevice) += ts[1]->tvec().square();\n ts[0]->tvec().device(*dev.edevice) += ts[1]->tvec() \/ (ts[2]->tvec() + epsilon).sqrt() * (-eta \/ global_weight_decay.CurrentWeightDecay());\n}\nCNN_TRAINER_INST_DEV_IMPL(AdagradTrainer)\n\n#ifndef __CUDACC__\nvoid AdagradTrainer::update_params(real scale, real gscale, size_t idx) {\n auto & p = model->parameters_list()[idx];\n update_rule(scale, gscale, {&p->values, &p->g, &vp[idx].h});\n}\nvoid AdagradTrainer::update_lookup_params(real scale, real gscale, size_t idx, size_t lidx) {\n auto & p = model->lookup_parameters_list()[idx];\n update_rule(scale, gscale, {&p->values[lidx], &p->grads[lidx], &vlp[idx].h[lidx]});\n}\nvoid AdagradTrainer::alloc_impl() {\n vp = AllocateShadowParameters(*model);\n vlp = AllocateShadowLookupParameters(*model);\n}\n#endif\n\n\/\/ --- AdadeltaTrainer\n\n\/\/ Perform update of ts[0]=parameters, ts[1]=gradients, ts[2]=hg, ts[3]=hd\ntemplate \nvoid AdadeltaTrainer::update_rule_dev(const MyDevice & dev, real scale, real gscale, const std::vector & ts) {\n ts[1]->tvec().device(*dev.edevice) = ts[1]->tvec() * (scale * gscale);\n ts[2]->tvec().device(*dev.edevice) = ts[2]->tvec() * rho + ts[1]->tvec().square() * (1.f - rho);\n ts[1]->tvec().device(*dev.edevice) = - ts[1]->tvec() * (ts[3]->tvec() + epsilon).sqrt() \/ (ts[2]->tvec() + epsilon).sqrt();\n ts[3]->tvec().device(*dev.edevice) = ts[3]->tvec() * rho + ts[1]->tvec().square() * (1.f - rho);\n ts[0]->tvec().device(*dev.edevice) += ts[1]->tvec() \/ global_weight_decay.CurrentWeightDecay();\n}\nCNN_TRAINER_INST_DEV_IMPL(AdadeltaTrainer)\n\n#ifndef __CUDACC__\nvoid AdadeltaTrainer::update_params(real scale, real gscale, size_t idx) {\n auto & p = model->parameters_list()[idx];\n update_rule(scale, gscale, {&p->values, &p->g, &hg[idx].h, &hd[idx].h});\n}\nvoid AdadeltaTrainer::update_lookup_params(real scale, real gscale, size_t idx, size_t lidx) {\n auto & p = model->lookup_parameters_list()[idx];\n update_rule(scale, gscale, {&p->values[lidx], &p->grads[lidx], &hlg[idx].h[lidx], &hld[idx].h[lidx]});\n}\nvoid AdadeltaTrainer::alloc_impl() {\n hg = AllocateShadowParameters(*model);\n hlg = AllocateShadowLookupParameters(*model);\n hd = AllocateShadowParameters(*model);\n hld = AllocateShadowLookupParameters(*model);\n}\n#endif\n\n\/\/ --- RmsPropTrainer\n\/\/ TODO: This is not finished yet, because it memorizes a scalar for each set of parameters, not each parameter itself.\n\/\/ We could implement this with one tensor for each scalar, but this is pretty wasteful\n\n\/\/ Perform update of ts[0]=parameters, ts[1]=gradients\ntemplate \nvoid RmsPropTrainer::update_rule_dev(const MyDevice & dev, real scale, real gscale, const std::vector & ts) {\n throw std::runtime_error(\"RMSProp optimization not implemented yet.\");\n \/\/ real& d2 = hg[pi++];\n \/\/ real g2 = p->g.vec().squaredNorm();\n \/\/ d2 = rho * d2 + (1.f - rho) * g2;\n \/\/ p->values.vec() -= ((eta * scale * gscale \/ sqrt(d2 + epsilon)) * p->g.vec()) \/ global_weight_decay.CurrentWeightDecay();\n}\nCNN_TRAINER_INST_DEV_IMPL(RmsPropTrainer)\n\n#ifndef __CUDACC__\nvoid RmsPropTrainer::update_params(real scale, real gscale, size_t idx) {\n throw std::runtime_error(\"RMSProp optimization not implemented yet.\");\n \/\/ auto & p = model->parameters_list()[idx];\n \/\/ update_rule(scale, gscale, {&p->values, &p->g, &hg[idx].h, &hd[idx].h});\n}\nvoid RmsPropTrainer::update_lookup_params(real scale, real gscale, size_t idx, size_t lidx) {\n throw std::runtime_error(\"RMSProp optimization not implemented yet.\");\n \/\/ auto & p = model->lookup_parameters_list()[idx];\n \/\/ update_rule(scale, gscale, {&p->values[lidx], &p->grads[lidx], &hlg[idx].h[lidx], &hld[idx].h[lidx]});\n}\nvoid RmsPropTrainer::alloc_impl() {\n throw std::runtime_error(\"RMSProp optimization not implemented yet.\");\n \/\/ hg.resize(model->parameters_list().size());\n \/\/ unsigned pi = 0;\n \/\/ hlg.resize(model->lookup_parameters_list().size());\n \/\/ for (auto p : model->lookup_parameters_list()) {\n \/\/ hlg[pi++].resize(p->size());\n \/\/ }\n}\n#endif\n\n\/\/ --- AdamTrainer\n\n\/\/ Perform update of ts[0]=parameters, ts[1]=gradients, ts[2]=mean, ts[3]=variance\ntemplate \nvoid AdamTrainer::update_rule_dev(const MyDevice & dev, real scale, real gscale, const std::vector & ts) {\n ts[1]->tvec().device(*dev.edevice) = ts[1]->tvec() * (scale * gscale);\n ts[2]->tvec().device(*dev.edevice) = ts[2]->tvec() * beta_1 + ts[1]->tvec() * (1.f - beta_1);\n ts[3]->tvec().device(*dev.edevice) = ts[3]->tvec() * beta_2 + ts[1]->tvec().square() * (1.f - beta_2);\n float s1 = 1 - pow(beta_1, updates+1);\n float s2 = 1 - pow(beta_2, updates+1);\n ts[0]->tvec().device(*dev.edevice) += ts[2]->tvec() \/ ((ts[3]->tvec() \/ s2).sqrt() + epsilon) * (-eta \/ s1 \/ global_weight_decay.CurrentWeightDecay());\n}\nCNN_TRAINER_INST_DEV_IMPL(AdamTrainer)\n\n#ifndef __CUDACC__\nvoid AdamTrainer::update_params(real scale, real gscale, size_t idx) {\n auto & p = model->parameters_list()[idx];\n update_rule(scale, gscale, {&p->values, &p->g, &m[idx].h, &v[idx].h});\n}\nvoid AdamTrainer::update_lookup_params(real scale, real gscale, size_t idx, size_t lidx) {\n auto & p = model->lookup_parameters_list()[idx];\n update_rule(scale, gscale, {&p->values[lidx], &p->grads[lidx], &lm[idx].h[lidx], &lv[idx].h[lidx]});\n}\nvoid AdamTrainer::alloc_impl() {\n m = AllocateShadowParameters(*model);\n lm = AllocateShadowLookupParameters(*model);\n v = AllocateShadowParameters(*model);\n lv = AllocateShadowLookupParameters(*model);\n}\n#endif\n\n} \/\/ namespace cnn\n<|endoftext|>"} {"text":"#include \"ecs.hpp\"\n#include \n\nnamespace entity\n{\n\n\tBaseComponent::Id BaseComponent::id_counter = 0;\n\n\t\/\/ Entity\n\n\tvoid Entity::kill()\n\t{\n\t\tentities->kill(*this);\n\t}\n\n\tbool Entity::is_alive() const\n\t{\n\t\treturn entities->is_entity_alive(*this);\n\t}\n\n\tvoid Entity::tag(std::string tag_name)\n\t{\n\t\tentities->tag_entity(*this, tag_name);\n\t}\n\n\tvoid Entity::group(std::string group_name)\n\t{\n\t\tentities->group_entity(*this, group_name);\n\t}\n\n\tstd::string Entity::to_string() const\n\t{\n\t\tstd::string s = \"entity_\" + std::to_string(get_index()) + \"_v\" + std::to_string(get_version());\n\t\treturn s;\n\t}\n\n\t\/\/ System\n\n\tvoid System::add_entity(Entity e)\n\t{\n\t\tentities.push_back(e);\n\t}\n\n\tvoid System::remove_entity(Entity e)\n\t{\n\t\tentities.erase(std::remove_if(entities.begin(), entities.end(),\n\t\t\t[&e](Entity other) { return e == other; }\n\t\t), entities.end());\n\t}\n\n\t\/\/ Entities\n\n\tEntities::Entities()\n\t{\n\t}\n\n\tvoid Entities::update()\n\t{\n\t\tfor (auto e : created_entities) {\n\t\t\tupdate_systems(e);\n\t\t}\n\t\tcreated_entities.clear();\n\n\t\tfor (auto e : killed_entities) {\n\t\t\tdestroy_entity(e);\n\t\t}\n\t\tkilled_entities.clear();\n\t}\n\n\tvoid Entities::update_systems(Entity e)\n\t{\n\t\tconst auto &entity_component_mask = get_component_mask(e);\n\n\t\tfor (auto &it : systems) {\n\t\t\tauto system = it.second;\n\t\t\tconst auto &system_component_mask = system->get_component_mask();\n\t\t\tauto interest = (entity_component_mask & system_component_mask) == system_component_mask;\n\n\t\t\tif (interest) {\n\t\t\t\tsystem->add_entity(e);\n\t\t\t}\n\t\t}\n\t}\n\n\tEntity Entities::create()\n\t{\n\t\tauto e = create_entity();\n\t\tcreated_entities.push_back(e);\n\t\treturn e;\n\t}\n\n\tvoid Entities::kill(Entity e)\n\t{\n\t\tkilled_entities.push_back(e);\n\t}\n\n\tEntity Entities::create_entity()\n\t{\n\t\tEntity::Id index;\n\n\t\tif (free_ids.size() > MINIMUM_FREE_IDS) {\n\t\t\tindex = free_ids.front();\n\t\t\tfree_ids.pop_front();\n\t\t}\n\t\telse {\n\t\t\tversions.push_back(0);\n\t\t\tindex = (unsigned int)versions.size() - 1;\n\t\t\tassert(index < (1 << Entity::INDEX_BITS));\n\n\t\t\tif (index >= component_masks.size()) {\n\t\t\t\t\/\/ TODO: grow by doubling?\n\t\t\t\tcomponent_masks.resize(index + 1);\n\t\t\t}\n\t\t}\n\n\t\tassert(index < versions.size());\n\t\tEntity e(index, versions[index]);\n\t\te.entities = this;\n\n\t\treturn e;\n\t}\n\n\tvoid Entities::destroy_entity(Entity e)\n\t{\n\t\tconst auto index = e.get_index();\n\t\tassert(index < versions.size()); \/\/ sanity check\n\t\tassert(index < component_masks.size());\n\t\t++versions[index]; \/\/ increase the version for that id\n\t\tfree_ids.push_back(index); \/\/ make the id available for reuse\n\t\tcomponent_masks[index].reset(); \/\/ reset the component mask for that id\n\t}\n\n\tbool Entities::is_entity_alive(Entity e) const\n\t{\n\t\tconst auto index = e.get_index();\n\t\tassert(index < versions.size());\n\t\treturn versions[index] == e.get_version();\n\t}\n\n\tconst ComponentMask& Entities::get_component_mask(Entity e) const\n\t{\n\t\tconst auto index = e.get_index();\n\t\tassert(index < component_masks.size());\n\t\treturn component_masks[index];\n\t}\n\n\tvoid Entities::tag_entity(Entity e, std::string tag_name)\n\t{\n\t\ttagged_entities.emplace(tag_name, e);\n\t}\n\n\tbool Entities::has_tagged_entity(std::string tag_name) const\n\t{\n\t\treturn tagged_entities.find(tag_name) != tagged_entities.end();\n\t}\n\n\tEntity Entities::get_entity_by_tag(std::string tag_name)\n\t{\n\t\tassert(has_tagged_entity(tag_name));\n\t\treturn tagged_entities[tag_name];\n\t}\n\n\tvoid Entities::group_entity(Entity e, std::string group_name)\n\t{\n\t\tentity_groups.emplace(group_name, std::set());\n\t\tentity_groups[group_name].emplace(e);\n\t}\n\n\tbool Entities::has_entity_group(std::string group_name) const\n\t{\n\t\treturn entity_groups.find(group_name) != entity_groups.end();\n\t}\n\n\tstd::vector Entities::get_entity_group(std::string group_name)\n\t{\n\t\tassert(has_entity_group(group_name));\n\t\tauto &s = entity_groups[group_name];\n\t\treturn std::vector(s.begin(), s.end());\n\t}\n\n}\nAllow is_alive() on invalid Entity.#include \"ecs.hpp\"\n#include \n\nnamespace entity\n{\n\n\tBaseComponent::Id BaseComponent::id_counter = 0;\n\n\t\/\/ Entity\n\n\tvoid Entity::kill()\n\t{\n\t\tentities->kill(*this);\n\t}\n\n\tbool Entity::is_alive() const\n\t{\n\t\treturn entities && entities->is_entity_alive(*this);\n\t}\n\n\tvoid Entity::tag(std::string tag_name)\n\t{\n\t\tentities->tag_entity(*this, tag_name);\n\t}\n\n\tvoid Entity::group(std::string group_name)\n\t{\n\t\tentities->group_entity(*this, group_name);\n\t}\n\n\tstd::string Entity::to_string() const\n\t{\n\t\tstd::string s = \"entity_\" + std::to_string(get_index()) + \"_v\" + std::to_string(get_version());\n\t\treturn s;\n\t}\n\n\t\/\/ System\n\n\tvoid System::add_entity(Entity e)\n\t{\n\t\tentities.push_back(e);\n\t}\n\n\tvoid System::remove_entity(Entity e)\n\t{\n\t\tentities.erase(std::remove_if(entities.begin(), entities.end(),\n\t\t\t[&e](Entity other) { return e == other; }\n\t\t), entities.end());\n\t}\n\n\t\/\/ Entities\n\n\tEntities::Entities()\n\t{\n\t}\n\n\tvoid Entities::update()\n\t{\n\t\tfor (auto e : created_entities) {\n\t\t\tupdate_systems(e);\n\t\t}\n\t\tcreated_entities.clear();\n\n\t\tfor (auto e : killed_entities) {\n\t\t\tdestroy_entity(e);\n\t\t}\n\t\tkilled_entities.clear();\n\t}\n\n\tvoid Entities::update_systems(Entity e)\n\t{\n\t\tconst auto &entity_component_mask = get_component_mask(e);\n\n\t\tfor (auto &it : systems) {\n\t\t\tauto system = it.second;\n\t\t\tconst auto &system_component_mask = system->get_component_mask();\n\t\t\tauto interest = (entity_component_mask & system_component_mask) == system_component_mask;\n\n\t\t\tif (interest) {\n\t\t\t\tsystem->add_entity(e);\n\t\t\t}\n\t\t}\n\t}\n\n\tEntity Entities::create()\n\t{\n\t\tauto e = create_entity();\n\t\tcreated_entities.push_back(e);\n\t\treturn e;\n\t}\n\n\tvoid Entities::kill(Entity e)\n\t{\n\t\tkilled_entities.push_back(e);\n\t}\n\n\tEntity Entities::create_entity()\n\t{\n\t\tEntity::Id index;\n\n\t\tif (free_ids.size() > MINIMUM_FREE_IDS) {\n\t\t\tindex = free_ids.front();\n\t\t\tfree_ids.pop_front();\n\t\t}\n\t\telse {\n\t\t\tversions.push_back(0);\n\t\t\tindex = (unsigned int)versions.size() - 1;\n\t\t\tassert(index < (1 << Entity::INDEX_BITS));\n\n\t\t\tif (index >= component_masks.size()) {\n\t\t\t\t\/\/ TODO: grow by doubling?\n\t\t\t\tcomponent_masks.resize(index + 1);\n\t\t\t}\n\t\t}\n\n\t\tassert(index < versions.size());\n\t\tEntity e(index, versions[index]);\n\t\te.entities = this;\n\n\t\treturn e;\n\t}\n\n\tvoid Entities::destroy_entity(Entity e)\n\t{\n\t\tconst auto index = e.get_index();\n\t\tassert(index < versions.size()); \/\/ sanity check\n\t\tassert(index < component_masks.size());\n\t\t++versions[index]; \/\/ increase the version for that id\n\t\tfree_ids.push_back(index); \/\/ make the id available for reuse\n\t\tcomponent_masks[index].reset(); \/\/ reset the component mask for that id\n\t}\n\n\tbool Entities::is_entity_alive(Entity e) const\n\t{\n\t\tconst auto index = e.get_index();\n\t\tassert(index < versions.size());\n\t\treturn versions[index] == e.get_version();\n\t}\n\n\tconst ComponentMask& Entities::get_component_mask(Entity e) const\n\t{\n\t\tconst auto index = e.get_index();\n\t\tassert(index < component_masks.size());\n\t\treturn component_masks[index];\n\t}\n\n\tvoid Entities::tag_entity(Entity e, std::string tag_name)\n\t{\n\t\ttagged_entities.emplace(tag_name, e);\n\t}\n\n\tbool Entities::has_tagged_entity(std::string tag_name) const\n\t{\n\t\treturn tagged_entities.find(tag_name) != tagged_entities.end();\n\t}\n\n\tEntity Entities::get_entity_by_tag(std::string tag_name)\n\t{\n\t\tassert(has_tagged_entity(tag_name));\n\t\treturn tagged_entities[tag_name];\n\t}\n\n\tvoid Entities::group_entity(Entity e, std::string group_name)\n\t{\n\t\tentity_groups.emplace(group_name, std::set());\n\t\tentity_groups[group_name].emplace(e);\n\t}\n\n\tbool Entities::has_entity_group(std::string group_name) const\n\t{\n\t\treturn entity_groups.find(group_name) != entity_groups.end();\n\t}\n\n\tstd::vector Entities::get_entity_group(std::string group_name)\n\t{\n\t\tassert(has_entity_group(group_name));\n\t\tauto &s = entity_groups[group_name];\n\t\treturn std::vector(s.begin(), s.end());\n\t}\n\n}\n<|endoftext|>"} {"text":"#include \"model.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"util.h\"\n\nusing std::transform;\nusing std::ifstream;\nusing std::istringstream;\nusing std::vector;\nusing std::cerr;\nusing std::unordered_map;\nusing std::make_pair;\nusing std::pair;\n\nnamespace RawModelLoad\n{\n struct tex_coord\n {\n float u, v;\n };\n\n struct tri_ref\n {\n int v[3];\n };\n\n struct vertex_ref\n {\n int p, t, n;\n bool operator==(const vertex_ref& b) const\n {\n return p == b.p && t == b.t && n == b.n;\n }\n };\n\n}\n\nRawModel::RawModel() : verts(), tris(), has_tex(false)\n{\n}\n\nnamespace std\n{\n template <>\n struct hash\n {\n public:\n size_t operator ()(const RawModelLoad::vertex_ref& vr) const\n {\n size_t seed = 0;\n hash_combine(seed, vr.n);\n hash_combine(seed, vr.p);\n hash_combine(seed, vr.t);\n return seed;\n }\n };\n}\nusing namespace RawModelLoad;\n\nvertex_ref parse_obj_vertex_ref(string token);\n\nRawModelLoadStatus RawModel::load_obj_model(string filename)\n{\n RawModelLoadStatus mls;\n mls.success = false;\n\n ifstream fin(filename);\n if (!fin)\n {\n cerr << \"Could not load model.\\n\";\n return mls;\n }\n\n vector vertex_list;\n vector normal_list;\n vector tc_list;\n vector ref_list;\n vector tri_list;\n\n#define BUF_SIZE 1024\n char linebuf[BUF_SIZE];\n\n int line_count = 0;\n while (!fin.eof())\n {\n ++line_count;\n fin.getline(linebuf, BUF_SIZE);\n if (fin.fail())\n {\n if (fin.eof())\n\tbreak;\n\n cerr << \"Line \" << line_count << \" in obj too long.\";\n return mls;\n }\n string str(linebuf);\n\n if (str.empty() || str.find('#') != string::npos)\n continue;\n\n istringstream ss(str);\n\n string line_type;\n ss >> line_type;\n if (line_type == \"v\")\n {\n Vec3 v;\n ss >> v;\n vertex_list.push_back(v);\n }\n else if (line_type == \"vn\")\n {\n Vec3 v;\n ss >> v;\n normal_list.push_back(v);\n }\n else if (line_type == \"vt\")\n {\n tex_coord tc;\n ss >> tc.u >> tc.v;\n tc_list.push_back(tc);\n }\n else if (line_type == \"f\")\n {\n string part;\n int sidx = ref_list.size();\n int num_verts = 0;\n while (true)\n {\n\tss >> part;\n if (!ss)\n break;\n\tref_list.push_back(parse_obj_vertex_ref(part));\n\t++num_verts;\n }\n for (int i = 0; i < num_verts - 2; ++i)\n {\n\ttri_ref tri{sidx, sidx+i+1, sidx+i+2};\n\ttri_list.emplace_back(tri);\n }\n }\n else\n {\n cerr << \"unknown line type: \" << line_type << \"\\n\";\n return mls;\n }\n }\n\n mls = load_from_parts(vertex_list, normal_list,\n\t\t\ttc_list, ref_list,\n\t\t\ttri_list);\n\n if (mls.success && !mls.has_normals)\n {\n compute_normals();\n mls.has_normals = true;\n }\n has_tex = mls.has_tex;\n return mls;\n}\n\nRawModelLoadStatus RawModel::load_stl_model(string filename)\n{\n RawModelLoadStatus mls;\n mls.success = false;\n\n ifstream fin(filename);\n if (!fin)\n {\n cerr << \"Could not open model file (\" << filename << \").\\n\";\n return mls;\n }\n\n vector vertex_list;\n vector normal_list;\n vector tc_list;\n vector ref_list;\n vector tri_list;\n\n#define BUF_SIZE 1024\n char linebuf[BUF_SIZE];\n\n int line_count = 0;\n while (!fin.eof())\n {\n ++line_count;\n fin.getline(linebuf, BUF_SIZE);\n if (fin.fail())\n {\n if (fin.eof())\n\tbreak;\n\n cerr << \"Line \" << line_count << \" in obj too long.\";\n return mls;\n }\n string str(linebuf);\n\n if (str.empty())\n continue;\n\n istringstream ss(str);\n\n string line_type;\n ss >> line_type;\n if (line_type == \"vertex\")\n {\n Vec3 v;\n ss >> v;\n vertex_list.push_back(v);\n ref_list.emplace_back(vertex_ref{(int)ref_list.size(), -1, -1});\n }\n else if (line_type == \"endloop\")\n {\n int num_tris = tri_list.size();\n tri_ref tri{num_tris*3, num_tris*3+1, num_tris*3+2};\n tri_list.emplace_back(tri);\n }\n else if (line_type == \"facet\" || line_type == \"outer\" || \n line_type == \"endfacet\" || line_type == \"solid\")\n {\n }\n else if (line_type == \"endsolid\")\n break;\n else\n {\n cerr << \"unknown line type: \" << line_type << \"\\n\";\n return mls;\n }\n }\n\n mls = load_from_parts(vertex_list, normal_list,\n\t\t\ttc_list, ref_list,\n\t\t\ttri_list);\n\n if (mls.success && !mls.has_normals)\n {\n compute_normals();\n mls.has_normals = true;\n }\n has_tex = mls.has_tex;\n return mls;\n}\n\nRawModelLoadStatus RawModel::load_from_parts(const vector& vertex_list, const vector& normal_list,\n\t\t\t\t\t const vector& tc_list, const vector& vertex_ref_list,\n\t\t\t\t\t const vector& tri_list)\n{\n clear();\n\n unordered_map ref_map;\n\n RawModelLoadStatus mls;\n mls.success = true;\n mls.has_normals = normal_list.size() > 0;\n mls.has_tex = tc_list.size() > 0;\n\n for (const auto& tr: tri_list)\n {\n Triangle tri;\n for (int j = 0; j < 3; ++j)\n {\n int vidx = tr.v[j];\n auto vr = vertex_ref_list[vidx];\n\n \/\/ Add 'new' vertices.\n if (ref_map.find(vr) == ref_map.end())\n {\n\tref_map.insert(make_pair(vr, ref_map.size()));\n\tVertex v;\n\n\tv.position = vertex_list[vr.p];\n\tif (vr.t >= 0)\n\t{\n\t v.u = tc_list[vr.t].u;\n\t v.v = tc_list[vr.t].v;\n\t}\n\tif (vr.n >= 0)\n\t{\n\t v.normal = normal_list[vr.n];\n\t}\n\tverts.push_back(v);\n }\n\n tri.v[j] = ref_map[vr];\n }\n tris.push_back(tri);\n }\n\n return mls;\n}\n\nvoid RawModel::clear()\n{\n verts.clear();\n tris.clear();\n has_tex = false;\n}\n\nbounds::AABB RawModel::bounding_box() const\n{\n Vec3 min{std::numeric_limits::max()};\n Vec3 max{std::numeric_limits::min()};\n min = accumulate(verts.begin(), verts.end(), min,\n [] (const Vec3& v, const Vertex& w) { return ::min(v, w.position); });\n max = accumulate(verts.begin(), verts.end(), max,\n [] (const Vec3& v, const Vertex& w) { return ::max(v, w.position); });\n\n return bounds::AABB{min, max};\n}\n\nbounds::Sphere RawModel::bounding_sphere() const\n{\n Vec3 p1 = verts[0].position;\n\n Vec3 p2;\n scalar max_dist2 = 0;\n for (const auto& v: verts)\n {\n scalar dist2 = (v.position - p1).norm2();\n if (max_dist2 < dist2)\n {\n max_dist2 = dist2;\n p2 = v.position;\n }\n }\n\n Vec3 p3;\n max_dist2 = 0;\n for (const auto& v: verts)\n {\n scalar dist2 = (v.position - p2).norm2();\n if (max_dist2 < dist2)\n {\n max_dist2 = dist2;\n p3 = v.position;\n }\n }\n \n \/\/ Take the midpoint as the center, and find the best radius\n Vec3 mid = (p2 + p3) * 0.5;\n\n scalar radius = sqrt(accumulate(verts.begin(), verts.end(), (mid - p2).norm2(),\n \/* This could be generic\/polymorphic, but only\n in c++1y. *\/\n [&mid](scalar r2, const Vertex& v) { \n return max(r2, (mid - v.position).norm2()); \n }));\n\n return bounds::Sphere(mid, radius);\n}\n\nvoid RawModel::compute_normals()\n{\n vector normal_sum( verts.size() );\n vector normal_weight( verts.size() );\n\n for (const auto& tri: tris)\n {\n \/\/ compute the normal, and compute the angle\n auto p1 = verts[tri.v[1]].position - verts[tri.v[0]].position;\n auto p2 = verts[tri.v[1]].position - verts[tri.v[0]].position;\n Vec3 face_normal = p1.cross(p2).normal();\n for (int i: tri.v)\n normal_sum[i] += face_normal;\n }\n for (size_t i = 0; i < verts.size(); ++i)\n verts[i].normal = normal_sum[i].normal();\n}\n\nvoid RawModel::rescale(const bounds::AABB& new_bb)\n{\n auto bb = bounding_box();\n auto w = bb.max - bb.min;\n for (auto& f: w.v)\n if (f < EPSILON)\n f = 1;\n\n auto scale = (new_bb.max - new_bb.min).elem_div(w);\n \n for (auto& v: verts)\n {\n v.position = (v.position - bb.min).elem_mult(scale) + new_bb.min;\n v.normal = v.normal.elem_div(scale).normal();\n }\n}\n\nvoid RawModel::rescale(const bounds::Sphere& new_bs)\n{\n const auto bs = bounding_sphere();\n \n auto scale = new_bs.radius \/ bs.radius;\n for (auto& v: verts)\n {\n v.position = (v.position - bs.center) * scale + new_bs.center;\n }\n}\n\n\/*\n * A face in a .obj file is 'f' followed by a list of vertex references.\n *\n *\/\nvertex_ref parse_obj_vertex_ref(string token) {\n\n vertex_ref ref{-1, -1, -1};\n auto pos = token.find('\/');\n if (pos == string::npos)\n {\n ref.p = std::stoi(token) - 1;\n return ref;\n }\n ref.p = std::stoi(token.substr(pos)) - 1;\n\n auto tpos = token.find('\/', pos+1);\n if (tpos == string::npos)\n {\n ref.t = std::stoi(token.substr(pos+1, tpos-pos-1)) - 1;\n return ref;\n }\n\n if (tpos > pos + 1)\n {\n ref.t = std::stoi(token.substr(pos+1, tpos-pos-1)) - 1;\n }\n ref.n = std::stoi(token.substr(tpos+1)) - 1;\n return ref;\n}\nuses polymorhpic lambda in model.cpp#include \"model.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"util.h\"\n\nusing std::transform;\nusing std::ifstream;\nusing std::istringstream;\nusing std::vector;\nusing std::cerr;\nusing std::unordered_map;\nusing std::make_pair;\nusing std::pair;\n\nnamespace RawModelLoad\n{\n struct tex_coord\n {\n float u, v;\n };\n\n struct tri_ref\n {\n int v[3];\n };\n\n struct vertex_ref\n {\n int p, t, n;\n bool operator==(const vertex_ref& b) const\n {\n return p == b.p && t == b.t && n == b.n;\n }\n };\n\n}\n\nRawModel::RawModel() : verts(), tris(), has_tex(false)\n{\n}\n\nnamespace std\n{\n template <>\n struct hash\n {\n public:\n size_t operator ()(const RawModelLoad::vertex_ref& vr) const\n {\n size_t seed = 0;\n hash_combine(seed, vr.n);\n hash_combine(seed, vr.p);\n hash_combine(seed, vr.t);\n return seed;\n }\n };\n}\nusing namespace RawModelLoad;\n\nvertex_ref parse_obj_vertex_ref(string token);\n\nRawModelLoadStatus RawModel::load_obj_model(string filename)\n{\n RawModelLoadStatus mls;\n mls.success = false;\n\n ifstream fin(filename);\n if (!fin)\n {\n cerr << \"Could not load model.\\n\";\n return mls;\n }\n\n vector vertex_list;\n vector normal_list;\n vector tc_list;\n vector ref_list;\n vector tri_list;\n\n#define BUF_SIZE 1024\n char linebuf[BUF_SIZE];\n\n int line_count = 0;\n while (!fin.eof())\n {\n ++line_count;\n fin.getline(linebuf, BUF_SIZE);\n if (fin.fail())\n {\n if (fin.eof())\n\tbreak;\n\n cerr << \"Line \" << line_count << \" in obj too long.\";\n return mls;\n }\n string str(linebuf);\n\n if (str.empty() || str.find('#') != string::npos)\n continue;\n\n istringstream ss(str);\n\n string line_type;\n ss >> line_type;\n if (line_type == \"v\")\n {\n Vec3 v;\n ss >> v;\n vertex_list.push_back(v);\n }\n else if (line_type == \"vn\")\n {\n Vec3 v;\n ss >> v;\n normal_list.push_back(v);\n }\n else if (line_type == \"vt\")\n {\n tex_coord tc;\n ss >> tc.u >> tc.v;\n tc_list.push_back(tc);\n }\n else if (line_type == \"f\")\n {\n string part;\n int sidx = ref_list.size();\n int num_verts = 0;\n while (true)\n {\n\tss >> part;\n if (!ss)\n break;\n\tref_list.push_back(parse_obj_vertex_ref(part));\n\t++num_verts;\n }\n for (int i = 0; i < num_verts - 2; ++i)\n {\n\ttri_ref tri{sidx, sidx+i+1, sidx+i+2};\n\ttri_list.emplace_back(tri);\n }\n }\n else\n {\n cerr << \"unknown line type: \" << line_type << \"\\n\";\n return mls;\n }\n }\n\n mls = load_from_parts(vertex_list, normal_list,\n\t\t\ttc_list, ref_list,\n\t\t\ttri_list);\n\n if (mls.success && !mls.has_normals)\n {\n compute_normals();\n mls.has_normals = true;\n }\n has_tex = mls.has_tex;\n return mls;\n}\n\nRawModelLoadStatus RawModel::load_stl_model(string filename)\n{\n RawModelLoadStatus mls;\n mls.success = false;\n\n ifstream fin(filename);\n if (!fin)\n {\n cerr << \"Could not open model file (\" << filename << \").\\n\";\n return mls;\n }\n\n vector vertex_list;\n vector normal_list;\n vector tc_list;\n vector ref_list;\n vector tri_list;\n\n#define BUF_SIZE 1024\n char linebuf[BUF_SIZE];\n\n int line_count = 0;\n while (!fin.eof())\n {\n ++line_count;\n fin.getline(linebuf, BUF_SIZE);\n if (fin.fail())\n {\n if (fin.eof())\n\tbreak;\n\n cerr << \"Line \" << line_count << \" in obj too long.\";\n return mls;\n }\n string str(linebuf);\n\n if (str.empty())\n continue;\n\n istringstream ss(str);\n\n string line_type;\n ss >> line_type;\n if (line_type == \"vertex\")\n {\n Vec3 v;\n ss >> v;\n vertex_list.push_back(v);\n ref_list.emplace_back(vertex_ref{(int)ref_list.size(), -1, -1});\n }\n else if (line_type == \"endloop\")\n {\n int num_tris = tri_list.size();\n tri_ref tri{num_tris*3, num_tris*3+1, num_tris*3+2};\n tri_list.emplace_back(tri);\n }\n else if (line_type == \"facet\" || line_type == \"outer\" ||\n line_type == \"endfacet\" || line_type == \"solid\")\n {\n }\n else if (line_type == \"endsolid\")\n break;\n else\n {\n cerr << \"unknown line type: \" << line_type << \"\\n\";\n return mls;\n }\n }\n\n mls = load_from_parts(vertex_list, normal_list,\n\t\t\ttc_list, ref_list,\n\t\t\ttri_list);\n\n if (mls.success && !mls.has_normals)\n {\n compute_normals();\n mls.has_normals = true;\n }\n has_tex = mls.has_tex;\n return mls;\n}\n\nRawModelLoadStatus RawModel::load_from_parts(const vector& vertex_list, const vector& normal_list,\n\t\t\t\t\t const vector& tc_list, const vector& vertex_ref_list,\n\t\t\t\t\t const vector& tri_list)\n{\n clear();\n\n unordered_map ref_map;\n\n RawModelLoadStatus mls;\n mls.success = true;\n mls.has_normals = normal_list.size() > 0;\n mls.has_tex = tc_list.size() > 0;\n\n for (const auto& tr: tri_list)\n {\n Triangle tri;\n for (int j = 0; j < 3; ++j)\n {\n int vidx = tr.v[j];\n auto vr = vertex_ref_list[vidx];\n\n \/\/ Add 'new' vertices.\n if (ref_map.find(vr) == ref_map.end())\n {\n\tref_map.insert(make_pair(vr, ref_map.size()));\n\tVertex v;\n\n\tv.position = vertex_list[vr.p];\n\tif (vr.t >= 0)\n\t{\n\t v.u = tc_list[vr.t].u;\n\t v.v = tc_list[vr.t].v;\n\t}\n\tif (vr.n >= 0)\n\t{\n\t v.normal = normal_list[vr.n];\n\t}\n\tverts.push_back(v);\n }\n\n tri.v[j] = ref_map[vr];\n }\n tris.push_back(tri);\n }\n\n return mls;\n}\n\nvoid RawModel::clear()\n{\n verts.clear();\n tris.clear();\n has_tex = false;\n}\n\nbounds::AABB RawModel::bounding_box() const\n{\n Vec3 min{std::numeric_limits::max()};\n Vec3 max{std::numeric_limits::min()};\n min = accumulate(verts.begin(), verts.end(), min,\n [] (const Vec3& v, const Vertex& w) { return ::min(v, w.position); });\n max = accumulate(verts.begin(), verts.end(), max,\n [] (const Vec3& v, const Vertex& w) { return ::max(v, w.position); });\n\n return bounds::AABB{min, max};\n}\n\nbounds::Sphere RawModel::bounding_sphere() const\n{\n Vec3 p1 = verts[0].position;\n\n Vec3 p2;\n scalar max_dist2 = 0;\n for (const auto& v: verts)\n {\n scalar dist2 = (v.position - p1).norm2();\n if (max_dist2 < dist2)\n {\n max_dist2 = dist2;\n p2 = v.position;\n }\n }\n\n Vec3 p3;\n max_dist2 = 0;\n for (const auto& v: verts)\n {\n scalar dist2 = (v.position - p2).norm2();\n if (max_dist2 < dist2)\n {\n max_dist2 = dist2;\n p3 = v.position;\n }\n }\n\n \/\/ Take the midpoint as the center, and find the best radius\n Vec3 mid = (p2 + p3) * 0.5;\n\n scalar radius = sqrt(accumulate(verts.begin(), verts.end(), (mid - p2).norm2(),\n \/* This could be generic\/polymorphic, but only\n in c++1y. *\/\n\/\/ [&mid](scalar r2, const Vertex& v) {\n [&mid](auto r2, auto&& v) {\n return max(r2, (mid - v.position).norm2());\n }));\n\n return bounds::Sphere(mid, radius);\n}\n\nvoid RawModel::compute_normals()\n{\n vector normal_sum( verts.size() );\n vector normal_weight( verts.size() );\n\n for (const auto& tri: tris)\n {\n \/\/ compute the normal, and compute the angle\n auto p1 = verts[tri.v[1]].position - verts[tri.v[0]].position;\n auto p2 = verts[tri.v[1]].position - verts[tri.v[0]].position;\n Vec3 face_normal = p1.cross(p2).normal();\n for (int i: tri.v)\n normal_sum[i] += face_normal;\n }\n for (size_t i = 0; i < verts.size(); ++i)\n verts[i].normal = normal_sum[i].normal();\n}\n\nvoid RawModel::rescale(const bounds::AABB& new_bb)\n{\n auto bb = bounding_box();\n auto w = bb.max - bb.min;\n for (auto& f: w.v)\n if (f < EPSILON)\n f = 1;\n\n auto scale = (new_bb.max - new_bb.min).elem_div(w);\n\n for (auto& v: verts)\n {\n v.position = (v.position - bb.min).elem_mult(scale) + new_bb.min;\n v.normal = v.normal.elem_div(scale).normal();\n }\n}\n\nvoid RawModel::rescale(const bounds::Sphere& new_bs)\n{\n const auto bs = bounding_sphere();\n\n auto scale = new_bs.radius \/ bs.radius;\n for (auto& v: verts)\n {\n v.position = (v.position - bs.center) * scale + new_bs.center;\n }\n}\n\n\/*\n * A face in a .obj file is 'f' followed by a list of vertex references.\n *\n *\/\nvertex_ref parse_obj_vertex_ref(string token) {\n\n vertex_ref ref{-1, -1, -1};\n auto pos = token.find('\/');\n if (pos == string::npos)\n {\n ref.p = std::stoi(token) - 1;\n return ref;\n }\n ref.p = std::stoi(token.substr(pos)) - 1;\n\n auto tpos = token.find('\/', pos+1);\n if (tpos == string::npos)\n {\n ref.t = std::stoi(token.substr(pos+1, tpos-pos-1)) - 1;\n return ref;\n }\n\n if (tpos > pos + 1)\n {\n ref.t = std::stoi(token.substr(pos+1, tpos-pos-1)) - 1;\n }\n ref.n = std::stoi(token.substr(tpos+1)) - 1;\n return ref;\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: drdefuno.cxx,v $\n *\n * $Revision: 1.1 $\n *\n * last change: $Author: nn $ $Date: 2001-03-05 11:31:09 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifdef PCH\n#include \"ui_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n#include \"drdefuno.hxx\"\n#include \"docsh.hxx\"\n#include \"drwlayer.hxx\"\n\nusing namespace ::com::sun::star;\n\n\/\/------------------------------------------------------------------------\n\nScDrawDefaultsObj::ScDrawDefaultsObj(ScDocShell* pDocSh) :\n SvxUnoDrawPool( NULL ),\n pDocShell( pDocSh )\n{\n \/\/ SvxUnoDrawPool is initialized without model,\n \/\/ draw layer is created on demand in getModelPool\n\n pDocShell->GetDocument()->AddUnoObject(*this);\n}\n\nScDrawDefaultsObj::~ScDrawDefaultsObj()\n{\n if (pDocShell)\n pDocShell->GetDocument()->RemoveUnoObject(*this);\n}\n\nvoid ScDrawDefaultsObj::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )\n{\n if ( rHint.ISA( SfxSimpleHint ) &&\n ((const SfxSimpleHint&)rHint).GetId() == SFX_HINT_DYING )\n {\n pDocShell = NULL; \/\/ document gone\n }\n}\n\nSfxItemPool* ScDrawDefaultsObj::getModelPool( sal_Bool bReadOnly ) throw()\n{\n SfxItemPool* pRet = NULL;\n if ( pDocShell )\n {\n ScDrawLayer* pModel = bReadOnly ?\n pDocShell->GetDocument()->GetDrawLayer() :\n pDocShell->MakeDrawLayer();\n if ( pModel )\n pRet = &pModel->GetItemPool();\n }\n if ( !pRet )\n pRet = SvxUnoDrawPool::getModelPool( bReadOnly ); \/\/ uses default pool\n\n return pRet;\n}\n\n\n#92075# excption specificaion\/*************************************************************************\n *\n * $RCSfile: drdefuno.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: vg $ $Date: 2001-09-18 15:12:49 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifdef PCH\n#include \"ui_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n#include \"drdefuno.hxx\"\n#include \"docsh.hxx\"\n#include \"drwlayer.hxx\"\n\nusing namespace ::com::sun::star;\n\n\/\/------------------------------------------------------------------------\n\nScDrawDefaultsObj::ScDrawDefaultsObj(ScDocShell* pDocSh) :\n SvxUnoDrawPool( NULL ),\n pDocShell( pDocSh )\n{\n \/\/ SvxUnoDrawPool is initialized without model,\n \/\/ draw layer is created on demand in getModelPool\n\n pDocShell->GetDocument()->AddUnoObject(*this);\n}\n\nScDrawDefaultsObj::~ScDrawDefaultsObj() throw ()\n{\n if (pDocShell)\n pDocShell->GetDocument()->RemoveUnoObject(*this);\n}\n\nvoid ScDrawDefaultsObj::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )\n{\n if ( rHint.ISA( SfxSimpleHint ) &&\n ((const SfxSimpleHint&)rHint).GetId() == SFX_HINT_DYING )\n {\n pDocShell = NULL; \/\/ document gone\n }\n}\n\nSfxItemPool* ScDrawDefaultsObj::getModelPool( sal_Bool bReadOnly ) throw()\n{\n SfxItemPool* pRet = NULL;\n if ( pDocShell )\n {\n ScDrawLayer* pModel = bReadOnly ?\n pDocShell->GetDocument()->GetDrawLayer() :\n pDocShell->MakeDrawLayer();\n if ( pModel )\n pRet = &pModel->GetItemPool();\n }\n if ( !pRet )\n pRet = SvxUnoDrawPool::getModelPool( bReadOnly ); \/\/ uses default pool\n\n return pRet;\n}\n\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n* UrBackup - Client\/Server backup system\n* Copyright (C) 2011 Martin Raiber\n*\n* This program is free software: you can redistribute it and\/or modify\n* it under the terms of the GNU General Public License as published by\n* the Free Software Foundation, either version 3 of the License, or\n* (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU General Public License for more details.\n*\n* You should have received a copy of the GNU General Public License\n* along with this program. If not, see .\n**************************************************************************\/\n\n#include \"vld.h\"\n\n#include \n#include \"WorkerThread.h\"\n#include \"Client.h\"\n#include \"Server.h\"\n#include \"libfastcgi\/fastcgi.hpp\"\n#include \"SelectThread.h\"\n#include \"stringtools.h\"\n#include \"Interface\/File.h\"\n\n\/\/#define EXTENSIVE_DEBUGGING\n\nextern std::deque client_queue;\nextern IMutex* clients_mutex;\nextern ICondition* clients_cond;\n\nCWorkerThread::CWorkerThread(CSelectThread *pMaster)\n{\n\tstop_mutex=Server->createMutex();\n\tstop_cond=Server->createCondition();\n\tMaster=pMaster;\n\tkeep_alive=true;\n\trun=true;\n}\n\nCWorkerThread::~CWorkerThread()\n{\n shutdown();\n Server->destroy(stop_cond);\n Server->destroy(stop_mutex);\n}\n\nvoid CWorkerThread::shutdown(void)\n{\n IScopedLock slock(stop_mutex);\n Server->Log(\"waiting for worker...\");\n run=false;\n clients_cond->notify_all();\n stop_cond->wait(&slock);\n Server->Log(\"done.\");\n} \n\nvoid CWorkerThread::operator()()\n{\n\twhile(run)\n\t{\n\t\tsize_t nq=0;\n\t\tIScopedLock lock(clients_mutex);\n\n\t\twhile(client_queue.size()==0 )\n\t\t{\n\t\t\tclients_cond->wait(&lock);\n\t\t\tif(!run)\n\t\t\t{\n\t\t\t IScopedLock slock(stop_mutex);\n\t\t\t stop_cond->notify_one();\n\t\t\t return;\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\t{\n\t\t\twhile( client_queue.size()>0 )\n\t\t\t{\n\t\t\t\tchar buffer[WT_BUFFERSIZE];\n\t\t\t\tCClient *client=client_queue[0];\n\t\t\t\tclient_queue.erase(client_queue.begin());\n\t\t\t\tSOCKET s=client->getSocket();\t\n\n\t\t\t\tclients_mutex->Unlock();\n\n\t\t\t\t_i32 rc=recv(s, buffer, WT_BUFFERSIZE, MSG_NOSIGNAL);\n\n\t\t\t\tif( rc<1 )\n\t\t\t\t{\n\t\t\t\t\tkeep_alive=true;\n\t\t\t\t\tServer->Log(\"Client disconnected\", LL_INFO);\n\t\t\t\t\tMaster->RemoveClient( client );\n\t\t\t\t\tclients_mutex->Lock();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n#ifdef EXTENSIVE_DEBUGGING\n\t\t\t\t\tstd::string lbuf;\n\t\t\t\t\tfor(_i32 i=0;iLog(\"Incoming data: \"+lbuf, LL_INFO);\n#endif\n\t\t\t\t\tclient->lock();\n\t\t\t\t\tclient->getFCGIProtocolDriver()->process_input(buffer, rc);\n\t\t\t\t\t\n\t\t\t\t\tFCGIRequest* req=client->getFCGIProtocolDriver()->get_request();\n\t\t\t\t\tclient->unlock();\n\n\t\t\t\t\tif( req!=NULL )\n\t\t\t\t\t\tclient->addRequest(req);\n\n\t\t\t\t\twhile( (req=client->getAndRemoveReadyRequest())!=NULL )\n\t\t\t\t\t{\n\t\t\t\t\t\tServer->addRequest();\n\t\t\t\t\t\tclient->lock();\n\t\t\t\t\t\tProcessRequest(client, req);\n\t\t\t\t\t\tclient->unlock();\n\t\t\t\t\t}\n\n\t\t\t\t\tif( keep_alive==false )\n\t\t\t\t\t{\n\t\t\t\t\t\tkeep_alive=true;\n\t\t\t\t\t\tServer->Log(\"Client disconnected\", LL_INFO);\n\t\t\t\t\t\tMaster->RemoveClient( client );\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tclient->setProcessing(false);\n\t\t\t\t\t\tMaster->WakeUp();\n\t\t\t\t\t}\n\n\t\t\t\t\tclients_mutex->Lock();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tIScopedLock slock(stop_mutex);\n\tstop_cond->notify_one();\n}\n\nvoid CWorkerThread::ProcessRequest(CClient *client, FCGIRequest *req)\n{\n\tif( req->keep_connection )\n\t{\n\t\tkeep_alive=true;\n\t}\n\telse\n\t{\n\t\tkeep_alive=false;\n\t}\n\n\tif( req->role != FCGIRequest::RESPONDER )\n\t{\n\t\tServer->Log(\"Role ist not Responder\", LL_ERROR);\n\t\treturn;\n\t}\n\n\tstr_map GET,POST;\n\n\tstr_nmap::iterator iter=req->params.find(\"QUERY_STRING\");\n\tif( iter!=req->params.end() )\n\t{\n\t\tfor(size_t i=0,size=iter->second.size();isecond[i]=='+' )\n\t\t\t\titer->second[i]=' ';\n\t\t}\n\t\tParseParamStr(iter->second, &GET );\t\t\t\n\t\treq->params.erase( iter );\n\t}\n\t\n\tstd::string ct=req->params[\"CONTENT_TYPE\"];\n\tstd::string lct=ct;\n\tstrlower(lct);\n\tbool postfile=false;\n\tPOSTFILE_KEY pfkey;\n\tif(lct.find(\"multipart\/form-data\")==std::string::npos)\n\t{\n\t\tif( req->stdin_stream.size()>0 && req->stdin_stream.size()<1048576 )\n\t\t{\n\t\t\tfor(size_t i=0,size=req->stdin_stream.size();istdin_stream[i]=='+' )\n\t\t\t\t\treq->stdin_stream[i]=' ';\n\t\t\t}\n\t\t\tParseParamStr(req->stdin_stream, &POST );\n\t\t}\n\t}\n\telse\n\t{\n\t\tstd::string boundary=getafter(\"boundary=\",ct);\n\t\tpfkey=ParseMultipartData(req->stdin_stream, boundary);\n\t req->params[\"POSTFILEKEY\"]=nconvert(pfkey);\n\t postfile=true;\n\t}\n\n\tstr_map::iterator iter2=GET.find(L\"a\");\n\n\tif( iter2!=GET.end() )\n\t{\n\t\tint starttime=Server->getTimeMS();\n\n\t\tstr_map::iterator iter3=GET.find(L\"c\");\n\n\t\tstd::wstring context;\n\t\tif( iter3!=GET.end() )\n\t\t\tcontext=iter3->second;\n\n\t\tTHREAD_ID tid=Server->Execute(iter2->second, context, GET, POST, req->params, req );\n\n\t\tif( tid==0 )\n\t\t{\n\t\t\tstd::wstring error=L\"Error: Unknown action [\"+iter2->second+L\"]\";\n\t\t\tServer->Log(error, LL_WARNING);\n\t\t\treq->write(\"Content-type: text\/html; charset=UTF-8\\r\\n\\r\\n\"+wnarrow(error));\n\t\t}\n\n\t\tstarttime=Server->getTimeMS()-starttime;\n\t\tServer->Log(\"Execution Time: \"+nconvert(starttime)+\" ms - time=\"+nconvert(Server->getTimeMS() ), LL_INFO);\n\t}\n\telse\n\t{\n\t\tstd::string error=\"Error: Parameter 'action' not given.\";\n\t\treq->write(\"Content-type: text\/html; charset=UTF-8\\r\\n\\r\\n\"+error);\n\t}\n\t\n\tif(postfile)\n\t{\n\t\tServer->clearPostFiles(pfkey);\n\t}\n\n\treq->end_request(0, FCGIRequest::REQUEST_COMPLETE);\n}\n\nPOSTFILE_KEY CWorkerThread::ParseMultipartData(const std::string &data, const std::string &boundary)\n{\n\tstd::string rboundary=\"--\"+boundary;\n\tint state=0;\n\tstd::string key;\n\tstd::string value;\n\tstd::string filename;\n\tstd::string name;\n\tstd::string filedata;\n\tstd::string contenttype;\n\tsize_t start;\n\tPOSTFILE_KEY pfilekey=Server->getPostFileKey();\n\tfor(size_t i=0;iopenMemoryFile();\n\t\t\t\tmemfile->Write(data.substr(start,i-start-2) );\n\t\t\t\tmemfile->Seek(0);\n\t\t\t\tServer->addPostFile(pfilekey, name, SPostfile(memfile, widen(filename), widen(contenttype)) );\n\t\t\t\tstate=0;\n\t\t\t\trboundary.erase(rboundary.size()-2,2);\n\t\t\t\ti+=rboundary.size()+2;\n\t\t\t\tstate=0;\n\t\t\t}\n\t }\n\t}\n return pfilekey;\n}Catch exception if fcgi stream is invalid\/*************************************************************************\n* UrBackup - Client\/Server backup system\n* Copyright (C) 2011 Martin Raiber\n*\n* This program is free software: you can redistribute it and\/or modify\n* it under the terms of the GNU General Public License as published by\n* the Free Software Foundation, either version 3 of the License, or\n* (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU General Public License for more details.\n*\n* You should have received a copy of the GNU General Public License\n* along with this program. If not, see .\n**************************************************************************\/\n\n#include \"vld.h\"\n\n#include \n#include \"WorkerThread.h\"\n#include \"Client.h\"\n#include \"Server.h\"\n#include \"libfastcgi\/fastcgi.hpp\"\n#include \"SelectThread.h\"\n#include \"stringtools.h\"\n#include \"Interface\/File.h\"\n\n\/\/#define EXTENSIVE_DEBUGGING\n\nextern std::deque client_queue;\nextern IMutex* clients_mutex;\nextern ICondition* clients_cond;\n\nCWorkerThread::CWorkerThread(CSelectThread *pMaster)\n{\n\tstop_mutex=Server->createMutex();\n\tstop_cond=Server->createCondition();\n\tMaster=pMaster;\n\tkeep_alive=true;\n\trun=true;\n}\n\nCWorkerThread::~CWorkerThread()\n{\n shutdown();\n Server->destroy(stop_cond);\n Server->destroy(stop_mutex);\n}\n\nvoid CWorkerThread::shutdown(void)\n{\n IScopedLock slock(stop_mutex);\n Server->Log(\"waiting for worker...\");\n run=false;\n clients_cond->notify_all();\n stop_cond->wait(&slock);\n Server->Log(\"done.\");\n} \n\nvoid CWorkerThread::operator()()\n{\n\twhile(run)\n\t{\n\t\tsize_t nq=0;\n\t\tIScopedLock lock(clients_mutex);\n\n\t\twhile(client_queue.size()==0 )\n\t\t{\n\t\t\tclients_cond->wait(&lock);\n\t\t\tif(!run)\n\t\t\t{\n\t\t\t IScopedLock slock(stop_mutex);\n\t\t\t stop_cond->notify_one();\n\t\t\t return;\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\t{\n\t\t\twhile( client_queue.size()>0 )\n\t\t\t{\n\t\t\t\tchar buffer[WT_BUFFERSIZE];\n\t\t\t\tCClient *client=client_queue[0];\n\t\t\t\tclient_queue.erase(client_queue.begin());\n\t\t\t\tSOCKET s=client->getSocket();\t\n\n\t\t\t\tclients_mutex->Unlock();\n\n\t\t\t\t_i32 rc=recv(s, buffer, WT_BUFFERSIZE, MSG_NOSIGNAL);\n\n\t\t\t\tif( rc<1 )\n\t\t\t\t{\n\t\t\t\t\tkeep_alive=true;\n\t\t\t\t\tServer->Log(\"Client disconnected\", LL_INFO);\n\t\t\t\t\tMaster->RemoveClient( client );\n\t\t\t\t\tclients_mutex->Lock();\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n#ifdef EXTENSIVE_DEBUGGING\n\t\t\t\t\tstd::string lbuf;\n\t\t\t\t\tfor(_i32 i=0;iLog(\"Incoming data: \"+lbuf, LL_INFO);\n#endif\n\t\t\t\t\tclient->lock();\n\t\t\t\t\ttry\n\t\t\t\t\t{\n\t\t\t\t\t\tclient->getFCGIProtocolDriver()->process_input(buffer, rc);\n\t\t\t\t\t}catch(...){}\n\t\t\t\t\t\n\t\t\t\t\tFCGIRequest* req=NULL;\n\t\t\t\t\ttry\n\t\t\t\t\t{\n\t\t\t\t\t\treq=client->getFCGIProtocolDriver()->get_request();\n\t\t\t\t\t}catch(...){}\n\n\t\t\t\t\tclient->unlock();\n\n\t\t\t\t\tif( req!=NULL )\n\t\t\t\t\t\tclient->addRequest(req);\n\n\t\t\t\t\twhile( (req=client->getAndRemoveReadyRequest())!=NULL )\n\t\t\t\t\t{\n\t\t\t\t\t\tServer->addRequest();\n\t\t\t\t\t\tclient->lock();\n\t\t\t\t\t\tProcessRequest(client, req);\n\t\t\t\t\t\tclient->unlock();\n\t\t\t\t\t}\n\n\t\t\t\t\tif( keep_alive==false )\n\t\t\t\t\t{\n\t\t\t\t\t\tkeep_alive=true;\n\t\t\t\t\t\tServer->Log(\"Client disconnected\", LL_INFO);\n\t\t\t\t\t\tMaster->RemoveClient( client );\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tclient->setProcessing(false);\n\t\t\t\t\t\tMaster->WakeUp();\n\t\t\t\t\t}\n\n\t\t\t\t\tclients_mutex->Lock();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tIScopedLock slock(stop_mutex);\n\tstop_cond->notify_one();\n}\n\nvoid CWorkerThread::ProcessRequest(CClient *client, FCGIRequest *req)\n{\n\tif( req->keep_connection )\n\t{\n\t\tkeep_alive=true;\n\t}\n\telse\n\t{\n\t\tkeep_alive=false;\n\t}\n\n\tif( req->role != FCGIRequest::RESPONDER )\n\t{\n\t\tServer->Log(\"Role ist not Responder\", LL_ERROR);\n\t\treturn;\n\t}\n\n\tstr_map GET,POST;\n\n\tstr_nmap::iterator iter=req->params.find(\"QUERY_STRING\");\n\tif( iter!=req->params.end() )\n\t{\n\t\tfor(size_t i=0,size=iter->second.size();isecond[i]=='+' )\n\t\t\t\titer->second[i]=' ';\n\t\t}\n\t\tParseParamStr(iter->second, &GET );\t\t\t\n\t\treq->params.erase( iter );\n\t}\n\t\n\tstd::string ct=req->params[\"CONTENT_TYPE\"];\n\tstd::string lct=ct;\n\tstrlower(lct);\n\tbool postfile=false;\n\tPOSTFILE_KEY pfkey;\n\tif(lct.find(\"multipart\/form-data\")==std::string::npos)\n\t{\n\t\tif( req->stdin_stream.size()>0 && req->stdin_stream.size()<1048576 )\n\t\t{\n\t\t\tfor(size_t i=0,size=req->stdin_stream.size();istdin_stream[i]=='+' )\n\t\t\t\t\treq->stdin_stream[i]=' ';\n\t\t\t}\n\t\t\tParseParamStr(req->stdin_stream, &POST );\n\t\t}\n\t}\n\telse\n\t{\n\t\tstd::string boundary=getafter(\"boundary=\",ct);\n\t\tpfkey=ParseMultipartData(req->stdin_stream, boundary);\n\t req->params[\"POSTFILEKEY\"]=nconvert(pfkey);\n\t postfile=true;\n\t}\n\n\tstr_map::iterator iter2=GET.find(L\"a\");\n\n\tif( iter2!=GET.end() )\n\t{\n\t\tint starttime=Server->getTimeMS();\n\n\t\tstr_map::iterator iter3=GET.find(L\"c\");\n\n\t\tstd::wstring context;\n\t\tif( iter3!=GET.end() )\n\t\t\tcontext=iter3->second;\n\n\t\tTHREAD_ID tid=Server->Execute(iter2->second, context, GET, POST, req->params, req );\n\n\t\tif( tid==0 )\n\t\t{\n\t\t\tstd::wstring error=L\"Error: Unknown action [\"+iter2->second+L\"]\";\n\t\t\tServer->Log(error, LL_WARNING);\n\t\t\treq->write(\"Content-type: text\/html; charset=UTF-8\\r\\n\\r\\n\"+wnarrow(error));\n\t\t}\n\n\t\tstarttime=Server->getTimeMS()-starttime;\n\t\tServer->Log(\"Execution Time: \"+nconvert(starttime)+\" ms - time=\"+nconvert(Server->getTimeMS() ), LL_INFO);\n\t}\n\telse\n\t{\n\t\tstd::string error=\"Error: Parameter 'action' not given.\";\n\t\treq->write(\"Content-type: text\/html; charset=UTF-8\\r\\n\\r\\n\"+error);\n\t}\n\t\n\tif(postfile)\n\t{\n\t\tServer->clearPostFiles(pfkey);\n\t}\n\n\treq->end_request(0, FCGIRequest::REQUEST_COMPLETE);\n}\n\nPOSTFILE_KEY CWorkerThread::ParseMultipartData(const std::string &data, const std::string &boundary)\n{\n\tstd::string rboundary=\"--\"+boundary;\n\tint state=0;\n\tstd::string key;\n\tstd::string value;\n\tstd::string filename;\n\tstd::string name;\n\tstd::string filedata;\n\tstd::string contenttype;\n\tsize_t start;\n\tPOSTFILE_KEY pfilekey=Server->getPostFileKey();\n\tfor(size_t i=0;iopenMemoryFile();\n\t\t\t\tmemfile->Write(data.substr(start,i-start-2) );\n\t\t\t\tmemfile->Seek(0);\n\t\t\t\tServer->addPostFile(pfilekey, name, SPostfile(memfile, widen(filename), widen(contenttype)) );\n\t\t\t\tstate=0;\n\t\t\t\trboundary.erase(rboundary.size()-2,2);\n\t\t\t\ti+=rboundary.size()+2;\n\t\t\t\tstate=0;\n\t\t\t}\n\t }\n\t}\n return pfilekey;\n}<|endoftext|>"} {"text":"\/*!\n * Copyright (c) 2016 by Contributors\n * \\file infer_shape.cc\n * \\brief Inference the shapes given existin information.\n *\/\n#include \n#include \n#include \n\nnamespace nnvm {\nnamespace pass {\nnamespace {\n\ntemplate\nGraph InferAttr(Graph &&ret,\n const AttrType empty_val,\n const char* infer_name,\n const char* input_name,\n const char* attr_key_name,\n const char* attr_name,\n const char* unknown_name,\n IsNone fis_none,\n FDefault fdefault) {\n using AttrVector = std::vector;\n const IndexedGraph& idx = ret.indexed_graph();\n static auto& finfer_shape =\n Op::GetAttr >(infer_name);\n static auto& is_backward =\n Op::GetAttr(\"TIsBackward\");\n \/\/ gradient function, used to get node correspondence.\n static auto& fgrad =\n Op::GetAttr(\"FGradient\");\n \/\/ reshape shape vector\n AttrVector rshape;\n if (ret.attrs.count(attr_name) != 0) {\n rshape = ret.MoveCopyAttr(attr_name);\n } else {\n rshape.resize(idx.num_node_entries(), empty_val);\n }\n\n if (ret.attrs.count(input_name) != 0) {\n const AttrVector& shape_args = ret.GetAttr(input_name);\n CHECK_LE(shape_args.size(), idx.input_nodes().size())\n << \"More provided shapes than number of arguments.\";\n for (size_t i = 0; i < shape_args.size(); ++i) {\n rshape[idx.entry_id(idx.input_nodes()[i], 0)] = shape_args[i];\n }\n \/\/ erase the provided arguments\n ret.attrs.erase(input_name);\n }\n\n \/\/ get the shape hints\n std::string shape_hints_key = std::string(attr_name) + \"_hints\";\n if (ret.attrs.count(shape_hints_key)) {\n NodeEntryMap shape_hints =\n ret.GetAttr>(shape_hints_key);\n for (const auto& kv : shape_hints) {\n NodeEntry e = kv.first;\n if (idx.exist(e.node.get())) {\n rshape[idx.entry_id(kv.first)] = kv.second;\n }\n }\n }\n\n std::string shape_attr_key;\n if (ret.attrs.count(attr_key_name) != 0) {\n shape_attr_key = ret.GetAttr(attr_key_name);\n \/\/ erase the provided arguments\n ret.attrs.erase(attr_key_name);\n }\n \/\/ Temp space for shape inference.\n std::vector ishape, oshape;\n\n \/\/ inference step function for nid\n auto infer_step = [&](uint32_t nid, bool last_iter) {\n const auto& inode = idx[nid];\n const uint32_t num_inputs = inode.inputs.size();\n const uint32_t num_outputs = inode.source->num_outputs();\n if (inode.source->is_variable()) {\n \/\/ Variable node. No operator. Only one output entry.\n CHECK(inode.source->op() == nullptr);\n CHECK_EQ(num_outputs, 1U);\n const uint32_t out_ent_id = idx.entry_id(nid, 0);\n if (shape_attr_key.length() != 0 && fis_none(rshape[out_ent_id])) {\n auto it = inode.source->attrs.dict.find(shape_attr_key);\n if (it != inode.source->attrs.dict.end()) {\n std::istringstream is(it->second);\n CHECK(is >> rshape[out_ent_id]) << \"Invalid attribute\";\n }\n }\n } else if (is_backward.get(inode.source->op(), false) && inode.control_deps.size()) {\n CHECK_GE(inode.control_deps.size(), 1U)\n << \"BackwardOp need to have control_deps to its forward op\";\n const IndexedGraph::Node& fnode = idx[inode.control_deps[0]];\n NodePtr fwd_ptr = inode.source->control_deps[0];\n CHECK(fwd_ptr->op() != nullptr) << \"Forward op cannot be a variable\";\n \/\/ use gradient function to find out the correspondence.\n std::vector ograd(fwd_ptr->num_outputs());\n for (size_t i = 0; i < ograd.size(); ++i) {\n ograd[i].index = static_cast(i);\n }\n \/\/ input gradient list\n auto igrad = fgrad[fwd_ptr->op()](fwd_ptr, ograd);\n const Node* igrad_node = nullptr;\n \/\/ Input gradient assignement\n for (size_t i = 0; i < igrad.size(); ++i) {\n if (igrad[i].node->op() == inode.source->op()) {\n uint32_t eid = idx.entry_id(nid, igrad[i].index);\n if (fis_none(rshape[eid])) {\n rshape[eid] = rshape[idx.entry_id(fnode.inputs[i])];\n } else {\n CHECK_EQ(rshape[eid], rshape[idx.entry_id(fnode.inputs[i])])\n << \"Backward shape inconsistent with the forward shape\";\n }\n if (igrad_node == nullptr) {\n igrad_node = igrad[i].node.get();\n } else {\n CHECK(igrad_node == igrad[i].node.get());\n }\n }\n }\n \/\/ out grad entries\n CHECK(igrad_node != nullptr)\n << \"Cannot find matching backward op for \" << inode.source->attrs.name;\n for (size_t i = 0; i < igrad_node->inputs.size(); ++i) {\n const NodeEntry& e = igrad_node->inputs[i];\n if (e.node == nullptr) {\n uint32_t eid = idx.entry_id(inode.inputs[i]);\n if (fis_none(rshape[eid])) {\n rshape[eid] = rshape[idx.entry_id(inode.control_deps[0], e.index)];\n }\n }\n }\n } else {\n bool forward_known = true;\n \/\/ Forward operator inference.\n ishape.resize(num_inputs, empty_val);\n for (uint32_t i = 0; i < ishape.size(); ++i) {\n ishape[i] = rshape[idx.entry_id(inode.inputs[i])];\n if (fis_none(ishape[i])) forward_known = false;\n }\n oshape.resize(num_outputs, empty_val);\n for (uint32_t i = 0; i < oshape.size(); ++i) {\n oshape[i] = rshape[idx.entry_id(nid, i)];\n if (fis_none(oshape[i])) forward_known = false;\n }\n auto finfer = finfer_shape.get(inode.source->op(), fdefault);\n if (!forward_known) {\n if (finfer != nullptr) {\n \/\/ Call inference function of the operator.\n try {\n forward_known = finfer(inode.source->attrs, &ishape, &oshape);\n } catch (const std::exception& e) {\n throw dmlc::Error(\"Error in operator \" + inode.source->attrs.name + \": \" + e.what());\n }\n } else {\n CHECK(!last_iter)\n << \"Attribute \" << infer_name\n << \" is not registed by op \" << inode.source->op()->name\n << \" we are not able to complete the inference because of this\";\n }\n }\n \/\/ Save to the result map.\n for (uint32_t i = 0; i < num_inputs; ++i) {\n rshape[idx.entry_id(inode.inputs[i])] = ishape[i];\n }\n for (uint32_t i = 0; i < num_outputs; ++i) {\n rshape[idx.entry_id(nid, i)] = oshape[i];\n }\n }\n };\n\n size_t last_num_unknown;\n size_t num_unknown = rshape.size();\n int i = 0;\n do {\n if (i % 2 == 0) {\n for (uint32_t nid = 0; nid < idx.num_nodes(); ++nid) {\n infer_step(nid, false);\n }\n } else {\n \/\/ backward inference\n for (uint32_t i = idx.num_nodes(); i != 0; --i) {\n infer_step(i - 1, false);\n }\n }\n last_num_unknown = num_unknown;\n num_unknown = 0;\n for (size_t j = 0; j < idx.num_node_entries(); ++j) {\n if (fis_none(rshape[j])) {\n ++num_unknown;\n }\n }\n ++i;\n } while (num_unknown > 0 && last_num_unknown > num_unknown);\n \/\/ set the shapes\n ret.attrs[attr_name] = std::make_shared(std::move(rshape));\n \/\/ number of nodes who knows the shape.\n ret.attrs[unknown_name] = std::make_shared(num_unknown);\n return ret;\n}\n\nNNVM_REGISTER_PASS(InferShape)\n.describe(\"Infer the shape of each node entries.\")\n.set_body([](Graph ret) {\n return InferAttr(\n std::move(ret), TShape(),\n \"FInferShape\", \"shape_inputs\", \"shape_attr_key\",\n \"shape\", \"shape_num_unknown_nodes\",\n [](const TShape& s) { return s.ndim() == 0 || s.Size() == 0; },\n nullptr);\n })\n.set_change_graph(false)\n.provide_graph_attr(\"shape\");\n\n\/\/ inference fucntion for same type\ninline bool SameType(const NodeAttrs& attrs,\n std::vector *iattr,\n std::vector *oattr) {\n int def_v = -1;\n for (int v : *oattr) {\n if (v != -1) {\n def_v = v; break;\n }\n }\n if (def_v == -1) {\n for (int v : *iattr) {\n if (v != -1) {\n def_v = v; break;\n }\n }\n }\n if (def_v == -1) return false;\n for (int& v : *oattr) {\n v = def_v;\n }\n for (int& v : *iattr) {\n v = def_v;\n }\n return true;\n}\n\nNNVM_REGISTER_PASS(InferType)\n.describe(\"Infer the dtype of each node entries.\")\n.set_body([](Graph ret) {\n return InferAttr(\n std::move(ret), -1,\n \"FInferType\", \"dtype_inputs\", \"dtype_attr_key\",\n \"dtype\", \"dtype_num_unknown_nodes\",\n [](const int t) { return t == -1; },\n SameType);\n })\n.set_change_graph(false)\n.provide_graph_attr(\"dtype\");\n\nDMLC_JSON_ENABLE_ANY(ShapeVector, list_shape);\nDMLC_JSON_ENABLE_ANY(DTypeVector, list_int);\nDMLC_JSON_ENABLE_ANY(size_t, size_t);\n\n} \/\/ namespace\n} \/\/ namespace pass\n} \/\/ namespace nnvm\nFix infer shape bug (#148)\/*!\n * Copyright (c) 2016 by Contributors\n * \\file infer_shape.cc\n * \\brief Inference the shapes given existin information.\n *\/\n#include \n#include \n#include \n\nnamespace nnvm {\nnamespace pass {\nnamespace {\n\ntemplate\nGraph InferAttr(Graph &&ret,\n const AttrType empty_val,\n const char* infer_name,\n const char* input_name,\n const char* attr_key_name,\n const char* attr_name,\n const char* unknown_name,\n IsNone fis_none,\n FDefault fdefault) {\n using AttrVector = std::vector;\n const IndexedGraph& idx = ret.indexed_graph();\n static auto& finfer_shape =\n Op::GetAttr >(infer_name);\n static auto& is_backward =\n Op::GetAttr(\"TIsBackward\");\n \/\/ gradient function, used to get node correspondence.\n static auto& fgrad =\n Op::GetAttr(\"FGradient\");\n \/\/ reshape shape vector\n AttrVector rshape;\n if (ret.attrs.count(attr_name) != 0) {\n rshape = ret.MoveCopyAttr(attr_name);\n } else {\n rshape.resize(idx.num_node_entries(), empty_val);\n }\n\n if (ret.attrs.count(input_name) != 0) {\n const AttrVector& shape_args = ret.GetAttr(input_name);\n CHECK_LE(shape_args.size(), idx.input_nodes().size())\n << \"More provided shapes than number of arguments.\";\n for (size_t i = 0; i < shape_args.size(); ++i) {\n rshape[idx.entry_id(idx.input_nodes()[i], 0)] = shape_args[i];\n }\n \/\/ erase the provided arguments\n ret.attrs.erase(input_name);\n }\n\n \/\/ get the shape hints\n std::string shape_hints_key = std::string(attr_name) + \"_hints\";\n if (ret.attrs.count(shape_hints_key)) {\n NodeEntryMap shape_hints =\n ret.GetAttr>(shape_hints_key);\n for (const auto& kv : shape_hints) {\n NodeEntry e = kv.first;\n if (idx.exist(e.node.get())) {\n rshape[idx.entry_id(kv.first)] = kv.second;\n }\n }\n }\n\n std::string shape_attr_key;\n if (ret.attrs.count(attr_key_name) != 0) {\n shape_attr_key = ret.GetAttr(attr_key_name);\n \/\/ erase the provided arguments\n ret.attrs.erase(attr_key_name);\n }\n \/\/ Temp space for shape inference.\n std::vector ishape, oshape;\n\n \/\/ inference step function for nid\n auto infer_step = [&](uint32_t nid, bool last_iter) {\n const auto& inode = idx[nid];\n const uint32_t num_inputs = inode.inputs.size();\n const uint32_t num_outputs = inode.source->num_outputs();\n if (inode.source->is_variable()) {\n \/\/ Variable node. No operator. Only one output entry.\n CHECK(inode.source->op() == nullptr);\n CHECK_EQ(num_outputs, 1U);\n const uint32_t out_ent_id = idx.entry_id(nid, 0);\n if (shape_attr_key.length() != 0 && fis_none(rshape[out_ent_id])) {\n auto it = inode.source->attrs.dict.find(shape_attr_key);\n if (it != inode.source->attrs.dict.end()) {\n std::istringstream is(it->second);\n CHECK(is >> rshape[out_ent_id]) << \"Invalid attribute\";\n }\n }\n } else if (is_backward.get(inode.source->op(), false) && inode.control_deps.size()) {\n CHECK_GE(inode.control_deps.size(), 1U)\n << \"BackwardOp need to have control_deps to its forward op\";\n const IndexedGraph::Node& fnode = idx[inode.control_deps[0]];\n NodePtr fwd_ptr = inode.source->control_deps[0];\n CHECK(fwd_ptr->op() != nullptr) << \"Forward op cannot be a variable\";\n \/\/ use gradient function to find out the correspondence.\n std::vector ograd(fwd_ptr->num_outputs());\n for (size_t i = 0; i < ograd.size(); ++i) {\n ograd[i].index = static_cast(i);\n }\n \/\/ input gradient list\n auto igrad = fgrad[fwd_ptr->op()](fwd_ptr, ograd);\n const Node* igrad_node = nullptr;\n \/\/ Input gradient assignement\n for (size_t i = 0; i < igrad.size(); ++i) {\n if (igrad[i].node->op() == inode.source->op()) {\n uint32_t eid = idx.entry_id(nid, igrad[i].index);\n if (fis_none(rshape[eid])) {\n rshape[eid] = rshape[idx.entry_id(fnode.inputs[i])];\n } else if (!fis_none(rshape[idx.entry_id(fnode.inputs[i])])) {\n CHECK_EQ(rshape[eid], rshape[idx.entry_id(fnode.inputs[i])])\n << \"Backward shape inconsistent with the forward shape\";\n }\n if (igrad_node == nullptr) {\n igrad_node = igrad[i].node.get();\n } else {\n CHECK(igrad_node == igrad[i].node.get());\n }\n }\n }\n \/\/ out grad entries\n CHECK(igrad_node != nullptr)\n << \"Cannot find matching backward op for \" << inode.source->attrs.name;\n for (size_t i = 0; i < igrad_node->inputs.size(); ++i) {\n const NodeEntry& e = igrad_node->inputs[i];\n if (e.node == nullptr) {\n uint32_t eid = idx.entry_id(inode.inputs[i]);\n if (fis_none(rshape[eid])) {\n rshape[eid] = rshape[idx.entry_id(inode.control_deps[0], e.index)];\n }\n }\n }\n } else {\n bool forward_known = true;\n \/\/ Forward operator inference.\n ishape.resize(num_inputs, empty_val);\n for (uint32_t i = 0; i < ishape.size(); ++i) {\n ishape[i] = rshape[idx.entry_id(inode.inputs[i])];\n if (fis_none(ishape[i])) forward_known = false;\n }\n oshape.resize(num_outputs, empty_val);\n for (uint32_t i = 0; i < oshape.size(); ++i) {\n oshape[i] = rshape[idx.entry_id(nid, i)];\n if (fis_none(oshape[i])) forward_known = false;\n }\n auto finfer = finfer_shape.get(inode.source->op(), fdefault);\n if (!forward_known) {\n if (finfer != nullptr) {\n \/\/ Call inference function of the operator.\n try {\n forward_known = finfer(inode.source->attrs, &ishape, &oshape);\n } catch (const std::exception& e) {\n throw dmlc::Error(\"Error in operator \" + inode.source->attrs.name + \": \" + e.what());\n }\n } else {\n CHECK(!last_iter)\n << \"Attribute \" << infer_name\n << \" is not registed by op \" << inode.source->op()->name\n << \" we are not able to complete the inference because of this\";\n }\n }\n \/\/ Save to the result map.\n for (uint32_t i = 0; i < num_inputs; ++i) {\n rshape[idx.entry_id(inode.inputs[i])] = ishape[i];\n }\n for (uint32_t i = 0; i < num_outputs; ++i) {\n rshape[idx.entry_id(nid, i)] = oshape[i];\n }\n }\n };\n\n size_t last_num_unknown;\n size_t num_unknown = rshape.size();\n int i = 0;\n do {\n if (i % 2 == 0) {\n for (uint32_t nid = 0; nid < idx.num_nodes(); ++nid) {\n infer_step(nid, false);\n }\n } else {\n \/\/ backward inference\n for (uint32_t i = idx.num_nodes(); i != 0; --i) {\n infer_step(i - 1, false);\n }\n }\n last_num_unknown = num_unknown;\n num_unknown = 0;\n for (size_t j = 0; j < idx.num_node_entries(); ++j) {\n if (fis_none(rshape[j])) {\n ++num_unknown;\n }\n }\n ++i;\n } while (num_unknown > 0 && last_num_unknown > num_unknown);\n \/\/ set the shapes\n ret.attrs[attr_name] = std::make_shared(std::move(rshape));\n \/\/ number of nodes who knows the shape.\n ret.attrs[unknown_name] = std::make_shared(num_unknown);\n return ret;\n}\n\nNNVM_REGISTER_PASS(InferShape)\n.describe(\"Infer the shape of each node entries.\")\n.set_body([](Graph ret) {\n return InferAttr(\n std::move(ret), TShape(),\n \"FInferShape\", \"shape_inputs\", \"shape_attr_key\",\n \"shape\", \"shape_num_unknown_nodes\",\n [](const TShape& s) { return s.ndim() == 0 || s.Size() == 0; },\n nullptr);\n })\n.set_change_graph(false)\n.provide_graph_attr(\"shape\");\n\n\/\/ inference fucntion for same type\ninline bool SameType(const NodeAttrs& attrs,\n std::vector *iattr,\n std::vector *oattr) {\n int def_v = -1;\n for (int v : *oattr) {\n if (v != -1) {\n def_v = v; break;\n }\n }\n if (def_v == -1) {\n for (int v : *iattr) {\n if (v != -1) {\n def_v = v; break;\n }\n }\n }\n if (def_v == -1) return false;\n for (int& v : *oattr) {\n v = def_v;\n }\n for (int& v : *iattr) {\n v = def_v;\n }\n return true;\n}\n\nNNVM_REGISTER_PASS(InferType)\n.describe(\"Infer the dtype of each node entries.\")\n.set_body([](Graph ret) {\n return InferAttr(\n std::move(ret), -1,\n \"FInferType\", \"dtype_inputs\", \"dtype_attr_key\",\n \"dtype\", \"dtype_num_unknown_nodes\",\n [](const int t) { return t == -1; },\n SameType);\n })\n.set_change_graph(false)\n.provide_graph_attr(\"dtype\");\n\nDMLC_JSON_ENABLE_ANY(ShapeVector, list_shape);\nDMLC_JSON_ENABLE_ANY(DTypeVector, list_int);\nDMLC_JSON_ENABLE_ANY(size_t, size_t);\n\n} \/\/ namespace\n} \/\/ namespace pass\n} \/\/ namespace nnvm\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2016 Jason Waataja\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include \"module.h\"\n\n#include \n\n#include \n\nnamespace dfm {\n\nModule::Module() : name(DEFAULT_MODULE_NAMES)\n{\n}\n\nModule::Module(const std::string& name) : name(name)\n{\n}\n\nconst std::string&\nModule::getName() const\n{\n return name;\n}\n\nvoid\nModule::setName(const std::string& name)\n{\n this->name = name;\n}\n\nbool\nModule::install(const std::string& sourceDirectory) const\n{\n for (const auto& file : files) {\n std::shared_ptr installAction =\n file.createInstallAction(sourceDirectory);\n if (!installAction->performAction()) {\n warnx(\"Failed to perform install action \\\"%s\\\".\",\n installAction->getName().c_str());\n return false;\n }\n }\n for (const auto& action : installActions) {\n bool status = action->performAction();\n if (!status) {\n warnx(\"Failed to perform install action \\\"%s\\\".\",\n action->getName().c_str());\n return false;\n }\n }\n return true;\n}\n\nbool\nModule::uninstall(const std::string& sourceDirectory) const\n{\n for (const auto& file : files) {\n std::shared_ptr uninstallAction =\n file.createUninstallAction();\n if (!uninstallAction->performAction()) {\n warnx(\"Failed to perform uninstall action \\\"%s\\\".\",\n uninstallAction->getName().c_str());\n return false;\n }\n }\n for (const auto& action : uninstallActions) {\n bool status = action->performAction();\n if (!status) {\n warnx(\"Failed to perform uninstall action \\\"%s\\\".\",\n action->getName().c_str());\n return false;\n }\n }\n return true;\n}\n\n\nbool\nModule::update(const std::string& sourceDirectory) const\n{\n for (const auto& file : files) {\n std::shared_ptr updateAction =\n file.createUpdateAction(sourceDirectory);\n if (!updateAction->performAction()) {\n warnx(\"Failed to perform update action \\\"%s\\\".\",\n updateAction->getName().c_str());\n return false;\n }\n }\n for (const auto& action : updateActions) {\n bool status = action->performAction();\n if (!status) {\n warnx(\"Failed to perform update action \\\"%s\\\".\",\n action->getName().c_str());\n return false;\n }\n }\n return true;\n}\n\nvoid\nModule::addInstallAction(std::shared_ptr action)\n{\n installActions.push_back(action);\n}\n\nvoid\nModule::addUninstallAction(std::shared_ptr action)\n{\n uninstallActions.push_back(action);\n}\n\nvoid\nModule::addUpdateAction(std::shared_ptr action)\n{\n updateActions.push_back(action);\n}\n\nconst std::vector>&\nModule::getInstallActions() const\n{\n return installActions;\n}\n\nconst std::vector>&\nModule::getUninstallActions() const\n{\n return uninstallActions;\n}\n\nconst std::vector>&\nModule::getUpdateActions() const\n{\n return updateActions;\n}\n\nvoid\nModule::addFile(const std::string& filename)\n{\n files.push_back(ModuleFile(filename));\n}\n\nvoid\nModule::addFile(\n const std::string& filename, const std::string& destinationDirectory)\n{\n files.push_back(ModuleFile(filename, destinationDirectory));\n}\n\nvoid\nModule::addFile(const std::string& filename,\n const std::string& destinationDirectory,\n const std::string& destinationFilename)\n{\n files.push_back(\n ModuleFile(filename, destinationDirectory, destinationFilename));\n}\n\nconst std::vector\nModule::getFiles() const\n{\n return files;\n}\n\nstd::vector\nModule::createConfigLines() const\n{\n std::vector lines;\n lines.push_back(name + \":\");\n for (const auto& file : files)\n lines.push_back(\"\\t\" + file.createConfigLines()[0]);\n if (installActions.size() > 0)\n lines.push_back(\"install:\");\n \/*\n * It would make more sense to include this type of block in the if\n * statement above it but this way leads to less indentation.\n *\/\n for (const auto& action : installActions) {\n for (const auto& line : action->createConfigLines())\n lines.push_back(\"\\t\" + line);\n }\n if (uninstallActions.size() > 0)\n lines.push_back(\"uninstall:\");\n for (const auto& action : uninstallActions) {\n for (const auto& line : action->createConfigLines())\n lines.push_back(\"\\t\" + line);\n }\n if (updateActions.size() > 0)\n lines.push_back(\"update:\");\n for (const auto& action : updateActions) {\n for (const auto& line : action->createConfigLines())\n lines.push_back(\"\\t\" + line);\n }\n return lines;\n}\n} \/* namespace dfm *\/\nIncorporated small code change from gdfm\/*\n * Copyright (c) 2016 Jason Waataja\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include \"module.h\"\n\n#include \n\nnamespace dfm {\n\nModule::Module() : name(DEFAULT_MODULE_NAMES)\n{\n}\n\nModule::Module(const std::string& name) : name(name)\n{\n}\n\nconst std::string&\nModule::getName() const\n{\n return name;\n}\n\nvoid\nModule::setName(const std::string& name)\n{\n this->name = name;\n}\n\nbool\nModule::install(const std::string& sourceDirectory) const\n{\n for (const auto& file : files) {\n std::shared_ptr installAction =\n file.createInstallAction(sourceDirectory);\n if (!installAction->performAction()) {\n warnx(\"Failed to perform install action \\\"%s\\\".\",\n installAction->getName().c_str());\n return false;\n }\n }\n for (const auto& action : installActions) {\n if (action->performAction()) {\n warnx(\"Failed to perform install action \\\"%s\\\".\",\n action->getName().c_str());\n return false;\n }\n }\n return true;\n}\n\nbool\nModule::uninstall(const std::string& sourceDirectory) const\n{\n for (const auto& file : files) {\n std::shared_ptr uninstallAction =\n file.createUninstallAction();\n if (!uninstallAction->performAction()) {\n warnx(\"Failed to perform uninstall action \\\"%s\\\".\",\n uninstallAction->getName().c_str());\n return false;\n }\n }\n for (const auto& action : uninstallActions) {\n if (action->performAction()) {\n warnx(\"Failed to perform uninstall action \\\"%s\\\".\",\n action->getName().c_str());\n return false;\n }\n }\n return true;\n}\n\n\nbool\nModule::update(const std::string& sourceDirectory) const\n{\n for (const auto& file : files) {\n std::shared_ptr updateAction =\n file.createUpdateAction(sourceDirectory);\n if (!updateAction->performAction()) {\n warnx(\"Failed to perform update action \\\"%s\\\".\",\n updateAction->getName().c_str());\n return false;\n }\n }\n for (const auto& action : updateActions) {\n if (action->performAction()) {\n warnx(\"Failed to perform update action \\\"%s\\\".\",\n action->getName().c_str());\n return false;\n }\n }\n return true;\n}\n\nvoid\nModule::addInstallAction(std::shared_ptr action)\n{\n installActions.push_back(action);\n}\n\nvoid\nModule::addUninstallAction(std::shared_ptr action)\n{\n uninstallActions.push_back(action);\n}\n\nvoid\nModule::addUpdateAction(std::shared_ptr action)\n{\n updateActions.push_back(action);\n}\n\nconst std::vector>&\nModule::getInstallActions() const\n{\n return installActions;\n}\n\nconst std::vector>&\nModule::getUninstallActions() const\n{\n return uninstallActions;\n}\n\nconst std::vector>&\nModule::getUpdateActions() const\n{\n return updateActions;\n}\n\nvoid\nModule::addFile(const std::string& filename)\n{\n files.push_back(ModuleFile(filename));\n}\n\nvoid\nModule::addFile(\n const std::string& filename, const std::string& destinationDirectory)\n{\n files.push_back(ModuleFile(filename, destinationDirectory));\n}\n\nvoid\nModule::addFile(const std::string& filename,\n const std::string& destinationDirectory,\n const std::string& destinationFilename)\n{\n files.push_back(\n ModuleFile(filename, destinationDirectory, destinationFilename));\n}\n\nconst std::vector\nModule::getFiles() const\n{\n return files;\n}\n\nstd::vector\nModule::createConfigLines() const\n{\n std::vector lines;\n lines.push_back(name + \":\");\n for (const auto& file : files)\n lines.push_back(\"\\t\" + file.createConfigLines()[0]);\n if (installActions.size() > 0)\n lines.push_back(\"install:\");\n \/*\n * It would make more sense to include this type of block in the if\n * statement above it but this way leads to less indentation.\n *\/\n for (const auto& action : installActions) {\n for (const auto& line : action->createConfigLines())\n lines.push_back(\"\\t\" + line);\n }\n if (uninstallActions.size() > 0)\n lines.push_back(\"uninstall:\");\n for (const auto& action : uninstallActions) {\n for (const auto& line : action->createConfigLines())\n lines.push_back(\"\\t\" + line);\n }\n if (updateActions.size() > 0)\n lines.push_back(\"update:\");\n for (const auto& action : updateActions) {\n for (const auto& line : action->createConfigLines())\n lines.push_back(\"\\t\" + line);\n }\n return lines;\n}\n} \/* namespace dfm *\/\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"directshowioreader.h\"\n\n#include \"directshoweventloop.h\"\n#include \"directshowglobal.h\"\n#include \"directshowiosource.h\"\n\n#include \n#include \n#include \n#include \n\nclass DirectShowSampleRequest\n{\npublic:\n DirectShowSampleRequest(\n IMediaSample *sample, DWORD_PTR userData, LONGLONG position, LONG length, BYTE *buffer)\n : next(0)\n , sample(sample)\n , userData(userData)\n , position(position)\n , length(length)\n , buffer(buffer)\n , result(S_FALSE)\n {\n }\n\n DirectShowSampleRequest *remove() { DirectShowSampleRequest *n = next; delete this; return n; }\n\n DirectShowSampleRequest *next;\n IMediaSample *sample;\n DWORD_PTR userData;\n LONGLONG position;\n LONG length;\n BYTE *buffer;\n HRESULT result;\n};\n\nDirectShowIOReader::DirectShowIOReader(\n QIODevice *device, DirectShowIOSource *source, DirectShowEventLoop *loop)\n : m_source(source)\n , m_device(device)\n , m_loop(loop)\n , m_pendingHead(0)\n , m_pendingTail(0)\n , m_readyHead(0)\n , m_readyTail(0)\n , m_synchronousPosition(0)\n , m_synchronousLength(0)\n , m_synchronousBytesRead(0)\n , m_synchronousBuffer(0)\n , m_synchronousResult(S_OK)\n , m_totalLength(0)\n , m_availableLength(0)\n , m_flushing(false)\n{\n moveToThread(device->thread());\n\n connect(device, SIGNAL(readyRead()), this, SLOT(readyRead()));\n}\n\nDirectShowIOReader::~DirectShowIOReader()\n{\n flushRequests();\n}\n\nHRESULT DirectShowIOReader::QueryInterface(REFIID riid, void **ppvObject)\n{\n return m_source->QueryInterface(riid, ppvObject);\n}\n\nULONG DirectShowIOReader::AddRef()\n{\n return m_source->AddRef();\n}\n\nULONG DirectShowIOReader::Release()\n{\n return m_source->Release();\n}\n\n\/\/ IAsyncReader\nHRESULT DirectShowIOReader::RequestAllocator(\n IMemAllocator *pPreferred, ALLOCATOR_PROPERTIES *pProps, IMemAllocator **ppActual)\n{\n if (!ppActual || !pProps) {\n return E_POINTER;\n } else {\n ALLOCATOR_PROPERTIES actualProperties;\n\n if (pProps->cbAlign == 0)\n pProps->cbAlign = 1;\n\n if (pPreferred && pPreferred->SetProperties(pProps, &actualProperties) == S_OK) {\n pPreferred->AddRef();\n\n *ppActual = pPreferred;\n\n m_source->setAllocator(*ppActual);\n\n return S_OK;\n } else {\n *ppActual = com_new(CLSID_MemoryAllocator);\n\n if (*ppActual) {\n if ((*ppActual)->SetProperties(pProps, &actualProperties) != S_OK) {\n (*ppActual)->Release();\n } else {\n m_source->setAllocator(*ppActual);\n\n return S_OK;\n }\n }\n }\n ppActual = 0;\n\n return E_FAIL;\n }\n}\n\nHRESULT DirectShowIOReader::Request(IMediaSample *pSample, DWORD_PTR dwUser)\n{\n QMutexLocker locker(&m_mutex);\n\n if (!pSample) {\n return E_POINTER;\n } else if (m_flushing) {\n return VFW_E_WRONG_STATE;\n } else {\n REFERENCE_TIME startTime = 0;\n REFERENCE_TIME endTime = 0;\n BYTE *buffer;\n\n if (pSample->GetTime(&startTime, &endTime) != S_OK\n || pSample->GetPointer(&buffer) != S_OK) {\n return VFW_E_SAMPLE_TIME_NOT_SET;\n } else {\n LONGLONG position = startTime \/ 10000000;\n LONG length = ((endTime - startTime) \/ 10000000) + 1;\n\n DirectShowSampleRequest *request = new DirectShowSampleRequest(\n pSample, dwUser, position, length, buffer);\n\n if (m_pendingTail) {\n m_pendingTail->next = request;\n } else {\n m_pendingHead = request;\n\n m_loop->postEvent(this, new QEvent(QEvent::User));\n }\n m_pendingTail = request;\n\n return S_OK;\n }\n }\n}\n\nHRESULT DirectShowIOReader::WaitForNext(\n DWORD dwTimeout, IMediaSample **ppSample, DWORD_PTR *pdwUser)\n{\n if (!ppSample || !pdwUser)\n return E_POINTER;\n\n QMutexLocker locker(&m_mutex);\n\n do {\n if (m_readyHead) {\n DirectShowSampleRequest *request = m_readyHead;\n\n *ppSample = request->sample;\n *pdwUser = request->userData;\n\n HRESULT hr = request->result;\n\n m_readyHead = request->next;\n\n if (!m_readyHead)\n m_readyTail = 0;\n\n delete request;\n\n return hr;\n } else if (m_flushing) {\n *ppSample = 0;\n *pdwUser = 0;\n\n return VFW_E_WRONG_STATE;\n }\n } while (m_wait.wait(&m_mutex, dwTimeout));\n\n *ppSample = 0;\n *pdwUser = 0;\n\n return VFW_E_TIMEOUT;\n}\n\nHRESULT DirectShowIOReader::SyncReadAligned(IMediaSample *pSample)\n{\n if (!pSample) {\n return E_POINTER;\n } else {\n REFERENCE_TIME startTime = 0;\n REFERENCE_TIME endTime = 0;\n BYTE *buffer;\n\n if (pSample->GetTime(&startTime, &endTime) != S_OK\n || pSample->GetPointer(&buffer) != S_OK) {\n return VFW_E_SAMPLE_TIME_NOT_SET;\n } else {\n LONGLONG position = startTime \/ 10000000;\n LONG length = ((endTime - startTime) \/ 10000000) + 1;\n\n QMutexLocker locker(&m_mutex);\n\n if (thread() == QThread::currentThread()) {\n qint64 bytesRead = 0;\n\n HRESULT hr = blockingRead(position, length, buffer, &bytesRead);\n\n if (SUCCEEDED(hr))\n pSample->SetActualDataLength(bytesRead);\n \n return hr;\n } else {\n m_synchronousPosition = position;\n m_synchronousLength = length;\n m_synchronousBuffer = buffer;\n\n m_loop->postEvent(this, new QEvent(QEvent::User));\n\n m_wait.wait(&m_mutex);\n\n m_synchronousBuffer = 0;\n\n if (SUCCEEDED(m_synchronousResult))\n pSample->SetActualDataLength(m_synchronousBytesRead);\n\n return m_synchronousResult;\n }\n }\n }\n}\n\nHRESULT DirectShowIOReader::SyncRead(LONGLONG llPosition, LONG lLength, BYTE *pBuffer)\n{\n if (!pBuffer) {\n return E_POINTER;\n } else {\n if (thread() == QThread::currentThread()) {\n qint64 bytesRead;\n\n return blockingRead(llPosition, lLength, pBuffer, &bytesRead);\n } else {\n QMutexLocker locker(&m_mutex);\n\n m_synchronousPosition = llPosition;\n m_synchronousLength = lLength;\n m_synchronousBuffer = pBuffer;\n\n m_loop->postEvent(this, new QEvent(QEvent::User));\n\n m_wait.wait(&m_mutex);\n\n m_synchronousBuffer = 0;\n\n return m_synchronousResult;\n }\n }\n}\n\nHRESULT DirectShowIOReader::Length(LONGLONG *pTotal, LONGLONG *pAvailable)\n{\n if (!pTotal || !pAvailable) {\n return E_POINTER;\n } else {\n QMutexLocker locker(&m_mutex);\n\n *pTotal = m_totalLength;\n *pAvailable = m_availableLength;\n\n return S_OK;\n }\n}\n\n\nHRESULT DirectShowIOReader::BeginFlush()\n{\n QMutexLocker locker(&m_mutex);\n\n if (m_flushing)\n return S_FALSE;\n\n m_flushing = true;\n\n flushRequests();\n\n m_wait.wakeAll();\n\n return S_OK;\n}\n\nHRESULT DirectShowIOReader::EndFlush()\n{\n QMutexLocker locker(&m_mutex);\n\n if (!m_flushing)\n return S_FALSE;\n\n m_flushing = false;\n\n return S_OK;\n}\n\nvoid DirectShowIOReader::customEvent(QEvent *event)\n{\n if (event->type() == QEvent::User) {\n readyRead();\n } else {\n QObject::customEvent(event);\n }\n}\n\nvoid DirectShowIOReader::readyRead()\n{\n QMutexLocker locker(&m_mutex);\n\n m_availableLength = m_device->bytesAvailable() + m_device->pos();\n m_totalLength = m_device->size();\n\n if (m_synchronousBuffer) {\n if (nonBlockingRead(\n m_synchronousPosition,\n m_synchronousLength,\n m_synchronousBuffer,\n &m_synchronousBytesRead,\n &m_synchronousResult)) {\n m_wait.wakeAll();\n }\n } else {\n qint64 bytesRead = 0;\n\n while (m_pendingHead && nonBlockingRead(\n m_pendingHead->position,\n m_pendingHead->length,\n m_pendingHead->buffer,\n &bytesRead,\n &m_pendingHead->result)) {\n m_pendingHead->sample->SetActualDataLength(bytesRead);\n\n if (m_readyTail)\n m_readyTail->next = m_pendingHead;\n m_readyTail = m_pendingHead;\n\n m_pendingHead = m_pendingHead->next;\n\n m_readyTail->next = 0;\n\n if (!m_pendingHead)\n m_pendingTail = 0;\n\n if (!m_readyHead)\n m_readyHead = m_readyTail;\n\n m_wait.wakeAll();\n }\n }\n}\n\nHRESULT DirectShowIOReader::blockingRead(\n LONGLONG position, LONG length, BYTE *buffer, qint64 *bytesRead)\n{\n *bytesRead = 0;\n\n if (qint64(position) > m_device->size())\n return S_FALSE;\n\n const qint64 maxSize = qMin(m_device->size(), position + length);\n\n while (m_device->bytesAvailable() + m_device->pos() < maxSize) {\n if (!m_device->waitForReadyRead(-1))\n return S_FALSE;\n }\n\n if (m_device->pos() != position && !m_device->seek(position))\n return S_FALSE;\n\n const qint64 maxBytes = qMin(length, m_device->bytesAvailable());\n\n *bytesRead = m_device->read(reinterpret_cast(buffer), maxBytes);\n\n if (*bytesRead != length) {\n qMemSet(buffer + *bytesRead, 0, length - *bytesRead);\n\n return S_FALSE;\n } else {\n return S_OK;\n }\n}\n\nbool DirectShowIOReader::nonBlockingRead(\n LONGLONG position, LONG length, BYTE *buffer, qint64 *bytesRead, HRESULT *result)\n{\n const qint64 maxSize = qMin(m_device->size(), position + length);\n\n if (position > m_device->size()) {\n *bytesRead = 0;\n *result = S_FALSE;\n\n return true;\n } else if (m_device->bytesAvailable() + m_device->pos() >= maxSize) {\n if (m_device->pos() != position && !m_device->seek(position)) {\n *bytesRead = 0;\n *result = S_FALSE;\n\n return true;\n } else {\n const qint64 maxBytes = qMin(length, m_device->bytesAvailable());\n\n *bytesRead = m_device->read(reinterpret_cast(buffer), maxBytes);\n\n if (*bytesRead != length) {\n qMemSet(buffer + *bytesRead, 0, length - *bytesRead);\n\n *result = S_FALSE;\n } else {\n *result = S_OK;\n }\n\n return true;\n }\n } else {\n return false;\n }\n}\n\nvoid DirectShowIOReader::flushRequests()\n{\n while (m_pendingHead) {\n m_pendingHead->result = VFW_E_WRONG_STATE;\n\n if (m_readyTail)\n m_readyTail->next = m_pendingHead;\n\n m_readyTail = m_pendingHead;\n\n m_pendingHead = m_pendingHead->next;\n\n m_readyTail->next = 0;\n\n if (!m_pendingHead)\n m_pendingTail = 0;\n\n if (!m_readyHead)\n m_readyHead = m_readyTail;\n }\n}\nFix incorrect buffer size calculation.\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"directshowioreader.h\"\n\n#include \"directshoweventloop.h\"\n#include \"directshowglobal.h\"\n#include \"directshowiosource.h\"\n\n#include \n#include \n#include \n#include \n\nclass DirectShowSampleRequest\n{\npublic:\n DirectShowSampleRequest(\n IMediaSample *sample, DWORD_PTR userData, LONGLONG position, LONG length, BYTE *buffer)\n : next(0)\n , sample(sample)\n , userData(userData)\n , position(position)\n , length(length)\n , buffer(buffer)\n , result(S_FALSE)\n {\n }\n\n DirectShowSampleRequest *remove() { DirectShowSampleRequest *n = next; delete this; return n; }\n\n DirectShowSampleRequest *next;\n IMediaSample *sample;\n DWORD_PTR userData;\n LONGLONG position;\n LONG length;\n BYTE *buffer;\n HRESULT result;\n};\n\nDirectShowIOReader::DirectShowIOReader(\n QIODevice *device, DirectShowIOSource *source, DirectShowEventLoop *loop)\n : m_source(source)\n , m_device(device)\n , m_loop(loop)\n , m_pendingHead(0)\n , m_pendingTail(0)\n , m_readyHead(0)\n , m_readyTail(0)\n , m_synchronousPosition(0)\n , m_synchronousLength(0)\n , m_synchronousBytesRead(0)\n , m_synchronousBuffer(0)\n , m_synchronousResult(S_OK)\n , m_totalLength(0)\n , m_availableLength(0)\n , m_flushing(false)\n{\n moveToThread(device->thread());\n\n connect(device, SIGNAL(readyRead()), this, SLOT(readyRead()));\n}\n\nDirectShowIOReader::~DirectShowIOReader()\n{\n flushRequests();\n}\n\nHRESULT DirectShowIOReader::QueryInterface(REFIID riid, void **ppvObject)\n{\n return m_source->QueryInterface(riid, ppvObject);\n}\n\nULONG DirectShowIOReader::AddRef()\n{\n return m_source->AddRef();\n}\n\nULONG DirectShowIOReader::Release()\n{\n return m_source->Release();\n}\n\n\/\/ IAsyncReader\nHRESULT DirectShowIOReader::RequestAllocator(\n IMemAllocator *pPreferred, ALLOCATOR_PROPERTIES *pProps, IMemAllocator **ppActual)\n{\n if (!ppActual || !pProps) {\n return E_POINTER;\n } else {\n ALLOCATOR_PROPERTIES actualProperties;\n\n if (pProps->cbAlign == 0)\n pProps->cbAlign = 1;\n\n if (pPreferred && pPreferred->SetProperties(pProps, &actualProperties) == S_OK) {\n pPreferred->AddRef();\n\n *ppActual = pPreferred;\n\n m_source->setAllocator(*ppActual);\n\n return S_OK;\n } else {\n *ppActual = com_new(CLSID_MemoryAllocator);\n\n if (*ppActual) {\n if ((*ppActual)->SetProperties(pProps, &actualProperties) != S_OK) {\n (*ppActual)->Release();\n } else {\n m_source->setAllocator(*ppActual);\n\n return S_OK;\n }\n }\n }\n ppActual = 0;\n\n return E_FAIL;\n }\n}\n\nHRESULT DirectShowIOReader::Request(IMediaSample *pSample, DWORD_PTR dwUser)\n{\n QMutexLocker locker(&m_mutex);\n\n if (!pSample) {\n return E_POINTER;\n } else if (m_flushing) {\n return VFW_E_WRONG_STATE;\n } else {\n REFERENCE_TIME startTime = 0;\n REFERENCE_TIME endTime = 0;\n BYTE *buffer;\n\n if (pSample->GetTime(&startTime, &endTime) != S_OK\n || pSample->GetPointer(&buffer) != S_OK) {\n return VFW_E_SAMPLE_TIME_NOT_SET;\n } else {\n LONGLONG position = startTime \/ 10000000;\n LONG length = (endTime - startTime) \/ 10000000;\n\n DirectShowSampleRequest *request = new DirectShowSampleRequest(\n pSample, dwUser, position, length, buffer);\n\n if (m_pendingTail) {\n m_pendingTail->next = request;\n } else {\n m_pendingHead = request;\n\n m_loop->postEvent(this, new QEvent(QEvent::User));\n }\n m_pendingTail = request;\n\n return S_OK;\n }\n }\n}\n\nHRESULT DirectShowIOReader::WaitForNext(\n DWORD dwTimeout, IMediaSample **ppSample, DWORD_PTR *pdwUser)\n{\n if (!ppSample || !pdwUser)\n return E_POINTER;\n\n QMutexLocker locker(&m_mutex);\n\n do {\n if (m_readyHead) {\n DirectShowSampleRequest *request = m_readyHead;\n\n *ppSample = request->sample;\n *pdwUser = request->userData;\n\n HRESULT hr = request->result;\n\n m_readyHead = request->next;\n\n if (!m_readyHead)\n m_readyTail = 0;\n\n delete request;\n\n return hr;\n } else if (m_flushing) {\n *ppSample = 0;\n *pdwUser = 0;\n\n return VFW_E_WRONG_STATE;\n }\n } while (m_wait.wait(&m_mutex, dwTimeout));\n\n *ppSample = 0;\n *pdwUser = 0;\n\n return VFW_E_TIMEOUT;\n}\n\nHRESULT DirectShowIOReader::SyncReadAligned(IMediaSample *pSample)\n{\n if (!pSample) {\n return E_POINTER;\n } else {\n REFERENCE_TIME startTime = 0;\n REFERENCE_TIME endTime = 0;\n BYTE *buffer;\n\n if (pSample->GetTime(&startTime, &endTime) != S_OK\n || pSample->GetPointer(&buffer) != S_OK) {\n return VFW_E_SAMPLE_TIME_NOT_SET;\n } else {\n LONGLONG position = startTime \/ 10000000;\n LONG length = (endTime - startTime) \/ 10000000;\n\n QMutexLocker locker(&m_mutex);\n\n if (thread() == QThread::currentThread()) {\n qint64 bytesRead = 0;\n\n HRESULT hr = blockingRead(position, length, buffer, &bytesRead);\n\n if (SUCCEEDED(hr))\n pSample->SetActualDataLength(bytesRead);\n \n return hr;\n } else {\n m_synchronousPosition = position;\n m_synchronousLength = length;\n m_synchronousBuffer = buffer;\n\n m_loop->postEvent(this, new QEvent(QEvent::User));\n\n m_wait.wait(&m_mutex);\n\n m_synchronousBuffer = 0;\n\n if (SUCCEEDED(m_synchronousResult))\n pSample->SetActualDataLength(m_synchronousBytesRead);\n\n return m_synchronousResult;\n }\n }\n }\n}\n\nHRESULT DirectShowIOReader::SyncRead(LONGLONG llPosition, LONG lLength, BYTE *pBuffer)\n{\n if (!pBuffer) {\n return E_POINTER;\n } else {\n if (thread() == QThread::currentThread()) {\n qint64 bytesRead;\n\n return blockingRead(llPosition, lLength, pBuffer, &bytesRead);\n } else {\n QMutexLocker locker(&m_mutex);\n\n m_synchronousPosition = llPosition;\n m_synchronousLength = lLength;\n m_synchronousBuffer = pBuffer;\n\n m_loop->postEvent(this, new QEvent(QEvent::User));\n\n m_wait.wait(&m_mutex);\n\n m_synchronousBuffer = 0;\n\n return m_synchronousResult;\n }\n }\n}\n\nHRESULT DirectShowIOReader::Length(LONGLONG *pTotal, LONGLONG *pAvailable)\n{\n if (!pTotal || !pAvailable) {\n return E_POINTER;\n } else {\n QMutexLocker locker(&m_mutex);\n\n *pTotal = m_totalLength;\n *pAvailable = m_availableLength;\n\n return S_OK;\n }\n}\n\n\nHRESULT DirectShowIOReader::BeginFlush()\n{\n QMutexLocker locker(&m_mutex);\n\n if (m_flushing)\n return S_FALSE;\n\n m_flushing = true;\n\n flushRequests();\n\n m_wait.wakeAll();\n\n return S_OK;\n}\n\nHRESULT DirectShowIOReader::EndFlush()\n{\n QMutexLocker locker(&m_mutex);\n\n if (!m_flushing)\n return S_FALSE;\n\n m_flushing = false;\n\n return S_OK;\n}\n\nvoid DirectShowIOReader::customEvent(QEvent *event)\n{\n if (event->type() == QEvent::User) {\n readyRead();\n } else {\n QObject::customEvent(event);\n }\n}\n\nvoid DirectShowIOReader::readyRead()\n{\n QMutexLocker locker(&m_mutex);\n\n m_availableLength = m_device->bytesAvailable() + m_device->pos();\n m_totalLength = m_device->size();\n\n if (m_synchronousBuffer) {\n if (nonBlockingRead(\n m_synchronousPosition,\n m_synchronousLength,\n m_synchronousBuffer,\n &m_synchronousBytesRead,\n &m_synchronousResult)) {\n m_wait.wakeAll();\n }\n } else {\n qint64 bytesRead = 0;\n\n while (m_pendingHead && nonBlockingRead(\n m_pendingHead->position,\n m_pendingHead->length,\n m_pendingHead->buffer,\n &bytesRead,\n &m_pendingHead->result)) {\n m_pendingHead->sample->SetActualDataLength(bytesRead);\n\n if (m_readyTail)\n m_readyTail->next = m_pendingHead;\n m_readyTail = m_pendingHead;\n\n m_pendingHead = m_pendingHead->next;\n\n m_readyTail->next = 0;\n\n if (!m_pendingHead)\n m_pendingTail = 0;\n\n if (!m_readyHead)\n m_readyHead = m_readyTail;\n\n m_wait.wakeAll();\n }\n }\n}\n\nHRESULT DirectShowIOReader::blockingRead(\n LONGLONG position, LONG length, BYTE *buffer, qint64 *bytesRead)\n{\n *bytesRead = 0;\n\n if (qint64(position) > m_device->size())\n return S_FALSE;\n\n const qint64 maxSize = qMin(m_device->size(), position + length);\n\n while (m_device->bytesAvailable() + m_device->pos() < maxSize) {\n if (!m_device->waitForReadyRead(-1))\n return S_FALSE;\n }\n\n if (m_device->pos() != position && !m_device->seek(position))\n return S_FALSE;\n\n const qint64 maxBytes = qMin(length, m_device->bytesAvailable());\n\n *bytesRead = m_device->read(reinterpret_cast(buffer), maxBytes);\n\n if (*bytesRead != length) {\n qMemSet(buffer + *bytesRead, 0, length - *bytesRead);\n\n return S_FALSE;\n } else {\n return S_OK;\n }\n}\n\nbool DirectShowIOReader::nonBlockingRead(\n LONGLONG position, LONG length, BYTE *buffer, qint64 *bytesRead, HRESULT *result)\n{\n const qint64 maxSize = qMin(m_device->size(), position + length);\n\n if (position > m_device->size()) {\n *bytesRead = 0;\n *result = S_FALSE;\n\n return true;\n } else if (m_device->bytesAvailable() + m_device->pos() >= maxSize) {\n if (m_device->pos() != position && !m_device->seek(position)) {\n *bytesRead = 0;\n *result = S_FALSE;\n\n return true;\n } else {\n const qint64 maxBytes = qMin(length, m_device->bytesAvailable());\n\n *bytesRead = m_device->read(reinterpret_cast(buffer), maxBytes);\n\n if (*bytesRead != length) {\n qMemSet(buffer + *bytesRead, 0, length - *bytesRead);\n\n *result = S_FALSE;\n } else {\n *result = S_OK;\n }\n\n return true;\n }\n } else {\n return false;\n }\n}\n\nvoid DirectShowIOReader::flushRequests()\n{\n while (m_pendingHead) {\n m_pendingHead->result = VFW_E_WRONG_STATE;\n\n if (m_readyTail)\n m_readyTail->next = m_pendingHead;\n\n m_readyTail = m_pendingHead;\n\n m_pendingHead = m_pendingHead->next;\n\n m_readyTail->next = 0;\n\n if (!m_pendingHead)\n m_pendingTail = 0;\n\n if (!m_readyHead)\n m_readyHead = m_readyTail;\n }\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkUnicodeString.cxx\n \n-------------------------------------------------------------------------\n Copyright 2008 Sandia Corporation.\n Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,\n the U.S. Government retains certain rights in this software.\n-------------------------------------------------------------------------\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\n#include \"vtkUnicodeString.h\"\n\n#include \n#include \n\n#include \n#include \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ vtkUnicodeString::const_iterator\n\nvtkUnicodeString::const_iterator::const_iterator()\n{\n}\n\nvtkUnicodeString::const_iterator::const_iterator(vtkstd::string::const_iterator position) :\n Position(position)\n{\n}\n\nvtkUnicodeString::value_type vtkUnicodeString::const_iterator::operator*() const\n{\n return vtk_utf8::unchecked::peek_next(this->Position);\n}\n\nbool vtkUnicodeString::const_iterator::operator==(const const_iterator& rhs) const\n{\n return this->Position == rhs.Position;\n}\n\nbool vtkUnicodeString::const_iterator::operator!=(const const_iterator& rhs) const\n{\n return !(*this == rhs);\n}\n\nvtkUnicodeString::const_iterator& vtkUnicodeString::const_iterator::operator++()\n{\n vtk_utf8::unchecked::next(this->Position);\n return *this;\n}\n\nvtkUnicodeString::const_iterator vtkUnicodeString::const_iterator::operator++(int)\n{\n const_iterator result(this->Position);\n vtk_utf8::unchecked::next(this->Position);\n return result;\n}\n\nvtkUnicodeString::const_iterator& vtkUnicodeString::const_iterator::operator--()\n{\n vtk_utf8::unchecked::prior(this->Position);\n return *this;\n}\n\nvtkUnicodeString::const_iterator vtkUnicodeString::const_iterator::operator--(int)\n{\n const_iterator result(this->Position);\n vtk_utf8::unchecked::prior(this->Position);\n return result;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ vtkUnicodeString::back_insert_iterator\n\n\/\/ We provide our own implementation of vtkstd::back_insert_iterator for\n\/\/ use with MSVC 6, where push_back() isn't implemented for vtkstd::string.\n\nclass vtkUnicodeString::back_insert_iterator\n{\npublic:\n back_insert_iterator(vtkstd::string& container) :\n Container(&container)\n {\n }\n\n back_insert_iterator& operator*()\n {\n return *this;\n }\n\n back_insert_iterator& operator++()\n {\n return *this;\n }\n\n back_insert_iterator& operator++(int)\n {\n return *this;\n }\n\n back_insert_iterator& operator=(vtkstd::string::const_reference value)\n {\n#if defined(_MSC_VER) && (_MSC_VER < 1300) \/\/ MSVC 6\n this->Container->append(1, value);\n#else\n this->Container->push_back(value);\n#endif\n return *this;\n }\n\nprivate:\n vtkstd::string* Container;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ vtkUnicodeString\n\nvtkUnicodeString::vtkUnicodeString()\n{\n}\n\nvtkUnicodeString::vtkUnicodeString(const vtkUnicodeString& rhs) :\n Storage(rhs.Storage)\n{\n}\n\nvtkUnicodeString::vtkUnicodeString(size_type count, value_type character)\n{\n for(size_type i = 0; i != count; ++i)\n vtk_utf8::append(character, vtkUnicodeString::back_insert_iterator(this->Storage));\n}\n\nvtkUnicodeString::vtkUnicodeString(const_iterator first, const_iterator last) :\n Storage(first.Position, last.Position)\n{\n}\n\nbool vtkUnicodeString::is_utf8(const char* value)\n{\n return vtkUnicodeString::is_utf8(vtkstd::string(value ? value : \"\"));\n}\n\nbool vtkUnicodeString::is_utf8(const vtkstd::string& value)\n{\n return vtk_utf8::is_valid(value.begin(), value.end());\n}\n\nvtkUnicodeString vtkUnicodeString::from_utf8(const char* value)\n{\n return vtkUnicodeString::from_utf8(vtkstd::string(value ? value : \"\"));\n}\n\nvtkUnicodeString vtkUnicodeString::from_utf8(const char* begin, const char* end)\n{\n vtkUnicodeString result;\n if(vtk_utf8::is_valid(begin, end))\n {\n result.Storage = vtkstd::string(begin, end);\n }\n else\n {\n vtkGenericWarningMacro(\"vtkUnicodeString::from_utf8(): not a valid UTF-8 string.\");\n }\n return result;\n}\n\nvtkUnicodeString vtkUnicodeString::from_utf8(const vtkstd::string& value)\n{\n vtkUnicodeString result;\n if(vtk_utf8::is_valid(value.begin(), value.end()))\n {\n result.Storage = value;\n }\n else\n {\n vtkGenericWarningMacro(\"vtkUnicodeString::from_utf8(): not a valid UTF-8 string.\");\n }\n return result;\n}\n\nvtkUnicodeString vtkUnicodeString::from_utf16(const vtkTypeUInt16* value)\n{\n vtkUnicodeString result;\n\n if(value)\n {\n size_type length = 0;\n while(value[length])\n ++length;\n\n try\n {\n vtk_utf8::utf16to8(value, value + length, vtkUnicodeString::back_insert_iterator(result.Storage));\n }\n catch(vtk_utf8::invalid_utf16&)\n {\n vtkGenericWarningMacro(<< \"vtkUnicodeString::from_utf16(): not a valid UTF-16 string.\");\n }\n }\n\n return result;\n}\n\nvtkUnicodeString& vtkUnicodeString::operator=(const vtkUnicodeString& rhs)\n{\n if(this == &rhs)\n return *this;\n\n this->Storage = rhs.Storage;\n return *this;\n}\n\nvtkUnicodeString::const_iterator vtkUnicodeString::begin() const\n{\n return const_iterator(this->Storage.begin());\n}\n\nvtkUnicodeString::const_iterator vtkUnicodeString::end() const\n{\n return const_iterator(this->Storage.end());\n}\n\nvtkUnicodeString::value_type vtkUnicodeString::at(size_type offset) const\n{\n if(offset >= this->character_count())\n throw vtkstd::out_of_range(\"character out-of-range\");\n\n vtkstd::string::const_iterator iterator = this->Storage.begin();\n vtk_utf8::unchecked::advance(iterator, offset);\n return vtk_utf8::unchecked::peek_next(iterator);\n}\n\nvtkUnicodeString::value_type vtkUnicodeString::operator[](size_type offset) const\n{\n vtkstd::string::const_iterator iterator = this->Storage.begin();\n vtk_utf8::unchecked::advance(iterator, offset);\n return vtk_utf8::unchecked::peek_next(iterator);\n}\n\nconst char* vtkUnicodeString::utf8_str() const\n{\n return this->Storage.c_str();\n}\n\nvoid vtkUnicodeString::utf8_str(vtkstd::string& result) const\n{\n result = this->Storage;\n}\n\nvtkstd::vector vtkUnicodeString::utf16_str() const\n{\n vtkstd::vector result;\n vtk_utf8::unchecked::utf8to16(this->Storage.begin(), this->Storage.end(), vtkstd::back_inserter(result));\n return result;\n}\n\nvoid vtkUnicodeString::utf16_str(vtkstd::vector& result) const\n{\n result.clear();\n vtk_utf8::unchecked::utf8to16(this->Storage.begin(), this->Storage.end(), vtkstd::back_inserter(result));\n}\n\nvtkUnicodeString::size_type vtkUnicodeString::byte_count() const\n{\n return this->Storage.size();\n}\n\nvtkUnicodeString::size_type vtkUnicodeString::character_count() const\n{\n return vtk_utf8::unchecked::distance(this->Storage.begin(), this->Storage.end());\n}\n\nbool vtkUnicodeString::empty() const\n{\n return this->Storage.empty();\n}\n\nconst vtkUnicodeString::size_type vtkUnicodeString::npos = vtkstd::string::npos;\n\nvtkUnicodeString& vtkUnicodeString::operator+=(value_type value)\n{\n this->push_back(value);\n return *this;\n}\n\nvtkUnicodeString& vtkUnicodeString::operator+=(const vtkUnicodeString& rhs)\n{\n this->append(rhs);\n return *this;\n}\n\nvoid vtkUnicodeString::push_back(value_type character)\n{\n try\n {\n vtk_utf8::append(character, vtkUnicodeString::back_insert_iterator(this->Storage));\n }\n catch(vtk_utf8::invalid_code_point&)\n {\n vtkGenericWarningMacro(\"vtkUnicodeString::push_back(): \" << character << \"is not a valid Unicode code point\");\n }\n}\n\nvoid vtkUnicodeString::append(const vtkUnicodeString& value)\n{\n this->Storage.append(value.Storage);\n}\n\nvoid vtkUnicodeString::append(size_type count, value_type character)\n{\n try\n {\n this->Storage.append(vtkUnicodeString(count, character).Storage);\n }\n catch(vtk_utf8::invalid_code_point&)\n {\n vtkGenericWarningMacro(\"vtkUnicodeString::append(): \" << character << \"is not a valid Unicode code point\");\n }\n}\n\nvoid vtkUnicodeString::append(const_iterator first, const_iterator last)\n{\n#ifdef __BORLANDC__\n this->Storage.append(first.Position, last.Position - first.Position);\n#else\n this->Storage.append(first.Position, last.Position);\n#endif\n}\n\nvoid vtkUnicodeString::assign(const vtkUnicodeString& value)\n{\n this->Storage.assign(value.Storage);\n}\n\nvoid vtkUnicodeString::assign(size_type count, value_type character)\n{\n try\n {\n this->Storage.assign(vtkUnicodeString(count, character).Storage);\n }\n catch(vtk_utf8::invalid_code_point&)\n {\n vtkGenericWarningMacro(\"vtkUnicodeString::assign(): \" << character << \"is not a valid Unicode code point\");\n }\n}\n\nvoid vtkUnicodeString::assign(const_iterator first, const_iterator last)\n{\n#ifdef __BORLANDC__\n this->Storage.assign(first.Position, last.Position - first.Position);\n#else\n this->Storage.assign(first.Position, last.Position);\n#endif\n}\n\nvoid vtkUnicodeString::clear()\n{\n \/\/ We use erase() because MSVC 6 doesn't provide clear() ...\n this->Storage.erase(this->Storage.begin(), this->Storage.end());\n}\n\nvtkUnicodeString vtkUnicodeString::fold_case() const\n{\n typedef vtkstd::map map_t;\n\n static map_t map;\n if(map.empty())\n {\n #include \n\n for(value_type* i = &vtkUnicodeCaseFoldData[0]; *i; ++i)\n {\n const value_type code = *i;\n vtkUnicodeString mapping;\n for(++i; *i; ++i)\n {\n mapping.push_back(*i);\n }\n map.insert(vtkstd::make_pair(code, mapping));\n }\n }\n \n vtkUnicodeString result;\n\n for(vtkUnicodeString::const_iterator source = this->begin(); source != this->end(); ++source)\n {\n map_t::const_iterator target = map.find(*source);\n if(target != map.end())\n {\n result.append(target->second);\n }\n else\n {\n result.push_back(*source);\n }\n }\n\n return result;\n}\n\nint vtkUnicodeString::compare(const vtkUnicodeString& rhs) const\n{\n return this->Storage.compare(rhs.Storage);\n}\n\nvtkUnicodeString vtkUnicodeString::substr(size_type offset, size_type count) const\n{\n vtkstd::string::const_iterator from = this->Storage.begin();\n vtkstd::string::const_iterator last = this->Storage.end();\n\n while(from != last && offset--)\n vtk_utf8::unchecked::advance(from, 1);\n\n vtkstd::string::const_iterator to = from;\n while(to != last && count--)\n vtk_utf8::unchecked::advance(to, 1);\n\n return vtkUnicodeString(from, to);\n}\n\nvoid vtkUnicodeString::swap(vtkUnicodeString& rhs)\n{\n vtkstd::swap(this->Storage, rhs.Storage);\n}\n\nbool operator==(const vtkUnicodeString& lhs, const vtkUnicodeString& rhs)\n{\n return lhs.compare(rhs) == 0;\n}\n\nbool operator!=(const vtkUnicodeString& lhs, const vtkUnicodeString& rhs)\n{\n return lhs.compare(rhs) != 0;\n}\n\nbool operator<(const vtkUnicodeString& lhs, const vtkUnicodeString& rhs)\n{\n return lhs.compare(rhs) < 0;\n}\n\nbool operator<=(const vtkUnicodeString& lhs, const vtkUnicodeString& rhs)\n{\n return lhs.compare(rhs) <= 0;\n}\n\nbool operator>=(const vtkUnicodeString& lhs, const vtkUnicodeString& rhs)\n{\n return lhs.compare(rhs) >= 0;\n}\n\nbool operator>(const vtkUnicodeString& lhs, const vtkUnicodeString& rhs)\n{\n return lhs.compare(rhs) > 0;\n}\nCOMP: fix ifdefs to accomodate bcc58.\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkUnicodeString.cxx\n \n-------------------------------------------------------------------------\n Copyright 2008 Sandia Corporation.\n Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,\n the U.S. Government retains certain rights in this software.\n-------------------------------------------------------------------------\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\n#include \"vtkUnicodeString.h\"\n\n#include \n#include \n\n#include \n#include \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ vtkUnicodeString::const_iterator\n\nvtkUnicodeString::const_iterator::const_iterator()\n{\n}\n\nvtkUnicodeString::const_iterator::const_iterator(vtkstd::string::const_iterator position) :\n Position(position)\n{\n}\n\nvtkUnicodeString::value_type vtkUnicodeString::const_iterator::operator*() const\n{\n return vtk_utf8::unchecked::peek_next(this->Position);\n}\n\nbool vtkUnicodeString::const_iterator::operator==(const const_iterator& rhs) const\n{\n return this->Position == rhs.Position;\n}\n\nbool vtkUnicodeString::const_iterator::operator!=(const const_iterator& rhs) const\n{\n return !(*this == rhs);\n}\n\nvtkUnicodeString::const_iterator& vtkUnicodeString::const_iterator::operator++()\n{\n vtk_utf8::unchecked::next(this->Position);\n return *this;\n}\n\nvtkUnicodeString::const_iterator vtkUnicodeString::const_iterator::operator++(int)\n{\n const_iterator result(this->Position);\n vtk_utf8::unchecked::next(this->Position);\n return result;\n}\n\nvtkUnicodeString::const_iterator& vtkUnicodeString::const_iterator::operator--()\n{\n vtk_utf8::unchecked::prior(this->Position);\n return *this;\n}\n\nvtkUnicodeString::const_iterator vtkUnicodeString::const_iterator::operator--(int)\n{\n const_iterator result(this->Position);\n vtk_utf8::unchecked::prior(this->Position);\n return result;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ vtkUnicodeString::back_insert_iterator\n\n\/\/ We provide our own implementation of vtkstd::back_insert_iterator for\n\/\/ use with MSVC 6, where push_back() isn't implemented for vtkstd::string.\n\nclass vtkUnicodeString::back_insert_iterator\n{\npublic:\n back_insert_iterator(vtkstd::string& container) :\n Container(&container)\n {\n }\n\n back_insert_iterator& operator*()\n {\n return *this;\n }\n\n back_insert_iterator& operator++()\n {\n return *this;\n }\n\n back_insert_iterator& operator++(int)\n {\n return *this;\n }\n\n back_insert_iterator& operator=(vtkstd::string::const_reference value)\n {\n#if defined(_MSC_VER) && (_MSC_VER < 1300) \/\/ MSVC 6\n this->Container->append(1, value);\n#else\n this->Container->push_back(value);\n#endif\n return *this;\n }\n\nprivate:\n vtkstd::string* Container;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ vtkUnicodeString\n\nvtkUnicodeString::vtkUnicodeString()\n{\n}\n\nvtkUnicodeString::vtkUnicodeString(const vtkUnicodeString& rhs) :\n Storage(rhs.Storage)\n{\n}\n\nvtkUnicodeString::vtkUnicodeString(size_type count, value_type character)\n{\n for(size_type i = 0; i != count; ++i)\n vtk_utf8::append(character, vtkUnicodeString::back_insert_iterator(this->Storage));\n}\n\nvtkUnicodeString::vtkUnicodeString(const_iterator first, const_iterator last) :\n Storage(first.Position, last.Position)\n{\n}\n\nbool vtkUnicodeString::is_utf8(const char* value)\n{\n return vtkUnicodeString::is_utf8(vtkstd::string(value ? value : \"\"));\n}\n\nbool vtkUnicodeString::is_utf8(const vtkstd::string& value)\n{\n return vtk_utf8::is_valid(value.begin(), value.end());\n}\n\nvtkUnicodeString vtkUnicodeString::from_utf8(const char* value)\n{\n return vtkUnicodeString::from_utf8(vtkstd::string(value ? value : \"\"));\n}\n\nvtkUnicodeString vtkUnicodeString::from_utf8(const char* begin, const char* end)\n{\n vtkUnicodeString result;\n if(vtk_utf8::is_valid(begin, end))\n {\n result.Storage = vtkstd::string(begin, end);\n }\n else\n {\n vtkGenericWarningMacro(\"vtkUnicodeString::from_utf8(): not a valid UTF-8 string.\");\n }\n return result;\n}\n\nvtkUnicodeString vtkUnicodeString::from_utf8(const vtkstd::string& value)\n{\n vtkUnicodeString result;\n if(vtk_utf8::is_valid(value.begin(), value.end()))\n {\n result.Storage = value;\n }\n else\n {\n vtkGenericWarningMacro(\"vtkUnicodeString::from_utf8(): not a valid UTF-8 string.\");\n }\n return result;\n}\n\nvtkUnicodeString vtkUnicodeString::from_utf16(const vtkTypeUInt16* value)\n{\n vtkUnicodeString result;\n\n if(value)\n {\n size_type length = 0;\n while(value[length])\n ++length;\n\n try\n {\n vtk_utf8::utf16to8(value, value + length, vtkUnicodeString::back_insert_iterator(result.Storage));\n }\n catch(vtk_utf8::invalid_utf16&)\n {\n vtkGenericWarningMacro(<< \"vtkUnicodeString::from_utf16(): not a valid UTF-16 string.\");\n }\n }\n\n return result;\n}\n\nvtkUnicodeString& vtkUnicodeString::operator=(const vtkUnicodeString& rhs)\n{\n if(this == &rhs)\n return *this;\n\n this->Storage = rhs.Storage;\n return *this;\n}\n\nvtkUnicodeString::const_iterator vtkUnicodeString::begin() const\n{\n return const_iterator(this->Storage.begin());\n}\n\nvtkUnicodeString::const_iterator vtkUnicodeString::end() const\n{\n return const_iterator(this->Storage.end());\n}\n\nvtkUnicodeString::value_type vtkUnicodeString::at(size_type offset) const\n{\n if(offset >= this->character_count())\n throw vtkstd::out_of_range(\"character out-of-range\");\n\n vtkstd::string::const_iterator iterator = this->Storage.begin();\n vtk_utf8::unchecked::advance(iterator, offset);\n return vtk_utf8::unchecked::peek_next(iterator);\n}\n\nvtkUnicodeString::value_type vtkUnicodeString::operator[](size_type offset) const\n{\n vtkstd::string::const_iterator iterator = this->Storage.begin();\n vtk_utf8::unchecked::advance(iterator, offset);\n return vtk_utf8::unchecked::peek_next(iterator);\n}\n\nconst char* vtkUnicodeString::utf8_str() const\n{\n return this->Storage.c_str();\n}\n\nvoid vtkUnicodeString::utf8_str(vtkstd::string& result) const\n{\n result = this->Storage;\n}\n\nvtkstd::vector vtkUnicodeString::utf16_str() const\n{\n vtkstd::vector result;\n vtk_utf8::unchecked::utf8to16(this->Storage.begin(), this->Storage.end(), vtkstd::back_inserter(result));\n return result;\n}\n\nvoid vtkUnicodeString::utf16_str(vtkstd::vector& result) const\n{\n result.clear();\n vtk_utf8::unchecked::utf8to16(this->Storage.begin(), this->Storage.end(), vtkstd::back_inserter(result));\n}\n\nvtkUnicodeString::size_type vtkUnicodeString::byte_count() const\n{\n return this->Storage.size();\n}\n\nvtkUnicodeString::size_type vtkUnicodeString::character_count() const\n{\n return vtk_utf8::unchecked::distance(this->Storage.begin(), this->Storage.end());\n}\n\nbool vtkUnicodeString::empty() const\n{\n return this->Storage.empty();\n}\n\nconst vtkUnicodeString::size_type vtkUnicodeString::npos = vtkstd::string::npos;\n\nvtkUnicodeString& vtkUnicodeString::operator+=(value_type value)\n{\n this->push_back(value);\n return *this;\n}\n\nvtkUnicodeString& vtkUnicodeString::operator+=(const vtkUnicodeString& rhs)\n{\n this->append(rhs);\n return *this;\n}\n\nvoid vtkUnicodeString::push_back(value_type character)\n{\n try\n {\n vtk_utf8::append(character, vtkUnicodeString::back_insert_iterator(this->Storage));\n }\n catch(vtk_utf8::invalid_code_point&)\n {\n vtkGenericWarningMacro(\"vtkUnicodeString::push_back(): \" << character << \"is not a valid Unicode code point\");\n }\n}\n\nvoid vtkUnicodeString::append(const vtkUnicodeString& value)\n{\n this->Storage.append(value.Storage);\n}\n\nvoid vtkUnicodeString::append(size_type count, value_type character)\n{\n try\n {\n this->Storage.append(vtkUnicodeString(count, character).Storage);\n }\n catch(vtk_utf8::invalid_code_point&)\n {\n vtkGenericWarningMacro(\"vtkUnicodeString::append(): \" << character << \"is not a valid Unicode code point\");\n }\n}\n\nvoid vtkUnicodeString::append(const_iterator first, const_iterator last)\n{\n#if defined (__BORLANDC__) && (__BORLANDC__ < 0x0580)\n this->Storage.append(first.Position, last.Position - first.Position);\n#else\n this->Storage.append(first.Position, last.Position);\n#endif\n}\n\nvoid vtkUnicodeString::assign(const vtkUnicodeString& value)\n{\n this->Storage.assign(value.Storage);\n}\n\nvoid vtkUnicodeString::assign(size_type count, value_type character)\n{\n try\n {\n this->Storage.assign(vtkUnicodeString(count, character).Storage);\n }\n catch(vtk_utf8::invalid_code_point&)\n {\n vtkGenericWarningMacro(\"vtkUnicodeString::assign(): \" << character << \"is not a valid Unicode code point\");\n }\n}\n\nvoid vtkUnicodeString::assign(const_iterator first, const_iterator last)\n{\n#if defined (__BORLANDC__) && (__BORLANDC__ < 0x0580)\n this->Storage.assign(first.Position, last.Position - first.Position);\n#else\n this->Storage.assign(first.Position, last.Position);\n#endif\n}\n\nvoid vtkUnicodeString::clear()\n{\n \/\/ We use erase() because MSVC 6 doesn't provide clear() ...\n this->Storage.erase(this->Storage.begin(), this->Storage.end());\n}\n\nvtkUnicodeString vtkUnicodeString::fold_case() const\n{\n typedef vtkstd::map map_t;\n\n static map_t map;\n if(map.empty())\n {\n #include \n\n for(value_type* i = &vtkUnicodeCaseFoldData[0]; *i; ++i)\n {\n const value_type code = *i;\n vtkUnicodeString mapping;\n for(++i; *i; ++i)\n {\n mapping.push_back(*i);\n }\n map.insert(vtkstd::make_pair(code, mapping));\n }\n }\n \n vtkUnicodeString result;\n\n for(vtkUnicodeString::const_iterator source = this->begin(); source != this->end(); ++source)\n {\n map_t::const_iterator target = map.find(*source);\n if(target != map.end())\n {\n result.append(target->second);\n }\n else\n {\n result.push_back(*source);\n }\n }\n\n return result;\n}\n\nint vtkUnicodeString::compare(const vtkUnicodeString& rhs) const\n{\n return this->Storage.compare(rhs.Storage);\n}\n\nvtkUnicodeString vtkUnicodeString::substr(size_type offset, size_type count) const\n{\n vtkstd::string::const_iterator from = this->Storage.begin();\n vtkstd::string::const_iterator last = this->Storage.end();\n\n while(from != last && offset--)\n vtk_utf8::unchecked::advance(from, 1);\n\n vtkstd::string::const_iterator to = from;\n while(to != last && count--)\n vtk_utf8::unchecked::advance(to, 1);\n\n return vtkUnicodeString(from, to);\n}\n\nvoid vtkUnicodeString::swap(vtkUnicodeString& rhs)\n{\n vtkstd::swap(this->Storage, rhs.Storage);\n}\n\nbool operator==(const vtkUnicodeString& lhs, const vtkUnicodeString& rhs)\n{\n return lhs.compare(rhs) == 0;\n}\n\nbool operator!=(const vtkUnicodeString& lhs, const vtkUnicodeString& rhs)\n{\n return lhs.compare(rhs) != 0;\n}\n\nbool operator<(const vtkUnicodeString& lhs, const vtkUnicodeString& rhs)\n{\n return lhs.compare(rhs) < 0;\n}\n\nbool operator<=(const vtkUnicodeString& lhs, const vtkUnicodeString& rhs)\n{\n return lhs.compare(rhs) <= 0;\n}\n\nbool operator>=(const vtkUnicodeString& lhs, const vtkUnicodeString& rhs)\n{\n return lhs.compare(rhs) >= 0;\n}\n\nbool operator>(const vtkUnicodeString& lhs, const vtkUnicodeString& rhs)\n{\n return lhs.compare(rhs) > 0;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\nusing namespace std;\nusing namespace cv;\n\nstatic void help()\n{\n cout << \"\\n This program demonstrates how to detect compute and match ORB BRISK and AKAZE descriptors \\n\"\n \"Usage: \\n\"\n \" .\/matchmethod_orb_akaze_brisk \\n\"\n \"Press a key when image window is active to change algorithm or descriptor\";\n}\n\n\n\nint main(int argc, char *argv[])\n{\n vector typeDesc;\n vector typeAlgoMatch;\n vector fileName;\n help();\n \/\/ This descriptor are going to be detect and compute\n typeDesc.push_back(\"AKAZE-DESCRIPTOR_KAZE_UPRIGHT\"); \/\/ see http:\/\/docs.opencv.org\/trunk\/d8\/d30\/classcv_1_1AKAZE.html\n typeDesc.push_back(\"AKAZE\"); \/\/ see http:\/\/docs.opencv.org\/trunk\/d8\/d30\/classcv_1_1AKAZE.html\n typeDesc.push_back(\"ORB\"); \/\/ see http:\/\/docs.opencv.org\/trunk\/de\/dbf\/classcv_1_1BRISK.html\n typeDesc.push_back(\"BRISK\"); \/\/ see http:\/\/docs.opencv.org\/trunk\/db\/d95\/classcv_1_1ORB.html\n \/\/ This algorithm would be used to match descriptors see http:\/\/docs.opencv.org\/trunk\/db\/d39\/classcv_1_1DescriptorMatcher.html#ab5dc5036569ecc8d47565007fa518257\n typeAlgoMatch.push_back(\"BruteForce\");\n typeAlgoMatch.push_back(\"BruteForce-L1\");\n typeAlgoMatch.push_back(\"BruteForce-Hamming\");\n typeAlgoMatch.push_back(\"BruteForce-Hamming(2)\");\n if (argc==1)\n {\n fileName.push_back(\"..\/data\/basketball1.png\");\n fileName.push_back(\"..\/data\/basketball2.png\");\n }\n else if (argc==3)\n {\n fileName.push_back(argv[1]);\n fileName.push_back(argv[2]);\n }\n else\n {\n help();\n return(0);\n }\n Mat img1 = imread(fileName[0], IMREAD_GRAYSCALE);\n Mat img2 = imread(fileName[1], IMREAD_GRAYSCALE);\n if (img1.rows*img1.cols <= 0)\n {\n cout << \"Image \" << fileName[0] << \" is empty or cannot be found\\n\";\n return(0);\n }\n if (img2.rows*img2.cols <= 0)\n {\n cout << \"Image \" << fileName[1] << \" is empty or cannot be found\\n\";\n return(0);\n }\n\n vector desMethCmp;\n Ptr b;\n\n \/\/ Descriptor loop\n vector::iterator itDesc;\n for (itDesc = typeDesc.begin(); itDesc != typeDesc.end(); itDesc++)\n {\n Ptr descriptorMatcher;\n \/\/ Match between img1 and img2\n vector matches;\n \/\/ keypoint for img1 and img2\n vector keyImg1, keyImg2;\n \/\/ Descriptor for img1 and img2\n Mat descImg1, descImg2;\n vector::iterator itMatcher = typeAlgoMatch.end();\n if (*itDesc == \"AKAZE-DESCRIPTOR_KAZE_UPRIGHT\"){\n b = AKAZE::create(AKAZE::DESCRIPTOR_KAZE_UPRIGHT);\n }\n if (*itDesc == \"AKAZE\"){\n b = AKAZE::create();\n }\n if (*itDesc == \"ORB\"){\n b = ORB::create();\n }\n else if (*itDesc == \"BRISK\"){\n b = BRISK::create();\n }\n try {\n \/\/ We can detect keypoint with detect method\n b->detect(img1, keyImg1, Mat());\n \/\/ and compute their descriptors with method compute\n b->compute(img1, keyImg1, descImg1);\n \/\/ or detect and compute descriptors in one step\n b->detectAndCompute(img2, Mat(),keyImg2, descImg2,false);\n \/\/ Match method loop\n for (itMatcher = typeAlgoMatch.begin(); itMatcher != typeAlgoMatch.end(); itMatcher++){\n descriptorMatcher = DescriptorMatcher::create(*itMatcher);\n if ((*itMatcher == \"BruteForce-Hamming\" || *itMatcher == \"BruteForce-Hamming(2)\") && (b->descriptorType() == CV_32F || b->defaultNorm() <= NORM_L2SQR) )\n {\n cout << \"**************************************************************************\\n\";\n cout << \"It's strange. You should use Hamming distance only for a binary descriptor\\n\";\n cout << \"**************************************************************************\\n\";\n }\n try \n {\n descriptorMatcher->match(descImg1, descImg2, matches, Mat());\n \/\/ Keep best matches only to have a nice drawing.\n \/\/ We sort distance between descriptor matches\n Mat index;\n int nbMatch=int(matches.size());\n Mat tab(nbMatch, 1, CV_32F);\n for (int i = 0; i(i, 0) = matches[i].distance;\n }\n sortIdx(tab, index, SORT_EVERY_COLUMN + SORT_ASCENDING);\n vector bestMatches;\n for (int i = 0; i<30; i++)\n {\n bestMatches.push_back(matches[index.at(i, 0)]);\n }\n Mat result;\n drawMatches(img1, keyImg1, img2, keyImg2, bestMatches, result);\n namedWindow(*itDesc+\": \"+*itMatcher, WINDOW_AUTOSIZE);\n imshow(*itDesc + \": \" + *itMatcher, result);\n \/\/ Saved result could be wrong due to bug 4308\n FileStorage fs(*itDesc + \"_\" + *itMatcher + \".yml\", FileStorage::WRITE);\n fs<<\"Matches\"<::iterator it;\n cout<<\"**********Match results**********\\n\";\n cout << \"Index \\tIndex \\tdistance\\n\";\n cout << \"in img1\\tin img2\\n\";\n \/\/ Use to compute distance between keyPoint matches and to evaluate match algorithm\n double cumSumDist2=0;\n for (it = bestMatches.begin(); it != bestMatches.end(); it++)\n {\n cout << it->queryIdx << \"\\t\" << it->trainIdx << \"\\t\" << it->distance << \"\\n\";\n Point2d p=keyImg1[it->queryIdx].pt-keyImg2[it->trainIdx].pt;\n cumSumDist2=p.x*p.x+p.y*p.y;\n }\n desMethCmp.push_back(cumSumDist2);\n waitKey();\n }\n catch (Exception& e)\n {\n desMethCmp.push_back(-1);\n }\n }\n }\n catch (Exception& e)\n {\n cout << \"Feature : \" << *itDesc << \"\\n\";\n if (itMatcher != typeAlgoMatch.end())\n {\n cout << \"Matcher : \" << *itMatcher << \"\\n\";\n }\n cout << e.msg << endl;\n }\n }\n int i=0;\n cout << \"Cumulative distance between keypoint match for different algorithm and feature detector \\n\\t\";\n cout << \"We cannot say which is the best but we can say results are differents! \\n\\t\";\n for (vector::iterator itMatcher = typeAlgoMatch.begin(); itMatcher != typeAlgoMatch.end(); itMatcher++)\n {\n cout<<*itMatcher<<\"\\t\";\n }\n cout << \"\\n\";\n for (itDesc = typeDesc.begin(); itDesc != typeDesc.end(); itDesc++)\n {\n cout << *itDesc << \"\\t\";\n for (vector::iterator itMatcher = typeAlgoMatch.begin(); itMatcher != typeAlgoMatch.end(); itMatcher++, i++)\n {\n cout << desMethCmp[i]<<\"\\t\";\n }\n cout<<\"\\n\";\n }\n return 0;\n}\ntrailing whitespace#include \n#include \n#include \n\nusing namespace std;\nusing namespace cv;\n\nstatic void help()\n{\n cout << \"\\n This program demonstrates how to detect compute and match ORB BRISK and AKAZE descriptors \\n\"\n \"Usage: \\n\"\n \" .\/matchmethod_orb_akaze_brisk \\n\"\n \"Press a key when image window is active to change algorithm or descriptor\";\n}\n\n\n\nint main(int argc, char *argv[])\n{\n vector typeDesc;\n vector typeAlgoMatch;\n vector fileName;\n help();\n \/\/ This descriptor are going to be detect and compute\n typeDesc.push_back(\"AKAZE-DESCRIPTOR_KAZE_UPRIGHT\"); \/\/ see http:\/\/docs.opencv.org\/trunk\/d8\/d30\/classcv_1_1AKAZE.html\n typeDesc.push_back(\"AKAZE\"); \/\/ see http:\/\/docs.opencv.org\/trunk\/d8\/d30\/classcv_1_1AKAZE.html\n typeDesc.push_back(\"ORB\"); \/\/ see http:\/\/docs.opencv.org\/trunk\/de\/dbf\/classcv_1_1BRISK.html\n typeDesc.push_back(\"BRISK\"); \/\/ see http:\/\/docs.opencv.org\/trunk\/db\/d95\/classcv_1_1ORB.html\n \/\/ This algorithm would be used to match descriptors see http:\/\/docs.opencv.org\/trunk\/db\/d39\/classcv_1_1DescriptorMatcher.html#ab5dc5036569ecc8d47565007fa518257\n typeAlgoMatch.push_back(\"BruteForce\");\n typeAlgoMatch.push_back(\"BruteForce-L1\");\n typeAlgoMatch.push_back(\"BruteForce-Hamming\");\n typeAlgoMatch.push_back(\"BruteForce-Hamming(2)\");\n if (argc==1)\n {\n fileName.push_back(\"..\/data\/basketball1.png\");\n fileName.push_back(\"..\/data\/basketball2.png\");\n }\n else if (argc==3)\n {\n fileName.push_back(argv[1]);\n fileName.push_back(argv[2]);\n }\n else\n {\n help();\n return(0);\n }\n Mat img1 = imread(fileName[0], IMREAD_GRAYSCALE);\n Mat img2 = imread(fileName[1], IMREAD_GRAYSCALE);\n if (img1.rows*img1.cols <= 0)\n {\n cout << \"Image \" << fileName[0] << \" is empty or cannot be found\\n\";\n return(0);\n }\n if (img2.rows*img2.cols <= 0)\n {\n cout << \"Image \" << fileName[1] << \" is empty or cannot be found\\n\";\n return(0);\n }\n\n vector desMethCmp;\n Ptr b;\n\n \/\/ Descriptor loop\n vector::iterator itDesc;\n for (itDesc = typeDesc.begin(); itDesc != typeDesc.end(); itDesc++)\n {\n Ptr descriptorMatcher;\n \/\/ Match between img1 and img2\n vector matches;\n \/\/ keypoint for img1 and img2\n vector keyImg1, keyImg2;\n \/\/ Descriptor for img1 and img2\n Mat descImg1, descImg2;\n vector::iterator itMatcher = typeAlgoMatch.end();\n if (*itDesc == \"AKAZE-DESCRIPTOR_KAZE_UPRIGHT\"){\n b = AKAZE::create(AKAZE::DESCRIPTOR_KAZE_UPRIGHT);\n }\n if (*itDesc == \"AKAZE\"){\n b = AKAZE::create();\n }\n if (*itDesc == \"ORB\"){\n b = ORB::create();\n }\n else if (*itDesc == \"BRISK\"){\n b = BRISK::create();\n }\n try {\n \/\/ We can detect keypoint with detect method\n b->detect(img1, keyImg1, Mat());\n \/\/ and compute their descriptors with method compute\n b->compute(img1, keyImg1, descImg1);\n \/\/ or detect and compute descriptors in one step\n b->detectAndCompute(img2, Mat(),keyImg2, descImg2,false);\n \/\/ Match method loop\n for (itMatcher = typeAlgoMatch.begin(); itMatcher != typeAlgoMatch.end(); itMatcher++){\n descriptorMatcher = DescriptorMatcher::create(*itMatcher);\n if ((*itMatcher == \"BruteForce-Hamming\" || *itMatcher == \"BruteForce-Hamming(2)\") && (b->descriptorType() == CV_32F || b->defaultNorm() <= NORM_L2SQR) )\n {\n cout << \"**************************************************************************\\n\";\n cout << \"It's strange. You should use Hamming distance only for a binary descriptor\\n\";\n cout << \"**************************************************************************\\n\";\n }\n try\n {\n descriptorMatcher->match(descImg1, descImg2, matches, Mat());\n \/\/ Keep best matches only to have a nice drawing.\n \/\/ We sort distance between descriptor matches\n Mat index;\n int nbMatch=int(matches.size());\n Mat tab(nbMatch, 1, CV_32F);\n for (int i = 0; i(i, 0) = matches[i].distance;\n }\n sortIdx(tab, index, SORT_EVERY_COLUMN + SORT_ASCENDING);\n vector bestMatches;\n for (int i = 0; i<30; i++)\n {\n bestMatches.push_back(matches[index.at(i, 0)]);\n }\n Mat result;\n drawMatches(img1, keyImg1, img2, keyImg2, bestMatches, result);\n namedWindow(*itDesc+\": \"+*itMatcher, WINDOW_AUTOSIZE);\n imshow(*itDesc + \": \" + *itMatcher, result);\n \/\/ Saved result could be wrong due to bug 4308\n FileStorage fs(*itDesc + \"_\" + *itMatcher + \".yml\", FileStorage::WRITE);\n fs<<\"Matches\"<::iterator it;\n cout<<\"**********Match results**********\\n\";\n cout << \"Index \\tIndex \\tdistance\\n\";\n cout << \"in img1\\tin img2\\n\";\n \/\/ Use to compute distance between keyPoint matches and to evaluate match algorithm\n double cumSumDist2=0;\n for (it = bestMatches.begin(); it != bestMatches.end(); it++)\n {\n cout << it->queryIdx << \"\\t\" << it->trainIdx << \"\\t\" << it->distance << \"\\n\";\n Point2d p=keyImg1[it->queryIdx].pt-keyImg2[it->trainIdx].pt;\n cumSumDist2=p.x*p.x+p.y*p.y;\n }\n desMethCmp.push_back(cumSumDist2);\n waitKey();\n }\n catch (Exception& e)\n {\n desMethCmp.push_back(-1);\n }\n }\n }\n catch (Exception& e)\n {\n cout << \"Feature : \" << *itDesc << \"\\n\";\n if (itMatcher != typeAlgoMatch.end())\n {\n cout << \"Matcher : \" << *itMatcher << \"\\n\";\n }\n cout << e.msg << endl;\n }\n }\n int i=0;\n cout << \"Cumulative distance between keypoint match for different algorithm and feature detector \\n\\t\";\n cout << \"We cannot say which is the best but we can say results are differents! \\n\\t\";\n for (vector::iterator itMatcher = typeAlgoMatch.begin(); itMatcher != typeAlgoMatch.end(); itMatcher++)\n {\n cout<<*itMatcher<<\"\\t\";\n }\n cout << \"\\n\";\n for (itDesc = typeDesc.begin(); itDesc != typeDesc.end(); itDesc++)\n {\n cout << *itDesc << \"\\t\";\n for (vector::iterator itMatcher = typeAlgoMatch.begin(); itMatcher != typeAlgoMatch.end(); itMatcher++, i++)\n {\n cout << desMethCmp[i]<<\"\\t\";\n }\n cout<<\"\\n\";\n }\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/\/\n\/\/\/ @file generate.hpp\n\/\/\/\n\/\/\/ Copyright (C) 2014 Kim Walisch, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#ifndef GENERATE_HPP\n#define GENERATE_HPP\n\n#include \n\n#include \n#include \n\nnamespace primesum {\n\n\/\/\/ Generate a vector with the primes <= max.\n\/\/\/ The primes vector uses 1-indexing i.e. primes[1] = 2.\n\/\/\/\ntemplate \nstd::vector generate_primes(int64_t max)\n{\n std::vector primes;\n primes.push_back(0);\n primesieve::generate_primes(max, &primes);\n return primes;\n}\n\n\/\/\/ Generate a vector with the prime sums <= max.\n\/\/\/ The primes vector uses 1-indexing i.e. primes[1] = 2.\n\/\/\/\ntemplate \nstd::vector generate_prime_sums(int64_t max)\n{\n std::vector primes;\n primes.push_back(0);\n primesieve::generate_primes(max, &primes);\n\n for (uint64_t i = 1; i < primes.size(); i++)\n primes[i] += primes[i - 1];\n\n return primes;\n}\n\n\/\/\/ Generate a vector with the primes <= max.\n\/\/\/ The primes vector uses 1-indexing i.e. primes[1] = 2.\n\/\/\nstd::vector generate_primes(int64_t max);\n\n\/\/\/ Generate a vector with the first n primes.\n\/\/\/ The primes vector uses 1-indexing i.e. primes[1] = 2.\n\/\/\nstd::vector generate_n_primes(int64_t n);\n\n\/\/\/ Generate a vector with Möbius function values.\nstd::vector generate_moebius(int64_t max);\n\n\/\/\/ Generate a vector with the least prime\n\/\/\/ factors of the integers <= max.\n\/\/\/\nstd::vector generate_least_prime_factors(int64_t max);\n\n\/\/\/ Generate a vector with the prime counts below max\n\/\/\/ using the sieve of Eratosthenes.\n\/\/\/\nstd::vector generate_pi(int64_t max);\n\n} \/\/ namespace\n\n#endif\nRefactor using C++11\/\/\/\n\/\/\/ @file generate.hpp\n\/\/\/\n\/\/\/ Copyright (C) 2018 Kim Walisch, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#ifndef GENERATE_HPP\n#define GENERATE_HPP\n\n#include \n\n#include \n#include \n\nnamespace primesum {\n\n\/\/\/ Generate a vector with the primes <= max.\n\/\/\/ The primes vector uses 1-indexing i.e. primes[1] = 2.\n\/\/\/\ntemplate \nstd::vector generate_primes(int64_t max)\n{\n std::vector primes = { 0 };\n primesieve::generate_primes(max, &primes);\n return primes;\n}\n\n\/\/\/ Generate a vector with the prime sums <= max.\n\/\/\/ The primes vector uses 1-indexing i.e. primes[1] = 2.\n\/\/\/\ntemplate \nstd::vector generate_prime_sums(int64_t max)\n{\n std::vector primes = { 0 };\n primesieve::generate_primes(max, &primes);\n\n for (uint64_t i = 1; i < primes.size(); i++)\n primes[i] += primes[i - 1];\n\n return primes;\n}\n\n\/\/\/ Generate a vector with the primes <= max.\n\/\/\/ The primes vector uses 1-indexing i.e. primes[1] = 2.\n\/\/\nstd::vector generate_primes(int64_t max);\n\n\/\/\/ Generate a vector with the first n primes.\n\/\/\/ The primes vector uses 1-indexing i.e. primes[1] = 2.\n\/\/\nstd::vector generate_n_primes(int64_t n);\n\n\/\/\/ Generate a vector with Möbius function values.\nstd::vector generate_moebius(int64_t max);\n\n\/\/\/ Generate a vector with the least prime\n\/\/\/ factors of the integers <= max.\n\/\/\/\nstd::vector generate_least_prime_factors(int64_t max);\n\n\/\/\/ Generate a vector with the prime counts below max\n\/\/\/ using the sieve of Eratosthenes.\n\/\/\/\nstd::vector generate_pi(int64_t max);\n\n} \/\/ namespace\n\n#endif\n<|endoftext|>"} {"text":"#include \"TileCollideableGroup.hpp\"\n#include \"Tilemap.hpp\"\n#include \"comp\/TileCollisionComponent.hpp\"\n#include \"Logfile.hpp\"\n#include \n#include \n#include \n\nTileCollideableGroup::TileCollideableGroup(jd::Tilemap& tilemap):\n m_tilemap(tilemap)\n{\n}\n\nvoid TileCollideableGroup::setProxy(unsigned tileId, TileCollisionComponent* proxy)\n{\n if (!m_proxyEntities.insert(std::make_pair(tileId, proxy)).second)\n throw std::logic_error(\n __FUNCTION__ \": cannot assign proxy entity: already assigned\");\n}\n\nvoid TileCollideableGroup::setColliding(Vector3u pos, TileCollisionComponent* e)\n{\n auto const it = m_entities.find(pos);\n bool const found = it != m_entities.end();\n if (e) {\n if (found) {\n it->second->notifyOverride(pos, *e);\n it->second = e;\n } else {\n bool const success = m_entities.insert(std::make_pair(pos, e)).second;\n assert(success);\n }\n } else if (found) {\n m_entities.erase(pos);\n } else {\n LOG_W(\"Attempt to unregister a TileCollisionComponent which was not registered.\");\n }\n}\n\nvoid TileCollideableGroup::addCollisions(\n Vector3u pos, std::vector& result,\n Entity* e, sf::FloatRect const& r)\n{\n auto const iEntity = m_entities.find(pos);\n if (iEntity != m_entities.end()) {\n if (e)\n iEntity->second->notifyCollision(pos, *e, r);\n result.push_back(Collision(\n iEntity->second->parent(),\n m_tilemap.globalTileRect(sf::Vector2i(pos.x, pos.y))));\n } else {\n unsigned const tileId = m_tilemap[pos];\n auto const iProxy = m_proxyEntities.find(tileId);\n if (iProxy != m_proxyEntities.end()) {\n if (e)\n iProxy->second->notifyCollision(pos, *e, r);\n result.push_back(Collision(\n iProxy->second->parent(),\n m_tilemap.globalTileRect(sf::Vector2i(pos.x, pos.y))));\n }\n } \/\/ if no entity at pos registered\n}\n\nstd::vector TileCollideableGroup::colliding(sf::FloatRect const& r, Entity* e)\n{\n sf::Vector2u begin = static_cast(\n m_tilemap.tilePosFromGlobal(jd::topLeft(r)));\n begin.x = std::max(begin.x, 0u);\n begin.y = std::max(begin.y, 0u);\n sf::Vector2u last = static_cast(\n m_tilemap.tilePosFromGlobal(jd::bottomRight(r)));\n last.x = std::min(last.x, m_tilemap.size().x - 1);\n last.y = std::min(last.y, m_tilemap.size().y - 1);\n\n std::vector result;\n result.reserve((last.x - begin.x + 1) * (last.y - begin.y + 1));\n\n for (unsigned z = 0; z < m_tilemap.size().z; ++z) {\n for (unsigned x = begin.x; x <= last.x; ++x) {\n for (unsigned y = begin.y; y <= last.y; ++y) {\n Vector3u const pos(x, y, z);\n addCollisions(pos, result, e, r);\n } \/\/ for y\n } \/\/ for x\n } \/\/ for z\n return result;\n}\n\nnamespace {\n std::array surroundingTiles(sf::Vector2i p)\n {\n std::array result;\n std::fill(result.begin(), result.end(), p);\n\n \/\/ 012\n \/\/ 3p4\n \/\/ 567\n --result[0].x; --result[0].y;\n --result[1].y;\n ++result[2].x; --result[2].y;\n --result[3].x;\n ++result[4].x;\n --result[5].x; ++result[5].y;\n ++result[6].y;\n ++result[7].x; ++result[7].y;\n\n return result;\n }\n}\n\nstd::vector TileCollideableGroup::colliding(sf::Vector2f gp1, sf::Vector2f gp2)\n{\n sf::Vector2u p1 = static_cast(\n m_tilemap.tilePosFromGlobal(gp1));\n sf::Vector2u p2 = static_cast(\n m_tilemap.tilePosFromGlobal(gp2));\n\n std::vector result;\n\n if (!jd::clipLine(p1, p2, sf::Rect(\n 0, 0, m_tilemap.size().x, m_tilemap.size().y)))\n return result;\n\n sf::Vector2u const d = p2 - p1;\n\n result.reserve(static_cast(\n jd::math::abs(static_cast(d))));\n\n sf::Vector2u pos = p1;\n sf::Vector2u lastPos = pos;\n bool foundNext = false;\n do {\n Vector3u idx(pos.x, pos.y, 0);\n for (; idx.z < m_tilemap.size().z; ++idx.z)\n addCollisions(idx, result);\n\n auto const surrounding(surroundingTiles(\n static_cast(pos)));\n for (sf::Vector2i next : surrounding) {\n if (pos != lastPos &&\n m_tilemap.isValidPosition(jd::vec2to3(next, 0)) &&\n jd::intersection(\n p1, p2,\n sf::Rect(\n static_cast(next),\n sf::Vector2u(1, 1)))\n ) {\n lastPos = pos;\n pos = static_cast(next);\n foundNext = true;\n break;\n }\n }\n assert(foundNext);\n } while (pos != p2);\n return result;\n}\nTileCollideableGroup::setProxy: Remove proxy if nullptr is passed.#include \"TileCollideableGroup.hpp\"\n#include \"Tilemap.hpp\"\n#include \"comp\/TileCollisionComponent.hpp\"\n#include \"Logfile.hpp\"\n#include \n#include \n#include \n\nTileCollideableGroup::TileCollideableGroup(jd::Tilemap& tilemap):\n m_tilemap(tilemap)\n{\n}\n\nvoid TileCollideableGroup::setProxy(unsigned tileId, TileCollisionComponent* proxy)\n{\n if (!proxy) {\n std::size_t const erasedCount = m_proxyEntities.erase(tileId);\n assert(erasedCount < 2);\n if (!erasedCount)\n LOG_W(\"Attempt to unset a proxy, which was not set.\");\n } else if (!m_proxyEntities.insert(std::make_pair(tileId, proxy)).second)\n throw std::logic_error(\n __FUNCTION__ \": cannot assign proxy entity: already assigned\");\n}\n\nvoid TileCollideableGroup::setColliding(Vector3u pos, TileCollisionComponent* e)\n{\n auto const it = m_entities.find(pos);\n bool const found = it != m_entities.end();\n if (e) {\n if (found) {\n it->second->notifyOverride(pos, *e);\n it->second = e;\n } else {\n bool const success = m_entities.insert(std::make_pair(pos, e)).second;\n assert(success);\n }\n } else if (found) {\n m_entities.erase(pos);\n } else {\n LOG_W(\"Attempt to unregister a TileCollisionComponent which was not registered.\");\n }\n}\n\nvoid TileCollideableGroup::addCollisions(\n Vector3u pos, std::vector& result,\n Entity* e, sf::FloatRect const& r)\n{\n auto const iEntity = m_entities.find(pos);\n if (iEntity != m_entities.end()) {\n if (e)\n iEntity->second->notifyCollision(pos, *e, r);\n result.push_back(Collision(\n iEntity->second->parent(),\n m_tilemap.globalTileRect(sf::Vector2i(pos.x, pos.y))));\n } else {\n unsigned const tileId = m_tilemap[pos];\n auto const iProxy = m_proxyEntities.find(tileId);\n if (iProxy != m_proxyEntities.end()) {\n if (e)\n iProxy->second->notifyCollision(pos, *e, r);\n result.push_back(Collision(\n iProxy->second->parent(),\n m_tilemap.globalTileRect(sf::Vector2i(pos.x, pos.y))));\n }\n } \/\/ if no entity at pos registered\n}\n\nstd::vector TileCollideableGroup::colliding(sf::FloatRect const& r, Entity* e)\n{\n sf::Vector2u begin = static_cast(\n m_tilemap.tilePosFromGlobal(jd::topLeft(r)));\n begin.x = std::max(begin.x, 0u);\n begin.y = std::max(begin.y, 0u);\n sf::Vector2u last = static_cast(\n m_tilemap.tilePosFromGlobal(jd::bottomRight(r)));\n last.x = std::min(last.x, m_tilemap.size().x - 1);\n last.y = std::min(last.y, m_tilemap.size().y - 1);\n\n std::vector result;\n result.reserve((last.x - begin.x + 1) * (last.y - begin.y + 1));\n\n for (unsigned z = 0; z < m_tilemap.size().z; ++z) {\n for (unsigned x = begin.x; x <= last.x; ++x) {\n for (unsigned y = begin.y; y <= last.y; ++y) {\n Vector3u const pos(x, y, z);\n addCollisions(pos, result, e, r);\n } \/\/ for y\n } \/\/ for x\n } \/\/ for z\n return result;\n}\n\nnamespace {\n std::array surroundingTiles(sf::Vector2i p)\n {\n std::array result;\n std::fill(result.begin(), result.end(), p);\n\n \/\/ 012\n \/\/ 3p4\n \/\/ 567\n --result[0].x; --result[0].y;\n --result[1].y;\n ++result[2].x; --result[2].y;\n --result[3].x;\n ++result[4].x;\n --result[5].x; ++result[5].y;\n ++result[6].y;\n ++result[7].x; ++result[7].y;\n\n return result;\n }\n}\n\nstd::vector TileCollideableGroup::colliding(sf::Vector2f gp1, sf::Vector2f gp2)\n{\n sf::Vector2u p1 = static_cast(\n m_tilemap.tilePosFromGlobal(gp1));\n sf::Vector2u p2 = static_cast(\n m_tilemap.tilePosFromGlobal(gp2));\n\n std::vector result;\n\n if (!jd::clipLine(p1, p2, sf::Rect(\n 0, 0, m_tilemap.size().x, m_tilemap.size().y)))\n return result;\n\n sf::Vector2u const d = p2 - p1;\n\n result.reserve(static_cast(\n jd::math::abs(static_cast(d))));\n\n sf::Vector2u pos = p1;\n sf::Vector2u lastPos = pos;\n bool foundNext = false;\n do {\n Vector3u idx(pos.x, pos.y, 0);\n for (; idx.z < m_tilemap.size().z; ++idx.z)\n addCollisions(idx, result);\n\n auto const surrounding(surroundingTiles(\n static_cast(pos)));\n for (sf::Vector2i next : surrounding) {\n if (pos != lastPos &&\n m_tilemap.isValidPosition(jd::vec2to3(next, 0)) &&\n jd::intersection(\n p1, p2,\n sf::Rect(\n static_cast(next),\n sf::Vector2u(1, 1)))\n ) {\n lastPos = pos;\n pos = static_cast(next);\n foundNext = true;\n break;\n }\n }\n assert(foundNext);\n } while (pos != p2);\n return result;\n}\n<|endoftext|>"} {"text":"\n\n#include \n#include \"instance.hpp\"\n#include \"manager.hpp\"\n#include \"broker.hpp\"\n#include \"logger.hpp\"\n#include \n#include \n\nusing namespace std;\n\nnamespace cossb {\nnamespace core {\n\nbool cossb_init(const char* manifest)\n{\n\n\t\/\/1. load manifest file\n\tif(!cossb_config->load(manifest))\n\t\treturn false;\n\n\t\/\/2. create(setup) instances according to the manifest\n\tif(!cossb_system_manager->setup(cossb_config))\n\t\treturn false;\n\n\treturn true;\n}\n\nvoid cossb_destroy()\n{\n\tcossb_stop();\n\tcossb_log->log(log::loglevel::INFO, \"Now terminating...\");\n\tcossb_system_manager->destroy();\n\tcossb_config->destroy();\n}\n\nbool cossb_sync()\n{\n\treturn true;\n}\n\n\nbool cossb_start()\n{\n\tcossb_log->log(log::loglevel::INFO, \"Now all components is running...\");\n\tif(cossb_component_manager->run())\n\t\treturn true;\n\n\treturn false;\n}\n\nbool cossb_stop()\n{\n\tcossb_log->log(log::loglevel::INFO, \"Now all components is stopping...\");\n\tif(cossb_component_manager->stop())\n\t\treturn true;\n\n\treturn false;\n}\n\n\n\n} \/* namespace core *\/\n} \/* namespace cossb *\/\ncossb_stop function checks the size of container.\n\n#include \n#include \"instance.hpp\"\n#include \"manager.hpp\"\n#include \"broker.hpp\"\n#include \"logger.hpp\"\n#include \n#include \n\nusing namespace std;\n\nnamespace cossb {\nnamespace core {\n\nbool cossb_init(const char* manifest)\n{\n\n\t\/\/1. load manifest file\n\tif(!cossb_config->load(manifest))\n\t\treturn false;\n\n\t\/\/2. create(setup) instances according to the manifest\n\tif(!cossb_system_manager->setup(cossb_config))\n\t\treturn false;\n\n\treturn true;\n}\n\nvoid cossb_destroy()\n{\n\tcossb_stop();\n\tcossb_log->log(log::loglevel::INFO, \"Now terminating...\");\n\tcossb_system_manager->destroy();\n\tcossb_config->destroy();\n}\n\nbool cossb_sync()\n{\n\treturn true;\n}\n\n\nbool cossb_start()\n{\n\tcossb_log->log(log::loglevel::INFO, \"Now all components is running...\");\n\tif(cossb_component_manager->run())\n\t\treturn true;\n\n\treturn false;\n}\n\nbool cossb_stop()\n{\n\tif(cossb_component_manager->count()>0)\n\t{\n\t\tcossb_log->log(log::loglevel::INFO, \"Now all components is stopping...\");\n\t\tif(cossb_component_manager->stop())\n\t\t\treturn true;\n\t}\n\n\treturn true;\n}\n\n\n\n} \/* namespace core *\/\n} \/* namespace cossb *\/\n<|endoftext|>"} {"text":"\/* MULTEQ - multi-band equalizer instrument\n\n p0 = output start time\n p1 = input start time\n p2 = input duration\n p3 = amplitude multiplier\n p4 = master bypass (0: no, 1: yes) \n\n Followed by one or more (up to 8) EQ band descriptions, given by\n quintuplets of\n EQ type (\"lowpass\", \"highpass\", \"lowshelf\", \"highshelf\", \"peaknotch\") *\n filter frequency (Hz)\n filter Q (c. 0.5-10)\n filter gain (cut or boost, in dB -- for shelf and peak\/notch only)\n bypass (0: no, 1: yes)\n\n So the settings for the first band would occupy pfields 5-9, the second,\n pfields 10-14, and so on.\n\n p3 (amplitude), p4 (bypass) as well as the freq, Q, gain and bypass pfields\n for individual bands can receive dynamic updates from a table or real-time\n control source.\n\n The EQ types can be updated only when using numeric codes (0: lowpass,\n 1: highpass, 2: lowshelf, 3: highshelf, 4: peaknotch). If you give the\n string version, you can't change types during a note.\n\n The number of input channels must equal the number of output channels.\n There can be as many as 8 channels.\n\n John Gibson , 26 Sep 2004; derived from EQ.\n\n Based on formulas by Robert Bristow-Johnson (\"Audio-EQ-Cookbook\") and code\n by Tom St Denis (see musicdsp.org)\n*\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"MULTEQ.h\"\n#include \n#include \n#include \/\/ for FLT_MIN\n\n#define FIRST_BAND_PF 5\n#define BAND_PFS 5\n\n\nEQBand :: EQBand(float srate, OeqType type, float freq, float Q, float gain,\n bool bypass)\n : _type(type), _freq(freq), _Q(Q), _gain(gain), _bypass(bypass)\n{\n _eq = new Oequalizer(srate, _type);\n if (_eq)\n _eq->setparams(_freq, _Q, _gain);\n}\n\n\nEQBand :: ~EQBand()\n{\n delete _eq;\n}\n\n\nMULTEQ :: MULTEQ() : Instrument()\n{\n in = NULL;\n branch = 0;\n for (int i = 0; i < MAXBAND * MAXCHAN; i++)\n eq[i] = NULL;\n}\n\n\nMULTEQ :: ~MULTEQ()\n{\n delete [] in;\n for (int i = 0; i < MAXBAND * MAXCHAN; i++)\n delete eq[i];\n}\n\n\nstatic char *_eqtype_name[] = {\n \"lowpass\", \/\/ 0\n \"highpass\", \/\/ 1\n \"lowshelf\", \/\/ 2\n \"highshelf\", \/\/ 3\n \"peaknotch\", \/\/ 4\n NULL\n};\n\ninline int _string_to_eqcode(const char *str)\n{\n for (int i = 0; _eqtype_name[i] != NULL; i++)\n if (strncmp(str, _eqtype_name[i], 5) == 0) \/\/ 5 is min. to distinguish\n return i;\n return -1;\n}\n\nOeqType MULTEQ :: getEQType(bool trystring, int pfindex)\n{\n double index = (double) currentFrame() \/ nSamps();\n const PField &field = getPField(pfindex);\n\n \/\/ must try int first, since a valid code cast to char * will crash strncmp\n int code = field.intValue(index);\n if (trystring && (code < 0 || code > 4)) {\n const char *str = field.stringValue(index);\n code = _string_to_eqcode(str); \/\/ -1 if no match\n }\n\n OeqType eqtype;\n switch (code) {\n case 0: eqtype = OeqLowPass; break;\n case 1: eqtype = OeqHighPass; break;\n case 2: eqtype = OeqLowShelf; break;\n case 3: eqtype = OeqHighShelf; break;\n case 4: eqtype = OeqPeaking; break;\n default: eqtype = OeqInvalid; break;\n }\n return eqtype;\n}\n\n\nint MULTEQ :: init(double p[], int n_args)\n{\n nargs = n_args;\n const float ringdur = 0.1;\n float outskip = p[0];\n float inskip = p[1];\n float dur = p[2];\n\n if (rtsetinput(inskip, this) == -1)\n return DONT_SCHEDULE;\n insamps = (int) (dur * SR + 0.5);\n\n if (rtsetoutput(outskip, dur + ringdur, this) == -1)\n return DONT_SCHEDULE;\n\n if (inputChannels() > MAXCHAN)\n return die(\"MULTEQ\",\n \"Input and output must have no more than %d channels.\", MAXCHAN);\n if (outputChannels() != inputChannels())\n return die(\"MULTEQ\", \"Input and output must have same number of \"\n \"channels, no more than %d.\", MAXCHAN);\n\n if ((nargs - FIRST_BAND_PF) % BAND_PFS)\n return die(\"MULTEQ\",\n \"For each band, need type, freq, Q, gain and bypass.\");\n\n numbands = 0;\n int band = 0;\n for (int i = FIRST_BAND_PF; i < nargs; i += BAND_PFS, band += MAXCHAN) {\n if (numbands == MAXBAND) {\n warn(\"MULTEQ\", \"You can only have %d EQ bands.\", MAXBAND);\n break;\n }\n\n OeqType type = getEQType(true, i);\n if (type == OeqInvalid)\n return die(\"MULTEQ\", \"Invalid EQ type string or code.\");\n float freq = p[i + 1];\n float Q = p[i + 2];\n float gain = p[i + 3];\n bool bypass = (bool) p[i + 4];\n\n for (int c = 0; c < inputChannels(); c++) {\n eq[band + c] = new EQBand(SR, type, freq, Q, gain, bypass);\n if (eq[band + c] == NULL)\n return die(\"MULTEQ\", \"Can't allocate EQ band.\");\n }\n\n numbands++;\n }\n\n skip = (int) (SR \/ (float) resetval);\n\n return nSamps();\n}\n\n\nvoid MULTEQ :: doupdate()\n{\n double p[nargs];\n update(p, nargs);\n\n amp = p[3];\n bypass = (bool) p[4];\n\n int band = 0;\n for (int i = FIRST_BAND_PF; i < nargs; i += BAND_PFS, band += MAXCHAN) {\n OeqType type = getEQType(false, i);\n float freq = p[i + 1];\n if (freq < 0.0)\n freq = 0.0;\n else if (freq > SR * 0.5)\n freq = SR * 0.5;\n float Q = p[i + 2];\n if (Q <= 0.0)\n Q = FLT_MIN;\n float gain = p[i + 3];\n bool bypass = (bool) p[i + 4];\n\n for (int c = 0; c < inputChannels(); c++)\n eq[band + c]->setparams(type, freq, Q, gain, bypass);\n }\n}\n\n\nint MULTEQ :: configure()\n{\n in = new float [RTBUFSAMPS * inputChannels()];\n return in ? 0 : -1;\n}\n\n\nint MULTEQ :: run()\n{\n const int samps = framesToRun() * inputChannels();\n if (currentFrame() < insamps)\n rtgetin(in, this, samps);\n\n for (int i = 0; i < samps; i += inputChannels()) {\n if (--branch <= 0) {\n doupdate();\n branch = skip;\n }\n\n float insig[MAXCHAN];\n if (currentFrame() < insamps) {\n for (int c = 0; c < inputChannels(); c++)\n insig[c] = in[i + c];\n }\n else {\n for (int c = 0; c < inputChannels(); c++)\n insig[c] = 0.0;\n }\n\n float out[MAXCHAN];\n if (bypass) {\n for (int c = 0; c < inputChannels(); c++)\n out[c] = insig[c] * amp;\n }\n else {\n for (int c = 0; c < inputChannels(); c++) {\n for (int b = 0; b < numbands; b++) {\n int index = (b * MAXCHAN) + c;\n insig[c] = eq[index]->next(insig[c]);\n }\n out[c] = insig[c] * amp;\n }\n }\n\n rtaddout(out);\n increment();\n }\n\n return framesToRun();\n}\n\n\nInstrument *makeMULTEQ()\n{\n MULTEQ *inst;\n\n inst = new MULTEQ();\n inst->set_bus_config(\"MULTEQ\");\n\n return inst;\n}\n\nvoid rtprofile()\n{\n RT_INTRO(\"MULTEQ\", makeMULTEQ);\n}\n\nAdd bandpass type.\/* MULTEQ - multi-band equalizer instrument\n\n p0 = output start time\n p1 = input start time\n p2 = input duration\n p3 = amplitude multiplier\n p4 = master bypass (0: no, 1: yes) \n\n Followed by one or more (up to 8) EQ band descriptions, given by\n quintuplets of\n EQ type (\"lowpass\", \"highpass\", \"lowshelf\", \"highshelf\", \"peaknotch\",\n \"bandpass\") *\n filter frequency (Hz)\n filter Q (c. 0.5-10)\n filter gain (cut or boost, in dB -- for shelf and peak\/notch only)\n bypass (0: no, 1: yes)\n\n So the settings for the first band would occupy pfields 5-9, the second,\n pfields 10-14, and so on.\n\n p3 (amplitude), p4 (bypass) as well as the freq, Q, gain and bypass pfields\n for individual bands can receive dynamic updates from a table or real-time\n control source.\n\n The EQ types can be updated only when using numeric codes (0: lowpass,\n 1: highpass, 2: lowshelf, 3: highshelf, 4: peaknotch, 5: bandpass). If\n you give the string version, you can't change types during a note.\n\n The number of input channels must equal the number of output channels.\n There can be as many as 8 channels.\n\n John Gibson , 26 Sep 2004; derived from EQ.\n\n Based on formulas by Robert Bristow-Johnson (\"Audio-EQ-Cookbook\") and code\n by Tom St Denis (see musicdsp.org)\n*\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"MULTEQ.h\"\n#include \n#include \n#include \/\/ for FLT_MIN\n\n#define FIRST_BAND_PF 5\n#define BAND_PFS 5\n\n\nEQBand :: EQBand(float srate, OeqType type, float freq, float Q, float gain,\n bool bypass)\n : _type(type), _freq(freq), _Q(Q), _gain(gain), _bypass(bypass)\n{\n _eq = new Oequalizer(srate, _type);\n if (_eq)\n _eq->setparams(_freq, _Q, _gain);\n}\n\n\nEQBand :: ~EQBand()\n{\n delete _eq;\n}\n\n\nMULTEQ :: MULTEQ() : Instrument()\n{\n in = NULL;\n branch = 0;\n for (int i = 0; i < MAXBAND * MAXCHAN; i++)\n eq[i] = NULL;\n}\n\n\nMULTEQ :: ~MULTEQ()\n{\n delete [] in;\n for (int i = 0; i < MAXBAND * MAXCHAN; i++)\n delete eq[i];\n}\n\n\nstatic char *_eqtype_name[] = {\n \"lowpass\", \/\/ 0\n \"highpass\", \/\/ 1\n \"lowshelf\", \/\/ 2\n \"highshelf\", \/\/ 3\n \"peaknotch\", \/\/ 4\n \"bandpass\", \/\/ 5\n NULL\n};\n\ninline int _string_to_eqcode(const char *str)\n{\n for (int i = 0; _eqtype_name[i] != NULL; i++)\n if (strncmp(str, _eqtype_name[i], 5) == 0) \/\/ 5 is min. to distinguish\n return i;\n return -1;\n}\n\nOeqType MULTEQ :: getEQType(bool trystring, int pfindex)\n{\n double index = (double) currentFrame() \/ nSamps();\n const PField &field = getPField(pfindex);\n\n \/\/ must try int first, since a valid code cast to char * will crash strncmp\n int code = field.intValue(index);\n if (trystring && (code < 0 || code > 4)) {\n const char *str = field.stringValue(index);\n code = _string_to_eqcode(str); \/\/ -1 if no match\n }\n\n OeqType eqtype;\n switch (code) {\n case 0: eqtype = OeqLowPass; break;\n case 1: eqtype = OeqHighPass; break;\n case 2: eqtype = OeqLowShelf; break;\n case 3: eqtype = OeqHighShelf; break;\n case 4: eqtype = OeqPeaking; break;\n case 5: eqtype = OeqBandPassCSG; break;\n default: eqtype = OeqInvalid; break;\n }\n return eqtype;\n}\n\n\nint MULTEQ :: init(double p[], int n_args)\n{\n nargs = n_args;\n const float ringdur = 0.1;\n float outskip = p[0];\n float inskip = p[1];\n float dur = p[2];\n\n if (rtsetinput(inskip, this) == -1)\n return DONT_SCHEDULE;\n insamps = (int) (dur * SR + 0.5);\n\n if (rtsetoutput(outskip, dur + ringdur, this) == -1)\n return DONT_SCHEDULE;\n\n if (inputChannels() > MAXCHAN)\n return die(\"MULTEQ\",\n \"Input and output must have no more than %d channels.\", MAXCHAN);\n if (outputChannels() != inputChannels())\n return die(\"MULTEQ\", \"Input and output must have same number of \"\n \"channels, no more than %d.\", MAXCHAN);\n\n if ((nargs - FIRST_BAND_PF) % BAND_PFS)\n return die(\"MULTEQ\",\n \"For each band, need type, freq, Q, gain and bypass.\");\n\n numbands = 0;\n int band = 0;\n for (int i = FIRST_BAND_PF; i < nargs; i += BAND_PFS, band += MAXCHAN) {\n if (numbands == MAXBAND) {\n warn(\"MULTEQ\", \"You can only have %d EQ bands.\", MAXBAND);\n break;\n }\n\n OeqType type = getEQType(true, i);\n if (type == OeqInvalid)\n return die(\"MULTEQ\", \"Invalid EQ type string or code.\");\n float freq = p[i + 1];\n float Q = p[i + 2];\n float gain = p[i + 3];\n bool bypass = (bool) p[i + 4];\n\n for (int c = 0; c < inputChannels(); c++) {\n eq[band + c] = new EQBand(SR, type, freq, Q, gain, bypass);\n if (eq[band + c] == NULL)\n return die(\"MULTEQ\", \"Can't allocate EQ band.\");\n }\n\n numbands++;\n }\n\n skip = (int) (SR \/ (float) resetval);\n\n return nSamps();\n}\n\n\nvoid MULTEQ :: doupdate()\n{\n double p[nargs];\n update(p, nargs);\n\n amp = p[3];\n bypass = (bool) p[4];\n\n int band = 0;\n for (int i = FIRST_BAND_PF; i < nargs; i += BAND_PFS, band += MAXCHAN) {\n OeqType type = getEQType(false, i);\n float freq = p[i + 1];\n if (freq < 0.0)\n freq = 0.0;\n else if (freq > SR * 0.5)\n freq = SR * 0.5;\n float Q = p[i + 2];\n if (Q <= 0.0)\n Q = FLT_MIN;\n float gain = p[i + 3];\n bool bypass = (bool) p[i + 4];\n\n for (int c = 0; c < inputChannels(); c++)\n eq[band + c]->setparams(type, freq, Q, gain, bypass);\n }\n}\n\n\nint MULTEQ :: configure()\n{\n in = new float [RTBUFSAMPS * inputChannels()];\n return in ? 0 : -1;\n}\n\n\nint MULTEQ :: run()\n{\n const int samps = framesToRun() * inputChannels();\n if (currentFrame() < insamps)\n rtgetin(in, this, samps);\n\n for (int i = 0; i < samps; i += inputChannels()) {\n if (--branch <= 0) {\n doupdate();\n branch = skip;\n }\n\n float insig[MAXCHAN];\n if (currentFrame() < insamps) {\n for (int c = 0; c < inputChannels(); c++)\n insig[c] = in[i + c];\n }\n else {\n for (int c = 0; c < inputChannels(); c++)\n insig[c] = 0.0;\n }\n\n float out[MAXCHAN];\n if (bypass) {\n for (int c = 0; c < inputChannels(); c++)\n out[c] = insig[c] * amp;\n }\n else {\n for (int c = 0; c < inputChannels(); c++) {\n for (int b = 0; b < numbands; b++) {\n int index = (b * MAXCHAN) + c;\n insig[c] = eq[index]->next(insig[c]);\n }\n out[c] = insig[c] * amp;\n }\n }\n\n rtaddout(out);\n increment();\n }\n\n return framesToRun();\n}\n\n\nInstrument *makeMULTEQ()\n{\n MULTEQ *inst;\n\n inst = new MULTEQ();\n inst->set_bus_config(\"MULTEQ\");\n\n return inst;\n}\n\nvoid rtprofile()\n{\n RT_INTRO(\"MULTEQ\", makeMULTEQ);\n}\n\n<|endoftext|>"} {"text":"\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *\n* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *\n* *\n* This library is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU Lesser General Public License as published by *\n* the Free Software Foundation; either version 2.1 of the License, or (at *\n* your option) any later version. *\n* *\n* This library is distributed in the hope that it will be useful, but WITHOUT *\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *\n* for more details. *\n* *\n* You should have received a copy of the GNU Lesser General Public License *\n* along with this library; if not, write to the Free Software Foundation, *\n* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *\n*******************************************************************************\n* SOFA :: Modules *\n* *\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#ifndef SOFA_COMPONENT_PROJECTIVECONSTRAINTSET_FIXEDCONSTRAINT_INL\n#define SOFA_COMPONENT_PROJECTIVECONSTRAINTSET_FIXEDCONSTRAINT_INL\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n#include \n\n\n\n\nnamespace sofa\n{\n\nnamespace component\n{\n\nnamespace projectiveconstraintset\n{\n\nusing namespace core::topology;\n\nusing namespace sofa::defaulttype;\nusing namespace sofa::helper;\nusing namespace sofa::core::behavior;\n\n\n\/\/ Define TestNewPointFunction\ntemplate< class DataTypes>\nbool FixedConstraint::FCTestNewPointFunction(int \/*nbPoints*\/, void* param, const sofa::helper::vector< unsigned int > &, const sofa::helper::vector< double >& )\n{\n FixedConstraint *fc= (FixedConstraint *)param;\n if (fc)\n {\n return true;\n }\n else\n {\n return false;\n }\n}\n\n\/\/ Define RemovalFunction\ntemplate< class DataTypes>\nvoid FixedConstraint::FCRemovalFunction(int pointIndex, void* param)\n{\n FixedConstraint *fc= (FixedConstraint *)param;\n if (fc)\n {\n fc->removeConstraint((unsigned int) pointIndex);\n }\n return;\n}\n\ntemplate \nFixedConstraint::FixedConstraint()\n : core::behavior::ProjectiveConstraintSet(NULL)\n , f_indices( initData(&f_indices,\"indices\",\"Indices of the fixed points\") )\n , f_fixAll( initData(&f_fixAll,false,\"fixAll\",\"filter all the DOF to implement a fixed object\") )\n , _drawSize( initData(&_drawSize,0.0,\"drawSize\",\"0 -> point based rendering, >0 -> radius of spheres\") )\n{\n \/\/ default to indice 0\n f_indices.beginEdit()->push_back(0);\n f_indices.endEdit();\n}\n\n\n\/\/ Handle topological changes\ntemplate void FixedConstraint::handleTopologyChange()\n{\n std::list::const_iterator itBegin=topology->beginChange();\n std::list::const_iterator itEnd=topology->endChange();\n\n f_indices.beginEdit()->handleTopologyEvents(itBegin,itEnd,this->getMState()->getSize());\n\n}\n\ntemplate \nFixedConstraint::~FixedConstraint()\n{\n}\n\ntemplate \nvoid FixedConstraint::clearConstraints()\n{\n f_indices.beginEdit()->clear();\n f_indices.endEdit();\n}\n\ntemplate \nvoid FixedConstraint::addConstraint(unsigned int index)\n{\n f_indices.beginEdit()->push_back(index);\n f_indices.endEdit();\n}\n\ntemplate \nvoid FixedConstraint::removeConstraint(unsigned int index)\n{\n removeValue(*f_indices.beginEdit(),index);\n f_indices.endEdit();\n}\n\n\/\/ -- Constraint interface\n\n\ntemplate \nvoid FixedConstraint::init()\n{\n this->core::behavior::ProjectiveConstraintSet::init();\n\n topology = this->getContext()->getMeshTopology();\n\n\/\/ if (!topology)\n\/\/ serr << \"Can not find the topology.\" << sendl;\n\n \/\/ Initialize functions and parameters\n topology::PointSubset my_subset = f_indices.getValue();\n\n my_subset.setTestFunction(FCTestNewPointFunction);\n my_subset.setRemovalFunction(FCRemovalFunction);\n\n my_subset.setTestParameter( (void *) this );\n my_subset.setRemovalParameter( (void *) this );\n\n\n unsigned int maxIndex=this->mstate->getSize();\n for (topology::PointSubset::iterator it = my_subset.begin(); it != my_subset.end(); )\n {\n topology::PointSubset::iterator currentIterator=it;\n const unsigned int index=*it;\n it++;\n if (index >= maxIndex)\n {\n serr << \"Index \" << index << \" not valid!\" << sendl;\n removeConstraint(index);\n }\n }\n\n}\n\ntemplate \nvoid FixedConstraint::projectResponse(const core::MechanicalParams* mparams \/* PARAMS FIRST *\/, DataVecDeriv& resData)\n{\n \/\/cerr<<\"FixedConstraint::projectResponse is called \"< res ( mparams, resData );\n const SetIndexArray & indices = f_indices.getValue(mparams).getArray();\n \/\/serr<<\"FixedConstraint::projectResponse, dx.size()=\"<getNbPoints(); ++i )\n res[i] = Deriv();\n }\n else\n {\n for (SetIndexArray::const_iterator it = indices.begin();\n it != indices.end();\n ++it)\n {\n res[*it] = Deriv();\n }\n }\n \/\/cerr<<\"FixedConstraint::projectResponse is called res = \"<\nvoid FixedConstraint::projectJacobianMatrix(const core::MechanicalParams* mparams \/* PARAMS FIRST *\/, DataMatrixDeriv& cData)\n{\n helper::WriteAccessor c ( mparams, cData );\n const SetIndexArray & indices = f_indices.getValue(mparams).getArray();\n\n MatrixDerivRowIterator rowIt = c->begin();\n MatrixDerivRowIterator rowItEnd = c->end();\n\n if( f_fixAll.getValue(mparams) )\n {\n \/\/ fix everything\n while (rowIt != rowItEnd)\n {\n rowIt.row().clear();\n ++rowIt;\n }\n }\n else\n {\n while (rowIt != rowItEnd)\n {\n for (SetIndexArray::const_iterator it = indices.begin();\n it != indices.end();\n ++it)\n {\n rowIt.row().erase(*it);\n }\n ++rowIt;\n }\n }\n \/\/cerr<<\"FixedConstraint::projectJacobianMatrix : helper::WriteAccessor c = \"<\nvoid FixedConstraint::projectVelocity(const core::MechanicalParams* \/*mparams*\/ \/* PARAMS FIRST *\/, DataVecDeriv& \/*vData*\/)\n{\n#if 0 \/\/\/ @TODO ADD A FLAG FOR THIS\n const SetIndexArray & indices = f_indices.getValue().getArray();\n \/\/serr<<\"FixedConstraint::projectVelocity, res.size()=\"<\nvoid FixedConstraint::projectPosition(const core::MechanicalParams* \/*mparams*\/ \/* PARAMS FIRST *\/, DataVecCoord& \/*xData*\/)\n{\n\n}\n\n\/\/ Matrix Integration interface\ntemplate \nvoid FixedConstraint::applyConstraint(defaulttype::BaseMatrix *mat, unsigned int offset)\n{\n \/\/sout << \"applyConstraint in Matrix with offset = \" << offset << sendl;\n \/\/cerr<<\"FixedConstraint::applyConstraint(defaulttype::BaseMatrix *mat, unsigned int offset) is called \"<clearRowCol(offset + N * (*it) + c);\n \/\/ Set Fixed Vertex\n for (unsigned int c=0; cset(offset + N * (*it) + c, offset + N * (*it) + c, 1.0);\n }\n}\n\ntemplate \nvoid FixedConstraint::applyConstraint(defaulttype::BaseVector *vect, unsigned int offset)\n{\n \/\/cerr<<\"FixedConstraint::applyConstraint(defaulttype::BaseVector *vect, unsigned int offset) is called \"<clear(offset + N * (*it) + c);\n }\n}\n\n\ntemplate \nvoid FixedConstraint::draw()\n{\n if (!this->getContext()->\n getShowBehaviorModels()) return;\n if (!this->isActive()) return;\n const VecCoord& x = *this->mstate->getX();\n \/\/serr<<\"FixedConstraint::draw(), x.size() = \"< points;\n Vector3 point;\n \/\/serr<<\"FixedConstraint::draw(), indices = \"<DrawUtility().drawPoints(points, 10, Vec<4,float>(1,0.5,0.5,1));\n }\n else \/\/ new drawing by spheres\n {\n std::vector< Vector3 > points;\n Vector3 point;\n glColor4f (1.0f,0.35f,0.35f,1.0f);\n if( f_fixAll.getValue()==true )\n for (unsigned i=0; iDrawUtility().drawSpheres(points, (float)_drawSize.getValue(), Vec<4,float>(1.0f,0.35f,0.35f,1.0f));\n }\n}\n\n\/\/ Specialization for rigids\n#ifndef SOFA_FLOAT\ntemplate <>\nvoid FixedConstraint::draw();\ntemplate <>\nvoid FixedConstraint::draw();\n#endif\n#ifndef SOFA_DOUBLE\ntemplate <>\nvoid FixedConstraint::draw();\ntemplate <>\nvoid FixedConstraint::draw();\n#endif\n\n\n\n} \/\/ namespace constraint\n\n} \/\/ namespace component\n\n} \/\/ namespace sofa\n\n#endif\n\n\nr10100\/sofa-dev : FIX: bug in FixedConstraint::projectResponse() see ticket#236\/******************************************************************************\n* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *\n* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *\n* *\n* This library is free software; you can redistribute it and\/or modify it *\n* under the terms of the GNU Lesser General Public License as published by *\n* the Free Software Foundation; either version 2.1 of the License, or (at *\n* your option) any later version. *\n* *\n* This library is distributed in the hope that it will be useful, but WITHOUT *\n* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *\n* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *\n* for more details. *\n* *\n* You should have received a copy of the GNU Lesser General Public License *\n* along with this library; if not, write to the Free Software Foundation, *\n* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *\n*******************************************************************************\n* SOFA :: Modules *\n* *\n* Authors: The SOFA Team and external contributors (see Authors.txt) *\n* *\n* Contact information: contact@sofa-framework.org *\n******************************************************************************\/\n#ifndef SOFA_COMPONENT_PROJECTIVECONSTRAINTSET_FIXEDCONSTRAINT_INL\n#define SOFA_COMPONENT_PROJECTIVECONSTRAINTSET_FIXEDCONSTRAINT_INL\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n#include \n\n\n\n\nnamespace sofa\n{\n\nnamespace component\n{\n\nnamespace projectiveconstraintset\n{\n\nusing namespace core::topology;\n\nusing namespace sofa::defaulttype;\nusing namespace sofa::helper;\nusing namespace sofa::core::behavior;\n\n\n\/\/ Define TestNewPointFunction\ntemplate< class DataTypes>\nbool FixedConstraint::FCTestNewPointFunction(int \/*nbPoints*\/, void* param, const sofa::helper::vector< unsigned int > &, const sofa::helper::vector< double >& )\n{\n FixedConstraint *fc= (FixedConstraint *)param;\n if (fc)\n {\n return true;\n }\n else\n {\n return false;\n }\n}\n\n\/\/ Define RemovalFunction\ntemplate< class DataTypes>\nvoid FixedConstraint::FCRemovalFunction(int pointIndex, void* param)\n{\n FixedConstraint *fc= (FixedConstraint *)param;\n if (fc)\n {\n fc->removeConstraint((unsigned int) pointIndex);\n }\n return;\n}\n\ntemplate \nFixedConstraint::FixedConstraint()\n : core::behavior::ProjectiveConstraintSet(NULL)\n , f_indices( initData(&f_indices,\"indices\",\"Indices of the fixed points\") )\n , f_fixAll( initData(&f_fixAll,false,\"fixAll\",\"filter all the DOF to implement a fixed object\") )\n , _drawSize( initData(&_drawSize,0.0,\"drawSize\",\"0 -> point based rendering, >0 -> radius of spheres\") )\n{\n \/\/ default to indice 0\n f_indices.beginEdit()->push_back(0);\n f_indices.endEdit();\n}\n\n\n\/\/ Handle topological changes\ntemplate void FixedConstraint::handleTopologyChange()\n{\n std::list::const_iterator itBegin=topology->beginChange();\n std::list::const_iterator itEnd=topology->endChange();\n\n f_indices.beginEdit()->handleTopologyEvents(itBegin,itEnd,this->getMState()->getSize());\n\n}\n\ntemplate \nFixedConstraint::~FixedConstraint()\n{\n}\n\ntemplate \nvoid FixedConstraint::clearConstraints()\n{\n f_indices.beginEdit()->clear();\n f_indices.endEdit();\n}\n\ntemplate \nvoid FixedConstraint::addConstraint(unsigned int index)\n{\n f_indices.beginEdit()->push_back(index);\n f_indices.endEdit();\n}\n\ntemplate \nvoid FixedConstraint::removeConstraint(unsigned int index)\n{\n removeValue(*f_indices.beginEdit(),index);\n f_indices.endEdit();\n}\n\n\/\/ -- Constraint interface\n\n\ntemplate \nvoid FixedConstraint::init()\n{\n this->core::behavior::ProjectiveConstraintSet::init();\n\n topology = this->getContext()->getMeshTopology();\n\n\/\/ if (!topology)\n\/\/ serr << \"Can not find the topology.\" << sendl;\n\n \/\/ Initialize functions and parameters\n topology::PointSubset my_subset = f_indices.getValue();\n\n my_subset.setTestFunction(FCTestNewPointFunction);\n my_subset.setRemovalFunction(FCRemovalFunction);\n\n my_subset.setTestParameter( (void *) this );\n my_subset.setRemovalParameter( (void *) this );\n\n\n unsigned int maxIndex=this->mstate->getSize();\n for (topology::PointSubset::iterator it = my_subset.begin(); it != my_subset.end(); )\n {\n topology::PointSubset::iterator currentIterator=it;\n const unsigned int index=*it;\n it++;\n if (index >= maxIndex)\n {\n serr << \"Index \" << index << \" not valid!\" << sendl;\n removeConstraint(index);\n }\n }\n\n}\n\ntemplate \nvoid FixedConstraint::projectResponse(const core::MechanicalParams* mparams \/* PARAMS FIRST *\/, DataVecDeriv& resData)\n{\n \/\/cerr<<\"FixedConstraint::projectResponse is called \"< res ( mparams, resData );\n const SetIndexArray & indices = f_indices.getValue(mparams).getArray();\n \/\/serr<<\"FixedConstraint::projectResponse, dx.size()=\"<::projectResponse is called res = \"<\nvoid FixedConstraint::projectJacobianMatrix(const core::MechanicalParams* mparams \/* PARAMS FIRST *\/, DataMatrixDeriv& cData)\n{\n helper::WriteAccessor c ( mparams, cData );\n const SetIndexArray & indices = f_indices.getValue(mparams).getArray();\n\n MatrixDerivRowIterator rowIt = c->begin();\n MatrixDerivRowIterator rowItEnd = c->end();\n\n if( f_fixAll.getValue(mparams) )\n {\n \/\/ fix everything\n while (rowIt != rowItEnd)\n {\n rowIt.row().clear();\n ++rowIt;\n }\n }\n else\n {\n while (rowIt != rowItEnd)\n {\n for (SetIndexArray::const_iterator it = indices.begin();\n it != indices.end();\n ++it)\n {\n rowIt.row().erase(*it);\n }\n ++rowIt;\n }\n }\n \/\/cerr<<\"FixedConstraint::projectJacobianMatrix : helper::WriteAccessor c = \"<\nvoid FixedConstraint::projectVelocity(const core::MechanicalParams* \/*mparams*\/ \/* PARAMS FIRST *\/, DataVecDeriv& \/*vData*\/)\n{\n#if 0 \/\/\/ @TODO ADD A FLAG FOR THIS\n const SetIndexArray & indices = f_indices.getValue().getArray();\n \/\/serr<<\"FixedConstraint::projectVelocity, res.size()=\"<\nvoid FixedConstraint::projectPosition(const core::MechanicalParams* \/*mparams*\/ \/* PARAMS FIRST *\/, DataVecCoord& \/*xData*\/)\n{\n\n}\n\n\/\/ Matrix Integration interface\ntemplate \nvoid FixedConstraint::applyConstraint(defaulttype::BaseMatrix *mat, unsigned int offset)\n{\n \/\/sout << \"applyConstraint in Matrix with offset = \" << offset << sendl;\n \/\/cerr<<\"FixedConstraint::applyConstraint(defaulttype::BaseMatrix *mat, unsigned int offset) is called \"<clearRowCol(offset + N * (*it) + c);\n \/\/ Set Fixed Vertex\n for (unsigned int c=0; cset(offset + N * (*it) + c, offset + N * (*it) + c, 1.0);\n }\n}\n\ntemplate \nvoid FixedConstraint::applyConstraint(defaulttype::BaseVector *vect, unsigned int offset)\n{\n \/\/cerr<<\"FixedConstraint::applyConstraint(defaulttype::BaseVector *vect, unsigned int offset) is called \"<clear(offset + N * (*it) + c);\n }\n}\n\n\ntemplate \nvoid FixedConstraint::draw()\n{\n if (!this->getContext()->\n getShowBehaviorModels()) return;\n if (!this->isActive()) return;\n const VecCoord& x = *this->mstate->getX();\n \/\/serr<<\"FixedConstraint::draw(), x.size() = \"< points;\n Vector3 point;\n \/\/serr<<\"FixedConstraint::draw(), indices = \"<DrawUtility().drawPoints(points, 10, Vec<4,float>(1,0.5,0.5,1));\n }\n else \/\/ new drawing by spheres\n {\n std::vector< Vector3 > points;\n Vector3 point;\n glColor4f (1.0f,0.35f,0.35f,1.0f);\n if( f_fixAll.getValue()==true )\n for (unsigned i=0; iDrawUtility().drawSpheres(points, (float)_drawSize.getValue(), Vec<4,float>(1.0f,0.35f,0.35f,1.0f));\n }\n}\n\n\/\/ Specialization for rigids\n#ifndef SOFA_FLOAT\ntemplate <>\nvoid FixedConstraint::draw();\ntemplate <>\nvoid FixedConstraint::draw();\n#endif\n#ifndef SOFA_DOUBLE\ntemplate <>\nvoid FixedConstraint::draw();\ntemplate <>\nvoid FixedConstraint::draw();\n#endif\n\n\n\n} \/\/ namespace constraint\n\n} \/\/ namespace component\n\n} \/\/ namespace sofa\n\n#endif\n\n\n<|endoftext|>"} {"text":"#ifndef LIBTEN_ERROR_HH\n#define LIBTEN_ERROR_HH\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace ten {\n\n\/\/! capture the current stack trace\nstruct saved_backtrace {\n void *array[50];\n int size;\n\n saved_backtrace();\n std::string str();\n};\n\n\/\/! captures the backtrace in the constructor\n\/\/\n\/\/! useful for coroutines because the stack is lost switching contexts\nclass backtrace_exception : public std::exception {\npublic:\n std::string backtrace_str() { return bt.str(); }\nprivate:\n saved_backtrace bt;\n};\n\n\/\/! exception that sets what() based on current errno value\nstruct errno_error : backtrace_exception {\nprivate:\n \/\/! the value of errno when this exception was created\n int _error;\n char _buf[128];\n const char *_what;\n\npublic:\n \/\/! \\param err the error as specified by errno\n errno_error(int err = errno) : _error(err) {\n \/\/ requires GNU specific strerror_r\n \/\/ _what might be _buf or an internal static string\n _what = strerror_r(_error, _buf, sizeof(_buf));\n }\n errno_error(const errno_error &ee) { copy(ee); }\n errno_error & operator = (const errno_error &ee) { copy(ee); return *this; }\n\n \/\/! \\return string result from strerror_r\n const char *what() const noexcept override { return _what; }\n\nprivate:\n void copy(const errno_error &ee) {\n _error = ee._error;\n memcpy(_buf, ee._buf, sizeof _buf);\n _what = (ee._what == ee._buf) ? _buf : ee._what;\n }\n};\n\n\/\/! construct a what() string in printf() format\nstruct errorx : backtrace_exception {\nprivate:\n char _buf[256];\n\npublic:\n \/\/! \\param fmt printf-style format string\n errorx(const char *fmt, ...) __attribute__((format (printf, 2, 3))) {\n _buf[0] = 0;\n va_list ap;\n va_start(ap, fmt);\n vsnprintf(_buf, sizeof(_buf), fmt, ap);\n va_end(ap);\n }\n\n errorx(const std::string &msg) {\n strncpy(_buf, msg.data(), sizeof(_buf)-1);\n _buf[sizeof(_buf)-1] = 0;\n }\n\n \/\/! \\return a string describing the error\n const char *what() const noexcept override { return _buf; }\n};\n\n\/\/! macro to throw errno_error if exp returns -1\n#define THROW_ON_ERROR(exp) \\\n if ((exp) == -1) { \\\n throw errno_error(); \\\n }\n\n\/\/! macro to throw errno_error if exp returns NULL\n#define THROW_ON_NULL(exp) \\\n if ((exp) == NULL) { \\\n throw errno_error(); \\\n }\n\n\/\/! macro to throw errno_error if exp != 0\n#define THROW_ON_NONZERO_ERRNO(exp) \\\n do { \\\n int _rv = (exp); \\\n if (_rv != 0) throw errno_error(_rv); \\\n } while (0)\n\n} \/\/ end namespace ten\n\n#endif \/\/ LIBTEN_ERROR_HH\nno longer require dummy format \"%s\" for errorx#ifndef LIBTEN_ERROR_HH\n#define LIBTEN_ERROR_HH\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace ten {\n\n\/\/! capture the current stack trace\nstruct saved_backtrace {\n void *array[50];\n int size;\n\n saved_backtrace();\n std::string str();\n};\n\n\/\/! captures the backtrace in the constructor\n\/\/\n\/\/! useful for coroutines because the stack is lost switching contexts\nclass backtrace_exception : public std::exception {\npublic:\n std::string backtrace_str() { return bt.str(); }\nprivate:\n saved_backtrace bt;\n};\n\n\/\/! exception that sets what() based on current errno value\nstruct errno_error : backtrace_exception {\nprivate:\n \/\/! the value of errno when this exception was created\n int _error;\n char _buf[128];\n const char *_what;\n\npublic:\n \/\/! \\param err the error as specified by errno\n errno_error(int err = errno) : _error(err) {\n \/\/ requires GNU specific strerror_r\n \/\/ _what might be _buf or an internal static string\n _what = strerror_r(_error, _buf, sizeof(_buf));\n }\n errno_error(const errno_error &ee) { copy(ee); }\n errno_error & operator = (const errno_error &ee) { copy(ee); return *this; }\n\n \/\/! \\return string result from strerror_r\n const char *what() const noexcept override { return _what; }\n\nprivate:\n void copy(const errno_error &ee) {\n _error = ee._error;\n memcpy(_buf, ee._buf, sizeof _buf);\n _what = (ee._what == ee._buf) ? _buf : ee._what;\n }\n};\n\n\/\/! construct a what() string in printf() format\nstruct errorx : backtrace_exception {\nprivate:\n char _buf[256];\n\n void init(const char *msg, size_t len) {\n len = std::min(len, sizeof(_buf)-1);\n memcpy(_buf, msg, len);\n _buf[len] = 0;\n }\n void initf(const char *fmt, ...) __attribute__((format (printf, 2, 3))) {\n _buf[0] = 0;\n va_list ap;\n va_start(ap, fmt);\n vsnprintf(_buf, sizeof(_buf), fmt, ap);\n va_end(ap);\n }\n\npublic:\n errorx(const std::string &msg) { init(msg.data(), msg.size()); }\n errorx(const char *msg) { init(msg, strlen(msg)); }\n\n \/\/! \\param fmt printf-style format string\n template \n errorx(const char *fmt, A &&a, Args&&... args) { initf(fmt, std::forward(a), std::forward(args)...); }\n\n \/\/! \\return a string describing the error\n const char *what() const noexcept override { return _buf; }\n};\n\n\/\/! macro to throw errno_error if exp returns -1\n#define THROW_ON_ERROR(exp) \\\n if ((exp) == -1) { \\\n throw errno_error(); \\\n }\n\n\/\/! macro to throw errno_error if exp returns NULL\n#define THROW_ON_NULL(exp) \\\n if ((exp) == NULL) { \\\n throw errno_error(); \\\n }\n\n\/\/! macro to throw errno_error if exp != 0\n#define THROW_ON_NONZERO_ERRNO(exp) \\\n do { \\\n int _rv = (exp); \\\n if (_rv != 0) throw errno_error(_rv); \\\n } while (0)\n\n} \/\/ end namespace ten\n\n#endif \/\/ LIBTEN_ERROR_HH\n<|endoftext|>"} {"text":"\/*\n -----------------------------------------------------------------------------\n This source file is part of OGRE\n (Object-oriented Graphics Rendering Engine)\n For the latest info, see http:\/\/www.ogre3d.org\/\n \n Copyright (c) 2000-2014 Torus Knot Software Ltd\n \n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n \n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n \n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE.\n -----------------------------------------------------------------------------\n *\/\n#include \"OgreFileSystemLayer.h\"\n#include \"macUtils.h\"\n#include \n#include \n\nnamespace Ogre\n{\n String FileSystemLayer::resolveBundlePath(String path)\n {\n if(!path.empty() && path[0] != '\/') \/\/ only adjust relative dirs\n path = macBundlePath() + \"\/\" + path;\n\n return path;\n }\n\n void FileSystemLayer::getConfigPaths()\n {\n mConfigPaths.push_back(Ogre::macBundlePath() + \"\/Contents\/Resources\/\");\n mConfigPaths.push_back(Ogre::macBundlePath() + \"\/\");\n\n Dl_info info;\n if (dladdr((const void*)macBundlePath, &info))\n {\n String base(info.dli_fname);\n \/\/ need to strip the module filename from the path\n String::size_type pos = base.rfind('\/');\n if (pos != String::npos)\n base.erase(pos);\n\n \/\/ look relative to the dylib according to PIP structure\n mConfigPaths.push_back(StringUtil::normalizeFilePath(base+\"\/..\/..\/..\/..\/bin\/\"));\n }\n }\n \/\/---------------------------------------------------------------------\n void FileSystemLayer::prepareUserHome(const Ogre::String& subdir)\n {\n struct passwd* pwd = getpwuid(getuid());\n if (pwd)\n {\n mHomePath = pwd->pw_dir;\n }\n else\n {\n \/\/ try the $HOME environment variable\n mHomePath = getenv(\"HOME\");\n }\n\n if (!mHomePath.empty())\n {\n mHomePath.append(\"\/Library\/Application Support\/\");\n \/\/ now create the given subdir\n mHomePath.append(subdir + '\/');\n if (mkdir(mHomePath.c_str(), 0755) != 0 && errno != EEXIST)\n {\n \/\/ can't create dir\n mHomePath.clear();\n }\n }\n\n if (mHomePath.empty())\n {\n \/\/ couldn't create dir in home directory, fall back to cwd\n mHomePath = \".\/\";\n }\n }\n \/\/---------------------------------------------------------------------\n bool FileSystemLayer::fileExists(const Ogre::String& path)\n {\n return access(path.c_str(), R_OK) == 0;\n }\n \/\/---------------------------------------------------------------------\n bool FileSystemLayer::createDirectory(const Ogre::String& path)\n {\n return !mkdir(path.c_str(), 0755) || errno == EEXIST;\n }\n \/\/---------------------------------------------------------------------\n bool FileSystemLayer::removeDirectory(const Ogre::String& path)\n {\n return !rmdir(path.c_str()) || errno == ENOENT;\n }\n \/\/---------------------------------------------------------------------\n bool FileSystemLayer::removeFile(const Ogre::String& path)\n {\n return !unlink(path.c_str()) || errno == ENOENT;\n }\n \/\/---------------------------------------------------------------------\n bool FileSystemLayer::renameFile(const Ogre::String& oldname, const Ogre::String& newname)\n {\n return !rename(oldname.c_str(), newname.c_str());\n }\n}\nMain: FileSystemLayer - add include for OSX to be sure\/*\n -----------------------------------------------------------------------------\n This source file is part of OGRE\n (Object-oriented Graphics Rendering Engine)\n For the latest info, see http:\/\/www.ogre3d.org\/\n \n Copyright (c) 2000-2014 Torus Knot Software Ltd\n \n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n \n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n \n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE.\n -----------------------------------------------------------------------------\n *\/\n#include \"OgreFileSystemLayer.h\"\n#include \"macUtils.h\"\n#include \n#include \n#include \n\nnamespace Ogre\n{\n String FileSystemLayer::resolveBundlePath(String path)\n {\n if(!path.empty() && path[0] != '\/') \/\/ only adjust relative dirs\n path = macBundlePath() + \"\/\" + path;\n\n return path;\n }\n\n void FileSystemLayer::getConfigPaths()\n {\n mConfigPaths.push_back(Ogre::macBundlePath() + \"\/Contents\/Resources\/\");\n mConfigPaths.push_back(Ogre::macBundlePath() + \"\/\");\n\n Dl_info info;\n if (dladdr((const void*)macBundlePath, &info))\n {\n String base(info.dli_fname);\n \/\/ need to strip the module filename from the path\n String::size_type pos = base.rfind('\/');\n if (pos != String::npos)\n base.erase(pos);\n\n \/\/ look relative to the dylib according to PIP structure\n mConfigPaths.push_back(StringUtil::normalizeFilePath(base+\"\/..\/..\/..\/..\/bin\/\"));\n }\n }\n \/\/---------------------------------------------------------------------\n void FileSystemLayer::prepareUserHome(const Ogre::String& subdir)\n {\n struct passwd* pwd = getpwuid(getuid());\n if (pwd)\n {\n mHomePath = pwd->pw_dir;\n }\n else\n {\n \/\/ try the $HOME environment variable\n mHomePath = getenv(\"HOME\");\n }\n\n if (!mHomePath.empty())\n {\n mHomePath.append(\"\/Library\/Application Support\/\");\n \/\/ now create the given subdir\n mHomePath.append(subdir + '\/');\n if (mkdir(mHomePath.c_str(), 0755) != 0 && errno != EEXIST)\n {\n \/\/ can't create dir\n mHomePath.clear();\n }\n }\n\n if (mHomePath.empty())\n {\n \/\/ couldn't create dir in home directory, fall back to cwd\n mHomePath = \".\/\";\n }\n }\n \/\/---------------------------------------------------------------------\n bool FileSystemLayer::fileExists(const Ogre::String& path)\n {\n return access(path.c_str(), R_OK) == 0;\n }\n \/\/---------------------------------------------------------------------\n bool FileSystemLayer::createDirectory(const Ogre::String& path)\n {\n return !mkdir(path.c_str(), 0755) || errno == EEXIST;\n }\n \/\/---------------------------------------------------------------------\n bool FileSystemLayer::removeDirectory(const Ogre::String& path)\n {\n return !rmdir(path.c_str()) || errno == ENOENT;\n }\n \/\/---------------------------------------------------------------------\n bool FileSystemLayer::removeFile(const Ogre::String& path)\n {\n return !unlink(path.c_str()) || errno == ENOENT;\n }\n \/\/---------------------------------------------------------------------\n bool FileSystemLayer::renameFile(const Ogre::String& oldname, const Ogre::String& newname)\n {\n return !rename(oldname.c_str(), newname.c_str());\n }\n}\n<|endoftext|>"} {"text":"Control: clean up error status logic.<|endoftext|>"} {"text":"Control: updated preprocessor submodule<|endoftext|>"} {"text":"\/******************************************************************************\n * This file is part of the Gluon Development Platform\n * Copyright (c) 2010 Arjen Hiemstra \n * Copyright (c) 2011 Giulio Camuffo \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"uimanagercomponent.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"uiasset.h\"\n#include \"engineaccess.h\"\n#include \"renderablescene.h\"\n\nREGISTER_OBJECTTYPE( GluonEngine, UiManagerComponent )\n\nusing namespace GluonEngine;\nusing namespace GluonGraphics;\n\ntemplate \nQScriptValue scriptValueFromQObject( QScriptEngine *engine, Tp const& qobject)\n{\n return engine->newQObject( qobject );\n}\n\ntemplate \nvoid scriptValueToQObject(const QScriptValue &value, Tp &qobject)\n{\n qobject = qobject_cast( value.toQObject() );\n}\n\ntemplate \nint qScriptRegisterQObjectMetaType( QScriptEngine *engine )\n{\n return qScriptRegisterMetaType( engine, scriptValueFromQObject, scriptValueToQObject );\n}\n\nclass UiManagerComponent::UiManagerComponentPrivate\n{\n public:\n UiManagerComponentPrivate( UiManagerComponent *component )\n : q(component)\n , scene(0)\n , ui(0)\n , updateFunction(0)\n {\n }\n\n void setupBindings( QScriptEngine* engine )\n {\n \/\/FIXME: this code is duplicated with the scripting conponent.\n \/\/It should be moved to a common place.\n\n engine->importExtension( \"jsmoke.qtcore\" );\n engine->importExtension( \"jsmoke.qtgui\" );\n engine->importExtension( \"jsmoke.qtopengl\" );\n\n qScriptRegisterQObjectMetaType( engine );\n qScriptRegisterQObjectMetaType( engine );\n qScriptRegisterQObjectMetaType( engine );\n qScriptRegisterQObjectMetaType( engine );\n qScriptRegisterQObjectMetaType( engine );\n qScriptRegisterQObjectMetaType( engine );\n\n QScriptEngine::QObjectWrapOptions wrapOptions = QScriptEngine::AutoCreateDynamicProperties | QScriptEngine::ExcludeDeleteLater | QScriptEngine::PreferExistingWrapperObject;\n QScriptEngine::ValueOwnership ownership = QScriptEngine::QtOwnership;\n QScriptValue object = engine->globalObject();\n\n QScriptValue component = engine->newQObject( q, ownership, wrapOptions );\n object.setProperty( \"Component\", component );\n\n QScriptValue gameObj = engine->newQObject( q->gameObject(), ownership, wrapOptions );\n object.setProperty( \"GameObject\", gameObj );\n\n QScriptValue sceneObj = engine->newQObject( q->gameObject()->scene(), ownership, wrapOptions );\n object.setProperty( \"Scene\", sceneObj );\n\n QScriptValue gameProjectObj = engine->newQObject( GluonEngine::Game::instance()->gameProject(), ownership, wrapOptions );\n object.setProperty( \"GameProject\", gameProjectObj );\n\n QScriptValue game = engine->newQObject( GluonEngine::Game::instance(), ownership, wrapOptions );\n object.setProperty( \"Game\", game );\n }\n\n void resizeQmlItem( const QRectF& rect )\n {\n if ( ui )\n {\n QDeclarativeItem* item = ui->qmlItem();\n if( item )\n {\n item->setWidth( rect.width() );\n item->setHeight( rect.height() );\n }\n }\n }\n\n void reload()\n {\n q->cleanup();\n q->initialize();\n }\n\n UiManagerComponent* q;\n RenderableScene* scene;\n UiAsset *ui;\n QSizeF size;\n Item *item;\n EngineAccess* engineAccess;\n QScriptEngine* scriptEngine;\n\n QScriptValue scriptItem;\n QScriptValue updateFunction;\n};\n\nUiManagerComponent::UiManagerComponent( QObject* parent )\n : Component( parent )\n , d( new UiManagerComponentPrivate( this ) )\n{\n\n}\n\nUiManagerComponent::UiManagerComponent( const UiManagerComponent& other )\n : Component( other )\n , d( other.d )\n{\n}\n\nUiManagerComponent::~UiManagerComponent()\n{\n delete d;\n}\n\nQString UiManagerComponent::category() const\n{\n return QString( \"Graphics Rendering\" );\n}\n\nvoid UiManagerComponent::initialize()\n{\n if( !d->scene )\n {\n d->scene = new RenderableScene( this );\n connect( d->scene, SIGNAL( sceneRectChanged( const QRectF& ) ),\n this, SLOT( resizeQmlItem( const QRectF& ) ) );\n }\n\n if( d->ui && !d->ui->isLoaded() )\n {\n qmlRegisterType(\"org.kde.gluon\", 1, 0, \"GameObject\" );\n qmlRegisterInterface(\"gameObject\");\n\n d->ui->load();\n\n QDeclarativeEngine* engine = d->ui->engine();\n\n d->engineAccess = new EngineAccess(this);\n engine->rootContext()->setContextProperty( \"__engineAccess\", d->engineAccess );\n\n \/\/Glorious hack:steal the engine\n QDeclarativeExpression *expr = new QDeclarativeExpression( engine->rootContext(), 0,\n \"__engineAccess.setEngine( this )\" );\n expr->evaluate();\n delete expr;\n }\n\n if( d->ui && d->ui->isLoaded() )\n {\n d->ui->execute();\n\n QDeclarativeItem* item = d->ui->qmlItem();\n if( item )\n {\n d->scene->addItem( item );\n\n d->scriptItem = d->scriptEngine->newQObject( item );\n d->updateFunction = d->scriptItem.property( \"update\" );\n }\n }\n}\n\nvoid UiManagerComponent::setScriptEngine( QScriptValue &value )\n{\n d->scriptEngine = value.engine();\n\n QScriptValue originalGlobalObject = d->scriptEngine->globalObject();\n QScriptValue newGlobalObject = d->scriptEngine->newObject();\n\n QString eval = QLatin1String( \"eval\" );\n QString version = QLatin1String( \"version\" );\n\n QScriptValueIterator iter( originalGlobalObject );\n QVector names;\n QVector values;\n QVector flags;\n while ( iter.hasNext() )\n {\n iter.next();\n\n QString name = iter.name();\n\n if ( name == version )\n {\n continue;\n }\n\n if ( name != eval )\n {\n names.append( name );\n values.append( iter.value() );\n flags.append( iter.flags() | QScriptValue::Undeletable );\n }\n newGlobalObject.setProperty( iter.scriptName(), iter.value() );\n }\n\n d->scriptEngine->setGlobalObject( newGlobalObject );\n\n d->setupBindings( d->scriptEngine );\n\n delete d->engineAccess;\n d->ui->engine()->rootContext()->setContextProperty( \"__engineAccess\", 0 );\n}\n\nvoid UiManagerComponent::start()\n{\n\n}\n\nvoid UiManagerComponent::draw( int timeLapse )\n{\n Q_UNUSED( timeLapse )\n\n if( !d->scene || !d->ui || !d->ui->qmlItem() )\n {\n return;\n }\n\n d->scene->renderScene();\n}\n\nvoid UiManagerComponent::update( int elapsedMilliseconds )\n{\n if( d->updateFunction.isFunction() )\n {\n d->updateFunction.call( d->scriptItem, QScriptValueList() << elapsedMilliseconds );\n if( d->scriptEngine->uncaughtException().isValid() )\n \/\/ This needs to be mapped...\n debug( QString( \"%1: %2\" )\n .arg( d->scriptEngine->uncaughtException().toString() )\n .arg( d->scriptEngine->uncaughtExceptionBacktrace().join( \" \" ) ) );\n }\n}\n\nvoid UiManagerComponent::cleanup()\n{\n if( !d->ui )\n {\n return;\n }\n\n QDeclarativeItem* item = d->ui->qmlItem();\n if( d->scene && item && item->scene() == d->scene )\n {\n d->scene->removeItem( item );\n }\n\n delete d->scene;\n d->scene = 0;\n}\n\nvoid UiManagerComponent::setUi(UiAsset* ui)\n{\n d->ui = ui;\n\n connect( ui, SIGNAL( dataChanged() ), this, SLOT( reload() ) );\n}\n\nUiAsset* UiManagerComponent::ui() const\n{\n return d->ui;\n}\n\nvoid UiManagerComponent::setSize( const QSizeF& size )\n{\n d->size = size;\n}\n\nQSizeF UiManagerComponent::size() const\n{\n return d->size;\n}\n\nQ_EXPORT_PLUGIN2( gluon_component_uimanager, GluonEngine::UiManagerComponent );\n\n#include \"uimanagercomponent.moc\"\nResize the qml item when adding it to the scene.\/******************************************************************************\n * This file is part of the Gluon Development Platform\n * Copyright (c) 2010 Arjen Hiemstra \n * Copyright (c) 2011 Giulio Camuffo \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"uimanagercomponent.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"uiasset.h\"\n#include \"engineaccess.h\"\n#include \"renderablescene.h\"\n\nREGISTER_OBJECTTYPE( GluonEngine, UiManagerComponent )\n\nusing namespace GluonEngine;\nusing namespace GluonGraphics;\n\ntemplate \nQScriptValue scriptValueFromQObject( QScriptEngine *engine, Tp const& qobject)\n{\n return engine->newQObject( qobject );\n}\n\ntemplate \nvoid scriptValueToQObject(const QScriptValue &value, Tp &qobject)\n{\n qobject = qobject_cast( value.toQObject() );\n}\n\ntemplate \nint qScriptRegisterQObjectMetaType( QScriptEngine *engine )\n{\n return qScriptRegisterMetaType( engine, scriptValueFromQObject, scriptValueToQObject );\n}\n\nclass UiManagerComponent::UiManagerComponentPrivate\n{\n public:\n UiManagerComponentPrivate( UiManagerComponent *component )\n : q(component)\n , scene(0)\n , ui(0)\n , updateFunction(0)\n {\n }\n\n void setupBindings( QScriptEngine* engine )\n {\n \/\/FIXME: this code is duplicated with the scripting conponent.\n \/\/It should be moved to a common place.\n\n engine->importExtension( \"jsmoke.qtcore\" );\n engine->importExtension( \"jsmoke.qtgui\" );\n engine->importExtension( \"jsmoke.qtopengl\" );\n\n qScriptRegisterQObjectMetaType( engine );\n qScriptRegisterQObjectMetaType( engine );\n qScriptRegisterQObjectMetaType( engine );\n qScriptRegisterQObjectMetaType( engine );\n qScriptRegisterQObjectMetaType( engine );\n qScriptRegisterQObjectMetaType( engine );\n\n QScriptEngine::QObjectWrapOptions wrapOptions = QScriptEngine::AutoCreateDynamicProperties | QScriptEngine::ExcludeDeleteLater | QScriptEngine::PreferExistingWrapperObject;\n QScriptEngine::ValueOwnership ownership = QScriptEngine::QtOwnership;\n QScriptValue object = engine->globalObject();\n\n QScriptValue component = engine->newQObject( q, ownership, wrapOptions );\n object.setProperty( \"Component\", component );\n\n QScriptValue gameObj = engine->newQObject( q->gameObject(), ownership, wrapOptions );\n object.setProperty( \"GameObject\", gameObj );\n\n QScriptValue sceneObj = engine->newQObject( q->gameObject()->scene(), ownership, wrapOptions );\n object.setProperty( \"Scene\", sceneObj );\n\n QScriptValue gameProjectObj = engine->newQObject( GluonEngine::Game::instance()->gameProject(), ownership, wrapOptions );\n object.setProperty( \"GameProject\", gameProjectObj );\n\n QScriptValue game = engine->newQObject( GluonEngine::Game::instance(), ownership, wrapOptions );\n object.setProperty( \"Game\", game );\n }\n\n void resizeQmlItem( const QRectF& rect )\n {\n if ( ui )\n {\n QDeclarativeItem* item = ui->qmlItem();\n if( item )\n {\n item->setWidth( rect.width() );\n item->setHeight( rect.height() );\n }\n }\n }\n\n void reload()\n {\n q->cleanup();\n q->initialize();\n }\n\n UiManagerComponent* q;\n RenderableScene* scene;\n UiAsset *ui;\n QSizeF size;\n Item *item;\n EngineAccess* engineAccess;\n QScriptEngine* scriptEngine;\n\n QScriptValue scriptItem;\n QScriptValue updateFunction;\n};\n\nUiManagerComponent::UiManagerComponent( QObject* parent )\n : Component( parent )\n , d( new UiManagerComponentPrivate( this ) )\n{\n\n}\n\nUiManagerComponent::UiManagerComponent( const UiManagerComponent& other )\n : Component( other )\n , d( other.d )\n{\n}\n\nUiManagerComponent::~UiManagerComponent()\n{\n delete d;\n}\n\nQString UiManagerComponent::category() const\n{\n return QString( \"Graphics Rendering\" );\n}\n\nvoid UiManagerComponent::initialize()\n{\n if( !d->scene )\n {\n d->scene = new RenderableScene( this );\n connect( d->scene, SIGNAL( sceneRectChanged( const QRectF& ) ),\n this, SLOT( resizeQmlItem( const QRectF& ) ) );\n }\n\n if( d->ui && !d->ui->isLoaded() )\n {\n qmlRegisterType(\"org.kde.gluon\", 1, 0, \"GameObject\" );\n qmlRegisterInterface(\"gameObject\");\n\n d->ui->load();\n\n QDeclarativeEngine* engine = d->ui->engine();\n\n d->engineAccess = new EngineAccess(this);\n engine->rootContext()->setContextProperty( \"__engineAccess\", d->engineAccess );\n\n \/\/Glorious hack:steal the engine\n QDeclarativeExpression *expr = new QDeclarativeExpression( engine->rootContext(), 0,\n \"__engineAccess.setEngine( this )\" );\n expr->evaluate();\n delete expr;\n }\n\n if( d->ui && d->ui->isLoaded() )\n {\n d->ui->execute();\n\n QDeclarativeItem* item = d->ui->qmlItem();\n if( item )\n {\n d->scene->addItem( item );\n QRectF rect( d->scene->sceneRect() );\n item->setWidth( rect.width() );\n item->setHeight( rect.height() );\n\n d->scriptItem = d->scriptEngine->newQObject( item );\n d->updateFunction = d->scriptItem.property( \"update\" );\n }\n }\n}\n\nvoid UiManagerComponent::setScriptEngine( QScriptValue &value )\n{\n d->scriptEngine = value.engine();\n\n QScriptValue originalGlobalObject = d->scriptEngine->globalObject();\n QScriptValue newGlobalObject = d->scriptEngine->newObject();\n\n QString eval = QLatin1String( \"eval\" );\n QString version = QLatin1String( \"version\" );\n\n QScriptValueIterator iter( originalGlobalObject );\n QVector names;\n QVector values;\n QVector flags;\n while ( iter.hasNext() )\n {\n iter.next();\n\n QString name = iter.name();\n\n if ( name == version )\n {\n continue;\n }\n\n if ( name != eval )\n {\n names.append( name );\n values.append( iter.value() );\n flags.append( iter.flags() | QScriptValue::Undeletable );\n }\n newGlobalObject.setProperty( iter.scriptName(), iter.value() );\n }\n\n d->scriptEngine->setGlobalObject( newGlobalObject );\n\n d->setupBindings( d->scriptEngine );\n\n delete d->engineAccess;\n d->ui->engine()->rootContext()->setContextProperty( \"__engineAccess\", 0 );\n}\n\nvoid UiManagerComponent::start()\n{\n\n}\n\nvoid UiManagerComponent::draw( int timeLapse )\n{\n Q_UNUSED( timeLapse )\n\n if( !d->scene || !d->ui || !d->ui->qmlItem() )\n {\n return;\n }\n\n d->scene->renderScene();\n}\n\nvoid UiManagerComponent::update( int elapsedMilliseconds )\n{\n if( d->updateFunction.isFunction() )\n {\n d->updateFunction.call( d->scriptItem, QScriptValueList() << elapsedMilliseconds );\n if( d->scriptEngine->uncaughtException().isValid() )\n \/\/ This needs to be mapped...\n debug( QString( \"%1: %2\" )\n .arg( d->scriptEngine->uncaughtException().toString() )\n .arg( d->scriptEngine->uncaughtExceptionBacktrace().join( \" \" ) ) );\n }\n}\n\nvoid UiManagerComponent::cleanup()\n{\n if( !d->ui )\n {\n return;\n }\n\n QDeclarativeItem* item = d->ui->qmlItem();\n if( d->scene && item && item->scene() == d->scene )\n {\n d->scene->removeItem( item );\n }\n\n delete d->scene;\n d->scene = 0;\n}\n\nvoid UiManagerComponent::setUi(UiAsset* ui)\n{\n d->ui = ui;\n\n connect( ui, SIGNAL( dataChanged() ), this, SLOT( reload() ) );\n}\n\nUiAsset* UiManagerComponent::ui() const\n{\n return d->ui;\n}\n\nvoid UiManagerComponent::setSize( const QSizeF& size )\n{\n d->size = size;\n}\n\nQSizeF UiManagerComponent::size() const\n{\n return d->size;\n}\n\nQ_EXPORT_PLUGIN2( gluon_component_uimanager, GluonEngine::UiManagerComponent );\n\n#include \"uimanagercomponent.moc\"\n<|endoftext|>"} {"text":"#include \n\nusing namespace std;\n\nstatic const string textureNames[]{\n \"spaceship1.png\", \"spaceship2.png\", \"spaceship3.png\",\n \"Spaceship-Drakir1.png\", \"Spaceship-Drakir2.png\", \"Spaceship-Drakir3.png\",\n \"Spaceship-Drakir4.png\", \"Spaceship-Drakir5.png\", \"Spaceship-Drakir6.png\",\n \"Spaceship-Drakir7.png\",\n};\n\nstatic sf::Texture *textures[10];\n\nstatic const string filepath = \"..\\\\res\/img\/\";\n\nstatic sf::Sprite enemies[16];\n\nsf::Sprite playerSprite;\nsf::Texture *playerTexture;\n\nvoid Loadcontent() {\n\n for (size_t i = 0; i < 10; i++) {\n textures[i] = new sf::Texture();\n if (!textures[i]->loadFromFile(filepath + textureNames[i])) {\n throw invalid_argument(\"Ship not loaded!\");\n }\n }\n playerSprite.setTexture(*textures[0]);\n playerSprite.setPosition(512, 256);\n\n for (size_t i = 0; i < 16; i++) {\n enemies[i].setTexture(*textures[(i % 7) + 3]);\n enemies[i].setPosition(sf::Vector2f((1024 \/ 16) * i, (i % 4) * 20));\n }\n}\n\nvoid Update(sf::RenderWindow &window) {\n static float tick = 0.0f;\n tick += 0.01f;\n sf::Event e;\n\n while (window.pollEvent(e)) {\n if (e.type == sf::Event::Closed)\n window.close();\n\n\t\/\/keyboard event handling\n\tif (e.type == sf::Event::KeyPressed) {\n\t\tif (e.key.code == sf::Keyboard::Escape)\n\t\t{\n\t\t\twindow.close();\n\t\t}\n\n\t\tif (e.key.code == sf::Keyboard::W)\n\t\t{\n\t\t\tplayerSprite.setPosition(playerSprite.getPosition().x, playerSprite.getPosition().y - tick);\n\t\t}\n\n\t\tif (e.key.code == sf::Keyboard::S)\n\t\t{\n\t\t\tplayerSprite.setPosition(playerSprite.getPosition().x, playerSprite.getPosition().y + tick);\n\t\t}\n\t\tif (e.key.code == sf::Keyboard::A)\n\t\t{\n\t\t\tplayerSprite.setPosition(playerSprite.getPosition().x - tick, playerSprite.getPosition().y);\n\t\t}\n\t\tif (e.key.code == sf::Keyboard::D)\n\t\t{\n\t\t\tplayerSprite.setPosition(playerSprite.getPosition().x + tick, playerSprite.getPosition().y);\n\t\t}\n\t}\n\n\t\/\/joystick input\n\t if (sf::Joystick::isConnected(0))\n\t{\n\t\tfloat joystickX = sf::Joystick::getAxisPosition(0, sf::Joystick::X);\n\t\tfloat joystickY = sf::Joystick::getAxisPosition(0, sf::Joystick::Y);\n\n\t\tplayerSprite.setPosition(playerSprite.getPosition().x + (joystickX * 0.1), playerSprite.getPosition().y + (joystickY * 0.1));\n\n\t} \n\n }\n\n for (size_t i = 0; i < 16; i++) {\n enemies[i].setPosition(enemies[i].getPosition() +\n sf::Vector2f(sinf(tick + i), 1));\n }\n}\n\nvoid Render(sf::RenderWindow &window) {\n window.clear();\n\n window.draw(playerSprite);\n for (size_t i = 0; i < 16; i++) {\n window.draw(enemies[i]);\n }\n\n window.display();\n}\n\nint main() {\n Loadcontent();\n sf::RenderWindow window(sf::VideoMode(1024, 768), \"Main Window\");\n window.setVerticalSyncEnabled(true);\n while (window.isOpen()) {\n Update(window);\n Render(window);\n }\n return 0;\n}joystick controlls#include \n\nusing namespace std;\n\nstatic const string textureNames[]{\"spaceship1.png\",\n \"spaceship2.png\",\n \"spaceship3.png\",\n \"Spaceship-Drakir1.png\",\n \"Spaceship-Drakir2.png\",\n \"Spaceship-Drakir3.png\",\n \"Spaceship-Drakir4.png\",\n \"Spaceship-Drakir5.png\",\n \"Spaceship-Drakir6.png\",\n \"Spaceship-Drakir7.png\",\n \"bullet.png\"};\n\nstatic sf::Texture *textures[11];\n\nstatic const string filepath = \"..\\\\res\/img\/\";\n\nstatic sf::Sprite enemies[16];\n\nsf::Sprite playerSprite;\nsf::Texture *playerTexture;\nsf::Sprite bulletsprite;\nsf::Texture *bulletTexture;\nvoid Loadcontent() {\n\n for (size_t i = 0; i < 11; i++) {\n textures[i] = new sf::Texture();\n if (!textures[i]->loadFromFile(filepath + textureNames[i])) {\n throw invalid_argument(\"Loading error!\");\n }\n }\n\n playerSprite.setTexture(*textures[0]);\n playerSprite.setPosition(512, 256);\n bulletsprite.setTexture(*textures[10]);\n\n for (size_t i = 0; i < 16; i++) {\n enemies[i].setTexture(*textures[(i % 7) + 3]);\n enemies[i].setPosition(sf::Vector2f((1024 \/ 16) * i, (i % 4) * 20));\n }\n}\n\nvoid Update(sf::RenderWindow &window) {\n static float tick = 0.0f;\n tick += 0.01f;\n sf::Event e;\n\n while (window.pollEvent(e)) {\n if (e.type == sf::Event::Closed)\n window.close();\n\n \/\/ keyboard event handling\n if (e.type == sf::Event::KeyPressed) {\n if (e.key.code == sf::Keyboard::Escape) {\n window.close();\n }\n\n if (e.key.code == sf::Keyboard::W) {\n playerSprite.setPosition(playerSprite.getPosition().x,\n playerSprite.getPosition().y - tick);\n }\n\n if (e.key.code == sf::Keyboard::S) {\n playerSprite.setPosition(playerSprite.getPosition().x,\n playerSprite.getPosition().y + tick);\n }\n if (e.key.code == sf::Keyboard::A) {\n playerSprite.setPosition(playerSprite.getPosition().x - tick,\n playerSprite.getPosition().y);\n }\n if (e.key.code == sf::Keyboard::D) {\n playerSprite.setPosition(playerSprite.getPosition().x + tick,\n playerSprite.getPosition().y);\n }\n }\n\n \/\/ joystick input\n if (sf::Joystick::isConnected(0)) {\n float joystickX = sf::Joystick::getAxisPosition(0, sf::Joystick::X);\n float joystickY = sf::Joystick::getAxisPosition(0, sf::Joystick::Y);\n\n playerSprite.setPosition(playerSprite.getPosition().x + (joystickX * 0.1),\n playerSprite.getPosition().y +\n (joystickY * 0.1));\n\n \/\/ if the B button is pressed fire a bullet\n if (e.JoystickButtonPressed) {\n if (e.joystickButton.button == 0) {\n bulletsprite.setPosition(playerSprite.getPosition().x + 30,\n playerSprite.getPosition().y - 1);\n }\n }\n\n bulletsprite.setPosition(bulletsprite.getPosition().x,\n bulletsprite.getPosition().y - tick);\n }\n }\n\n for (size_t i = 0; i < 16; i++) {\n enemies[i].setPosition(enemies[i].getPosition() +\n sf::Vector2f(sinf(tick + i), 1));\n }\n}\n\nvoid Render(sf::RenderWindow &window) {\n window.clear();\n\n window.draw(playerSprite);\n\n window.draw(bulletsprite);\n\n for (size_t i = 0; i < 16; i++) {\n window.draw(enemies[i]);\n }\n\n window.display();\n}\n\nint main() {\n Loadcontent();\n sf::RenderWindow window(sf::VideoMode(1024, 768), \"Main Window\");\n window.setVerticalSyncEnabled(true);\n while (window.isOpen()) {\n Update(window);\n Render(window);\n }\n return 0;\n}<|endoftext|>"} {"text":"\/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/lite\/tools\/benchmark\/benchmark_performance_options.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"tensorflow\/core\/util\/stats_calculator.h\"\n#include \"tensorflow\/lite\/c\/common.h\"\n#if defined(__ANDROID__)\n#include \"tensorflow\/lite\/delegates\/gpu\/delegate.h\"\n#include \"tensorflow\/lite\/nnapi\/nnapi_util.h\"\n#endif\n#include \"tensorflow\/lite\/profiling\/time.h\"\n#include \"tensorflow\/lite\/tools\/benchmark\/benchmark_params.h\"\n#include \"tensorflow\/lite\/tools\/benchmark\/benchmark_utils.h\"\n#include \"tensorflow\/lite\/tools\/command_line_flags.h\"\n#include \"tensorflow\/lite\/tools\/logging.h\"\n\nnamespace tflite {\nnamespace benchmark {\n\nstd::string MultiRunStatsRecorder::PerfOptionName(\n const BenchmarkParams& params) const {\n#if defined(__ANDROID__)\n if (params.Get(\"use_nnapi\")) {\n const std::string accelerator =\n params.Get(\"nnapi_accelerator_name\");\n return accelerator.empty() ? \"nnapi(w\/o accel name)\"\n : \"nnapi(\" + accelerator + \")\";\n }\n#endif\n\n if (params.Get(\"use_gpu\")) {\n#if defined(__ANDROID__)\n if (params.Get(\"gpu_precision_loss_allowed\")) {\n return \"gpu-fp16\";\n } else {\n return \"gpu-default\";\n }\n#else\n return \"gpu-default\";\n#endif\n }\n\n#if defined(TFLITE_ENABLE_HEXAGON)\n if (params.Get(\"use_hexagon\")) {\n return \"dsp w\/ hexagon\";\n }\n#endif\n\n \/\/ Handle cases run on CPU\n \/\/ Note: could use std::to_string to convert an integer to string but it\n \/\/ requires C++11.\n std::stringstream sstm;\n sstm << \"cpu w\/ \" << params.Get(\"num_threads\") << \" threads\";\n\n \/\/ Handle cases run on CPU w\/ the xnnpack delegate\n if (params.Get(\"use_xnnpack\")) {\n sstm << \" (xnnpack)\";\n }\n\n return sstm.str();\n}\n\nvoid MultiRunStatsRecorder::OutputStats() {\n \/\/ Make a 80-character-long header.\n TFLITE_LOG(INFO) << \"\\n==============Summary of All Runs w\/ Different \"\n \"Performance Options==============\";\n std::sort(results_.begin(), results_.end(), EachRunStatsEntryComparator());\n\n for (const auto& run_stats : results_) {\n const auto perf_option_name = PerfOptionName(*run_stats.params);\n std::stringstream stream;\n stream << std::setw(26) << perf_option_name << \": \";\n if (!run_stats.completed) {\n stream << \" failed!\";\n } else {\n run_stats.metrics.inference_time_us().OutputToStream(&stream);\n \/\/ NOTE: As of 2019\/11\/07, the memory usage is collected in an\n \/\/ OS-process-wide way and this program performs multiple runs in a single\n \/\/ OS process, therefore, the memory usage information of each run becomes\n \/\/ incorrect, hence no output here.\n }\n TFLITE_LOG(INFO) << stream.str();\n }\n}\n\nBenchmarkPerformanceOptions::BenchmarkPerformanceOptions(\n BenchmarkModel* single_option_run,\n std::unique_ptr all_run_stats)\n : BenchmarkPerformanceOptions(DefaultParams(), single_option_run,\n std::move(all_run_stats)) {}\n\nBenchmarkPerformanceOptions::BenchmarkPerformanceOptions(\n BenchmarkParams params, BenchmarkModel* single_option_run,\n std::unique_ptr all_run_stats)\n : params_(std::move(params)),\n single_option_run_(single_option_run),\n single_option_run_params_(single_option_run->mutable_params()),\n all_run_stats_(std::move(all_run_stats)) {\n single_option_run_->AddListener(all_run_stats_.get());\n}\n\nBenchmarkParams BenchmarkPerformanceOptions::DefaultParams() {\n BenchmarkParams params;\n params.AddParam(\"perf_options_list\",\n BenchmarkParam::Create(\"all\"));\n params.AddParam(\"option_benchmark_run_delay\",\n BenchmarkParam::Create(-1.0f));\n params.AddParam(\"random_shuffle_benchmark_runs\",\n BenchmarkParam::Create(true));\n return params;\n}\n\nstd::vector BenchmarkPerformanceOptions::GetFlags() {\n return {\n CreateFlag(\n \"perf_options_list\", ¶ms_,\n \"A comma-separated list of TFLite performance options to benchmark. \"\n \"By default, all performance options are benchmarked. Note if it's \"\n \"set to 'none', then the tool simply benchmark the model against the \"\n \"specified benchmark parameters.\"),\n CreateFlag(\"option_benchmark_run_delay\", ¶ms_,\n \"The delay between two consecutive runs of \"\n \"benchmarking performance options in seconds.\"),\n CreateFlag(\n \"random_shuffle_benchmark_runs\", ¶ms_,\n \"Whether to perform all benchmark runs, each of which has different \"\n \"performance options, in a random order. It is enabled by default.\"),\n };\n}\n\nbool BenchmarkPerformanceOptions::ParseFlags(int* argc, char** argv) {\n auto flag_list = GetFlags();\n const bool parse_result =\n Flags::Parse(argc, const_cast(argv), flag_list);\n if (!parse_result) {\n std::string usage = Flags::Usage(argv[0], flag_list);\n TFLITE_LOG(ERROR) << usage;\n return false;\n }\n\n \/\/ Parse the value of --perf_options_list to find performance options to be\n \/\/ benchmarked.\n return ParsePerfOptions();\n}\n\nbool BenchmarkPerformanceOptions::ParsePerfOptions() {\n const auto& perf_options_list = params_.Get(\"perf_options_list\");\n if (!util::SplitAndParse(perf_options_list, ',', &perf_options_)) {\n TFLITE_LOG(ERROR) << \"Cannot parse --perf_options_list: '\"\n << perf_options_list\n << \"'. Please double-check its value.\";\n perf_options_.clear();\n return false;\n }\n\n const auto valid_options = GetValidPerfOptions();\n bool is_valid = true;\n for (const auto& option : perf_options_) {\n if (std::find(valid_options.begin(), valid_options.end(), option) ==\n valid_options.end()) {\n is_valid = false;\n break;\n }\n }\n if (!is_valid) {\n std::string valid_options_str;\n for (int i = 0; i < valid_options.size() - 1; ++i) {\n valid_options_str += (valid_options[i] + \", \");\n }\n valid_options_str += valid_options.back();\n TFLITE_LOG(ERROR)\n << \"There are invalid perf options in --perf_options_list: '\"\n << perf_options_list << \"'. Valid perf options are: [\"\n << valid_options_str << \"]\";\n perf_options_.clear();\n return false;\n }\n\n if (HasOption(\"none\") && perf_options_.size() > 1) {\n TFLITE_LOG(ERROR) << \"The 'none' option can not be used together with \"\n \"other perf options in --perf_options_list!\";\n perf_options_.clear();\n return false;\n }\n return true;\n}\n\nstd::vector BenchmarkPerformanceOptions::GetValidPerfOptions()\n const {\n std::vector valid_options = {\"all\", \"cpu\", \"gpu\", \"nnapi\",\n \"none\"};\n#if defined(TFLITE_ENABLE_HEXAGON)\n valid_options.emplace_back(\"dsp\");\n#endif\n return valid_options;\n}\n\nbool BenchmarkPerformanceOptions::HasOption(const std::string& option) const {\n return std::find(perf_options_.begin(), perf_options_.end(), option) !=\n perf_options_.end();\n}\n\nvoid BenchmarkPerformanceOptions::ResetPerformanceOptions() {\n single_option_run_params_->Set(\"num_threads\", 1);\n single_option_run_params_->Set(\"use_gpu\", false);\n#if defined(__ANDROID__)\n single_option_run_params_->Set(\"gpu_precision_loss_allowed\", true);\n single_option_run_params_->Set(\"use_nnapi\", false);\n single_option_run_params_->Set(\"nnapi_accelerator_name\", \"\");\n single_option_run_params_->Set(\"disable_nnapi_cpu\", false);\n single_option_run_params_->Set(\"max_delegated_partitions\", 0);\n single_option_run_params_->Set(\"nnapi_allow_fp16\", false);\n#endif\n#if defined(TFLITE_ENABLE_HEXAGON)\n single_option_run_params_->Set(\"use_hexagon\", false);\n#endif\n single_option_run_params_->Set(\"use_xnnpack\", false);\n}\n\nvoid BenchmarkPerformanceOptions::CreatePerformanceOptions() {\n TFLITE_LOG(INFO) << \"The list of TFLite runtime options to be benchmarked: [\"\n << params_.Get(\"perf_options_list\") << \"]\";\n\n if (HasOption(\"none\")) {\n \/\/ Just add an empty BenchmarkParams instance.\n BenchmarkParams params;\n all_run_params_.emplace_back(std::move(params));\n \/\/ As 'none' is exclusive to others, simply return here.\n return;\n }\n\n const bool benchmark_all = HasOption(\"all\");\n\n if (benchmark_all || HasOption(\"cpu\")) {\n const std::vector num_threads = {1, 2, 4};\n for (const int count : num_threads) {\n BenchmarkParams params;\n params.AddParam(\"num_threads\", BenchmarkParam::Create(count));\n all_run_params_.emplace_back(std::move(params));\n\n BenchmarkParams xnnpack_params;\n xnnpack_params.AddParam(\"use_xnnpack\",\n BenchmarkParam::Create(true));\n xnnpack_params.AddParam(\"num_threads\",\n BenchmarkParam::Create(count));\n all_run_params_.emplace_back(std::move(xnnpack_params));\n }\n }\n\n if (benchmark_all || HasOption(\"gpu\")) {\n#if defined(__ANDROID__)\n const std::vector allow_precision_loss = {true, false};\n for (const auto precision_loss : allow_precision_loss) {\n BenchmarkParams params;\n params.AddParam(\"use_gpu\", BenchmarkParam::Create(true));\n params.AddParam(\"gpu_precision_loss_allowed\",\n BenchmarkParam::Create(precision_loss));\n all_run_params_.emplace_back(std::move(params));\n }\n#else\n BenchmarkParams params;\n params.AddParam(\"use_gpu\", BenchmarkParam::Create(true));\n all_run_params_.emplace_back(std::move(params));\n#endif\n }\n\n#if defined(__ANDROID__)\n if (benchmark_all || HasOption(\"nnapi\")) {\n std::string nnapi_accelerators = nnapi::GetStringDeviceNamesList();\n if (!nnapi_accelerators.empty()) {\n std::vector device_names;\n util::SplitAndParse(nnapi_accelerators, ',', &device_names);\n for (const auto& name : device_names) {\n BenchmarkParams params;\n params.AddParam(\"use_nnapi\", BenchmarkParam::Create(true));\n params.AddParam(\"nnapi_accelerator_name\",\n BenchmarkParam::Create(name));\n params.AddParam(\"disable_nnapi_cpu\",\n BenchmarkParam::Create(false));\n params.AddParam(\"max_delegated_partitions\",\n BenchmarkParam::Create(0));\n all_run_params_.emplace_back(std::move(params));\n }\n }\n \/\/ Explicitly test the case when there's no \"nnapi_accelerator_name\"\n \/\/ parameter as the nnpai execution is different from the case when\n \/\/ an accelerator name is explicitly specified.\n BenchmarkParams params;\n params.AddParam(\"use_nnapi\", BenchmarkParam::Create(true));\n all_run_params_.emplace_back(std::move(params));\n }\n#endif\n\n#if defined(TFLITE_ENABLE_HEXAGON)\n if (benchmark_all || HasOption(\"dsp\")) {\n BenchmarkParams params;\n params.AddParam(\"use_hexagon\", BenchmarkParam::Create(true));\n all_run_params_.emplace_back(std::move(params));\n }\n#endif\n}\n\nvoid BenchmarkPerformanceOptions::Run() {\n CreatePerformanceOptions();\n\n if (params_.Get(\"random_shuffle_benchmark_runs\")) {\n std::random_shuffle(all_run_params_.begin(), all_run_params_.end());\n }\n\n \/\/ We need to clean *internally* created benchmark listeners, like the\n \/\/ profiling listener etc. in each Run() invoke because such listeners may be\n \/\/ reset and become invalid in the next Run(). As a result, we record the\n \/\/ number of externally-added listeners here to prevent they're cleared later.\n const int num_external_listeners = single_option_run_->NumListeners();\n\n \/\/ Now perform all runs, each with different performance-affecting parameters.\n for (const auto& run_params : all_run_params_) {\n \/\/ If the run_params is empty, then it means \"none\" is set for\n \/\/ --perf_options_list.\n if (!run_params.Empty()) {\n \/\/ Reset all performance-related options before any runs.\n ResetPerformanceOptions();\n single_option_run_params_->Set(run_params);\n }\n util::SleepForSeconds(params_.Get(\"option_benchmark_run_delay\"));\n\n \/\/ Clear internally created listeners before each run but keep externally\n \/\/ created ones.\n single_option_run_->RemoveListeners(num_external_listeners);\n\n all_run_stats_->MarkBenchmarkStart(*single_option_run_params_);\n single_option_run_->Run();\n }\n\n all_run_stats_->OutputStats();\n}\n\nvoid BenchmarkPerformanceOptions::Run(int argc, char** argv) {\n \/\/ Parse flags that are supported by this particular binary first.\n if (!ParseFlags(&argc, argv)) return;\n\n \/\/ Then parse flags for single-option runs to get information like parameters\n \/\/ of the input model etc.\n if (single_option_run_->ParseFlags(&argc, argv) != kTfLiteOk) return;\n\n \/\/ Now, the remaining are unrecognized flags and we simply print them out.\n for (int i = 1; i < argc; ++i) {\n TFLITE_LOG(WARN) << \"WARNING: unrecognized commandline flag: \" << argv[i];\n }\n\n Run();\n}\n} \/\/ namespace benchmark\n} \/\/ namespace tflite\n[lite] Update random_shuffle to std::shuffle and use version which accept random generator. random_shuffle was removed in C++17\/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/lite\/tools\/benchmark\/benchmark_performance_options.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"tensorflow\/core\/util\/stats_calculator.h\"\n#include \"tensorflow\/lite\/c\/common.h\"\n#if defined(__ANDROID__)\n#include \"tensorflow\/lite\/delegates\/gpu\/delegate.h\"\n#include \"tensorflow\/lite\/nnapi\/nnapi_util.h\"\n#endif\n#include \"tensorflow\/lite\/profiling\/time.h\"\n#include \"tensorflow\/lite\/tools\/benchmark\/benchmark_params.h\"\n#include \"tensorflow\/lite\/tools\/benchmark\/benchmark_utils.h\"\n#include \"tensorflow\/lite\/tools\/command_line_flags.h\"\n#include \"tensorflow\/lite\/tools\/logging.h\"\n\nnamespace tflite {\nnamespace benchmark {\n\nstd::string MultiRunStatsRecorder::PerfOptionName(\n const BenchmarkParams& params) const {\n#if defined(__ANDROID__)\n if (params.Get(\"use_nnapi\")) {\n const std::string accelerator =\n params.Get(\"nnapi_accelerator_name\");\n return accelerator.empty() ? \"nnapi(w\/o accel name)\"\n : \"nnapi(\" + accelerator + \")\";\n }\n#endif\n\n if (params.Get(\"use_gpu\")) {\n#if defined(__ANDROID__)\n if (params.Get(\"gpu_precision_loss_allowed\")) {\n return \"gpu-fp16\";\n } else {\n return \"gpu-default\";\n }\n#else\n return \"gpu-default\";\n#endif\n }\n\n#if defined(TFLITE_ENABLE_HEXAGON)\n if (params.Get(\"use_hexagon\")) {\n return \"dsp w\/ hexagon\";\n }\n#endif\n\n \/\/ Handle cases run on CPU\n \/\/ Note: could use std::to_string to convert an integer to string but it\n \/\/ requires C++11.\n std::stringstream sstm;\n sstm << \"cpu w\/ \" << params.Get(\"num_threads\") << \" threads\";\n\n \/\/ Handle cases run on CPU w\/ the xnnpack delegate\n if (params.Get(\"use_xnnpack\")) {\n sstm << \" (xnnpack)\";\n }\n\n return sstm.str();\n}\n\nvoid MultiRunStatsRecorder::OutputStats() {\n \/\/ Make a 80-character-long header.\n TFLITE_LOG(INFO) << \"\\n==============Summary of All Runs w\/ Different \"\n \"Performance Options==============\";\n std::sort(results_.begin(), results_.end(), EachRunStatsEntryComparator());\n\n for (const auto& run_stats : results_) {\n const auto perf_option_name = PerfOptionName(*run_stats.params);\n std::stringstream stream;\n stream << std::setw(26) << perf_option_name << \": \";\n if (!run_stats.completed) {\n stream << \" failed!\";\n } else {\n run_stats.metrics.inference_time_us().OutputToStream(&stream);\n \/\/ NOTE: As of 2019\/11\/07, the memory usage is collected in an\n \/\/ OS-process-wide way and this program performs multiple runs in a single\n \/\/ OS process, therefore, the memory usage information of each run becomes\n \/\/ incorrect, hence no output here.\n }\n TFLITE_LOG(INFO) << stream.str();\n }\n}\n\nBenchmarkPerformanceOptions::BenchmarkPerformanceOptions(\n BenchmarkModel* single_option_run,\n std::unique_ptr all_run_stats)\n : BenchmarkPerformanceOptions(DefaultParams(), single_option_run,\n std::move(all_run_stats)) {}\n\nBenchmarkPerformanceOptions::BenchmarkPerformanceOptions(\n BenchmarkParams params, BenchmarkModel* single_option_run,\n std::unique_ptr all_run_stats)\n : params_(std::move(params)),\n single_option_run_(single_option_run),\n single_option_run_params_(single_option_run->mutable_params()),\n all_run_stats_(std::move(all_run_stats)) {\n single_option_run_->AddListener(all_run_stats_.get());\n}\n\nBenchmarkParams BenchmarkPerformanceOptions::DefaultParams() {\n BenchmarkParams params;\n params.AddParam(\"perf_options_list\",\n BenchmarkParam::Create(\"all\"));\n params.AddParam(\"option_benchmark_run_delay\",\n BenchmarkParam::Create(-1.0f));\n params.AddParam(\"random_shuffle_benchmark_runs\",\n BenchmarkParam::Create(true));\n return params;\n}\n\nstd::vector BenchmarkPerformanceOptions::GetFlags() {\n return {\n CreateFlag(\n \"perf_options_list\", ¶ms_,\n \"A comma-separated list of TFLite performance options to benchmark. \"\n \"By default, all performance options are benchmarked. Note if it's \"\n \"set to 'none', then the tool simply benchmark the model against the \"\n \"specified benchmark parameters.\"),\n CreateFlag(\"option_benchmark_run_delay\", ¶ms_,\n \"The delay between two consecutive runs of \"\n \"benchmarking performance options in seconds.\"),\n CreateFlag(\n \"random_shuffle_benchmark_runs\", ¶ms_,\n \"Whether to perform all benchmark runs, each of which has different \"\n \"performance options, in a random order. It is enabled by default.\"),\n };\n}\n\nbool BenchmarkPerformanceOptions::ParseFlags(int* argc, char** argv) {\n auto flag_list = GetFlags();\n const bool parse_result =\n Flags::Parse(argc, const_cast(argv), flag_list);\n if (!parse_result) {\n std::string usage = Flags::Usage(argv[0], flag_list);\n TFLITE_LOG(ERROR) << usage;\n return false;\n }\n\n \/\/ Parse the value of --perf_options_list to find performance options to be\n \/\/ benchmarked.\n return ParsePerfOptions();\n}\n\nbool BenchmarkPerformanceOptions::ParsePerfOptions() {\n const auto& perf_options_list = params_.Get(\"perf_options_list\");\n if (!util::SplitAndParse(perf_options_list, ',', &perf_options_)) {\n TFLITE_LOG(ERROR) << \"Cannot parse --perf_options_list: '\"\n << perf_options_list\n << \"'. Please double-check its value.\";\n perf_options_.clear();\n return false;\n }\n\n const auto valid_options = GetValidPerfOptions();\n bool is_valid = true;\n for (const auto& option : perf_options_) {\n if (std::find(valid_options.begin(), valid_options.end(), option) ==\n valid_options.end()) {\n is_valid = false;\n break;\n }\n }\n if (!is_valid) {\n std::string valid_options_str;\n for (int i = 0; i < valid_options.size() - 1; ++i) {\n valid_options_str += (valid_options[i] + \", \");\n }\n valid_options_str += valid_options.back();\n TFLITE_LOG(ERROR)\n << \"There are invalid perf options in --perf_options_list: '\"\n << perf_options_list << \"'. Valid perf options are: [\"\n << valid_options_str << \"]\";\n perf_options_.clear();\n return false;\n }\n\n if (HasOption(\"none\") && perf_options_.size() > 1) {\n TFLITE_LOG(ERROR) << \"The 'none' option can not be used together with \"\n \"other perf options in --perf_options_list!\";\n perf_options_.clear();\n return false;\n }\n return true;\n}\n\nstd::vector BenchmarkPerformanceOptions::GetValidPerfOptions()\n const {\n std::vector valid_options = {\"all\", \"cpu\", \"gpu\", \"nnapi\",\n \"none\"};\n#if defined(TFLITE_ENABLE_HEXAGON)\n valid_options.emplace_back(\"dsp\");\n#endif\n return valid_options;\n}\n\nbool BenchmarkPerformanceOptions::HasOption(const std::string& option) const {\n return std::find(perf_options_.begin(), perf_options_.end(), option) !=\n perf_options_.end();\n}\n\nvoid BenchmarkPerformanceOptions::ResetPerformanceOptions() {\n single_option_run_params_->Set(\"num_threads\", 1);\n single_option_run_params_->Set(\"use_gpu\", false);\n#if defined(__ANDROID__)\n single_option_run_params_->Set(\"gpu_precision_loss_allowed\", true);\n single_option_run_params_->Set(\"use_nnapi\", false);\n single_option_run_params_->Set(\"nnapi_accelerator_name\", \"\");\n single_option_run_params_->Set(\"disable_nnapi_cpu\", false);\n single_option_run_params_->Set(\"max_delegated_partitions\", 0);\n single_option_run_params_->Set(\"nnapi_allow_fp16\", false);\n#endif\n#if defined(TFLITE_ENABLE_HEXAGON)\n single_option_run_params_->Set(\"use_hexagon\", false);\n#endif\n single_option_run_params_->Set(\"use_xnnpack\", false);\n}\n\nvoid BenchmarkPerformanceOptions::CreatePerformanceOptions() {\n TFLITE_LOG(INFO) << \"The list of TFLite runtime options to be benchmarked: [\"\n << params_.Get(\"perf_options_list\") << \"]\";\n\n if (HasOption(\"none\")) {\n \/\/ Just add an empty BenchmarkParams instance.\n BenchmarkParams params;\n all_run_params_.emplace_back(std::move(params));\n \/\/ As 'none' is exclusive to others, simply return here.\n return;\n }\n\n const bool benchmark_all = HasOption(\"all\");\n\n if (benchmark_all || HasOption(\"cpu\")) {\n const std::vector num_threads = {1, 2, 4};\n for (const int count : num_threads) {\n BenchmarkParams params;\n params.AddParam(\"num_threads\", BenchmarkParam::Create(count));\n all_run_params_.emplace_back(std::move(params));\n\n BenchmarkParams xnnpack_params;\n xnnpack_params.AddParam(\"use_xnnpack\",\n BenchmarkParam::Create(true));\n xnnpack_params.AddParam(\"num_threads\",\n BenchmarkParam::Create(count));\n all_run_params_.emplace_back(std::move(xnnpack_params));\n }\n }\n\n if (benchmark_all || HasOption(\"gpu\")) {\n#if defined(__ANDROID__)\n const std::vector allow_precision_loss = {true, false};\n for (const auto precision_loss : allow_precision_loss) {\n BenchmarkParams params;\n params.AddParam(\"use_gpu\", BenchmarkParam::Create(true));\n params.AddParam(\"gpu_precision_loss_allowed\",\n BenchmarkParam::Create(precision_loss));\n all_run_params_.emplace_back(std::move(params));\n }\n#else\n BenchmarkParams params;\n params.AddParam(\"use_gpu\", BenchmarkParam::Create(true));\n all_run_params_.emplace_back(std::move(params));\n#endif\n }\n\n#if defined(__ANDROID__)\n if (benchmark_all || HasOption(\"nnapi\")) {\n std::string nnapi_accelerators = nnapi::GetStringDeviceNamesList();\n if (!nnapi_accelerators.empty()) {\n std::vector device_names;\n util::SplitAndParse(nnapi_accelerators, ',', &device_names);\n for (const auto& name : device_names) {\n BenchmarkParams params;\n params.AddParam(\"use_nnapi\", BenchmarkParam::Create(true));\n params.AddParam(\"nnapi_accelerator_name\",\n BenchmarkParam::Create(name));\n params.AddParam(\"disable_nnapi_cpu\",\n BenchmarkParam::Create(false));\n params.AddParam(\"max_delegated_partitions\",\n BenchmarkParam::Create(0));\n all_run_params_.emplace_back(std::move(params));\n }\n }\n \/\/ Explicitly test the case when there's no \"nnapi_accelerator_name\"\n \/\/ parameter as the nnpai execution is different from the case when\n \/\/ an accelerator name is explicitly specified.\n BenchmarkParams params;\n params.AddParam(\"use_nnapi\", BenchmarkParam::Create(true));\n all_run_params_.emplace_back(std::move(params));\n }\n#endif\n\n#if defined(TFLITE_ENABLE_HEXAGON)\n if (benchmark_all || HasOption(\"dsp\")) {\n BenchmarkParams params;\n params.AddParam(\"use_hexagon\", BenchmarkParam::Create(true));\n all_run_params_.emplace_back(std::move(params));\n }\n#endif\n}\n\nvoid BenchmarkPerformanceOptions::Run() {\n CreatePerformanceOptions();\n\n if (params_.Get(\"random_shuffle_benchmark_runs\")) {\n std::random_device rd;\n std::mt19937 generator(rd());\n std::shuffle(all_run_params_.begin(), all_run_params_.end(), generator);\n }\n\n \/\/ We need to clean *internally* created benchmark listeners, like the\n \/\/ profiling listener etc. in each Run() invoke because such listeners may be\n \/\/ reset and become invalid in the next Run(). As a result, we record the\n \/\/ number of externally-added listeners here to prevent they're cleared later.\n const int num_external_listeners = single_option_run_->NumListeners();\n\n \/\/ Now perform all runs, each with different performance-affecting parameters.\n for (const auto& run_params : all_run_params_) {\n \/\/ If the run_params is empty, then it means \"none\" is set for\n \/\/ --perf_options_list.\n if (!run_params.Empty()) {\n \/\/ Reset all performance-related options before any runs.\n ResetPerformanceOptions();\n single_option_run_params_->Set(run_params);\n }\n util::SleepForSeconds(params_.Get(\"option_benchmark_run_delay\"));\n\n \/\/ Clear internally created listeners before each run but keep externally\n \/\/ created ones.\n single_option_run_->RemoveListeners(num_external_listeners);\n\n all_run_stats_->MarkBenchmarkStart(*single_option_run_params_);\n single_option_run_->Run();\n }\n\n all_run_stats_->OutputStats();\n}\n\nvoid BenchmarkPerformanceOptions::Run(int argc, char** argv) {\n \/\/ Parse flags that are supported by this particular binary first.\n if (!ParseFlags(&argc, argv)) return;\n\n \/\/ Then parse flags for single-option runs to get information like parameters\n \/\/ of the input model etc.\n if (single_option_run_->ParseFlags(&argc, argv) != kTfLiteOk) return;\n\n \/\/ Now, the remaining are unrecognized flags and we simply print them out.\n for (int i = 1; i < argc; ++i) {\n TFLITE_LOG(WARN) << \"WARNING: unrecognized commandline flag: \" << argv[i];\n }\n\n Run();\n}\n} \/\/ namespace benchmark\n} \/\/ namespace tflite\n<|endoftext|>"} {"text":"#include \"mex.h\"\n#include \"opencv_matlab_interop.h\"\n\n#define PRINT_INPUTS\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {\n ASSERT_NUM_RHS_ARGS_EQUALS(2);\n\n \n \/\/retrieve the pointer to the random forest\n const mxArray *forestPtr = prhs[0];\n ASSERT_IS_POINTER(forestPtr);\n CvRTrees *forest = (CvRTrees *)unpack_pointer(forestPtr);\n\n \/\/get the data which we need to predict on into opencv format\n CvMat* dataMtx = matlab_matrix_to_opencv_matrix(prhs[1]);\n CvMat sample; \/\/this is used to point to each row, one at a time\n\n int numSamples = dataMtx->rows;\n mexPrintf(\"predicting on %d samples\\n\", numSamples);\n\n mxArray* output = mxCreateDoubleMatrix(numSamples, 1, mxREAL);\n double *outputData = (double *)mxGetPr(output);\n\n \/\/\n for (unsigned int i=0; ipredict(&sample);\n }\n\n plhs[0] = output;\n cvReleaseMat(&dataMtx);\n}\nAdded support for computing variances.#include \"mex.h\"\n#include \"opencv_matlab_interop.h\"\n\n#define PRINT_INPUTS\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {\n ASSERT_NUM_RHS_ARGS_EQUALS(2);\n \n\n \n \/\/retrieve the pointer to the random forest\n const mxArray *forestPtr = prhs[0];\n ASSERT_IS_POINTER(forestPtr);\n CvRTrees *forest = (CvRTrees *)unpack_pointer(forestPtr);\n\n \/\/get the data which we need to predict on into opencv format\n CvMat* dataMtx = matlab_matrix_to_opencv_matrix(prhs[1]);\n CvMat sample; \/\/this is used to point to each row, one at a time\n\n int numSamples = dataMtx->rows;\n mexPrintf(\"predicting on %d samples\\n\", numSamples);\n\n mxArray* output = mxCreateDoubleMatrix(numSamples, 1, mxREAL);\n double *outputData = (double *)mxGetPr(output);\n\n if (nrhs > 1) { \/\/are we doing variances?\n mexPrintf(\"Calculating variances.\\n\");\n mxArray* variances = mxCreateDoubleMatrix(numSamples, 1, mxREAL);\n double *varianceData = (double *)mxGetPr(output);\n \n for (unsigned int i=0; ipredict_variance(&sample, NULL, varianceData+i);\n }\n plhs[1] = variances;\n }\n else {\n for (unsigned int i=0; ipredict(&sample, NULL);\n }\n }\n \n plhs[0] = output;\n cvReleaseMat(&dataMtx);\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: testconnection.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: rt $ $Date: 2003-04-23 16:22:11 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#include \n\n#ifndef _OSL_TIME_H_\n#include \n#endif\n\n#include \n#include \n\n#include \n\n#include \n\n#include \n\n#include \n#include \n\nusing namespace ::osl;\nusing namespace ::rtl;\nusing namespace ::cppu;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::io;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::registry;\nusing namespace ::com::sun::star::connection;\n\n\nclass MyThread :\n public Thread\n{\npublic:\n MyThread( const Reference< XAcceptor > &r , const OUString & sConnectionDescription) :\n m_rAcceptor( r ),\n m_sConnectionDescription( sConnectionDescription )\n {}\n virtual void SAL_CALL run();\n\n Reference < XAcceptor > m_rAcceptor;\nprivate:\n Reference < XConnection > m_rConnection;\n OUString m_sConnectionDescription;\n};\n\nvoid doWrite( const Reference < XConnection > &r )\n{\n Sequence < sal_Int8 > seq(10);\n for( sal_Int32 i = 0 ; i < 10 ; i ++ )\n {\n seq.getArray()[i] = i;\n }\n\n r->write( seq );\n}\n\nvoid doRead( const Reference < XConnection > &r )\n{\n Sequence < sal_Int8 > seq(10);\n\n OSL_ASSERT( 10 == r->read( seq , 10 ) );\n\n for( sal_Int32 i = 0 ; i < 10 ; i ++ )\n {\n OSL_ASSERT( seq.getConstArray()[i] == i );\n }\n}\n\n\nvoid MyThread::run()\n{\n try\n {\n m_rConnection = m_rAcceptor->accept( m_sConnectionDescription );\n }\n catch ( Exception &e)\n {\n OString tmp= OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US );\n printf( \"Exception was thrown by acceptor thread: %s\\n\", tmp.getStr() );\n }\n\n if( m_rConnection.is() )\n {\n Sequence < sal_Int8 > seq(12);\n try\n {\n doWrite( m_rConnection );\n doRead( m_rConnection );\n }\n catch (... )\n {\n printf( \"unknown exception was thrown\\n\" );\n throw;\n }\n }\n\n}\n\n\n\n\n\nvoid testConnection( const OUString &sConnectionDescription ,\n const Reference < XAcceptor > &rAcceptor,\n const Reference < XConnector > &rConnector )\n{\n {\n MyThread thread( rAcceptor , sConnectionDescription );\n thread.create();\n\n sal_Bool bGotit = sal_False;\n Reference < XConnection > r;\n\n while( ! bGotit )\n {\n try\n {\n \/\/ Why is this wait necessary ????\n TimeValue value = {1,0};\n osl_waitThread( &value );\n r = rConnector->connect( sConnectionDescription );\n OSL_ASSERT( r.is() );\n doWrite( r );\n doRead( r );\n bGotit = sal_True;\n }\n catch( ... )\n {\n printf( \"Couldn't connect, retrying ...\\n\" );\n\n }\n }\n\n r->close();\n\n try\n {\n Sequence < sal_Int8 > seq(10);\n r->write( seq );\n OSL_ENSURE( 0 , \"expected exception not thrown\" );\n }\n catch ( IOException & )\n {\n \/\/ everything is ok\n }\n catch ( ... )\n {\n OSL_ENSURE( 0 , \"wrong exception was thrown\" );\n }\n\n thread.join();\n }\n}\n\n\n#if (defined UNX) || (defined OS2)\nint main( int argc, char * argv[] )\n#else\nint __cdecl main( int argc, char * argv[] )\n#endif\n{\n Reference< XMultiServiceFactory > xMgr(\n createRegistryServiceFactory( OUString( RTL_CONSTASCII_USTRINGPARAM(\"applicat.rdb\")) ) );\n\n Reference< XImplementationRegistration > xImplReg(\n xMgr->createInstance( OUString::createFromAscii(\"com.sun.star.registry.ImplementationRegistration\") ), UNO_QUERY );\n OSL_ENSURE( xImplReg.is(), \"### no impl reg!\" );\n\n OUString aLibName =\n OUString::createFromAscii( \"connector.uno\" SAL_DLLEXTENSION );\n xImplReg->registerImplementation(\n OUString::createFromAscii(\"com.sun.star.loader.SharedLibrary\"), aLibName, Reference< XSimpleRegistry >() );\n\n aLibName = OUString::createFromAscii( \"acceptor.uno\" SAL_DLLEXTENSION );\n xImplReg->registerImplementation(\n OUString::createFromAscii(\"com.sun.star.loader.SharedLibrary\"), aLibName, Reference< XSimpleRegistry >() );\n\n Reference < XAcceptor > rAcceptor(\n xMgr->createInstance(\n OUString::createFromAscii(\"com.sun.star.connection.Acceptor\" ) ) , UNO_QUERY );\n\n Reference < XAcceptor > rAcceptorPipe(\n xMgr->createInstance(\n OUString::createFromAscii(\"com.sun.star.connection.Acceptor\" ) ) , UNO_QUERY );\n\n Reference < XConnector > rConnector(\n xMgr->createInstance( OUString::createFromAscii(\"com.sun.star.connection.Connector\") ) , UNO_QUERY );\n\n\n printf( \"Testing sockets\" );\n fflush( stdout );\n testConnection( OUString::createFromAscii(\"socket,host=localhost,port=2001\"), rAcceptor , rConnector );\n printf( \" Done\\n\" );\n\n printf( \"Testing pipe\" );\n fflush( stdout );\n testConnection( OUString::createFromAscii(\"pipe,name=bla\") , rAcceptorPipe , rConnector );\n printf( \" Done\\n\" );\n\n \/\/ check, if errornous strings make any problem\n rAcceptor = Reference< XAcceptor > (\n xMgr->createInstance( OUString::createFromAscii( \"com.sun.star.connection.Acceptor\" ) ),\n UNO_QUERY );\n\n try\n {\n rAcceptor->accept( OUString() );\n OSL_ENSURE( 0 , \"empty connection string\" );\n }\n catch( IllegalArgumentException & )\n {\n \/\/ everything is fine\n }\n catch( ... )\n {\n OSL_ENSURE( 0, \"unexpected akexception with empty connection string\" );\n }\n\n try\n {\n rConnector->connect( OUString() );\n OSL_ENSURE( 0 , \"empty connection string\" );\n }\n catch( ConnectionSetupException & )\n {\n \/\/ everything is fine\n }\n catch( ... )\n {\n OSL_ENSURE( 0, \"unexpected exception with empty connection string\" );\n }\n\n\n MyThread thread( rAcceptor , OUString::createFromAscii(\"socket,host=localhost,port=2001\") );\n thread.create();\n\n TimeValue value = {0,1};\n osl_waitThread( &value );\n try\n {\n rAcceptor->accept( OUString::createFromAscii(\"socket,host=localhost,port=2001\") );\n OSL_ENSURE( 0 , \"already existing exception expected\" );\n }\n catch( AlreadyAcceptingException & e)\n {\n \/\/ everything is fine\n }\n catch( ... )\n {\n OSL_ENSURE( 0, \"unknown exception, already existing existing expected\" );\n }\n\n rAcceptor->stopAccepting();\n thread.join();\n\n Reference < XComponent > rComp( xMgr , UNO_QUERY );\n if( rComp.is() )\n {\n rComp->dispose();\n }\n}\nINTEGRATION: CWS ooo19126 (1.9.86); FILE MERGED 2005\/09\/05 17:14:52 rt 1.9.86.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: testconnection.cxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: rt $ $Date: 2005-09-07 18:33:03 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#include \n\n#ifndef _OSL_TIME_H_\n#include \n#endif\n\n#include \n#include \n\n#include \n\n#include \n\n#include \n\n#include \n#include \n\nusing namespace ::osl;\nusing namespace ::rtl;\nusing namespace ::cppu;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::io;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::registry;\nusing namespace ::com::sun::star::connection;\n\n\nclass MyThread :\n public Thread\n{\npublic:\n MyThread( const Reference< XAcceptor > &r , const OUString & sConnectionDescription) :\n m_rAcceptor( r ),\n m_sConnectionDescription( sConnectionDescription )\n {}\n virtual void SAL_CALL run();\n\n Reference < XAcceptor > m_rAcceptor;\nprivate:\n Reference < XConnection > m_rConnection;\n OUString m_sConnectionDescription;\n};\n\nvoid doWrite( const Reference < XConnection > &r )\n{\n Sequence < sal_Int8 > seq(10);\n for( sal_Int32 i = 0 ; i < 10 ; i ++ )\n {\n seq.getArray()[i] = i;\n }\n\n r->write( seq );\n}\n\nvoid doRead( const Reference < XConnection > &r )\n{\n Sequence < sal_Int8 > seq(10);\n\n OSL_ASSERT( 10 == r->read( seq , 10 ) );\n\n for( sal_Int32 i = 0 ; i < 10 ; i ++ )\n {\n OSL_ASSERT( seq.getConstArray()[i] == i );\n }\n}\n\n\nvoid MyThread::run()\n{\n try\n {\n m_rConnection = m_rAcceptor->accept( m_sConnectionDescription );\n }\n catch ( Exception &e)\n {\n OString tmp= OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US );\n printf( \"Exception was thrown by acceptor thread: %s\\n\", tmp.getStr() );\n }\n\n if( m_rConnection.is() )\n {\n Sequence < sal_Int8 > seq(12);\n try\n {\n doWrite( m_rConnection );\n doRead( m_rConnection );\n }\n catch (... )\n {\n printf( \"unknown exception was thrown\\n\" );\n throw;\n }\n }\n\n}\n\n\n\n\n\nvoid testConnection( const OUString &sConnectionDescription ,\n const Reference < XAcceptor > &rAcceptor,\n const Reference < XConnector > &rConnector )\n{\n {\n MyThread thread( rAcceptor , sConnectionDescription );\n thread.create();\n\n sal_Bool bGotit = sal_False;\n Reference < XConnection > r;\n\n while( ! bGotit )\n {\n try\n {\n \/\/ Why is this wait necessary ????\n TimeValue value = {1,0};\n osl_waitThread( &value );\n r = rConnector->connect( sConnectionDescription );\n OSL_ASSERT( r.is() );\n doWrite( r );\n doRead( r );\n bGotit = sal_True;\n }\n catch( ... )\n {\n printf( \"Couldn't connect, retrying ...\\n\" );\n\n }\n }\n\n r->close();\n\n try\n {\n Sequence < sal_Int8 > seq(10);\n r->write( seq );\n OSL_ENSURE( 0 , \"expected exception not thrown\" );\n }\n catch ( IOException & )\n {\n \/\/ everything is ok\n }\n catch ( ... )\n {\n OSL_ENSURE( 0 , \"wrong exception was thrown\" );\n }\n\n thread.join();\n }\n}\n\n\n#if (defined UNX) || (defined OS2)\nint main( int argc, char * argv[] )\n#else\nint __cdecl main( int argc, char * argv[] )\n#endif\n{\n Reference< XMultiServiceFactory > xMgr(\n createRegistryServiceFactory( OUString( RTL_CONSTASCII_USTRINGPARAM(\"applicat.rdb\")) ) );\n\n Reference< XImplementationRegistration > xImplReg(\n xMgr->createInstance( OUString::createFromAscii(\"com.sun.star.registry.ImplementationRegistration\") ), UNO_QUERY );\n OSL_ENSURE( xImplReg.is(), \"### no impl reg!\" );\n\n OUString aLibName =\n OUString::createFromAscii( \"connector.uno\" SAL_DLLEXTENSION );\n xImplReg->registerImplementation(\n OUString::createFromAscii(\"com.sun.star.loader.SharedLibrary\"), aLibName, Reference< XSimpleRegistry >() );\n\n aLibName = OUString::createFromAscii( \"acceptor.uno\" SAL_DLLEXTENSION );\n xImplReg->registerImplementation(\n OUString::createFromAscii(\"com.sun.star.loader.SharedLibrary\"), aLibName, Reference< XSimpleRegistry >() );\n\n Reference < XAcceptor > rAcceptor(\n xMgr->createInstance(\n OUString::createFromAscii(\"com.sun.star.connection.Acceptor\" ) ) , UNO_QUERY );\n\n Reference < XAcceptor > rAcceptorPipe(\n xMgr->createInstance(\n OUString::createFromAscii(\"com.sun.star.connection.Acceptor\" ) ) , UNO_QUERY );\n\n Reference < XConnector > rConnector(\n xMgr->createInstance( OUString::createFromAscii(\"com.sun.star.connection.Connector\") ) , UNO_QUERY );\n\n\n printf( \"Testing sockets\" );\n fflush( stdout );\n testConnection( OUString::createFromAscii(\"socket,host=localhost,port=2001\"), rAcceptor , rConnector );\n printf( \" Done\\n\" );\n\n printf( \"Testing pipe\" );\n fflush( stdout );\n testConnection( OUString::createFromAscii(\"pipe,name=bla\") , rAcceptorPipe , rConnector );\n printf( \" Done\\n\" );\n\n \/\/ check, if errornous strings make any problem\n rAcceptor = Reference< XAcceptor > (\n xMgr->createInstance( OUString::createFromAscii( \"com.sun.star.connection.Acceptor\" ) ),\n UNO_QUERY );\n\n try\n {\n rAcceptor->accept( OUString() );\n OSL_ENSURE( 0 , \"empty connection string\" );\n }\n catch( IllegalArgumentException & )\n {\n \/\/ everything is fine\n }\n catch( ... )\n {\n OSL_ENSURE( 0, \"unexpected akexception with empty connection string\" );\n }\n\n try\n {\n rConnector->connect( OUString() );\n OSL_ENSURE( 0 , \"empty connection string\" );\n }\n catch( ConnectionSetupException & )\n {\n \/\/ everything is fine\n }\n catch( ... )\n {\n OSL_ENSURE( 0, \"unexpected exception with empty connection string\" );\n }\n\n\n MyThread thread( rAcceptor , OUString::createFromAscii(\"socket,host=localhost,port=2001\") );\n thread.create();\n\n TimeValue value = {0,1};\n osl_waitThread( &value );\n try\n {\n rAcceptor->accept( OUString::createFromAscii(\"socket,host=localhost,port=2001\") );\n OSL_ENSURE( 0 , \"already existing exception expected\" );\n }\n catch( AlreadyAcceptingException & e)\n {\n \/\/ everything is fine\n }\n catch( ... )\n {\n OSL_ENSURE( 0, \"unknown exception, already existing existing expected\" );\n }\n\n rAcceptor->stopAccepting();\n thread.join();\n\n Reference < XComponent > rComp( xMgr , UNO_QUERY );\n if( rComp.is() )\n {\n rComp->dispose();\n }\n}\n<|endoftext|>"} {"text":"\r\n#include \"CShader.h\"\r\n\r\n\r\nCShader * CompileVertFragShader(string const VertexShaderSource, string const FragmentShaderSource)\r\n{\r\n\tion::GL::VertexShader * VertexShader = new ion::GL::VertexShader;\r\n\tVertexShader->Source(VertexShaderSource);\r\n\tif (! VertexShader->Compile())\r\n\t\tstd::cerr << \"Failed to compile vertex shader!\" << std::endl << VertexShader->InfoLog() << std::endl;\r\n\r\n\tion::GL::FragmentShader * FragmentShader = new ion::GL::FragmentShader;\r\n\tFragmentShader->Source(FragmentShaderSource);\r\n\tif (! FragmentShader->Compile())\r\n\t\tstd::cerr << \"Failed to compile fragment shader!\" << std::endl << FragmentShader->InfoLog() << std::endl;\r\n\r\n\tion::GL::Program * Program = new ion::GL::Program;\r\n\tProgram->AttachShader(VertexShader);\r\n\tProgram->AttachShader(FragmentShader);\r\n\tProgram->Link();\r\n\tProgram->InfoLog();\r\n\t\r\n\treturn Program;\r\n}\r\nAdd display of program link output in event of linker stage failure\r\n#include \"CShader.h\"\r\n\r\n\r\nCShader * CompileVertFragShader(string const VertexShaderSource, string const FragmentShaderSource)\r\n{\r\n\tion::GL::VertexShader * VertexShader = new ion::GL::VertexShader;\r\n\tVertexShader->Source(VertexShaderSource);\r\n\tif (! VertexShader->Compile())\r\n\t\tstd::cerr << \"Failed to compile vertex shader!\" << std::endl << VertexShader->InfoLog() << std::endl;\r\n\r\n\tion::GL::FragmentShader * FragmentShader = new ion::GL::FragmentShader;\r\n\tFragmentShader->Source(FragmentShaderSource);\r\n\tif (! FragmentShader->Compile())\r\n\t\tstd::cerr << \"Failed to compile fragment shader!\" << std::endl << FragmentShader->InfoLog() << std::endl;\r\n\r\n\tion::GL::Program * Program = new ion::GL::Program;\r\n\tProgram->AttachShader(VertexShader);\r\n\tProgram->AttachShader(FragmentShader);\r\n\tif (! Program->Link())\r\n\t\tstd::cerr << \"Failed to link vertex\/fragment program!\" << std::endl << Program->InfoLog() << std::endl;\r\n\t\r\n\treturn Program;\r\n}\r\n<|endoftext|>"} {"text":"\/** @file\n\n A brief file description\n\n @section license License\n\n Licensed to the Apache Software Foundation (ASF) under one\n or more contributor license agreements. See the NOTICE file\n distributed with this work for additional information\n regarding copyright ownership. The ASF licenses this file\n to you under the Apache License, Version 2.0 (the\n \"License\"); you may not use this file except in compliance\n with the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n *\/\n\n\/*************************** -*- Mod: C++ -*- ******************************\n SSLSNIConfig.cc\n Created On : 05\/02\/2017\n\n Description:\n SNI based Configuration in ATS\n ****************************************************************************\/\n\n#include \"P_SSLSNI.h\"\n#include \"ts\/Diags.h\"\n#include \"ts\/SimpleTokenizer.h\"\n#include \"P_SSLConfig.h\"\n#include \"ts\/ink_memory.h\"\n\n#define SNI_NAME_TAG \"dest_host\"\n#define SNI_ACTION_TAG \"action\"\n#define SNI_PARAM_TAG \"param\"\n\nstatic ConfigUpdateHandler *sniConfigUpdate;\nstruct NetAccept;\nextern std::vector naVec;\nMap snpsMap;\nextern TunnelHashMap TunnelMap;\nNextHopProperty::NextHopProperty()\n{\n}\n\nNextHopProperty *\nSNIConfigParams::getPropertyConfig(cchar *servername) const\n{\n NextHopProperty *nps = nullptr;\n nps = next_hop_table.get(servername);\n if (!nps)\n nps = wild_next_hop_table.get(servername);\n return nps;\n}\n\nvoid\nSNIConfigParams::loadSNIConfig()\n{\n for (auto item : L_sni.items) {\n actionVector *aiVec = new actionVector();\n Debug(\"ssl\", \"name: %s\", item.fqdn.data());\n cchar *servername = item.fqdn.data();\n ats_wildcard_matcher w_Matcher;\n auto wildcard = w_Matcher.match(servername);\n\n \/\/ set SNI based actions to be called in the ssl_servername_only callback\n auto ai1 = new DisableH2();\n aiVec->push_back(ai1);\n auto ai2 = new VerifyClient(item.verify_client_level);\n aiVec->push_back(ai2);\n sni_action_map.put(ats_strdup(servername), aiVec);\n\n if (item.tunnel_destination.length()) {\n TunnelMap.emplace(item.fqdn.data(), item.tunnel_destination);\n }\n\n \/\/ set the next hop properties\n SSLConfig::scoped_config params;\n auto clientCTX = params->getCTX(servername);\n cchar *certFile = item.client_cert.data();\n if (!clientCTX && certFile) {\n clientCTX = params->getNewCTX(certFile);\n params->InsertCTX(certFile, clientCTX);\n }\n NextHopProperty *nps = new NextHopProperty();\n nps->name = ats_strdup(servername);\n nps->verifyLevel = item.verify_origin_server;\n nps->ctx = clientCTX;\n if (wildcard)\n wild_next_hop_table.put(nps->name, nps);\n else\n next_hop_table.put(nps->name, nps);\n } \/\/ end for\n}\n\nint SNIConfig::configid = 0;\n\/*definition of member functions of SNIConfigParams*\/\nSNIConfigParams::SNIConfigParams()\n{\n}\n\nactionVector *\nSNIConfigParams::get(cchar *servername) const\n{\n auto actionVec = sni_action_map.get(servername);\n if (!actionVec)\n actionVec = wild_sni_action_map.get(servername);\n return actionVec;\n}\n\nvoid\nSNIConfigParams::printSNImap() const\n{\n Vec keys;\n sni_action_map.get_keys(keys);\n for (size_t i = 0; i < keys.length(); i++) {\n Debug(\"ssl\", \"Domain name in the map %s: # of registered action items %lu\", (char *)keys.get(i),\n sni_action_map.get(keys.get(i))->size());\n }\n}\n\nint\nSNIConfigParams::Initialize()\n{\n sni_filename = ats_stringdup(RecConfigReadConfigPath(\"proxy.config.ssl.servername.filename\"));\n lua_State *L = lua_open(); \/* opens Lua *\/\n luaL_openlibs(L);\n luaL_loadfile(L, sni_filename);\n lua_pcall(L, 0, 0, 0);\n L_sni.loader(L);\n loadSNIConfig();\n return 0;\n}\n\nvoid\nSNIConfigParams::cleanup()\n{\n Vec keys;\n sni_action_map.get_keys(keys);\n for (int i = keys.length() - 1; i >= 0; i--) {\n auto actionVec = sni_action_map.get(keys.get(i));\n for (auto &ai : *actionVec)\n delete ai;\n\n actionVec->clear();\n }\n keys.free_and_clear();\n\n wild_sni_action_map.get_keys(keys);\n for (int i = keys.length() - 1; i >= 0; i--) {\n auto actionVec = wild_sni_action_map.get(keys.get(i));\n for (auto &ai : *actionVec)\n delete ai;\n\n actionVec->clear();\n }\n keys.free_and_clear();\n\n next_hop_table.get_keys(keys);\n for (int i = 0; i < static_cast(keys.length()); i++) {\n auto *nps = next_hop_table.get(keys.get(i));\n delete (nps);\n }\n keys.free_and_clear();\n\n wild_next_hop_table.get_keys(keys);\n for (int i = 0; static_cast(keys.length()); i++) {\n auto *nps = wild_next_hop_table.get(keys.get(i));\n delete (nps);\n }\n keys.free_and_clear();\n}\n\nSNIConfigParams::~SNIConfigParams()\n{\n cleanup();\n}\n\n\/*definition of member functions of SNIConfig*\/\nvoid\nSNIConfig::startup()\n{\n sniConfigUpdate = new ConfigUpdateHandler();\n sniConfigUpdate->attach(\"proxy.config.ssl.servername.filename\");\n reconfigure();\n}\n\nvoid\nSNIConfig::cloneProtoSet()\n{\n for (auto na : naVec) {\n if (na->snpa) {\n auto snps = na->snpa->cloneProtoSet();\n snps->unregisterEndpoint(TS_ALPN_PROTOCOL_HTTP_2_0, nullptr);\n snpsMap.put(na->id, snps);\n }\n }\n}\n\nvoid\nSNIConfig::reconfigure()\n{\n SNIConfigParams *params = new SNIConfigParams;\n\n params->Initialize();\n configid = configProcessor.set(configid, params);\n}\n\nSNIConfigParams *\nSNIConfig::acquire()\n{\n return (SNIConfigParams *)configProcessor.get(configid);\n}\n\nvoid\nSNIConfig::release(SNIConfigParams *params)\n{\n configProcessor.release(configid, params);\n}\ncoverity 1382799, 1382796: Unchecked return value\/** @file\n\n A brief file description\n\n @section license License\n\n Licensed to the Apache Software Foundation (ASF) under one\n or more contributor license agreements. See the NOTICE file\n distributed with this work for additional information\n regarding copyright ownership. The ASF licenses this file\n to you under the Apache License, Version 2.0 (the\n \"License\"); you may not use this file except in compliance\n with the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n *\/\n\n\/*************************** -*- Mod: C++ -*- ******************************\n SSLSNIConfig.cc\n Created On : 05\/02\/2017\n\n Description:\n SNI based Configuration in ATS\n ****************************************************************************\/\n\n#include \"P_SSLSNI.h\"\n#include \"ts\/Diags.h\"\n#include \"ts\/SimpleTokenizer.h\"\n#include \"P_SSLConfig.h\"\n#include \"ts\/ink_memory.h\"\n\n#define SNI_NAME_TAG \"dest_host\"\n#define SNI_ACTION_TAG \"action\"\n#define SNI_PARAM_TAG \"param\"\n\nstatic ConfigUpdateHandler *sniConfigUpdate;\nstruct NetAccept;\nextern std::vector naVec;\nMap snpsMap;\nextern TunnelHashMap TunnelMap;\nNextHopProperty::NextHopProperty()\n{\n}\n\nNextHopProperty *\nSNIConfigParams::getPropertyConfig(cchar *servername) const\n{\n NextHopProperty *nps = nullptr;\n nps = next_hop_table.get(servername);\n if (!nps)\n nps = wild_next_hop_table.get(servername);\n return nps;\n}\n\nvoid\nSNIConfigParams::loadSNIConfig()\n{\n for (auto item : L_sni.items) {\n actionVector *aiVec = new actionVector();\n Debug(\"ssl\", \"name: %s\", item.fqdn.data());\n cchar *servername = item.fqdn.data();\n ats_wildcard_matcher w_Matcher;\n auto wildcard = w_Matcher.match(servername);\n\n \/\/ set SNI based actions to be called in the ssl_servername_only callback\n auto ai1 = new DisableH2();\n aiVec->push_back(ai1);\n auto ai2 = new VerifyClient(item.verify_client_level);\n aiVec->push_back(ai2);\n sni_action_map.put(ats_strdup(servername), aiVec);\n\n if (item.tunnel_destination.length()) {\n TunnelMap.emplace(item.fqdn.data(), item.tunnel_destination);\n }\n\n \/\/ set the next hop properties\n SSLConfig::scoped_config params;\n auto clientCTX = params->getCTX(servername);\n cchar *certFile = item.client_cert.data();\n if (!clientCTX && certFile) {\n clientCTX = params->getNewCTX(certFile);\n params->InsertCTX(certFile, clientCTX);\n }\n NextHopProperty *nps = new NextHopProperty();\n nps->name = ats_strdup(servername);\n nps->verifyLevel = item.verify_origin_server;\n nps->ctx = clientCTX;\n if (wildcard)\n wild_next_hop_table.put(nps->name, nps);\n else\n next_hop_table.put(nps->name, nps);\n } \/\/ end for\n}\n\nint SNIConfig::configid = 0;\n\/*definition of member functions of SNIConfigParams*\/\nSNIConfigParams::SNIConfigParams()\n{\n}\n\nactionVector *\nSNIConfigParams::get(cchar *servername) const\n{\n auto actionVec = sni_action_map.get(servername);\n if (!actionVec)\n actionVec = wild_sni_action_map.get(servername);\n return actionVec;\n}\n\nvoid\nSNIConfigParams::printSNImap() const\n{\n Vec keys;\n sni_action_map.get_keys(keys);\n for (size_t i = 0; i < keys.length(); i++) {\n Debug(\"ssl\", \"Domain name in the map %s: # of registered action items %lu\", (char *)keys.get(i),\n sni_action_map.get(keys.get(i))->size());\n }\n}\n\nint\nSNIConfigParams::Initialize()\n{\n sni_filename = ats_stringdup(RecConfigReadConfigPath(\"proxy.config.ssl.servername.filename\"));\n struct stat sbuf;\n if (stat(sni_filename, &sbuf) == -1 && errno == ENOENT) {\n Warning(\"Loading SNI configuration - filename: %s doesn't exist\", sni_filename);\n return 1;\n }\n\n lua_State *L = lua_open(); \/* opens Lua *\/\n luaL_openlibs(L);\n if (luaL_loadfile(L, sni_filename)) {\n Error(\"Loading SNI configuration - luaL_loadfile: %s\", lua_tostring(L, -1));\n lua_pop(L, 1);\n return 1;\n }\n\n if (lua_pcall(L, 0, 0, 0)) {\n Error(\"Loading SNI configuration - luap_pcall: %s failed: %s\", sni_filename, lua_tostring(L, -1));\n lua_pop(L, 1);\n return 1;\n }\n\n L_sni.loader(L);\n loadSNIConfig();\n return 0;\n}\n\nvoid\nSNIConfigParams::cleanup()\n{\n Vec keys;\n sni_action_map.get_keys(keys);\n for (int i = keys.length() - 1; i >= 0; i--) {\n auto actionVec = sni_action_map.get(keys.get(i));\n for (auto &ai : *actionVec)\n delete ai;\n\n actionVec->clear();\n }\n keys.free_and_clear();\n\n wild_sni_action_map.get_keys(keys);\n for (int i = keys.length() - 1; i >= 0; i--) {\n auto actionVec = wild_sni_action_map.get(keys.get(i));\n for (auto &ai : *actionVec)\n delete ai;\n\n actionVec->clear();\n }\n keys.free_and_clear();\n\n next_hop_table.get_keys(keys);\n for (int i = 0; i < static_cast(keys.length()); i++) {\n auto *nps = next_hop_table.get(keys.get(i));\n delete (nps);\n }\n keys.free_and_clear();\n\n wild_next_hop_table.get_keys(keys);\n for (int i = 0; static_cast(keys.length()); i++) {\n auto *nps = wild_next_hop_table.get(keys.get(i));\n delete (nps);\n }\n keys.free_and_clear();\n}\n\nSNIConfigParams::~SNIConfigParams()\n{\n cleanup();\n}\n\n\/*definition of member functions of SNIConfig*\/\nvoid\nSNIConfig::startup()\n{\n sniConfigUpdate = new ConfigUpdateHandler();\n sniConfigUpdate->attach(\"proxy.config.ssl.servername.filename\");\n reconfigure();\n}\n\nvoid\nSNIConfig::cloneProtoSet()\n{\n for (auto na : naVec) {\n if (na->snpa) {\n auto snps = na->snpa->cloneProtoSet();\n snps->unregisterEndpoint(TS_ALPN_PROTOCOL_HTTP_2_0, nullptr);\n snpsMap.put(na->id, snps);\n }\n }\n}\n\nvoid\nSNIConfig::reconfigure()\n{\n SNIConfigParams *params = new SNIConfigParams;\n\n params->Initialize();\n configid = configProcessor.set(configid, params);\n}\n\nSNIConfigParams *\nSNIConfig::acquire()\n{\n return (SNIConfigParams *)configProcessor.get(configid);\n}\n\nvoid\nSNIConfig::release(SNIConfigParams *params)\n{\n configProcessor.release(configid, params);\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"webrtc\/video_engine\/vie_base_impl.h\"\n\n#include \n#include \n\n#include \"webrtc\/engine_configurations.h\"\n#include \"webrtc\/modules\/rtp_rtcp\/interface\/rtp_rtcp.h\"\n#include \"webrtc\/modules\/video_coding\/main\/interface\/video_coding.h\"\n#include \"webrtc\/modules\/video_processing\/main\/interface\/video_processing.h\"\n#include \"webrtc\/modules\/video_render\/include\/video_render.h\"\n#include \"webrtc\/system_wrappers\/interface\/critical_section_wrapper.h\"\n#include \"webrtc\/system_wrappers\/interface\/trace.h\"\n#include \"webrtc\/video_engine\/include\/vie_errors.h\"\n#include \"webrtc\/video_engine\/vie_channel.h\"\n#include \"webrtc\/video_engine\/vie_channel_manager.h\"\n#include \"webrtc\/video_engine\/vie_defines.h\"\n#include \"webrtc\/video_engine\/vie_encoder.h\"\n#include \"webrtc\/video_engine\/vie_impl.h\"\n#include \"webrtc\/video_engine\/vie_input_manager.h\"\n#include \"webrtc\/video_engine\/vie_shared_data.h\"\n\nnamespace webrtc {\n\nViEBase* ViEBase::GetInterface(VideoEngine* video_engine) {\n if (!video_engine) {\n return NULL;\n }\n VideoEngineImpl* vie_impl = static_cast(video_engine);\n ViEBaseImpl* vie_base_impl = vie_impl;\n (*vie_base_impl)++; \/\/ Increase ref count.\n\n return vie_base_impl;\n}\n\nint ViEBaseImpl::Release() {\n WEBRTC_TRACE(kTraceApiCall, kTraceVideo, shared_data_.instance_id(),\n \"ViEBase::Release()\");\n (*this)--; \/\/ Decrease ref count.\n\n int32_t ref_count = GetCount();\n if (ref_count < 0) {\n WEBRTC_TRACE(kTraceWarning, kTraceVideo, shared_data_.instance_id(),\n \"ViEBase release too many times\");\n shared_data_.SetLastError(kViEAPIDoesNotExist);\n return -1;\n }\n WEBRTC_TRACE(kTraceInfo, kTraceVideo, shared_data_.instance_id(),\n \"ViEBase reference count: %d\", ref_count);\n return ref_count;\n}\n\nViEBaseImpl::ViEBaseImpl(const Config& config)\n : shared_data_(config) {\n WEBRTC_TRACE(kTraceMemory, kTraceVideo, shared_data_.instance_id(),\n \"ViEBaseImpl::ViEBaseImpl() Ctor\");\n}\n\nViEBaseImpl::~ViEBaseImpl() {\n WEBRTC_TRACE(kTraceMemory, kTraceVideo, shared_data_.instance_id(),\n \"ViEBaseImpl::ViEBaseImpl() Dtor\");\n}\n\nint ViEBaseImpl::Init() {\n WEBRTC_TRACE(kTraceApiCall, kTraceVideo, shared_data_.instance_id(),\n \"Init\");\n return 0;\n}\n\nint ViEBaseImpl::SetVoiceEngine(VoiceEngine* voice_engine) {\n WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id()),\n \"%s\", __FUNCTION__);\n if (shared_data_.channel_manager()->SetVoiceEngine(voice_engine) != 0) {\n shared_data_.SetLastError(kViEBaseVoEFailure);\n return -1;\n }\n return 0;\n}\n\nint ViEBaseImpl::CreateChannel(int& video_channel) { \/\/ NOLINT\n WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id()),\n \"%s\", __FUNCTION__);\n if (shared_data_.channel_manager()->CreateChannel(&video_channel) == -1) {\n WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()),\n \"%s: Could not create channel\", __FUNCTION__);\n video_channel = -1;\n shared_data_.SetLastError(kViEBaseChannelCreationFailed);\n return -1;\n }\n WEBRTC_TRACE(kTraceInfo, kTraceVideo, ViEId(shared_data_.instance_id()),\n \"%s: channel created: %d\", __FUNCTION__, video_channel);\n return 0;\n}\n\nint ViEBaseImpl::CreateChannel(int& video_channel, \/\/ NOLINT\n int original_channel) {\n return CreateChannel(video_channel, original_channel, true);\n}\n\nint ViEBaseImpl::CreateReceiveChannel(int& video_channel, \/\/ NOLINT\n int original_channel) {\n return CreateChannel(video_channel, original_channel, false);\n}\n\nint ViEBaseImpl::DeleteChannel(const int video_channel) {\n WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id()),\n \"%s(%d)\", __FUNCTION__, video_channel);\n {\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n WEBRTC_TRACE(kTraceError, kTraceVideo,\n ViEId(shared_data_.instance_id()),\n \"%s: channel %d doesn't exist\", __FUNCTION__, video_channel);\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n\n \/\/ Deregister the ViEEncoder if no other channel is using it.\n ViEEncoder* vie_encoder = cs.Encoder(video_channel);\n if (cs.ChannelUsingViEEncoder(video_channel) == false) {\n ViEInputManagerScoped is(*(shared_data_.input_manager()));\n ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder);\n if (provider) {\n provider->DeregisterFrameCallback(vie_encoder);\n }\n }\n }\n\n if (shared_data_.channel_manager()->DeleteChannel(video_channel) == -1) {\n WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()),\n \"%s: Could not delete channel %d\", __FUNCTION__,\n video_channel);\n shared_data_.SetLastError(kViEBaseUnknownError);\n return -1;\n }\n WEBRTC_TRACE(kTraceInfo, kTraceVideo, ViEId(shared_data_.instance_id()),\n \"%s: channel deleted: %d\", __FUNCTION__, video_channel);\n return 0;\n}\n\nint ViEBaseImpl::ConnectAudioChannel(const int video_channel,\n const int audio_channel) {\n WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id()),\n \"%s(%d)\", __FUNCTION__, video_channel);\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n if (!cs.Channel(video_channel)) {\n WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()),\n \"%s: channel %d doesn't exist\", __FUNCTION__, video_channel);\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n\n if (shared_data_.channel_manager()->ConnectVoiceChannel(video_channel,\n audio_channel) != 0) {\n shared_data_.SetLastError(kViEBaseVoEFailure);\n return -1;\n }\n return 0;\n}\n\nint ViEBaseImpl::DisconnectAudioChannel(const int video_channel) {\n WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id()),\n \"%s(%d)\", __FUNCTION__, video_channel);\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n if (!cs.Channel(video_channel)) {\n WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()),\n \"%s: channel %d doesn't exist\", __FUNCTION__, video_channel);\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n\n if (shared_data_.channel_manager()->DisconnectVoiceChannel(\n video_channel) != 0) {\n shared_data_.SetLastError(kViEBaseVoEFailure);\n return -1;\n }\n return 0;\n}\n\nint ViEBaseImpl::StartSend(const int video_channel) {\n WEBRTC_TRACE(kTraceApiCall, kTraceVideo,\n ViEId(shared_data_.instance_id(), video_channel),\n \"%s(channel: %d)\", __FUNCTION__, video_channel);\n\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n WEBRTC_TRACE(kTraceError, kTraceVideo,\n ViEId(shared_data_.instance_id(), video_channel),\n \"%s: Channel %d does not exist\", __FUNCTION__, video_channel);\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n\n ViEEncoder* vie_encoder = cs.Encoder(video_channel);\n assert(vie_encoder != NULL);\n if (vie_encoder->Owner() != video_channel) {\n WEBRTC_TRACE(kTraceError, kTraceVideo,\n ViEId(shared_data_.instance_id(), video_channel),\n \"Can't start ssend on a receive only channel.\");\n shared_data_.SetLastError(kViEBaseReceiveOnlyChannel);\n return -1;\n }\n\n \/\/ Pause and trigger a key frame.\n vie_encoder->Pause();\n int32_t error = vie_channel->StartSend();\n if (error != 0) {\n vie_encoder->Restart();\n WEBRTC_TRACE(kTraceError, kTraceVideo,\n ViEId(shared_data_.instance_id(), video_channel),\n \"%s: Could not start sending on channel %d\", __FUNCTION__,\n video_channel);\n if (error == kViEBaseAlreadySending) {\n shared_data_.SetLastError(kViEBaseAlreadySending);\n }\n shared_data_.SetLastError(kViEBaseUnknownError);\n return -1;\n }\n vie_encoder->SendKeyFrame();\n vie_encoder->Restart();\n return 0;\n}\n\nint ViEBaseImpl::StopSend(const int video_channel) {\n WEBRTC_TRACE(kTraceApiCall, kTraceVideo,\n ViEId(shared_data_.instance_id(), video_channel),\n \"%s(channel: %d)\", __FUNCTION__, video_channel);\n\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n WEBRTC_TRACE(kTraceError, kTraceVideo,\n ViEId(shared_data_.instance_id(), video_channel),\n \"%s: Channel %d does not exist\", __FUNCTION__, video_channel);\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n\n int32_t error = vie_channel->StopSend();\n if (error != 0) {\n WEBRTC_TRACE(kTraceError, kTraceVideo,\n ViEId(shared_data_.instance_id(), video_channel),\n \"%s: Could not stop sending on channel %d\", __FUNCTION__,\n video_channel);\n if (error == kViEBaseNotSending) {\n shared_data_.SetLastError(kViEBaseNotSending);\n } else {\n shared_data_.SetLastError(kViEBaseUnknownError);\n }\n return -1;\n }\n return 0;\n}\n\nint ViEBaseImpl::StartReceive(const int video_channel) {\n WEBRTC_TRACE(kTraceApiCall, kTraceVideo,\n ViEId(shared_data_.instance_id(), video_channel),\n \"%s(channel: %d)\", __FUNCTION__, video_channel);\n\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n WEBRTC_TRACE(kTraceError, kTraceVideo,\n ViEId(shared_data_.instance_id(), video_channel),\n \"%s: Channel %d does not exist\", __FUNCTION__, video_channel);\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n if (vie_channel->StartReceive() != 0) {\n shared_data_.SetLastError(kViEBaseUnknownError);\n return -1;\n }\n return 0;\n}\n\nint ViEBaseImpl::StopReceive(const int video_channel) {\n WEBRTC_TRACE(kTraceApiCall, kTraceVideo,\n ViEId(shared_data_.instance_id(), video_channel),\n \"%s(channel: %d)\", __FUNCTION__, video_channel);\n\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n WEBRTC_TRACE(kTraceError, kTraceVideo,\n ViEId(shared_data_.instance_id(), video_channel),\n \"%s: Channel %d does not exist\", __FUNCTION__, video_channel);\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n if (vie_channel->StopReceive() != 0) {\n shared_data_.SetLastError(kViEBaseUnknownError);\n return -1;\n }\n return 0;\n}\n\nint ViEBaseImpl::GetVersion(char version[1024]) {\n WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id()),\n \"GetVersion(version=?)\");\n assert(kViEVersionMaxMessageSize == 1024);\n if (!version) {\n shared_data_.SetLastError(kViEBaseInvalidArgument);\n return -1;\n }\n\n \/\/ Add WebRTC Version.\n std::stringstream version_stream;\n version_stream << \"VideoEngine 3.33.0\" << std::endl;\n\n \/\/ Add build info.\n version_stream << \"Build: svn:\" << WEBRTC_SVNREVISION << \" \" << BUILDINFO\n << std::endl;\n\n#ifdef WEBRTC_EXTERNAL_TRANSPORT\n version_stream << \"External transport build\" << std::endl;\n#endif\n int version_length = version_stream.tellp();\n assert(version_length < 1024);\n memcpy(version, version_stream.str().c_str(), version_length);\n version[version_length] = '\\0';\n\n WEBRTC_TRACE(kTraceStateInfo, kTraceVideo,\n ViEId(shared_data_.instance_id()), \"GetVersion() => %s\",\n version);\n return 0;\n}\n\nint ViEBaseImpl::LastError() {\n return shared_data_.LastErrorInternal();\n}\n\nint ViEBaseImpl::CreateChannel(int& video_channel, \/\/ NOLINT\n int original_channel, bool sender) {\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n if (!cs.Channel(original_channel)) {\n WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()),\n \"%s - original_channel does not exist.\", __FUNCTION__,\n shared_data_.instance_id());\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n\n if (shared_data_.channel_manager()->CreateChannel(&video_channel,\n original_channel,\n sender) == -1) {\n WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()),\n \"%s: Could not create channel\", __FUNCTION__);\n video_channel = -1;\n shared_data_.SetLastError(kViEBaseChannelCreationFailed);\n return -1;\n }\n WEBRTC_TRACE(kTraceInfo, kTraceVideo, ViEId(shared_data_.instance_id()),\n \"%s: channel created: %d\", __FUNCTION__, video_channel);\n return 0;\n}\n\n} \/\/ namespace webrtc\nUpdate version number to 3.34\/*\n * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"webrtc\/video_engine\/vie_base_impl.h\"\n\n#include \n#include \n\n#include \"webrtc\/engine_configurations.h\"\n#include \"webrtc\/modules\/rtp_rtcp\/interface\/rtp_rtcp.h\"\n#include \"webrtc\/modules\/video_coding\/main\/interface\/video_coding.h\"\n#include \"webrtc\/modules\/video_processing\/main\/interface\/video_processing.h\"\n#include \"webrtc\/modules\/video_render\/include\/video_render.h\"\n#include \"webrtc\/system_wrappers\/interface\/critical_section_wrapper.h\"\n#include \"webrtc\/system_wrappers\/interface\/trace.h\"\n#include \"webrtc\/video_engine\/include\/vie_errors.h\"\n#include \"webrtc\/video_engine\/vie_channel.h\"\n#include \"webrtc\/video_engine\/vie_channel_manager.h\"\n#include \"webrtc\/video_engine\/vie_defines.h\"\n#include \"webrtc\/video_engine\/vie_encoder.h\"\n#include \"webrtc\/video_engine\/vie_impl.h\"\n#include \"webrtc\/video_engine\/vie_input_manager.h\"\n#include \"webrtc\/video_engine\/vie_shared_data.h\"\n\nnamespace webrtc {\n\nViEBase* ViEBase::GetInterface(VideoEngine* video_engine) {\n if (!video_engine) {\n return NULL;\n }\n VideoEngineImpl* vie_impl = static_cast(video_engine);\n ViEBaseImpl* vie_base_impl = vie_impl;\n (*vie_base_impl)++; \/\/ Increase ref count.\n\n return vie_base_impl;\n}\n\nint ViEBaseImpl::Release() {\n WEBRTC_TRACE(kTraceApiCall, kTraceVideo, shared_data_.instance_id(),\n \"ViEBase::Release()\");\n (*this)--; \/\/ Decrease ref count.\n\n int32_t ref_count = GetCount();\n if (ref_count < 0) {\n WEBRTC_TRACE(kTraceWarning, kTraceVideo, shared_data_.instance_id(),\n \"ViEBase release too many times\");\n shared_data_.SetLastError(kViEAPIDoesNotExist);\n return -1;\n }\n WEBRTC_TRACE(kTraceInfo, kTraceVideo, shared_data_.instance_id(),\n \"ViEBase reference count: %d\", ref_count);\n return ref_count;\n}\n\nViEBaseImpl::ViEBaseImpl(const Config& config)\n : shared_data_(config) {\n WEBRTC_TRACE(kTraceMemory, kTraceVideo, shared_data_.instance_id(),\n \"ViEBaseImpl::ViEBaseImpl() Ctor\");\n}\n\nViEBaseImpl::~ViEBaseImpl() {\n WEBRTC_TRACE(kTraceMemory, kTraceVideo, shared_data_.instance_id(),\n \"ViEBaseImpl::ViEBaseImpl() Dtor\");\n}\n\nint ViEBaseImpl::Init() {\n WEBRTC_TRACE(kTraceApiCall, kTraceVideo, shared_data_.instance_id(),\n \"Init\");\n return 0;\n}\n\nint ViEBaseImpl::SetVoiceEngine(VoiceEngine* voice_engine) {\n WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id()),\n \"%s\", __FUNCTION__);\n if (shared_data_.channel_manager()->SetVoiceEngine(voice_engine) != 0) {\n shared_data_.SetLastError(kViEBaseVoEFailure);\n return -1;\n }\n return 0;\n}\n\nint ViEBaseImpl::CreateChannel(int& video_channel) { \/\/ NOLINT\n WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id()),\n \"%s\", __FUNCTION__);\n if (shared_data_.channel_manager()->CreateChannel(&video_channel) == -1) {\n WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()),\n \"%s: Could not create channel\", __FUNCTION__);\n video_channel = -1;\n shared_data_.SetLastError(kViEBaseChannelCreationFailed);\n return -1;\n }\n WEBRTC_TRACE(kTraceInfo, kTraceVideo, ViEId(shared_data_.instance_id()),\n \"%s: channel created: %d\", __FUNCTION__, video_channel);\n return 0;\n}\n\nint ViEBaseImpl::CreateChannel(int& video_channel, \/\/ NOLINT\n int original_channel) {\n return CreateChannel(video_channel, original_channel, true);\n}\n\nint ViEBaseImpl::CreateReceiveChannel(int& video_channel, \/\/ NOLINT\n int original_channel) {\n return CreateChannel(video_channel, original_channel, false);\n}\n\nint ViEBaseImpl::DeleteChannel(const int video_channel) {\n WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id()),\n \"%s(%d)\", __FUNCTION__, video_channel);\n {\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n WEBRTC_TRACE(kTraceError, kTraceVideo,\n ViEId(shared_data_.instance_id()),\n \"%s: channel %d doesn't exist\", __FUNCTION__, video_channel);\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n\n \/\/ Deregister the ViEEncoder if no other channel is using it.\n ViEEncoder* vie_encoder = cs.Encoder(video_channel);\n if (cs.ChannelUsingViEEncoder(video_channel) == false) {\n ViEInputManagerScoped is(*(shared_data_.input_manager()));\n ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder);\n if (provider) {\n provider->DeregisterFrameCallback(vie_encoder);\n }\n }\n }\n\n if (shared_data_.channel_manager()->DeleteChannel(video_channel) == -1) {\n WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()),\n \"%s: Could not delete channel %d\", __FUNCTION__,\n video_channel);\n shared_data_.SetLastError(kViEBaseUnknownError);\n return -1;\n }\n WEBRTC_TRACE(kTraceInfo, kTraceVideo, ViEId(shared_data_.instance_id()),\n \"%s: channel deleted: %d\", __FUNCTION__, video_channel);\n return 0;\n}\n\nint ViEBaseImpl::ConnectAudioChannel(const int video_channel,\n const int audio_channel) {\n WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id()),\n \"%s(%d)\", __FUNCTION__, video_channel);\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n if (!cs.Channel(video_channel)) {\n WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()),\n \"%s: channel %d doesn't exist\", __FUNCTION__, video_channel);\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n\n if (shared_data_.channel_manager()->ConnectVoiceChannel(video_channel,\n audio_channel) != 0) {\n shared_data_.SetLastError(kViEBaseVoEFailure);\n return -1;\n }\n return 0;\n}\n\nint ViEBaseImpl::DisconnectAudioChannel(const int video_channel) {\n WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id()),\n \"%s(%d)\", __FUNCTION__, video_channel);\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n if (!cs.Channel(video_channel)) {\n WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()),\n \"%s: channel %d doesn't exist\", __FUNCTION__, video_channel);\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n\n if (shared_data_.channel_manager()->DisconnectVoiceChannel(\n video_channel) != 0) {\n shared_data_.SetLastError(kViEBaseVoEFailure);\n return -1;\n }\n return 0;\n}\n\nint ViEBaseImpl::StartSend(const int video_channel) {\n WEBRTC_TRACE(kTraceApiCall, kTraceVideo,\n ViEId(shared_data_.instance_id(), video_channel),\n \"%s(channel: %d)\", __FUNCTION__, video_channel);\n\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n WEBRTC_TRACE(kTraceError, kTraceVideo,\n ViEId(shared_data_.instance_id(), video_channel),\n \"%s: Channel %d does not exist\", __FUNCTION__, video_channel);\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n\n ViEEncoder* vie_encoder = cs.Encoder(video_channel);\n assert(vie_encoder != NULL);\n if (vie_encoder->Owner() != video_channel) {\n WEBRTC_TRACE(kTraceError, kTraceVideo,\n ViEId(shared_data_.instance_id(), video_channel),\n \"Can't start ssend on a receive only channel.\");\n shared_data_.SetLastError(kViEBaseReceiveOnlyChannel);\n return -1;\n }\n\n \/\/ Pause and trigger a key frame.\n vie_encoder->Pause();\n int32_t error = vie_channel->StartSend();\n if (error != 0) {\n vie_encoder->Restart();\n WEBRTC_TRACE(kTraceError, kTraceVideo,\n ViEId(shared_data_.instance_id(), video_channel),\n \"%s: Could not start sending on channel %d\", __FUNCTION__,\n video_channel);\n if (error == kViEBaseAlreadySending) {\n shared_data_.SetLastError(kViEBaseAlreadySending);\n }\n shared_data_.SetLastError(kViEBaseUnknownError);\n return -1;\n }\n vie_encoder->SendKeyFrame();\n vie_encoder->Restart();\n return 0;\n}\n\nint ViEBaseImpl::StopSend(const int video_channel) {\n WEBRTC_TRACE(kTraceApiCall, kTraceVideo,\n ViEId(shared_data_.instance_id(), video_channel),\n \"%s(channel: %d)\", __FUNCTION__, video_channel);\n\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n WEBRTC_TRACE(kTraceError, kTraceVideo,\n ViEId(shared_data_.instance_id(), video_channel),\n \"%s: Channel %d does not exist\", __FUNCTION__, video_channel);\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n\n int32_t error = vie_channel->StopSend();\n if (error != 0) {\n WEBRTC_TRACE(kTraceError, kTraceVideo,\n ViEId(shared_data_.instance_id(), video_channel),\n \"%s: Could not stop sending on channel %d\", __FUNCTION__,\n video_channel);\n if (error == kViEBaseNotSending) {\n shared_data_.SetLastError(kViEBaseNotSending);\n } else {\n shared_data_.SetLastError(kViEBaseUnknownError);\n }\n return -1;\n }\n return 0;\n}\n\nint ViEBaseImpl::StartReceive(const int video_channel) {\n WEBRTC_TRACE(kTraceApiCall, kTraceVideo,\n ViEId(shared_data_.instance_id(), video_channel),\n \"%s(channel: %d)\", __FUNCTION__, video_channel);\n\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n WEBRTC_TRACE(kTraceError, kTraceVideo,\n ViEId(shared_data_.instance_id(), video_channel),\n \"%s: Channel %d does not exist\", __FUNCTION__, video_channel);\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n if (vie_channel->StartReceive() != 0) {\n shared_data_.SetLastError(kViEBaseUnknownError);\n return -1;\n }\n return 0;\n}\n\nint ViEBaseImpl::StopReceive(const int video_channel) {\n WEBRTC_TRACE(kTraceApiCall, kTraceVideo,\n ViEId(shared_data_.instance_id(), video_channel),\n \"%s(channel: %d)\", __FUNCTION__, video_channel);\n\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n ViEChannel* vie_channel = cs.Channel(video_channel);\n if (!vie_channel) {\n WEBRTC_TRACE(kTraceError, kTraceVideo,\n ViEId(shared_data_.instance_id(), video_channel),\n \"%s: Channel %d does not exist\", __FUNCTION__, video_channel);\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n if (vie_channel->StopReceive() != 0) {\n shared_data_.SetLastError(kViEBaseUnknownError);\n return -1;\n }\n return 0;\n}\n\nint ViEBaseImpl::GetVersion(char version[1024]) {\n WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id()),\n \"GetVersion(version=?)\");\n assert(kViEVersionMaxMessageSize == 1024);\n if (!version) {\n shared_data_.SetLastError(kViEBaseInvalidArgument);\n return -1;\n }\n\n \/\/ Add WebRTC Version.\n std::stringstream version_stream;\n version_stream << \"VideoEngine 3.34.0\" << std::endl;\n\n \/\/ Add build info.\n version_stream << \"Build: svn:\" << WEBRTC_SVNREVISION << \" \" << BUILDINFO\n << std::endl;\n\n#ifdef WEBRTC_EXTERNAL_TRANSPORT\n version_stream << \"External transport build\" << std::endl;\n#endif\n int version_length = version_stream.tellp();\n assert(version_length < 1024);\n memcpy(version, version_stream.str().c_str(), version_length);\n version[version_length] = '\\0';\n\n WEBRTC_TRACE(kTraceStateInfo, kTraceVideo,\n ViEId(shared_data_.instance_id()), \"GetVersion() => %s\",\n version);\n return 0;\n}\n\nint ViEBaseImpl::LastError() {\n return shared_data_.LastErrorInternal();\n}\n\nint ViEBaseImpl::CreateChannel(int& video_channel, \/\/ NOLINT\n int original_channel, bool sender) {\n ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));\n if (!cs.Channel(original_channel)) {\n WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()),\n \"%s - original_channel does not exist.\", __FUNCTION__,\n shared_data_.instance_id());\n shared_data_.SetLastError(kViEBaseInvalidChannelId);\n return -1;\n }\n\n if (shared_data_.channel_manager()->CreateChannel(&video_channel,\n original_channel,\n sender) == -1) {\n WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()),\n \"%s: Could not create channel\", __FUNCTION__);\n video_channel = -1;\n shared_data_.SetLastError(kViEBaseChannelCreationFailed);\n return -1;\n }\n WEBRTC_TRACE(kTraceInfo, kTraceVideo, ViEId(shared_data_.instance_id()),\n \"%s: channel created: %d\", __FUNCTION__, video_channel);\n return 0;\n}\n\n} \/\/ namespace webrtc\n<|endoftext|>"} {"text":"\n#include \n\n#include \"Werk\/OS\/Hardware.hpp\"\n\nBOOST_AUTO_TEST_SUITE(HardwareTest)\n\nBOOST_AUTO_TEST_CASE(TestGetPageSize)\n{\n\tuint64_t pageSize = werk::getPageSize();\n\n\t\/\/Anything less than 4K won't be adequate anyway\n\tBOOST_REQUIRE(pageSize >= 4 * 1024);\n\n\t\/\/And memory should come in at least 1K chunks\n\tBOOST_CHECK_EQUAL(pageSize % 1024, 0);\n}\n\nBOOST_AUTO_TEST_CASE(TestGetPhysicalMemorySize)\n{\n\tsize_t memorySize = werk::getPhysicalMemorySize();\n\n\t\/\/Anything less than 64M won't be adequate anyway\n\tBOOST_REQUIRE(memorySize >= 64 * 1024 * 1024);\n\n\t\/\/And memory should come in at least 1M chunks\n\tBOOST_CHECK_EQUAL(memorySize % (1024 * 1024), 0);\n}\n\nBOOST_AUTO_TEST_CASE(TestGetProcessorCount)\n{\n\tsize_t processorCount = werk::getProcessorCount();\n\tBOOST_REQUIRE(processorCount >= 1);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\nModify memory tests to be more robust on different systems\n#include \n\n#include \"Werk\/OS\/Hardware.hpp\"\n\nBOOST_AUTO_TEST_SUITE(HardwareTest)\n\nBOOST_AUTO_TEST_CASE(TestGetPageSize)\n{\n\tuint64_t pageSize = werk::getPageSize();\n\n\t\/\/Anything less than 4K won't be adequate anyway\n\tBOOST_REQUIRE(pageSize >= 4 * 1024);\n\n\t\/\/And pages should come in at least 1K chunks\n\tBOOST_CHECK_EQUAL(pageSize % 1024, 0);\n}\n\nBOOST_AUTO_TEST_CASE(TestGetPhysicalMemorySize)\n{\n\tsize_t memorySize = werk::getPhysicalMemorySize();\n\n\t\/\/Anything less than 64M won't be adequate anyway\n\tBOOST_REQUIRE(memorySize >= 64 * 1024 * 1024);\n\n\t\/\/And memory should come in at least 1K chunks\n\tBOOST_CHECK_EQUAL(memorySize % 1024, 0);\n}\n\nBOOST_AUTO_TEST_CASE(TestGetProcessorCount)\n{\n\tsize_t processorCount = werk::getProcessorCount();\n\tBOOST_REQUIRE(processorCount >= 1);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"\/*\n * Copyright 2015 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"src\/gpu\/vk\/GrVkTexture.h\"\n\n#include \"src\/gpu\/GrTexturePriv.h\"\n#include \"src\/gpu\/vk\/GrVkDescriptorSet.h\"\n#include \"src\/gpu\/vk\/GrVkGpu.h\"\n#include \"src\/gpu\/vk\/GrVkImageView.h\"\n#include \"src\/gpu\/vk\/GrVkTextureRenderTarget.h\"\n#include \"src\/gpu\/vk\/GrVkUtil.h\"\n\n#include \"include\/gpu\/vk\/GrVkTypes.h\"\n\n#define VK_CALL(GPU, X) GR_VK_CALL(GPU->vkInterface(), X)\n\n\/\/ Because this class is virtually derived from GrSurface we must explicitly call its constructor.\nGrVkTexture::GrVkTexture(GrVkGpu* gpu,\n SkBudgeted budgeted,\n SkISize dimensions,\n const GrVkImageInfo& info,\n sk_sp layout,\n const GrVkImageView* view,\n GrMipMapsStatus mipMapsStatus)\n : GrSurface(gpu, dimensions, info.fProtected)\n , GrVkImage(info, std::move(layout), GrBackendObjectOwnership::kOwned)\n , INHERITED(gpu, dimensions, info.fProtected, GrTextureType::k2D, mipMapsStatus)\n , fTextureView(view)\n , fDescSetCache(kMaxCachedDescSets) {\n SkASSERT((GrMipMapsStatus::kNotAllocated == mipMapsStatus) == (1 == info.fLevelCount));\n \/\/ We don't support creating external GrVkTextures\n SkASSERT(!info.fYcbcrConversionInfo.isValid() || !info.fYcbcrConversionInfo.fExternalFormat);\n this->registerWithCache(budgeted);\n if (GrVkFormatIsCompressed(info.fFormat)) {\n this->setReadOnly();\n }\n}\n\nGrVkTexture::GrVkTexture(GrVkGpu* gpu, SkISize dimensions, const GrVkImageInfo& info,\n sk_sp layout, const GrVkImageView* view,\n GrMipMapsStatus mipMapsStatus, GrBackendObjectOwnership ownership,\n GrWrapCacheable cacheable, GrIOType ioType, bool isExternal)\n : GrSurface(gpu, dimensions, info.fProtected)\n , GrVkImage(info, std::move(layout), ownership)\n , INHERITED(gpu, dimensions, info.fProtected,\n isExternal ? GrTextureType::kExternal : GrTextureType::k2D, mipMapsStatus)\n , fTextureView(view)\n , fDescSetCache(kMaxCachedDescSets) {\n SkASSERT((GrMipMapsStatus::kNotAllocated == mipMapsStatus) == (1 == info.fLevelCount));\n if (ioType == kRead_GrIOType) {\n this->setReadOnly();\n }\n this->registerWithCacheWrapped(cacheable);\n}\n\n\/\/ Because this class is virtually derived from GrSurface we must explicitly call its constructor.\nGrVkTexture::GrVkTexture(GrVkGpu* gpu,\n SkISize dimensions,\n const GrVkImageInfo& info,\n sk_sp layout,\n const GrVkImageView* view,\n GrMipMapsStatus mipMapsStatus,\n GrBackendObjectOwnership ownership)\n : GrSurface(gpu, dimensions, info.fProtected)\n , GrVkImage(info, layout, ownership)\n , INHERITED(gpu, dimensions, info.fProtected, GrTextureType::k2D, mipMapsStatus)\n , fTextureView(view)\n , fDescSetCache(kMaxCachedDescSets) {\n SkASSERT((GrMipMapsStatus::kNotAllocated == mipMapsStatus) == (1 == info.fLevelCount));\n \/\/ Since this ctor is only called from GrVkTextureRenderTarget, we can't have a ycbcr conversion\n \/\/ since we don't support that on render targets.\n SkASSERT(!info.fYcbcrConversionInfo.isValid());\n}\n\nsk_sp GrVkTexture::MakeNewTexture(GrVkGpu* gpu, SkBudgeted budgeted,\n SkISize dimensions,\n const GrVkImage::ImageDesc& imageDesc,\n GrMipMapsStatus mipMapsStatus) {\n SkASSERT(imageDesc.fUsageFlags & VK_IMAGE_USAGE_SAMPLED_BIT);\n\n GrVkImageInfo info;\n if (!GrVkImage::InitImageInfo(gpu, imageDesc, &info)) {\n return nullptr;\n }\n\n const GrVkImageView* imageView = GrVkImageView::Create(\n gpu, info.fImage, info.fFormat, GrVkImageView::kColor_Type, info.fLevelCount,\n info.fYcbcrConversionInfo);\n if (!imageView) {\n GrVkImage::DestroyImageInfo(gpu, &info);\n return nullptr;\n }\n sk_sp layout(new GrVkImageLayout(info.fImageLayout));\n\n return sk_sp(new GrVkTexture(gpu, budgeted, dimensions, info, std::move(layout),\n imageView, mipMapsStatus));\n}\n\nsk_sp GrVkTexture::MakeWrappedTexture(GrVkGpu* gpu,\n SkISize dimensions,\n GrWrapOwnership wrapOwnership,\n GrWrapCacheable cacheable,\n GrIOType ioType,\n const GrVkImageInfo& info,\n sk_sp layout) {\n \/\/ Adopted textures require both image and allocation because we're responsible for freeing\n SkASSERT(VK_NULL_HANDLE != info.fImage &&\n (kBorrow_GrWrapOwnership == wrapOwnership || VK_NULL_HANDLE != info.fAlloc.fMemory));\n\n const GrVkImageView* imageView = GrVkImageView::Create(\n gpu, info.fImage, info.fFormat, GrVkImageView::kColor_Type, info.fLevelCount,\n info.fYcbcrConversionInfo);\n if (!imageView) {\n return nullptr;\n }\n\n GrMipMapsStatus mipMapsStatus = info.fLevelCount > 1 ? GrMipMapsStatus::kValid\n : GrMipMapsStatus::kNotAllocated;\n\n GrBackendObjectOwnership ownership = kBorrow_GrWrapOwnership == wrapOwnership\n ? GrBackendObjectOwnership::kBorrowed : GrBackendObjectOwnership::kOwned;\n bool isExternal = info.fYcbcrConversionInfo.isValid() &&\n (info.fYcbcrConversionInfo.fExternalFormat != 0);\n return sk_sp(new GrVkTexture(gpu, dimensions, info, std::move(layout), imageView,\n mipMapsStatus, ownership, cacheable, ioType,\n isExternal));\n}\n\nGrVkTexture::~GrVkTexture() {\n \/\/ either release or abandon should have been called by the owner of this object.\n SkASSERT(!fTextureView);\n}\n\nvoid GrVkTexture::onRelease() {\n \/\/ We're about to be severed from our GrVkResource. If there are \"finish\" idle procs we have to\n \/\/ decide who will handle them. If the resource is still tied to a command buffer we let it\n \/\/ handle them. Otherwise, we handle them.\n if (this->hasResource() && this->resource()->isOwnedByCommandBuffer()) {\n this->removeFinishIdleProcs();\n }\n\n \/\/ we create this and don't hand it off, so we should always destroy it\n if (fTextureView) {\n fTextureView->unref(this->getVkGpu());\n fTextureView = nullptr;\n }\n\n fDescSetCache.reset();\n\n this->releaseImage(this->getVkGpu());\n\n INHERITED::onRelease();\n}\n\nstruct GrVkTexture::DescriptorCacheEntry {\n DescriptorCacheEntry(const GrVkDescriptorSet* fDescSet, GrVkGpu* gpu)\n : fDescriptorSet(fDescSet), fGpu(gpu) {}\n ~DescriptorCacheEntry() {\n if (fDescriptorSet) {\n fDescriptorSet->recycle(fGpu);\n }\n }\n\n const GrVkDescriptorSet* fDescriptorSet;\n GrVkGpu* fGpu;\n};\n\nvoid GrVkTexture::onAbandon() {\n \/\/ We're about to be severed from our GrVkResource. If there are \"finish\" idle procs we have to\n \/\/ decide who will handle them. If the resource is still tied to a command buffer we let it\n \/\/ handle them. Otherwise, we handle them.\n if (this->hasResource() && this->resource()->isOwnedByCommandBuffer()) {\n this->removeFinishIdleProcs();\n }\n\n \/\/ we create this and don't hand it off, so we should always destroy it\n if (fTextureView) {\n fTextureView->unref(this->getVkGpu());\n fTextureView = nullptr;\n }\n\n fDescSetCache.reset();\n\n this->releaseImage(this->getVkGpu());\n INHERITED::onAbandon();\n}\n\nGrBackendTexture GrVkTexture::getBackendTexture() const {\n return GrBackendTexture(this->width(), this->height(), fInfo, this->grVkImageLayout());\n}\n\nGrVkGpu* GrVkTexture::getVkGpu() const {\n SkASSERT(!this->wasDestroyed());\n return static_cast(this->getGpu());\n}\n\nconst GrVkImageView* GrVkTexture::textureView() {\n return fTextureView;\n}\n\nvoid GrVkTexture::addIdleProc(sk_sp idleProc, IdleState type) {\n INHERITED::addIdleProc(idleProc, type);\n if (type == IdleState::kFinished) {\n if (auto* resource = this->resource()) {\n resource->addIdleProc(this, std::move(idleProc));\n }\n }\n}\n\nvoid GrVkTexture::callIdleProcsOnBehalfOfResource() {\n \/\/ If we got here then the resource is being removed from its last command buffer and the\n \/\/ texture is idle in the cache. Any kFlush idle procs should already have been called. So\n \/\/ the texture and resource should have the same set of procs.\n SkASSERT(this->resource());\n SkASSERT(this->resource()->idleProcCnt() == fIdleProcs.count());\n#ifdef SK_DEBUG\n for (int i = 0; i < fIdleProcs.count(); ++i) {\n SkASSERT(fIdleProcs[i] == this->resource()->idleProc(i));\n }\n#endif\n fIdleProcs.reset();\n this->resource()->resetIdleProcs();\n}\n\nvoid GrVkTexture::willRemoveLastRef() {\n if (!fIdleProcs.count()) {\n return;\n }\n \/\/ This is called when the GrTexture is purgeable. However, we need to check whether the\n \/\/ Resource is still owned by any command buffers. If it is then it will call the proc.\n auto* resource = this->hasResource() ? this->resource() : nullptr;\n bool callFinishProcs = !resource || !resource->isOwnedByCommandBuffer();\n if (callFinishProcs) {\n \/\/ Everything must go!\n fIdleProcs.reset();\n resource->resetIdleProcs();\n } else {\n \/\/ The procs that should be called on flush but not finish are those that are owned\n \/\/ by the GrVkTexture and not the Resource. We do this by copying the resource's array\n \/\/ and thereby dropping refs to procs we own but the resource does not.\n SkASSERT(resource);\n fIdleProcs.reset(resource->idleProcCnt());\n for (int i = 0; i < fIdleProcs.count(); ++i) {\n fIdleProcs[i] = resource->idleProc(i);\n }\n }\n}\n\nvoid GrVkTexture::removeFinishIdleProcs() {\n \/\/ This should only be called by onRelease\/onAbandon when we have already checked for a\n \/\/ resource.\n const auto* resource = this->resource();\n SkASSERT(resource);\n SkSTArray<4, sk_sp> procsToKeep;\n int resourceIdx = 0;\n \/\/ The idle procs that are common between the GrVkTexture and its Resource should be found in\n \/\/ the same order.\n for (int i = 0; i < fIdleProcs.count(); ++i) {\n if (fIdleProcs[i] == resource->idleProc(resourceIdx)) {\n ++resourceIdx;\n } else {\n procsToKeep.push_back(fIdleProcs[i]);\n }\n }\n SkASSERT(resourceIdx == resource->idleProcCnt());\n fIdleProcs = procsToKeep;\n}\n\nconst GrVkDescriptorSet* GrVkTexture::cachedSingleDescSet(GrSamplerState state) {\n if (std::unique_ptr* e = fDescSetCache.find(state)) {\n return (*e)->fDescriptorSet;\n }\n return nullptr;\n}\n\nvoid GrVkTexture::addDescriptorSetToCache(const GrVkDescriptorSet* descSet, GrSamplerState state) {\n SkASSERT(!fDescSetCache.find(state));\n descSet->ref();\n fDescSetCache.insert(state,\n std::unique_ptr(\n new DescriptorCacheEntry(descSet, this->getVkGpu())));\n}\nAvoid possible nullptr dereference am: e26a98217e am: f6cc75d713\/*\n * Copyright 2015 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"src\/gpu\/vk\/GrVkTexture.h\"\n\n#include \"src\/gpu\/GrTexturePriv.h\"\n#include \"src\/gpu\/vk\/GrVkDescriptorSet.h\"\n#include \"src\/gpu\/vk\/GrVkGpu.h\"\n#include \"src\/gpu\/vk\/GrVkImageView.h\"\n#include \"src\/gpu\/vk\/GrVkTextureRenderTarget.h\"\n#include \"src\/gpu\/vk\/GrVkUtil.h\"\n\n#include \"include\/gpu\/vk\/GrVkTypes.h\"\n\n#define VK_CALL(GPU, X) GR_VK_CALL(GPU->vkInterface(), X)\n\n\/\/ Because this class is virtually derived from GrSurface we must explicitly call its constructor.\nGrVkTexture::GrVkTexture(GrVkGpu* gpu,\n SkBudgeted budgeted,\n SkISize dimensions,\n const GrVkImageInfo& info,\n sk_sp layout,\n const GrVkImageView* view,\n GrMipMapsStatus mipMapsStatus)\n : GrSurface(gpu, dimensions, info.fProtected)\n , GrVkImage(info, std::move(layout), GrBackendObjectOwnership::kOwned)\n , INHERITED(gpu, dimensions, info.fProtected, GrTextureType::k2D, mipMapsStatus)\n , fTextureView(view)\n , fDescSetCache(kMaxCachedDescSets) {\n SkASSERT((GrMipMapsStatus::kNotAllocated == mipMapsStatus) == (1 == info.fLevelCount));\n \/\/ We don't support creating external GrVkTextures\n SkASSERT(!info.fYcbcrConversionInfo.isValid() || !info.fYcbcrConversionInfo.fExternalFormat);\n this->registerWithCache(budgeted);\n if (GrVkFormatIsCompressed(info.fFormat)) {\n this->setReadOnly();\n }\n}\n\nGrVkTexture::GrVkTexture(GrVkGpu* gpu, SkISize dimensions, const GrVkImageInfo& info,\n sk_sp layout, const GrVkImageView* view,\n GrMipMapsStatus mipMapsStatus, GrBackendObjectOwnership ownership,\n GrWrapCacheable cacheable, GrIOType ioType, bool isExternal)\n : GrSurface(gpu, dimensions, info.fProtected)\n , GrVkImage(info, std::move(layout), ownership)\n , INHERITED(gpu, dimensions, info.fProtected,\n isExternal ? GrTextureType::kExternal : GrTextureType::k2D, mipMapsStatus)\n , fTextureView(view)\n , fDescSetCache(kMaxCachedDescSets) {\n SkASSERT((GrMipMapsStatus::kNotAllocated == mipMapsStatus) == (1 == info.fLevelCount));\n if (ioType == kRead_GrIOType) {\n this->setReadOnly();\n }\n this->registerWithCacheWrapped(cacheable);\n}\n\n\/\/ Because this class is virtually derived from GrSurface we must explicitly call its constructor.\nGrVkTexture::GrVkTexture(GrVkGpu* gpu,\n SkISize dimensions,\n const GrVkImageInfo& info,\n sk_sp layout,\n const GrVkImageView* view,\n GrMipMapsStatus mipMapsStatus,\n GrBackendObjectOwnership ownership)\n : GrSurface(gpu, dimensions, info.fProtected)\n , GrVkImage(info, layout, ownership)\n , INHERITED(gpu, dimensions, info.fProtected, GrTextureType::k2D, mipMapsStatus)\n , fTextureView(view)\n , fDescSetCache(kMaxCachedDescSets) {\n SkASSERT((GrMipMapsStatus::kNotAllocated == mipMapsStatus) == (1 == info.fLevelCount));\n \/\/ Since this ctor is only called from GrVkTextureRenderTarget, we can't have a ycbcr conversion\n \/\/ since we don't support that on render targets.\n SkASSERT(!info.fYcbcrConversionInfo.isValid());\n}\n\nsk_sp GrVkTexture::MakeNewTexture(GrVkGpu* gpu, SkBudgeted budgeted,\n SkISize dimensions,\n const GrVkImage::ImageDesc& imageDesc,\n GrMipMapsStatus mipMapsStatus) {\n SkASSERT(imageDesc.fUsageFlags & VK_IMAGE_USAGE_SAMPLED_BIT);\n\n GrVkImageInfo info;\n if (!GrVkImage::InitImageInfo(gpu, imageDesc, &info)) {\n return nullptr;\n }\n\n const GrVkImageView* imageView = GrVkImageView::Create(\n gpu, info.fImage, info.fFormat, GrVkImageView::kColor_Type, info.fLevelCount,\n info.fYcbcrConversionInfo);\n if (!imageView) {\n GrVkImage::DestroyImageInfo(gpu, &info);\n return nullptr;\n }\n sk_sp layout(new GrVkImageLayout(info.fImageLayout));\n\n return sk_sp(new GrVkTexture(gpu, budgeted, dimensions, info, std::move(layout),\n imageView, mipMapsStatus));\n}\n\nsk_sp GrVkTexture::MakeWrappedTexture(GrVkGpu* gpu,\n SkISize dimensions,\n GrWrapOwnership wrapOwnership,\n GrWrapCacheable cacheable,\n GrIOType ioType,\n const GrVkImageInfo& info,\n sk_sp layout) {\n \/\/ Adopted textures require both image and allocation because we're responsible for freeing\n SkASSERT(VK_NULL_HANDLE != info.fImage &&\n (kBorrow_GrWrapOwnership == wrapOwnership || VK_NULL_HANDLE != info.fAlloc.fMemory));\n\n const GrVkImageView* imageView = GrVkImageView::Create(\n gpu, info.fImage, info.fFormat, GrVkImageView::kColor_Type, info.fLevelCount,\n info.fYcbcrConversionInfo);\n if (!imageView) {\n return nullptr;\n }\n\n GrMipMapsStatus mipMapsStatus = info.fLevelCount > 1 ? GrMipMapsStatus::kValid\n : GrMipMapsStatus::kNotAllocated;\n\n GrBackendObjectOwnership ownership = kBorrow_GrWrapOwnership == wrapOwnership\n ? GrBackendObjectOwnership::kBorrowed : GrBackendObjectOwnership::kOwned;\n bool isExternal = info.fYcbcrConversionInfo.isValid() &&\n (info.fYcbcrConversionInfo.fExternalFormat != 0);\n return sk_sp(new GrVkTexture(gpu, dimensions, info, std::move(layout), imageView,\n mipMapsStatus, ownership, cacheable, ioType,\n isExternal));\n}\n\nGrVkTexture::~GrVkTexture() {\n \/\/ either release or abandon should have been called by the owner of this object.\n SkASSERT(!fTextureView);\n}\n\nvoid GrVkTexture::onRelease() {\n \/\/ We're about to be severed from our GrVkResource. If there are \"finish\" idle procs we have to\n \/\/ decide who will handle them. If the resource is still tied to a command buffer we let it\n \/\/ handle them. Otherwise, we handle them.\n if (this->hasResource() && this->resource()->isOwnedByCommandBuffer()) {\n this->removeFinishIdleProcs();\n }\n\n \/\/ we create this and don't hand it off, so we should always destroy it\n if (fTextureView) {\n fTextureView->unref(this->getVkGpu());\n fTextureView = nullptr;\n }\n\n fDescSetCache.reset();\n\n this->releaseImage(this->getVkGpu());\n\n INHERITED::onRelease();\n}\n\nstruct GrVkTexture::DescriptorCacheEntry {\n DescriptorCacheEntry(const GrVkDescriptorSet* fDescSet, GrVkGpu* gpu)\n : fDescriptorSet(fDescSet), fGpu(gpu) {}\n ~DescriptorCacheEntry() {\n if (fDescriptorSet) {\n fDescriptorSet->recycle(fGpu);\n }\n }\n\n const GrVkDescriptorSet* fDescriptorSet;\n GrVkGpu* fGpu;\n};\n\nvoid GrVkTexture::onAbandon() {\n \/\/ We're about to be severed from our GrVkResource. If there are \"finish\" idle procs we have to\n \/\/ decide who will handle them. If the resource is still tied to a command buffer we let it\n \/\/ handle them. Otherwise, we handle them.\n if (this->hasResource() && this->resource()->isOwnedByCommandBuffer()) {\n this->removeFinishIdleProcs();\n }\n\n \/\/ we create this and don't hand it off, so we should always destroy it\n if (fTextureView) {\n fTextureView->unref(this->getVkGpu());\n fTextureView = nullptr;\n }\n\n fDescSetCache.reset();\n\n this->releaseImage(this->getVkGpu());\n INHERITED::onAbandon();\n}\n\nGrBackendTexture GrVkTexture::getBackendTexture() const {\n return GrBackendTexture(this->width(), this->height(), fInfo, this->grVkImageLayout());\n}\n\nGrVkGpu* GrVkTexture::getVkGpu() const {\n SkASSERT(!this->wasDestroyed());\n return static_cast(this->getGpu());\n}\n\nconst GrVkImageView* GrVkTexture::textureView() {\n return fTextureView;\n}\n\nvoid GrVkTexture::addIdleProc(sk_sp idleProc, IdleState type) {\n INHERITED::addIdleProc(idleProc, type);\n if (type == IdleState::kFinished) {\n if (auto* resource = this->resource()) {\n resource->addIdleProc(this, std::move(idleProc));\n }\n }\n}\n\nvoid GrVkTexture::callIdleProcsOnBehalfOfResource() {\n \/\/ If we got here then the resource is being removed from its last command buffer and the\n \/\/ texture is idle in the cache. Any kFlush idle procs should already have been called. So\n \/\/ the texture and resource should have the same set of procs.\n SkASSERT(this->resource());\n SkASSERT(this->resource()->idleProcCnt() == fIdleProcs.count());\n#ifdef SK_DEBUG\n for (int i = 0; i < fIdleProcs.count(); ++i) {\n SkASSERT(fIdleProcs[i] == this->resource()->idleProc(i));\n }\n#endif\n fIdleProcs.reset();\n this->resource()->resetIdleProcs();\n}\n\nvoid GrVkTexture::willRemoveLastRef() {\n if (!fIdleProcs.count()) {\n return;\n }\n \/\/ This is called when the GrTexture is purgeable. However, we need to check whether the\n \/\/ Resource is still owned by any command buffers. If it is then it will call the proc.\n auto* resource = this->hasResource() ? this->resource() : nullptr;\n bool callFinishProcs = !resource || !resource->isOwnedByCommandBuffer();\n if (callFinishProcs) {\n \/\/ Everything must go!\n fIdleProcs.reset();\n if (resource) {\n resource->resetIdleProcs();\n }\n } else {\n \/\/ The procs that should be called on flush but not finish are those that are owned\n \/\/ by the GrVkTexture and not the Resource. We do this by copying the resource's array\n \/\/ and thereby dropping refs to procs we own but the resource does not.\n SkASSERT(resource);\n fIdleProcs.reset(resource->idleProcCnt());\n for (int i = 0; i < fIdleProcs.count(); ++i) {\n fIdleProcs[i] = resource->idleProc(i);\n }\n }\n}\n\nvoid GrVkTexture::removeFinishIdleProcs() {\n \/\/ This should only be called by onRelease\/onAbandon when we have already checked for a\n \/\/ resource.\n const auto* resource = this->resource();\n SkASSERT(resource);\n SkSTArray<4, sk_sp> procsToKeep;\n int resourceIdx = 0;\n \/\/ The idle procs that are common between the GrVkTexture and its Resource should be found in\n \/\/ the same order.\n for (int i = 0; i < fIdleProcs.count(); ++i) {\n if (fIdleProcs[i] == resource->idleProc(resourceIdx)) {\n ++resourceIdx;\n } else {\n procsToKeep.push_back(fIdleProcs[i]);\n }\n }\n SkASSERT(resourceIdx == resource->idleProcCnt());\n fIdleProcs = procsToKeep;\n}\n\nconst GrVkDescriptorSet* GrVkTexture::cachedSingleDescSet(GrSamplerState state) {\n if (std::unique_ptr* e = fDescSetCache.find(state)) {\n return (*e)->fDescriptorSet;\n }\n return nullptr;\n}\n\nvoid GrVkTexture::addDescriptorSetToCache(const GrVkDescriptorSet* descSet, GrSamplerState state) {\n SkASSERT(!fDescSetCache.find(state));\n descSet->ref();\n fDescSetCache.insert(state,\n std::unique_ptr(\n new DescriptorCacheEntry(descSet, this->getVkGpu())));\n}\n<|endoftext|>"} {"text":"\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield \n *\n * This library is open source and may be redistributed and\/or modified under \n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or \n * (at your option) any later version. The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the \n * OpenSceneGraph Public License for more details.\n*\/\n\n#include \n#include \n\nusing namespace osgGA;\n\nSimpleViewer::SimpleViewer():\n _firstFrame(true)\n{\n _sceneView = new osgUtil::SceneView;\n _sceneView->setDefaults();\n _sceneView->getState()->setContextID(osg::GraphicsContext::createNewContextID());\n \n _startTick = osg::Timer::instance()->tick();\n _frameStamp = new osg::FrameStamp;\n _frameStamp->setFrameNumber(0);\n _frameStamp->setReferenceTime(0);\n \n _eventQueue = new osgGA::EventQueue;\n _eventQueue->setStartTick(_startTick);\n\n _eventVisitor = new osgGA::EventVisitor;\n \n setDatabasePager(new osgDB::DatabasePager);\n}\n\nSimpleViewer::~SimpleViewer()\n{\n _sceneView->releaseAllGLObjects();\n osg::GraphicsContext::decrementContextIDUsageCount(_sceneView->getState()->getContextID());\n}\n\nvoid SimpleViewer::setSceneData(osg::Node* node)\n{\n _sceneView->setSceneData(node);\n \n if (_cameraManipulator.valid())\n {\n _cameraManipulator->setNode(node);\n \n osg::ref_ptr dummyEvent = _eventQueue->createEvent();\n _cameraManipulator->home(*dummyEvent, *this);\n }\n\n if (_databasePager.valid())\n { \n \/\/ register any PagedLOD that need to be tracked in the scene graph\n _databasePager->registerPagedLODs(node);\n }\n}\n\nosg::Node* SimpleViewer::getSceneData()\n{\n return _sceneView->getSceneData();\n}\n\nconst osg::Node* SimpleViewer::getSceneData() const\n{\n return _sceneView->getSceneData();\n}\n\nosg::CameraNode* SimpleViewer::getCamera()\n{\n return _sceneView->getCamera();\n}\n\nconst osg::CameraNode* SimpleViewer::getCamera() const\n{\n return _sceneView->getCamera();\n}\n\nvoid SimpleViewer::setCameraManipulator(MatrixManipulator* manipulator)\n{\n if (_cameraManipulator == manipulator) return;\n \n _cameraManipulator = manipulator;\n if (_cameraManipulator.valid())\n {\n _cameraManipulator->setNode(_sceneView->getSceneData());\n \n osg::ref_ptr dummyEvent = _eventQueue->createEvent();\n _cameraManipulator->home(*dummyEvent, *this);\n }\n}\n\nvoid SimpleViewer::addEventHandler(GUIEventHandler* eventHandler)\n{\n _eventHandlers.push_back(eventHandler);\n}\n\nvoid SimpleViewer::setDatabasePager(osgDB::DatabasePager* dp)\n{\n _databasePager = dp;\n \n if (dp && _sceneView.valid())\n {\n \/\/ need to register the DatabasePager with the SceneView's CullVisitor so it can pass on request\n \/\/ for files to be loaded.\n _sceneView->getCullVisitor()->setDatabaseRequestHandler(_databasePager.get());\n }\n}\n\nvoid SimpleViewer::init()\n{\n osg::ref_ptr initEvent = _eventQueue->createEvent();\n initEvent->setEventType(osgGA::GUIEventAdapter::FRAME);\n _cameraManipulator->init(*initEvent, *this);\n}\n\nvoid SimpleViewer::frame()\n{\n if (_firstFrame)\n {\n init();\n _firstFrame = false;\n }\n\n frameAdvance();\n frameEventTraversal();\n frameUpdateTraversal();\n frameCullTraversal();\n frameDrawTraversal();\n}\n\nvoid SimpleViewer::frameAdvance()\n{\n osg::Timer_t currentTick = osg::Timer::instance()->tick();\n _frameStamp->setReferenceTime(osg::Timer::instance()->delta_s(_startTick,currentTick));\n _frameStamp->setFrameNumber(_frameStamp->getFrameNumber()+1);\n\n _sceneView->setFrameStamp(_frameStamp.get());\n}\n\nvoid SimpleViewer::frameEventTraversal()\n{\n _eventQueue->frame( _frameStamp->getReferenceTime() );\n\n osgGA::EventQueue::Events events;\n _eventQueue->takeEvents(events);\n \n if (_eventVisitor.valid())\n {\n _eventVisitor->setTraversalNumber(_frameStamp->getFrameNumber());\n }\n \n for(osgGA::EventQueue::Events::iterator itr = events.begin();\n itr != events.end();\n ++itr)\n {\n osgGA::GUIEventAdapter* event = itr->get();\n \n bool handled = false;\n \n if (_eventVisitor.valid())\n {\n _eventVisitor->reset();\n _eventVisitor->addEvent( event );\n \n getSceneData()->accept(*_eventVisitor);\n \n if (_eventVisitor->getEventHandled()) handled = true;\n }\n \n if (_cameraManipulator.valid())\n {\n _cameraManipulator->handle( *event, *this );\n }\n \n for(EventHandlers::iterator hitr = _eventHandlers.begin();\n hitr != _eventHandlers.end() && !handled;\n ++hitr)\n {\n handled = (*hitr)->handle( *event, *this, 0, 0);\n }\n }\n}\n\nvoid SimpleViewer::frameUpdateTraversal()\n{\n double previousAspectRatio = ( static_cast(_sceneView->getViewport()->width())\/\n static_cast(_sceneView->getViewport()->height()) );\n\n \/\/ update the viewport\n int width = _eventQueue->getCurrentEventState()->getWindowWidth();\n int height = _eventQueue->getCurrentEventState()->getWindowHeight();\n _sceneView->setViewport(0,0,width,height);\n\n double newAspectRatio = ( static_cast(_sceneView->getViewport()->width())\/\n static_cast(_sceneView->getViewport()->height()) );\n \n \n \/\/ if aspect ratio adjusted change the project matrix to suit.\n if (previousAspectRatio != newAspectRatio)\n {\n osg::Matrixd& pm = _sceneView->getProjectionMatrix();\n bool orthographicCamera = (pm(0,3)==0.0) && (pm(0,3)==0.0) && (pm(0,3)==0.0) && (pm(0,3)==1.0); \n if (orthographicCamera)\n {\n double left, right, bottom, top, zNear, zFar;\n _sceneView->getProjectionMatrixAsOrtho(left, right, bottom, top, zNear, zFar);\n\n double mid = (right+left)*0.5;\n double halfWidth = (right-left)*0.5;\n left = mid - halfWidth * (newAspectRatio\/previousAspectRatio);\n right = mid + halfWidth * (newAspectRatio\/previousAspectRatio);\n _sceneView->setProjectionMatrixAsOrtho(left, right, bottom, top, zNear, zFar);\n }\n else\n {\n double left, right, bottom, top, zNear, zFar;\n _sceneView->getProjectionMatrixAsFrustum(left, right, bottom, top, zNear, zFar);\n\n double mid = (right+left)*0.5;\n double halfWidth = (right-left)*0.5;\n left = mid - halfWidth * (newAspectRatio\/previousAspectRatio);\n right = mid + halfWidth * (newAspectRatio\/previousAspectRatio);\n _sceneView->setProjectionMatrixAsFrustum(left, right, bottom, top, zNear, zFar);\n }\n } \n \n if (_cameraManipulator.valid())\n {\n _sceneView->setViewMatrix(_cameraManipulator->getInverseMatrix());\n }\n\n if (_databasePager.valid())\n { \n \/\/ tell the DatabasePager the frame number of that the scene graph is being actively used to render a frame\n _databasePager->signalBeginFrame(_frameStamp.get());\n\n \/\/ syncronize changes required by the DatabasePager thread to the scene graph\n _databasePager->updateSceneGraph(_frameStamp->getReferenceTime());\n }\n \n _sceneView->update();\n}\n\nvoid SimpleViewer::frameCullTraversal()\n{\n _sceneView->cull();\n}\n\nvoid SimpleViewer::frameDrawTraversal()\n{\n _sceneView->draw();\n\n if (_databasePager.valid())\n { \n \/\/ tell the DatabasePager the frame number of that the scene graph is being actively used to render a frame\n _databasePager->signalEndFrame();\n\n \/\/ clean up and compile gl objects with a specified limit \n double availableTime = 0.0025; \/\/ 2.5 ms\n\n \/\/ compile any GL objects that are required.\n _databasePager->compileGLObjects(*(_sceneView->getState()),availableTime);\n\n \/\/ flush deleted GL objects.\n _sceneView->flushDeletedGLObjects(availableTime);\n }\n}\n\nvoid SimpleViewer::cleanup()\n{\n if (_databasePager.valid())\n { \n \/\/ clear the database pager so its starts a fresh on the next update\/cull\/draw traversals \n _databasePager->clear();\n \n \/\/ release the GL objects stored in the scene graph.\n _sceneView->releaseAllGLObjects();\n \n \/\/ do a flush to delete all the OpenGL objects that have been deleted or released from the scene graph.\n _sceneView->flushAllDeletedGLObjects();\n }\n \n _sceneView->releaseAllGLObjects();\n _sceneView->flushAllDeletedGLObjects();\n}\nAdded check to init to prevent crash when no camera manipulator is supplied.\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield \n *\n * This library is open source and may be redistributed and\/or modified under \n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or \n * (at your option) any later version. The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the \n * OpenSceneGraph Public License for more details.\n*\/\n\n#include \n#include \n\nusing namespace osgGA;\n\nSimpleViewer::SimpleViewer():\n _firstFrame(true)\n{\n _sceneView = new osgUtil::SceneView;\n _sceneView->setDefaults();\n _sceneView->getState()->setContextID(osg::GraphicsContext::createNewContextID());\n \n _startTick = osg::Timer::instance()->tick();\n _frameStamp = new osg::FrameStamp;\n _frameStamp->setFrameNumber(0);\n _frameStamp->setReferenceTime(0);\n \n _eventQueue = new osgGA::EventQueue;\n _eventQueue->setStartTick(_startTick);\n\n _eventVisitor = new osgGA::EventVisitor;\n \n setDatabasePager(new osgDB::DatabasePager);\n}\n\nSimpleViewer::~SimpleViewer()\n{\n _sceneView->releaseAllGLObjects();\n osg::GraphicsContext::decrementContextIDUsageCount(_sceneView->getState()->getContextID());\n}\n\nvoid SimpleViewer::setSceneData(osg::Node* node)\n{\n _sceneView->setSceneData(node);\n \n if (_cameraManipulator.valid())\n {\n _cameraManipulator->setNode(node);\n \n osg::ref_ptr dummyEvent = _eventQueue->createEvent();\n _cameraManipulator->home(*dummyEvent, *this);\n }\n\n if (_databasePager.valid())\n { \n \/\/ register any PagedLOD that need to be tracked in the scene graph\n _databasePager->registerPagedLODs(node);\n }\n}\n\nosg::Node* SimpleViewer::getSceneData()\n{\n return _sceneView->getSceneData();\n}\n\nconst osg::Node* SimpleViewer::getSceneData() const\n{\n return _sceneView->getSceneData();\n}\n\nosg::CameraNode* SimpleViewer::getCamera()\n{\n return _sceneView->getCamera();\n}\n\nconst osg::CameraNode* SimpleViewer::getCamera() const\n{\n return _sceneView->getCamera();\n}\n\nvoid SimpleViewer::setCameraManipulator(MatrixManipulator* manipulator)\n{\n if (_cameraManipulator == manipulator) return;\n \n _cameraManipulator = manipulator;\n if (_cameraManipulator.valid())\n {\n _cameraManipulator->setNode(_sceneView->getSceneData());\n \n osg::ref_ptr dummyEvent = _eventQueue->createEvent();\n _cameraManipulator->home(*dummyEvent, *this);\n }\n}\n\nvoid SimpleViewer::addEventHandler(GUIEventHandler* eventHandler)\n{\n _eventHandlers.push_back(eventHandler);\n}\n\nvoid SimpleViewer::setDatabasePager(osgDB::DatabasePager* dp)\n{\n _databasePager = dp;\n \n if (dp && _sceneView.valid())\n {\n \/\/ need to register the DatabasePager with the SceneView's CullVisitor so it can pass on request\n \/\/ for files to be loaded.\n _sceneView->getCullVisitor()->setDatabaseRequestHandler(_databasePager.get());\n }\n}\n\nvoid SimpleViewer::init()\n{\n osg::ref_ptr initEvent = _eventQueue->createEvent();\n initEvent->setEventType(osgGA::GUIEventAdapter::FRAME);\n \n if (_cameraManipulator.valid())\n {\n _cameraManipulator->init(*initEvent, *this);\n }\n}\n\nvoid SimpleViewer::frame()\n{\n if (_firstFrame)\n {\n init();\n _firstFrame = false;\n }\n\n frameAdvance();\n frameEventTraversal();\n frameUpdateTraversal();\n frameCullTraversal();\n frameDrawTraversal();\n}\n\nvoid SimpleViewer::frameAdvance()\n{\n osg::Timer_t currentTick = osg::Timer::instance()->tick();\n _frameStamp->setReferenceTime(osg::Timer::instance()->delta_s(_startTick,currentTick));\n _frameStamp->setFrameNumber(_frameStamp->getFrameNumber()+1);\n\n _sceneView->setFrameStamp(_frameStamp.get());\n}\n\nvoid SimpleViewer::frameEventTraversal()\n{\n _eventQueue->frame( _frameStamp->getReferenceTime() );\n\n osgGA::EventQueue::Events events;\n _eventQueue->takeEvents(events);\n \n if (_eventVisitor.valid())\n {\n _eventVisitor->setTraversalNumber(_frameStamp->getFrameNumber());\n }\n \n for(osgGA::EventQueue::Events::iterator itr = events.begin();\n itr != events.end();\n ++itr)\n {\n osgGA::GUIEventAdapter* event = itr->get();\n \n bool handled = false;\n \n if (_eventVisitor.valid())\n {\n _eventVisitor->reset();\n _eventVisitor->addEvent( event );\n \n getSceneData()->accept(*_eventVisitor);\n \n if (_eventVisitor->getEventHandled()) handled = true;\n }\n \n if (_cameraManipulator.valid())\n {\n _cameraManipulator->handle( *event, *this );\n }\n \n for(EventHandlers::iterator hitr = _eventHandlers.begin();\n hitr != _eventHandlers.end() && !handled;\n ++hitr)\n {\n handled = (*hitr)->handle( *event, *this, 0, 0);\n }\n }\n}\n\nvoid SimpleViewer::frameUpdateTraversal()\n{\n double previousAspectRatio = ( static_cast(_sceneView->getViewport()->width())\/\n static_cast(_sceneView->getViewport()->height()) );\n\n \/\/ update the viewport\n int width = _eventQueue->getCurrentEventState()->getWindowWidth();\n int height = _eventQueue->getCurrentEventState()->getWindowHeight();\n _sceneView->setViewport(0,0,width,height);\n\n double newAspectRatio = ( static_cast(_sceneView->getViewport()->width())\/\n static_cast(_sceneView->getViewport()->height()) );\n \n \n \/\/ if aspect ratio adjusted change the project matrix to suit.\n if (previousAspectRatio != newAspectRatio)\n {\n osg::Matrixd& pm = _sceneView->getProjectionMatrix();\n bool orthographicCamera = (pm(0,3)==0.0) && (pm(0,3)==0.0) && (pm(0,3)==0.0) && (pm(0,3)==1.0); \n if (orthographicCamera)\n {\n double left, right, bottom, top, zNear, zFar;\n _sceneView->getProjectionMatrixAsOrtho(left, right, bottom, top, zNear, zFar);\n\n double mid = (right+left)*0.5;\n double halfWidth = (right-left)*0.5;\n left = mid - halfWidth * (newAspectRatio\/previousAspectRatio);\n right = mid + halfWidth * (newAspectRatio\/previousAspectRatio);\n _sceneView->setProjectionMatrixAsOrtho(left, right, bottom, top, zNear, zFar);\n }\n else\n {\n double left, right, bottom, top, zNear, zFar;\n _sceneView->getProjectionMatrixAsFrustum(left, right, bottom, top, zNear, zFar);\n\n double mid = (right+left)*0.5;\n double halfWidth = (right-left)*0.5;\n left = mid - halfWidth * (newAspectRatio\/previousAspectRatio);\n right = mid + halfWidth * (newAspectRatio\/previousAspectRatio);\n _sceneView->setProjectionMatrixAsFrustum(left, right, bottom, top, zNear, zFar);\n }\n } \n \n if (_cameraManipulator.valid())\n {\n _sceneView->setViewMatrix(_cameraManipulator->getInverseMatrix());\n }\n\n if (_databasePager.valid())\n { \n \/\/ tell the DatabasePager the frame number of that the scene graph is being actively used to render a frame\n _databasePager->signalBeginFrame(_frameStamp.get());\n\n \/\/ syncronize changes required by the DatabasePager thread to the scene graph\n _databasePager->updateSceneGraph(_frameStamp->getReferenceTime());\n }\n \n _sceneView->update();\n}\n\nvoid SimpleViewer::frameCullTraversal()\n{\n _sceneView->cull();\n}\n\nvoid SimpleViewer::frameDrawTraversal()\n{\n _sceneView->draw();\n\n if (_databasePager.valid())\n { \n \/\/ tell the DatabasePager the frame number of that the scene graph is being actively used to render a frame\n _databasePager->signalEndFrame();\n\n \/\/ clean up and compile gl objects with a specified limit \n double availableTime = 0.0025; \/\/ 2.5 ms\n\n \/\/ compile any GL objects that are required.\n _databasePager->compileGLObjects(*(_sceneView->getState()),availableTime);\n\n \/\/ flush deleted GL objects.\n _sceneView->flushDeletedGLObjects(availableTime);\n }\n}\n\nvoid SimpleViewer::cleanup()\n{\n if (_databasePager.valid())\n { \n \/\/ clear the database pager so its starts a fresh on the next update\/cull\/draw traversals \n _databasePager->clear();\n \n \/\/ release the GL objects stored in the scene graph.\n _sceneView->releaseAllGLObjects();\n \n \/\/ do a flush to delete all the OpenGL objects that have been deleted or released from the scene graph.\n _sceneView->flushAllDeletedGLObjects();\n }\n \n _sceneView->releaseAllGLObjects();\n _sceneView->flushAllDeletedGLObjects();\n}\n<|endoftext|>"} {"text":"\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield \n *\n * This library is open source and may be redistributed and\/or modified under \n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or \n * (at your option) any later version. The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the \n * OpenSceneGraph Public License for more details.\n*\/\n#include \n#include \n\nusing namespace osg;\nusing namespace osgUtil;\n\n\/\/ comment if you are are working with vertex programs,\n\/\/ but it does break osgreflect demo and perhaps others, so keep an eye\n\/\/ out artifacts.\n\/\/ #define APPLY_MATICES_BEFORE_STATE\n\nvoid RenderLeaf::render(State& state,RenderLeaf* previous)\n{\n\n if (previous)\n {\n\n#ifdef APPLY_MATICES_BEFORE_STATE\n \/\/ apply matrices if required.\n state.applyProjectionMatrix(_projection.get());\n state.applyModelViewMatrix(_modelview.get());\n#endif \n \/\/ apply state if required.\n RenderGraph* prev_rg = previous->_parent;\n RenderGraph* prev_rg_parent = prev_rg->_parent;\n RenderGraph* rg = _parent;\n if (prev_rg_parent!=rg->_parent)\n {\n RenderGraph::moveRenderGraph(state,prev_rg_parent,rg->_parent);\n\n \/\/ send state changes and matrix changes to OpenGL.\n state.apply(rg->_stateset.get());\n\n }\n else if (rg!=prev_rg)\n {\n\n \/\/ send state changes and matrix changes to OpenGL.\n state.apply(rg->_stateset.get());\n\n }\n \n#ifndef APPLY_MATICES_BEFORE_STATE\n \/\/ apply matrices if required.\n state.applyProjectionMatrix(_projection.get());\n state.applyModelViewMatrix(_modelview.get());\n#endif\n\n \/\/ draw the drawable\n _drawable->draw(state);\n }\n else\n {\n#ifdef APPLY_MATICES_BEFORE_STATE\n \/\/ apply matrices if required.\n state.applyProjectionMatrix(_projection.get());\n state.applyModelViewMatrix(_modelview.get());\n#endif \n\n \/\/ apply state if required.\n RenderGraph::moveRenderGraph(state,NULL,_parent->_parent);\n\n state.apply(_parent->_stateset.get());\n\n#ifndef APPLY_MATICES_BEFORE_STATE\n \/\/ apply matrices if required.\n state.applyProjectionMatrix(_projection.get());\n state.applyModelViewMatrix(_modelview.get());\n#endif\n\n \/\/ draw the drawable\n _drawable->draw(state);\n }\n}\nFixed typo of APPLY_MATICES_BEFORE_STATE.\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield \n *\n * This library is open source and may be redistributed and\/or modified under \n * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or \n * (at your option) any later version. The full license is in LICENSE file\n * included with this distribution, and on the openscenegraph.org website.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the \n * OpenSceneGraph Public License for more details.\n*\/\n#include \n#include \n\nusing namespace osg;\nusing namespace osgUtil;\n\n\/\/ comment if you are are working with vertex programs,\n\/\/ but it does break osgreflect demo and perhaps others, so keep an eye\n\/\/ out artifacts.\n\/\/ #define APPLY_MATRICES_BEFORE_STATE\n\nvoid RenderLeaf::render(State& state,RenderLeaf* previous)\n{\n\n if (previous)\n {\n\n#ifdef APPLY_MATRICES_BEFORE_STATE\n \/\/ apply matrices if required.\n state.applyProjectionMatrix(_projection.get());\n state.applyModelViewMatrix(_modelview.get());\n#endif \n \/\/ apply state if required.\n RenderGraph* prev_rg = previous->_parent;\n RenderGraph* prev_rg_parent = prev_rg->_parent;\n RenderGraph* rg = _parent;\n if (prev_rg_parent!=rg->_parent)\n {\n RenderGraph::moveRenderGraph(state,prev_rg_parent,rg->_parent);\n\n \/\/ send state changes and matrix changes to OpenGL.\n state.apply(rg->_stateset.get());\n\n }\n else if (rg!=prev_rg)\n {\n\n \/\/ send state changes and matrix changes to OpenGL.\n state.apply(rg->_stateset.get());\n\n }\n \n#ifndef APPLY_MATRICES_BEFORE_STATE\n \/\/ apply matrices if required.\n state.applyProjectionMatrix(_projection.get());\n state.applyModelViewMatrix(_modelview.get());\n#endif\n\n \/\/ draw the drawable\n _drawable->draw(state);\n }\n else\n {\n#ifdef APPLY_MATRICES_BEFORE_STATE\n \/\/ apply matrices if required.\n state.applyProjectionMatrix(_projection.get());\n state.applyModelViewMatrix(_modelview.get());\n#endif \n\n \/\/ apply state if required.\n RenderGraph::moveRenderGraph(state,NULL,_parent->_parent);\n\n state.apply(_parent->_stateset.get());\n\n#ifndef APPLY_MATRICES_BEFORE_STATE\n \/\/ apply matrices if required.\n state.applyProjectionMatrix(_projection.get());\n state.applyModelViewMatrix(_modelview.get());\n#endif\n\n \/\/ draw the drawable\n _drawable->draw(state);\n }\n}\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \n\n#ifndef _RTL_UUID_H_\n#include \n#endif\n\n#ifndef _RTL_USTRING_H_\n#include \n#endif\n#ifndef _RTL_USTRING_HXX_\n#include \n#endif\n\n#ifdef UNX\n#include \n#include \n#endif\n\nusing namespace rtl;\n\n\/** print a UNI_CODE String. And also print some comments of the string.\n*\/\ninline void printUString( const ::rtl::OUString & str, const sal_Char * msg = \"\" )\n{\n t_print(\"#%s #printUString_u# \", msg );\n rtl::OString aString;\n aString = ::rtl::OUStringToOString( str, RTL_TEXTENCODING_ASCII_US );\n t_print(\"%s\\n\", (char *)aString.getStr( ) );\n}\n\n\/************************************************************************\n * For diagnostics( from sal\/test\/testuuid.cxx )\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sal.hxx\"\nvoid printUuid( sal_uInt8 *pNode )\n{\n for( sal_Int32 i1 = 0 ; i1 < 4 ; i1++ )\n {\n for( sal_Int32 i2 = 0 ; i2 < 4 ; i2++ )\n {\n printf( \"%02x\" , pNode[i1*4 +i2] );\n }\n if( i1 == 3 )\n break;\n printf( \"-\" );\n }\n\n printf( \"\\n# \" );\n}\n\nnamespace rtl_Uuid\n{\nclass createUuid : public CppUnit::TestFixture\n{\npublic:\n \/\/ initialise your test code values here.\n void setUp()\n {\n }\n\n void tearDown()\n {\n }\n\n#define TEST_UUID 20\n void createUuid_001()\n {\n sal_uInt8 aNode[TEST_UUID][16];\n sal_Int32 i,i2;\n for( i = 0 ; i < TEST_UUID ; i ++ )\n {\n rtl_createUuid( aNode[i], 0, sal_False );\n }\n sal_Bool bRes = sal_True;\n for( i = 0 ; i < TEST_UUID ; i ++ )\n {\n for( i2 = i+1 ; i2 < TEST_UUID ; i2 ++ )\n {\n if ( rtl_compareUuid( aNode[i] , aNode[i2] ) == 0 )\n {\n bRes = sal_False;\n break;\n }\n }\n if ( bRes == sal_False )\n break;\n }\n CPPUNIT_ASSERT_MESSAGE(\"createUuid: every uuid must be different.\", bRes == sal_True );\n }\n \/*\n void createUuid_002()\n {\n sal_uInt8 pNode[16];\n sal_uInt8 aNode[TEST_UUID][16];\n sal_Int32 i,i2;\n for( i = 0 ; i < TEST_UUID ; i ++ )\n {\n rtl_createUuid( aNode[i], pNode, sal_True );\n }\n sal_Bool bRes = sal_True;\n for( i = 0 ; i < TEST_UUID ; i ++ )\n {\n \/\/printUuid( aNode[i] );\n for( i2 = i+1 ; i2 < TEST_UUID ; i2 ++ )\n {\n if ( rtl_compareUuid( aNode[i] , aNode[i2] ) == 0 )\n {\n bRes = sal_False;\n break;\n }\n }\n if ( bRes == sal_False )\n break;\n }\n CPPUNIT_ASSERT_MESSAGE(\"createUuid: every uuid must be different.\", bRes == sal_True );\n }*\/\n\n CPPUNIT_TEST_SUITE(createUuid);\n CPPUNIT_TEST(createUuid_001);\n \/\/CPPUNIT_TEST(createUuid_002);\n CPPUNIT_TEST_SUITE_END();\n}; \/\/ class createUuid\n\nnamespace ThreadHelper\n{\n void thread_sleep(sal_Int32 _nSec)\n {\n#ifdef WNT \/\/Windows\n Sleep(_nSec * 10 );\n#endif\n#if ( defined UNX ) || ( defined OS2 ) \/\/Unix\n sleep( _nSec );\n#endif\n }\n}\n\nclass createNamedUuid : public CppUnit::TestFixture\n{\npublic:\n \/\/ initialise your test code values here.\n void setUp()\n {\n }\n\n void tearDown()\n {\n }\n\n void createNamedUuid_001()\n {\n sal_uInt8 NameSpace_DNS[16] = RTL_UUID_NAMESPACE_DNS;\n sal_uInt8 NameSpace_URL[16] = RTL_UUID_NAMESPACE_URL;\n sal_uInt8 pPriorCalculatedUUID[16] = {\n 0x52,0xc9,0x30,0xa5,\n 0xd1,0x61,0x3b,0x16,\n 0x98,0xc5,0xf8,0xd1,\n 0x10,0x10,0x6d,0x4d };\n\n sal_uInt8 pNamedUUID[16], pNamedUUID2[16];\n\n \/\/ Same name does generate the same uuid\n rtl_String *pName = 0;\n rtl_string_newFromStr( &pName , \"this is a bla.blubs.DNS-Name\" );\n rtl_createNamedUuid( pNamedUUID , NameSpace_DNS , pName );\n rtl_createNamedUuid( pNamedUUID2 , NameSpace_DNS , pName );\n CPPUNIT_ASSERT_MESSAGE( \"Same name should generate the same uuid\", ! memcmp( pNamedUUID , pNamedUUID2 , 16 ) && rtl_compareUuid( pNamedUUID , pNamedUUID2 ) == 0 );\n CPPUNIT_ASSERT_MESSAGE( \"Same name should generate the same uuid\", ! memcmp( pNamedUUID , pPriorCalculatedUUID , 16 ) );\n\n \/\/ Different names does not generate the same uuid\n rtl_string_newFromStr( &pName , \"this is a bla.blubs.DNS-Namf\" );\n rtl_createNamedUuid( pNamedUUID2 , NameSpace_DNS , pName );\n CPPUNIT_ASSERT_MESSAGE(\"Different names does not generate the same uuid.\", memcmp( pNamedUUID , pNamedUUID2 , 16 ) );\n\n \/\/ the same name with different namespace uuid produces different uuids\n rtl_createNamedUuid( pNamedUUID , NameSpace_URL , pName );\n CPPUNIT_ASSERT_MESSAGE( \" same name with different namespace uuid produces different uuids\", memcmp( pNamedUUID , pNamedUUID2 , 16 ) && rtl_compareUuid( pNamedUUID , pNamedUUID2 ) != 0);\n\n \/\/test compareUuid\n if ( rtl_compareUuid( pNamedUUID , pNamedUUID2 ) > 0 )\n { CPPUNIT_ASSERT_MESSAGE( \" compare uuids\", rtl_compareUuid( pNamedUUID2 , pNamedUUID ) < 0);\n }\n else\n CPPUNIT_ASSERT_MESSAGE( \" compare uuids\", rtl_compareUuid( pNamedUUID2 , pNamedUUID ) > 0);\n\n rtl_string_release( pName );\n }\n\n CPPUNIT_TEST_SUITE(createNamedUuid);\n CPPUNIT_TEST(createNamedUuid_001);\n CPPUNIT_TEST_SUITE_END();\n}; \/\/ class createNamedUuid\n\nCPPUNIT_TEST_SUITE_NAMED_REGISTRATION(rtl_Uuid::createUuid, \"rtl_Uuid\");\nCPPUNIT_TEST_SUITE_NAMED_REGISTRATION(rtl_Uuid::createNamedUuid, \"rtl_Uuid\");\n} \/\/ namespace rtl_Uuid\n\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ this macro creates an empty function, which will called by the RegisterAllFunctions()\n\/\/ to let the user the possibility to also register some functions by hand.\nNOADDITIONAL;\n\n\nINTEGRATION: CWS reportdesign01 (1.5.98); FILE MERGED 2007\/10\/04 09:03:58 lla 1.5.98.1: #i67655# only updates on some tests to build warning free \/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: rtl_Uuid.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: ihi $ $Date: 2007-11-20 19:48:05 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sal.hxx\"\n\n#include \n#include \n\n#include \n\n#ifndef _RTL_UUID_H_\n#include \n#endif\n\n#ifndef _RTL_USTRING_H_\n#include \n#endif\n#ifndef _RTL_USTRING_HXX_\n#include \n#endif\n\n#ifdef UNX\n#include \n#include \n#endif\n\nusing namespace rtl;\n\n\/** print a UNI_CODE String. And also print some comments of the string.\n*\/\ninline void printUString( const ::rtl::OUString & str, const sal_Char * msg = \"\" )\n{\n t_print(\"#%s #printUString_u# \", msg );\n rtl::OString aString;\n aString = ::rtl::OUStringToOString( str, RTL_TEXTENCODING_ASCII_US );\n t_print(\"%s\\n\", (char *)aString.getStr( ) );\n}\n\n\/************************************************************************\n * For diagnostics( from sal\/test\/testuuid.cxx )\n ************************************************************************\/\n\nvoid printUuid( sal_uInt8 *pNode )\n{\n for( sal_Int32 i1 = 0 ; i1 < 4 ; i1++ )\n {\n for( sal_Int32 i2 = 0 ; i2 < 4 ; i2++ )\n {\n printf( \"%02x\" , pNode[i1*4 +i2] );\n }\n if( i1 == 3 )\n break;\n printf( \"-\" );\n }\n\n printf( \"\\n# \" );\n}\n\nnamespace rtl_Uuid\n{\nclass createUuid : public CppUnit::TestFixture\n{\npublic:\n \/\/ initialise your test code values here.\n void setUp()\n {\n }\n\n void tearDown()\n {\n }\n\n#define TEST_UUID 20\n void createUuid_001()\n {\n sal_uInt8 aNode[TEST_UUID][16];\n sal_Int32 i,i2;\n for( i = 0 ; i < TEST_UUID ; i ++ )\n {\n rtl_createUuid( aNode[i], 0, sal_False );\n }\n sal_Bool bRes = sal_True;\n for( i = 0 ; i < TEST_UUID ; i ++ )\n {\n for( i2 = i+1 ; i2 < TEST_UUID ; i2 ++ )\n {\n if ( rtl_compareUuid( aNode[i] , aNode[i2] ) == 0 )\n {\n bRes = sal_False;\n break;\n }\n }\n if ( bRes == sal_False )\n break;\n }\n CPPUNIT_ASSERT_MESSAGE(\"createUuid: every uuid must be different.\", bRes == sal_True );\n }\n \/*\n void createUuid_002()\n {\n sal_uInt8 pNode[16];\n sal_uInt8 aNode[TEST_UUID][16];\n sal_Int32 i,i2;\n for( i = 0 ; i < TEST_UUID ; i ++ )\n {\n rtl_createUuid( aNode[i], pNode, sal_True );\n }\n sal_Bool bRes = sal_True;\n for( i = 0 ; i < TEST_UUID ; i ++ )\n {\n \/\/printUuid( aNode[i] );\n for( i2 = i+1 ; i2 < TEST_UUID ; i2 ++ )\n {\n if ( rtl_compareUuid( aNode[i] , aNode[i2] ) == 0 )\n {\n bRes = sal_False;\n break;\n }\n }\n if ( bRes == sal_False )\n break;\n }\n CPPUNIT_ASSERT_MESSAGE(\"createUuid: every uuid must be different.\", bRes == sal_True );\n }*\/\n\n CPPUNIT_TEST_SUITE(createUuid);\n CPPUNIT_TEST(createUuid_001);\n \/\/CPPUNIT_TEST(createUuid_002);\n CPPUNIT_TEST_SUITE_END();\n}; \/\/ class createUuid\n\nnamespace ThreadHelper\n{\n void thread_sleep(sal_Int32 _nSec)\n {\n#ifdef WNT \/\/Windows\n Sleep(_nSec * 10 );\n#endif\n#if ( defined UNX ) || ( defined OS2 ) \/\/Unix\n sleep( _nSec );\n#endif\n }\n}\n\nclass createNamedUuid : public CppUnit::TestFixture\n{\npublic:\n \/\/ initialise your test code values here.\n void setUp()\n {\n }\n\n void tearDown()\n {\n }\n\n void createNamedUuid_001()\n {\n sal_uInt8 NameSpace_DNS[16] = RTL_UUID_NAMESPACE_DNS;\n sal_uInt8 NameSpace_URL[16] = RTL_UUID_NAMESPACE_URL;\n sal_uInt8 pPriorCalculatedUUID[16] = {\n 0x52,0xc9,0x30,0xa5,\n 0xd1,0x61,0x3b,0x16,\n 0x98,0xc5,0xf8,0xd1,\n 0x10,0x10,0x6d,0x4d };\n\n sal_uInt8 pNamedUUID[16], pNamedUUID2[16];\n\n \/\/ Same name does generate the same uuid\n rtl_String *pName = 0;\n rtl_string_newFromStr( &pName , \"this is a bla.blubs.DNS-Name\" );\n rtl_createNamedUuid( pNamedUUID , NameSpace_DNS , pName );\n rtl_createNamedUuid( pNamedUUID2 , NameSpace_DNS , pName );\n CPPUNIT_ASSERT_MESSAGE( \"Same name should generate the same uuid\", ! memcmp( pNamedUUID , pNamedUUID2 , 16 ) && rtl_compareUuid( pNamedUUID , pNamedUUID2 ) == 0 );\n CPPUNIT_ASSERT_MESSAGE( \"Same name should generate the same uuid\", ! memcmp( pNamedUUID , pPriorCalculatedUUID , 16 ) );\n\n \/\/ Different names does not generate the same uuid\n rtl_string_newFromStr( &pName , \"this is a bla.blubs.DNS-Namf\" );\n rtl_createNamedUuid( pNamedUUID2 , NameSpace_DNS , pName );\n CPPUNIT_ASSERT_MESSAGE(\"Different names does not generate the same uuid.\", memcmp( pNamedUUID , pNamedUUID2 , 16 ) );\n\n \/\/ the same name with different namespace uuid produces different uuids\n rtl_createNamedUuid( pNamedUUID , NameSpace_URL , pName );\n CPPUNIT_ASSERT_MESSAGE( \" same name with different namespace uuid produces different uuids\", memcmp( pNamedUUID , pNamedUUID2 , 16 ) && rtl_compareUuid( pNamedUUID , pNamedUUID2 ) != 0);\n\n \/\/test compareUuid\n if ( rtl_compareUuid( pNamedUUID , pNamedUUID2 ) > 0 )\n { CPPUNIT_ASSERT_MESSAGE( \" compare uuids\", rtl_compareUuid( pNamedUUID2 , pNamedUUID ) < 0);\n }\n else\n CPPUNIT_ASSERT_MESSAGE( \" compare uuids\", rtl_compareUuid( pNamedUUID2 , pNamedUUID ) > 0);\n\n rtl_string_release( pName );\n }\n\n CPPUNIT_TEST_SUITE(createNamedUuid);\n CPPUNIT_TEST(createNamedUuid_001);\n CPPUNIT_TEST_SUITE_END();\n}; \/\/ class createNamedUuid\n\nCPPUNIT_TEST_SUITE_NAMED_REGISTRATION(rtl_Uuid::createUuid, \"rtl_Uuid\");\nCPPUNIT_TEST_SUITE_NAMED_REGISTRATION(rtl_Uuid::createNamedUuid, \"rtl_Uuid\");\n} \/\/ namespace rtl_Uuid\n\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ this macro creates an empty function, which will called by the RegisterAllFunctions()\n\/\/ to let the user the possibility to also register some functions by hand.\nNOADDITIONAL;\n\n\n<|endoftext|>"} {"text":"#include \"nodes.hpp\"\n\nnamespace lang {\n \n void printIndent(int level) {\n for (int i = 0; i < level; ++i) print(\" \");\n }\n \n ASTNode::ASTNode() {}\n ASTNode::~ASTNode() {}\n \n void ASTNode::addChild(ASTNode* child) {\n child->setParent(this);\n children.push_back(child);\n }\n \n std::vector& ASTNode::getChildren() {\n return children;\n }\n \n void ASTNode::setParent(ASTNode* parent) {\n this->parent = parent;\n }\n ASTNode* ASTNode::getParent() {\n return parent;\n }\n \n void ASTNode::setLineNumber(int lines) {\n this->lines = lines;\n }\n int ASTNode::getLineNumber() {\n return this->lines;\n }\n \n std::string ASTNode::getNodeType() {\n return \"ASTNode\";\n }\n \n void ASTNode::printTree(int level) {\n printIndent(level);\n print(\"Plain ASTNode\");\n for (auto child : children) {\n child->printTree(level + 1);\n }\n }\n \n SingleChildNode::SingleChildNode() {};\n void SingleChildNode::addChild(ASTNode* child) {\n if (this->getChildren().size() >= 1) throw std::runtime_error(\"Trying to add more than one child to SingleChildNode.\");\n else {\n this->ASTNode::addChild(child);\n }\n }\n \n ASTNode* SingleChildNode::getChild() {\n return children[0];\n }\n \n std::string SingleChildNode::getNodeType() {\n return \"SingleChildNode\";\n }\n \n void SingleChildNode::printTree(int level) {\n printIndent(level);\n auto child = dynamic_cast(this->getChild());\n if (child == nullptr) {\n print(\"SingleChildNode, empty\", \"\\n\");\n return;\n }\n print(\"SingleChildNode with: \", child, \"\\n\");\n child->printTree(level + 1);\n }\n \n DeclarationNode::DeclarationNode(std::string typeName, Token identifier) {\n this->typeName = typeName;\n this->identifier = identifier;\n }\n \n void DeclarationNode::addChild(ASTNode* child) {\n auto node = dynamic_cast(child);\n if (node == 0) throw std::invalid_argument(\"DeclarationNode only accepts an ExpressionNode as its child.\");\n this->SingleChildNode::addChild(node);\n }\n \n std::string DeclarationNode::getNodeType() {\n return \"DeclarationNode\";\n }\n \n void DeclarationNode::printTree(int level) {\n printIndent(level);\n print(\"Declared \", this->typeName, \" as \", this->identifier, \"\\n\");\n if (this->getChildren().size() == 1) dynamic_cast(this->getChild())->printTree(level + 1);\n }\n \n std::vector ExpressionNode::validOperandTypes {\n INTEGER, FLOAT, STRING, BOOLEAN, ARRAY, TYPE, VARIABLE, FUNCTION, UNPROCESSED\n };\n \n ExpressionNode::ExpressionNode(std::vector& tokens) {\n for (uint64 i = 0; i < tokens.size(); ++i) {\n if (EXPRESSION_STEPS) {\n for (auto tok : outStack) print(tok.data, \" \");\n print(\"\\n-------\\n\");\n for (auto tok : opStack) print(tok.data, \" \");\n print(\"\\n=======\\n\");\n }\n if (contains(tokens[i].type, validOperandTypes)) {\n outStack.push_back(tokens[i]);\n } else if (tokens[i].type == OPERATOR) {\n \/* \n * This prevents crash when there's no operators.\n * Or when it found a parenthesis, because they're not really operators.\n *\/\n if (opStack.size() == 0 || opStack.back().data == \"(\") {\n opStack.push_back(tokens[i]);\n continue;\n }\n Operator current = *static_cast(tokens[i].typeData);\n Operator topOfStack = *static_cast(opStack.back().typeData);\n while (opStack.size() != 0) {\n if ((current.getAssociativity() == ASSOCIATE_FROM_LEFT && current.getPrecedence() <= topOfStack.getPrecedence()) ||\n (current.getAssociativity() == ASSOCIATE_FROM_RIGHT && current.getPrecedence() < topOfStack.getPrecedence())) {\n popToOut();\n } else break;\n \/\/ Non-operators (eg parenthesis) will crash on next line, and must break to properly evaluate expression\n if (opStack.back().type != OPERATOR) break;\n \/\/ Get new top of stack\n if (opStack.size() != 0) topOfStack = *static_cast(opStack.back().typeData);\n }\n opStack.push_back(tokens[i]);\n } else if (tokens[i].type == CONSTRUCT) {\n if (tokens[i].data == \";\") break;\n if (tokens[i].data != \"(\" && tokens[i].data != \")\") {\n throw SyntaxError(\"Illegal construct in expression. \\\"\" + tokens[i].data + \"\\\"\", tokens[i].line);\n } else if (tokens[i].data == \"(\") {\n opStack.push_back(tokens[i]);\n } else if (tokens[i].data == \")\") {\n while (opStack.size() != 0 && opStack.back().data != \"(\") popToOut();\n if (opStack.back().data != \"(\") throw SyntaxError(\"Mismatched parenthesis in expression\", outStack.back().line);\n opStack.pop_back(); \/\/ Get rid of \"(\"\n if (opStack.back().type == FUNCTION) popToOut();\n }\n }\n }\n while (opStack.size() > 0) popToOut();\n }\n \n std::vector ExpressionNode::getRPNOutput() {\n return outStack;\n }\n \n void ExpressionNode::buildSubtree(void) {\n std::vector stackCopy(outStack);\n ExpressionChildNode* node;\n if (stackCopy.size() >= 1) {\n auto tok = stackCopy.back();\n stackCopy.pop_back();\n node = new ExpressionChildNode(tok, stackCopy);\n } else {\n throw std::runtime_error(\"Empty expression.\\n\");\n }\n\n this->addChild(node);\n }\n \n std::string ExpressionNode::getNodeType() {\n return \"ExpressionNode\";\n }\n \n void ExpressionNode::printTree(int level) {\n auto top = static_cast(this->getChildren()[0]);\n top->printTree(level);\n }\n \n ExpressionChildNode::ExpressionChildNode(Token operand): t(operand) {};\n ExpressionChildNode::ExpressionChildNode(Token op, std::vector& operands): t(op) {\n if (operands.size() == 0) return;\n auto arity = static_cast(op.typeData)->getArity();\n for (int i = 0; i < arity; ++i) {\n auto next = operands[operands.size() - 1];\n if (next.type == OPERATOR) {\n operands.pop_back();\n auto branch = new ExpressionChildNode(next, operands);\n this->addChild(branch);\n } else {\n operands.pop_back();\n auto leaf = new ExpressionChildNode(next);\n this->addChild(leaf);\n }\n }\n };\n \n std::string ExpressionChildNode::getNodeType() {\n return \"ExpressionChildNode\";\n }\n \n void ExpressionChildNode::printTree(int level) {\n printIndent(level);\n print(this->t, \"\\n\");\n for (auto child : this->getChildren()) {\n static_cast(child)->printTree(level + 1);\n }\n }\n \n BlockNode::BlockNode() {}\n \n std::string BlockNode::getNodeType() {\n return \"BlockNode\";\n }\n \n void BlockNode::printTree(int level) {\n printIndent(level);\n print(\"BlockNode\\n\");\n for (auto node : children) {\n node->printTree(level + 1);\n }\n }\n \n ConditionalNode::ConditionalNode(ExpressionNode* condition, BlockNode* trueBlock, BlockNode* falseBlock) {\n this->children.push_back(condition);\n this->children.push_back(trueBlock);\n this->children.push_back(falseBlock);\n condition->setParent(this);\n trueBlock->setParent(this);\n falseBlock->setParent(this);\n }\n \n ExpressionNode* ConditionalNode::getCondition() {return dynamic_cast(children[0]);}\n BlockNode* ConditionalNode::getTrueBlock() {return dynamic_cast(children[1]);}\n BlockNode* ConditionalNode::getFalseBlock() {return dynamic_cast(children[2]);}\n \n void ConditionalNode::addChild(ASTNode* child) {\n children[this->block]->addChild(child);\n }\n \n void ConditionalNode::nextBlock() {\n static bool wasCalled = false;\n if (!wasCalled) {\n wasCalled = true;\n this->block++;\n } else throw SyntaxError(\"Multiple else statements.\\n\", children[2]->getLineNumber());\n }\n \n std::string ConditionalNode::getNodeType() {\n return \"ConditionalNode\";\n }\n \n void ConditionalNode::printTree(int level) {\n printIndent(level);\n print(\"Condition\\n\");\n this->getCondition()->printTree(level + 1);\n }\n \n AST::AbstractSyntaxTree() {}\n \n void AST::addRootChild(ASTNode* node) {\n root.addChild(node);\n }\n \n ChildrenNodes AST::getRootChildren() {\n return root.getChildren();\n }\n \n} \/* namespace lang *\/\nImproved newline detection in ExprNode#include \"nodes.hpp\"\n\nnamespace lang {\n \n void printIndent(int level) {\n for (int i = 0; i < level; ++i) print(\" \");\n }\n \n ASTNode::ASTNode() {}\n ASTNode::~ASTNode() {}\n \n void ASTNode::addChild(ASTNode* child) {\n child->setParent(this);\n children.push_back(child);\n }\n \n std::vector& ASTNode::getChildren() {\n return children;\n }\n \n void ASTNode::setParent(ASTNode* parent) {\n this->parent = parent;\n }\n ASTNode* ASTNode::getParent() {\n return parent;\n }\n \n void ASTNode::setLineNumber(int lines) {\n this->lines = lines;\n }\n int ASTNode::getLineNumber() {\n return this->lines;\n }\n \n std::string ASTNode::getNodeType() {\n return \"ASTNode\";\n }\n \n void ASTNode::printTree(int level) {\n printIndent(level);\n print(\"Plain ASTNode\");\n for (auto child : children) {\n child->printTree(level + 1);\n }\n }\n \n SingleChildNode::SingleChildNode() {};\n void SingleChildNode::addChild(ASTNode* child) {\n if (this->getChildren().size() >= 1) throw std::runtime_error(\"Trying to add more than one child to SingleChildNode.\");\n else {\n this->ASTNode::addChild(child);\n }\n }\n \n ASTNode* SingleChildNode::getChild() {\n return children[0];\n }\n \n std::string SingleChildNode::getNodeType() {\n return \"SingleChildNode\";\n }\n \n void SingleChildNode::printTree(int level) {\n printIndent(level);\n auto child = dynamic_cast(this->getChild());\n if (child == nullptr) {\n print(\"SingleChildNode, empty\", \"\\n\");\n return;\n }\n print(\"SingleChildNode with: \", child, \"\\n\");\n child->printTree(level + 1);\n }\n \n DeclarationNode::DeclarationNode(std::string typeName, Token identifier) {\n this->typeName = typeName;\n this->identifier = identifier;\n }\n \n void DeclarationNode::addChild(ASTNode* child) {\n auto node = dynamic_cast(child);\n if (node == 0) throw std::invalid_argument(\"DeclarationNode only accepts an ExpressionNode as its child.\");\n this->SingleChildNode::addChild(node);\n }\n \n std::string DeclarationNode::getNodeType() {\n return \"DeclarationNode\";\n }\n \n void DeclarationNode::printTree(int level) {\n printIndent(level);\n print(\"Declared \", this->typeName, \" as \", this->identifier, \"\\n\");\n if (this->getChildren().size() == 1) dynamic_cast(this->getChild())->printTree(level + 1);\n }\n \n std::vector ExpressionNode::validOperandTypes {\n INTEGER, FLOAT, STRING, BOOLEAN, ARRAY, TYPE, VARIABLE, FUNCTION, UNPROCESSED\n };\n \n ExpressionNode::ExpressionNode(std::vector& tokens) {\n for (uint64 i = 0; i < tokens.size(); ++i) {\n if (EXPRESSION_STEPS) {\n for (auto tok : outStack) print(tok.data, \" \");\n print(\"\\n-------\\n\");\n for (auto tok : opStack) print(tok.data, \" \");\n print(\"\\n=======\\n\");\n }\n if (contains(tokens[i].type, validOperandTypes)) {\n outStack.push_back(tokens[i]);\n } else if (tokens[i].type == OPERATOR) {\n \/* \n * This prevents crash when there's no operators.\n * Or when it found a parenthesis, because they're not really operators.\n *\/\n if (opStack.size() == 0 || opStack.back().data == \"(\") {\n opStack.push_back(tokens[i]);\n continue;\n }\n Operator current = *static_cast(tokens[i].typeData);\n Operator topOfStack = *static_cast(opStack.back().typeData);\n while (opStack.size() != 0) {\n if ((current.getAssociativity() == ASSOCIATE_FROM_LEFT && current.getPrecedence() <= topOfStack.getPrecedence()) ||\n (current.getAssociativity() == ASSOCIATE_FROM_RIGHT && current.getPrecedence() < topOfStack.getPrecedence())) {\n popToOut();\n } else break;\n \/\/ Non-operators (eg parenthesis) will crash on next line, and must break to properly evaluate expression\n if (opStack.back().type != OPERATOR) break;\n \/\/ Get new top of stack\n if (opStack.size() != 0) topOfStack = *static_cast(opStack.back().typeData);\n }\n opStack.push_back(tokens[i]);\n } else if (tokens[i].type == CONSTRUCT) {\n if (isNewLine(tokens[i])) break;\n if (tokens[i].data != \"(\" && tokens[i].data != \")\") {\n throw SyntaxError(\"Illegal construct in expression. \\\"\" + tokens[i].data + \"\\\"\", tokens[i].line);\n } else if (tokens[i].data == \"(\") {\n opStack.push_back(tokens[i]);\n } else if (tokens[i].data == \")\") {\n while (opStack.size() != 0 && opStack.back().data != \"(\") popToOut();\n if (opStack.back().data != \"(\") throw SyntaxError(\"Mismatched parenthesis in expression\", outStack.back().line);\n opStack.pop_back(); \/\/ Get rid of \"(\"\n if (opStack.back().type == FUNCTION) popToOut();\n }\n }\n }\n while (opStack.size() > 0) popToOut();\n }\n \n std::vector ExpressionNode::getRPNOutput() {\n return outStack;\n }\n \n void ExpressionNode::buildSubtree(void) {\n std::vector stackCopy(outStack);\n ExpressionChildNode* node;\n if (stackCopy.size() >= 1) {\n auto tok = stackCopy.back();\n stackCopy.pop_back();\n node = new ExpressionChildNode(tok, stackCopy);\n } else {\n throw std::runtime_error(\"Empty expression.\\n\");\n }\n\n this->addChild(node);\n }\n \n std::string ExpressionNode::getNodeType() {\n return \"ExpressionNode\";\n }\n \n void ExpressionNode::printTree(int level) {\n auto top = static_cast(this->getChildren()[0]);\n top->printTree(level);\n }\n \n ExpressionChildNode::ExpressionChildNode(Token operand): t(operand) {};\n ExpressionChildNode::ExpressionChildNode(Token op, std::vector& operands): t(op) {\n if (operands.size() == 0) return;\n auto arity = static_cast(op.typeData)->getArity();\n for (int i = 0; i < arity; ++i) {\n auto next = operands[operands.size() - 1];\n if (next.type == OPERATOR) {\n operands.pop_back();\n auto branch = new ExpressionChildNode(next, operands);\n this->addChild(branch);\n } else {\n operands.pop_back();\n auto leaf = new ExpressionChildNode(next);\n this->addChild(leaf);\n }\n }\n };\n \n std::string ExpressionChildNode::getNodeType() {\n return \"ExpressionChildNode\";\n }\n \n void ExpressionChildNode::printTree(int level) {\n printIndent(level);\n print(this->t, \"\\n\");\n for (auto child : this->getChildren()) {\n static_cast(child)->printTree(level + 1);\n }\n }\n \n BlockNode::BlockNode() {}\n \n std::string BlockNode::getNodeType() {\n return \"BlockNode\";\n }\n \n void BlockNode::printTree(int level) {\n printIndent(level);\n print(\"BlockNode\\n\");\n for (auto node : children) {\n node->printTree(level + 1);\n }\n }\n \n ConditionalNode::ConditionalNode(ExpressionNode* condition, BlockNode* trueBlock, BlockNode* falseBlock) {\n this->children.push_back(condition);\n this->children.push_back(trueBlock);\n this->children.push_back(falseBlock);\n condition->setParent(this);\n trueBlock->setParent(this);\n falseBlock->setParent(this);\n }\n \n ExpressionNode* ConditionalNode::getCondition() {return dynamic_cast(children[0]);}\n BlockNode* ConditionalNode::getTrueBlock() {return dynamic_cast(children[1]);}\n BlockNode* ConditionalNode::getFalseBlock() {return dynamic_cast(children[2]);}\n \n void ConditionalNode::addChild(ASTNode* child) {\n children[this->block]->addChild(child);\n }\n \n void ConditionalNode::nextBlock() {\n static bool wasCalled = false;\n if (!wasCalled) {\n wasCalled = true;\n this->block++;\n } else throw SyntaxError(\"Multiple else statements.\\n\", children[2]->getLineNumber());\n }\n \n std::string ConditionalNode::getNodeType() {\n return \"ConditionalNode\";\n }\n \n void ConditionalNode::printTree(int level) {\n printIndent(level);\n print(\"Condition\\n\");\n this->getCondition()->printTree(level + 1);\n }\n \n AST::AbstractSyntaxTree() {}\n \n void AST::addRootChild(ASTNode* node) {\n root.addChild(node);\n }\n \n ChildrenNodes AST::getRootChildren() {\n return root.getChildren();\n }\n \n} \/* namespace lang *\/\n<|endoftext|>"} {"text":"\/\/\n\/\/ libavg - Media Playback Engine. \n\/\/ Copyright (C) 2003-2011 Ulrich von Zadow\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Current versions can be found at www.libavg.de\n\/\/\n\n#include \"GLTexture.h\"\n\n#include \"..\/base\/Exception.h\"\n#include \"..\/base\/StringHelper.h\"\n#include \"..\/base\/MathHelper.h\"\n#include \"..\/base\/ObjectCounter.h\"\n\n#include \"GLContext.h\"\n#include \"TextureMover.h\"\n#ifndef AVG_ENABLE_EGL\n #include \"PBO.h\"\n#endif\n#include \"FBO.h\"\n#include \"Filterfliprgb.h\"\n\n#include \n#include \n\nnamespace avg {\n\nusing namespace std;\n\n\/\/ We assign our own texture ids and never reuse them instead of using glGenTextures.\n\/\/ That works very well, except that other components (e.g. Ogre3d) with shared gl \n\/\/ contexts don't know anything about our ids and thus use the same ones.\n\/\/ Somewhat hackish solution: Assign ids starting with a very high id, so the id ranges\n\/\/ don't overlap.\nunsigned GLTexture::s_LastTexID = 10000000;\n\nGLTexture::GLTexture(const IntPoint& size, PixelFormat pf, bool bMipmap,\n int potBorderColor, unsigned wrapSMode, unsigned wrapTMode, bool bForcePOT)\n : m_Size(size),\n m_pf(pf),\n m_bMipmap(bMipmap),\n m_bDeleteTex(true),\n m_bIsDirty(true)\n{\n m_pGLContext = GLContext::getCurrent();\n ObjectCounter::get()->incRef(&typeid(*this));\n m_bUsePOT = m_pGLContext->usePOTTextures() || bForcePOT;\n if (m_pGLContext->isGLES() && bMipmap) {\n m_bUsePOT = true;\n }\n if (m_bUsePOT) {\n m_GLSize.x = nextpow2(m_Size.x);\n m_GLSize.y = nextpow2(m_Size.y);\n } else {\n m_GLSize = m_Size;\n }\n\n int maxTexSize = m_pGLContext->getMaxTexSize();\n if (m_Size.x > maxTexSize || m_Size.y > maxTexSize) {\n throw Exception(AVG_ERR_VIDEO_GENERAL, \"Texture too large (\" + toString(m_Size)\n + \"). Maximum supported by graphics card is \"\n + toString(maxTexSize));\n }\n if (getGLType(m_pf) == GL_FLOAT && !isFloatFormatSupported()) {\n throw Exception(AVG_ERR_UNSUPPORTED, \n \"Float textures not supported by OpenGL configuration.\");\n }\n\n s_LastTexID++;\n m_TexID = s_LastTexID;\n m_pGLContext->bindTexture(GL_TEXTURE0, m_TexID);\n if (bMipmap) {\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);\n } else {\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n }\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapSMode);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapTMode);\n glTexImage2D(GL_TEXTURE_2D, 0, getGLInternalFormat(), m_GLSize.x, m_GLSize.y, 0,\n getGLFormat(m_pf), getGLType(m_pf), 0);\n GLContext::checkError(\"GLTexture: glTexImage2D()\");\n\n if (m_bUsePOT) {\n \/\/ Make sure the texture is transparent and black before loading stuff \n \/\/ into it to avoid garbage at the borders.\n \/\/ In the case of UV textures, we set the border color to 128...\n int TexMemNeeded = m_GLSize.x*m_GLSize.y*getBytesPerPixel(m_pf);\n char * pPixels = new char[TexMemNeeded];\n memset(pPixels, potBorderColor, TexMemNeeded);\n glTexImage2D(GL_TEXTURE_2D, 0, getGLInternalFormat(), m_GLSize.x, \n m_GLSize.y, 0, getGLFormat(m_pf), getGLType(m_pf), \n pPixels);\n GLContext::checkError(\"PBOTexture::createTexture: glTexImage2D()\");\n delete[] pPixels;\n }\n}\n\nGLTexture::GLTexture(unsigned glTexID, const IntPoint& size, PixelFormat pf, bool bMipmap,\n bool bDeleteTex)\n : m_Size(size),\n m_GLSize(size),\n m_pf(pf),\n m_bMipmap(bMipmap),\n m_bDeleteTex(bDeleteTex),\n m_bUsePOT(false),\n m_TexID(glTexID),\n m_bIsDirty(true)\n{\n m_pGLContext = GLContext::getCurrent();\n ObjectCounter::get()->incRef(&typeid(*this));\n}\n\nGLTexture::~GLTexture()\n{\n if (m_bDeleteTex) {\n glDeleteTextures(1, &m_TexID);\n GLContext::checkError(\"GLTexture: DeleteTextures()\");\n }\n ObjectCounter::get()->decRef(&typeid(*this));\n}\n\nvoid GLTexture::activate(int textureUnit)\n{\n m_pGLContext->bindTexture(textureUnit, m_TexID);\n}\n\nvoid GLTexture::generateMipmaps()\n{\n if (m_bMipmap) {\n activate();\n glproc::GenerateMipmap(GL_TEXTURE_2D);\n GLContext::checkError(\"GLTexture::generateMipmaps()\");\n }\n}\n\nvoid GLTexture::setWrapMode(unsigned wrapSMode, unsigned wrapTMode)\n{\n activate();\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapSMode);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapTMode);\n}\n\nvoid GLTexture::enableStreaming()\n{\n m_pMover = TextureMover::create(m_Size, m_pf, GL_STREAM_DRAW);\n}\n\nBitmapPtr GLTexture::lockStreamingBmp()\n{\n AVG_ASSERT(m_pMover);\n return m_pMover->lock();\n}\n\nvoid GLTexture::unlockStreamingBmp(bool bUpdated)\n{\n AVG_ASSERT(m_pMover);\n m_pMover->unlock();\n if (bUpdated) {\n m_pMover->moveToTexture(*this);\n m_bIsDirty = true;\n }\n}\n\nvoid GLTexture::moveBmpToTexture(BitmapPtr pBmp)\n{\n TextureMoverPtr pMover = TextureMover::create(m_Size, m_pf, GL_DYNAMIC_DRAW);\n pMover->moveBmpToTexture(pBmp, *this);\n m_bIsDirty = true;\n}\n\nBitmapPtr GLTexture::moveTextureToBmp(int mipmapLevel)\n{\n GLContext* pContext = GLContext::getCurrent();\n if (pContext->getMemoryMode() == MM_PBO) {\n#ifdef AVG_ENABLE_EGL\n AVG_ASSERT(false);\n return BitmapPtr();\n#else\n return PBO(m_GLSize, m_pf, GL_DYNAMIC_READ).moveTextureToBmp(*this, mipmapLevel);\n#endif\n } else {\n unsigned fbo = pContext->genFBO();\n glproc::BindFramebuffer(GL_FRAMEBUFFER, fbo);\n glproc::FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, \n GL_TEXTURE_2D, m_TexID, mipmapLevel);\n FBO::checkError(\"moveTextureToBmp\");\n IntPoint size = getMipmapSize(mipmapLevel);\n BitmapPtr pBmp(new Bitmap(size, m_pf));\n int glPixelFormat = getGLReadFormat(m_pf);\n glReadPixels(0, 0, size.x, size.y, glPixelFormat, getGLType(m_pf), \n pBmp->getPixels());\n if (m_pf == R8G8B8A8 || m_pf == R8G8B8 || pContext->isGLES()) {\n FilterFlipRGB(!pContext->isGLES()).applyInPlace(pBmp);\n }\n GLContext::checkError(\"GLTexture::moveTextureToBmp: glReadPixels()\");\n glproc::FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, \n GL_TEXTURE_2D, 0, 0);\n pContext->returnFBOToCache(fbo);\n return pBmp;\n }\n}\n\nconst IntPoint& GLTexture::getSize() const\n{\n return m_Size;\n}\n\nconst IntPoint& GLTexture::getGLSize() const\n{\n return m_GLSize;\n}\n\nPixelFormat GLTexture::getPF() const\n{\n return m_pf;\n}\n\nunsigned GLTexture::getID() const\n{\n return m_TexID;\n}\n\nIntPoint GLTexture::getMipmapSize(int level) const\n{\n IntPoint size = m_Size;\n for (int i=0; i> 1);\n size.y = max(1, size.y >> 1);\n }\n return size;\n}\n\nbool GLTexture::isFloatFormatSupported()\n{\n return queryOGLExtension(\"GL_ARB_texture_float\");\n}\n\nint GLTexture::getGLFormat(PixelFormat pf)\n{\n switch (pf) {\n case I8:\n case I32F:\n return GL_LUMINANCE;\n case A8:\n return GL_ALPHA;\n case R8G8B8A8:\n case R8G8B8X8:\n return GL_RGBA;\n#ifdef AVG_ENABLE_EGL\n case B8G8R8A8:\n case B8G8R8X8:\n return GL_BGRA_EXT;\n#else\n case B8G8R8A8:\n case B8G8R8X8:\n return GL_BGRA;\n case R32G32B32A32F:\n return GL_BGRA;\n#endif\n case B5G6R5:\n return GL_RGB;\n default:\n AVG_ASSERT(false);\n return 0;\n }\n}\n\nint GLTexture::getGLReadFormat(PixelFormat pf)\n{\n int glPixelFormat = getGLFormat(pf);\n#ifdef AVG_ENABLE_EGL \n if (glPixelFormat == GL_BGRA_EXT) {\n glPixelFormat = GL_RGBA;\n }\n#endif\n return glPixelFormat;\n}\n\nint GLTexture::getGLType(PixelFormat pf)\n{\n switch (pf) {\n case I8:\n case A8:\n return GL_UNSIGNED_BYTE;\n case R8G8B8A8:\n case R8G8B8X8:\n case B8G8R8A8:\n case B8G8R8X8:\n#ifdef __APPLE__\n return GL_UNSIGNED_INT_8_8_8_8_REV;\n#else\n return GL_UNSIGNED_BYTE;\n#endif\n case R32G32B32A32F:\n case I32F:\n return GL_FLOAT;\n case B5G6R5:\n return GL_UNSIGNED_SHORT_5_6_5;\n default:\n AVG_ASSERT(false);\n return 0;\n }\n}\n\nint GLTexture::getGLInternalFormat() const\n{\n switch (m_pf) {\n case I8:\n return GL_LUMINANCE;\n case A8:\n return GL_ALPHA;\n case R8G8B8A8:\n case R8G8B8X8:\n return GL_RGBA;\n#ifdef AVG_ENABLE_EGL\n case B8G8R8A8:\n case B8G8R8X8:\n return GL_BGRA_EXT;\n#else\n case B8G8R8A8:\n case B8G8R8X8:\n return GL_RGBA;\n case R32G32B32A32F:\n return GL_RGBA32F_ARB;\n case I32F:\n return GL_LUMINANCE32F_ARB;\n#endif\n case B5G6R5:\n return GL_RGB;\n default:\n AVG_ASSERT(false);\n return 0;\n }\n}\n\nvoid GLTexture::setDirty()\n{\n m_bIsDirty = true;\n}\n\nbool GLTexture::isDirty() const\n{\n return m_bIsDirty;\n}\n\nvoid GLTexture::resetDirty()\n{\n m_bIsDirty = false;\n}\n\n\n}\negl branch: Fixed nvidia glx tests.\/\/\n\/\/ libavg - Media Playback Engine. \n\/\/ Copyright (C) 2003-2011 Ulrich von Zadow\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Current versions can be found at www.libavg.de\n\/\/\n\n#include \"GLTexture.h\"\n\n#include \"..\/base\/Exception.h\"\n#include \"..\/base\/StringHelper.h\"\n#include \"..\/base\/MathHelper.h\"\n#include \"..\/base\/ObjectCounter.h\"\n\n#include \"GLContext.h\"\n#include \"TextureMover.h\"\n#ifndef AVG_ENABLE_EGL\n #include \"PBO.h\"\n#endif\n#include \"FBO.h\"\n#include \"Filterfliprgb.h\"\n\n#include \n#include \n\nnamespace avg {\n\nusing namespace std;\n\n\/\/ We assign our own texture ids and never reuse them instead of using glGenTextures.\n\/\/ That works very well, except that other components (e.g. Ogre3d) with shared gl \n\/\/ contexts don't know anything about our ids and thus use the same ones.\n\/\/ Somewhat hackish solution: Assign ids starting with a very high id, so the id ranges\n\/\/ don't overlap.\nunsigned GLTexture::s_LastTexID = 10000000;\n\nGLTexture::GLTexture(const IntPoint& size, PixelFormat pf, bool bMipmap,\n int potBorderColor, unsigned wrapSMode, unsigned wrapTMode, bool bForcePOT)\n : m_Size(size),\n m_pf(pf),\n m_bMipmap(bMipmap),\n m_bDeleteTex(true),\n m_bIsDirty(true)\n{\n m_pGLContext = GLContext::getCurrent();\n ObjectCounter::get()->incRef(&typeid(*this));\n m_bUsePOT = m_pGLContext->usePOTTextures() || bForcePOT;\n if (m_pGLContext->isGLES() && bMipmap) {\n m_bUsePOT = true;\n }\n if (m_bUsePOT) {\n m_GLSize.x = nextpow2(m_Size.x);\n m_GLSize.y = nextpow2(m_Size.y);\n } else {\n m_GLSize = m_Size;\n }\n\n int maxTexSize = m_pGLContext->getMaxTexSize();\n if (m_Size.x > maxTexSize || m_Size.y > maxTexSize) {\n throw Exception(AVG_ERR_VIDEO_GENERAL, \"Texture too large (\" + toString(m_Size)\n + \"). Maximum supported by graphics card is \"\n + toString(maxTexSize));\n }\n if (getGLType(m_pf) == GL_FLOAT && !isFloatFormatSupported()) {\n throw Exception(AVG_ERR_UNSUPPORTED, \n \"Float textures not supported by OpenGL configuration.\");\n }\n\n s_LastTexID++;\n m_TexID = s_LastTexID;\n m_pGLContext->bindTexture(GL_TEXTURE0, m_TexID);\n if (bMipmap) {\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);\n } else {\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n }\n glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapSMode);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapTMode);\n glTexImage2D(GL_TEXTURE_2D, 0, getGLInternalFormat(), m_GLSize.x, m_GLSize.y, 0,\n getGLFormat(m_pf), getGLType(m_pf), 0);\n GLContext::checkError(\"GLTexture: glTexImage2D()\");\n\n if (m_bUsePOT) {\n \/\/ Make sure the texture is transparent and black before loading stuff \n \/\/ into it to avoid garbage at the borders.\n \/\/ In the case of UV textures, we set the border color to 128...\n int TexMemNeeded = m_GLSize.x*m_GLSize.y*getBytesPerPixel(m_pf);\n char * pPixels = new char[TexMemNeeded];\n memset(pPixels, potBorderColor, TexMemNeeded);\n glTexImage2D(GL_TEXTURE_2D, 0, getGLInternalFormat(), m_GLSize.x, \n m_GLSize.y, 0, getGLFormat(m_pf), getGLType(m_pf), \n pPixels);\n GLContext::checkError(\"PBOTexture::createTexture: glTexImage2D()\");\n delete[] pPixels;\n }\n}\n\nGLTexture::GLTexture(unsigned glTexID, const IntPoint& size, PixelFormat pf, bool bMipmap,\n bool bDeleteTex)\n : m_Size(size),\n m_GLSize(size),\n m_pf(pf),\n m_bMipmap(bMipmap),\n m_bDeleteTex(bDeleteTex),\n m_bUsePOT(false),\n m_TexID(glTexID),\n m_bIsDirty(true)\n{\n m_pGLContext = GLContext::getCurrent();\n ObjectCounter::get()->incRef(&typeid(*this));\n}\n\nGLTexture::~GLTexture()\n{\n if (m_bDeleteTex) {\n glDeleteTextures(1, &m_TexID);\n GLContext::checkError(\"GLTexture: DeleteTextures()\");\n }\n ObjectCounter::get()->decRef(&typeid(*this));\n}\n\nvoid GLTexture::activate(int textureUnit)\n{\n m_pGLContext->bindTexture(textureUnit, m_TexID);\n}\n\nvoid GLTexture::generateMipmaps()\n{\n if (m_bMipmap) {\n activate();\n glproc::GenerateMipmap(GL_TEXTURE_2D);\n GLContext::checkError(\"GLTexture::generateMipmaps()\");\n }\n}\n\nvoid GLTexture::setWrapMode(unsigned wrapSMode, unsigned wrapTMode)\n{\n activate();\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapSMode);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapTMode);\n}\n\nvoid GLTexture::enableStreaming()\n{\n m_pMover = TextureMover::create(m_Size, m_pf, GL_STREAM_DRAW);\n}\n\nBitmapPtr GLTexture::lockStreamingBmp()\n{\n AVG_ASSERT(m_pMover);\n return m_pMover->lock();\n}\n\nvoid GLTexture::unlockStreamingBmp(bool bUpdated)\n{\n AVG_ASSERT(m_pMover);\n m_pMover->unlock();\n if (bUpdated) {\n m_pMover->moveToTexture(*this);\n m_bIsDirty = true;\n }\n}\n\nvoid GLTexture::moveBmpToTexture(BitmapPtr pBmp)\n{\n TextureMoverPtr pMover = TextureMover::create(m_Size, m_pf, GL_DYNAMIC_DRAW);\n pMover->moveBmpToTexture(pBmp, *this);\n m_bIsDirty = true;\n}\n\nBitmapPtr GLTexture::moveTextureToBmp(int mipmapLevel)\n{\n GLContext* pContext = GLContext::getCurrent();\n if (pContext->getMemoryMode() == MM_PBO) {\n#ifdef AVG_ENABLE_EGL\n AVG_ASSERT(false);\n return BitmapPtr();\n#else\n return PBO(m_GLSize, m_pf, GL_DYNAMIC_READ).moveTextureToBmp(*this, mipmapLevel);\n#endif\n } else {\n unsigned fbo = pContext->genFBO();\n glproc::BindFramebuffer(GL_FRAMEBUFFER, fbo);\n glproc::FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, \n GL_TEXTURE_2D, m_TexID, mipmapLevel);\n FBO::checkError(\"moveTextureToBmp\");\n IntPoint size = getMipmapSize(mipmapLevel);\n BitmapPtr pBmp(new Bitmap(size, m_pf));\n int glPixelFormat = getGLReadFormat(m_pf);\n glReadPixels(0, 0, size.x, size.y, glPixelFormat, getGLType(m_pf), \n pBmp->getPixels());\n if (m_pf == R8G8B8A8 || m_pf == R8G8B8 || pContext->isGLES()) {\n FilterFlipRGB(!pContext->isGLES()).applyInPlace(pBmp);\n }\n GLContext::checkError(\"GLTexture::moveTextureToBmp: glReadPixels()\");\n glproc::FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, \n GL_TEXTURE_2D, 0, 0);\n pContext->returnFBOToCache(fbo);\n return pBmp;\n }\n}\n\nconst IntPoint& GLTexture::getSize() const\n{\n return m_Size;\n}\n\nconst IntPoint& GLTexture::getGLSize() const\n{\n return m_GLSize;\n}\n\nPixelFormat GLTexture::getPF() const\n{\n return m_pf;\n}\n\nunsigned GLTexture::getID() const\n{\n return m_TexID;\n}\n\nIntPoint GLTexture::getMipmapSize(int level) const\n{\n IntPoint size = m_Size;\n for (int i=0; i> 1);\n size.y = max(1, size.y >> 1);\n }\n return size;\n}\n\nbool GLTexture::isFloatFormatSupported()\n{\n return queryOGLExtension(\"GL_ARB_texture_float\");\n}\n\nint GLTexture::getGLFormat(PixelFormat pf)\n{\n switch (pf) {\n case I8:\n case I32F:\n return GL_LUMINANCE;\n case A8:\n return GL_ALPHA;\n case R8G8B8A8:\n case R8G8B8X8:\n return GL_RGBA;\n#ifdef AVG_ENABLE_EGL\n case B8G8R8A8:\n case B8G8R8X8:\n return GL_BGRA_EXT;\n#else\n case B8G8R8A8:\n case B8G8R8X8:\n return GL_BGRA;\n case R32G32B32A32F:\n return GL_BGRA;\n#endif\n case B5G6R5:\n return GL_RGB;\n default:\n AVG_ASSERT(false);\n return 0;\n }\n}\n\nint GLTexture::getGLReadFormat(PixelFormat pf)\n{\n int glPixelFormat = getGLFormat(pf);\n if (GLContext::getCurrent()->isGLES()) {\n if (glPixelFormat == GL_BGRA_EXT) {\n glPixelFormat = GL_RGBA;\n }\n }\n return glPixelFormat;\n}\n\nint GLTexture::getGLType(PixelFormat pf)\n{\n switch (pf) {\n case I8:\n case A8:\n return GL_UNSIGNED_BYTE;\n case R8G8B8A8:\n case R8G8B8X8:\n case B8G8R8A8:\n case B8G8R8X8:\n#ifdef __APPLE__\n return GL_UNSIGNED_INT_8_8_8_8_REV;\n#else\n return GL_UNSIGNED_BYTE;\n#endif\n case R32G32B32A32F:\n case I32F:\n return GL_FLOAT;\n case B5G6R5:\n return GL_UNSIGNED_SHORT_5_6_5;\n default:\n AVG_ASSERT(false);\n return 0;\n }\n}\n\nint GLTexture::getGLInternalFormat() const\n{\n switch (m_pf) {\n case I8:\n return GL_LUMINANCE;\n case A8:\n return GL_ALPHA;\n case R8G8B8A8:\n case R8G8B8X8:\n return GL_RGBA;\n#ifdef AVG_ENABLE_EGL\n case B8G8R8A8:\n case B8G8R8X8:\n return GL_BGRA_EXT;\n#else\n case B8G8R8A8:\n case B8G8R8X8:\n return GL_RGBA;\n case R32G32B32A32F:\n return GL_RGBA32F_ARB;\n case I32F:\n return GL_LUMINANCE32F_ARB;\n#endif\n case B5G6R5:\n return GL_RGB;\n default:\n AVG_ASSERT(false);\n return 0;\n }\n}\n\nvoid GLTexture::setDirty()\n{\n m_bIsDirty = true;\n}\n\nbool GLTexture::isDirty() const\n{\n return m_bIsDirty;\n}\n\nvoid GLTexture::resetDirty()\n{\n m_bIsDirty = false;\n}\n\n\n}\n<|endoftext|>"} {"text":"#include \".\/ha_buffer.h\"\n#include \n#include \n#include \".\/shader_program.h\"\n#include \".\/quad.h\"\n\nnamespace Graphics\n{\n\nHABuffer::HABuffer(Eigen::Vector2i size) : size(size)\n{\n offsets = new unsigned int[512];\n}\n\nHABuffer::~HABuffer()\n{\n delete[] offsets;\n}\n\nvoid HABuffer::initialize(Gl *gl)\n{\n this->gl = gl;\n\n quad = std::make_shared();\n quad->skipSettingUniforms = true;\n quad->initialize(gl);\n\n initializeShadersHash();\n initializeBufferHash();\n}\n\nvoid HABuffer::initializeShadersHash()\n{\n printf(\"initShaders %d %d\\n\", size(0), size(1));\n\n renderShader = std::make_shared(\n gl, \":shader\/renderHABuffer.vert\", \":shader\/renderHABuffer.frag\");\n clearShader = std::make_shared(\n gl, \":shader\/clearHABuffer.vert\", \":shader\/clearHABuffer.frag\");\n}\n\nvoid HABuffer::initializeBufferHash()\n{\n habufferScreenSize = std::max(size[0], size[1]);\n uint num_records = habufferScreenSize * habufferScreenSize * 8;\n habufferTableSize =\n std::max(habufferScreenSize,\n static_cast(ceil(sqrt(static_cast(num_records)))));\n habufferNumRecords = habufferTableSize * habufferTableSize;\n habufferCountsSize = habufferScreenSize * habufferScreenSize + 1;\n printf(\"HA-Buffer: Screen size: %d %d\\n\"\n \" # records: %d (%d x %d)\\n\",\n size.x(), size.y(), habufferNumRecords, habufferTableSize,\n habufferTableSize);\n\n \/\/ HA-Buffer records\n if (!RecordsBuffer.isInitialized())\n RecordsBuffer.initialize(gl, habufferNumRecords * sizeof(uint) * 2);\n else\n RecordsBuffer.resize(habufferNumRecords * sizeof(uint) * 2);\n\n if (!CountsBuffer.isInitialized())\n CountsBuffer.initialize(gl, habufferCountsSize * sizeof(uint));\n else\n CountsBuffer.resize(habufferCountsSize * sizeof(uint));\n\n if (!FragmentDataBuffer.isInitialized())\n FragmentDataBuffer.initialize(gl,\n habufferNumRecords * sizeof(FragmentData));\n else\n FragmentDataBuffer.resize(habufferNumRecords * sizeof(FragmentData));\n\n \/\/ clear counts\n CountsBuffer.clear(0);\n\n gl->glMemoryBarrier(GL_ALL_BARRIER_BITS);\n\n printf(\"[HABuffer] Memory usage: %.2fMB\",\n ((habufferNumRecords * sizeof(uint) * 2 +\n habufferNumRecords * sizeof(FragmentData) +\n (habufferScreenSize * habufferScreenSize + 1) * sizeof(uint)) \/\n 1024) \/\n 1024.0f);\n}\n\nvoid HABuffer::begin(const RenderData &renderData)\n{\n glAssert(gl->glDisable(GL_CULL_FACE));\n glAssert(gl->glDisable(GL_DEPTH_TEST));\n}\n\nbool HABuffer::end()\n{\n#if 1\n glAssert(gl->glMemoryBarrier(GL_ALL_BARRIER_BITS));\n#endif\n glAssert(gl->glMemoryBarrier(GL_BUFFER_UPDATE_BARRIER_BIT));\n\n uint numInserted = 1;\n CountsBuffer.getData(&numInserted, sizeof(uint),\n CountsBuffer.getSize() - sizeof(uint));\n\n bool overflow = false;\n if (numInserted >= habufferNumRecords)\n {\n overflow = true;\n printf(\"Frame was interrupted: %u\\n\", numInserted);\n }\n else if (numInserted > habufferNumRecords * 0.8)\n {\n printf(\"inserted %u \/ %u\\n\", numInserted, habufferNumRecords);\n }\n\n displayStatistics(\"after render\");\n\n return overflow;\n}\n\nvoid HABuffer::render()\n{\n renderShader->bind();\n Eigen::Matrix4f identity = Eigen::Matrix4f::Identity();\n renderShader->setUniform(\"u_Projection\", identity);\n renderShader->setUniform(\"u_View\", identity);\n renderShader->setUniform(\"u_Model\", identity);\n\n renderShader->setUniform(\"u_ScreenSz\", habufferScreenSize);\n renderShader->setUniform(\"u_HashSz\", habufferTableSize);\n renderShader->setUniformAsVec2Array(\"u_Offsets\", offsets, 512);\n renderShader->setUniform(\"u_Records\", RecordsBuffer);\n renderShader->setUniform(\"u_Counts\", CountsBuffer);\n renderShader->setUniform(\"u_FragmentData\", FragmentDataBuffer);\n\n \/\/ Ensure that all global memory write are done before resolving\n glAssert(gl->glMemoryBarrier(GL_SHADER_GLOBAL_ACCESS_BARRIER_BIT_NV));\n\n glAssert(gl->glDepthMask(GL_FALSE));\n glAssert(gl->glDisable(GL_DEPTH_TEST));\n\n quad->setShaderProgram(renderShader);\n quad->render(gl, RenderData());\n\n glAssert(gl->glDepthMask(GL_TRUE));\n glAssert(gl->glEnable(GL_DEPTH_TEST));\n\n \/\/ TODO(SIRK): print timing\n \/*\n float tm_threshold = TIMING_THRESHOLD;\n float cleartime = g_TmClear.waitResult();\n float buildtime = g_TmBuild.waitResult();\n float rendertime = g_TmRender.waitResult();\n if (cleartime > tm_threshold ||\n buildtime > tm_threshold ||\n rendertime > tm_threshold)\n {\n printf(\"Clear time %lf ms\\n\", cleartime);\n printf(\"Build time %lf ms\\n\", buildtime);\n printf(\"Render time %lf ms\\n\", rendertime);\n }\n *\/\n}\n\nvoid HABuffer::clear()\n{\n for (int i = 0; i < 512; i++)\n {\n offsets[i] = rand() ^ (rand() << 8) ^ (rand() << 16);\n offsets[i] = offsets[i] % habufferTableSize;\n }\n\n clearShader->bind();\n clearShader->setUniform(\"u_NumRecords\", habufferNumRecords);\n clearShader->setUniform(\"u_ScreenSz\", habufferScreenSize);\n clearShader->setUniform(\"u_Records\", RecordsBuffer);\n clearShader->setUniform(\"u_Counts\", CountsBuffer);\n\n \/\/ Render the full screen quad\n\n quad->setShaderProgram(clearShader);\n quad->render(gl, RenderData());\n\n \/\/ Ensure that all global memory write are done before starting to render\n glAssert(gl->glMemoryBarrier(GL_SHADER_GLOBAL_ACCESS_BARRIER_BIT_NV));\n}\n\nvoid HABuffer::setBuildHABufferUniforms(std::shared_ptr shader)\n{\n shader->setUniform(\"u_NumRecords\", habufferNumRecords);\n shader->setUniform(\"u_ScreenSz\", habufferScreenSize);\n shader->setUniform(\"u_HashSz\", habufferTableSize);\n shader->setUniformAsVec2Array(\"u_Offsets\", offsets, 512);\n\n shader->setUniform(\"u_ZNear\", habufferZNear);\n shader->setUniform(\"u_ZFar\", habufferZFar);\n shader->setUniform(\"Opacity\", habufferOpacity);\n shader->setUniform(\"u_Records\", RecordsBuffer);\n shader->setUniform(\"u_Counts\", CountsBuffer);\n shader->setUniform(\"u_FragmentData\", FragmentDataBuffer);\n}\n\nvoid HABuffer::displayStatistics(const char *label)\n{\n uint *lcounts = new uint[habufferCountsSize];\n\n CountsBuffer.getData(lcounts, CountsBuffer.getSize());\n\n int avgdepth = 0;\n int num = 0;\n for (uint c = 0; c < habufferCountsSize - 1; c++)\n {\n if (lcounts[c] > 0)\n {\n num++;\n avgdepth += lcounts[c];\n }\n }\n if (num == 0)\n num = 1;\n\n double rec_percentage = lcounts[habufferCountsSize - 1] \/\n static_cast(habufferNumRecords) * 100.0;\n\n if (rec_percentage > 80.0)\n {\n std::cerr << label << \" habufferCountsSize:\" << habufferCountsSize\n << \"(num)\n << \" max: \" << lcounts[habufferCountsSize - 1] << \"\/\"\n << habufferNumRecords << \"(\" << rec_percentage << \"% \" << '>'\n << std::endl;\n }\n\n delete[] lcounts;\n}\n\n} \/\/ namespace Graphics\nFix argument to setUniformAsVec2Array because it is the element count, not the size.#include \".\/ha_buffer.h\"\n#include \n#include \n#include \".\/shader_program.h\"\n#include \".\/quad.h\"\n\nnamespace Graphics\n{\n\nHABuffer::HABuffer(Eigen::Vector2i size) : size(size)\n{\n offsets = new unsigned int[512];\n}\n\nHABuffer::~HABuffer()\n{\n delete[] offsets;\n}\n\nvoid HABuffer::initialize(Gl *gl)\n{\n this->gl = gl;\n\n quad = std::make_shared();\n quad->skipSettingUniforms = true;\n quad->initialize(gl);\n\n initializeShadersHash();\n initializeBufferHash();\n}\n\nvoid HABuffer::initializeShadersHash()\n{\n printf(\"initShaders %d %d\\n\", size(0), size(1));\n\n renderShader = std::make_shared(\n gl, \":shader\/renderHABuffer.vert\", \":shader\/renderHABuffer.frag\");\n clearShader = std::make_shared(\n gl, \":shader\/clearHABuffer.vert\", \":shader\/clearHABuffer.frag\");\n}\n\nvoid HABuffer::initializeBufferHash()\n{\n habufferScreenSize = std::max(size[0], size[1]);\n uint num_records = habufferScreenSize * habufferScreenSize * 8;\n habufferTableSize =\n std::max(habufferScreenSize,\n static_cast(ceil(sqrt(static_cast(num_records)))));\n habufferNumRecords = habufferTableSize * habufferTableSize;\n habufferCountsSize = habufferScreenSize * habufferScreenSize + 1;\n printf(\"HA-Buffer: Screen size: %d %d\\n\"\n \" # records: %d (%d x %d)\\n\",\n size.x(), size.y(), habufferNumRecords, habufferTableSize,\n habufferTableSize);\n\n \/\/ HA-Buffer records\n if (!RecordsBuffer.isInitialized())\n RecordsBuffer.initialize(gl, habufferNumRecords * sizeof(uint) * 2);\n else\n RecordsBuffer.resize(habufferNumRecords * sizeof(uint) * 2);\n\n if (!CountsBuffer.isInitialized())\n CountsBuffer.initialize(gl, habufferCountsSize * sizeof(uint));\n else\n CountsBuffer.resize(habufferCountsSize * sizeof(uint));\n\n if (!FragmentDataBuffer.isInitialized())\n FragmentDataBuffer.initialize(gl,\n habufferNumRecords * sizeof(FragmentData));\n else\n FragmentDataBuffer.resize(habufferNumRecords * sizeof(FragmentData));\n\n \/\/ clear counts\n CountsBuffer.clear(0);\n\n gl->glMemoryBarrier(GL_ALL_BARRIER_BITS);\n\n printf(\"[HABuffer] Memory usage: %.2fMB\",\n ((habufferNumRecords * sizeof(uint) * 2 +\n habufferNumRecords * sizeof(FragmentData) +\n (habufferScreenSize * habufferScreenSize + 1) * sizeof(uint)) \/\n 1024) \/\n 1024.0f);\n}\n\nvoid HABuffer::begin(const RenderData &renderData)\n{\n glAssert(gl->glDisable(GL_CULL_FACE));\n glAssert(gl->glDisable(GL_DEPTH_TEST));\n}\n\nbool HABuffer::end()\n{\n#if 1\n glAssert(gl->glMemoryBarrier(GL_ALL_BARRIER_BITS));\n#endif\n glAssert(gl->glMemoryBarrier(GL_BUFFER_UPDATE_BARRIER_BIT));\n\n uint numInserted = 1;\n CountsBuffer.getData(&numInserted, sizeof(uint),\n CountsBuffer.getSize() - sizeof(uint));\n\n bool overflow = false;\n if (numInserted >= habufferNumRecords)\n {\n overflow = true;\n printf(\"Frame was interrupted: %u\\n\", numInserted);\n }\n else if (numInserted > habufferNumRecords * 0.8)\n {\n printf(\"inserted %u \/ %u\\n\", numInserted, habufferNumRecords);\n }\n\n displayStatistics(\"after render\");\n\n return overflow;\n}\n\nvoid HABuffer::render()\n{\n renderShader->bind();\n Eigen::Matrix4f identity = Eigen::Matrix4f::Identity();\n renderShader->setUniform(\"u_Projection\", identity);\n renderShader->setUniform(\"u_View\", identity);\n renderShader->setUniform(\"u_Model\", identity);\n\n renderShader->setUniform(\"u_ScreenSz\", habufferScreenSize);\n renderShader->setUniform(\"u_HashSz\", habufferTableSize);\n renderShader->setUniformAsVec2Array(\"u_Offsets\", offsets, 256);\n renderShader->setUniform(\"u_Records\", RecordsBuffer);\n renderShader->setUniform(\"u_Counts\", CountsBuffer);\n renderShader->setUniform(\"u_FragmentData\", FragmentDataBuffer);\n\n \/\/ Ensure that all global memory write are done before resolving\n glAssert(gl->glMemoryBarrier(GL_SHADER_GLOBAL_ACCESS_BARRIER_BIT_NV));\n\n glAssert(gl->glDepthMask(GL_FALSE));\n glAssert(gl->glDisable(GL_DEPTH_TEST));\n\n quad->setShaderProgram(renderShader);\n quad->render(gl, RenderData());\n\n glAssert(gl->glDepthMask(GL_TRUE));\n glAssert(gl->glEnable(GL_DEPTH_TEST));\n\n \/\/ TODO(SIRK): print timing\n \/*\n float tm_threshold = TIMING_THRESHOLD;\n float cleartime = g_TmClear.waitResult();\n float buildtime = g_TmBuild.waitResult();\n float rendertime = g_TmRender.waitResult();\n if (cleartime > tm_threshold ||\n buildtime > tm_threshold ||\n rendertime > tm_threshold)\n {\n printf(\"Clear time %lf ms\\n\", cleartime);\n printf(\"Build time %lf ms\\n\", buildtime);\n printf(\"Render time %lf ms\\n\", rendertime);\n }\n *\/\n}\n\nvoid HABuffer::clear()\n{\n for (int i = 0; i < 512; i++)\n {\n offsets[i] = rand() ^ (rand() << 8) ^ (rand() << 16);\n offsets[i] = offsets[i] % habufferTableSize;\n }\n\n clearShader->bind();\n clearShader->setUniform(\"u_NumRecords\", habufferNumRecords);\n clearShader->setUniform(\"u_ScreenSz\", habufferScreenSize);\n clearShader->setUniform(\"u_Records\", RecordsBuffer);\n clearShader->setUniform(\"u_Counts\", CountsBuffer);\n\n \/\/ Render the full screen quad\n\n quad->setShaderProgram(clearShader);\n quad->render(gl, RenderData());\n\n \/\/ Ensure that all global memory write are done before starting to render\n glAssert(gl->glMemoryBarrier(GL_SHADER_GLOBAL_ACCESS_BARRIER_BIT_NV));\n}\n\nvoid HABuffer::setBuildHABufferUniforms(std::shared_ptr shader)\n{\n shader->setUniform(\"u_NumRecords\", habufferNumRecords);\n shader->setUniform(\"u_ScreenSz\", habufferScreenSize);\n shader->setUniform(\"u_HashSz\", habufferTableSize);\n shader->setUniformAsVec2Array(\"u_Offsets\", offsets, 256);\n\n shader->setUniform(\"u_ZNear\", habufferZNear);\n shader->setUniform(\"u_ZFar\", habufferZFar);\n shader->setUniform(\"Opacity\", habufferOpacity);\n shader->setUniform(\"u_Records\", RecordsBuffer);\n shader->setUniform(\"u_Counts\", CountsBuffer);\n shader->setUniform(\"u_FragmentData\", FragmentDataBuffer);\n}\n\nvoid HABuffer::displayStatistics(const char *label)\n{\n uint *lcounts = new uint[habufferCountsSize];\n\n CountsBuffer.getData(lcounts, CountsBuffer.getSize());\n\n int avgdepth = 0;\n int num = 0;\n for (uint c = 0; c < habufferCountsSize - 1; c++)\n {\n if (lcounts[c] > 0)\n {\n num++;\n avgdepth += lcounts[c];\n }\n }\n if (num == 0)\n num = 1;\n\n double rec_percentage = lcounts[habufferCountsSize - 1] \/\n static_cast(habufferNumRecords) * 100.0;\n\n if (rec_percentage > 80.0)\n {\n std::cerr << label << \" habufferCountsSize:\" << habufferCountsSize\n << \"(num)\n << \" max: \" << lcounts[habufferCountsSize - 1] << \"\/\"\n << habufferNumRecords << \"(\" << rec_percentage << \"% \" << '>'\n << std::endl;\n }\n\n delete[] lcounts;\n}\n\n} \/\/ namespace Graphics\n<|endoftext|>"} {"text":"\/** @file gsDofMapper.h\n\n @brief Provides the gsDofMapper class for re-indexing DoFs.\n\n This file is part of the G+Smo library.\n\n This Source Code Form is subject to the terms of the Mozilla Public\n License, v. 2.0. If a copy of the MPL was not distributed with this\n file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n Author(s): C. Hofreither, A. Mantzaflaris\n*\/\n\n#include \n\n\nnamespace gismo \n{\n\ngsDofMapper::gsDofMapper() : \nm_shift(0), m_numFreeDofs(0), m_curElimId(-1), m_curCouplingId(1)\n{ \n m_offset.resize(1,0);\n}\n\n\nvoid gsDofMapper::localToGlobal(const gsMatrix& locals,\n index_t patchIndex,\n gsMatrix& globals) const\n{\n GISMO_ASSERT( locals.cols() == 1, \"localToGlobal: Expecting one column of locals\");\n const index_t numActive = locals.rows();\n \n globals.resize(numActive,1);\n \n for (index_t i = 0; i < numActive; ++i)\n globals(i,0) = MAPPER_PATCH_DOF(locals(i,0), patchIndex)+m_shift;\n}\n\n\/\/ This function can not have enough information to do its job if dim>2\n\/\/ GISMO_DEPRECATED\nvoid gsDofMapper::matchInterface( index_t k1, index_t k2,\n const gsMatrix & b1,\n const gsMatrix & b2,\n const gsVector &orient )\n{\n \/\/ Boundaries must be conforming (matching)\n const index_t sz = b1.size();\n if ( sz != b2.size() )\n {\n gsWarn<<\"gsDofMapper: Problem: non-conforming interface \"<<\n \"(\" <(\"<matchDof( k1, b1(k,0), k2, b2(k,0) );\n }\n else\n {\n for ( index_t k=0; kmatchDof( k1, b1(k,0), k2, b2(sz-k-1,0) );\n }\n }\n else\n for ( index_t k=0; kmatchDof( k1, b1(k,0), k2, b2(k,0) );\n}\n\nvoid gsDofMapper::colapseDofs(index_t k, const gsMatrix & b )\n{\n const index_t last = b.size()-1;\n for ( index_t k=0; kmatchDof( k, b(k,0), k, b(k+1,0) );\n }\n}\n\n\n\n\n\nvoid gsDofMapper::matchDof( index_t u, index_t i, index_t v, index_t j )\n{\n index_t d1 = MAPPER_PATCH_DOF(i,u);\n index_t d2 = MAPPER_PATCH_DOF(j,v);\n\n \/\/ make sure that d1 <= d2, simplifies implementation\n if (d1 > d2)\n {\n std::swap(d1, d2);\n std::swap(u, v);\n std::swap(i, j);\n }\n\n if (d1 < 0) \/\/ first dof is eliminated\n {\n if (d2 < 0) mergeDofsGlobally( d1, d2 ); \/\/ both are eliminated, merge their indices\n else if (d2 == 0) MAPPER_PATCH_DOF(j,v) = d1; \/\/ second is free, eliminate it along with first\n else \/* d2 > 0*\/ replaceDofGlobally( d2, d1 ); \/\/ second is coupling, eliminate all instances of it\n }\n else if (d1 == 0) \/\/ first dof is a free dof\n {\n if (d2 == 0) MAPPER_PATCH_DOF(i,u) = MAPPER_PATCH_DOF(j,v) = m_curCouplingId++; \/\/ both are free, assign them a new coupling id\n else if (d2 > 0) MAPPER_PATCH_DOF(i,u) = d2; \/\/ second is coupling, add first to the same coupling group\n else GISMO_ERROR(\"Something went terribly wrong\");\n }\n else \/* d1 > 0 *\/ \/\/ first dof is a coupling dof\n {\n GISMO_ASSERT(d2 > 0, \"Something went terribly wrong\");\n mergeDofsGlobally( d1, d2 ); \/\/ both are coupling dofs, merge them\n }\n\n \/\/ if we merged two different non-eliminated dofs, we lost one free dof\n if ( (d1 != d2 && (d1 >= 0 || d2 >= 0) ) || (d1 == 0 && d2 == 0) )\n --m_numFreeDofs;\n}\n\n\nvoid gsDofMapper::markBoundary( index_t k, const gsMatrix & boundaryDofs )\n{\n for (index_t i = 0; i < boundaryDofs.rows(); ++i)\n {\n eliminateDof( boundaryDofs(i,0), k );\n }\n\n \/\/ TO DO: save inverse, eg boundaryDofs(i,0)\n}\n\nvoid gsDofMapper::eliminateDof( index_t i, index_t k )\n{\n const index_t old = MAPPER_PATCH_DOF(i,k);\n if (old == 0) \/\/ regular free dof\n {\n --m_numFreeDofs;\n MAPPER_PATCH_DOF(i,k) = m_curElimId--;\n }\n else if (old > 0) \/\/ coupling dof\n {\n --m_numFreeDofs;\n replaceDofGlobally( old, m_curElimId-- );\n }\n \/\/ else: old < 0: already an eliminated dof, nothing to do\n}\n\nvoid gsDofMapper::finalize()\n{\n GISMO_ASSERT(m_curElimId!=0, \"Error in gsDofMapper::finalize() called twince.\");\n \n index_t curFreeDof = 0; \/\/ free dofs start at 0\n index_t curElimDof = m_numFreeDofs; \/\/ eliminated dofs start after free dofs\n std::vector couplingDofs(m_curCouplingId - 1, -1);\n std::vector elimDofs(-m_curElimId - 1, -1);\n\n \/\/ Coupled dofs start after standard dofs\n index_t curCplDof = m_numFreeDofs - couplingDofs.size();\n\n for (std::size_t k = 0; k < m_dofs.size(); ++k)\n {\n const index_t dofType = m_dofs[k];\n\n if (dofType == 0) \/\/ standard dof\n m_dofs[k] = curFreeDof++;\n else if (dofType < 0) \/\/ eliminated dof\n {\n const index_t id = -dofType - 1;\n if (elimDofs[id] < 0)\n elimDofs[id] = curElimDof++;\n m_dofs[k] = elimDofs[id];\n }\n else \/\/ dofType > 0 \/\/ coupling dof\n {\n const index_t id = dofType - 1;\n if (couplingDofs[id] < 0)\n \/\/couplingDofs[id] = curFreeDof++;\n couplingDofs[id] = curCplDof++;\n m_dofs[k] = couplingDofs[id];\n }\n }\n m_numElimDofs = curElimDof - m_numFreeDofs;\n\n GISMO_ASSERT(curCplDof == m_numFreeDofs,\n \"gsDofMapper::finalize() - computed number of coupling dofs does not match allocated number\");\n GISMO_ASSERT(curFreeDof + static_cast(couplingDofs.size()) == m_numFreeDofs,\n \"gsDofMapper::finalize() - computed number of free dofs does not match allocated number\");\n\n m_curElimId = 0;\/\/ Only equal to zero after finalize is called.\n\n}\n\nvoid gsDofMapper::print() const\n{\n gsInfo<<\"Dofs: \"<< this->size() <<\"\\n\";\n gsInfo<<\" free: \"<< this->freeSize() <<\"\\n\";\n gsInfo<<\" elim: \"<< this->boundarySize() <<\"\\n\";\n}\n\n\n\nvoid gsDofMapper::setIdentity(index_t nPatches, size_t nDofs)\n{\n m_curElimId = -1;\n m_curCouplingId = 1;\n m_numFreeDofs = nDofs;\n\n \/\/ Initialize all offsets to zero\n m_offset.resize(nPatches, 0);\n\n m_dofs.resize( m_numFreeDofs, 0);\n\n finalize();\n}\n\nvoid gsDofMapper::initPatchDofs(const gsVector & patchDofSizes)\n{\n m_curElimId = -1;\n m_curCouplingId = 1;\n\n const size_t nPatches = patchDofSizes.size();\n\n \/\/ Initialize offsets and dof holder\n m_offset.reserve( nPatches );\n m_offset.push_back(0);\n for (size_t k = 1; k < nPatches; ++k)\n {\n m_offset.push_back( m_offset.back() + patchDofSizes[k-1] );\n }\n\n m_numFreeDofs = m_offset.back() + patchDofSizes[nPatches-1];\n\n m_dofs.resize( m_numFreeDofs, 0);\n}\n\n\n\nvoid gsDofMapper::replaceDofGlobally(index_t oldIdx, index_t newIdx)\n{\n std::replace( m_dofs.begin(), m_dofs.end(), oldIdx, newIdx );\n}\n\nvoid gsDofMapper::mergeDofsGlobally(index_t dof1, index_t dof2)\n{\n if (dof1 != dof2)\n {\n \/\/ replace the larger by the smaller for more consistent numbering.\n if (dof1 < dof2)\n std::swap(dof1, dof2);\n\n replaceDofGlobally(dof1, dof2);\n }\n}\n\n\nindex_t gsDofMapper::coupledSize() const\n{ \n \/\/ Property: coupled (eliminated or not) DoFs appear more than once in the mapping.\n GISMO_ENSURE(m_curElimId==0, \"finalize() was not called on gsDofMapper\");\n\n std::vector CountMap(m_numFreeDofs,0);\n \n \/\/ Count number of appearances of each free DoF\n for (std::vector::const_iterator it = m_dofs.begin(); it != m_dofs.end(); ++it)\n if ( *it < m_numFreeDofs )\n CountMap[*it]++;\n\n \/\/ Count the number of freeDoFs that appear more than once\n index_t count = 0;\n for (std::vector::const_iterator it = CountMap.begin(); it != CountMap.end(); ++it)\n if ( *it > 1 )\n count++;\n\n return count; \n}\n\n\nvoid gsDofMapper::setShift (index_t shift)\n{\n m_shift=shift;\n}\n\n} \/\/ namespace gismo\n\n\nmore improvement in coupledSize\/** @file gsDofMapper.h\n\n @brief Provides the gsDofMapper class for re-indexing DoFs.\n\n This file is part of the G+Smo library.\n\n This Source Code Form is subject to the terms of the Mozilla Public\n License, v. 2.0. If a copy of the MPL was not distributed with this\n file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n Author(s): C. Hofreither, A. Mantzaflaris\n*\/\n\n#include \n\n\nnamespace gismo \n{\n\ngsDofMapper::gsDofMapper() : \nm_shift(0), m_numFreeDofs(0), m_curElimId(-1), m_curCouplingId(1)\n{ \n m_offset.resize(1,0);\n}\n\n\nvoid gsDofMapper::localToGlobal(const gsMatrix& locals,\n index_t patchIndex,\n gsMatrix& globals) const\n{\n GISMO_ASSERT( locals.cols() == 1, \"localToGlobal: Expecting one column of locals\");\n const index_t numActive = locals.rows();\n \n globals.resize(numActive,1);\n \n for (index_t i = 0; i < numActive; ++i)\n globals(i,0) = MAPPER_PATCH_DOF(locals(i,0), patchIndex)+m_shift;\n}\n\n\/\/ This function can not have enough information to do its job if dim>2\n\/\/ GISMO_DEPRECATED\nvoid gsDofMapper::matchInterface( index_t k1, index_t k2,\n const gsMatrix & b1,\n const gsMatrix & b2,\n const gsVector &orient )\n{\n \/\/ Boundaries must be conforming (matching)\n const index_t sz = b1.size();\n if ( sz != b2.size() )\n {\n gsWarn<<\"gsDofMapper: Problem: non-conforming interface \"<<\n \"(\" <(\"<matchDof( k1, b1(k,0), k2, b2(k,0) );\n }\n else\n {\n for ( index_t k=0; kmatchDof( k1, b1(k,0), k2, b2(sz-k-1,0) );\n }\n }\n else\n for ( index_t k=0; kmatchDof( k1, b1(k,0), k2, b2(k,0) );\n}\n\nvoid gsDofMapper::colapseDofs(index_t k, const gsMatrix & b )\n{\n const index_t last = b.size()-1;\n for ( index_t k=0; kmatchDof( k, b(k,0), k, b(k+1,0) );\n }\n}\n\n\n\n\n\nvoid gsDofMapper::matchDof( index_t u, index_t i, index_t v, index_t j )\n{\n index_t d1 = MAPPER_PATCH_DOF(i,u);\n index_t d2 = MAPPER_PATCH_DOF(j,v);\n\n \/\/ make sure that d1 <= d2, simplifies implementation\n if (d1 > d2)\n {\n std::swap(d1, d2);\n std::swap(u, v);\n std::swap(i, j);\n }\n\n if (d1 < 0) \/\/ first dof is eliminated\n {\n if (d2 < 0) mergeDofsGlobally( d1, d2 ); \/\/ both are eliminated, merge their indices\n else if (d2 == 0) MAPPER_PATCH_DOF(j,v) = d1; \/\/ second is free, eliminate it along with first\n else \/* d2 > 0*\/ replaceDofGlobally( d2, d1 ); \/\/ second is coupling, eliminate all instances of it\n }\n else if (d1 == 0) \/\/ first dof is a free dof\n {\n if (d2 == 0) MAPPER_PATCH_DOF(i,u) = MAPPER_PATCH_DOF(j,v) = m_curCouplingId++; \/\/ both are free, assign them a new coupling id\n else if (d2 > 0) MAPPER_PATCH_DOF(i,u) = d2; \/\/ second is coupling, add first to the same coupling group\n else GISMO_ERROR(\"Something went terribly wrong\");\n }\n else \/* d1 > 0 *\/ \/\/ first dof is a coupling dof\n {\n GISMO_ASSERT(d2 > 0, \"Something went terribly wrong\");\n mergeDofsGlobally( d1, d2 ); \/\/ both are coupling dofs, merge them\n }\n\n \/\/ if we merged two different non-eliminated dofs, we lost one free dof\n if ( (d1 != d2 && (d1 >= 0 || d2 >= 0) ) || (d1 == 0 && d2 == 0) )\n --m_numFreeDofs;\n}\n\n\nvoid gsDofMapper::markBoundary( index_t k, const gsMatrix & boundaryDofs )\n{\n for (index_t i = 0; i < boundaryDofs.rows(); ++i)\n {\n eliminateDof( boundaryDofs(i,0), k );\n }\n\n \/\/ TO DO: save inverse, eg boundaryDofs(i,0)\n}\n\nvoid gsDofMapper::eliminateDof( index_t i, index_t k )\n{\n const index_t old = MAPPER_PATCH_DOF(i,k);\n if (old == 0) \/\/ regular free dof\n {\n --m_numFreeDofs;\n MAPPER_PATCH_DOF(i,k) = m_curElimId--;\n }\n else if (old > 0) \/\/ coupling dof\n {\n --m_numFreeDofs;\n replaceDofGlobally( old, m_curElimId-- );\n }\n \/\/ else: old < 0: already an eliminated dof, nothing to do\n}\n\nvoid gsDofMapper::finalize()\n{\n GISMO_ASSERT(m_curElimId!=0, \"Error in gsDofMapper::finalize() called twince.\");\n \n index_t curFreeDof = 0; \/\/ free dofs start at 0\n index_t curElimDof = m_numFreeDofs; \/\/ eliminated dofs start after free dofs\n std::vector couplingDofs(m_curCouplingId - 1, -1);\n std::vector elimDofs(-m_curElimId - 1, -1);\n\n \/\/ Coupled dofs start after standard dofs\n index_t curCplDof = m_numFreeDofs - couplingDofs.size();\n\n for (std::size_t k = 0; k < m_dofs.size(); ++k)\n {\n const index_t dofType = m_dofs[k];\n\n if (dofType == 0) \/\/ standard dof\n m_dofs[k] = curFreeDof++;\n else if (dofType < 0) \/\/ eliminated dof\n {\n const index_t id = -dofType - 1;\n if (elimDofs[id] < 0)\n elimDofs[id] = curElimDof++;\n m_dofs[k] = elimDofs[id];\n }\n else \/\/ dofType > 0 \/\/ coupling dof\n {\n const index_t id = dofType - 1;\n if (couplingDofs[id] < 0)\n \/\/couplingDofs[id] = curFreeDof++;\n couplingDofs[id] = curCplDof++;\n m_dofs[k] = couplingDofs[id];\n }\n }\n m_numElimDofs = curElimDof - m_numFreeDofs;\n\n GISMO_ASSERT(curCplDof == m_numFreeDofs,\n \"gsDofMapper::finalize() - computed number of coupling dofs does not match allocated number\");\n GISMO_ASSERT(curFreeDof + static_cast(couplingDofs.size()) == m_numFreeDofs,\n \"gsDofMapper::finalize() - computed number of free dofs does not match allocated number\");\n\n m_curElimId = 0;\/\/ Only equal to zero after finalize is called.\n\n}\n\nvoid gsDofMapper::print() const\n{\n gsInfo<<\"Dofs: \"<< this->size() <<\"\\n\";\n gsInfo<<\" free: \"<< this->freeSize() <<\"\\n\";\n gsInfo<<\" elim: \"<< this->boundarySize() <<\"\\n\";\n}\n\n\n\nvoid gsDofMapper::setIdentity(index_t nPatches, size_t nDofs)\n{\n m_curElimId = -1;\n m_curCouplingId = 1;\n m_numFreeDofs = nDofs;\n\n \/\/ Initialize all offsets to zero\n m_offset.resize(nPatches, 0);\n\n m_dofs.resize( m_numFreeDofs, 0);\n\n finalize();\n}\n\nvoid gsDofMapper::initPatchDofs(const gsVector & patchDofSizes)\n{\n m_curElimId = -1;\n m_curCouplingId = 1;\n\n const size_t nPatches = patchDofSizes.size();\n\n \/\/ Initialize offsets and dof holder\n m_offset.reserve( nPatches );\n m_offset.push_back(0);\n for (size_t k = 1; k < nPatches; ++k)\n {\n m_offset.push_back( m_offset.back() + patchDofSizes[k-1] );\n }\n\n m_numFreeDofs = m_offset.back() + patchDofSizes[nPatches-1];\n\n m_dofs.resize( m_numFreeDofs, 0);\n}\n\n\n\nvoid gsDofMapper::replaceDofGlobally(index_t oldIdx, index_t newIdx)\n{\n std::replace( m_dofs.begin(), m_dofs.end(), oldIdx, newIdx );\n}\n\nvoid gsDofMapper::mergeDofsGlobally(index_t dof1, index_t dof2)\n{\n if (dof1 != dof2)\n {\n \/\/ replace the larger by the smaller for more consistent numbering.\n if (dof1 < dof2)\n std::swap(dof1, dof2);\n\n replaceDofGlobally(dof1, dof2);\n }\n}\n\n\nindex_t gsDofMapper::coupledSize() const\n{ \n \/\/ Property: coupled (eliminated or not) DoFs appear more than once in the mapping.\n GISMO_ENSURE(m_curElimId==0, \"finalize() was not called on gsDofMapper\");\n \n std::vector CountMap(m_numFreeDofs,0);\n \n \/\/ Count number of appearances of each free DoF\n for (std::vector::const_iterator it = m_dofs.begin(); it != m_dofs.end(); ++it)\n if ( *it < m_numFreeDofs )\n CountMap[*it]++;\n \n \/\/ Count the number of freeDoFs that appear more than once\n return std::count_if( CountMap.begin(), CountMap.end(), std::bind1st(std::greater(), 1) );\n \/* \/\/ Equivalent implementation\n index_t count = 0;\n for (std::vector::const_iterator it = CountMap.begin(); it != CountMap.end(); ++it)\n if ( *it > 1 )\n count++;\n return count; \n *\/\n}\n\n\nvoid gsDofMapper::setShift (index_t shift)\n{\n m_shift=shift;\n}\n\n} \/\/ namespace gismo\n\n\n<|endoftext|>"} {"text":"#include \"terminalpp\/terminal.hpp\"\n#include \"terminalpp\/ansi\/osc.hpp\"\n#include \"terminalpp\/detail\/terminal_control.hpp\"\n#include \"terminalpp\/detail\/terminal_cursor_control.hpp\"\n#include \"terminalpp\/detail\/element_difference.hpp\"\n#include \"terminalpp\/detail\/parser.hpp\"\n#include \"terminalpp\/detail\/well_known_virtual_key.hpp\"\n#include \n\nnamespace terminalpp {\n\nnamespace {\n\n\/\/ ==========================================================================\n\/\/ WRITE_ELEMENT\n\/\/ ==========================================================================\nstd::string write_element(const element& elem)\n{\n std::string text;\n\n if (elem.glyph_.charset_ == terminalpp::ansi::charset::utf8)\n {\n for (size_t index = 0;\n index < sizeof(elem.glyph_.ucharacter_)\n && elem.glyph_.ucharacter_[index] != '\\0';\n ++index)\n {\n text += elem.glyph_.ucharacter_[index];\n\n if (!(elem.glyph_.ucharacter_[index] & 0x80))\n {\n break;\n }\n }\n }\n else\n {\n text += elem.glyph_.character_;\n }\n\n return text;\n}\n\n\/\/ ==========================================================================\n\/\/ REPLACE_WELL_KNOWN_VIRTUAL_KEYS\n\/\/ ==========================================================================\nstd::vector replace_well_known_virtual_keys(std::vector tokens)\n{\n std::transform(tokens.begin(), tokens.end(), tokens.begin(),\n detail::get_well_known_virtual_key);\n\n return tokens;\n}\n\n}\n\n\/\/ ==========================================================================\n\/\/ CONSTRUCTOR\n\/\/ ==========================================================================\nterminal::terminal(terminal::behaviour const &behaviour)\n : behaviour_(behaviour)\n{\n}\n\n\/\/ ==========================================================================\n\/\/ INIT\n\/\/ ==========================================================================\nstd::string terminal::init()\n{\n std::string result;\n\n if (behaviour_.can_use_eight_bit_control_codes\n && !behaviour_.uses_eight_bit_control_codes_by_default)\n {\n result += terminalpp::ansi::control8::ENABLE;\n }\n\n return result;\n}\n\n\/\/ ==========================================================================\n\/\/ ENABLE_MOUSE\n\/\/ ==========================================================================\nstd::string terminal::enable_mouse()\n{\n std::string result;\n\n if (behaviour_.supports_all_mouse_motion_tracking)\n {\n result += detail::csi(control_mode_)\n + ansi::DEC_PRIVATE_MODE\n + ansi::dec_pm::ALL_MOTION_MOUSE_TRACKING\n + ansi::dec_pm::SET;\n }\n else if (behaviour_.supports_basic_mouse_tracking)\n {\n result += detail::csi(control_mode_)\n + ansi::DEC_PRIVATE_MODE\n + ansi::dec_pm::BASIC_MOUSE_TRACKING\n + ansi::dec_pm::SET;\n }\n\n return result;\n}\n\n\/\/ ==========================================================================\n\/\/ SET_WINDOW_TITLE\n\/\/ ==========================================================================\nstd::string terminal::set_window_title(std::string const &title)\n{\n if (behaviour_.supports_window_title_bel)\n {\n return detail::osc(control_mode_)\n + ansi::osc::SET_WINDOW_TITLE\n + ansi::PS\n + title\n + ascii::BEL;\n }\n\n if (behaviour_.supports_window_title_st)\n {\n return detail::osc(control_mode_)\n + ansi::osc::SET_WINDOW_TITLE\n + ansi::PS\n + title\n + detail::st(control_mode_);\n }\n\n return {};\n}\n\n\/\/ ==========================================================================\n\/\/ SET_SIZE\n\/\/ ==========================================================================\nvoid terminal::set_size(const extent& size)\n{\n size_ = size;\n}\n\n\n\/\/ ==========================================================================\n\/\/ SHOW_CURSOR\n\/\/ ==========================================================================\nstd::string terminal::show_cursor()\n{\n if (cursor_mode_ != cursor_mode::shown)\n {\n cursor_mode_ = cursor_mode::shown;\n\n return detail::csi(control_mode_)\n + terminalpp::ansi::DEC_PRIVATE_MODE\n + terminalpp::ansi::dec_pm::CURSOR\n + terminalpp::ansi::dec_pm::SET;\n }\n else\n {\n return {};\n }\n}\n\n\/\/ ==========================================================================\n\/\/ HIDE_CURSOR\n\/\/ ==========================================================================\nstd::string terminal::hide_cursor()\n{\n if (cursor_mode_ != cursor_mode::hidden)\n {\n cursor_mode_ = cursor_mode::hidden;\n\n return detail::csi(control_mode_)\n + terminalpp::ansi::DEC_PRIVATE_MODE\n + terminalpp::ansi::dec_pm::CURSOR\n + terminalpp::ansi::dec_pm::RESET;\n }\n else\n {\n return {};\n }\n}\n\n\/\/ ==========================================================================\n\/\/ SAVE_CURSOR\n\/\/ ==========================================================================\nstd::string terminal::save_cursor()\n{\n saved_cursor_position_ = cursor_position_;\n\n return detail::csi(control_mode_)\n + terminalpp::ansi::csi::SAVE_CURSOR_POSITION;\n}\n\n\/\/ ==========================================================================\n\/\/ RESTORE_CURSOR\n\/\/ ==========================================================================\nstd::string terminal::restore_cursor()\n{\n cursor_position_ = saved_cursor_position_;\n\n return detail::csi(control_mode_)\n + terminalpp::ansi::csi::RESTORE_CURSOR_POSITION;\n}\n\n\/\/ ==========================================================================\n\/\/ MOVE_CURSOR\n\/\/ ==========================================================================\nstd::string terminal::move_cursor(point const &pos)\n{\n std::string result;\n\n \/\/ Note: terminal uses 0-based co-ordinates whereas ANSI uses a\n \/\/ 1-based indexing. Therefore, we need to offset the cursor position\n \/\/ in order to get the correct output when actually calling functions\n \/\/ that refer to co-ordinates (cursor_position and\n \/\/ cursor_horizontal_absolute).\n auto ansipos = pos + point{1, 1};\n\n if (cursor_position_)\n {\n \/\/ If we have a known cursor position, then we may be able to return a\n \/\/ shorter sequence, depending on the exact operation required.\n\n \/\/ If we're staying on the same line, then the following options are\n \/\/ available to us, if they are supported.\n \/\/ * Cursor Horizontal Absolute (move to position on current line)\n \/\/ * Cursor Forward\n \/\/ * Cursor Backward\n if (*cursor_position_ == pos)\n {\n \/\/ Do nothing.\n return result;\n }\n\n if (cursor_position_->y == pos.y)\n {\n if (ansipos.x < 10 && behaviour_.supports_cha)\n {\n \/\/ Note: Cursor Horizontal Absolute uses 1-based indexing,\n \/\/ where terminal uses 0-based indexing. Therefore, it needs\n \/\/ an offset.\n result =\n detail::cursor_horizontal_absolute(\n ansipos.x, behaviour_, control_mode_);\n }\n else\n {\n if (pos.x > cursor_position_->x)\n {\n result =\n detail::cursor_forward(\n pos.x - cursor_position_->x,\n control_mode_);\n }\n else\n {\n result =\n detail::cursor_backward(\n cursor_position_->x - pos.x,\n control_mode_);\n }\n }\n }\n else if (cursor_position_->x == pos.x)\n {\n if (cursor_position_->y > pos.y)\n {\n result = detail::cursor_up(cursor_position_->y - pos.y, control_mode_);\n }\n else\n {\n result = detail::cursor_down(pos.y - cursor_position_->y, control_mode_);\n }\n }\n else\n {\n \/\/ Since we must move in both dimensions, there's no short-cut\n \/\/ command to use.\n result = detail::cursor_position(ansipos, behaviour_, control_mode_);\n }\n }\n else\n {\n \/\/ The cursor position was unknown. There are no shortcuts we can\n \/\/ sensibly take in this situation.\n result = detail::cursor_position(ansipos, behaviour_, control_mode_);\n }\n\n cursor_position_ = pos;\n\n return result;\n}\n\n\/\/ ==========================================================================\n\/\/ READ\n\/\/ ==========================================================================\nstd::vector terminal::read(std::string const &data)\n{\n std::vector results;\n\n std::for_each(data.begin(), data.end(),\n [&](auto ch)\n {\n auto result = parser_(ch);\n\n if (result)\n {\n results.push_back(*result);\n }\n });\n\n \/\/ Some postprocessing for well-known control sequence->\n \/\/ virtual key mappings.\n return replace_well_known_virtual_keys(results);\n}\n\n\/\/ ==========================================================================\n\/\/ WRITE\n\/\/ ==========================================================================\nstd::string terminal::write(element const &elem)\n{\n std::string result = detail::element_difference(last_element_, elem)\n + write_element(elem);\n\n if (cursor_position_)\n {\n ++(cursor_position_->x);\n\n if (size_)\n {\n while (cursor_position_->x > size_->width)\n {\n cursor_position_->x -= size_->width;\n\n if (cursor_position_->y < size_->height)\n {\n ++cursor_position_->y;\n }\n }\n }\n }\n\n last_element_ = elem;\n\n return result;\n}\n\n\/\/ ==========================================================================\n\/\/ WRITE\n\/\/ ==========================================================================\nstd::string terminal::write(string const& str)\n{\n std::string result;\n\n std::for_each(str.begin(), str.end(),\n [&result, this](auto const &elem) mutable\n {\n result += write(elem);\n });\n\n return result;\n}\n\n\/\/ ==========================================================================\n\/\/ ERASE_IN_DISPLAY\n\/\/ ==========================================================================\nstd::string terminal::erase_in_display(terminal::erase_display how)\n{\n std::string result;\n\n result = detail::csi(control_mode_);\n\n switch (how)\n {\n default :\n \/\/ Fall-through\n case terminal::erase_display::all :\n result += terminalpp::ansi::csi::ERASE_IN_DISPLAY_ALL;\n break;\n\n case terminal::erase_display::above :\n result += terminalpp::ansi::csi::ERASE_IN_DISPLAY_ABOVE;\n break;\n\n case terminal::erase_display::below :\n result += terminalpp::ansi::csi::ERASE_IN_DISPLAY_BELOW;\n break;\n }\n\n result += terminalpp::ansi::csi::ERASE_IN_DISPLAY;\n\n return result;\n}\n\n\/\/ ==========================================================================\n\/\/ ERASE_IN_LINE\n\/\/ ==========================================================================\nstd::string terminal::erase_in_line(terminal::erase_line how)\n{\n std::string result;\n\n result = detail::csi(control_mode_);\n\n switch (how)\n {\n default :\n \/\/ Fall-through\n case terminal::erase_line::all :\n result += terminalpp::ansi::csi::ERASE_IN_LINE_ALL;\n break;\n\n case terminal::erase_line::left :\n result += terminalpp::ansi::csi::ERASE_IN_LINE_LEFT;\n break;\n\n case terminal::erase_line::right :\n result += terminalpp::ansi::csi::ERASE_IN_LINE_RIGHT;\n break;\n }\n\n result += terminalpp::ansi::csi::ERASE_IN_LINE;\n\n return result;\n}\n\n\n}\nAddition of this-> in lambda because g++ requires it.#include \"terminalpp\/terminal.hpp\"\n#include \"terminalpp\/ansi\/osc.hpp\"\n#include \"terminalpp\/detail\/terminal_control.hpp\"\n#include \"terminalpp\/detail\/terminal_cursor_control.hpp\"\n#include \"terminalpp\/detail\/element_difference.hpp\"\n#include \"terminalpp\/detail\/parser.hpp\"\n#include \"terminalpp\/detail\/well_known_virtual_key.hpp\"\n#include \n\nnamespace terminalpp {\n\nnamespace {\n\n\/\/ ==========================================================================\n\/\/ WRITE_ELEMENT\n\/\/ ==========================================================================\nstd::string write_element(const element& elem)\n{\n std::string text;\n\n if (elem.glyph_.charset_ == terminalpp::ansi::charset::utf8)\n {\n for (size_t index = 0;\n index < sizeof(elem.glyph_.ucharacter_)\n && elem.glyph_.ucharacter_[index] != '\\0';\n ++index)\n {\n text += elem.glyph_.ucharacter_[index];\n\n if (!(elem.glyph_.ucharacter_[index] & 0x80))\n {\n break;\n }\n }\n }\n else\n {\n text += elem.glyph_.character_;\n }\n\n return text;\n}\n\n\/\/ ==========================================================================\n\/\/ REPLACE_WELL_KNOWN_VIRTUAL_KEYS\n\/\/ ==========================================================================\nstd::vector replace_well_known_virtual_keys(std::vector tokens)\n{\n std::transform(tokens.begin(), tokens.end(), tokens.begin(),\n detail::get_well_known_virtual_key);\n\n return tokens;\n}\n\n}\n\n\/\/ ==========================================================================\n\/\/ CONSTRUCTOR\n\/\/ ==========================================================================\nterminal::terminal(terminal::behaviour const &behaviour)\n : behaviour_(behaviour)\n{\n}\n\n\/\/ ==========================================================================\n\/\/ INIT\n\/\/ ==========================================================================\nstd::string terminal::init()\n{\n std::string result;\n\n if (behaviour_.can_use_eight_bit_control_codes\n && !behaviour_.uses_eight_bit_control_codes_by_default)\n {\n result += terminalpp::ansi::control8::ENABLE;\n }\n\n return result;\n}\n\n\/\/ ==========================================================================\n\/\/ ENABLE_MOUSE\n\/\/ ==========================================================================\nstd::string terminal::enable_mouse()\n{\n std::string result;\n\n if (behaviour_.supports_all_mouse_motion_tracking)\n {\n result += detail::csi(control_mode_)\n + ansi::DEC_PRIVATE_MODE\n + ansi::dec_pm::ALL_MOTION_MOUSE_TRACKING\n + ansi::dec_pm::SET;\n }\n else if (behaviour_.supports_basic_mouse_tracking)\n {\n result += detail::csi(control_mode_)\n + ansi::DEC_PRIVATE_MODE\n + ansi::dec_pm::BASIC_MOUSE_TRACKING\n + ansi::dec_pm::SET;\n }\n\n return result;\n}\n\n\/\/ ==========================================================================\n\/\/ SET_WINDOW_TITLE\n\/\/ ==========================================================================\nstd::string terminal::set_window_title(std::string const &title)\n{\n if (behaviour_.supports_window_title_bel)\n {\n return detail::osc(control_mode_)\n + ansi::osc::SET_WINDOW_TITLE\n + ansi::PS\n + title\n + ascii::BEL;\n }\n\n if (behaviour_.supports_window_title_st)\n {\n return detail::osc(control_mode_)\n + ansi::osc::SET_WINDOW_TITLE\n + ansi::PS\n + title\n + detail::st(control_mode_);\n }\n\n return {};\n}\n\n\/\/ ==========================================================================\n\/\/ SET_SIZE\n\/\/ ==========================================================================\nvoid terminal::set_size(const extent& size)\n{\n size_ = size;\n}\n\n\n\/\/ ==========================================================================\n\/\/ SHOW_CURSOR\n\/\/ ==========================================================================\nstd::string terminal::show_cursor()\n{\n if (cursor_mode_ != cursor_mode::shown)\n {\n cursor_mode_ = cursor_mode::shown;\n\n return detail::csi(control_mode_)\n + terminalpp::ansi::DEC_PRIVATE_MODE\n + terminalpp::ansi::dec_pm::CURSOR\n + terminalpp::ansi::dec_pm::SET;\n }\n else\n {\n return {};\n }\n}\n\n\/\/ ==========================================================================\n\/\/ HIDE_CURSOR\n\/\/ ==========================================================================\nstd::string terminal::hide_cursor()\n{\n if (cursor_mode_ != cursor_mode::hidden)\n {\n cursor_mode_ = cursor_mode::hidden;\n\n return detail::csi(control_mode_)\n + terminalpp::ansi::DEC_PRIVATE_MODE\n + terminalpp::ansi::dec_pm::CURSOR\n + terminalpp::ansi::dec_pm::RESET;\n }\n else\n {\n return {};\n }\n}\n\n\/\/ ==========================================================================\n\/\/ SAVE_CURSOR\n\/\/ ==========================================================================\nstd::string terminal::save_cursor()\n{\n saved_cursor_position_ = cursor_position_;\n\n return detail::csi(control_mode_)\n + terminalpp::ansi::csi::SAVE_CURSOR_POSITION;\n}\n\n\/\/ ==========================================================================\n\/\/ RESTORE_CURSOR\n\/\/ ==========================================================================\nstd::string terminal::restore_cursor()\n{\n cursor_position_ = saved_cursor_position_;\n\n return detail::csi(control_mode_)\n + terminalpp::ansi::csi::RESTORE_CURSOR_POSITION;\n}\n\n\/\/ ==========================================================================\n\/\/ MOVE_CURSOR\n\/\/ ==========================================================================\nstd::string terminal::move_cursor(point const &pos)\n{\n std::string result;\n\n \/\/ Note: terminal uses 0-based co-ordinates whereas ANSI uses a\n \/\/ 1-based indexing. Therefore, we need to offset the cursor position\n \/\/ in order to get the correct output when actually calling functions\n \/\/ that refer to co-ordinates (cursor_position and\n \/\/ cursor_horizontal_absolute).\n auto ansipos = pos + point{1, 1};\n\n if (cursor_position_)\n {\n \/\/ If we have a known cursor position, then we may be able to return a\n \/\/ shorter sequence, depending on the exact operation required.\n\n \/\/ If we're staying on the same line, then the following options are\n \/\/ available to us, if they are supported.\n \/\/ * Cursor Horizontal Absolute (move to position on current line)\n \/\/ * Cursor Forward\n \/\/ * Cursor Backward\n if (*cursor_position_ == pos)\n {\n \/\/ Do nothing.\n return result;\n }\n\n if (cursor_position_->y == pos.y)\n {\n if (ansipos.x < 10 && behaviour_.supports_cha)\n {\n \/\/ Note: Cursor Horizontal Absolute uses 1-based indexing,\n \/\/ where terminal uses 0-based indexing. Therefore, it needs\n \/\/ an offset.\n result =\n detail::cursor_horizontal_absolute(\n ansipos.x, behaviour_, control_mode_);\n }\n else\n {\n if (pos.x > cursor_position_->x)\n {\n result =\n detail::cursor_forward(\n pos.x - cursor_position_->x,\n control_mode_);\n }\n else\n {\n result =\n detail::cursor_backward(\n cursor_position_->x - pos.x,\n control_mode_);\n }\n }\n }\n else if (cursor_position_->x == pos.x)\n {\n if (cursor_position_->y > pos.y)\n {\n result = detail::cursor_up(cursor_position_->y - pos.y, control_mode_);\n }\n else\n {\n result = detail::cursor_down(pos.y - cursor_position_->y, control_mode_);\n }\n }\n else\n {\n \/\/ Since we must move in both dimensions, there's no short-cut\n \/\/ command to use.\n result = detail::cursor_position(ansipos, behaviour_, control_mode_);\n }\n }\n else\n {\n \/\/ The cursor position was unknown. There are no shortcuts we can\n \/\/ sensibly take in this situation.\n result = detail::cursor_position(ansipos, behaviour_, control_mode_);\n }\n\n cursor_position_ = pos;\n\n return result;\n}\n\n\/\/ ==========================================================================\n\/\/ READ\n\/\/ ==========================================================================\nstd::vector terminal::read(std::string const &data)\n{\n std::vector results;\n\n std::for_each(data.begin(), data.end(),\n [&](auto ch)\n {\n auto result = parser_(ch);\n\n if (result)\n {\n results.push_back(*result);\n }\n });\n\n \/\/ Some postprocessing for well-known control sequence->\n \/\/ virtual key mappings.\n return replace_well_known_virtual_keys(results);\n}\n\n\/\/ ==========================================================================\n\/\/ WRITE\n\/\/ ==========================================================================\nstd::string terminal::write(element const &elem)\n{\n std::string result = detail::element_difference(last_element_, elem)\n + write_element(elem);\n\n if (cursor_position_)\n {\n ++(cursor_position_->x);\n\n if (size_)\n {\n while (cursor_position_->x > size_->width)\n {\n cursor_position_->x -= size_->width;\n\n if (cursor_position_->y < size_->height)\n {\n ++cursor_position_->y;\n }\n }\n }\n }\n\n last_element_ = elem;\n\n return result;\n}\n\n\/\/ ==========================================================================\n\/\/ WRITE\n\/\/ ==========================================================================\nstd::string terminal::write(string const& str)\n{\n std::string result;\n\n std::for_each(str.begin(), str.end(),\n [&result, this](auto const &elem)\n {\n result += this->write(elem);\n });\n\n return result;\n}\n\n\/\/ ==========================================================================\n\/\/ ERASE_IN_DISPLAY\n\/\/ ==========================================================================\nstd::string terminal::erase_in_display(terminal::erase_display how)\n{\n std::string result;\n\n result = detail::csi(control_mode_);\n\n switch (how)\n {\n default :\n \/\/ Fall-through\n case terminal::erase_display::all :\n result += terminalpp::ansi::csi::ERASE_IN_DISPLAY_ALL;\n break;\n\n case terminal::erase_display::above :\n result += terminalpp::ansi::csi::ERASE_IN_DISPLAY_ABOVE;\n break;\n\n case terminal::erase_display::below :\n result += terminalpp::ansi::csi::ERASE_IN_DISPLAY_BELOW;\n break;\n }\n\n result += terminalpp::ansi::csi::ERASE_IN_DISPLAY;\n\n return result;\n}\n\n\/\/ ==========================================================================\n\/\/ ERASE_IN_LINE\n\/\/ ==========================================================================\nstd::string terminal::erase_in_line(terminal::erase_line how)\n{\n std::string result;\n\n result = detail::csi(control_mode_);\n\n switch (how)\n {\n default :\n \/\/ Fall-through\n case terminal::erase_line::all :\n result += terminalpp::ansi::csi::ERASE_IN_LINE_ALL;\n break;\n\n case terminal::erase_line::left :\n result += terminalpp::ansi::csi::ERASE_IN_LINE_LEFT;\n break;\n\n case terminal::erase_line::right :\n result += terminalpp::ansi::csi::ERASE_IN_LINE_RIGHT;\n break;\n }\n\n result += terminalpp::ansi::csi::ERASE_IN_LINE;\n\n return result;\n}\n\n\n}\n<|endoftext|>"} {"text":"#pragma once\n\/\/=====================================================================\/\/\n\/*!\t@file\n\t@brief\tFIFO (first in first out)\n\t@author\t平松邦仁 (hira@rvf-rc45.net)\n*\/\n\/\/=====================================================================\/\/\n#include \n\nnamespace utils {\n\n \/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n \/*!\n @brief fifo クラス\n\t\t@param[in]\tsize\tバッファサイズ\n *\/\n \/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate \n\tclass fifo {\n\n\t\tvolatile uint16_t\tget_;\n\t\tvolatile uint16_t\tput_;\n\n\t\tchar\t\tbuff_[size_];\n\n\tpublic:\n \/\/-----------------------------------------------------------------\/\/\n \/*!\n @brief コンストラクター\n *\/\n \/\/-----------------------------------------------------------------\/\/\n\t\tfifo() : get_(0), put_(0) { }\n\n\n \/\/-----------------------------------------------------------------\/\/\n \/*!\n @brief クリア\n *\/\n \/\/-----------------------------------------------------------------\/\/\n\t\tvoid clear() { get_ = put_ = 0; }\n\n\n \/\/-----------------------------------------------------------------\/\/\n \/*!\n @brief 値の格納\n\t\t\t@param[in]\tv\t値\n *\/\n \/\/-----------------------------------------------------------------\/\/\n\t\tvoid put(uint8_t v) {\n\t\t\tbuff_[put_] = v;\n\t\t\t++put_;\n\t\t\tif(put_ >= size_) {\n\t\t\t\tput_ = 0;\n\t\t\t}\n\t\t}\n\n\n \/\/-----------------------------------------------------------------\/\/\n \/*!\n @brief 値の取得\n\t\t\t@return\t値\n *\/\n \/\/-----------------------------------------------------------------\/\/\n\t\tuint8_t get() {\n\t\t\tuint8_t data = buff_[get_];\n\t\t\t++get_;\n\t\t\tif(get_ >= size_) {\n\t\t\t\tget_ = 0;\n\t\t\t}\n\t\t\treturn data;\n\t\t}\n\n\n \/\/-----------------------------------------------------------------\/\/\n \/*!\n @brief 長さを返す\n\t\t\t@return\t長さ\n *\/\n \/\/-----------------------------------------------------------------\/\/\n\t\tuint16_t length() const {\n\t\t\tif(put_ >= get_) return (put_ - get_);\n\t\t\telse return (size_ + put_ - get_);\n\t\t}\n\n\n \/\/-----------------------------------------------------------------\/\/\n \/*!\n @brief get 位置を返す\n\t\t\t@return\t位置\n *\/\n \/\/-----------------------------------------------------------------\/\/\n\t\tuint16_t pos_get() const { return get_; }\n\n\n \/\/-----------------------------------------------------------------\/\/\n \/*!\n @brief put 位置を返す\n\t\t\t@return\t位置\n *\/\n \/\/-----------------------------------------------------------------\/\/\n\t\tuint16_t pos_put() const { return put_; }\n\n\n \/\/-----------------------------------------------------------------\/\/\n \/*!\n @brief バッファのサイズを返す\n\t\t\t@return\tバッファのサイズ\n *\/\n \/\/-----------------------------------------------------------------\/\/\n\t\tuint16_t size() const { return size_; }\n\n\t};\n\n}\nコメント修正#pragma once\n\/\/=====================================================================\/\/\n\/*!\t@file\n\t@brief\tFIFO (first in first out)\n\t@author\t平松邦仁 (hira@rvf-rc45.net)\n*\/\n\/\/=====================================================================\/\/\n#include \n\nnamespace utils {\n\n \/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n \/*!\n @brief fifo クラス\n\t\t@param[in]\tsize_\tバッファサイズ\n *\/\n \/\/+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\/\/\n\ttemplate \n\tclass fifo {\n\n\t\tvolatile uint16_t\tget_;\n\t\tvolatile uint16_t\tput_;\n\n\t\tchar\t\tbuff_[size_];\n\n\tpublic:\n \/\/-----------------------------------------------------------------\/\/\n \/*!\n @brief コンストラクター\n *\/\n \/\/-----------------------------------------------------------------\/\/\n\t\tfifo() : get_(0), put_(0) { }\n\n\n \/\/-----------------------------------------------------------------\/\/\n \/*!\n @brief クリア\n *\/\n \/\/-----------------------------------------------------------------\/\/\n\t\tvoid clear() { get_ = put_ = 0; }\n\n\n \/\/-----------------------------------------------------------------\/\/\n \/*!\n @brief 値の格納\n\t\t\t@param[in]\tv\t値\n *\/\n \/\/-----------------------------------------------------------------\/\/\n\t\tvoid put(uint8_t v) {\n\t\t\tbuff_[put_] = v;\n\t\t\t++put_;\n\t\t\tif(put_ >= size_) {\n\t\t\t\tput_ = 0;\n\t\t\t}\n\t\t}\n\n\n \/\/-----------------------------------------------------------------\/\/\n \/*!\n @brief 値の取得\n\t\t\t@return\t値\n *\/\n \/\/-----------------------------------------------------------------\/\/\n\t\tuint8_t get() {\n\t\t\tuint8_t data = buff_[get_];\n\t\t\t++get_;\n\t\t\tif(get_ >= size_) {\n\t\t\t\tget_ = 0;\n\t\t\t}\n\t\t\treturn data;\n\t\t}\n\n\n \/\/-----------------------------------------------------------------\/\/\n \/*!\n @brief 長さを返す\n\t\t\t@return\t長さ\n *\/\n \/\/-----------------------------------------------------------------\/\/\n\t\tuint16_t length() const {\n\t\t\tif(put_ >= get_) return (put_ - get_);\n\t\t\telse return (size_ + put_ - get_);\n\t\t}\n\n\n \/\/-----------------------------------------------------------------\/\/\n \/*!\n @brief get 位置を返す\n\t\t\t@return\t位置\n *\/\n \/\/-----------------------------------------------------------------\/\/\n\t\tuint16_t pos_get() const { return get_; }\n\n\n \/\/-----------------------------------------------------------------\/\/\n \/*!\n @brief put 位置を返す\n\t\t\t@return\t位置\n *\/\n \/\/-----------------------------------------------------------------\/\/\n\t\tuint16_t pos_put() const { return put_; }\n\n\n \/\/-----------------------------------------------------------------\/\/\n \/*!\n @brief バッファのサイズを返す\n\t\t\t@return\tバッファのサイズ\n *\/\n \/\/-----------------------------------------------------------------\/\/\n\t\tuint16_t size() const { return size_; }\n\n\t};\n\n}\n<|endoftext|>"} {"text":"\/*\n============================================================================\nDELLY: Structural variant discovery by integrated PE mapping and SR analysis\n============================================================================\nCopyright (C) 2012 Tobias Rausch\n\nThis program is free software: you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\nany later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see .\n============================================================================\nContact: Tobias Rausch (rausch@embl.de)\n============================================================================\n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"api\/BamReader.h\"\n#include \"api\/BamIndex.h\"\n\n#include \"tags.h\"\n#include \"coverage.h\"\n#include \"tokenizer.h\"\n#include \"memory_mapped_file.h\"\n#include \"version.h\"\n#include \"fasta_reader.h\"\n#include \"util.h\"\n\nusing namespace torali;\n\nstruct Config {\n unsigned int window_size;\n unsigned int window_offset;\n uint16_t minMapQual;\n bool bp_flag;\n bool avg_flag;\n bool inclCigar;\n boost::filesystem::path outfile;\n boost::filesystem::path int_file;\n std::vector files;\n};\n\n\ntemplate\ninline int\nrun(Config const& c, TSingleHit)\n{\n \/\/ Create library objects\n typedef std::map TLibraryMap;\n typedef std::map TSampleLibrary;\n TSampleLibrary sampleLib;\n\n \/\/ Scan libraries\n for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {\n \/\/ Get a sample name\n std::string sampleName(c.files[file_c].stem().string());\n\n \/\/ Check that all input bam files exist\n BamTools::BamReader reader;\n if ( ! reader.Open(c.files[file_c].string()) ) {\n std::cerr << \"Could not open input bam file: \" << c.files[file_c].string() << std::endl;\n reader.Close();\n return -1;\n }\n \n \/\/ Check that all input bam files are indexed\n reader.LocateIndex();\n if ( !reader.HasIndex() ) {\n std::cerr << \"Missing bam index file: \" << c.files[file_c].string() << std::endl;\n reader.Close();\n return -1;\n }\n\n \/\/ Get library parameters and overall maximum insert size\n TLibraryMap libInfo;\n getLibraryParams(c.files[file_c], libInfo, 0, 5);\n sampleLib.insert(std::make_pair(sampleName, libInfo));\n }\n\n \/\/ Read all SV intervals\n typedef std::vector TSVs;\n TSVs svs;\n std::map idToName;\n unsigned int intervalCount=1;\n if (boost::filesystem::exists(c.int_file) && boost::filesystem::is_regular_file(c.int_file) && boost::filesystem::file_size(c.int_file)) {\n Memory_mapped_file interval_file(c.int_file.string().c_str());\n char interval_buffer[Memory_mapped_file::MAX_LINE_LENGTH];\n while (interval_file.left_bytes() > 0) {\n interval_file.read_line(interval_buffer);\n \/\/ Read single interval line\n StructuralVariantRecord sv;\n Tokenizer token(interval_buffer, Memory_mapped_file::MAX_LINE_LENGTH);\n std::string interval_rname;\n token.getString(sv.chr);\n sv.svStart = token.getUInt();\n sv.svEnd = token.getUInt() + 1;\n std::string svName;\n token.getString(svName);\n idToName.insert(std::make_pair(intervalCount, svName));\n sv.id = intervalCount++;\n svs.push_back(sv);\n }\n interval_file.close();\n } else {\n \/\/ Create artificial intervals\n BamTools::BamReader readerRef;\n if ( ! readerRef.Open(c.files[0].string()) ) return -1;\n BamTools::RefVector references = readerRef.GetReferenceData();\n typename BamTools::RefVector::const_iterator itRef = references.begin();\n for(int refIndex=0;itRef!=references.end();++itRef, ++refIndex) {\n int32_t pos = 0;\n while (pos < references[refIndex].RefLength) {\n\tint32_t window_len = pos+c.window_size;\n\tif (window_len > references[refIndex].RefLength) window_len = references[refIndex].RefLength;\n\tStructuralVariantRecord sv;\n\tsv.chr = references[refIndex].RefName;\n\tsv.svStart = pos;\n\tsv.svEnd = window_len;\n\tstd::stringstream s; \n\ts << sv.chr << \":\" << sv.svStart << \"-\" << sv.svEnd;\n\tidToName.insert(std::make_pair(intervalCount, s.str()));\n\tsv.id = intervalCount++;\n\tsvs.push_back(sv);\n\tpos += c.window_offset;\n }\n }\n }\n\n \/\/ Output data types\n typedef std::pair TSampleSVPair;\n typedef std::pair TBpRead;\n typedef std::map TCountMap;\n TCountMap countMap;\n\n \/\/ Annotate coverage\n annotateCoverage(c.files, c.minMapQual, c.inclCigar, sampleLib, svs, countMap, TSingleHit());\n\n \/\/ Output library statistics\n std::cout << \"Library statistics\" << std::endl;\n TSampleLibrary::const_iterator sampleIt=sampleLib.begin();\n for(;sampleIt!=sampleLib.end();++sampleIt) {\n std::cout << \"Sample: \" << sampleIt->first << std::endl;\n TLibraryMap::const_iterator libIt=sampleIt->second.begin();\n for(;libIt!=sampleIt->second.end();++libIt) {\n std::cout << \"RG: ID=\" << libIt->first << \",Median=\" << libIt->second.median << \",MAD=\" << libIt->second.mad << \",Orientation=\" << (int) libIt->second.defaultOrient << \",MappedReads=\" << libIt->second.mappedReads << \",DuplicatePairs=\" << libIt->second.non_unique_pairs << \",UniquePairs=\" << libIt->second.unique_pairs << std::endl;\n }\n }\n\n \/\/ Output file\n boost::iostreams::filtering_ostream dataOut;\n dataOut.push(boost::iostreams::gzip_compressor());\n dataOut.push(boost::iostreams::file_sink(c.outfile.string().c_str(), std::ios_base::out | std::ios_base::binary));\n\n \/\/ Iterate all SVs\n typename TSVs::const_iterator itSV = svs.begin();\n typename TSVs::const_iterator itSVEnd = svs.end();\n for(;itSV!=itSVEnd;++itSV) {\n dataOut << itSV->chr << \"\\t\" << itSV->svStart << \"\\t\" << itSV->svEnd << \"\\t\" << idToName.find(itSV->id)->second;\n \/\/ Iterate all samples\n for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {\n \/\/ Get the sample name\n std::string sampleName(c.files[file_c].stem().string());\n TSampleSVPair sampleSVPair = std::make_pair(sampleName, itSV->id);\n typename TCountMap::iterator countMapIt=countMap.find(sampleSVPair);\n dataOut << \"\\t\";\n if (c.avg_flag) dataOut << ( (countMapIt->second.first) \/ (double) (itSV->svEnd - itSV->svStart)) << \"\\t\";\n if (c.bp_flag) dataOut << countMapIt->second.first << \"\\t\";\n dataOut << countMapIt->second.second;\n }\n dataOut << std::endl;\n }\n\n \/\/ End\n boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();\n std::cout << '[' << boost::posix_time::to_simple_string(now) << \"] Done.\" << std::endl;;\n return 0;\n}\n\n\nint main(int argc, char **argv) {\n Config c;\n\n \/\/ Define generic options\n boost::program_options::options_description generic(\"Generic options\");\n generic.add_options()\n (\"help,?\", \"show help message\")\n (\"bp-count,b\", \"show base pair count\")\n (\"avg-cov,a\", \"show average coverage\")\n (\"quality-cut,q\", boost::program_options::value(&c.minMapQual)->default_value(0), \"exclude all alignments with quality < q\")\n (\"outfile,f\", boost::program_options::value(&c.outfile)->default_value(\"cov.gz\"), \"coverage output file\")\n ;\n\n \/\/ Define window options\n boost::program_options::options_description window(\"Window options\");\n window.add_options()\n (\"window-size,s\", boost::program_options::value(&c.window_size)->default_value(10000), \"window size\")\n (\"window-offset,o\", boost::program_options::value(&c.window_offset)->default_value(10000), \"window offset\")\n ;\n\n \/\/ Define interval options\n boost::program_options::options_description interval(\"Interval options\");\n interval.add_options()\n (\"interval-file,i\", boost::program_options::value(&c.int_file), \"interval file\")\n ;\n\n \/\/ Define hidden options\n boost::program_options::options_description hidden(\"Hidden options\");\n hidden.add_options()\n (\"input-file\", boost::program_options::value< std::vector >(&c.files), \"input file\")\n (\"license,l\", \"show license\")\n (\"warranty,w\", \"show warranty\")\n ;\n boost::program_options::positional_options_description pos_args;\n pos_args.add(\"input-file\", -1);\n\n \/\/ Set the visibility\n boost::program_options::options_description cmdline_options;\n cmdline_options.add(generic).add(window).add(interval).add(hidden);\n boost::program_options::options_description visible_options;\n visible_options.add(generic).add(window).add(interval);\n boost::program_options::variables_map vm;\n boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(cmdline_options).positional(pos_args).run(), vm);\n boost::program_options::notify(vm);\n\n\n \/\/ Check command line arguments\n if ((vm.count(\"help\")) || (!vm.count(\"input-file\"))) { \n printTitle(\"Coverage calculation\");\n if (vm.count(\"warranty\")) {\n displayWarranty();\n } else if (vm.count(\"license\")) {\n gplV3();\n } else {\n std::cout << \"Usage: \" << argv[0] << \" [OPTIONS] ...\" << std::endl;\n std::cout << visible_options << \"\\n\"; \n }\n return 1; \n }\n if (vm.count(\"bp-count\")) c.bp_flag = true;\n else c.bp_flag = false;\n if (vm.count(\"avg-cov\")) c.avg_flag = true;\n else c.avg_flag = false;\n if ((c.bp_flag) || (c.avg_flag)) c.inclCigar = true;\n else c.inclCigar = false;\n\n \/\/ Show cmd\n boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();\n std::cout << '[' << boost::posix_time::to_simple_string(now) << \"] \";\n for(int i=0; i());\n else return run(c, SingleHit());\n}\nChanged chr names to ids.\/*\n============================================================================\nDELLY: Structural variant discovery by integrated PE mapping and SR analysis\n============================================================================\nCopyright (C) 2012 Tobias Rausch\n\nThis program is free software: you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\nany later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see .\n============================================================================\nContact: Tobias Rausch (rausch@embl.de)\n============================================================================\n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"api\/BamReader.h\"\n#include \"api\/BamIndex.h\"\n\n#include \"tags.h\"\n#include \"coverage.h\"\n#include \"tokenizer.h\"\n#include \"memory_mapped_file.h\"\n#include \"version.h\"\n#include \"fasta_reader.h\"\n#include \"util.h\"\n\nusing namespace torali;\n\nstruct Config {\n unsigned int window_size;\n unsigned int window_offset;\n uint16_t minMapQual;\n bool bp_flag;\n bool avg_flag;\n bool inclCigar;\n boost::filesystem::path outfile;\n boost::filesystem::path int_file;\n std::vector files;\n};\n\n\ntemplate\ninline int\nrun(Config const& c, TSingleHit)\n{\n \/\/ Create library objects\n typedef std::map TLibraryMap;\n typedef std::map TSampleLibrary;\n TSampleLibrary sampleLib;\n\n \/\/ Scan libraries\n for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {\n \/\/ Get a sample name\n std::string sampleName(c.files[file_c].stem().string());\n\n \/\/ Check that all input bam files exist\n BamTools::BamReader reader;\n if ( ! reader.Open(c.files[file_c].string()) ) {\n std::cerr << \"Could not open input bam file: \" << c.files[file_c].string() << std::endl;\n reader.Close();\n return -1;\n }\n \n \/\/ Check that all input bam files are indexed\n reader.LocateIndex();\n if ( !reader.HasIndex() ) {\n std::cerr << \"Missing bam index file: \" << c.files[file_c].string() << std::endl;\n reader.Close();\n return -1;\n }\n\n \/\/ Get library parameters and overall maximum insert size\n TLibraryMap libInfo;\n getLibraryParams(c.files[file_c], libInfo, 0, 5);\n sampleLib.insert(std::make_pair(sampleName, libInfo));\n }\n\n \/\/ Get references\n BamTools::BamReader readerRef;\n if ( ! readerRef.Open(c.files[0].string()) ) return -1;\n BamTools::RefVector references = readerRef.GetReferenceData();\n\n \/\/ Read all SV intervals\n typedef std::vector TSVs;\n TSVs svs;\n std::map idToName;\n unsigned int intervalCount=1;\n if (boost::filesystem::exists(c.int_file) && boost::filesystem::is_regular_file(c.int_file) && boost::filesystem::file_size(c.int_file)) {\n Memory_mapped_file interval_file(c.int_file.string().c_str());\n char interval_buffer[Memory_mapped_file::MAX_LINE_LENGTH];\n while (interval_file.left_bytes() > 0) {\n interval_file.read_line(interval_buffer);\n \/\/ Read single interval line\n StructuralVariantRecord sv;\n Tokenizer token(interval_buffer, Memory_mapped_file::MAX_LINE_LENGTH);\n std::string chrName;\n token.getString(chrName);\n typename BamTools::RefVector::const_iterator itRef = references.begin();\n for(int refIndex=0;itRef!=references.end();++itRef, ++refIndex) {\n\tif (chrName==references[refIndex].RefName) {\n\t sv.chr = refIndex;\n\t break;\n\t}\n }\n sv.svStart = token.getUInt();\n sv.svEnd = token.getUInt() + 1;\n std::string svName;\n token.getString(svName);\n idToName.insert(std::make_pair(intervalCount, svName));\n sv.id = intervalCount++;\n svs.push_back(sv);\n }\n interval_file.close();\n } else {\n \/\/ Create artificial intervals\n typename BamTools::RefVector::const_iterator itRef = references.begin();\n for(int refIndex=0;itRef!=references.end();++itRef, ++refIndex) {\n int32_t pos = 0;\n while (pos < references[refIndex].RefLength) {\n\tint32_t window_len = pos+c.window_size;\n\tif (window_len > references[refIndex].RefLength) window_len = references[refIndex].RefLength;\n\tStructuralVariantRecord sv;\n\tsv.chr = refIndex;\n\tsv.svStart = pos;\n\tsv.svEnd = window_len;\n\tstd::stringstream s; \n\ts << references[sv.chr].RefName << \":\" << sv.svStart << \"-\" << sv.svEnd;\n\tidToName.insert(std::make_pair(intervalCount, s.str()));\n\tsv.id = intervalCount++;\n\tsvs.push_back(sv);\n\tpos += c.window_offset;\n }\n }\n }\n\n \/\/ Output data types\n typedef std::pair TSampleSVPair;\n typedef std::pair TBpRead;\n typedef std::map TCountMap;\n TCountMap countMap;\n\n \/\/ Annotate coverage\n annotateCoverage(c.files, c.minMapQual, c.inclCigar, sampleLib, svs, countMap, TSingleHit());\n\n \/\/ Output library statistics\n std::cout << \"Library statistics\" << std::endl;\n TSampleLibrary::const_iterator sampleIt=sampleLib.begin();\n for(;sampleIt!=sampleLib.end();++sampleIt) {\n std::cout << \"Sample: \" << sampleIt->first << std::endl;\n TLibraryMap::const_iterator libIt=sampleIt->second.begin();\n for(;libIt!=sampleIt->second.end();++libIt) {\n std::cout << \"RG: ID=\" << libIt->first << \",Median=\" << libIt->second.median << \",MAD=\" << libIt->second.mad << \",Orientation=\" << (int) libIt->second.defaultOrient << \",MappedReads=\" << libIt->second.mappedReads << \",DuplicatePairs=\" << libIt->second.non_unique_pairs << \",UniquePairs=\" << libIt->second.unique_pairs << std::endl;\n }\n }\n\n \/\/ Output file\n boost::iostreams::filtering_ostream dataOut;\n dataOut.push(boost::iostreams::gzip_compressor());\n dataOut.push(boost::iostreams::file_sink(c.outfile.string().c_str(), std::ios_base::out | std::ios_base::binary));\n\n \/\/ Iterate all SVs\n typename TSVs::const_iterator itSV = svs.begin();\n typename TSVs::const_iterator itSVEnd = svs.end();\n for(;itSV!=itSVEnd;++itSV) {\n dataOut << references[itSV->chr].RefName << \"\\t\" << itSV->svStart << \"\\t\" << itSV->svEnd << \"\\t\" << idToName.find(itSV->id)->second;\n \/\/ Iterate all samples\n for(unsigned int file_c = 0; file_c < c.files.size(); ++file_c) {\n \/\/ Get the sample name\n std::string sampleName(c.files[file_c].stem().string());\n TSampleSVPair sampleSVPair = std::make_pair(sampleName, itSV->id);\n typename TCountMap::iterator countMapIt=countMap.find(sampleSVPair);\n dataOut << \"\\t\";\n if (c.avg_flag) dataOut << ( (countMapIt->second.first) \/ (double) (itSV->svEnd - itSV->svStart)) << \"\\t\";\n if (c.bp_flag) dataOut << countMapIt->second.first << \"\\t\";\n dataOut << countMapIt->second.second;\n }\n dataOut << std::endl;\n }\n\n \/\/ End\n boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();\n std::cout << '[' << boost::posix_time::to_simple_string(now) << \"] Done.\" << std::endl;;\n return 0;\n}\n\n\nint main(int argc, char **argv) {\n Config c;\n\n \/\/ Define generic options\n boost::program_options::options_description generic(\"Generic options\");\n generic.add_options()\n (\"help,?\", \"show help message\")\n (\"bp-count,b\", \"show base pair count\")\n (\"avg-cov,a\", \"show average coverage\")\n (\"quality-cut,q\", boost::program_options::value(&c.minMapQual)->default_value(0), \"exclude all alignments with quality < q\")\n (\"outfile,f\", boost::program_options::value(&c.outfile)->default_value(\"cov.gz\"), \"coverage output file\")\n ;\n\n \/\/ Define window options\n boost::program_options::options_description window(\"Window options\");\n window.add_options()\n (\"window-size,s\", boost::program_options::value(&c.window_size)->default_value(10000), \"window size\")\n (\"window-offset,o\", boost::program_options::value(&c.window_offset)->default_value(10000), \"window offset\")\n ;\n\n \/\/ Define interval options\n boost::program_options::options_description interval(\"Interval options\");\n interval.add_options()\n (\"interval-file,i\", boost::program_options::value(&c.int_file), \"interval file\")\n ;\n\n \/\/ Define hidden options\n boost::program_options::options_description hidden(\"Hidden options\");\n hidden.add_options()\n (\"input-file\", boost::program_options::value< std::vector >(&c.files), \"input file\")\n (\"license,l\", \"show license\")\n (\"warranty,w\", \"show warranty\")\n ;\n boost::program_options::positional_options_description pos_args;\n pos_args.add(\"input-file\", -1);\n\n \/\/ Set the visibility\n boost::program_options::options_description cmdline_options;\n cmdline_options.add(generic).add(window).add(interval).add(hidden);\n boost::program_options::options_description visible_options;\n visible_options.add(generic).add(window).add(interval);\n boost::program_options::variables_map vm;\n boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(cmdline_options).positional(pos_args).run(), vm);\n boost::program_options::notify(vm);\n\n\n \/\/ Check command line arguments\n if ((vm.count(\"help\")) || (!vm.count(\"input-file\"))) { \n printTitle(\"Coverage calculation\");\n if (vm.count(\"warranty\")) {\n displayWarranty();\n } else if (vm.count(\"license\")) {\n gplV3();\n } else {\n std::cout << \"Usage: \" << argv[0] << \" [OPTIONS] ...\" << std::endl;\n std::cout << visible_options << \"\\n\"; \n }\n return 1; \n }\n if (vm.count(\"bp-count\")) c.bp_flag = true;\n else c.bp_flag = false;\n if (vm.count(\"avg-cov\")) c.avg_flag = true;\n else c.avg_flag = false;\n if ((c.bp_flag) || (c.avg_flag)) c.inclCigar = true;\n else c.inclCigar = false;\n\n \/\/ Show cmd\n boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();\n std::cout << '[' << boost::posix_time::to_simple_string(now) << \"] \";\n for(int i=0; i());\n else return run(c, SingleHit());\n}\n<|endoftext|>"} {"text":"\/*\n * nextpnr -- Next Generation Place and Route\n *\n * Copyright (C) 2018 Clifford Wolf \n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \n#include \n\n#include \"log.h\"\n#include \"route.h\"\n\nnamespace {\n\nUSING_NEXTPNR_NAMESPACE\n\nstruct QueuedWire\n{\n WireId wire;\n PipId pip;\n\n float delay = 0, togo = 0;\n\n struct Greater\n {\n bool operator()(const QueuedWire &lhs, const QueuedWire &rhs) const\n noexcept\n {\n return (lhs.delay + lhs.togo) > (rhs.delay + rhs.togo);\n }\n };\n};\n\nvoid ripup_net(Design *design, IdString net_name)\n{\n auto &chip = design->chip;\n auto net_info = design->nets.at(net_name);\n\n for (auto &it : net_info->wires) {\n if (it.second != PipId())\n chip.unbindPip(it.second);\n chip.unbindWire(it.first);\n }\n\n net_info->wires.clear();\n}\n\nstruct Router\n{\n std::unordered_set rippedNets;\n int visitCnt = 0, revisitCnt = 0;\n bool routedOkay = false;\n float maxDelay = 0.0;\n\n Router(Design *design, IdString net_name, bool verbose, bool ripup = false,\n float ripup_pip_penalty = 5.0, float ripup_wire_penalty = 5.0)\n {\n auto &chip = design->chip;\n auto net_info = design->nets.at(net_name);\n\n if (verbose)\n log(\"Routing net %s.\\n\", net_name.c_str());\n\n if (verbose)\n log(\" Source: %s.%s.\\n\", net_info->driver.cell->name.c_str(),\n net_info->driver.port.c_str());\n\n auto src_bel = net_info->driver.cell->bel;\n\n if (src_bel == BelId())\n log_error(\"Source cell %s (%s) is not mapped to a bel.\\n\",\n net_info->driver.cell->name.c_str(),\n net_info->driver.cell->type.c_str());\n\n if (verbose)\n log(\" Source bel: %s\\n\", chip.getBelName(src_bel).c_str());\n\n IdString driver_port = net_info->driver.port;\n\n auto driver_port_it = net_info->driver.cell->pins.find(driver_port);\n if (driver_port_it != net_info->driver.cell->pins.end())\n driver_port = driver_port_it->second;\n\n auto src_wire = chip.getWireBelPin(src_bel, portPinFromId(driver_port));\n\n if (src_wire == WireId())\n log_error(\"No wire found for port %s (pin %s) on source cell %s \"\n \"(bel %s).\\n\",\n net_info->driver.port.c_str(), driver_port.c_str(),\n net_info->driver.cell->name.c_str(),\n chip.getBelName(src_bel).c_str());\n\n if (verbose)\n log(\" Source wire: %s\\n\", chip.getWireName(src_wire).c_str());\n\n std::unordered_map src_wires;\n src_wires[src_wire] = DelayInfo();\n net_info->wires[src_wire] = PipId();\n chip.bindWire(src_wire, net_name);\n\n for (auto &user_it : net_info->users) {\n if (verbose)\n log(\" Route to: %s.%s.\\n\", user_it.cell->name.c_str(),\n user_it.port.c_str());\n\n auto dst_bel = user_it.cell->bel;\n\n if (dst_bel == BelId())\n log_error(\"Destination cell %s (%s) is not mapped to a bel.\\n\",\n user_it.cell->name.c_str(),\n user_it.cell->type.c_str());\n\n if (verbose)\n log(\" Destination bel: %s\\n\",\n chip.getBelName(dst_bel).c_str());\n\n IdString user_port = user_it.port;\n\n auto user_port_it = user_it.cell->pins.find(user_port);\n\n if (user_port_it != user_it.cell->pins.end())\n user_port = user_port_it->second;\n\n auto dst_wire =\n chip.getWireBelPin(dst_bel, portPinFromId(user_port));\n\n if (dst_wire == WireId())\n log_error(\"No wire found for port %s (pin %s) on destination \"\n \"cell %s (bel %s).\\n\",\n user_it.port.c_str(), user_port.c_str(),\n user_it.cell->name.c_str(),\n chip.getBelName(dst_bel).c_str());\n\n if (verbose) {\n log(\" Destination wire: %s\\n\",\n chip.getWireName(dst_wire).c_str());\n log(\" Path delay estimate: %.2f\\n\",\n chip.estimateDelay(src_wire, dst_wire));\n }\n\n std::unordered_map visited;\n std::priority_queue,\n QueuedWire::Greater>\n queue;\n\n for (auto &it : src_wires) {\n QueuedWire qw;\n qw.wire = it.first;\n qw.pip = PipId();\n qw.delay = it.second.avgDelay();\n qw.togo = chip.estimateDelay(qw.wire, dst_wire);\n\n queue.push(qw);\n visited[qw.wire] = qw;\n }\n\n while (!queue.empty() && !visited.count(dst_wire)) {\n QueuedWire qw = queue.top();\n queue.pop();\n\n for (auto pip : chip.getPipsDownhill(qw.wire)) {\n float next_delay = qw.delay;\n visitCnt++;\n\n if (!chip.checkPipAvail(pip)) {\n if (!ripup || net_name == chip.getPipNet(pip, true))\n continue;\n next_delay += ripup_pip_penalty;\n }\n\n WireId next_wire = chip.getPipDstWire(pip);\n next_delay += chip.getPipDelay(pip).avgDelay();\n\n if (visited.count(next_wire)) {\n if (visited.at(next_wire).delay <= next_delay + 1e-3)\n continue;\n#if 0 \/\/ FIXME\n if (verbose)\n log(\"Found better route to %s. Old vs new delay \"\n \"estimate: %.2f %.2f\\n\",\n chip.getWireName(next_wire).c_str(),\n visited.at(next_wire).delay, next_delay);\n#endif\n revisitCnt++;\n }\n\n if (!chip.checkWireAvail(next_wire)) {\n if (!ripup ||\n net_name == chip.getWireNet(next_wire, true))\n continue;\n next_delay += ripup_wire_penalty;\n }\n\n QueuedWire next_qw;\n next_qw.wire = next_wire;\n next_qw.pip = pip;\n next_qw.delay = next_delay;\n next_qw.togo = chip.estimateDelay(next_wire, dst_wire);\n visited[next_qw.wire] = next_qw;\n queue.push(next_qw);\n }\n }\n\n if (visited.count(dst_wire) == 0) {\n if (verbose)\n log(\"Failed to route %s -> %s.\\n\",\n chip.getWireName(src_wire).c_str(),\n chip.getWireName(dst_wire).c_str());\n else if (ripup)\n log_info(\"Failed to route %s -> %s.\\n\",\n chip.getWireName(src_wire).c_str(),\n chip.getWireName(dst_wire).c_str());\n ripup_net(design, net_name);\n return;\n }\n\n if (verbose)\n log(\" Final path delay: %.2f\\n\", visited[dst_wire].delay);\n maxDelay = fmaxf(maxDelay, visited[dst_wire].delay);\n\n if (verbose)\n log(\" Route (from destination to source):\\n\");\n\n WireId cursor = dst_wire;\n\n while (1) {\n if (verbose)\n log(\" %8.2f %s\\n\", visited[cursor].delay,\n chip.getWireName(cursor).c_str());\n\n if (src_wires.count(cursor))\n break;\n\n IdString conflicting_net = chip.getWireNet(cursor, true);\n\n if (conflicting_net != IdString()) {\n assert(ripup);\n assert(conflicting_net != net_name);\n ripup_net(design, conflicting_net);\n rippedNets.insert(conflicting_net);\n }\n\n conflicting_net = chip.getPipNet(visited[cursor].pip, true);\n\n if (conflicting_net != IdString()) {\n assert(ripup);\n assert(conflicting_net != net_name);\n ripup_net(design, conflicting_net);\n rippedNets.insert(conflicting_net);\n }\n\n net_info->wires[cursor] = visited[cursor].pip;\n chip.bindWire(cursor, net_name);\n chip.bindPip(visited[cursor].pip, net_name);\n\n src_wires[cursor] = chip.getPipDelay(visited[cursor].pip);\n cursor = chip.getPipSrcWire(visited[cursor].pip);\n }\n }\n\n routedOkay = true;\n }\n};\n\n} \/\/ namespace\n\nNEXTPNR_NAMESPACE_BEGIN\n\nvoid route_design(Design *design, bool verbose)\n{\n auto &chip = design->chip;\n float maxDelay = 0.0;\n float ripup_pip_penalty = 5.0;\n float ripup_wire_penalty = 5.0;\n\n log_info(\"Routing..\\n\");\n\n std::unordered_set netsQueue;\n\n for (auto &net_it : design->nets) {\n auto net_name = net_it.first;\n auto net_info = net_it.second;\n\n if (net_info->driver.cell == nullptr)\n continue;\n\n if (!net_info->wires.empty())\n continue;\n\n netsQueue.insert(net_name);\n }\n\n if (netsQueue.empty()) {\n log_info(\"found no unrouted nets. no routing necessary.\\n\");\n return;\n }\n\n log_info(\"found %d unrouted nets. starting routing procedure.\\n\",\n int(netsQueue.size()));\n\n float estimatedTotalDelay = 0.0;\n int estimatedTotalDelayCnt = 0;\n\n for (auto net_name : netsQueue) {\n auto net_info = design->nets.at(net_name);\n\n auto src_bel = net_info->driver.cell->bel;\n\n if (src_bel == BelId())\n continue;\n\n IdString driver_port = net_info->driver.port;\n\n auto driver_port_it = net_info->driver.cell->pins.find(driver_port);\n if (driver_port_it != net_info->driver.cell->pins.end())\n driver_port = driver_port_it->second;\n\n auto src_wire = chip.getWireBelPin(src_bel, portPinFromId(driver_port));\n\n if (src_wire == WireId())\n continue;\n\n for (auto &user_it : net_info->users) {\n auto dst_bel = user_it.cell->bel;\n\n if (dst_bel == BelId())\n continue;\n\n IdString user_port = user_it.port;\n\n auto user_port_it = user_it.cell->pins.find(user_port);\n\n if (user_port_it != user_it.cell->pins.end())\n user_port = user_port_it->second;\n\n auto dst_wire =\n chip.getWireBelPin(dst_bel, portPinFromId(user_port));\n\n if (dst_wire == WireId())\n continue;\n\n estimatedTotalDelay += chip.estimateDelay(src_wire, dst_wire);\n estimatedTotalDelayCnt++;\n }\n }\n\n log_info(\"estimated total wire delay: %.2f (avg %.2f)\\n\",\n estimatedTotalDelay, estimatedTotalDelay \/ estimatedTotalDelayCnt);\n\n while (!netsQueue.empty()) {\n int visitCnt = 0, revisitCnt = 0, netCnt = 0;\n\n std::unordered_set ripupQueue;\n\n for (auto net_name : netsQueue) {\n Router router(design, net_name, verbose, false);\n\n netCnt++;\n visitCnt += router.visitCnt;\n revisitCnt += router.revisitCnt;\n\n if (router.routedOkay) {\n maxDelay = fmaxf(maxDelay, router.maxDelay);\n } else {\n ripupQueue.insert(net_name);\n }\n\n if (netCnt % 100 == 0)\n log_info(\" processed %d nets. (%d routed, %d failed)\\n\",\n netCnt, netCnt - int(ripupQueue.size()),\n int(ripupQueue.size()));\n }\n\n netsQueue.clear();\n\n if (netCnt % 100 != 0)\n log_info(\" processed %d nets. (%d routed, %d failed)\\n\", netCnt,\n netCnt - int(ripupQueue.size()), int(ripupQueue.size()));\n log_info(\"routing pass visited %d PIPs (%.2f%% revisits).\\n\", visitCnt,\n (100.0 * revisitCnt) \/ visitCnt);\n\n if (!ripupQueue.empty()) {\n log_info(\"failed to route %d nets. re-routing in ripup mode.\\n\",\n int(ripupQueue.size()));\n\n visitCnt = 0;\n revisitCnt = 0;\n netCnt = 0;\n int ripCnt = 0;\n\n for (auto net_name : ripupQueue) {\n Router router(design, net_name, verbose, true,\n ripup_pip_penalty, ripup_wire_penalty);\n\n netCnt++;\n visitCnt += router.visitCnt;\n revisitCnt += router.revisitCnt;\n\n if (!router.routedOkay)\n log_error(\"Net %s is impossible to route.\\n\",\n net_name.c_str());\n\n maxDelay = fmaxf(maxDelay, router.maxDelay);\n\n for (auto it : router.rippedNets)\n netsQueue.insert(it);\n\n ripCnt += router.rippedNets.size();\n\n if (netCnt % 100 == 0)\n log_info(\" routed %d nets, ripped %d nets.\\n\", netCnt,\n ripCnt);\n }\n\n if (netCnt % 100 != 0)\n log_info(\" routed %d nets, ripped %d nets.\\n\", netCnt, ripCnt);\n log_info(\"routing pass visited %d PIPs (%.2f%% revisits).\\n\",\n visitCnt, (100.0 * revisitCnt) \/ visitCnt);\n\n log_info(\"ripped up %d previously routed nets. continue routing.\\n\",\n int(netsQueue.size()));\n\n ripup_pip_penalty *= 1.5;\n ripup_wire_penalty *= 1.5;\n }\n }\n\n log_info(\"routing complete. longest path delay: %.2f\\n\", maxDelay);\n}\n\nNEXTPNR_NAMESPACE_END\nrouter: Fixing loop issue\/*\n * nextpnr -- Next Generation Place and Route\n *\n * Copyright (C) 2018 Clifford Wolf \n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n *\/\n\n#include \n#include \n\n#include \"log.h\"\n#include \"route.h\"\n\nnamespace {\n\nUSING_NEXTPNR_NAMESPACE\n\nstruct QueuedWire\n{\n WireId wire;\n PipId pip;\n\n float delay = 0, togo = 0;\n\n struct Greater\n {\n bool operator()(const QueuedWire &lhs, const QueuedWire &rhs) const\n noexcept\n {\n return (lhs.delay + lhs.togo) > (rhs.delay + rhs.togo);\n }\n };\n};\n\nvoid ripup_net(Design *design, IdString net_name)\n{\n auto &chip = design->chip;\n auto net_info = design->nets.at(net_name);\n\n for (auto &it : net_info->wires) {\n if (it.second != PipId())\n chip.unbindPip(it.second);\n chip.unbindWire(it.first);\n }\n\n net_info->wires.clear();\n}\n\nstruct Router\n{\n std::unordered_set rippedNets;\n int visitCnt = 0, revisitCnt = 0;\n bool routedOkay = false;\n float maxDelay = 0.0;\n\n Router(Design *design, IdString net_name, bool verbose, bool ripup = false,\n float ripup_pip_penalty = 5.0, float ripup_wire_penalty = 5.0)\n {\n auto &chip = design->chip;\n auto net_info = design->nets.at(net_name);\n\n if (verbose)\n log(\"Routing net %s.\\n\", net_name.c_str());\n\n if (verbose)\n log(\" Source: %s.%s.\\n\", net_info->driver.cell->name.c_str(),\n net_info->driver.port.c_str());\n\n auto src_bel = net_info->driver.cell->bel;\n\n if (src_bel == BelId())\n log_error(\"Source cell %s (%s) is not mapped to a bel.\\n\",\n net_info->driver.cell->name.c_str(),\n net_info->driver.cell->type.c_str());\n\n if (verbose)\n log(\" Source bel: %s\\n\", chip.getBelName(src_bel).c_str());\n\n IdString driver_port = net_info->driver.port;\n\n auto driver_port_it = net_info->driver.cell->pins.find(driver_port);\n if (driver_port_it != net_info->driver.cell->pins.end())\n driver_port = driver_port_it->second;\n\n auto src_wire = chip.getWireBelPin(src_bel, portPinFromId(driver_port));\n\n if (src_wire == WireId())\n log_error(\"No wire found for port %s (pin %s) on source cell %s \"\n \"(bel %s).\\n\",\n net_info->driver.port.c_str(), driver_port.c_str(),\n net_info->driver.cell->name.c_str(),\n chip.getBelName(src_bel).c_str());\n\n if (verbose)\n log(\" Source wire: %s\\n\", chip.getWireName(src_wire).c_str());\n\n std::unordered_map src_wires;\n src_wires[src_wire] = DelayInfo();\n net_info->wires[src_wire] = PipId();\n chip.bindWire(src_wire, net_name);\n\n for (auto &user_it : net_info->users) {\n if (verbose)\n log(\" Route to: %s.%s.\\n\", user_it.cell->name.c_str(),\n user_it.port.c_str());\n\n auto dst_bel = user_it.cell->bel;\n\n if (dst_bel == BelId())\n log_error(\"Destination cell %s (%s) is not mapped to a bel.\\n\",\n user_it.cell->name.c_str(),\n user_it.cell->type.c_str());\n\n if (verbose)\n log(\" Destination bel: %s\\n\",\n chip.getBelName(dst_bel).c_str());\n\n IdString user_port = user_it.port;\n\n auto user_port_it = user_it.cell->pins.find(user_port);\n\n if (user_port_it != user_it.cell->pins.end())\n user_port = user_port_it->second;\n\n auto dst_wire =\n chip.getWireBelPin(dst_bel, portPinFromId(user_port));\n\n if (dst_wire == WireId())\n log_error(\"No wire found for port %s (pin %s) on destination \"\n \"cell %s (bel %s).\\n\",\n user_it.port.c_str(), user_port.c_str(),\n user_it.cell->name.c_str(),\n chip.getBelName(dst_bel).c_str());\n\n if (verbose) {\n log(\" Destination wire: %s\\n\",\n chip.getWireName(dst_wire).c_str());\n log(\" Path delay estimate: %.2f\\n\",\n chip.estimateDelay(src_wire, dst_wire));\n }\n\n std::unordered_map visited;\n std::priority_queue,\n QueuedWire::Greater>\n queue;\n\n for (auto &it : src_wires) {\n QueuedWire qw;\n qw.wire = it.first;\n qw.pip = PipId();\n qw.delay = it.second.avgDelay();\n qw.togo = chip.estimateDelay(qw.wire, dst_wire);\n\n queue.push(qw);\n visited[qw.wire] = qw;\n }\n\n while (!queue.empty() && !visited.count(dst_wire)) {\n QueuedWire qw = queue.top();\n queue.pop();\n\n for (auto pip : chip.getPipsDownhill(qw.wire)) {\n float next_delay = qw.delay;\n visitCnt++;\n\n if (!chip.checkPipAvail(pip)) {\n if (!ripup || net_name == chip.getPipNet(pip, true))\n continue;\n next_delay += ripup_pip_penalty;\n }\n\n WireId next_wire = chip.getPipDstWire(pip);\n next_delay += chip.getPipDelay(pip).avgDelay();\n\n if (visited.count(next_wire)) {\n if (visited.at(next_wire).delay <= next_delay + 1e-3)\n continue;\n#if 0 \/\/ FIXME\n if (verbose)\n log(\"Found better route to %s. Old vs new delay \"\n \"estimate: %.2f %.2f\\n\",\n chip.getWireName(next_wire).c_str(),\n visited.at(next_wire).delay, next_delay);\n#endif\n revisitCnt++;\n continue;\n }\n\n if (!chip.checkWireAvail(next_wire)) {\n if (!ripup ||\n net_name == chip.getWireNet(next_wire, true))\n continue;\n next_delay += ripup_wire_penalty;\n }\n\n QueuedWire next_qw;\n next_qw.wire = next_wire;\n next_qw.pip = pip;\n next_qw.delay = next_delay;\n next_qw.togo = chip.estimateDelay(next_wire, dst_wire);\n visited[next_qw.wire] = next_qw;\n queue.push(next_qw);\n }\n }\n\n if (visited.count(dst_wire) == 0) {\n if (verbose)\n log(\"Failed to route %s -> %s.\\n\",\n chip.getWireName(src_wire).c_str(),\n chip.getWireName(dst_wire).c_str());\n else if (ripup)\n log_info(\"Failed to route %s -> %s.\\n\",\n chip.getWireName(src_wire).c_str(),\n chip.getWireName(dst_wire).c_str());\n ripup_net(design, net_name);\n return;\n }\n\n if (verbose)\n log(\" Final path delay: %.2f\\n\", visited[dst_wire].delay);\n maxDelay = fmaxf(maxDelay, visited[dst_wire].delay);\n\n if (verbose)\n log(\" Route (from destination to source):\\n\");\n\n WireId cursor = dst_wire;\n\n while (1) {\n if (verbose)\n log(\" %8.2f %s\\n\", visited[cursor].delay,\n chip.getWireName(cursor).c_str());\n\n if (src_wires.count(cursor))\n break;\n\n IdString conflicting_net = chip.getWireNet(cursor, true);\n\n if (conflicting_net != IdString()) {\n assert(ripup);\n assert(conflicting_net != net_name);\n ripup_net(design, conflicting_net);\n rippedNets.insert(conflicting_net);\n }\n\n conflicting_net = chip.getPipNet(visited[cursor].pip, true);\n\n if (conflicting_net != IdString()) {\n assert(ripup);\n assert(conflicting_net != net_name);\n ripup_net(design, conflicting_net);\n rippedNets.insert(conflicting_net);\n }\n\n net_info->wires[cursor] = visited[cursor].pip;\n chip.bindWire(cursor, net_name);\n chip.bindPip(visited[cursor].pip, net_name);\n\n src_wires[cursor] = chip.getPipDelay(visited[cursor].pip);\n cursor = chip.getPipSrcWire(visited[cursor].pip);\n }\n }\n\n routedOkay = true;\n }\n};\n\n} \/\/ namespace\n\nNEXTPNR_NAMESPACE_BEGIN\n\nvoid route_design(Design *design, bool verbose)\n{\n auto &chip = design->chip;\n float maxDelay = 0.0;\n float ripup_pip_penalty = 5.0;\n float ripup_wire_penalty = 5.0;\n\n log_info(\"Routing..\\n\");\n\n std::unordered_set netsQueue;\n\n for (auto &net_it : design->nets) {\n auto net_name = net_it.first;\n auto net_info = net_it.second;\n\n if (net_info->driver.cell == nullptr)\n continue;\n\n if (!net_info->wires.empty())\n continue;\n\n netsQueue.insert(net_name);\n }\n\n if (netsQueue.empty()) {\n log_info(\"found no unrouted nets. no routing necessary.\\n\");\n return;\n }\n\n log_info(\"found %d unrouted nets. starting routing procedure.\\n\",\n int(netsQueue.size()));\n\n float estimatedTotalDelay = 0.0;\n int estimatedTotalDelayCnt = 0;\n\n for (auto net_name : netsQueue) {\n auto net_info = design->nets.at(net_name);\n\n auto src_bel = net_info->driver.cell->bel;\n\n if (src_bel == BelId())\n continue;\n\n IdString driver_port = net_info->driver.port;\n\n auto driver_port_it = net_info->driver.cell->pins.find(driver_port);\n if (driver_port_it != net_info->driver.cell->pins.end())\n driver_port = driver_port_it->second;\n\n auto src_wire = chip.getWireBelPin(src_bel, portPinFromId(driver_port));\n\n if (src_wire == WireId())\n continue;\n\n for (auto &user_it : net_info->users) {\n auto dst_bel = user_it.cell->bel;\n\n if (dst_bel == BelId())\n continue;\n\n IdString user_port = user_it.port;\n\n auto user_port_it = user_it.cell->pins.find(user_port);\n\n if (user_port_it != user_it.cell->pins.end())\n user_port = user_port_it->second;\n\n auto dst_wire =\n chip.getWireBelPin(dst_bel, portPinFromId(user_port));\n\n if (dst_wire == WireId())\n continue;\n\n estimatedTotalDelay += chip.estimateDelay(src_wire, dst_wire);\n estimatedTotalDelayCnt++;\n }\n }\n\n log_info(\"estimated total wire delay: %.2f (avg %.2f)\\n\",\n estimatedTotalDelay, estimatedTotalDelay \/ estimatedTotalDelayCnt);\n\n while (!netsQueue.empty()) {\n int visitCnt = 0, revisitCnt = 0, netCnt = 0;\n\n std::unordered_set ripupQueue;\n\n for (auto net_name : netsQueue) {\n Router router(design, net_name, verbose, false);\n\n netCnt++;\n visitCnt += router.visitCnt;\n revisitCnt += router.revisitCnt;\n\n if (router.routedOkay) {\n maxDelay = fmaxf(maxDelay, router.maxDelay);\n } else {\n ripupQueue.insert(net_name);\n }\n\n if (netCnt % 100 == 0)\n log_info(\" processed %d nets. (%d routed, %d failed)\\n\",\n netCnt, netCnt - int(ripupQueue.size()),\n int(ripupQueue.size()));\n }\n\n netsQueue.clear();\n\n if (netCnt % 100 != 0)\n log_info(\" processed %d nets. (%d routed, %d failed)\\n\", netCnt,\n netCnt - int(ripupQueue.size()), int(ripupQueue.size()));\n log_info(\"routing pass visited %d PIPs (%.2f%% revisits).\\n\", visitCnt,\n (100.0 * revisitCnt) \/ visitCnt);\n\n if (!ripupQueue.empty()) {\n log_info(\"failed to route %d nets. re-routing in ripup mode.\\n\",\n int(ripupQueue.size()));\n\n visitCnt = 0;\n revisitCnt = 0;\n netCnt = 0;\n int ripCnt = 0;\n\n for (auto net_name : ripupQueue) {\n Router router(design, net_name, verbose, true,\n ripup_pip_penalty, ripup_wire_penalty);\n\n netCnt++;\n visitCnt += router.visitCnt;\n revisitCnt += router.revisitCnt;\n\n if (!router.routedOkay)\n log_error(\"Net %s is impossible to route.\\n\",\n net_name.c_str());\n\n maxDelay = fmaxf(maxDelay, router.maxDelay);\n\n for (auto it : router.rippedNets)\n netsQueue.insert(it);\n\n ripCnt += router.rippedNets.size();\n\n if (netCnt % 100 == 0)\n log_info(\" routed %d nets, ripped %d nets.\\n\", netCnt,\n ripCnt);\n }\n\n if (netCnt % 100 != 0)\n log_info(\" routed %d nets, ripped %d nets.\\n\", netCnt, ripCnt);\n log_info(\"routing pass visited %d PIPs (%.2f%% revisits).\\n\",\n visitCnt, (100.0 * revisitCnt) \/ visitCnt);\n\n log_info(\"ripped up %d previously routed nets. continue routing.\\n\",\n int(netsQueue.size()));\n\n ripup_pip_penalty *= 1.5;\n ripup_wire_penalty *= 1.5;\n }\n }\n\n log_info(\"routing complete. longest path delay: %.2f\\n\", maxDelay);\n}\n\nNEXTPNR_NAMESPACE_END\n<|endoftext|>"} {"text":"\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/lib\/eff_config\/timing.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/ *HWP HWP Owner: Andre Marin \n\/\/ *HWP HWP Backup: Jacob Harvey \n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 3\n\/\/ *HWP Consumed by: FSP:HB\n\n\n#include \n#include \n#include \n#include \n\nnamespace mss\n{\n\nenum temp_mode : uint8_t\n{\n NORMAL = 1,\n EXTENDED = 2,\n};\n\n\/\/ Proposed DDR4 Full spec update(79-4B)\n\/\/ Item No. 1716.78C\n\/\/ pg.46\n\/\/ Table 24 - tREFI and tRFC parameters (in ps)\nconstexpr uint64_t TREFI_BASE = 7800000;\n\n\/\/ Proposed DDR4 3DS Addendum\n\/\/ Item No. 1727.58A\n\/\/ pg. 69 - 71\n\/\/ Table 42 - Refresh parameters by logical rank density\nstatic const std::vector > TRFC_DLR1 =\n{\n \/\/ { density in GBs, tRFC4(min) in picoseconds }\n {4, 90000},\n {8, 120000},\n \/\/ 16Gb - TBD\n};\n\n\/\/ Proposed DDR4 3DS Addendum\n\/\/ Item No. 1727.58A\n\/\/ pg. 69 - 71\n\/\/ Table 42 - Refresh parameters by logical rank density\nstatic const std::vector > TRFC_DLR2 =\n{\n \/\/ { density in GBs, tRFC4(min) in picoseconds }\n {4, 55000},\n {8, 90000}\n \/\/ 16Gb - TBD\n};\n\n\/\/ Proposed DDR4 3DS Addendum\n\/\/ Item No. 1727.58A\n\/\/ pg. 69 - 71\n\/\/ Table 42 - Refresh parameters by logical rank density\nstatic const std::vector > TRFC_DLR4 =\n{\n \/\/ { density in GBs, tRFC4(min) in picoseconds }\n {4, 40000},\n {8, 55000}\n \/\/ 16Gb - TBD\n};\n\n\/\/\/\n\/\/\/ @brief Calculates refresh interval time\n\/\/\/ @param[in] i_mode fine refresh rate mode\n\/\/\/ @param[in] i_temp_refresh_range temperature refresh range\n\/\/\/ @param[out] o_value timing val in ps\n\/\/\/ @return fapi2::ReturnCode\n\/\/\/\nfapi2::ReturnCode calc_trefi( const refresh_rate i_mode,\n const uint8_t i_temp_refresh_range,\n uint64_t& o_timing )\n{\n uint64_t l_multiplier = 0;\n uint64_t l_quotient = 0;\n uint64_t l_remainder = 0;\n\n switch(i_temp_refresh_range)\n {\n case fapi2::ENUM_ATTR_MSS_MRW_TEMP_REFRESH_RANGE_NORMAL:\n l_multiplier = temp_mode::NORMAL;\n break;\n\n case fapi2::ENUM_ATTR_MSS_MRW_TEMP_REFRESH_RANGE_EXTEND:\n l_multiplier = temp_mode::EXTENDED;\n break;\n\n default:\n \/\/ Temperature Refresh Range will be a platform attribute set by the MRW,\n \/\/ which they \"shouldn't\" mess up as long as use \"attribute\" enums.\n \/\/ if someone messes this up we can at least catch it\n FAPI_ASSERT( false,\n fapi2::MSS_INVALID_TEMP_REFRESH()\n .set_TEMP_REFRESH_RANGE(i_temp_refresh_range),\n \"Incorrect Temperature Ref. Range received: %d \",\n i_temp_refresh_range);\n break;\n }\n\n l_quotient = TREFI_BASE \/ ( int64_t(i_mode) * l_multiplier );\n l_remainder = TREFI_BASE % ( int64_t(i_mode) * l_multiplier );\n o_timing = l_quotient + (l_remainder == 0 ? 0 : 1);\n\n FAPI_INF( \"tREFI: %d, quotient: %d, remainder: %d, tREFI_base: %d\",\n o_timing, l_quotient, l_remainder, TREFI_BASE );\n\n \/\/ FAPI_ASSERT doesn't set current error to good\n return fapi2::FAPI2_RC_SUCCESS;\nfapi_try_exit:\n return fapi2::current_err;\n}\n\n\/\/\/ @brief Calculates Minimum Refresh Recovery Delay Time (different logical rank)\n\/\/\/ @param[in] i_mode fine refresh rate mode\n\/\/\/ @param[in] i_density SDRAM density\n\/\/\/ @param[out] o_trfc_in_ps timing val in ps\n\/\/\/ @return fapi2::FAPI2_RC_SUCCESS iff okay\n\/\/\/\nfapi2::ReturnCode calc_trfc_dlr(const fapi2::Target& i_target,\n const uint8_t i_refresh_mode,\n const uint8_t i_density,\n uint64_t& o_trfc_in_ps)\n{\n bool l_is_val_found = 0;\n\n \/\/ Selects appropriate tRFC based on fine refresh mode\n switch(i_refresh_mode)\n {\n case fapi2::ENUM_ATTR_MSS_MRW_FINE_REFRESH_MODE_NORMAL:\n l_is_val_found = find_value_from_key(TRFC_DLR1, i_density, o_trfc_in_ps);\n break;\n\n case fapi2::ENUM_ATTR_MSS_MRW_FINE_REFRESH_MODE_FIXED_2X:\n case fapi2::ENUM_ATTR_MSS_MRW_FINE_REFRESH_MODE_FLY_2X:\n l_is_val_found = find_value_from_key(TRFC_DLR2, i_density, o_trfc_in_ps);\n break;\n\n case fapi2::ENUM_ATTR_MSS_MRW_FINE_REFRESH_MODE_FIXED_4X:\n case fapi2::ENUM_ATTR_MSS_MRW_FINE_REFRESH_MODE_FLY_4X:\n l_is_val_found = find_value_from_key(TRFC_DLR4, i_density, o_trfc_in_ps);\n break;\n\n default:\n \/\/ Fine Refresh Mode will be a platform attribute set by the MRW,\n \/\/ which they \"shouldn't\" mess up as long as use \"attribute\" enums.\n \/\/ if openpower messes this up we can at least catch it\n FAPI_ASSERT( false,\n fapi2::MSS_INVALID_FINE_REFRESH()\n .set_REFRESH_MODE(i_refresh_mode),\n \"Incorrect Fine Refresh Mode received: %d \",\n i_refresh_mode);\n break;\n }\/\/ switch\n\n FAPI_ASSERT( l_is_val_found,\n fapi2::MSS_FAILED_TO_FIND_TRFC()\n .set_SDRAM_DENSITY(i_density)\n .set_REFRESH_MODE(i_refresh_mode)\n .set_TARGET(i_target),\n \"%s: Unable to find tRFC (ps) from map with SDRAM density key %d with %d refresh mode\",\n mss::c_str(i_target),\n i_density,\n i_refresh_mode);\n\n \/\/ Again, FAPI_ASSERT doesn't set current_err to good, only to bad\n return fapi2::FAPI2_RC_SUCCESS;\nfapi_try_exit:\n return fapi2::current_err;\n}\n\n}\/\/ mss\nMove find API to share among memory controllers\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/memory\/lib\/eff_config\/timing.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2016,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/ *HWP HWP Owner: Andre Marin \n\/\/ *HWP HWP Backup: Jacob Harvey \n\/\/ *HWP Team: Memory\n\/\/ *HWP Level: 3\n\/\/ *HWP Consumed by: FSP:HB\n\n\n#include \n#include \n#include \n#include \n\nnamespace mss\n{\n\nenum temp_mode : uint8_t\n{\n NORMAL = 1,\n EXTENDED = 2,\n};\n\n\/\/ Proposed DDR4 Full spec update(79-4B)\n\/\/ Item No. 1716.78C\n\/\/ pg.46\n\/\/ Table 24 - tREFI and tRFC parameters (in ps)\nconstexpr uint64_t TREFI_BASE = 7800000;\n\n\/\/ Proposed DDR4 3DS Addendum\n\/\/ Item No. 1727.58A\n\/\/ pg. 69 - 71\n\/\/ Table 42 - Refresh parameters by logical rank density\nstatic const std::vector > TRFC_DLR1 =\n{\n \/\/ { density in GBs, tRFC4(min) in picoseconds }\n {4, 90000},\n {8, 120000},\n \/\/ 16Gb - TBD\n};\n\n\/\/ Proposed DDR4 3DS Addendum\n\/\/ Item No. 1727.58A\n\/\/ pg. 69 - 71\n\/\/ Table 42 - Refresh parameters by logical rank density\nstatic const std::vector > TRFC_DLR2 =\n{\n \/\/ { density in GBs, tRFC4(min) in picoseconds }\n {4, 55000},\n {8, 90000}\n \/\/ 16Gb - TBD\n};\n\n\/\/ Proposed DDR4 3DS Addendum\n\/\/ Item No. 1727.58A\n\/\/ pg. 69 - 71\n\/\/ Table 42 - Refresh parameters by logical rank density\nstatic const std::vector > TRFC_DLR4 =\n{\n \/\/ { density in GBs, tRFC4(min) in picoseconds }\n {4, 40000},\n {8, 55000}\n \/\/ 16Gb - TBD\n};\n\n\/\/\/\n\/\/\/ @brief Calculates refresh interval time\n\/\/\/ @param[in] i_mode fine refresh rate mode\n\/\/\/ @param[in] i_temp_refresh_range temperature refresh range\n\/\/\/ @param[out] o_value timing val in ps\n\/\/\/ @return fapi2::ReturnCode\n\/\/\/\nfapi2::ReturnCode calc_trefi( const refresh_rate i_mode,\n const uint8_t i_temp_refresh_range,\n uint64_t& o_timing )\n{\n uint64_t l_multiplier = 0;\n uint64_t l_quotient = 0;\n uint64_t l_remainder = 0;\n\n switch(i_temp_refresh_range)\n {\n case fapi2::ENUM_ATTR_MSS_MRW_TEMP_REFRESH_RANGE_NORMAL:\n l_multiplier = temp_mode::NORMAL;\n break;\n\n case fapi2::ENUM_ATTR_MSS_MRW_TEMP_REFRESH_RANGE_EXTEND:\n l_multiplier = temp_mode::EXTENDED;\n break;\n\n default:\n \/\/ Temperature Refresh Range will be a platform attribute set by the MRW,\n \/\/ which they \"shouldn't\" mess up as long as use \"attribute\" enums.\n \/\/ if someone messes this up we can at least catch it\n FAPI_ASSERT( false,\n fapi2::MSS_INVALID_TEMP_REFRESH()\n .set_TEMP_REFRESH_RANGE(i_temp_refresh_range),\n \"Incorrect Temperature Ref. Range received: %d \",\n i_temp_refresh_range);\n break;\n }\n\n l_quotient = TREFI_BASE \/ ( int64_t(i_mode) * l_multiplier );\n l_remainder = TREFI_BASE % ( int64_t(i_mode) * l_multiplier );\n o_timing = l_quotient + (l_remainder == 0 ? 0 : 1);\n\n FAPI_INF( \"tREFI: %d, quotient: %d, remainder: %d, tREFI_base: %d\",\n o_timing, l_quotient, l_remainder, TREFI_BASE );\n\n \/\/ FAPI_ASSERT doesn't set current error to good\n return fapi2::FAPI2_RC_SUCCESS;\nfapi_try_exit:\n return fapi2::current_err;\n}\n\n\/\/\/ @brief Calculates Minimum Refresh Recovery Delay Time (different logical rank)\n\/\/\/ @param[in] i_mode fine refresh rate mode\n\/\/\/ @param[in] i_density SDRAM density\n\/\/\/ @param[out] o_trfc_in_ps timing val in ps\n\/\/\/ @return fapi2::FAPI2_RC_SUCCESS iff okay\n\/\/\/\nfapi2::ReturnCode calc_trfc_dlr(const fapi2::Target& i_target,\n const uint8_t i_refresh_mode,\n const uint8_t i_density,\n uint64_t& o_trfc_in_ps)\n{\n bool l_is_val_found = 0;\n\n \/\/ Selects appropriate tRFC based on fine refresh mode\n switch(i_refresh_mode)\n {\n case fapi2::ENUM_ATTR_MSS_MRW_FINE_REFRESH_MODE_NORMAL:\n l_is_val_found = find_value_from_key(TRFC_DLR1, i_density, o_trfc_in_ps);\n break;\n\n case fapi2::ENUM_ATTR_MSS_MRW_FINE_REFRESH_MODE_FIXED_2X:\n case fapi2::ENUM_ATTR_MSS_MRW_FINE_REFRESH_MODE_FLY_2X:\n l_is_val_found = find_value_from_key(TRFC_DLR2, i_density, o_trfc_in_ps);\n break;\n\n case fapi2::ENUM_ATTR_MSS_MRW_FINE_REFRESH_MODE_FIXED_4X:\n case fapi2::ENUM_ATTR_MSS_MRW_FINE_REFRESH_MODE_FLY_4X:\n l_is_val_found = find_value_from_key(TRFC_DLR4, i_density, o_trfc_in_ps);\n break;\n\n default:\n \/\/ Fine Refresh Mode will be a platform attribute set by the MRW,\n \/\/ which they \"shouldn't\" mess up as long as use \"attribute\" enums.\n \/\/ if openpower messes this up we can at least catch it\n FAPI_ASSERT( false,\n fapi2::MSS_INVALID_FINE_REFRESH()\n .set_REFRESH_MODE(i_refresh_mode),\n \"Incorrect Fine Refresh Mode received: %d \",\n i_refresh_mode);\n break;\n }\/\/ switch\n\n FAPI_ASSERT( l_is_val_found,\n fapi2::MSS_FAILED_TO_FIND_TRFC()\n .set_SDRAM_DENSITY(i_density)\n .set_REFRESH_MODE(i_refresh_mode)\n .set_TARGET(i_target),\n \"%s: Unable to find tRFC (ps) from map with SDRAM density key %d with %d refresh mode\",\n mss::c_str(i_target),\n i_density,\n i_refresh_mode);\n\n \/\/ Again, FAPI_ASSERT doesn't set current_err to good, only to bad\n return fapi2::FAPI2_RC_SUCCESS;\nfapi_try_exit:\n return fapi2::current_err;\n}\n\n}\/\/ mss\n<|endoftext|>"} {"text":"Increasing AI spawn timer from 30 > 60 seconds.<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \n#include \n#include \n\n#include \"third_party\/skia\/include\/core\/SkTypes.h\"\n\n\/\/ This implementation of sk_malloc_flags() and friends is identical\n\/\/ to SkMemory_malloc.c, except that it disables the CRT's new_handler\n\/\/ during malloc(), when SK_MALLOC_THROW is not set (ie., when\n\/\/ sk_malloc_flags() would not abort on NULL).\n\nvoid sk_throw() {\n SkASSERT(!\"sk_throw\");\n abort();\n}\n\nvoid sk_out_of_memory(void) {\n SkASSERT(!\"sk_out_of_memory\");\n abort();\n}\n\nvoid* sk_malloc_throw(size_t size) {\n return sk_malloc_flags(size, SK_MALLOC_THROW);\n}\n\nvoid* sk_realloc_throw(void* addr, size_t size) {\n void* p = realloc(addr, size);\n if (size == 0) {\n return p;\n }\n if (p == NULL) {\n sk_throw();\n }\n return p;\n}\n\nvoid sk_free(void* p) {\n if (p) {\n free(p);\n }\n}\n\nvoid* sk_malloc_flags(size_t size, unsigned flags) {\n std::new_handler old_handler;\n if (!(flags & SK_MALLOC_THROW)) {\n old_handler = std::set_new_handler(NULL);\n }\n void* p = malloc(size);\n if (!(flags & SK_MALLOC_THROW)) {\n std::set_new_handler(old_handler);\n }\n if (p == NULL) {\n if (flags & SK_MALLOC_THROW) {\n sk_throw();\n }\n }\n return p;\n}\n\nFix for Skia data race. This may introduce some performance issues; will watch perf bots carefully.\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \n#include \n#include \n\n#include \"third_party\/skia\/include\/core\/SkTypes.h\"\n#include \"third_party\/skia\/include\/core\/SkThread.h\"\n\n\/\/ This implementation of sk_malloc_flags() and friends is identical\n\/\/ to SkMemory_malloc.c, except that it disables the CRT's new_handler\n\/\/ during malloc(), when SK_MALLOC_THROW is not set (ie., when\n\/\/ sk_malloc_flags() would not abort on NULL).\n\nstatic SkMutex gSkNewHandlerMutex;\n\nvoid sk_throw() {\n SkASSERT(!\"sk_throw\");\n abort();\n}\n\nvoid sk_out_of_memory(void) {\n SkASSERT(!\"sk_out_of_memory\");\n abort();\n}\n\nvoid* sk_malloc_throw(size_t size) {\n return sk_malloc_flags(size, SK_MALLOC_THROW);\n}\n\nvoid* sk_realloc_throw(void* addr, size_t size) {\n void* p = realloc(addr, size);\n if (size == 0) {\n return p;\n }\n if (p == NULL) {\n sk_throw();\n }\n return p;\n}\n\nvoid sk_free(void* p) {\n if (p) {\n free(p);\n }\n}\n\nvoid* sk_malloc_flags(size_t size, unsigned flags) {\n void* p;\n if (!(flags & SK_MALLOC_THROW)) {\n SkAutoMutexAcquire lock(gSkNewHandlerMutex);\n std::new_handler old_handler = std::set_new_handler(NULL);\n p = malloc(size);\n std::set_new_handler(old_handler);\n } else {\n p = malloc(size);\n }\n if (p == NULL) {\n if (flags & SK_MALLOC_THROW) {\n sk_throw();\n }\n }\n return p;\n}\n\n<|endoftext|>"} {"text":"\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include \"parser\/TypeGrammar.hpp\"\n#include \"lexer\/position.hpp\"\n\nusing namespace eddic;\n\nparser::TypeGrammar::TypeGrammar(const lexer::Lexer& lexer, const lexer::pos_iterator_type& position_begin) : \n TypeGrammar::base_type(type, \"Type Grammar\"),\n position_begin(position_begin){\n \n const_ %=\n (lexer.const_ > boost::spirit::attr(true))\n | boost::spirit::attr(false);\n\n array_type %=\n qi::eps\n >> lexer.identifier\n >> lexer.left_bracket\n >> lexer.right_bracket;\n \n pointer_type %=\n qi::eps\n >> lexer.identifier\n >> lexer.multiplication;\n\n simple_type %=\n qi::eps\n >> const_\n >> lexer.identifier;\n\n type %=\n array_type\n | pointer_type\n | simple_type;\n}\nCleanup\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include \"parser\/TypeGrammar.hpp\"\n#include \"lexer\/position.hpp\"\n\nusing namespace eddic;\n\nparser::TypeGrammar::TypeGrammar(const lexer::Lexer& lexer, const lexer::pos_iterator_type& position_begin) : \n TypeGrammar::base_type(type, \"Type Grammar\"),\n position_begin(position_begin){\n \n const_ %=\n (lexer.const_ > boost::spirit::attr(true))\n | boost::spirit::attr(false);\n\n array_type %=\n lexer.identifier\n >> lexer.left_bracket\n >> lexer.right_bracket;\n \n pointer_type %=\n lexer.identifier\n >> lexer.multiplication;\n\n simple_type %=\n const_\n >> lexer.identifier;\n\n type %=\n array_type\n | pointer_type\n | simple_type;\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ remapped_symbol_set.cpp\n\/\/ Parse\n\/\/\n\/\/ Created by Andrew Hunter on 26\/04\/2011.\n\/\/ Copyright 2011 __MyCompanyName__. All rights reserved.\n\/\/\n\n#include \n#include \n#include \n\n#include \"remapped_symbol_map.h\"\n#include \"range.h\"\n\nusing namespace std;\nusing namespace dfa;\n\n\/\/\/ \\brief Empty symbol set\nconst remapped_symbol_map::new_symbols remapped_symbol_map::s_NoSymbols;\n\n\/\/\/ \\brief Generates an empty remapped symbol map\nremapped_symbol_map::remapped_symbol_map() {\n}\n\n\/\/\/ \\brief Copy constructor\nremapped_symbol_map::remapped_symbol_map(const remapped_symbol_map& copyFrom) \n: m_OldToNew(copyFrom.m_OldToNew) {\n}\n\n\/\/\/ \\brief Finds or adds an identifier for the specified symbol, adding the specified set of new symbols as the new symbols\nint remapped_symbol_map::identifier_for_symbols(const symbol_set& symbols, const new_symbols& newSymbols) {\n \/\/ Get the set ID for these symbols\n int setId = symbol_map::identifier_for_symbols(symbols);\n \n \/\/ Try to look up the existing set\n old_to_new_map::iterator existing = m_OldToNew.find(setId);\n \n if (existing == m_OldToNew.end()) {\n \/\/ Just add these symbols\n m_OldToNew[setId] = newSymbols;\n } else {\n \/\/ Merge the sets\n for (new_symbols::iterator it = newSymbols.begin(); it != newSymbols.end(); it++) {\n existing->second.insert(*it);\n }\n }\n \n \/\/ Return this as the result\n return setId;\n}\n\n\/\/\/ \\brief Range of symbols\ntypedef range symbol_range;\n\n\/\/\/ \\brief Type mapping symbol ranges to the sets that contain them\ntypedef map, symbol_range::sort_by_lower > sets_for_range;\n\n\/\/\/ \\brief Splits a range that exists in sets into two.\n\/\/\/\n\/\/\/ We end up with two ranges: lower..splitPoint and splitPoint..upper\n\/\/\/ Returns an iterator for the start of the new ranges\nstatic sets_for_range::iterator split(sets_for_range& sets, symbol_range original, int splitPoint) {\n \/\/ Get the values for this range\n set values = sets[original];\n \n \/\/ Remove the original range\n sets.erase(original);\n \n \/\/ Create the split ranges\n sets[symbol_range(splitPoint, original.upper())] = values;\n sets_for_range::iterator result = sets.insert(sets_for_range::value_type(symbol_range(original.lower(), splitPoint), values)).first;\n return result;\n}\n\n\/\/\/ \\brief Adds the ranges in a particular symbol set \nstatic void add_set(sets_for_range& sets, const symbol_set& symbols, int identifier) {\n \/\/ Iterate through the ranges in this set\n for (symbol_set::iterator range = symbols.begin(); range != symbols.end(); range++) {\n \/\/ Find the first item in the set whose lower bound is >= this range\n sets_for_range::iterator firstGreaterThan = sets.lower_bound(*range);\n \n \/\/ If this isn't at the beginning, then it's possible that this set overlaps the preceeding set\n if (firstGreaterThan != sets.begin()) {\n \/\/ Get the previous set\n sets_for_range::iterator preceeding = firstGreaterThan;\n preceeding--;\n \n \/\/ See if there's an overlap\n if (preceeding->first.upper() >= range->lower()) {\n \/\/ Start from the preceeding set if they do\n firstGreaterThan = preceeding;\n }\n }\n \n \/\/ If we're at the end of the list here, then this is an entirely new range\n \/\/ This is also a new range if the item at firstGreaterThan doesn't overlap the range\n \/\/ Finally, we can just add to the set for a particular range if we get an exact match\n if (firstGreaterThan == sets.end() || !firstGreaterThan->first.overlaps(*range) || firstGreaterThan->first == *range) {\n \/\/ Just add this range\n sets[*range].insert(identifier);\n continue;\n }\n\n \/\/ We've got some overlap, but it's not exact\n symbol_range remaining = *range; \/\/ Range of characters remaining to merge in\n set justUs; \/\/ Set containing only the new identifier\n \n justUs.insert(identifier);\n\n while (remaining.upper() != remaining.lower()) {\n cout << \"Remaining: \" << remaining.lower() << \"-\" << remaining.upper() << endl;\n cout << \"Sets:\";\n for (sets_for_range::iterator it = sets.begin(); it != sets.end(); it++) {\n cout << \" \" << it->first.lower() << \"-\" << it->first.upper();\n }\n cout << endl;\n if (firstGreaterThan == sets.end()) cout << \"At end\" << endl;\n else cout << \"Position: \" << firstGreaterThan->first.lower() << \"-\" << firstGreaterThan->first.upper() << endl;\n \n \/\/ If we're at the end, we can just add the remaining set and stop\n if (firstGreaterThan == sets.end()) {\n sets[remaining] = justUs;\n break;\n }\n \n \/\/ If there's a gap between the remaining set and the current position, then fill it in\n if (firstGreaterThan->first.lower() > remaining.lower()) {\n int newUpper = firstGreaterThan->first.lower();\n \n \/\/ Insert a value to fill the gap\n firstGreaterThan = sets.insert(firstGreaterThan, sets_for_range::value_type(symbol_range(remaining.lower(), newUpper), justUs));\n \n \/\/ Adjust the remaining set\n remaining = symbol_range(newUpper, remaining.upper());\n \n \/\/ Want the value after the one we just inserted\n firstGreaterThan++;\n \n \/\/ Start again\n continue;\n }\n \n \/\/ If there's a gap between the lowest point in the range we're currently splitting and the current range, then split there\n if (firstGreaterThan->first.lower() < remaining.lower()) {\n \/\/ Split the ranges and move so that the lowest point matches\n firstGreaterThan = split(sets, firstGreaterThan->first, remaining.lower());\n firstGreaterThan++;\n }\n \n \/\/ If the current range ends beyond the end of the remaining set, then split it\n if (firstGreaterThan->first.upper() > remaining.upper()) {\n firstGreaterThan = split(sets, firstGreaterThan->first, remaining.upper());\n }\n \n \/\/ Current range should overlap the range specified by firstGreaterThan: add this identifier\n firstGreaterThan->second.insert(identifier);\n \n \/\/ Adjust the remaining set\n remaining = symbol_range(firstGreaterThan->first.upper(), remaining.upper());\n \n \/\/ Move on\n firstGreaterThan++;\n }\n \n cout << \"Done adding\" << endl;\n cout << \"Sets:\";\n for (sets_for_range::iterator it = sets.begin(); it != sets.end(); it++) {\n cout << \" \" << it->first.lower() << \"-\" << it->first.upper();\n }\n cout << endl;\n }\n}\n\n\/\/\/ \\brief Factory method that generates a remapped symbol map by removing duplicates\n\/\/\/\n\/\/\/ This finds all the symbol sets that overlap in the original, and splits them up so that any given symbol is only in one set.\n\/\/\/ It sets up the remapping so it is possible to find the new set IDs for any symbol set in the original.\nremapped_symbol_map* remapped_symbol_map::deduplicate(const symbol_map& source) {\n \/\/ Map of symbol ranges to the symbol sets in the original that contain them\n sets_for_range setsContainingRange;\n \n \/\/ Iterate through the sets in the source\n for (symbol_map::iterator symSet = source.begin(); symSet != source.end(); symSet++) {\n \/\/ Add this into the sets containing this range\n add_set(setsContainingRange, symSet->first, symSet->second);\n }\n \n \/\/ Create the result\n remapped_symbol_map* newSet = new remapped_symbol_map();\n \n \/\/ Create a new set for each range we got in the previous step\n for (sets_for_range::iterator it = setsContainingRange.begin(); it != setsContainingRange.end(); it++) {\n newSet->identifier_for_symbols(it->first, it->second);\n }\n \n \/\/ This is the result\n return newSet;\n}\nRemoved debugging code\/\/\n\/\/ remapped_symbol_set.cpp\n\/\/ Parse\n\/\/\n\/\/ Created by Andrew Hunter on 26\/04\/2011.\n\/\/ Copyright 2011 __MyCompanyName__. All rights reserved.\n\/\/\n\n#include \n#include \n#include \n\n#include \"remapped_symbol_map.h\"\n#include \"range.h\"\n\nusing namespace std;\nusing namespace dfa;\n\n\/\/\/ \\brief Empty symbol set\nconst remapped_symbol_map::new_symbols remapped_symbol_map::s_NoSymbols;\n\n\/\/\/ \\brief Generates an empty remapped symbol map\nremapped_symbol_map::remapped_symbol_map() {\n}\n\n\/\/\/ \\brief Copy constructor\nremapped_symbol_map::remapped_symbol_map(const remapped_symbol_map& copyFrom) \n: m_OldToNew(copyFrom.m_OldToNew) {\n}\n\n\/\/\/ \\brief Finds or adds an identifier for the specified symbol, adding the specified set of new symbols as the new symbols\nint remapped_symbol_map::identifier_for_symbols(const symbol_set& symbols, const new_symbols& newSymbols) {\n \/\/ Get the set ID for these symbols\n int setId = symbol_map::identifier_for_symbols(symbols);\n \n \/\/ Try to look up the existing set\n old_to_new_map::iterator existing = m_OldToNew.find(setId);\n \n if (existing == m_OldToNew.end()) {\n \/\/ Just add these symbols\n m_OldToNew[setId] = newSymbols;\n } else {\n \/\/ Merge the sets\n for (new_symbols::iterator it = newSymbols.begin(); it != newSymbols.end(); it++) {\n existing->second.insert(*it);\n }\n }\n \n \/\/ Return this as the result\n return setId;\n}\n\n\/\/\/ \\brief Range of symbols\ntypedef range symbol_range;\n\n\/\/\/ \\brief Type mapping symbol ranges to the sets that contain them\ntypedef map, symbol_range::sort_by_lower > sets_for_range;\n\n\/\/\/ \\brief Splits a range that exists in sets into two.\n\/\/\/\n\/\/\/ We end up with two ranges: lower..splitPoint and splitPoint..upper\n\/\/\/ Returns an iterator for the start of the new ranges\nstatic sets_for_range::iterator split(sets_for_range& sets, symbol_range original, int splitPoint) {\n \/\/ Get the values for this range\n set values = sets[original];\n \n \/\/ Remove the original range\n sets.erase(original);\n \n \/\/ Create the split ranges\n sets[symbol_range(splitPoint, original.upper())] = values;\n sets_for_range::iterator result = sets.insert(sets_for_range::value_type(symbol_range(original.lower(), splitPoint), values)).first;\n return result;\n}\n\n\/\/\/ \\brief Adds the ranges in a particular symbol set \nstatic void add_set(sets_for_range& sets, const symbol_set& symbols, int identifier) {\n \/\/ Iterate through the ranges in this set\n for (symbol_set::iterator range = symbols.begin(); range != symbols.end(); range++) {\n \/\/ Find the first item in the set whose lower bound is >= this range\n sets_for_range::iterator firstGreaterThan = sets.lower_bound(*range);\n \n \/\/ If this isn't at the beginning, then it's possible that this set overlaps the preceeding set\n if (firstGreaterThan != sets.begin()) {\n \/\/ Get the previous set\n sets_for_range::iterator preceeding = firstGreaterThan;\n preceeding--;\n \n \/\/ See if there's an overlap\n if (preceeding->first.upper() >= range->lower()) {\n \/\/ Start from the preceeding set if they do\n firstGreaterThan = preceeding;\n }\n }\n \n \/\/ If we're at the end of the list here, then this is an entirely new range\n \/\/ This is also a new range if the item at firstGreaterThan doesn't overlap the range\n \/\/ Finally, we can just add to the set for a particular range if we get an exact match\n if (firstGreaterThan == sets.end() || !firstGreaterThan->first.overlaps(*range) || firstGreaterThan->first == *range) {\n \/\/ Just add this range\n sets[*range].insert(identifier);\n continue;\n }\n\n \/\/ We've got some overlap, but it's not exact\n symbol_range remaining = *range; \/\/ Range of characters remaining to merge in\n set justUs; \/\/ Set containing only the new identifier\n \n justUs.insert(identifier);\n\n while (remaining.upper() != remaining.lower()) {\n \/\/ If we're at the end, we can just add the remaining set and stop\n if (firstGreaterThan == sets.end()) {\n sets[remaining] = justUs;\n break;\n }\n \n \/\/ If there's a gap between the remaining set and the current position, then fill it in\n if (firstGreaterThan->first.lower() > remaining.lower()) {\n int newUpper = firstGreaterThan->first.lower();\n \n \/\/ Insert a value to fill the gap\n firstGreaterThan = sets.insert(firstGreaterThan, sets_for_range::value_type(symbol_range(remaining.lower(), newUpper), justUs));\n \n \/\/ Adjust the remaining set\n remaining = symbol_range(newUpper, remaining.upper());\n \n \/\/ Want the value after the one we just inserted\n firstGreaterThan++;\n \n \/\/ Start again\n continue;\n }\n \n \/\/ If there's a gap between the lowest point in the range we're currently splitting and the current range, then split there\n if (firstGreaterThan->first.lower() < remaining.lower()) {\n \/\/ Split the ranges and move so that the lowest point matches\n firstGreaterThan = split(sets, firstGreaterThan->first, remaining.lower());\n firstGreaterThan++;\n }\n \n \/\/ If the current range ends beyond the end of the remaining set, then split it\n if (firstGreaterThan->first.upper() > remaining.upper()) {\n firstGreaterThan = split(sets, firstGreaterThan->first, remaining.upper());\n }\n \n \/\/ Current range should overlap the range specified by firstGreaterThan: add this identifier\n firstGreaterThan->second.insert(identifier);\n \n \/\/ Adjust the remaining set\n remaining = symbol_range(firstGreaterThan->first.upper(), remaining.upper());\n \n \/\/ Move on\n firstGreaterThan++;\n }\n }\n}\n\n\/\/\/ \\brief Factory method that generates a remapped symbol map by removing duplicates\n\/\/\/\n\/\/\/ This finds all the symbol sets that overlap in the original, and splits them up so that any given symbol is only in one set.\n\/\/\/ It sets up the remapping so it is possible to find the new set IDs for any symbol set in the original.\nremapped_symbol_map* remapped_symbol_map::deduplicate(const symbol_map& source) {\n \/\/ Map of symbol ranges to the symbol sets in the original that contain them\n sets_for_range setsContainingRange;\n \n \/\/ Iterate through the sets in the source\n for (symbol_map::iterator symSet = source.begin(); symSet != source.end(); symSet++) {\n \/\/ Add this into the sets containing this range\n add_set(setsContainingRange, symSet->first, symSet->second);\n }\n \n \/\/ Create the result\n remapped_symbol_map* newSet = new remapped_symbol_map();\n \n \/\/ Create a new set for each range we got in the previous step\n for (sets_for_range::iterator it = setsContainingRange.begin(); it != setsContainingRange.end(); it++) {\n newSet->identifier_for_symbols(it->first, it->second);\n }\n \n \/\/ This is the result\n return newSet;\n}\n<|endoftext|>"} {"text":"#include \"..\/..\/..\/..\/vowpalwabbit\/parser.h\"\n#include \"..\/..\/..\/..\/vowpalwabbit\/vw.h\"\n#include \"vw_VW.h\"\n\nvoid throw_java_exception(JNIEnv *env, const char* name, const char* msg) {\n jclass jc = env->FindClass(name);\n if (jc)\n env->ThrowNew (jc, msg);\n}\n\nvoid rethrow_cpp_exception_as_java_exception(JNIEnv *env) {\n try {\n throw;\n }\n catch(const std::bad_alloc& e) {\n throw_java_exception(env, \"java\/lang\/OutOfMemoryError\", e.what());\n }\n catch(const std::ios_base::failure& e) {\n throw_java_exception(env, \"java\/io\/IOException\", e.what());\n }\n catch(const std::exception& e) {\n const char* what = e.what();\n \/\/ It would appear that this text has changed between different boost variants\n std::string prefix1(\"unrecognised option\");\n std::string prefix2(\"unknown option\");\n\n std::cout << what << std::endl;\n\n if (std::string(what).substr(0, prefix1.size()) == prefix1 ||\n std::string(what).substr(0, prefix2.size()) == prefix2)\n throw_java_exception(env, \"java\/lang\/IllegalArgumentException\", what);\n else\n throw_java_exception(env, \"java\/lang\/Exception\", what);\n }\n catch (...) {\n throw_java_exception(env, \"java\/lang\/Error\", \"Unidentified exception => \"\n \"rethrow_cpp_exception_as_java_exception \"\n \"may require some completion...\");\n }\n}\n\nvw* getVW(jlong vwPtr) {\n return (vw*) vwPtr;\n}\n\nJNIEXPORT jlong JNICALL Java_vw_VW_initialize(JNIEnv *env, jobject obj, jstring command) {\n jlong vwPtr = 0;\n try {\n vwPtr = (jlong) VW::initialize(env->GetStringUTFChars(command, NULL));\n }\n catch(...) {\n rethrow_cpp_exception_as_java_exception(env);\n }\n return vwPtr;\n}\n\nJNIEXPORT jfloat JNICALL Java_vw_VW_predict(JNIEnv *env, jobject obj, jstring example_string, jboolean learn, jlong vwPtr) {\n float prediction = 0.0f;\n try {\n vw* vw = getVW(vwPtr);\n const char *utf_string = env->GetStringUTFChars(example_string, NULL);\n example *vec2 = VW::read_example(*vw, utf_string);\n if (learn)\n vw->l->learn(*vec2);\n else\n vw->l->predict(*vec2);\n if (vw->p->lp.parse_label == simple_label.parse_label)\n prediction = vec2->pred.scalar;\n else\n prediction = vec2->pred.multiclass;\n\n VW::finish_example(*vw, vec2);\n env->ReleaseStringUTFChars(example_string, utf_string);\n env->DeleteLocalRef(example_string);\n }\n catch (...) {\n rethrow_cpp_exception_as_java_exception(env);\n }\n return prediction;\n}\n\nJNIEXPORT jfloatArray JNICALL Java_vw_VW_batchPredict(JNIEnv *env, jobject obj, jobjectArray examples, jboolean learn, jlong vwPtr) {\n size_t len = env->GetArrayLength(examples);\n float* predictions = new float[len];\n for (size_t i=0; iGetObjectArrayElement(examples, i);\n predictions[i] = Java_vw_VW_predict(env, obj, example, learn, vwPtr);\n env->DeleteLocalRef(example);\n }\n jfloatArray jPredictions = env->NewFloatArray(len);\n env->SetFloatArrayRegion(jPredictions, 0, len, predictions);\n\n free(predictions);\n env->DeleteLocalRef(examples);\n return jPredictions;\n}\n\nJNIEXPORT void JNICALL Java_vw_VW_closeInstance(JNIEnv *env, jobject obj, jlong vwPtr) {\n try {\n VW::finish(*getVW(vwPtr));\n }\n catch(...) {\n rethrow_cpp_exception_as_java_exception(env);\n }\n}\nGetting all Java tests to pass in Travis#include \"..\/..\/..\/..\/vowpalwabbit\/parser.h\"\n#include \"..\/..\/..\/..\/vowpalwabbit\/vw.h\"\n#include \"vw_VW.h\"\n\nvoid throw_java_exception(JNIEnv *env, const char* name, const char* msg) {\n jclass jc = env->FindClass(name);\n if (jc)\n env->ThrowNew (jc, msg);\n}\n\nvoid rethrow_cpp_exception_as_java_exception(JNIEnv *env) {\n try {\n throw;\n }\n catch(const std::bad_alloc& e) {\n throw_java_exception(env, \"java\/lang\/OutOfMemoryError\", e.what());\n }\n catch(const std::ios_base::failure& e) {\n throw_java_exception(env, \"java\/io\/IOException\", e.what());\n }\n catch(const std::exception& e) {\n const char* what = e.what();\n std::string what_str = std::string(what);\n \/\/ It would appear that this text has changed between different boost variants\n std::string prefix1(\"unrecognised option\");\n std::string prefix2(\"unknown option\");\n\n std::cout << what_str << std::endl;\n std::cout << prefix2 << std::endl;\n std::cout << prefix2.size() << std::endl;\n std::cout << what_str.substr(0, prefix.size()) << std::endl;\n std::cout << what_str.substr(0, prefix2.size()) == prefix2 << std::endl;\n\n if (what_str.substr(0, prefix1.size()) == prefix1 ||\n what_str.substr(0, prefix2.size()) == prefix2)\n throw_java_exception(env, \"java\/lang\/IllegalArgumentException\", what);\n else\n throw_java_exception(env, \"java\/lang\/Exception\", what);\n }\n catch (...) {\n throw_java_exception(env, \"java\/lang\/Error\", \"Unidentified exception => \"\n \"rethrow_cpp_exception_as_java_exception \"\n \"may require some completion...\");\n }\n}\n\nvw* getVW(jlong vwPtr) {\n return (vw*) vwPtr;\n}\n\nJNIEXPORT jlong JNICALL Java_vw_VW_initialize(JNIEnv *env, jobject obj, jstring command) {\n jlong vwPtr = 0;\n try {\n vwPtr = (jlong) VW::initialize(env->GetStringUTFChars(command, NULL));\n }\n catch(...) {\n rethrow_cpp_exception_as_java_exception(env);\n }\n return vwPtr;\n}\n\nJNIEXPORT jfloat JNICALL Java_vw_VW_predict(JNIEnv *env, jobject obj, jstring example_string, jboolean learn, jlong vwPtr) {\n float prediction = 0.0f;\n try {\n vw* vw = getVW(vwPtr);\n const char *utf_string = env->GetStringUTFChars(example_string, NULL);\n example *vec2 = VW::read_example(*vw, utf_string);\n if (learn)\n vw->l->learn(*vec2);\n else\n vw->l->predict(*vec2);\n if (vw->p->lp.parse_label == simple_label.parse_label)\n prediction = vec2->pred.scalar;\n else\n prediction = vec2->pred.multiclass;\n\n VW::finish_example(*vw, vec2);\n env->ReleaseStringUTFChars(example_string, utf_string);\n env->DeleteLocalRef(example_string);\n }\n catch (...) {\n rethrow_cpp_exception_as_java_exception(env);\n }\n return prediction;\n}\n\nJNIEXPORT jfloatArray JNICALL Java_vw_VW_batchPredict(JNIEnv *env, jobject obj, jobjectArray examples, jboolean learn, jlong vwPtr) {\n size_t len = env->GetArrayLength(examples);\n float* predictions = new float[len];\n for (size_t i=0; iGetObjectArrayElement(examples, i);\n predictions[i] = Java_vw_VW_predict(env, obj, example, learn, vwPtr);\n env->DeleteLocalRef(example);\n }\n jfloatArray jPredictions = env->NewFloatArray(len);\n env->SetFloatArrayRegion(jPredictions, 0, len, predictions);\n\n free(predictions);\n env->DeleteLocalRef(examples);\n return jPredictions;\n}\n\nJNIEXPORT void JNICALL Java_vw_VW_closeInstance(JNIEnv *env, jobject obj, jlong vwPtr) {\n try {\n VW::finish(*getVW(vwPtr));\n }\n catch(...) {\n rethrow_cpp_exception_as_java_exception(env);\n }\n}\n<|endoftext|>"} {"text":"\/**\n * @file pelleg_moore_kmeans_impl.hpp\n * @author Ryan Curtin\n *\n * An implementation of Pelleg-Moore's 'blacklist' algorithm for k-means\n * clustering.\n *\/\n#ifndef __MLPACK_METHODS_KMEANS_PELLEG_MOORE_KMEANS_IMPL_HPP\n#define __MLPACK_METHODS_KMEANS_PELLEG_MOORE_KMEANS_IMPL_HPP\n\n#include \"pelleg_moore_kmeans.hpp\"\n#include \"pelleg_moore_kmeans_rules.hpp\"\n\nnamespace mlpack {\nnamespace kmeans {\n\ntemplate\nPellegMooreKMeans::PellegMooreKMeans(\n const MatType& dataset,\n MetricType& metric) :\n datasetOrig(dataset),\n dataset(tree::TreeTraits::RearrangesDataset ? datasetCopy :\n datasetOrig),\n metric(metric),\n distanceCalculations(0)\n{\n Timer::Start(\"tree_building\");\n\n \/\/ Copy the dataset, if necessary.\n if (tree::TreeTraits::RearrangesDataset)\n datasetCopy = datasetOrig;\n\n \/\/ Now build the tree. We don't need any mappings.\n tree = new TreeType(const_cast(this->dataset));\n\n Timer::Stop(\"tree_building\");\n}\n\ntemplate\nPellegMooreKMeans::~PellegMooreKMeans()\n{\n delete tree;\n}\n\n\/\/ Run a single iteration.\ntemplate\ndouble PellegMooreKMeans::Iterate(\n const arma::mat& centroids,\n arma::mat& newCentroids,\n arma::Col& counts)\n{\n newCentroids.zeros(centroids.n_rows, centroids.n_cols);\n counts.zeros(centroids.n_cols);\n\n \/\/ Create rules object.\n typedef PellegMooreKMeansRules RulesType;\n RulesType rules(dataset, centroids, newCentroids, counts, metric);\n\n \/\/ Use single-tree traverser.\n typename TreeType::template SingleTreeTraverser traverser(rules);\n\n \/\/ Now, do a traversal with a fake query index (since the query index is\n \/\/ irrelevant; we are checking each node with all clusters.\n traverser.Traverse(0, *tree);\n\n distanceCalculations += rules.DistanceCalculations();\n\n \/\/ Now, calculate how far the clusters moved, after normalizing them.\n double residual = 0.0;\n for (size_t c = 0; c < centroids.n_cols; ++c)\n {\n if (counts[c] == 0)\n {\n newCentroids.col(c).fill(DBL_MAX); \/\/ Should have happened anyway I think.\n }\n else\n {\n newCentroids.col(c) \/= counts(c);\n residual += std::pow(metric.Evaluate(centroids.col(c),\n newCentroids.col(c)), 2.0);\n }\n }\n\n return std::sqrt(residual);\n}\n\n} \/\/ namespace kmeans\n} \/\/ namespace mlpack\n\n#endif\nI suppose we should exercise at least some caution in the destructor.\/**\n * @file pelleg_moore_kmeans_impl.hpp\n * @author Ryan Curtin\n *\n * An implementation of Pelleg-Moore's 'blacklist' algorithm for k-means\n * clustering.\n *\/\n#ifndef __MLPACK_METHODS_KMEANS_PELLEG_MOORE_KMEANS_IMPL_HPP\n#define __MLPACK_METHODS_KMEANS_PELLEG_MOORE_KMEANS_IMPL_HPP\n\n#include \"pelleg_moore_kmeans.hpp\"\n#include \"pelleg_moore_kmeans_rules.hpp\"\n\nnamespace mlpack {\nnamespace kmeans {\n\ntemplate\nPellegMooreKMeans::PellegMooreKMeans(\n const MatType& dataset,\n MetricType& metric) :\n datasetOrig(dataset),\n dataset(tree::TreeTraits::RearrangesDataset ? datasetCopy :\n datasetOrig),\n metric(metric),\n distanceCalculations(0)\n{\n Timer::Start(\"tree_building\");\n\n \/\/ Copy the dataset, if necessary.\n if (tree::TreeTraits::RearrangesDataset)\n datasetCopy = datasetOrig;\n\n \/\/ Now build the tree. We don't need any mappings.\n tree = new TreeType(const_cast(this->dataset));\n\n Timer::Stop(\"tree_building\");\n}\n\ntemplate\nPellegMooreKMeans::~PellegMooreKMeans()\n{\n if (tree)\n delete tree;\n}\n\n\/\/ Run a single iteration.\ntemplate\ndouble PellegMooreKMeans::Iterate(\n const arma::mat& centroids,\n arma::mat& newCentroids,\n arma::Col& counts)\n{\n newCentroids.zeros(centroids.n_rows, centroids.n_cols);\n counts.zeros(centroids.n_cols);\n\n \/\/ Create rules object.\n typedef PellegMooreKMeansRules RulesType;\n RulesType rules(dataset, centroids, newCentroids, counts, metric);\n\n \/\/ Use single-tree traverser.\n typename TreeType::template SingleTreeTraverser traverser(rules);\n\n \/\/ Now, do a traversal with a fake query index (since the query index is\n \/\/ irrelevant; we are checking each node with all clusters.\n traverser.Traverse(0, *tree);\n\n distanceCalculations += rules.DistanceCalculations();\n\n \/\/ Now, calculate how far the clusters moved, after normalizing them.\n double residual = 0.0;\n for (size_t c = 0; c < centroids.n_cols; ++c)\n {\n if (counts[c] == 0)\n {\n newCentroids.col(c).fill(DBL_MAX); \/\/ Should have happened anyway I think.\n }\n else\n {\n newCentroids.col(c) \/= counts(c);\n residual += std::pow(metric.Evaluate(centroids.col(c),\n newCentroids.col(c)), 2.0);\n }\n }\n\n return std::sqrt(residual);\n}\n\n} \/\/ namespace kmeans\n} \/\/ namespace mlpack\n\n#endif\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"dns.h\"\n\n\/*\n * Decode\n *\/\nvoid Dns::decode(const char* buffer)\n{\n decode_hdr(buffer);\n buffer += hdr_offset;\n\n decode_qname(buffer);\n m_qType = get16bits(buffer);\n m_qClass = get16bits(buffer);\n \/\/std::cout << \"m_qName:\" << m_qName << \"\\n\";\n \/\/std::cout << \"m_qType:\" << m_qType << \"\\n\";\n \/\/std::cout << \"m_qClass:\" << m_qClass << \"\\n\";\n\n is_csubnet = false;\n if (dns_hdr.adcount)\n decode_additional(buffer);\n}\n\nvoid Dns::decode_hdr(const char* buffer)\n{\n dns_hdr = *(struct dnshdr*) buffer;\n\n\t\/\/dns_hdr.id = EXTRACT_16BITS(&dns_hdr.id);\n\tdns_hdr.qucount = EXTRACT_16BITS(&dns_hdr.qucount);\n\t\/\/dns_hdr.ancount = EXTRACT_16BITS(&dns_hdr.ancount);\n\t\/\/dns_hdr.aucount = EXTRACT_16BITS(&dns_hdr.aucount);\n\tdns_hdr.adcount = EXTRACT_16BITS(&dns_hdr.adcount);\n}\n\nvoid Dns::decode_qname(const char*& buffer)\n{\n int i;\n char c;\n\n m_qName = \"\";\n\n int length = *buffer++;\n while (length != 0) {\n for (i = 0; i < length; i++) {\n c = *buffer++;\n m_qName += c;\n }\n length = *buffer++;\n if (length != 0) m_qName += '.';\n }\n\n query_len = m_qName.length() + 2 + 4;\n}\n\nvoid Dns::decode_additional(const char* buffer)\n{\n opt = *(struct optrr*) buffer;\n opt.opt_type = EXTRACT_16BITS(&opt.opt_type);\n opt.opt_udpsize = EXTRACT_16BITS(&opt.opt_udpsize);\n opt.opt_ttl = EXTRACT_32BITS(&opt.opt_ttl);\n opt.rdlen = EXTRACT_16BITS(&opt.rdlen);\n \/*std::cout << \"name=\" << (uint16_t) opt.opt_name\n << \", type=\" << opt.opt_type\n << \", class=\" << opt.opt_udpsize\n << \", ttl=\" << opt.opt_ttl\n << \", rdlen=\" << opt.rdlen << \"\\n\";*\/\n if (opt.rdlen)\n decode_option(buffer + 11);\n}\n\nvoid Dns::decode_option(const char* p)\n{\n uint16_t tmp = *(uint16_t*) p;\n if (tmp == 0x0800) {\n is_csubnet = true;\n\n eo = *(struct edns0opt*) p;\n eo.opt_code = EXTRACT_16BITS(&eo.opt_code);\n eo.opt_len = EXTRACT_16BITS(&eo.opt_len);\n eo.family = EXTRACT_16BITS(&eo.family);\n inet_ntop(AF_INET, &eo.sub_addr, client_ip, 16);\n\n \/*std::cout << \"opt_code=\" << eo.opt_code\n << \", opt_len=\" << eo.opt_len\n << \", family=\" << eo.family\n << \", smask=\" << (uint16_t)eo.source_netmask\n << \", scropmask=\" << (uint16_t)eo.scope_netmask\n << \", client_ip=\" << client_ip << \"\\n\";*\/\n } else if (tmp == 0x0a00) {\n co = *(struct cookieopt*) p;\n co.opt_code = EXTRACT_16BITS(&co.opt_code);\n co.opt_len = EXTRACT_16BITS(&co.opt_len);\n }\n}\n\n\/*\n * Code\n *\/\nint Dns::code(char* buffer)\n{\n char* bufferBegin = buffer;\n char* start_hdr = buffer;\n uint32_t intip;\n\n domain_ip_len_ = domain_ip_.length();\n std::strncpy(cstr, domain_ip_.c_str(), domain_ip_len_);\n cstr[domain_ip_len_] = '\\0';\n\n dns_hdr.ancount = 0;\n\n \/\/code_hdr(buffer);\n \/\/buffer += hdr_offset;\n\n \/* Code Question section *\/\n buffer += hdr_offset + query_len;\n\n \/* Code Answer section *\/\n m_ra.r_zone = 0xc00c;\n m_ra.r_ttl = 0;\n m_ra.r_size = 4;\n\n char* p = std::strtok(cstr, \",\");\n while (p) {\n\t\tput16bits(buffer, m_ra.r_zone);\n\t\tput16bits(buffer, m_qType);\n\t\tput16bits(buffer, m_qClass);\n\t\tput32bits(buffer, m_ra.r_ttl);\n\t\tput16bits(buffer, m_ra.r_size);\n\n inet_pton(AF_INET, p, (void *)&intip);\n buffer[0] = (intip & 0xFF);\n buffer[1] = (intip & 0xFF00) >> 8;\n buffer[2] = (intip & 0xFF0000) >> 16;\n buffer[3] = (intip & 0xFF000000) >> 24;\n buffer += 4;\n\n dns_hdr.ancount++;\n if (dns_hdr.ancount >= 10) break;\n\n p = std::strtok(NULL, \",\");\n }\n\n \/* Code Additional section *\/\n if (dns_hdr.adcount) {\n buffer[0] = opt.opt_name;\n buffer++;\n put16bits(buffer, opt.opt_type);\n opt.opt_udpsize = 512;\n put16bits(buffer, opt.opt_udpsize);\n put32bits(buffer, opt.opt_ttl);\n\n if (opt.rdlen)\n opt.rdlen = 12;\n put16bits(buffer, opt.rdlen);\n \n\n if (opt.rdlen) {\n if (is_csubnet) {\n put16bits(buffer, eo.opt_code);\n put16bits(buffer, eo.opt_len);\n put16bits(buffer, eo.family);\n buffer[0] = eo.source_netmask;\n buffer[1] = eo.scope_netmask;\n buffer += 2;\n buffer[0] = (eo.sub_addr & 0xFF);\n buffer[1] = (eo.sub_addr & 0xFF00) >> 8;\n buffer[2] = (eo.sub_addr & 0xFF0000) >> 16;\n buffer[3] = (eo.sub_addr & 0xFF000000) >> 24;\n buffer += 4;\n } else {\n put16bits(buffer, co.opt_code);\n put16bits(buffer, co.opt_len);\n for (unsigned i = 0; i < 8; i++) {\n buffer[i] = co.client_cookie[i];\n }\n buffer += 8;\n }\n }\n }\n\n code_hdr(start_hdr);\n\n return (buffer - bufferBegin);\n}\n\nvoid Dns::code_hdr(char*& buffer)\n{\n\/\/\tdns_hdr.flags1 = 0x81;\n\/\/\tdns_hdr.flags2 = 0x80;\n\tdns_hdr.qucount\t= 1;\n\t\/\/dns_hdr.ancount\t= 1;\n\/\/\tdns_hdr.nscount\t= 0;\n\/\/\tdns_hdr.arcount\t= 0;\n\n\tbuffer += 2; \/\/ skip id\n\tbuffer[0] = 0x81;\n\tbuffer[1] = 0x80;\n\tbuffer += 2; \/\/ skip flags\n\tput16bits(buffer, dns_hdr.qucount);\n\tput16bits(buffer, dns_hdr.ancount);\n\t\/\/buffer += 4; \/\/ skip auth and add\n}\n\nvoid Dns::code_domain(char*& buffer, const std::string& domain)\n{\n int start(0); \/\/ indexes\n std::size_t end;\n\n while ((end = domain.find('.', start)) != std::string::npos) {\n *buffer++ = end - start; \/\/ label length octet\n for (unsigned i=start; iAdded edns experimental option code#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"dns.h\"\n\n\/*\n * Decode\n *\/\nvoid Dns::decode(const char* buffer)\n{\n decode_hdr(buffer);\n buffer += hdr_offset;\n\n decode_qname(buffer);\n m_qType = get16bits(buffer);\n m_qClass = get16bits(buffer);\n \/\/std::cout << \"m_qName:\" << m_qName << \"\\n\";\n \/\/std::cout << \"m_qType:\" << m_qType << \"\\n\";\n \/\/std::cout << \"m_qClass:\" << m_qClass << \"\\n\";\n\n is_csubnet = false;\n if (dns_hdr.adcount)\n decode_additional(buffer);\n}\n\nvoid Dns::decode_hdr(const char* buffer)\n{\n dns_hdr = *(struct dnshdr*) buffer;\n\n\t\/\/dns_hdr.id = EXTRACT_16BITS(&dns_hdr.id);\n\tdns_hdr.qucount = EXTRACT_16BITS(&dns_hdr.qucount);\n\t\/\/dns_hdr.ancount = EXTRACT_16BITS(&dns_hdr.ancount);\n\t\/\/dns_hdr.aucount = EXTRACT_16BITS(&dns_hdr.aucount);\n\tdns_hdr.adcount = EXTRACT_16BITS(&dns_hdr.adcount);\n}\n\nvoid Dns::decode_qname(const char*& buffer)\n{\n int i;\n char c;\n\n m_qName = \"\";\n\n int length = *buffer++;\n while (length != 0) {\n for (i = 0; i < length; i++) {\n c = *buffer++;\n m_qName += c;\n }\n length = *buffer++;\n if (length != 0) m_qName += '.';\n }\n\n query_len = m_qName.length() + 2 + 4;\n}\n\nvoid Dns::decode_additional(const char* buffer)\n{\n opt = *(struct optrr*) buffer;\n opt.opt_type = EXTRACT_16BITS(&opt.opt_type);\n opt.opt_udpsize = EXTRACT_16BITS(&opt.opt_udpsize);\n opt.opt_ttl = EXTRACT_32BITS(&opt.opt_ttl);\n opt.rdlen = EXTRACT_16BITS(&opt.rdlen);\n \/*std::cout << \"name=\" << (uint16_t) opt.opt_name\n << \", type=\" << opt.opt_type\n << \", class=\" << opt.opt_udpsize\n << \", ttl=\" << opt.opt_ttl\n << \", rdlen=\" << opt.rdlen << \"\\n\";*\/\n if (opt.rdlen)\n decode_option(buffer + 11);\n}\n\nvoid Dns::decode_option(const char* p)\n{\n uint16_t tmp = *(uint16_t*) p;\n if (tmp == 0x0800 || tmp == 0xfa50) {\n is_csubnet = true;\n\n eo = *(struct edns0opt*) p;\n eo.opt_code = EXTRACT_16BITS(&eo.opt_code);\n eo.opt_len = EXTRACT_16BITS(&eo.opt_len);\n eo.family = EXTRACT_16BITS(&eo.family);\n inet_ntop(AF_INET, &eo.sub_addr, client_ip, 16);\n\n \/*std::cout << \"opt_code=\" << eo.opt_code\n << \", opt_len=\" << eo.opt_len\n << \", family=\" << eo.family\n << \", smask=\" << (uint16_t)eo.source_netmask\n << \", scropmask=\" << (uint16_t)eo.scope_netmask\n << \", client_ip=\" << client_ip << \"\\n\";*\/\n } else if (tmp == 0x0a00) {\n co = *(struct cookieopt*) p;\n co.opt_code = EXTRACT_16BITS(&co.opt_code);\n co.opt_len = EXTRACT_16BITS(&co.opt_len);\n }\n}\n\n\/*\n * Code\n *\/\nint Dns::code(char* buffer)\n{\n char* bufferBegin = buffer;\n char* start_hdr = buffer;\n uint32_t intip;\n\n domain_ip_len_ = domain_ip_.length();\n std::strncpy(cstr, domain_ip_.c_str(), domain_ip_len_);\n cstr[domain_ip_len_] = '\\0';\n\n dns_hdr.ancount = 0;\n\n \/\/code_hdr(buffer);\n \/\/buffer += hdr_offset;\n\n \/* Code Question section *\/\n buffer += hdr_offset + query_len;\n\n \/* Code Answer section *\/\n m_ra.r_zone = 0xc00c;\n m_ra.r_ttl = 0;\n m_ra.r_size = 4;\n\n char* p = std::strtok(cstr, \",\");\n while (p) {\n\t\tput16bits(buffer, m_ra.r_zone);\n\t\tput16bits(buffer, m_qType);\n\t\tput16bits(buffer, m_qClass);\n\t\tput32bits(buffer, m_ra.r_ttl);\n\t\tput16bits(buffer, m_ra.r_size);\n\n inet_pton(AF_INET, p, (void *)&intip);\n buffer[0] = (intip & 0xFF);\n buffer[1] = (intip & 0xFF00) >> 8;\n buffer[2] = (intip & 0xFF0000) >> 16;\n buffer[3] = (intip & 0xFF000000) >> 24;\n buffer += 4;\n\n dns_hdr.ancount++;\n if (dns_hdr.ancount >= 10) break;\n\n p = std::strtok(NULL, \",\");\n }\n\n \/* Code Additional section *\/\n if (dns_hdr.adcount) {\n buffer[0] = opt.opt_name;\n buffer++;\n put16bits(buffer, opt.opt_type);\n opt.opt_udpsize = 512;\n put16bits(buffer, opt.opt_udpsize);\n put32bits(buffer, opt.opt_ttl);\n\n if (opt.rdlen)\n opt.rdlen = 12;\n put16bits(buffer, opt.rdlen);\n \n\n if (opt.rdlen) {\n if (is_csubnet) {\n put16bits(buffer, eo.opt_code);\n put16bits(buffer, eo.opt_len);\n put16bits(buffer, eo.family);\n buffer[0] = eo.source_netmask;\n buffer[1] = eo.scope_netmask;\n buffer += 2;\n buffer[0] = (eo.sub_addr & 0xFF);\n buffer[1] = (eo.sub_addr & 0xFF00) >> 8;\n buffer[2] = (eo.sub_addr & 0xFF0000) >> 16;\n buffer[3] = (eo.sub_addr & 0xFF000000) >> 24;\n buffer += 4;\n } else {\n put16bits(buffer, co.opt_code);\n put16bits(buffer, co.opt_len);\n for (unsigned i = 0; i < 8; i++) {\n buffer[i] = co.client_cookie[i];\n }\n buffer += 8;\n }\n }\n }\n\n code_hdr(start_hdr);\n\n return (buffer - bufferBegin);\n}\n\nvoid Dns::code_hdr(char*& buffer)\n{\n\/\/\tdns_hdr.flags1 = 0x81;\n\/\/\tdns_hdr.flags2 = 0x80;\n\tdns_hdr.qucount\t= 1;\n\t\/\/dns_hdr.ancount\t= 1;\n\/\/\tdns_hdr.nscount\t= 0;\n\/\/\tdns_hdr.arcount\t= 0;\n\n\tbuffer += 2; \/\/ skip id\n\tbuffer[0] = 0x81;\n\tbuffer[1] = 0x80;\n\tbuffer += 2; \/\/ skip flags\n\tput16bits(buffer, dns_hdr.qucount);\n\tput16bits(buffer, dns_hdr.ancount);\n\t\/\/buffer += 4; \/\/ skip auth and add\n}\n\nvoid Dns::code_domain(char*& buffer, const std::string& domain)\n{\n int start(0); \/\/ indexes\n std::size_t end;\n\n while ((end = domain.find('.', start)) != std::string::npos) {\n *buffer++ = end - start; \/\/ label length octet\n for (unsigned i=start; i"} {"text":"\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2013-2014.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include \n#include \n#include \n\nint main(){\n char input_buffer[64];\n\n while(true){\n print(\"thor> \");\n\n auto c = read_input(input_buffer, 63);\n\n if(input_buffer[c-1] == '\\n'){\n if(c == 1){\n print_line();\n continue;\n }\n\n input_buffer[c-1] = '\\0';\n\n if(str_equals(input_buffer, \"exit\")){\n exit(0);\n } else if(str_equals(input_buffer, \"long\")){\n \/\/TODO Remove this function when exec system is complete\n exec_and_wait(\"long\");\n } else if(str_equals(input_buffer, \"sleep\")){\n \/\/TODO Once better infrastrucure, parse command line and sleep the\n \/\/correct number of milliseconds\n sleep_ms(5000);\n } else {\n print_line(\"Unknown command\");\n }\n } else {\n \/\/TODO Once in good shape, just append to current input buffer\n }\n\n }\n}Clean\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2013-2014.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include \n#include \n#include \n\nint main(){\n char input_buffer[64];\n\n while(true){\n print(\"thor> \");\n\n auto c = read_input(input_buffer, 63);\n\n if(input_buffer[c-1] == '\\n'){\n if(c == 1){\n print_line();\n continue;\n }\n\n input_buffer[c-1] = '\\0';\n\n if(str_equals(input_buffer, \"exit\")){\n exit(0);\n } else if(str_equals(input_buffer, \"long\")){\n \/\/TODO Remove this function when exec system is complete\n exec_and_wait(\"long\");\n } else if(str_equals(input_buffer, \"sleep\")){\n \/\/TODO Once better infrastrucure, parse command line and sleep the\n \/\/correct number of milliseconds\n sleep_ms(5000);\n } else {\n print_line(\"Unknown command\");\n }\n } else {\n \/\/TODO Once in good shape, just append to current input buffer\n }\n }\n}<|endoftext|>"} {"text":"\/*\n Persons Model Item\n Represents one person in the model\n Copyright (C) 2012 Martin Klapetek \n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n\n#include \"persons-model-item.h\"\n#include \"persons-model-contact-item.h\"\n\n#include \n#include \n#include \n\nPersonsModelItem::PersonsModelItem(const QUrl &personUri)\n{\n setData(personUri, PersonsModel::UriRole);\n}\n\nQVariant PersonsModelItem::queryChildrenForRole(int role) const\n{\n for (int i = 0; i < rowCount(); i++) {\n QVariant value = child(i)->data(role);\n if (!value.isNull()) {\n return value;\n }\n }\n return QVariant();\n}\n\nQVariantList PersonsModelItem::queryChildrenForRoleList(int role) const\n{\n QVariantList ret;\n for (int i = 0; i < rowCount(); i++) {\n QVariant value = child(i)->data(role);\n if (!value.isNull()) {\n ret += value;\n }\n }\n return ret;\n}\n\nQVariant PersonsModelItem::data(int role) const\n{\n switch(role) {\n case PersonsModel::NameRole:\n case Qt::DisplayRole: {\n QVariant value = queryChildrenForRole(Qt::DisplayRole);\n if(value.isNull())\n return QString(\"PIMO:Person - %1\").arg(data(PersonsModel::UriRole).toString());\n else\n return value;\n }\n case PersonsModel::NickRole:\n return queryChildrenForRole(role);\n case PersonsModel::IMRole:\n case PersonsModel::PhoneRole:\n case PersonsModel::EmailRole:\n case PersonsModel::PhotoRole:\n return queryChildrenForRoleList(role);\n }\n\n return QStandardItem::data(role);\n}\nMake it possible to provide all person's contact id's\/*\n Persons Model Item\n Represents one person in the model\n Copyright (C) 2012 Martin Klapetek \n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n\n#include \"persons-model-item.h\"\n#include \"persons-model-contact-item.h\"\n\n#include \n#include \n#include \n\nPersonsModelItem::PersonsModelItem(const QUrl &personUri)\n{\n setData(personUri, PersonsModel::UriRole);\n}\n\nQVariant PersonsModelItem::queryChildrenForRole(int role) const\n{\n for (int i = 0; i < rowCount(); i++) {\n QVariant value = child(i)->data(role);\n if (!value.isNull()) {\n return value;\n }\n }\n return QVariant();\n}\n\nQVariantList PersonsModelItem::queryChildrenForRoleList(int role) const\n{\n QVariantList ret;\n for (int i = 0; i < rowCount(); i++) {\n QVariant value = child(i)->data(role);\n if (!value.isNull()) {\n ret += value;\n }\n }\n return ret;\n}\n\nQVariant PersonsModelItem::data(int role) const\n{\n switch(role) {\n case PersonsModel::NameRole:\n case Qt::DisplayRole: {\n QVariant value = queryChildrenForRole(Qt::DisplayRole);\n if(value.isNull())\n return QString(\"PIMO:Person - %1\").arg(data(PersonsModel::UriRole).toString());\n else\n return value;\n }\n case PersonsModel::NickRole:\n return queryChildrenForRole(role);\n case PersonsModel::IMRole:\n case PersonsModel::PhoneRole:\n case PersonsModel::EmailRole:\n case PersonsModel::PhotoRole:\n case PersonsModel::ContactIdRole:\n return queryChildrenForRoleList(role);\n }\n\n return QStandardItem::data(role);\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"parser.h\"\n\nnamespace claudia {\n\n\/*\n * multiline support missing in most environments; parse line-by-line\n * see: http:\/\/cplusplus.github.io\/LWG\/lwg-active.html#2343\n *\/\nparser::parser(std::istream& in, const std::string& format)\n{\n std::vector lines;\n\n for (std::string line; std::getline(in, line);)\n lines.emplace_back(std::move(line));\n\n const boost::regex pattern{format, boost::regex::optimize};\n boost::smatch match;\n\n auto it = std::make_move_iterator(std::begin(lines));\n auto end = std::make_move_iterator(std::end(lines));\n\n \/* exception safe parsing *\/\n decltype(diagnostics_) local;\n\n \/* non-matches are silently ignored *\/\n std::for_each(it, end, [&](std::string line) {\n if (boost::regex_search(std::move(line), match, pattern))\n local.emplace_back(match[1], std::stoull(match[2]), std::stoull(match[3]), match[4], match[5]);\n });\n\n \/* no std::set -- this way it's more memory friendly *\/\n boost::erase(local, boost::unique(boost::sort(local)));\n\n diagnostics_ = std::move(local);\n}\n\nvoid parser::report(std::ostream& out, bool summary) const\n{\n boost::property_tree::ptree root;\n\n if (summary)\n root.add_child(\"summary\", do_summary());\n\n root.add_child(\"diagnostics\", do_report());\n\n boost::property_tree::write_json(out, root);\n}\n\nboost::property_tree::ptree parser::do_summary() const\n{\n boost::property_tree::ptree root;\n\n \/\/ XXX: statistics\n \/\/ root.put(k, v);\n\n return root;\n}\n\nboost::property_tree::ptree parser::do_report() const\n{\n boost::property_tree::ptree root;\n\n for (const auto diagnostic : diagnostics_)\n root.push_back(std::make_pair(\"\", diagnostic.report()));\n\n return root;\n}\n}\nDetect user-provided format mismatch on sub-match extraction#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"parser.h\"\n\nnamespace claudia {\n\n\/*\n * multiline support missing in most environments; parse line-by-line\n * see: http:\/\/cplusplus.github.io\/LWG\/lwg-active.html#2343\n *\/\nparser::parser(std::istream& in, const std::string& format)\n{\n std::vector lines;\n\n for (std::string line; std::getline(in, line);)\n lines.emplace_back(std::move(line));\n\n const boost::regex pattern{format, boost::regex::optimize};\n boost::smatch match;\n\n auto it = std::make_move_iterator(std::begin(lines));\n auto end = std::make_move_iterator(std::end(lines));\n\n \/* exception safe parsing *\/\n decltype(diagnostics_) local;\n\n \/* non-matches are silently ignored *\/\n std::for_each(it, end, [&](std::string line) {\n if (boost::regex_search(std::move(line), match, pattern)) {\n \/* 0th sub-match is entire matched expression *\/\n if (match.size() - 1 != 5)\n throw std::runtime_error{\"bad format: five groups required: file, line, column, message, flag\"};\n\n local.emplace_back(match[1], std::stoull(match[2]), std::stoull(match[3]), match[4], match[5]);\n }\n });\n\n \/* no std::set -- this way it's more memory friendly *\/\n boost::erase(local, boost::unique(boost::sort(local)));\n\n diagnostics_ = std::move(local);\n}\n\nvoid parser::report(std::ostream& out, bool summary) const\n{\n boost::property_tree::ptree root;\n\n if (summary)\n root.add_child(\"summary\", do_summary());\n\n root.add_child(\"diagnostics\", do_report());\n\n boost::property_tree::write_json(out, root);\n}\n\nboost::property_tree::ptree parser::do_summary() const\n{\n boost::property_tree::ptree root;\n\n \/\/ XXX: statistics\n \/\/ root.put(k, v);\n\n return root;\n}\n\nboost::property_tree::ptree parser::do_report() const\n{\n boost::property_tree::ptree root;\n\n for (const auto diagnostic : diagnostics_)\n root.push_back(std::make_pair(\"\", diagnostic.report()));\n\n return root;\n}\n}\n<|endoftext|>"} {"text":"\/*\n * fPls - playlist handler for fIcy\n * Copyright(c) 2004-2008 of wave++ (Yuri D'Elia) \n * Distributed under GNU LGPL without ANY warranty.\n *\/\n\n\/\/ local headers\n#include \"fIcy.hh\"\n#include \"msg.hh\"\n#include \"htfollow.hh\"\n#include \"plsparse.hh\"\n#include \"tmparse.hh\"\n#include \"authparse.hh\"\nusing std::string;\nusing std::list;\nusing std::map;\n\n\/\/ system headers\n#include \nusing std::ifstream;\n\n#include \nusing std::istringstream;\n\n#include \nusing std::cout;\n\n#include \nusing std::auto_ptr;\n\n#include \nusing std::runtime_error;\n\n\/\/ c system headers\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n\/*\n * Parameters handling\n *\/\nclass Params\n{\npublic:\n explicit\n Params(int argc, char* argv[]);\n\n ~Params() throw()\n {\n if(fIcyParams)\n delete[] fIcyParams;\n }\n\n\n const char* uri;\n const char** fIcyParams;\n size_t urlPos;\n size_t timePos;\n size_t maxRetries;\n long maxLoops;\n time_t waitSecs;\n time_t maxTime;\n time_t idleTime;\n size_t maxFollow;\n char* daemonize;\n char* auth;\n Http::Auth authData;\n bool help;\n};\n\n\nParams::Params(int argc, char* argv[])\n{\n \/\/ defaults\n prg = argv[0];\n maxRetries = fIcy::maxRetries;\n maxLoops = fIcy::maxLoops;\n waitSecs = fIcy::waitSecs;\n maxTime = 0;\n maxFollow = fIcy::maxFollow;\n idleTime = 0;\n verbose = help = false;\n daemonize = NULL;\n auth = NULL;\n\n \/\/ locals\n const char* path = \"fIcy\";\n const char* maxFollowBuf = NULL;\n const char* idleTimeBuf = NULL;\n int arg;\n\n \/\/ let's again put a bit of SHAME... those FSC**BEEP GNU extensions.\n \/\/ WHY _NOT_ BEING POSIXLY_CORRECT BY DEFAULT EH? oooh, \"features\"! I see.\n while((arg = getopt(argc, argv, \"+P:R:L:T:M:l:d:a:vhi:\")) != -1)\n switch(arg)\n {\n case 'P':\n path = optarg;\n break;\n\n case 'R':\n maxRetries = strtoul(optarg, NULL, 0);\n break;\n\n case 'L':\n maxLoops = strtol(optarg, NULL, 0);\n break;\n\n case 'T':\n waitSecs = tmParse(optarg);\n break;\n\n case 'M':\n maxTime = tmParse(optarg);\n break;\n\n case 'l':\n maxFollowBuf = optarg;\n maxFollow = strtol(optarg, NULL, 0);\n break;\n\n case 'd':\n daemonize = optarg;\n break;\n\n case 'h':\n help = true;\n break;\n\n case 'a':\n auth = optarg;\n break;\n\n case 'v':\n verbose = true;\n break;\n\n case 'i':\n idleTimeBuf = optarg;\n idleTime = tmParse(optarg);\n break;\n }\n\n \/\/ fetch authentication tokens immediately to avoid further requests\n if(auth)\n authParse(authData, auth);\n\n \/\/ playlist\n argc -= optind;\n uri = argv[optind++];\n\n \/\/ fIcy parameters\n if(--argc >= 0)\n {\n fIcyParams = new const char*[argc + 13];\n fIcyParams[0] = path;\n arg = 1;\n\n \/\/ parameters we allow to override\n if(auth)\n {\n fIcyParams[arg++] = \"-a\";\n fIcyParams[arg++] = auth;\n }\n if(maxFollowBuf)\n {\n fIcyParams[arg++] = \"-l\";\n fIcyParams[arg++] = maxFollowBuf;\n }\n if(idleTimeBuf)\n {\n fIcyParams[arg++] = \"-i\";\n fIcyParams[arg++] = idleTimeBuf;\n }\n\n \/\/ forward other parameters\n for(int i = 1; i <= argc; ++i)\n fIcyParams[arg++] = argv[optind++];\n\n \/\/ imposed parameters\n fIcyParams[arg++] = \"-M\";\n timePos = arg++;\n\n if(daemonize)\n fIcyParams[arg++] = \"-d\";\n\n fIcyParams[arg++] = \"--\";\n urlPos = arg++;\n\n fIcyParams[arg++] = NULL;\n }\n else\n fIcyParams = NULL;\n}\n\n\nvoid\nshow_help()\n{\n cout << prg << fIcy::fPlsHelp << prg << \" v\" << fIcy::version <<\n \" is\\n\" << fIcy::copyright;\n}\n\n\nvoid\nload_file(string& out, const char* file)\n{\n ifstream in(file);\n if(!in)\n throw runtime_error(string(\"cannot open \") + file);\n\n \/\/ load the file\n char buf[fIcy::bufSz];\n\n do\n {\n in.read(buf, sizeof(buf));\n out.append(buf, in.gcount());\n }\n while(in);\n\n if(!in.eof())\n throw runtime_error(string(\"errors while reading from \") + file);\n}\n\n\nvoid\nload_url(string& out, const URL& url, const Params& params)\n{\n \/\/ setup headers\n Http::Header qHeaders;\n qHeaders.push_back(fIcy::userAgent);\n if(params.auth)\n qHeaders.push_back(params.authData.basicHeader());\n\n \/\/ connection\n map pReply;\n auto_ptr s(htFollow(pReply, url, qHeaders,\n\t params.maxFollow, params.idleTime,\n\t params.maxRetries, params.waitSecs));\n\n \/\/ load the file\n char buf[fIcy::bufSz];\n size_t ret;\n\n while((ret = s->read(buf, sizeof(buf))) > 0)\n out.append(buf, ret);\n}\n\n\nvoid\nload_list(string& buf, const char* uri, const Params& params)\n{\n URL url(uri);\n\n if(url.proto == Http::Proto::proto)\n load_url(buf, url, params);\n else if(!url.proto.size())\n {\n msg(\"loading playlist from %s\", uri);\n load_file(buf, uri);\n }\n else\n throw runtime_error(string(\"unknown protocol \") + url.proto);\n}\n\n\n\/\/ exec fIcy and return the exit code\nint\nexec_fIcy(Params& params, const time_t maxTime, const char* stream)\n{\n const char** args = params.fIcyParams;\n char buf[16];\n snprintf(buf, sizeof(buf), \"%lu\", maxTime);\n args[params.timePos] = buf;\n args[params.urlPos] = stream;\n int ret;\n\n switch(fork())\n {\n case -1:\n err(\"cannot fork\");\n return Exit::args;\n\n case 0:\n execvp(args[0], const_cast(args));\n err(\"cannot exec fIcy: %s\", strerror(errno));\n exit(Exit::args);\n }\n\n wait(&ret);\n return (WIFEXITED(ret)? WEXITSTATUS(ret): Exit::args);\n}\n\n\nvoid\ndaemonize(const char* logFile)\n{\n int fd;\n\n \/\/ ensure correctness before daemonization\n if(logFile)\n if((fd = open(logFile, O_WRONLY | O_APPEND | O_CREAT, 0666)) == -1)\n throw runtime_error((string(\"cannot open log file \") + logFile).c_str());\n\n \/\/ daemonize\n#ifdef __sgi\n if(_daemonize(0, fd, -1, -1) == -1)\n#else\n if(daemon(0, 0) == -1)\n#endif\n throw runtime_error(\"cannot daemonize process\");\n\n \/\/ fix stderr\n if(logFile)\n dup2(fd, STDERR_FILENO);\n}\n\n\nint\nmain(int argc, char* argv[]) try\n{\n \/\/ initialize\n Params params(argc, argv);\n if(!params.uri && !params.help)\n {\n err(\"bad parameters; see %s -h\", prg);\n return Exit::args;\n }\n if(params.help)\n {\n show_help();\n return Exit::args;\n }\n\n time_t start(time(NULL));\n time_t resTime(params.maxTime);\n\n \/\/ fetch and parse the playlist\n list playlist;\n {\n string buf;\n load_list(buf, params.uri, params);\n istringstream stream(buf);\n plsParse(playlist, stream);\n }\n msg(\"loaded %d elements\", playlist.size());\n\n \/\/ daemonize now if requested\n if(params.daemonize)\n daemonize(params.daemonize);\n\n \/\/ main loop\n for(size_t loop = 0; static_cast(loop) != params.maxLoops; ++loop)\n {\n for(list::const_iterator it = playlist.begin();\n\tit != playlist.end(); ++it)\n {\n for(size_t retry = 0; retry != params.maxRetries; ++retry)\n {\n\t\/\/ sweet dreams on temporary failures\n\tif(loop || it != playlist.begin())\n\t sleep(params.waitSecs);\n\n\t\/\/ residual playing time\n\tif(params.maxTime)\n\t{\n\t time_t d(time(NULL) - start);\n\t if(d >= params.maxTime)\n\t return Exit::success;\n\t resTime = params.maxTime - d;\n\t}\n\n\tmsg(\"stream %s: retry %d of loop %d\", it->c_str(), retry + 1, loop + 1);\n\n\tint ret = exec_fIcy(params, resTime, it->c_str());\n\tif(ret == Exit::args)\n\t return Exit::fail;\n\n\t\/\/ check for success after maxTime\n\tif(ret == Exit::success)\n\t break;\n }\n }\n }\n\n return Exit::success;\n}\ncatch(runtime_error& err)\n{\n ::err(\"%s\", err.what());\n return Exit::fail;\n}\ncatch(...)\n{\n err(\"unknown error, aborting\");\n abort();\n}\nfPls: sleep the defined amount when retrying.\/*\n * fPls - playlist handler for fIcy\n * Copyright(c) 2004-2008 of wave++ (Yuri D'Elia) \n * Distributed under GNU LGPL without ANY warranty.\n *\/\n\n\/\/ local headers\n#include \"fIcy.hh\"\n#include \"msg.hh\"\n#include \"htfollow.hh\"\n#include \"plsparse.hh\"\n#include \"tmparse.hh\"\n#include \"authparse.hh\"\nusing std::string;\nusing std::list;\nusing std::map;\n\n\/\/ system headers\n#include \nusing std::ifstream;\n\n#include \nusing std::istringstream;\n\n#include \nusing std::cout;\n\n#include \nusing std::auto_ptr;\n\n#include \nusing std::runtime_error;\n\n\/\/ c system headers\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n\/*\n * Parameters handling\n *\/\nclass Params\n{\npublic:\n explicit\n Params(int argc, char* argv[]);\n\n ~Params() throw()\n {\n if(fIcyParams)\n delete[] fIcyParams;\n }\n\n\n const char* uri;\n const char** fIcyParams;\n size_t urlPos;\n size_t timePos;\n size_t maxRetries;\n long maxLoops;\n time_t waitSecs;\n time_t maxTime;\n time_t idleTime;\n size_t maxFollow;\n char* daemonize;\n char* auth;\n Http::Auth authData;\n bool help;\n};\n\n\nParams::Params(int argc, char* argv[])\n{\n \/\/ defaults\n prg = argv[0];\n maxRetries = fIcy::maxRetries;\n maxLoops = fIcy::maxLoops;\n waitSecs = fIcy::waitSecs;\n maxTime = 0;\n maxFollow = fIcy::maxFollow;\n idleTime = 0;\n verbose = help = false;\n daemonize = NULL;\n auth = NULL;\n\n \/\/ locals\n const char* path = \"fIcy\";\n const char* maxFollowBuf = NULL;\n const char* idleTimeBuf = NULL;\n int arg;\n\n \/\/ let's again put a bit of SHAME... those FSC**BEEP GNU extensions.\n \/\/ WHY _NOT_ BEING POSIXLY_CORRECT BY DEFAULT EH? oooh, \"features\"! I see.\n while((arg = getopt(argc, argv, \"+P:R:L:T:M:l:d:a:vhi:\")) != -1)\n switch(arg)\n {\n case 'P':\n path = optarg;\n break;\n\n case 'R':\n maxRetries = strtoul(optarg, NULL, 0);\n break;\n\n case 'L':\n maxLoops = strtol(optarg, NULL, 0);\n break;\n\n case 'T':\n waitSecs = tmParse(optarg);\n break;\n\n case 'M':\n maxTime = tmParse(optarg);\n break;\n\n case 'l':\n maxFollowBuf = optarg;\n maxFollow = strtol(optarg, NULL, 0);\n break;\n\n case 'd':\n daemonize = optarg;\n break;\n\n case 'h':\n help = true;\n break;\n\n case 'a':\n auth = optarg;\n break;\n\n case 'v':\n verbose = true;\n break;\n\n case 'i':\n idleTimeBuf = optarg;\n idleTime = tmParse(optarg);\n break;\n }\n\n \/\/ fetch authentication tokens immediately to avoid further requests\n if(auth)\n authParse(authData, auth);\n\n \/\/ playlist\n argc -= optind;\n uri = argv[optind++];\n\n \/\/ fIcy parameters\n if(--argc >= 0)\n {\n fIcyParams = new const char*[argc + 13];\n fIcyParams[0] = path;\n arg = 1;\n\n \/\/ parameters we allow to override\n if(auth)\n {\n fIcyParams[arg++] = \"-a\";\n fIcyParams[arg++] = auth;\n }\n if(maxFollowBuf)\n {\n fIcyParams[arg++] = \"-l\";\n fIcyParams[arg++] = maxFollowBuf;\n }\n if(idleTimeBuf)\n {\n fIcyParams[arg++] = \"-i\";\n fIcyParams[arg++] = idleTimeBuf;\n }\n\n \/\/ forward other parameters\n for(int i = 1; i <= argc; ++i)\n fIcyParams[arg++] = argv[optind++];\n\n \/\/ imposed parameters\n fIcyParams[arg++] = \"-M\";\n timePos = arg++;\n\n if(daemonize)\n fIcyParams[arg++] = \"-d\";\n\n fIcyParams[arg++] = \"--\";\n urlPos = arg++;\n\n fIcyParams[arg++] = NULL;\n }\n else\n fIcyParams = NULL;\n}\n\n\nvoid\nshow_help()\n{\n cout << prg << fIcy::fPlsHelp << prg << \" v\" << fIcy::version <<\n \" is\\n\" << fIcy::copyright;\n}\n\n\nvoid\nload_file(string& out, const char* file)\n{\n ifstream in(file);\n if(!in)\n throw runtime_error(string(\"cannot open \") + file);\n\n \/\/ load the file\n char buf[fIcy::bufSz];\n\n do\n {\n in.read(buf, sizeof(buf));\n out.append(buf, in.gcount());\n }\n while(in);\n\n if(!in.eof())\n throw runtime_error(string(\"errors while reading from \") + file);\n}\n\n\nvoid\nload_url(string& out, const URL& url, const Params& params)\n{\n \/\/ setup headers\n Http::Header qHeaders;\n qHeaders.push_back(fIcy::userAgent);\n if(params.auth)\n qHeaders.push_back(params.authData.basicHeader());\n\n \/\/ connection\n map pReply;\n auto_ptr s(htFollow(pReply, url, qHeaders,\n\t params.maxFollow, params.idleTime,\n\t params.maxRetries, params.waitSecs));\n\n \/\/ load the file\n char buf[fIcy::bufSz];\n size_t ret;\n\n while((ret = s->read(buf, sizeof(buf))) > 0)\n out.append(buf, ret);\n}\n\n\nvoid\nload_list(string& buf, const char* uri, const Params& params)\n{\n URL url(uri);\n\n if(url.proto == Http::Proto::proto)\n load_url(buf, url, params);\n else if(!url.proto.size())\n {\n msg(\"loading playlist from %s\", uri);\n load_file(buf, uri);\n }\n else\n throw runtime_error(string(\"unknown protocol \") + url.proto);\n}\n\n\n\/\/ exec fIcy and return the exit code\nint\nexec_fIcy(Params& params, const time_t maxTime, const char* stream)\n{\n const char** args = params.fIcyParams;\n char buf[16];\n snprintf(buf, sizeof(buf), \"%lu\", maxTime);\n args[params.timePos] = buf;\n args[params.urlPos] = stream;\n int ret;\n\n switch(fork())\n {\n case -1:\n err(\"cannot fork\");\n return Exit::args;\n\n case 0:\n execvp(args[0], const_cast(args));\n err(\"cannot exec fIcy: %s\", strerror(errno));\n exit(Exit::args);\n }\n\n wait(&ret);\n return (WIFEXITED(ret)? WEXITSTATUS(ret): Exit::args);\n}\n\n\nvoid\ndaemonize(const char* logFile)\n{\n int fd;\n\n \/\/ ensure correctness before daemonization\n if(logFile)\n if((fd = open(logFile, O_WRONLY | O_APPEND | O_CREAT, 0666)) == -1)\n throw runtime_error((string(\"cannot open log file \") + logFile).c_str());\n\n \/\/ daemonize\n#ifdef __sgi\n if(_daemonize(0, fd, -1, -1) == -1)\n#else\n if(daemon(0, 0) == -1)\n#endif\n throw runtime_error(\"cannot daemonize process\");\n\n \/\/ fix stderr\n if(logFile)\n dup2(fd, STDERR_FILENO);\n}\n\n\nint\nmain(int argc, char* argv[]) try\n{\n \/\/ initialize\n Params params(argc, argv);\n if(!params.uri && !params.help)\n {\n err(\"bad parameters; see %s -h\", prg);\n return Exit::args;\n }\n if(params.help)\n {\n show_help();\n return Exit::args;\n }\n\n time_t start(time(NULL));\n time_t resTime(params.maxTime);\n\n \/\/ fetch and parse the playlist\n list playlist;\n {\n string buf;\n load_list(buf, params.uri, params);\n istringstream stream(buf);\n plsParse(playlist, stream);\n }\n msg(\"loaded %d elements\", playlist.size());\n\n \/\/ daemonize now if requested\n if(params.daemonize)\n daemonize(params.daemonize);\n\n \/\/ main loop\n for(size_t loop = 0; static_cast(loop) != params.maxLoops; ++loop)\n {\n for(list::const_iterator it = playlist.begin();\n\tit != playlist.end(); ++it)\n {\n for(size_t retry = 0; retry != params.maxRetries; ++retry)\n {\n\t\/\/ sweet dreams on temporary failures\n\tif(loop || retry || it != playlist.begin())\n\t sleep(params.waitSecs);\n\n\t\/\/ residual playing time\n\tif(params.maxTime)\n\t{\n\t time_t d(time(NULL) - start);\n\t if(d >= params.maxTime)\n\t return Exit::success;\n\t resTime = params.maxTime - d;\n\t}\n\n\tmsg(\"stream %s: retry %d of loop %d\", it->c_str(), retry + 1, loop + 1);\n\n\tint ret = exec_fIcy(params, resTime, it->c_str());\n\tif(ret == Exit::args)\n\t return Exit::fail;\n\n\t\/\/ check for success after maxTime\n\tif(ret == Exit::success)\n\t break;\n }\n }\n }\n\n return Exit::success;\n}\ncatch(runtime_error& err)\n{\n ::err(\"%s\", err.what());\n return Exit::fail;\n}\ncatch(...)\n{\n err(\"unknown error, aborting\");\n abort();\n}\n<|endoftext|>"} {"text":"\/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-\n\nCopyright 2010, 2011, 2012, 2013, 2014, 2015\nRaffaello D. Di Napoli\n\nThis file is part of Abaclade.\n\nAbaclade is free software: you can redistribute it and\/or modify it under the terms of the GNU\nGeneral Public License as published by the Free Software Foundation, either version 3 of the\nLicense, or (at your option) any later version.\n\nAbaclade is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General\nPublic License for more details.\n\nYou should have received a copy of the GNU General Public License along with Abaclade. If not, see\n.\n--------------------------------------------------------------------------------------------------*\/\n\n#include \n#ifdef _ABACLADE_STL_MEMORY_HXX\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace abc { namespace _std {\n\nbad_weak_ptr::bad_weak_ptr() {\n}\n\n\/*virtual*\/ bad_weak_ptr::~bad_weak_ptr() {\n}\n\n\/*virtual*\/ char const * bad_weak_ptr::what() const \/*override*\/ {\n return \"abc::_std::bad_weak_ptr\";\n}\n\n}} \/\/namespace abc::_std\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace abc { namespace _std { namespace detail {\n\nshared_refcount::shared_refcount(unsigned cStrongRefs, unsigned cWeakRefs) :\n m_cStrongRefs(cStrongRefs),\n m_cWeakRefs(cWeakRefs + (cStrongRefs > 0 ? 1 : 0)) {\n}\n\n\/*virtual*\/ shared_refcount::~shared_refcount() {\n ABC_ASSERT(m_cStrongRefs == 0);\n ABC_ASSERT(m_cWeakRefs == 0);\n}\n\nvoid shared_refcount::add_strong_ref() {\n \/\/ Increment the count of strong references if non-zero; it it’s zero, the owned object is gone.\n unsigned cStrongRefsOld;\n do {\n cStrongRefsOld = m_cStrongRefs;\n if (cStrongRefsOld == 0) {\n throw bad_weak_ptr();\n }\n } while (!m_cStrongRefs.compare_exchange_strong(cStrongRefsOld, cStrongRefsOld + 1));\n}\n\n\/*virtual*\/ void * shared_refcount::get_deleter(type_info const & ti) const {\n ABC_UNUSED_ARG(ti);\n return nullptr;\n}\n\n\/*virtual*\/ void shared_refcount::delete_this() {\n delete this;\n}\n\n}}} \/\/namespace abc::_std::detail\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#endif \/\/ifdef _ABACLADE_STL_MEMORY_HXX\nFix use of atomics in abc::_std::detail::shared_refcount\/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-\n\nCopyright 2010, 2011, 2012, 2013, 2014, 2015\nRaffaello D. Di Napoli\n\nThis file is part of Abaclade.\n\nAbaclade is free software: you can redistribute it and\/or modify it under the terms of the GNU\nGeneral Public License as published by the Free Software Foundation, either version 3 of the\nLicense, or (at your option) any later version.\n\nAbaclade is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General\nPublic License for more details.\n\nYou should have received a copy of the GNU General Public License along with Abaclade. If not, see\n.\n--------------------------------------------------------------------------------------------------*\/\n\n#include \n#ifdef _ABACLADE_STL_MEMORY_HXX\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace abc { namespace _std {\n\nbad_weak_ptr::bad_weak_ptr() {\n}\n\n\/*virtual*\/ bad_weak_ptr::~bad_weak_ptr() {\n}\n\n\/*virtual*\/ char const * bad_weak_ptr::what() const \/*override*\/ {\n return \"abc::_std::bad_weak_ptr\";\n}\n\n}} \/\/namespace abc::_std\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace abc { namespace _std { namespace detail {\n\nshared_refcount::shared_refcount(unsigned cStrongRefs, unsigned cWeakRefs) :\n m_cStrongRefs(cStrongRefs),\n m_cWeakRefs(cWeakRefs + (cStrongRefs > 0 ? 1 : 0)) {\n}\n\n\/*virtual*\/ shared_refcount::~shared_refcount() {\n ABC_ASSERT(\n m_cStrongRefs.load() == 0,\n ABC_SL(\"shared_refcount being destructed with non-zero strong references!\")\n );\n ABC_ASSERT(\n m_cWeakRefs.load() == 0,\n ABC_SL(\"shared_refcount being destructed with non-zero weak references!\")\n );\n}\n\nvoid shared_refcount::add_strong_ref() {\n \/\/ Increment the count of strong references if non-zero; it it’s zero, the owned object is gone.\n unsigned cStrongRefsOld;\n do {\n cStrongRefsOld = m_cStrongRefs.load();\n if (cStrongRefsOld == 0) {\n throw bad_weak_ptr();\n }\n } while (!m_cStrongRefs.compare_exchange_strong(cStrongRefsOld, cStrongRefsOld + 1));\n}\n\n\/*virtual*\/ void * shared_refcount::get_deleter(type_info const & ti) const {\n ABC_UNUSED_ARG(ti);\n return nullptr;\n}\n\n\/*virtual*\/ void shared_refcount::delete_this() {\n delete this;\n}\n\n}}} \/\/namespace abc::_std::detail\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#endif \/\/ifdef _ABACLADE_STL_MEMORY_HXX\n<|endoftext|>"} {"text":"\/*\n * manager.cpp\n *\n * Created on: 23\/03\/2015\n *\n * =========================================================================\n * Copyright (C) 2015-, Daniele De Sensi (d.desensi.software@gmail.com)\n *\n * This file is part of AdaptiveFastFlow.\n *\n * AdaptiveFastFlow is free software: you can redistribute it and\/or\n * modify it under the terms of the Lesser GNU General Public\n * License as published by the Free Software Foundation, either\n * version 3 of the License, or (at your option) any later version.\n\n * AdaptiveFastFlow is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * Lesser GNU General Public License for more details.\n *\n * You should have received a copy of the Lesser GNU General Public\n * License along with AdaptiveFastFlow.\n * If not, see .\n *\n * =========================================================================\n *\/\n\n#include \".\/manager.hpp\"\n#include \"parameters.hpp\"\n#include \"predictors.hpp\"\n#include \".\/node.hpp\"\n#include \"utils.hpp\"\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#undef DEBUG\n#undef DEBUGB\n\n#ifdef DEBUG_MANAGER\n#define DEBUG(x) do { cerr << \"[Manager] \" << x << endl; } while (0)\n#define DEBUGB(x) do {x;} while(0)\n#else\n#define DEBUG(x)\n#define DEBUGB(x)\n#endif\n\nnamespace adpff{\n\nclass Parameters;\n\nusing namespace std;\nusing namespace ff;\nusing namespace mammut::cpufreq;\nusing namespace mammut::energy;\nusing namespace mammut::task;\nusing namespace mammut::topology;\nusing namespace mammut::utils;\n\ntemplate \nvoid ManagerFarm::setDomainToHighestFrequency(const Domain* domain){\n if(!domain->setGovernor(GOVERNOR_PERFORMANCE)){\n if(!domain->setGovernor(GOVERNOR_USERSPACE) ||\n !domain->setHighestFrequencyUserspace()){\n throw runtime_error(\"AdaptivityManagerFarm: Fatal error while \"\n \"setting highest frequency for sensitive \"\n \"emitter\/collector. Try to run it without \"\n \"sensitivity parameters.\");\n }\n }\n}\n\ntemplate \ndouble ManagerFarm::getPrimaryValue(const MonitoredSample& sample) const{\n switch(_p.contractType){\n case CONTRACT_PERF_UTILIZATION:{\n return sample.utilization;\n }break;\n case CONTRACT_PERF_BANDWIDTH:\n case CONTRACT_PERF_COMPLETION_TIME:{\n return sample.bandwidth;\n }break;\n case CONTRACT_POWER_BUDGET:{\n return sample.watts;\n }break;\n default:{\n return 0;\n }break;\n }\n}\n\ntemplate \ndouble ManagerFarm::getSecondaryValue(const MonitoredSample& sample) const{\n switch(_p.contractType){\n case CONTRACT_PERF_UTILIZATION:\n case CONTRACT_PERF_BANDWIDTH:\n case CONTRACT_PERF_COMPLETION_TIME:{\n return sample.watts;\n }break;\n case CONTRACT_POWER_BUDGET:{\n return sample.bandwidth;\n }break;\n default:{\n return 0;\n }break;\n }\n}\n\ntemplate \ndouble ManagerFarm::getPrimaryValue() const{\n return getPrimaryValue(_samples->average());\n}\n\ntemplate \ndouble ManagerFarm::getSecondaryValue() const{\n return getSecondaryValue(_samples->average());\n}\n\ntemplate \nbool ManagerFarm::terminated(){\n \/**\n * We do not need to wait if the emitter is terminated.\n * Indeed, if the workers terminated, the emitter surely terminated\n * too.\n *\/\n\n for(size_t i = 0; i < _activeWorkers.size(); i++){\n if(!_activeWorkers.at(i)->isTerminated()){\n return false;\n }else{\n DEBUG(\"Worker \" << i << \" terminated.\");\n }\n }\n\n if(_collector &&\n !_collector->isTerminated()){\n return false;\n }else{\n DEBUG(\"Collector terminated.\");\n }\n\n return true;\n}\n\ntemplate \nvoid ManagerFarm::changeKnobs(){\n KnobsValues values = _calibrator->getNextKnobsValues(getPrimaryValue(),\n getSecondaryValue(),\n _remainingTasks);\n if(values != _configuration.getRealValues()){\n _configuration.setValues(values);\n _activeWorkers = dynamic_cast(_configuration.getKnob(KNOB_TYPE_WORKERS))->getActiveWorkers();\n\n \/****************** Clean state ******************\/\n _lastStoredSampleMs = getMillisecondsTime();\n _samples->reset();\n if(_counter){\n _counter->reset();\n }\n _totalTasks = 0;\n }\n}\n\ntemplate \nvoid ManagerFarm::observe(){\n if(_p.observer){\n const KnobMapping* kMapping = dynamic_cast(_configuration.getKnob(KNOB_TYPE_MAPPING));\n _p.observer->observe(_lastStoredSampleMs,\n _configuration.getRealValue(KNOB_TYPE_WORKERS),\n _configuration.getRealValue(KNOB_TYPE_FREQUENCY),\n kMapping->getEmitterVirtualCore(),\n kMapping->getWorkersVirtualCore(),\n kMapping->getCollectorVirtualCore(),\n _samples->getLastSample().bandwidth,\n _samples->average().bandwidth,\n _samples->coefficientVariation().bandwidth,\n _samples->average().utilization,\n _samples->average().watts);\n }\n}\n\ntemplate \nvoid ManagerFarm::askForWorkersSamples(){\n for(size_t i = 0; i < _activeWorkers.size(); i++){\n _activeWorkers.at(i)->askForSample();\n }\n}\n\ntemplate \nvoid ManagerFarm::getWorkersSamples(WorkerSample& sample){\n AdaptiveNode* w;\n uint numActiveWorkers = _activeWorkers.size();\n sample = WorkerSample();\n\n for(size_t i = 0; i < numActiveWorkers; i++){\n WorkerSample tmp;\n w = _activeWorkers.at(i);\n w->getSampleResponse(tmp, _p.strategyPolling,\n _samples->average().latency);\n sample += tmp;\n }\n sample.loadPercentage \/= numActiveWorkers;\n sample.latency \/= numActiveWorkers;\n}\n\ntemplate \nvoid ManagerFarm::storeNewSample(){\n MonitoredSample sample;\n WorkerSample ws;\n Joules joules = 0.0;\n\n askForWorkersSamples();\n getWorkersSamples(ws);\n\n _totalTasks += ws.tasksCount;\n if(_p.contractType == CONTRACT_PERF_COMPLETION_TIME){\n if(_remainingTasks > ws.tasksCount){\n _remainingTasks -= ws.tasksCount;\n }else{\n _remainingTasks = 0;\n }\n }\n\n if(_counter){\n switch(_counter->getType()){\n case COUNTER_CPUS:{\n joules = ((CounterCpus*) _counter)->getJoulesCoresAll();\n }break;\n default:{\n joules = _counter->getJoules();\n }break;\n }\n }\n\n double now = getMillisecondsTime();\n double durationSecs = (now - _lastStoredSampleMs) \/ 1000.0;\n _lastStoredSampleMs = now;\n\n sample.watts = joules \/ durationSecs;\n sample.utilization = ws.loadPercentage;\n \/\/ ATTENTION: Bandwidth is not the number of task since the\n \/\/ last observation but the number of expected\n \/\/ tasks that will be processed in 1 second.\n \/\/ For this reason, if we sum all the bandwidths in\n \/\/ the result observation file, we may have an higher\n \/\/ number than the number of tasks.\n sample.bandwidth = ws.bandwidthTotal;\n sample.latency = ws.latency;\n\n if(_counter){\n _counter->reset();\n }\n _samples->add(sample);\n\n DEBUGB(samplesFile << *_samples << \"\\n\");\n}\n\ntemplate \nbool ManagerFarm::persist() const{\n bool r = false;\n switch(_p.strategyPersistence){\n case STRATEGY_PERSISTENCE_SAMPLES:{\n r = _samples->size() < _p.persistenceValue;\n }break;\n case STRATEGY_PERSISTENCE_TASKS:{\n r = _totalTasks < _p.persistenceValue;\n }break;\n case STRATEGY_PERSISTENCE_VARIATION:{\n const MonitoredSample& variation =\n _samples->coefficientVariation();\n r = getPrimaryValue(variation) < _p.persistenceValue &&\n getSecondaryValue(variation) < _p.persistenceValue;\n }break;\n }\n return r;\n}\n\ntemplate \nvoid ManagerFarm::initPredictors(){\n if(_p.strategyCalibration == STRATEGY_CALIBRATION_RANDOM){\n ; \/\/CREARE TODO: Ci deve sempre essere un calibratore\n }else{\n switch(_p.strategyPrediction){\n case STRATEGY_PREDICTION_SIMPLE:{\n _calibrator = new CalibratorDummy(_p, _configuration, _samples);\n }break;\n case STRATEGY_PREDICTION_REGRESSION_LINEAR:{\n _calibrator = new CalibratorLowDiscrepancy(_p, _configuration, _samples);\n }break;\n }\n }\n}\n\nstatic Parameters& validate(Parameters& p){\n ParametersValidation apv = p.validate();\n if(apv != VALIDATION_OK){\n throw runtime_error(\"Invalid adaptivity parameters: \" + std::to_string(apv));\n }\n return p;\n}\n\nstatic std::vector convertWorkers(svector w){\n std::vector r;\n for(size_t i = 0; i < w.size(); i++){\n r.push_back(dynamic_cast(w[i]));\n }\n return r;\n}\n\ntemplate \nManagerFarm::ManagerFarm(ff_farm* farm, Parameters parameters):\n _farm(farm),\n _p(validate(parameters)),\n _startTimeMs(0),\n _cpufreq(_p.mammut.getInstanceCpuFreq()),\n _counter(_p.mammut.getInstanceEnergy()->getCounter()),\n _task(_p.mammut.getInstanceTask()),\n _topology(_p.mammut.getInstanceTopology()),\n _emitter(dynamic_cast(_farm->getEmitter())),\n _collector(dynamic_cast(_farm->getCollector())),\n _activeWorkers(convertWorkers(_farm->getWorkers())),\n _configuration(_p, _emitter, _collector, _farm->getgt(), _activeWorkers),\n _samples(NULL),\n _totalTasks(0),\n _remainingTasks(0),\n _deadline(0),\n _lastStoredSampleMs(0),\n _calibrator(NULL){\n\n _samples = NULL;\n switch(_p.strategySmoothing){\n case STRATEGY_SMOOTHING_MOVING_AVERAGE:{\n _samples = new MovingAverageSimple(_p.smoothingFactor);\n }break;\n case STRATEGY_SMOOTHING_EXPONENTIAL:{\n _samples = new MovingAverageExponential(_p.smoothingFactor);\n }break;\n }\n\n DEBUGB(samplesFile.open(\"samples.csv\"));\n}\n\ntemplate \nManagerFarm::~ManagerFarm(){\n delete _samples;\n if(_calibrator){\n delete _calibrator;\n }\n DEBUGB(samplesFile.close());\n}\n\ntemplate \nvoid ManagerFarm::initNodesPreRun() {\n for (size_t i = 0; i < _activeWorkers.size(); i++) {\n _activeWorkers.at(i)->initPreRun(_p.mammut, _p.archData.ticksPerNs, NODE_TYPE_WORKER);\n }\n if (_emitter) {\n _emitter->initPreRun(_p.mammut, _p.archData.ticksPerNs, NODE_TYPE_EMITTER);\n } else {\n throw runtime_error(\"Emitter is needed to use the manager.\");\n }\n if (_collector) {\n _collector->initPreRun(_p.mammut, _p.archData.ticksPerNs, NODE_TYPE_COLLECTOR);\n }\n}\n\ntemplate \nvoid ManagerFarm::initNodesPostRun() {\n for (size_t i = 0; i < _activeWorkers.size(); i++) {\n _activeWorkers.at(i)->initPostRun();\n }\n _emitter->initPostRun();\n if (_collector) {\n _collector->initPostRun();\n }\n}\n\ntemplate \nvoid ManagerFarm::cleanNodes() {\n for (size_t i = 0; i < _activeWorkers.size(); i++) {\n _activeWorkers.at(i)->clean();\n }\n if (_emitter) {\n _emitter->clean();\n }\n if (_collector) {\n _collector->clean();\n }\n}\n\ntemplate \nvoid ManagerFarm::run(){\n initNodesPreRun();\n _farm->run_then_freeze();\n initNodesPostRun();\n\n if(_p.contractType != CONTRACT_NONE){\n _configuration.maxAllKnobs();\n }\n\n _startTimeMs = getMillisecondsTime();\n if(_counter){\n _counter->reset();\n }\n _lastStoredSampleMs = _startTimeMs;\n if(_p.observer){\n _p.observer->_startMonitoringMs = _lastStoredSampleMs;\n }\n\n if(_p.contractType == CONTRACT_PERF_COMPLETION_TIME){\n _remainingTasks = _p.expectedTasksNumber;\n _deadline = getMillisecondsTime()\/1000.0 + _p.requiredCompletionTime;\n }\n\n initPredictors();\n\n double microsecsSleep = 0;\n if(_p.contractType == CONTRACT_NONE){\n _farm->wait();\n storeNewSample();\n observe();\n }else{\n \/* Force the first calibration point. **\/\n assert(_calibrator);\n changeKnobs();\n\n double startSample = getMillisecondsTime();\n\n while(!terminated()){\n double overheadMs = getMillisecondsTime() - startSample;\n microsecsSleep = ((double)_p.samplingInterval - overheadMs)*\n (double)MAMMUT_MICROSECS_IN_MILLISEC;\n if(microsecsSleep < 0){\n microsecsSleep = 0;\n }\n usleep(microsecsSleep);\n startSample = getMillisecondsTime();\n\n storeNewSample();\n DEBUG(\"New sample stored.\");\n\n if(_p.contractType == CONTRACT_PERF_COMPLETION_TIME){\n double now = getMillisecondsTime()\/1000.0;\n if(now >= _deadline){\n _p.requiredBandwidth = numeric_limits::max();\n }else{\n _p.requiredBandwidth = _remainingTasks \/\n (_deadline - now);\n }\n }\n\n observe();\n\n if(!persist()){\n assert(_calibrator);\n changeKnobs();\n startSample = getMillisecondsTime();\n }\n }\n DEBUG(\"Terminated.\");\n }\n\n uint duration = getMillisecondsTime() - _startTimeMs;\n if(_p.observer){\n vector cs;\n if(_calibrator){\n cs = _calibrator->getCalibrationsStats();\n _p.observer->calibrationStats(cs, duration);\n }\n _p.observer->summaryStats(cs, duration);\n }\n\n cleanNodes();\n}\n\n}\n[FIX] Fixed execution time calculation when contract is NONE.\/*\n * manager.cpp\n *\n * Created on: 23\/03\/2015\n *\n * =========================================================================\n * Copyright (C) 2015-, Daniele De Sensi (d.desensi.software@gmail.com)\n *\n * This file is part of AdaptiveFastFlow.\n *\n * AdaptiveFastFlow is free software: you can redistribute it and\/or\n * modify it under the terms of the Lesser GNU General Public\n * License as published by the Free Software Foundation, either\n * version 3 of the License, or (at your option) any later version.\n\n * AdaptiveFastFlow is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * Lesser GNU General Public License for more details.\n *\n * You should have received a copy of the Lesser GNU General Public\n * License along with AdaptiveFastFlow.\n * If not, see .\n *\n * =========================================================================\n *\/\n\n#include \".\/manager.hpp\"\n#include \"parameters.hpp\"\n#include \"predictors.hpp\"\n#include \".\/node.hpp\"\n#include \"utils.hpp\"\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#undef DEBUG\n#undef DEBUGB\n\n#ifdef DEBUG_MANAGER\n#define DEBUG(x) do { cerr << \"[Manager] \" << x << endl; } while (0)\n#define DEBUGB(x) do {x;} while(0)\n#else\n#define DEBUG(x)\n#define DEBUGB(x)\n#endif\n\nnamespace adpff{\n\nclass Parameters;\n\nusing namespace std;\nusing namespace ff;\nusing namespace mammut::cpufreq;\nusing namespace mammut::energy;\nusing namespace mammut::task;\nusing namespace mammut::topology;\nusing namespace mammut::utils;\n\ntemplate \nvoid ManagerFarm::setDomainToHighestFrequency(const Domain* domain){\n if(!domain->setGovernor(GOVERNOR_PERFORMANCE)){\n if(!domain->setGovernor(GOVERNOR_USERSPACE) ||\n !domain->setHighestFrequencyUserspace()){\n throw runtime_error(\"AdaptivityManagerFarm: Fatal error while \"\n \"setting highest frequency for sensitive \"\n \"emitter\/collector. Try to run it without \"\n \"sensitivity parameters.\");\n }\n }\n}\n\ntemplate \ndouble ManagerFarm::getPrimaryValue(const MonitoredSample& sample) const{\n switch(_p.contractType){\n case CONTRACT_PERF_UTILIZATION:{\n return sample.utilization;\n }break;\n case CONTRACT_PERF_BANDWIDTH:\n case CONTRACT_PERF_COMPLETION_TIME:{\n return sample.bandwidth;\n }break;\n case CONTRACT_POWER_BUDGET:{\n return sample.watts;\n }break;\n default:{\n return 0;\n }break;\n }\n}\n\ntemplate \ndouble ManagerFarm::getSecondaryValue(const MonitoredSample& sample) const{\n switch(_p.contractType){\n case CONTRACT_PERF_UTILIZATION:\n case CONTRACT_PERF_BANDWIDTH:\n case CONTRACT_PERF_COMPLETION_TIME:{\n return sample.watts;\n }break;\n case CONTRACT_POWER_BUDGET:{\n return sample.bandwidth;\n }break;\n default:{\n return 0;\n }break;\n }\n}\n\ntemplate \ndouble ManagerFarm::getPrimaryValue() const{\n return getPrimaryValue(_samples->average());\n}\n\ntemplate \ndouble ManagerFarm::getSecondaryValue() const{\n return getSecondaryValue(_samples->average());\n}\n\ntemplate \nbool ManagerFarm::terminated(){\n \/**\n * We do not need to wait if the emitter is terminated.\n * Indeed, if the workers terminated, the emitter surely terminated\n * too.\n *\/\n\n for(size_t i = 0; i < _activeWorkers.size(); i++){\n if(!_activeWorkers.at(i)->isTerminated()){\n return false;\n }else{\n DEBUG(\"Worker \" << i << \" terminated.\");\n }\n }\n\n if(_collector &&\n !_collector->isTerminated()){\n return false;\n }else{\n DEBUG(\"Collector terminated.\");\n }\n\n return true;\n}\n\ntemplate \nvoid ManagerFarm::changeKnobs(){\n KnobsValues values = _calibrator->getNextKnobsValues(getPrimaryValue(),\n getSecondaryValue(),\n _remainingTasks);\n if(values != _configuration.getRealValues()){\n _configuration.setValues(values);\n _activeWorkers = dynamic_cast(_configuration.getKnob(KNOB_TYPE_WORKERS))->getActiveWorkers();\n\n \/****************** Clean state ******************\/\n _lastStoredSampleMs = getMillisecondsTime();\n _samples->reset();\n if(_counter){\n _counter->reset();\n }\n _totalTasks = 0;\n }\n}\n\ntemplate \nvoid ManagerFarm::observe(){\n if(_p.observer){\n const KnobMapping* kMapping = dynamic_cast(_configuration.getKnob(KNOB_TYPE_MAPPING));\n _p.observer->observe(_lastStoredSampleMs,\n _configuration.getRealValue(KNOB_TYPE_WORKERS),\n _configuration.getRealValue(KNOB_TYPE_FREQUENCY),\n kMapping->getEmitterVirtualCore(),\n kMapping->getWorkersVirtualCore(),\n kMapping->getCollectorVirtualCore(),\n _samples->getLastSample().bandwidth,\n _samples->average().bandwidth,\n _samples->coefficientVariation().bandwidth,\n _samples->average().utilization,\n _samples->average().watts);\n }\n}\n\ntemplate \nvoid ManagerFarm::askForWorkersSamples(){\n for(size_t i = 0; i < _activeWorkers.size(); i++){\n _activeWorkers.at(i)->askForSample();\n }\n}\n\ntemplate \nvoid ManagerFarm::getWorkersSamples(WorkerSample& sample){\n AdaptiveNode* w;\n uint numActiveWorkers = _activeWorkers.size();\n sample = WorkerSample();\n\n for(size_t i = 0; i < numActiveWorkers; i++){\n WorkerSample tmp;\n w = _activeWorkers.at(i);\n w->getSampleResponse(tmp, _p.strategyPolling,\n _samples->average().latency);\n sample += tmp;\n }\n sample.loadPercentage \/= numActiveWorkers;\n sample.latency \/= numActiveWorkers;\n}\n\ntemplate \nvoid ManagerFarm::storeNewSample(){\n MonitoredSample sample;\n WorkerSample ws;\n Joules joules = 0.0;\n\n askForWorkersSamples();\n getWorkersSamples(ws);\n\n _totalTasks += ws.tasksCount;\n if(_p.contractType == CONTRACT_PERF_COMPLETION_TIME){\n if(_remainingTasks > ws.tasksCount){\n _remainingTasks -= ws.tasksCount;\n }else{\n _remainingTasks = 0;\n }\n }\n\n if(_counter){\n switch(_counter->getType()){\n case COUNTER_CPUS:{\n joules = ((CounterCpus*) _counter)->getJoulesCoresAll();\n }break;\n default:{\n joules = _counter->getJoules();\n }break;\n }\n }\n\n double now = getMillisecondsTime();\n double durationSecs = (now - _lastStoredSampleMs) \/ 1000.0;\n _lastStoredSampleMs = now;\n\n sample.watts = joules \/ durationSecs;\n sample.utilization = ws.loadPercentage;\n \/\/ ATTENTION: Bandwidth is not the number of task since the\n \/\/ last observation but the number of expected\n \/\/ tasks that will be processed in 1 second.\n \/\/ For this reason, if we sum all the bandwidths in\n \/\/ the result observation file, we may have an higher\n \/\/ number than the number of tasks.\n sample.bandwidth = ws.bandwidthTotal;\n sample.latency = ws.latency;\n\n if(_counter){\n _counter->reset();\n }\n _samples->add(sample);\n\n DEBUGB(samplesFile << *_samples << \"\\n\");\n}\n\ntemplate \nbool ManagerFarm::persist() const{\n bool r = false;\n switch(_p.strategyPersistence){\n case STRATEGY_PERSISTENCE_SAMPLES:{\n r = _samples->size() < _p.persistenceValue;\n }break;\n case STRATEGY_PERSISTENCE_TASKS:{\n r = _totalTasks < _p.persistenceValue;\n }break;\n case STRATEGY_PERSISTENCE_VARIATION:{\n const MonitoredSample& variation =\n _samples->coefficientVariation();\n r = getPrimaryValue(variation) < _p.persistenceValue &&\n getSecondaryValue(variation) < _p.persistenceValue;\n }break;\n }\n return r;\n}\n\ntemplate \nvoid ManagerFarm::initPredictors(){\n if(_p.strategyCalibration == STRATEGY_CALIBRATION_RANDOM){\n ; \/\/CREARE TODO: Ci deve sempre essere un calibratore\n }else{\n switch(_p.strategyPrediction){\n case STRATEGY_PREDICTION_SIMPLE:{\n _calibrator = new CalibratorDummy(_p, _configuration, _samples);\n }break;\n case STRATEGY_PREDICTION_REGRESSION_LINEAR:{\n _calibrator = new CalibratorLowDiscrepancy(_p, _configuration, _samples);\n }break;\n }\n }\n}\n\nstatic Parameters& validate(Parameters& p){\n ParametersValidation apv = p.validate();\n if(apv != VALIDATION_OK){\n throw runtime_error(\"Invalid adaptivity parameters: \" + std::to_string(apv));\n }\n return p;\n}\n\nstatic std::vector convertWorkers(svector w){\n std::vector r;\n for(size_t i = 0; i < w.size(); i++){\n r.push_back(dynamic_cast(w[i]));\n }\n return r;\n}\n\ntemplate \nManagerFarm::ManagerFarm(ff_farm* farm, Parameters parameters):\n _farm(farm),\n _p(validate(parameters)),\n _startTimeMs(0),\n _cpufreq(_p.mammut.getInstanceCpuFreq()),\n _counter(_p.mammut.getInstanceEnergy()->getCounter()),\n _task(_p.mammut.getInstanceTask()),\n _topology(_p.mammut.getInstanceTopology()),\n _emitter(dynamic_cast(_farm->getEmitter())),\n _collector(dynamic_cast(_farm->getCollector())),\n _activeWorkers(convertWorkers(_farm->getWorkers())),\n _configuration(_p, _emitter, _collector, _farm->getgt(), _activeWorkers),\n _samples(NULL),\n _totalTasks(0),\n _remainingTasks(0),\n _deadline(0),\n _lastStoredSampleMs(0),\n _calibrator(NULL){\n\n _samples = NULL;\n switch(_p.strategySmoothing){\n case STRATEGY_SMOOTHING_MOVING_AVERAGE:{\n _samples = new MovingAverageSimple(_p.smoothingFactor);\n }break;\n case STRATEGY_SMOOTHING_EXPONENTIAL:{\n _samples = new MovingAverageExponential(_p.smoothingFactor);\n }break;\n }\n\n DEBUGB(samplesFile.open(\"samples.csv\"));\n}\n\ntemplate \nManagerFarm::~ManagerFarm(){\n delete _samples;\n if(_calibrator){\n delete _calibrator;\n }\n DEBUGB(samplesFile.close());\n}\n\ntemplate \nvoid ManagerFarm::initNodesPreRun() {\n for (size_t i = 0; i < _activeWorkers.size(); i++) {\n _activeWorkers.at(i)->initPreRun(_p.mammut, _p.archData.ticksPerNs, NODE_TYPE_WORKER);\n }\n if (_emitter) {\n _emitter->initPreRun(_p.mammut, _p.archData.ticksPerNs, NODE_TYPE_EMITTER);\n } else {\n throw runtime_error(\"Emitter is needed to use the manager.\");\n }\n if (_collector) {\n _collector->initPreRun(_p.mammut, _p.archData.ticksPerNs, NODE_TYPE_COLLECTOR);\n }\n}\n\ntemplate \nvoid ManagerFarm::initNodesPostRun() {\n for (size_t i = 0; i < _activeWorkers.size(); i++) {\n _activeWorkers.at(i)->initPostRun();\n }\n _emitter->initPostRun();\n if (_collector) {\n _collector->initPostRun();\n }\n}\n\ntemplate \nvoid ManagerFarm::cleanNodes() {\n for (size_t i = 0; i < _activeWorkers.size(); i++) {\n _activeWorkers.at(i)->clean();\n }\n if (_emitter) {\n _emitter->clean();\n }\n if (_collector) {\n _collector->clean();\n }\n}\n\ntemplate \nvoid ManagerFarm::run(){\n initNodesPreRun();\n _farm->run_then_freeze();\n initNodesPostRun();\n\n if(_p.contractType != CONTRACT_NONE){\n _configuration.maxAllKnobs();\n }\n\n _startTimeMs = getMillisecondsTime();\n if(_counter){\n _counter->reset();\n }\n _lastStoredSampleMs = _startTimeMs;\n if(_p.observer){\n _p.observer->_startMonitoringMs = _lastStoredSampleMs;\n }\n\n if(_p.contractType == CONTRACT_PERF_COMPLETION_TIME){\n _remainingTasks = _p.expectedTasksNumber;\n _deadline = getMillisecondsTime()\/1000.0 + _p.requiredCompletionTime;\n }\n\n initPredictors();\n\n double microsecsSleep = 0;\n double startSample = getMillisecondsTime();\n\n if(_p.contractType == CONTRACT_NONE){\n _farm->wait();\n storeNewSample();\n observe();\n }else{\n \/* Force the first calibration point. **\/\n assert(_calibrator);\n changeKnobs();\n\n while(!terminated()){\n double overheadMs = getMillisecondsTime() - startSample;\n microsecsSleep = ((double)_p.samplingInterval - overheadMs)*\n (double)MAMMUT_MICROSECS_IN_MILLISEC;\n if(microsecsSleep < 0){\n microsecsSleep = 0;\n }\n usleep(microsecsSleep);\n startSample = getMillisecondsTime();\n\n storeNewSample();\n DEBUG(\"New sample stored.\");\n\n if(_p.contractType == CONTRACT_PERF_COMPLETION_TIME){\n double now = getMillisecondsTime()\/1000.0;\n if(now >= _deadline){\n _p.requiredBandwidth = numeric_limits::max();\n }else{\n _p.requiredBandwidth = _remainingTasks \/\n (_deadline - now);\n }\n }\n\n observe();\n\n if(!persist()){\n assert(_calibrator);\n changeKnobs();\n startSample = getMillisecondsTime();\n }\n }\n DEBUG(\"Terminated.\");\n }\n\n uint duration = getMillisecondsTime() - _startTimeMs;\n if(_p.observer){\n vector cs;\n if(_calibrator){\n cs = _calibrator->getCalibrationsStats();\n _p.observer->calibrationStats(cs, duration);\n }\n _p.observer->summaryStats(cs, duration);\n }\n\n cleanNodes();\n}\n\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2014 Matthew Harvey\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"time_log.hpp\"\n#include \"atomic_writer.hpp\"\n#include \"file_utilities.hpp\"\n#include \"stint.hpp\"\n#include \"stream_utilities.hpp\"\n#include \"string_utilities.hpp\"\n#include \"time_point.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing std::cerr;\nusing std::endl;\nusing std::getline;\nusing std::ifstream;\nusing std::isspace;\nusing std::ios;\nusing std::move;\nusing std::ofstream;\nusing std::ostringstream;\nusing std::regex;\nusing std::regex_search;\nusing std::remove;\nusing std::runtime_error;\nusing std::size_t;\nusing std::string;\nusing std::stringstream;\nusing std::tm;\nusing std::upper_bound;\nusing std::vector;\n\nnamespace chrono = std::chrono;\n\nnamespace swx\n{\n\nnamespace\n{\n\tstring::size_type expected_time_stamp_length\n\t(\tstring const& p_time_format,\n\t\tunsigned int p_formatted_buf_len\n\t)\n\t{\n\t\tstatic string const time_format =\n\t\t\ttime_point_to_stamp(now(), p_time_format, p_formatted_buf_len);\n\t\treturn time_format.length();\n\t}\n\n} \/\/ end anonymous namespace\n\nTimeLog::TimeLog\n(\tstring const& p_filepath,\n\tstring const& p_time_format,\n\tunsigned int p_formatted_buf_len\n):\n\tm_is_loaded(false),\n\tm_formatted_buf_len(p_formatted_buf_len),\n\tm_filepath(p_filepath),\n\tm_time_format(p_time_format)\n{\n\tassert (m_entries.empty());\n\tassert (m_activities.empty());\n}\n\nTimeLog::~TimeLog() = default;\n\nvoid\nTimeLog::append_entry(string const& p_activity)\n{\n\tAtomicWriter writer(m_filepath);\n\tmark_cache_as_stale();\n\twriter.append(time_point_to_stamp(now(), m_time_format, m_formatted_buf_len));\n\tif (!p_activity.empty())\n\t{\n\t\twriter.append(\" \");\n\t\twriter.append(p_activity);\n\t}\n\twriter.append(\"\\n\");\n\twriter.commit();\n\tmark_cache_as_stale();\n\treturn;\n}\n\nvector\nTimeLog::get_stints\n(\tstring const* p_sought_activity,\n\tTimePoint const* p_begin,\n\tTimePoint const* p_end,\n\tbool p_use_regex\n)\n{\n\tload();\t\n\tregex reg;\n\tif (!p_sought_activity) p_use_regex = false;\n\tif (p_use_regex)\n\t{\n\t\tassert (p_sought_activity);\n\t\treg = regex(*p_sought_activity, regex::extended | regex::optimize);\n\t}\n\tvector ret;\n\tauto const e = m_entries.end();\n\tauto it = (p_begin? find_entry_just_before(*p_begin): m_entries.begin());\n\tauto const n = now();\n\tauto const sought_id =\n\t\t(p_sought_activity? register_activity(*p_sought_activity): 0);\n\tfor ( ; (it != e) && (!p_end || (it->time_point < *p_end)); ++it)\n\t{\n\t\tActivityId const activity_id = it->activity_id;\n\t\tif (!p_sought_activity || (sought_id == activity_id) || p_use_regex)\n\t\t{\n\t\t\tauto const& activity = id_to_activity(activity_id);\n\t\t\tif (!p_use_regex || regex_search(activity, reg))\n\t\t\t{\n\t\t\t\tauto tp = it->time_point;\n\t\t\t\tif (p_begin && (tp < *p_begin)) tp = *p_begin;\n\t\t\t\tauto const next_it = it + 1;\n\t\t\t\tauto const done = (next_it == e);\n\t\t\t\tauto next_tp = (done? (n > tp? n: tp): next_it->time_point);\n\t\t\t\tif (p_end && (next_tp > *p_end)) next_tp = *p_end;\n\t\t\t\tassert (next_tp >= tp);\n\t\t\t\tassert (!p_begin || (tp >= *p_begin));\n\t\t\t\tassert (!p_end || (next_tp <= *p_end));\n\t\t\t\tauto const duration = next_tp - tp;\n\t\t\t\tauto const seconds = chrono::duration_cast(duration);\n\t\t\t\tInterval const interval(tp, seconds, done);\n\t\t\t\tret.push_back(Stint(activity, interval));\n\t\t\t}\n\t\t}\n\t}\n\treturn ret;\t\n}\n\nstring\nTimeLog::last_activity_to_match(string const& p_regex)\n{\n\tload();\n\tregex const reg(p_regex, regex::extended | regex::optimize);\n\ttypedef decltype(m_entries)::const_reverse_iterator RevIter;\n\tauto const empty_activity_id = register_activity(\"\");\n\tfor (RevIter rit = m_entries.rbegin(); rit != m_entries.rend(); ++rit)\n\t{\n\t\tauto const id = rit->activity_id;\n\t\tif (id != empty_activity_id)\n\t\t{\n\t\t\tauto const& activity = id_to_activity(id);\n\t\t\tif (regex_search(activity, reg))\n\t\t\t{\n\t\t\t\treturn activity;\n\t\t\t}\n\t\t}\n\t}\n\treturn string();\n}\n\nvector\nTimeLog::last_activities(size_t p_num)\n{\n\tload();\n\tvector ret;\n\tif (m_entries.empty())\n\t{\n\t\treturn ret;\n\t}\n\tassert (m_entries.size() >= 1);\n\ttypedef decltype(m_entries)::const_reverse_iterator RevIter;\n\tfor (RevIter it = m_entries.rbegin(); it != m_entries.rend(); ++it)\n\t{\n\t\tif (ret.size() == p_num)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t\tauto const& activity = id_to_activity(it->activity_id);\n\t\tif (!activity.empty() && (ret.empty() || (activity != ret.back())))\n\t\t{\n\t\t\tret.push_back(activity);\n\t\t}\n\t}\n\tassert (ret.size() <= p_num);\n\tassert (ret.size() <= m_entries.size());\n\treturn ret;\n}\n\nbool\nTimeLog::is_active()\n{\n\tload();\n\tif (m_entries.empty())\n\t{\n\t\treturn false;\n\t}\n\treturn !id_to_activity(m_entries.back().activity_id).empty();\n}\n\nbool\nTimeLog::has_activity(string const& p_activity)\n{\n\tload();\n\treturn m_activities.find(p_activity) != m_activities.end();\n}\n\nvoid\nTimeLog::clear_cache()\n{\n\tm_entries.clear();\n\tm_activities.clear();\n\tmark_cache_as_stale();\n\treturn;\n}\n\nvoid\nTimeLog::mark_cache_as_stale()\n{\n\tm_is_loaded = false;\n}\n\nvoid\nTimeLog::load()\n{\n\tif (!m_is_loaded)\n\t{\n\t\tclear_cache();\n\t\tif (file_exists_at(m_filepath))\n\t\t{\n\t\t\tifstream infile(m_filepath.c_str());\n\t\t\tenable_exceptions(infile);\n\t\t\tstring line;\n\t\t\tsize_t line_number = 1;\n\t\t\twhile (infile.peek() != EOF)\n\t\t\t{\n\t\t\t\tgetline(infile, line);\n\t\t\t\tload_entry(line, line_number);\n\t\t\t\t++line_number;\n\t\t\t}\n\t\t\tif (!m_entries.empty() && (m_entries.back().time_point > now()))\n\t\t\t{\n\t\t\t\tthrow runtime_error\n\t\t\t\t(\t\"The final entry in the time log is future-dated. \"\n\t\t\t\t \"Future dated entries are not supported.\"\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tm_is_loaded = true;\n\t}\n\treturn;\n}\n\nTimeLog::ActivityId\nTimeLog::register_activity(string const& p_activity)\n{\n\treturn &*(m_activities.insert(p_activity).first);\n}\n\nvoid\nTimeLog::load_entry(string const& p_entry_string, size_t p_line_number)\n{\n\tif (p_entry_string.size() < expected_time_stamp_length(m_time_format, m_formatted_buf_len))\n\t{\n\t\tostringstream oss;\n\t\tenable_exceptions(oss);\n\t\toss << \"Error parsing the time log at line \"\n\t\t << p_line_number << '.';\n\t\tthrow runtime_error(oss.str());\n\t}\n\tauto it = p_entry_string.begin() + expected_time_stamp_length(m_time_format, m_formatted_buf_len);\n\tassert (it > p_entry_string.begin());\n\tstring const time_stamp(p_entry_string.begin(), it);\n\tauto const activity = trim(string(it, p_entry_string.end()));\n\tauto const activity_id = register_activity(activity);\n\tauto const time_point = time_stamp_to_point(time_stamp, m_time_format);\n\tEntry entry(activity_id, time_point);\n\tif (!m_entries.empty())\n\t{\n\t\tauto const last_time_point = m_entries.back().time_point;\n\t\tif (entry.time_point < last_time_point)\n\t\t{\t\t\n\t\t\tostringstream oss;\n\t\t\tenable_exceptions(oss);\n\t\t\toss << \"Time log entries out of order at line \"\n\t\t\t << p_line_number << '.'; \n\t\t\tthrow runtime_error(oss.str());\n\t\t}\n\t}\n\tm_entries.push_back(entry);\n\treturn;\n}\n\nstring const&\nTimeLog::id_to_activity(ActivityId p_activity_id)\n{\n\tload();\n\treturn *p_activity_id;\n}\n\nvector::const_iterator\nTimeLog::find_entry_just_before(TimePoint const& p_time_point)\n{\n\tload();\n\tauto const comp = [](Entry const& lhs, Entry const& rhs)\n\t{\n\t\treturn lhs.time_point < rhs.time_point;\n\t};\n\tauto const b = m_entries.begin(), e = m_entries.end();\n\tEntry const dummy(0, p_time_point);\n\tauto it = upper_bound(b, e, dummy, comp);\n\tfor ( ; (it != b) && ((it == e) || (it->time_point > p_time_point)); --it)\n\t{\n\t}\n\treturn it;\n}\n\nTimeLog::Entry::Entry(ActivityId p_activity_id, TimePoint const& p_time_point):\n\tactivity_id(p_activity_id),\n\ttime_point(p_time_point)\n{\n}\n\n} \/\/ namespace swx\nRemove unused dependencies from time_log.cpp.\/*\n * Copyright 2014 Matthew Harvey\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"time_log.hpp\"\n#include \"atomic_writer.hpp\"\n#include \"file_utilities.hpp\"\n#include \"stint.hpp\"\n#include \"stream_utilities.hpp\"\n#include \"string_utilities.hpp\"\n#include \"time_point.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing std::getline;\nusing std::ifstream;\nusing std::isspace;\nusing std::ios;\nusing std::move;\nusing std::ofstream;\nusing std::ostringstream;\nusing std::regex;\nusing std::regex_search;\nusing std::remove;\nusing std::runtime_error;\nusing std::size_t;\nusing std::string;\nusing std::stringstream;\nusing std::tm;\nusing std::upper_bound;\nusing std::vector;\n\nnamespace chrono = std::chrono;\n\nnamespace swx\n{\n\nnamespace\n{\n\tstring::size_type expected_time_stamp_length\n\t(\tstring const& p_time_format,\n\t\tunsigned int p_formatted_buf_len\n\t)\n\t{\n\t\tstatic string const time_format =\n\t\t\ttime_point_to_stamp(now(), p_time_format, p_formatted_buf_len);\n\t\treturn time_format.length();\n\t}\n\n} \/\/ end anonymous namespace\n\nTimeLog::TimeLog\n(\tstring const& p_filepath,\n\tstring const& p_time_format,\n\tunsigned int p_formatted_buf_len\n):\n\tm_is_loaded(false),\n\tm_formatted_buf_len(p_formatted_buf_len),\n\tm_filepath(p_filepath),\n\tm_time_format(p_time_format)\n{\n\tassert (m_entries.empty());\n\tassert (m_activities.empty());\n}\n\nTimeLog::~TimeLog() = default;\n\nvoid\nTimeLog::append_entry(string const& p_activity)\n{\n\tAtomicWriter writer(m_filepath);\n\tmark_cache_as_stale();\n\twriter.append(time_point_to_stamp(now(), m_time_format, m_formatted_buf_len));\n\tif (!p_activity.empty())\n\t{\n\t\twriter.append(\" \");\n\t\twriter.append(p_activity);\n\t}\n\twriter.append(\"\\n\");\n\twriter.commit();\n\tmark_cache_as_stale();\n\treturn;\n}\n\nvector\nTimeLog::get_stints\n(\tstring const* p_sought_activity,\n\tTimePoint const* p_begin,\n\tTimePoint const* p_end,\n\tbool p_use_regex\n)\n{\n\tload();\t\n\tregex reg;\n\tif (!p_sought_activity) p_use_regex = false;\n\tif (p_use_regex)\n\t{\n\t\tassert (p_sought_activity);\n\t\treg = regex(*p_sought_activity, regex::extended | regex::optimize);\n\t}\n\tvector ret;\n\tauto const e = m_entries.end();\n\tauto it = (p_begin? find_entry_just_before(*p_begin): m_entries.begin());\n\tauto const n = now();\n\tauto const sought_id =\n\t\t(p_sought_activity? register_activity(*p_sought_activity): 0);\n\tfor ( ; (it != e) && (!p_end || (it->time_point < *p_end)); ++it)\n\t{\n\t\tActivityId const activity_id = it->activity_id;\n\t\tif (!p_sought_activity || (sought_id == activity_id) || p_use_regex)\n\t\t{\n\t\t\tauto const& activity = id_to_activity(activity_id);\n\t\t\tif (!p_use_regex || regex_search(activity, reg))\n\t\t\t{\n\t\t\t\tauto tp = it->time_point;\n\t\t\t\tif (p_begin && (tp < *p_begin)) tp = *p_begin;\n\t\t\t\tauto const next_it = it + 1;\n\t\t\t\tauto const done = (next_it == e);\n\t\t\t\tauto next_tp = (done? (n > tp? n: tp): next_it->time_point);\n\t\t\t\tif (p_end && (next_tp > *p_end)) next_tp = *p_end;\n\t\t\t\tassert (next_tp >= tp);\n\t\t\t\tassert (!p_begin || (tp >= *p_begin));\n\t\t\t\tassert (!p_end || (next_tp <= *p_end));\n\t\t\t\tauto const duration = next_tp - tp;\n\t\t\t\tauto const seconds = chrono::duration_cast(duration);\n\t\t\t\tInterval const interval(tp, seconds, done);\n\t\t\t\tret.push_back(Stint(activity, interval));\n\t\t\t}\n\t\t}\n\t}\n\treturn ret;\t\n}\n\nstring\nTimeLog::last_activity_to_match(string const& p_regex)\n{\n\tload();\n\tregex const reg(p_regex, regex::extended | regex::optimize);\n\ttypedef decltype(m_entries)::const_reverse_iterator RevIter;\n\tauto const empty_activity_id = register_activity(\"\");\n\tfor (RevIter rit = m_entries.rbegin(); rit != m_entries.rend(); ++rit)\n\t{\n\t\tauto const id = rit->activity_id;\n\t\tif (id != empty_activity_id)\n\t\t{\n\t\t\tauto const& activity = id_to_activity(id);\n\t\t\tif (regex_search(activity, reg))\n\t\t\t{\n\t\t\t\treturn activity;\n\t\t\t}\n\t\t}\n\t}\n\treturn string();\n}\n\nvector\nTimeLog::last_activities(size_t p_num)\n{\n\tload();\n\tvector ret;\n\tif (m_entries.empty())\n\t{\n\t\treturn ret;\n\t}\n\tassert (m_entries.size() >= 1);\n\ttypedef decltype(m_entries)::const_reverse_iterator RevIter;\n\tfor (RevIter it = m_entries.rbegin(); it != m_entries.rend(); ++it)\n\t{\n\t\tif (ret.size() == p_num)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\t\tauto const& activity = id_to_activity(it->activity_id);\n\t\tif (!activity.empty() && (ret.empty() || (activity != ret.back())))\n\t\t{\n\t\t\tret.push_back(activity);\n\t\t}\n\t}\n\tassert (ret.size() <= p_num);\n\tassert (ret.size() <= m_entries.size());\n\treturn ret;\n}\n\nbool\nTimeLog::is_active()\n{\n\tload();\n\tif (m_entries.empty())\n\t{\n\t\treturn false;\n\t}\n\treturn !id_to_activity(m_entries.back().activity_id).empty();\n}\n\nbool\nTimeLog::has_activity(string const& p_activity)\n{\n\tload();\n\treturn m_activities.find(p_activity) != m_activities.end();\n}\n\nvoid\nTimeLog::clear_cache()\n{\n\tm_entries.clear();\n\tm_activities.clear();\n\tmark_cache_as_stale();\n\treturn;\n}\n\nvoid\nTimeLog::mark_cache_as_stale()\n{\n\tm_is_loaded = false;\n}\n\nvoid\nTimeLog::load()\n{\n\tif (!m_is_loaded)\n\t{\n\t\tclear_cache();\n\t\tif (file_exists_at(m_filepath))\n\t\t{\n\t\t\tifstream infile(m_filepath.c_str());\n\t\t\tenable_exceptions(infile);\n\t\t\tstring line;\n\t\t\tsize_t line_number = 1;\n\t\t\twhile (infile.peek() != EOF)\n\t\t\t{\n\t\t\t\tgetline(infile, line);\n\t\t\t\tload_entry(line, line_number);\n\t\t\t\t++line_number;\n\t\t\t}\n\t\t\tif (!m_entries.empty() && (m_entries.back().time_point > now()))\n\t\t\t{\n\t\t\t\tthrow runtime_error\n\t\t\t\t(\t\"The final entry in the time log is future-dated. \"\n\t\t\t\t \"Future dated entries are not supported.\"\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tm_is_loaded = true;\n\t}\n\treturn;\n}\n\nTimeLog::ActivityId\nTimeLog::register_activity(string const& p_activity)\n{\n\treturn &*(m_activities.insert(p_activity).first);\n}\n\nvoid\nTimeLog::load_entry(string const& p_entry_string, size_t p_line_number)\n{\n\tif (p_entry_string.size() < expected_time_stamp_length(m_time_format, m_formatted_buf_len))\n\t{\n\t\tostringstream oss;\n\t\tenable_exceptions(oss);\n\t\toss << \"Error parsing the time log at line \"\n\t\t << p_line_number << '.';\n\t\tthrow runtime_error(oss.str());\n\t}\n\tauto it = p_entry_string.begin() + expected_time_stamp_length(m_time_format, m_formatted_buf_len);\n\tassert (it > p_entry_string.begin());\n\tstring const time_stamp(p_entry_string.begin(), it);\n\tauto const activity = trim(string(it, p_entry_string.end()));\n\tauto const activity_id = register_activity(activity);\n\tauto const time_point = time_stamp_to_point(time_stamp, m_time_format);\n\tEntry entry(activity_id, time_point);\n\tif (!m_entries.empty())\n\t{\n\t\tauto const last_time_point = m_entries.back().time_point;\n\t\tif (entry.time_point < last_time_point)\n\t\t{\t\t\n\t\t\tostringstream oss;\n\t\t\tenable_exceptions(oss);\n\t\t\toss << \"Time log entries out of order at line \"\n\t\t\t << p_line_number << '.'; \n\t\t\tthrow runtime_error(oss.str());\n\t\t}\n\t}\n\tm_entries.push_back(entry);\n\treturn;\n}\n\nstring const&\nTimeLog::id_to_activity(ActivityId p_activity_id)\n{\n\tload();\n\treturn *p_activity_id;\n}\n\nvector::const_iterator\nTimeLog::find_entry_just_before(TimePoint const& p_time_point)\n{\n\tload();\n\tauto const comp = [](Entry const& lhs, Entry const& rhs)\n\t{\n\t\treturn lhs.time_point < rhs.time_point;\n\t};\n\tauto const b = m_entries.begin(), e = m_entries.end();\n\tEntry const dummy(0, p_time_point);\n\tauto it = upper_bound(b, e, dummy, comp);\n\tfor ( ; (it != b) && ((it == e) || (it->time_point > p_time_point)); --it)\n\t{\n\t}\n\treturn it;\n}\n\nTimeLog::Entry::Entry(ActivityId p_activity_id, TimePoint const& p_time_point):\n\tactivity_id(p_activity_id),\n\ttime_point(p_time_point)\n{\n}\n\n} \/\/ namespace swx\n<|endoftext|>"} {"text":"\/\/\/\n\/\/\/ @file calculator.hpp\n\/\/\/ @brief calculator::eval(const std::string&) evaluates an integer\n\/\/\/ arithmetic expression and returns the result. If an error\n\/\/\/ occurs a calculator::error exception is thrown.\n\/\/\/ \n\/\/\/ @author Kim Walisch, \n\/\/\/ @copyright Copyright (C) 2013 Kim Walisch\n\/\/\/ @date November 30, 2013\n\/\/\/ @license BSD 2-Clause, http:\/\/opensource.org\/licenses\/BSD-2-Clause\n\/\/\/ @version 1.0 patched: `^' is raise to power instead of XOR.\n\/\/\/\n\/\/\/ == Supported operators ==\n\/\/\/\n\/\/\/ OPERATOR NAME ASSOCIATIVITY PRECEDENCE\n\/\/\/\n\/\/\/ | Bitwise Inclusive OR Left 4\n\/\/\/ & Bitwise AND Left 6\n\/\/\/ << Shift Left Left 9\n\/\/\/ >> Shift Right Left 9\n\/\/\/ + Addition Left 10\n\/\/\/ - Subtraction Left 10\n\/\/\/ * Multiplication Left 20\n\/\/\/ \/ Division Left 20\n\/\/\/ % Modulo Left 20\n\/\/\/ ^, ** Raise to power Right 30\n\/\/\/ e, E Scientific notation Right 40\n\/\/\/ ~ Unary complement Left 99\n\/\/\/\n\/\/\/ The operator precedence has been set according to (uses the C and\n\/\/\/ C++ operator precedence): http:\/\/en.wikipedia.org\/wiki\/Order_of_operations\n\/\/\/ Operators with higher precedence are evaluated before operators\n\/\/\/ with relatively lower precedence. Unary operators are set to have\n\/\/\/ the highest precedence, this is not strictly correct for the power\n\/\/\/ operator e.g. \"-3**2\" = 9 but a lot of software tools (Bash shell,\n\/\/\/ Microsoft Excel, GNU bc, ...) use the same convention.\n\/\/\/\n\/\/\/ == Examples of valid expressions ==\n\/\/\/\n\/\/\/ \"65536 >> 15\" = 2\n\/\/\/ \"2**16\" = 65536\n\/\/\/ \"(0 + 0xDf234 - 1000)*3\/2%999\" = 828\n\/\/\/ \"-(2**2**2**2)\" = -65536\n\/\/\/ \"(0 + ~(0xDF234 & 1000) *3) \/-2\" = 817\n\/\/\/ \"(2**16) + (1 << 16) >> 0X5\" = 4096\n\/\/\/ \"5*-(2**(9+7))\/3+5*(1 & 0xFf123)\" = -109221\n\/\/\/\n\/\/\/ == About the algorithm used ==\n\/\/\/\n\/\/\/ calculator::eval(std::string&) relies on the ExpressionParser\n\/\/\/ class which is a simple C++ operator precedence parser with infix\n\/\/\/ notation for integer arithmetic expressions.\n\/\/\/ ExpressionParser has its roots in a JavaScript parser published\n\/\/\/ at: http:\/\/stackoverflow.com\/questions\/28256\/equation-expression-parser-with-precedence\/114961#114961\n\/\/\/ The same author has also published an article about his operator\n\/\/\/ precedence algorithm at PerlMonks:\n\/\/\/ http:\/\/www.perlmonks.org\/?node_id=554516\n\/\/\/\n\n#ifndef CALCULATOR_HPP\n#define CALCULATOR_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace calculator\n{\n\n\/\/\/ calculator::eval() throws a calculator::error if it fails\n\/\/\/ to evaluate the expression string.\n\/\/\/\nclass error : public std::runtime_error\n{\npublic:\n error(const std::string& expr, const std::string& message)\n : std::runtime_error(message),\n expr_(expr)\n { }\n#if __cplusplus >= 201103L\n ~error() { }\n#else\n ~error() throw() { }\n#endif\n std::string expression() const\n {\n return expr_;\n }\nprivate:\n std::string expr_;\n};\n\ntemplate \nclass ExpressionParser\n{\npublic:\n \/\/\/ Evaluate an integer arithmetic expression and return its result.\n \/\/\/ @throw error if parsing fails.\n \/\/\/\n T eval(const std::string& expr)\n {\n T result = 0;\n index_ = 0;\n expr_ = expr;\n try\n {\n result = parseExpr();\n if (!isEnd())\n unexpected();\n }\n catch (const calculator::error&)\n {\n while(!stack_.empty())\n stack_.pop();\n throw;\n }\n return result;\n }\n\n \/\/\/ Get the integer value of a character.\n T eval(char c)\n {\n std::string expr(1, c);\n return eval(expr);\n }\n\nprivate:\n enum\n {\n OPERATOR_NULL,\n OPERATOR_BITWISE_OR, \/\/\/ |\n OPERATOR_BITWISE_XOR, \/\/\/ ^\n OPERATOR_BITWISE_AND, \/\/\/ &\n OPERATOR_BITWISE_SHL, \/\/\/ <<\n OPERATOR_BITWISE_SHR, \/\/\/ >>\n OPERATOR_ADDITION, \/\/\/ +\n OPERATOR_SUBTRACTION, \/\/\/ -\n OPERATOR_MULTIPLICATION, \/\/\/ *\n OPERATOR_DIVISION, \/\/\/ \/\n OPERATOR_MODULO, \/\/\/ %\n OPERATOR_POWER, \/\/\/ **\n OPERATOR_EXPONENT \/\/\/ e, E\n };\n\n struct Operator\n {\n \/\/\/ Operator, one of the OPERATOR_* enum definitions\n int op;\n int precedence;\n \/\/\/ 'L' = left or 'R' = right\n int associativity;\n Operator(int opr, int prec, int assoc) :\n op(opr),\n precedence(prec),\n associativity(assoc)\n { }\n };\n\n struct OperatorValue\n {\n Operator op;\n T value;\n OperatorValue(const Operator& opr, T val) :\n op(opr),\n value(val)\n { }\n int getPrecedence() const\n {\n return op.precedence;\n }\n bool isNull() const\n {\n return op.op == OPERATOR_NULL;\n }\n };\n\n \/\/\/ Expression string\n std::string expr_;\n \/\/\/ Current expression index, incremented whilst parsing\n std::size_t index_;\n \/\/\/ The current operator and its left value\n \/\/\/ are pushed onto the stack if the operator on\n \/\/\/ top of the stack has lower precedence.\n std::stack stack_;\n\n \/\/\/ Exponentiation by squaring, x^n.\n static T pow(T x, T n)\n {\n T res = 1;\n while (n != 0)\n {\n if (n % 2 != 0)\n {\n res *= x;\n n -= 1;\n }\n x *= x;\n n \/= 2;\n }\n return res;\n }\n\n T checkZero(T value) const\n {\n if (value == 0)\n {\n std::string divOperators(\"\/%\");\n std::size_t division = expr_.find_last_of(divOperators, index_ - 2);\n std::ostringstream msg;\n msg << \"Parser error: division by 0\";\n if (division != std::string::npos)\n msg << \" (error token is \\\"\"\n << expr_.substr(division, expr_.size() - division)\n << \"\\\")\";\n throw calculator::error(expr_, msg.str());\n }\n return value;\n }\n\n T calculate(T v1, T v2, const Operator& op) const\n {\n switch (op.op)\n {\n case OPERATOR_BITWISE_OR: return v1 | v2;\n case OPERATOR_BITWISE_XOR: return v1 ^ v2;\n case OPERATOR_BITWISE_AND: return v1 & v2;\n case OPERATOR_BITWISE_SHL: return v1 << v2;\n case OPERATOR_BITWISE_SHR: return v1 >> v2;\n case OPERATOR_ADDITION: return v1 + v2;\n case OPERATOR_SUBTRACTION: return v1 - v2;\n case OPERATOR_MULTIPLICATION: return v1 * v2;\n case OPERATOR_DIVISION: return v1 \/ checkZero(v2);\n case OPERATOR_MODULO: return v1 % checkZero(v2);\n case OPERATOR_POWER: return pow(v1, v2);\n case OPERATOR_EXPONENT: return v1 * pow(10, v2);\n default: return 0;\n }\n }\n\n bool isEnd() const\n {\n return index_ >= expr_.size();\n }\n\n \/\/\/ Returns the character at the current expression index or\n \/\/\/ 0 if the end of the expression is reached.\n \/\/\/\n char getCharacter() const\n {\n if (!isEnd())\n return expr_[index_];\n return 0;\n }\n\n \/\/\/ Parse str at the current expression index.\n \/\/\/ @throw error if parsing fails.\n \/\/\/\n void expect(const std::string& str)\n {\n if (expr_.compare(index_, str.size(), str) != 0)\n unexpected();\n index_ += str.size();\n }\n\n void unexpected() const\n {\n std::ostringstream msg;\n msg << \"Syntax error: unexpected token \\\"\"\n << expr_.substr(index_, expr_.size() - index_)\n << \"\\\" at index \"\n << index_;\n throw calculator::error(expr_, msg.str());\n }\n\n \/\/\/ Eat all white space characters at the\n \/\/\/ current expression index.\n \/\/\/\n void eatSpaces()\n {\n while (std::isspace(getCharacter()) != 0)\n index_++;\n }\n\n \/\/\/ Parse a binary operator at the current expression index.\n \/\/\/ @return Operator with precedence and associativity.\n \/\/\/\n Operator parseOp()\n {\n eatSpaces();\n switch (getCharacter())\n {\n case '|': index_++; return Operator(OPERATOR_BITWISE_OR, 4, 'L');\n case '&': index_++; return Operator(OPERATOR_BITWISE_AND, 6, 'L');\n case '<': expect(\"<<\"); return Operator(OPERATOR_BITWISE_SHL, 9, 'L');\n case '>': expect(\">>\"); return Operator(OPERATOR_BITWISE_SHR, 9, 'L');\n case '+': index_++; return Operator(OPERATOR_ADDITION, 10, 'L');\n case '-': index_++; return Operator(OPERATOR_SUBTRACTION, 10, 'L');\n case '\/': index_++; return Operator(OPERATOR_DIVISION, 20, 'L');\n case '%': index_++; return Operator(OPERATOR_MODULO, 20, 'L');\n case '*': index_++; if (getCharacter() != '*')\n return Operator(OPERATOR_MULTIPLICATION, 20, 'L');\n index_++; return Operator(OPERATOR_POWER, 30, 'R');\n case '^': index_++; return Operator(OPERATOR_POWER, 30, 'R');\n case 'e': index_++; return Operator(OPERATOR_EXPONENT, 40, 'R');\n case 'E': index_++; return Operator(OPERATOR_EXPONENT, 40, 'R');\n default : return Operator(OPERATOR_NULL, 0, 'L');\n }\n }\n\n static T toInteger(char c)\n {\n if (c >= '0' && c <= '9') return c -'0';\n if (c >= 'a' && c <= 'f') return c -'a' + 0xa;\n if (c >= 'A' && c <= 'F') return c -'A' + 0xa;\n T noDigit = 0xf + 1;\n return noDigit;\n }\n\n T getInteger() const\n {\n return toInteger(getCharacter());\n }\n\n T parseDecimal()\n {\n T value = 0;\n for (T d; (d = getInteger()) <= 9; index_++)\n value = value * 10 + d;\n return value;\n }\n\n T parseHex()\n {\n index_ = index_ + 2;\n T value = 0;\n for (T h; (h = getInteger()) <= 0xf; index_++)\n value = value * 0x10 + h;\n return value;\n }\n\n bool isHex() const\n {\n if (index_ + 2 < expr_.size())\n {\n char x = expr_[index_ + 1];\n char h = expr_[index_ + 2];\n return (std::tolower(x) == 'x' && toInteger(h) <= 0xf);\n }\n return false;\n }\n\n \/\/\/ Parse an integer value at the current expression index.\n \/\/\/ The unary `+', `-' and `~' operators and opening\n \/\/\/ parentheses `(' cause recursion.\n \/\/\/\n T parseValue()\n {\n T val = 0;\n eatSpaces();\n switch (getCharacter())\n {\n case '0': if (isHex())\n val = parseHex();\n else\n val = parseDecimal();\n break;\n case '1': case '2': case '3': case '4': case '5':\n case '6': case '7': case '8': case '9':\n val = parseDecimal();\n break;\n case '(': index_++;\n val = parseExpr();\n eatSpaces();\n if (getCharacter() != ')')\n {\n if (!isEnd())\n unexpected();\n throw calculator::error(expr_, \"Syntax error: `)' expected at end of expression\");\n }\n index_++; break;\n case '~': index_++; val = ~parseValue(); break;\n case '+': index_++; val = parseValue(); break;\n case '-': index_++; val = parseValue() * static_cast(-1);\n break;\n default : if (!isEnd())\n unexpected();\n throw calculator::error(expr_, \"Syntax error: value expected at end of expression\");\n }\n return val;\n }\n\n \/\/\/ Parse all operations of the current parenthesis\n \/\/\/ level and the levels above, when done\n \/\/\/ return the result (value).\n \/\/\/\n T parseExpr()\n {\n stack_.push(OperatorValue(Operator(OPERATOR_NULL, 0, 'L'), 0));\n \/\/ first parse value on the left\n T value = parseValue();\n\n while (!stack_.empty())\n {\n \/\/ parse an operator (+, -, *, ...)\n Operator op(parseOp());\n while (op.precedence < stack_.top().getPrecedence() || (\n op.precedence == stack_.top().getPrecedence() &&\n op.associativity == 'L'))\n {\n \/\/ end reached\n if (stack_.top().isNull())\n {\n stack_.pop();\n return value;\n }\n \/\/ do the calculation (\"reduce\"), producing a new value\n value = calculate(stack_.top().value, value, stack_.top().op);\n stack_.pop();\n }\n\n \/\/ store on stack_ and continue parsing (\"shift\")\n stack_.push(OperatorValue(op, value));\n \/\/ parse value on the right\n value = parseValue();\n }\n return 0;\n }\n};\n\ntemplate \ninline T eval(const std::string& expression)\n{\n ExpressionParser parser;\n return parser.eval(expression);\n}\n\ntemplate \ninline T eval(char c)\n{\n ExpressionParser parser;\n return parser.eval(c);\n}\n\ninline int eval(const std::string& expression)\n{\n return eval(expression);\n}\n\ninline int eval(char c)\n{\n return eval(c);\n}\n\n} \/\/ namespace calculator\n\n#endif\nUpdate copyright year\/\/\/\n\/\/\/ @file calculator.hpp\n\/\/\/ @brief calculator::eval(const std::string&) evaluates an integer\n\/\/\/ arithmetic expression and returns the result. If an error\n\/\/\/ occurs a calculator::error exception is thrown.\n\/\/\/ \n\/\/\/ @author Kim Walisch, \n\/\/\/ @copyright Copyright (C) 2017 Kim Walisch\n\/\/\/ @license BSD 2-Clause, http:\/\/opensource.org\/licenses\/BSD-2-Clause\n\/\/\/ @version 1.1 patched: `^' is raise to power instead of XOR.\n\/\/\/\n\/\/\/ == Supported operators ==\n\/\/\/\n\/\/\/ OPERATOR NAME ASSOCIATIVITY PRECEDENCE\n\/\/\/\n\/\/\/ | Bitwise Inclusive OR Left 4\n\/\/\/ & Bitwise AND Left 6\n\/\/\/ << Shift Left Left 9\n\/\/\/ >> Shift Right Left 9\n\/\/\/ + Addition Left 10\n\/\/\/ - Subtraction Left 10\n\/\/\/ * Multiplication Left 20\n\/\/\/ \/ Division Left 20\n\/\/\/ % Modulo Left 20\n\/\/\/ ^, ** Raise to power Right 30\n\/\/\/ e, E Scientific notation Right 40\n\/\/\/ ~ Unary complement Left 99\n\/\/\/\n\/\/\/ The operator precedence has been set according to (uses the C and\n\/\/\/ C++ operator precedence): http:\/\/en.wikipedia.org\/wiki\/Order_of_operations\n\/\/\/ Operators with higher precedence are evaluated before operators\n\/\/\/ with relatively lower precedence. Unary operators are set to have\n\/\/\/ the highest precedence, this is not strictly correct for the power\n\/\/\/ operator e.g. \"-3**2\" = 9 but a lot of software tools (Bash shell,\n\/\/\/ Microsoft Excel, GNU bc, ...) use the same convention.\n\/\/\/\n\/\/\/ == Examples of valid expressions ==\n\/\/\/\n\/\/\/ \"65536 >> 15\" = 2\n\/\/\/ \"2**16\" = 65536\n\/\/\/ \"(0 + 0xDf234 - 1000)*3\/2%999\" = 828\n\/\/\/ \"-(2**2**2**2)\" = -65536\n\/\/\/ \"(0 + ~(0xDF234 & 1000) *3) \/-2\" = 817\n\/\/\/ \"(2**16) + (1 << 16) >> 0X5\" = 4096\n\/\/\/ \"5*-(2**(9+7))\/3+5*(1 & 0xFf123)\" = -109221\n\/\/\/\n\/\/\/ == About the algorithm used ==\n\/\/\/\n\/\/\/ calculator::eval(std::string&) relies on the ExpressionParser\n\/\/\/ class which is a simple C++ operator precedence parser with infix\n\/\/\/ notation for integer arithmetic expressions.\n\/\/\/ ExpressionParser has its roots in a JavaScript parser published\n\/\/\/ at: http:\/\/stackoverflow.com\/questions\/28256\/equation-expression-parser-with-precedence\/114961#114961\n\/\/\/ The same author has also published an article about his operator\n\/\/\/ precedence algorithm at PerlMonks:\n\/\/\/ http:\/\/www.perlmonks.org\/?node_id=554516\n\/\/\/\n\n#ifndef CALCULATOR_HPP\n#define CALCULATOR_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace calculator\n{\n\n\/\/\/ calculator::eval() throws a calculator::error if it fails\n\/\/\/ to evaluate the expression string.\n\/\/\/\nclass error : public std::runtime_error\n{\npublic:\n error(const std::string& expr, const std::string& message)\n : std::runtime_error(message),\n expr_(expr)\n { }\n#if __cplusplus >= 201103L\n ~error() { }\n#else\n ~error() throw() { }\n#endif\n std::string expression() const\n {\n return expr_;\n }\nprivate:\n std::string expr_;\n};\n\ntemplate \nclass ExpressionParser\n{\npublic:\n \/\/\/ Evaluate an integer arithmetic expression and return its result.\n \/\/\/ @throw error if parsing fails.\n \/\/\/\n T eval(const std::string& expr)\n {\n T result = 0;\n index_ = 0;\n expr_ = expr;\n try\n {\n result = parseExpr();\n if (!isEnd())\n unexpected();\n }\n catch (const calculator::error&)\n {\n while(!stack_.empty())\n stack_.pop();\n throw;\n }\n return result;\n }\n\n \/\/\/ Get the integer value of a character.\n T eval(char c)\n {\n std::string expr(1, c);\n return eval(expr);\n }\n\nprivate:\n enum\n {\n OPERATOR_NULL,\n OPERATOR_BITWISE_OR, \/\/\/ |\n OPERATOR_BITWISE_XOR, \/\/\/ ^\n OPERATOR_BITWISE_AND, \/\/\/ &\n OPERATOR_BITWISE_SHL, \/\/\/ <<\n OPERATOR_BITWISE_SHR, \/\/\/ >>\n OPERATOR_ADDITION, \/\/\/ +\n OPERATOR_SUBTRACTION, \/\/\/ -\n OPERATOR_MULTIPLICATION, \/\/\/ *\n OPERATOR_DIVISION, \/\/\/ \/\n OPERATOR_MODULO, \/\/\/ %\n OPERATOR_POWER, \/\/\/ **\n OPERATOR_EXPONENT \/\/\/ e, E\n };\n\n struct Operator\n {\n \/\/\/ Operator, one of the OPERATOR_* enum definitions\n int op;\n int precedence;\n \/\/\/ 'L' = left or 'R' = right\n int associativity;\n Operator(int opr, int prec, int assoc) :\n op(opr),\n precedence(prec),\n associativity(assoc)\n { }\n };\n\n struct OperatorValue\n {\n Operator op;\n T value;\n OperatorValue(const Operator& opr, T val) :\n op(opr),\n value(val)\n { }\n int getPrecedence() const\n {\n return op.precedence;\n }\n bool isNull() const\n {\n return op.op == OPERATOR_NULL;\n }\n };\n\n \/\/\/ Expression string\n std::string expr_;\n \/\/\/ Current expression index, incremented whilst parsing\n std::size_t index_;\n \/\/\/ The current operator and its left value\n \/\/\/ are pushed onto the stack if the operator on\n \/\/\/ top of the stack has lower precedence.\n std::stack stack_;\n\n \/\/\/ Exponentiation by squaring, x^n.\n static T pow(T x, T n)\n {\n T res = 1;\n while (n != 0)\n {\n if (n % 2 != 0)\n {\n res *= x;\n n -= 1;\n }\n x *= x;\n n \/= 2;\n }\n return res;\n }\n\n T checkZero(T value) const\n {\n if (value == 0)\n {\n std::string divOperators(\"\/%\");\n std::size_t division = expr_.find_last_of(divOperators, index_ - 2);\n std::ostringstream msg;\n msg << \"Parser error: division by 0\";\n if (division != std::string::npos)\n msg << \" (error token is \\\"\"\n << expr_.substr(division, expr_.size() - division)\n << \"\\\")\";\n throw calculator::error(expr_, msg.str());\n }\n return value;\n }\n\n T calculate(T v1, T v2, const Operator& op) const\n {\n switch (op.op)\n {\n case OPERATOR_BITWISE_OR: return v1 | v2;\n case OPERATOR_BITWISE_XOR: return v1 ^ v2;\n case OPERATOR_BITWISE_AND: return v1 & v2;\n case OPERATOR_BITWISE_SHL: return v1 << v2;\n case OPERATOR_BITWISE_SHR: return v1 >> v2;\n case OPERATOR_ADDITION: return v1 + v2;\n case OPERATOR_SUBTRACTION: return v1 - v2;\n case OPERATOR_MULTIPLICATION: return v1 * v2;\n case OPERATOR_DIVISION: return v1 \/ checkZero(v2);\n case OPERATOR_MODULO: return v1 % checkZero(v2);\n case OPERATOR_POWER: return pow(v1, v2);\n case OPERATOR_EXPONENT: return v1 * pow(10, v2);\n default: return 0;\n }\n }\n\n bool isEnd() const\n {\n return index_ >= expr_.size();\n }\n\n \/\/\/ Returns the character at the current expression index or\n \/\/\/ 0 if the end of the expression is reached.\n \/\/\/\n char getCharacter() const\n {\n if (!isEnd())\n return expr_[index_];\n return 0;\n }\n\n \/\/\/ Parse str at the current expression index.\n \/\/\/ @throw error if parsing fails.\n \/\/\/\n void expect(const std::string& str)\n {\n if (expr_.compare(index_, str.size(), str) != 0)\n unexpected();\n index_ += str.size();\n }\n\n void unexpected() const\n {\n std::ostringstream msg;\n msg << \"Syntax error: unexpected token \\\"\"\n << expr_.substr(index_, expr_.size() - index_)\n << \"\\\" at index \"\n << index_;\n throw calculator::error(expr_, msg.str());\n }\n\n \/\/\/ Eat all white space characters at the\n \/\/\/ current expression index.\n \/\/\/\n void eatSpaces()\n {\n while (std::isspace(getCharacter()) != 0)\n index_++;\n }\n\n \/\/\/ Parse a binary operator at the current expression index.\n \/\/\/ @return Operator with precedence and associativity.\n \/\/\/\n Operator parseOp()\n {\n eatSpaces();\n switch (getCharacter())\n {\n case '|': index_++; return Operator(OPERATOR_BITWISE_OR, 4, 'L');\n case '&': index_++; return Operator(OPERATOR_BITWISE_AND, 6, 'L');\n case '<': expect(\"<<\"); return Operator(OPERATOR_BITWISE_SHL, 9, 'L');\n case '>': expect(\">>\"); return Operator(OPERATOR_BITWISE_SHR, 9, 'L');\n case '+': index_++; return Operator(OPERATOR_ADDITION, 10, 'L');\n case '-': index_++; return Operator(OPERATOR_SUBTRACTION, 10, 'L');\n case '\/': index_++; return Operator(OPERATOR_DIVISION, 20, 'L');\n case '%': index_++; return Operator(OPERATOR_MODULO, 20, 'L');\n case '*': index_++; if (getCharacter() != '*')\n return Operator(OPERATOR_MULTIPLICATION, 20, 'L');\n index_++; return Operator(OPERATOR_POWER, 30, 'R');\n case '^': index_++; return Operator(OPERATOR_POWER, 30, 'R');\n case 'e': index_++; return Operator(OPERATOR_EXPONENT, 40, 'R');\n case 'E': index_++; return Operator(OPERATOR_EXPONENT, 40, 'R');\n default : return Operator(OPERATOR_NULL, 0, 'L');\n }\n }\n\n static T toInteger(char c)\n {\n if (c >= '0' && c <= '9') return c -'0';\n if (c >= 'a' && c <= 'f') return c -'a' + 0xa;\n if (c >= 'A' && c <= 'F') return c -'A' + 0xa;\n T noDigit = 0xf + 1;\n return noDigit;\n }\n\n T getInteger() const\n {\n return toInteger(getCharacter());\n }\n\n T parseDecimal()\n {\n T value = 0;\n for (T d; (d = getInteger()) <= 9; index_++)\n value = value * 10 + d;\n return value;\n }\n\n T parseHex()\n {\n index_ = index_ + 2;\n T value = 0;\n for (T h; (h = getInteger()) <= 0xf; index_++)\n value = value * 0x10 + h;\n return value;\n }\n\n bool isHex() const\n {\n if (index_ + 2 < expr_.size())\n {\n char x = expr_[index_ + 1];\n char h = expr_[index_ + 2];\n return (std::tolower(x) == 'x' && toInteger(h) <= 0xf);\n }\n return false;\n }\n\n \/\/\/ Parse an integer value at the current expression index.\n \/\/\/ The unary `+', `-' and `~' operators and opening\n \/\/\/ parentheses `(' cause recursion.\n \/\/\/\n T parseValue()\n {\n T val = 0;\n eatSpaces();\n switch (getCharacter())\n {\n case '0': if (isHex())\n val = parseHex();\n else\n val = parseDecimal();\n break;\n case '1': case '2': case '3': case '4': case '5':\n case '6': case '7': case '8': case '9':\n val = parseDecimal();\n break;\n case '(': index_++;\n val = parseExpr();\n eatSpaces();\n if (getCharacter() != ')')\n {\n if (!isEnd())\n unexpected();\n throw calculator::error(expr_, \"Syntax error: `)' expected at end of expression\");\n }\n index_++; break;\n case '~': index_++; val = ~parseValue(); break;\n case '+': index_++; val = parseValue(); break;\n case '-': index_++; val = parseValue() * static_cast(-1);\n break;\n default : if (!isEnd())\n unexpected();\n throw calculator::error(expr_, \"Syntax error: value expected at end of expression\");\n }\n return val;\n }\n\n \/\/\/ Parse all operations of the current parenthesis\n \/\/\/ level and the levels above, when done\n \/\/\/ return the result (value).\n \/\/\/\n T parseExpr()\n {\n stack_.push(OperatorValue(Operator(OPERATOR_NULL, 0, 'L'), 0));\n \/\/ first parse value on the left\n T value = parseValue();\n\n while (!stack_.empty())\n {\n \/\/ parse an operator (+, -, *, ...)\n Operator op(parseOp());\n while (op.precedence < stack_.top().getPrecedence() || (\n op.precedence == stack_.top().getPrecedence() &&\n op.associativity == 'L'))\n {\n \/\/ end reached\n if (stack_.top().isNull())\n {\n stack_.pop();\n return value;\n }\n \/\/ do the calculation (\"reduce\"), producing a new value\n value = calculate(stack_.top().value, value, stack_.top().op);\n stack_.pop();\n }\n\n \/\/ store on stack_ and continue parsing (\"shift\")\n stack_.push(OperatorValue(op, value));\n \/\/ parse value on the right\n value = parseValue();\n }\n return 0;\n }\n};\n\ntemplate \ninline T eval(const std::string& expression)\n{\n ExpressionParser parser;\n return parser.eval(expression);\n}\n\ntemplate \ninline T eval(char c)\n{\n ExpressionParser parser;\n return parser.eval(c);\n}\n\ninline int eval(const std::string& expression)\n{\n return eval(expression);\n}\n\ninline int eval(char c)\n{\n return eval(c);\n}\n\n} \/\/ namespace calculator\n\n#endif\n<|endoftext|>"} {"text":"#include \"..\/ris_lib\/ris_resources_from_file.h\"\n#include \"..\/ris_lib\/ris_bundle_compression.h\"\n#include \"..\/ris_lib\/ris_writing_files.h\"\n#include \"..\/ris_lib\/template.h\"\n#include \"..\/ris_lib\/ris_resource_loader.h\"\n#include \"..\/ris_lib\/ris_default_or_from_file.h\"\n#include \"..\/ris_lib\/ris_resource_snapshot.h\"\n#include \"..\/ris_lib\/ris_late_context.h\"\n#include \"..\/ris_lib\/ris_late.h\"\n#include \"..\/ris_lib\/ris_resource_loader.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n\nvoid print_usage() {\n std::cout\n << \"--- ris v0.2.0 ---\" << std::endl\n << \"a simple resource compiler for c++\" << std::endl\n << \"https:\/\/github.com\/d-led\/ris\" << std::endl\n << \"USAGE:\" << std::endl\n << \" ris \/.[json\/yml\/yaml] [.[json\/yml\/yaml]]\" << std::endl\n ;\n}\n\ntemplate \nstd::string member_name(TResource const& res) {\n if (!res.member_name.empty())\n return res.member_name;\n return res.name;\n}\n\nvoid process(std::string const& path, std::string const& source_template) {\n auto full_path = absolute(boost::filesystem::path(path));\n full_path.make_preferred();\n std::cout << \"reading \" << full_path.generic_string() << std::endl;\n\n auto user_resources = ris::load_resources_from_file(path);\n auto lookup = user_resources.to_lookup();\n std::cout << \"read \" << user_resources.resources().resources.size() << \" resources\" << std::endl;\n\n auto compression = ris::bundle_compression();\n auto ris_res = ris::default_or_from_file(source_template);\n auto template_snapshot = ris::resource_snapshot(ris_res);\n bool any_with_compression = std::any_of(std::begin(user_resources.resources().resources),\n std::end(user_resources.resources().resources),\n [&compression](ris::resource const& res) {\n return compression.is_legal(res.compression);\n });\n\n ris::write_to_temp_first_then_move header([&ris_res, &template_snapshot, &user_resources,&lookup](std::ostream& s) {\n template_snapshot[\"namespace_name\"] = user_resources.namespace_();\n template_snapshot[\"class_name\"] = user_resources.class_();\n auto lazy = ris::get_context(template_snapshot);\n lazy\n .lazy(\"header\", [&lazy, &ris_res](std::ostream& s) {\n ris::render(ris_res.Get(\"header\"), lazy, s);\n })\n .lazy(\"header_declarations\", [&ris_res,&user_resources,&lazy](std::ostream& s) {\n for (auto& resource : user_resources.resources().resources) {\n lazy.lazy(\"resource_member_name\", [&resource](std::ostream& s){\n s << member_name(resource);\n });\n ris::render(ris_res.Get(\"header_single_declaration\"), lazy, s);\n }\n })\n .lazy(\"header_resource_names\", [&ris_res, &user_resources, &lazy](std::ostream& s) {\n for (auto& resource : user_resources.resources().resources) {\n lazy.lazy(\"resource_name\", [&resource](std::ostream& s){\n s << resource.name;\n });\n ris::render(ris_res.Get(\"header_single_resource_name\"), lazy, s);\n }\n })\n ;\n ris::render(\"{{header}}\", lazy, s);\n }, user_resources.header());\n header.start();\n\n ris::write_to_temp_first_then_move source([&](std::ostream& s) {\n template_snapshot[\"namespace_name\"] = user_resources.namespace_();\n template_snapshot[\"class_name\"] = user_resources.class_();\n auto lazy = ris::get_context(template_snapshot);\n lazy\n .lazy(\"source\", [&lazy, &ris_res](std::ostream& s) {\n ris::render(ris_res.Get(\"source\"), lazy, s);\n })\n .lazy(\"optional_compression_header\", [&](std::ostream& s) {\n if (any_with_compression)\n s << \"#include \\n\";\n })\n .lazy(\"source_default_include\", [&](std::ostream& s) {\n s << \"#include \\\"\" << boost::filesystem::path(user_resources.header()).filename().generic_string() << \"\\\"\";\n })\n .lazy(\"source_definitions\", [&](std::ostream& s) {\n for (auto& resource : user_resources.resources().resources) {\n lazy\n .lazy(\"resource_member_name\", [&](std::ostream& s){\n s << member_name(resource);\n })\n .lazy(\"source_literal_bytes\", [&](std::ostream& s){\n static const unsigned MAX_IN_ONE_LINE = 100;\n std::string data = ris::resource_loader(resource, user_resources.base_path()).get();\n\n auto raw_size = data.size();\n\n if (compression.is_legal(resource.compression)) {\n data = compression.pack(resource.compression, data);\n auto new_size = data.size();\n std::cout << \"[\" << resource.compression << \"] \"\n << resource.name << \": \"\n << new_size << \"\/\" << raw_size\n << \" (\" << ((double)new_size \/ raw_size*100.0) << \"%)\" << std::endl;\n }\n\n int count = 0;\n\n for (char c : data) {\n if (count > MAX_IN_ONE_LINE - 1) {\n count = 0;\n }\n\n if (count == 0) {\n s << \"\\n \";\n }\n\n s << static_cast(c) << \", \";\n\n count++;\n }\n })\n .lazy(\"source_return_literal\", [&](std::ostream& s) {\n if (compression.is_legal(resource.compression)) {\n ris::render(ris_res.Get(\"source_return_compressed_literal\"), lazy, s);\n }\n else {\n ris::render(ris_res.Get(\"source_return_plain_literal\"), lazy, s);\n }\n })\n ;\n ris::render(ris_res.Get(\"source_single_definition\"), lazy, s);\n }\n })\n .lazy(\"source_getters\", [&](std::ostream& s) {\n for (auto& resource : user_resources.resources().resources) {\n lazy\n .lazy(\"resource_name\", [&resource](std::ostream& s){\n s << resource.name;\n })\n .lazy(\"resource_member_name\", [&](std::ostream& s){\n s << member_name(resource);\n })\n ;\n ris::render(ris_res.Get(\"source_single_getter\"), lazy, s);\n }\n })\n ;\n ris::render(\"{{source}}\", lazy, s);\n }, user_resources.source());\n source.start();\n}\n\nint main(int argc, char ** argv) {\n std::string source_template;\n\n switch (argc) {\n case 3:\n source_template = argv[2];\n \/\/ fall through\n case 2:\n try {\n process(argv[1], source_template);\n }\n catch (std::exception& e) {\n std::cerr << \"Error: \" << e.what() << std::endl;\n return 1;\n }\n break;\n default:\n print_usage();\n }\n}\nbump version [ci skip]#include \"..\/ris_lib\/ris_resources_from_file.h\"\n#include \"..\/ris_lib\/ris_bundle_compression.h\"\n#include \"..\/ris_lib\/ris_writing_files.h\"\n#include \"..\/ris_lib\/template.h\"\n#include \"..\/ris_lib\/ris_resource_loader.h\"\n#include \"..\/ris_lib\/ris_default_or_from_file.h\"\n#include \"..\/ris_lib\/ris_resource_snapshot.h\"\n#include \"..\/ris_lib\/ris_late_context.h\"\n#include \"..\/ris_lib\/ris_late.h\"\n#include \"..\/ris_lib\/ris_resource_loader.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n\nvoid print_usage() {\n std::cout\n << \"--- ris v0.3.0 ---\" << std::endl\n << \"a simple resource compiler for c++\" << std::endl\n << \"https:\/\/github.com\/d-led\/ris\" << std::endl\n << \"USAGE:\" << std::endl\n << \" ris \/.[json\/yml\/yaml] [.[json\/yml\/yaml]]\" << std::endl\n ;\n}\n\ntemplate \nstd::string member_name(TResource const& res) {\n if (!res.member_name.empty())\n return res.member_name;\n return res.name;\n}\n\nvoid process(std::string const& path, std::string const& source_template) {\n auto full_path = absolute(boost::filesystem::path(path));\n full_path.make_preferred();\n std::cout << \"reading \" << full_path.generic_string() << std::endl;\n\n auto user_resources = ris::load_resources_from_file(path);\n auto lookup = user_resources.to_lookup();\n std::cout << \"read \" << user_resources.resources().resources.size() << \" resources\" << std::endl;\n\n auto compression = ris::bundle_compression();\n auto ris_res = ris::default_or_from_file(source_template);\n auto template_snapshot = ris::resource_snapshot(ris_res);\n bool any_with_compression = std::any_of(std::begin(user_resources.resources().resources),\n std::end(user_resources.resources().resources),\n [&compression](ris::resource const& res) {\n return compression.is_legal(res.compression);\n });\n\n ris::write_to_temp_first_then_move header([&ris_res, &template_snapshot, &user_resources,&lookup](std::ostream& s) {\n template_snapshot[\"namespace_name\"] = user_resources.namespace_();\n template_snapshot[\"class_name\"] = user_resources.class_();\n auto lazy = ris::get_context(template_snapshot);\n lazy\n .lazy(\"header\", [&lazy, &ris_res](std::ostream& s) {\n ris::render(ris_res.Get(\"header\"), lazy, s);\n })\n .lazy(\"header_declarations\", [&ris_res,&user_resources,&lazy](std::ostream& s) {\n for (auto& resource : user_resources.resources().resources) {\n lazy.lazy(\"resource_member_name\", [&resource](std::ostream& s){\n s << member_name(resource);\n });\n ris::render(ris_res.Get(\"header_single_declaration\"), lazy, s);\n }\n })\n .lazy(\"header_resource_names\", [&ris_res, &user_resources, &lazy](std::ostream& s) {\n for (auto& resource : user_resources.resources().resources) {\n lazy.lazy(\"resource_name\", [&resource](std::ostream& s){\n s << resource.name;\n });\n ris::render(ris_res.Get(\"header_single_resource_name\"), lazy, s);\n }\n })\n ;\n ris::render(\"{{header}}\", lazy, s);\n }, user_resources.header());\n header.start();\n\n ris::write_to_temp_first_then_move source([&](std::ostream& s) {\n template_snapshot[\"namespace_name\"] = user_resources.namespace_();\n template_snapshot[\"class_name\"] = user_resources.class_();\n auto lazy = ris::get_context(template_snapshot);\n lazy\n .lazy(\"source\", [&lazy, &ris_res](std::ostream& s) {\n ris::render(ris_res.Get(\"source\"), lazy, s);\n })\n .lazy(\"optional_compression_header\", [&](std::ostream& s) {\n if (any_with_compression)\n s << \"#include \\n\";\n })\n .lazy(\"source_default_include\", [&](std::ostream& s) {\n s << \"#include \\\"\" << boost::filesystem::path(user_resources.header()).filename().generic_string() << \"\\\"\";\n })\n .lazy(\"source_definitions\", [&](std::ostream& s) {\n for (auto& resource : user_resources.resources().resources) {\n lazy\n .lazy(\"resource_member_name\", [&](std::ostream& s){\n s << member_name(resource);\n })\n .lazy(\"source_literal_bytes\", [&](std::ostream& s){\n static const unsigned MAX_IN_ONE_LINE = 100;\n std::string data = ris::resource_loader(resource, user_resources.base_path()).get();\n\n auto raw_size = data.size();\n\n if (compression.is_legal(resource.compression)) {\n data = compression.pack(resource.compression, data);\n auto new_size = data.size();\n std::cout << \"[\" << resource.compression << \"] \"\n << resource.name << \": \"\n << new_size << \"\/\" << raw_size\n << \" (\" << ((double)new_size \/ raw_size*100.0) << \"%)\" << std::endl;\n }\n\n int count = 0;\n\n for (char c : data) {\n if (count > MAX_IN_ONE_LINE - 1) {\n count = 0;\n }\n\n if (count == 0) {\n s << \"\\n \";\n }\n\n s << static_cast(c) << \", \";\n\n count++;\n }\n })\n .lazy(\"source_return_literal\", [&](std::ostream& s) {\n if (compression.is_legal(resource.compression)) {\n ris::render(ris_res.Get(\"source_return_compressed_literal\"), lazy, s);\n }\n else {\n ris::render(ris_res.Get(\"source_return_plain_literal\"), lazy, s);\n }\n })\n ;\n ris::render(ris_res.Get(\"source_single_definition\"), lazy, s);\n }\n })\n .lazy(\"source_getters\", [&](std::ostream& s) {\n for (auto& resource : user_resources.resources().resources) {\n lazy\n .lazy(\"resource_name\", [&resource](std::ostream& s){\n s << resource.name;\n })\n .lazy(\"resource_member_name\", [&](std::ostream& s){\n s << member_name(resource);\n })\n ;\n ris::render(ris_res.Get(\"source_single_getter\"), lazy, s);\n }\n })\n ;\n ris::render(\"{{source}}\", lazy, s);\n }, user_resources.source());\n source.start();\n}\n\nint main(int argc, char ** argv) {\n std::string source_template;\n\n switch (argc) {\n case 3:\n source_template = argv[2];\n \/\/ fall through\n case 2:\n try {\n process(argv[1], source_template);\n }\n catch (std::exception& e) {\n std::cerr << \"Error: \" << e.what() << std::endl;\n return 1;\n }\n break;\n default:\n print_usage();\n }\n}\n<|endoftext|>"} {"text":"\/**\n * @author Blurred-9L\n * @file Tokenizer.cpp\n *\/\n\n#include \"Tokenizer.h\"\n#include \"AbstractAutomata.h\"\n#include \"KeywordSet.h\"\n\n#include \"..\/Core\/Token.h\"\n#include \"..\/Core\/LineFileReader.h\"\n#include \"..\/Core\/ErrorKeeper.h\"\n\n\/**\n * @details Constructs a Tokenizer object. The object constructed\n * does not have a set automata, keyword set or line reader,\n * so the user should remember to set them before calling\n * getToken().\n *\/\nTokenizer::Tokenizer() :\n automata_(0), keywords_(0), lineReader_(0), errorKeeper_(0), line_(),\n charIdx(-1), tokenStartIndex(-1), tokenLineNumber_(0)\n{\n}\n\n\/**\n * @details Constructs a Tokenizer object with the given automata,\n * keyword set and line reader.\n *\n * @param[in] automata The automata to use. Should be dynamically\n * allocated.\n * @param[in] keywords The keyword set to use. Should be dynamically\n * allocated.\n * @param[in] lineReader The lineReader set to use. Should be dynamically\n * allocated.\n * @param[in] errorKeeper The errorKeeper set to use. Should be dynamically\n * allocated.\n *\/\nTokenizer::Tokenizer(AbstractAutomata * automata, KeywordSet * keywords,\n LineFileReader * lineReader, ErrorKeeper * errorKeeper) :\n automata_(automata), keywords_(keywords), lineReader_(lineReader),\n errorKeeper_(errorKeeper), line_(), charIdx(-1), tokenStartIndex(-1)\n{\n}\n\n\/**\n * @details Destroys the Tokenizer object.\n *\/\nTokenizer::~Tokenizer()\n{\n if (automata_ != 0) {\n delete automata_;\n }\n if (keywords_ != 0) {\n delete keywords_;\n }\n if (lineReader_ != 0) {\n delete lineReader_;\n }\n if (errorKeeper_ != 0) {\n delete errorKeeper_;\n }\n}\n\n\/**\n * @details Gets the automata attribute from the Tokenizer.\n *\n * @return A constant reference to the automata attribute.\n *\/\nconst AbstractAutomata & Tokenizer::automata() const\n{\n return *automata_;\n}\n\n\/**\n * @details Gets the automata attribute from the Tokenizer.\n *\n * @return A reference to the automata attribute.\n *\/\nAbstractAutomata & Tokenizer::automata()\n{\n return *automata_;\n}\n\n\/**\n * @details Gets the keywords attribute from the Tokenizer.\n *\n * @return A constant reference to the keywords attribute.\n *\/\nconst KeywordSet & Tokenizer::keywords() const\n{\n return *keywords_;\n}\n\n\/**\n * @details Gets the keywords attribute from the Tokenizer.\n *\n * @return A reference to the keywords attribute.\n *\/\nKeywordSet & Tokenizer::keywords()\n{\n return *keywords_;\n}\n\n\/**\n * @details Gets the lineReader attribute from the Tokenizer.\n *\n * @return A constant pointer to the lineReader attribute.\n *\/\nconst LineFileReader * Tokenizer::lineReader() const\n{\n return lineReader_;\n}\n\n\/**\n * @details Gets the lineReader attribute from the Tokenizer.\n *\n * @return A pointer to the lineReader attribute.\n *\/\nLineFileReader * Tokenizer::lineReader()\n{\n return lineReader_;\n}\n\n\/**\n * @details Gets the errorKeeper attribute from the Tokenizer.\n *\n * @return A constant pointer to the errorKeeper attribute.\n *\/\nconst ErrorKeeper * Tokenizer::errorKeeper() const\n{\n return errorKeeper_;\n}\n\n\/**\n * @details Gets the errorKeeper attribute from the Tokenizer.\n *\n * @return A pointer to the errorKeeper attribute.\n *\/\nErrorKeeper * Tokenizer::errorKeeper()\n{\n return errorKeeper_;\n}\n\n\/**\n * @details Gets the tokenLineNumber attribute of the tokenizer.\n *\n * @return The value of the tokenLineNumber attribute.\n *\/\nint Tokenizer::tokenLineNumber() const\n{\n return tokenLineNumber_;\n}\n\n\/**\n * @details Sets the automata to be used when tokenizing\n * the given input string. The automata passed\n * should be dynamically allocated. If a previous\n * automata had been set, it will be deleted.\n *\n * @param[in] automata The automata to use.\n *\/\nvoid Tokenizer::setAutomata(AbstractAutomata * automata)\n{\n if (automata != 0) {\n if (automata_ != 0) {\n delete automata_;\n }\n automata_ = automata;\n }\n}\n\n\/**\n * @details Sets the keyword set to be used when tokenizing\n * the given input string. The keyword set passed\n * should have been dynamically allocated. If a\n * previous keyword set had been set, it will be\n * deleted.\n *\n * @param[in] keywords The keyword set to use.\n *\/\nvoid Tokenizer::setKeywords(KeywordSet * keywords)\n{\n if (keywords != 0) {\n if (keywords_ != 0) {\n delete keywords_;\n }\n keywords_ = keywords;\n }\n}\n\n\/**\n * @details Sets the line reader to be used when this tokenizer\n * consumes a line. The lineReader passed should have\n * been dynamically allocated. If a previous line reader\n * had been set, it will be deleted. Since the line reader\n * is not strictly necessary for the Tokenizer to\n * function properly, it can be set to a 0 value.\n *\n * @param[in] lineReader The lineReader to use.\n *\/\nvoid Tokenizer::setLineReader(LineFileReader * lineReader)\n{\n if (lineReader_ != 0) {\n delete lineReader_;\n }\n lineReader_ = lineReader;\n}\n\n\/**\n * @details Sets the error keeper to be used whenever an error is\n * raised by this tokenizer. The errorKeeper passed should\n * have been dynamically allocated. If a previous error keeper\n * had been set, it will be deleted. Since the error keeper\n * is not strictly necessary for the Tokenizer to\n * function properly, it can be set to a 0 value.\n *\n * @param[in] errorKeeper The errorKeeper to use.\n *\/\nvoid Tokenizer::setErrorKeeper(ErrorKeeper * errorKeeper)\n{\n if (errorKeeper_ != 0) {\n delete errorKeeper_;\n }\n errorKeeper_ = errorKeeper;\n}\n\n\/**\n * @details Sets the line to use when tokenizing and also\n * resets the index used when iterating over it.\n *\n * @param[in] line The line to be tokenized.\n *\/\nvoid Tokenizer::setLine(const string & line)\n{\n line_ = line;\n charIdx = 0;\n}\n\n\/**\n * @details Sets the line number on which the given tokens\n * were found.\n *\n * @param[in] tokenLineNumber The line number.\n *\/\nvoid Tokenizer::setTokenLineNumber(int tokenLineNumber)\n{\n tokenLineNumber_ = tokenLineNumber;\n}\n\n\/**\n * @details Gets the next token from the given input string.\n * The token returned will be dynamically allocated,\n * so one should remember to deallocate it later.\n *\n * @return The token found or 0 if no more tokens can be\n * extracted.\n *\/\nToken * Tokenizer::getToken()\n{\n Token * token = 0;\n string symbol;\n int lastState;\n \n if (lineReader_ != 0) {\n while (charIdx >= line_.length() && lineReader_->hasNext()) {\n lineReader_->sendNextLine(*this);\n }\n }\n \n if ((charIdx < line_.length()) && (automata_ != 0) && (keywords_ != 0)) {\n lastState = getTokenString(symbol);\n if (keywords_->isKeyword(symbol)) {\n token = new Token(keywords_->getKeywordId(symbol), tokenStartIndex,\n tokenLineNumber_, symbol);\n } else if (automata_->isAcceptState(lastState)) {\n token = new Token(automata_->getTokenType(lastState), tokenStartIndex,\n tokenLineNumber_, symbol);\n }\n }\n \n return token;\n}\n\n\/**\n * @details Checks if an error has ocurred during the execution\n * of the tokenizer.\n *\n * @return A boolean value indicating if an error has occur.\n *\/\nbool Tokenizer::hasError() const\n{\n bool errorExists = false;\n \n if (errorKeeper_ != 0) {\n errorExists = errorKeeper_->hasError();\n }\n \n return errorExists;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Private \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/**\n * @details Algorithm used to build the substring of the\n * input string to be included on the next token.\n *\n * @param[out] symbol The string on which to copy the token's symbol.\n *\n * @return Returns the state at which the algorithm stopped. If\n * an error ocurred, -1 is returned. If the algorithm \n * stopped because the end of the string was reached\n * before a full token was found, the last state is\n * returned.\n *\/\nint Tokenizer::getTokenString(string & symbol)\n{\n int state = 0;\n unsigned lineLength = line_.length();\n bool done = false;\n bool error = false;\n bool gotFirstChar = false;\n \n while ((!done) && (!error) && (charIdx < lineLength)) {\n state = automata_->nextState(state, line_[charIdx]);\n if (state > 0) {\n if (!gotFirstChar) {\n gotFirstChar = true;\n tokenStartIndex = charIdx;\n }\n symbol.push_back(line_[charIdx]);\n if (automata_->isAcceptState(state)) {\n if (!automata_->includeNextChar(state, line_, charIdx)) {\n done = true;\n }\n }\n } else if (state < 0) {\n error = true;\n }\n charIdx++;\n }\n \n if (error) {\n if (errorKeeper_ != 0) {\n errorKeeper_->addError(LEXIC_INPUT_ERROR, \"Lexic Error: Wrong token formation | Unexpected symbol.\");\n }\n } else if (!done) {\n if (errorKeeper_ != 0) {\n errorKeeper_->addError(TOKEN_NO_END_ERROR, \"Lexic Error: Could not finish building last token.\");\n }\n }\n \n return state;\n}\nFixes bug where whitespace only lines caused Tokenizer to fail.\/**\n * @author Blurred-9L\n * @file Tokenizer.cpp\n *\/\n\n#include \"Tokenizer.h\"\n#include \"AbstractAutomata.h\"\n#include \"KeywordSet.h\"\n\n#include \"..\/Core\/Token.h\"\n#include \"..\/Core\/LineFileReader.h\"\n#include \"..\/Core\/ErrorKeeper.h\"\n\n#include \n\n\/**\n * @details Constructs a Tokenizer object. The object constructed\n * does not have a set automata, keyword set or line reader,\n * so the user should remember to set them before calling\n * getToken().\n *\/\nTokenizer::Tokenizer() :\n automata_(0), keywords_(0), lineReader_(0), errorKeeper_(0), line_(),\n charIdx(-1), tokenStartIndex(-1), tokenLineNumber_(0)\n{\n}\n\n\/**\n * @details Constructs a Tokenizer object with the given automata,\n * keyword set and line reader.\n *\n * @param[in] automata The automata to use. Should be dynamically\n * allocated.\n * @param[in] keywords The keyword set to use. Should be dynamically\n * allocated.\n * @param[in] lineReader The lineReader set to use. Should be dynamically\n * allocated.\n * @param[in] errorKeeper The errorKeeper set to use. Should be dynamically\n * allocated.\n *\/\nTokenizer::Tokenizer(AbstractAutomata * automata, KeywordSet * keywords,\n LineFileReader * lineReader, ErrorKeeper * errorKeeper) :\n automata_(automata), keywords_(keywords), lineReader_(lineReader),\n errorKeeper_(errorKeeper), line_(), charIdx(-1), tokenStartIndex(-1)\n{\n}\n\n\/**\n * @details Destroys the Tokenizer object.\n *\/\nTokenizer::~Tokenizer()\n{\n if (automata_ != 0) {\n delete automata_;\n }\n if (keywords_ != 0) {\n delete keywords_;\n }\n if (lineReader_ != 0) {\n delete lineReader_;\n }\n if (errorKeeper_ != 0) {\n delete errorKeeper_;\n }\n}\n\n\/**\n * @details Gets the automata attribute from the Tokenizer.\n *\n * @return A constant reference to the automata attribute.\n *\/\nconst AbstractAutomata & Tokenizer::automata() const\n{\n return *automata_;\n}\n\n\/**\n * @details Gets the automata attribute from the Tokenizer.\n *\n * @return A reference to the automata attribute.\n *\/\nAbstractAutomata & Tokenizer::automata()\n{\n return *automata_;\n}\n\n\/**\n * @details Gets the keywords attribute from the Tokenizer.\n *\n * @return A constant reference to the keywords attribute.\n *\/\nconst KeywordSet & Tokenizer::keywords() const\n{\n return *keywords_;\n}\n\n\/**\n * @details Gets the keywords attribute from the Tokenizer.\n *\n * @return A reference to the keywords attribute.\n *\/\nKeywordSet & Tokenizer::keywords()\n{\n return *keywords_;\n}\n\n\/**\n * @details Gets the lineReader attribute from the Tokenizer.\n *\n * @return A constant pointer to the lineReader attribute.\n *\/\nconst LineFileReader * Tokenizer::lineReader() const\n{\n return lineReader_;\n}\n\n\/**\n * @details Gets the lineReader attribute from the Tokenizer.\n *\n * @return A pointer to the lineReader attribute.\n *\/\nLineFileReader * Tokenizer::lineReader()\n{\n return lineReader_;\n}\n\n\/**\n * @details Gets the errorKeeper attribute from the Tokenizer.\n *\n * @return A constant pointer to the errorKeeper attribute.\n *\/\nconst ErrorKeeper * Tokenizer::errorKeeper() const\n{\n return errorKeeper_;\n}\n\n\/**\n * @details Gets the errorKeeper attribute from the Tokenizer.\n *\n * @return A pointer to the errorKeeper attribute.\n *\/\nErrorKeeper * Tokenizer::errorKeeper()\n{\n return errorKeeper_;\n}\n\n\/**\n * @details Gets the tokenLineNumber attribute of the tokenizer.\n *\n * @return The value of the tokenLineNumber attribute.\n *\/\nint Tokenizer::tokenLineNumber() const\n{\n return tokenLineNumber_;\n}\n\n\/**\n * @details Sets the automata to be used when tokenizing\n * the given input string. The automata passed\n * should be dynamically allocated. If a previous\n * automata had been set, it will be deleted.\n *\n * @param[in] automata The automata to use.\n *\/\nvoid Tokenizer::setAutomata(AbstractAutomata * automata)\n{\n if (automata != 0) {\n if (automata_ != 0) {\n delete automata_;\n }\n automata_ = automata;\n }\n}\n\n\/**\n * @details Sets the keyword set to be used when tokenizing\n * the given input string. The keyword set passed\n * should have been dynamically allocated. If a\n * previous keyword set had been set, it will be\n * deleted.\n *\n * @param[in] keywords The keyword set to use.\n *\/\nvoid Tokenizer::setKeywords(KeywordSet * keywords)\n{\n if (keywords != 0) {\n if (keywords_ != 0) {\n delete keywords_;\n }\n keywords_ = keywords;\n }\n}\n\n\/**\n * @details Sets the line reader to be used when this tokenizer\n * consumes a line. The lineReader passed should have\n * been dynamically allocated. If a previous line reader\n * had been set, it will be deleted. Since the line reader\n * is not strictly necessary for the Tokenizer to\n * function properly, it can be set to a 0 value.\n *\n * @param[in] lineReader The lineReader to use.\n *\/\nvoid Tokenizer::setLineReader(LineFileReader * lineReader)\n{\n if (lineReader_ != 0) {\n delete lineReader_;\n }\n lineReader_ = lineReader;\n}\n\n\/**\n * @details Sets the error keeper to be used whenever an error is\n * raised by this tokenizer. The errorKeeper passed should\n * have been dynamically allocated. If a previous error keeper\n * had been set, it will be deleted. Since the error keeper\n * is not strictly necessary for the Tokenizer to\n * function properly, it can be set to a 0 value.\n *\n * @param[in] errorKeeper The errorKeeper to use.\n *\/\nvoid Tokenizer::setErrorKeeper(ErrorKeeper * errorKeeper)\n{\n if (errorKeeper_ != 0) {\n delete errorKeeper_;\n }\n errorKeeper_ = errorKeeper;\n}\n\n\/**\n * @details Sets the line to use when tokenizing and also\n * resets the index used when iterating over it.\n *\n * @param[in] line The line to be tokenized.\n *\/\nvoid Tokenizer::setLine(const string & line)\n{\n line_ = line;\n charIdx = 0;\n}\n\n\/**\n * @details Sets the line number on which the given tokens\n * were found.\n *\n * @param[in] tokenLineNumber The line number.\n *\/\nvoid Tokenizer::setTokenLineNumber(int tokenLineNumber)\n{\n tokenLineNumber_ = tokenLineNumber;\n}\n\n\/**\n * @details Gets the next token from the given input string.\n * The token returned will be dynamically allocated,\n * so one should remember to deallocate it later.\n *\n * @return The token found or 0 if no more tokens can be\n * extracted.\n *\/\nToken * Tokenizer::getToken()\n{\n Token * token = 0;\n string symbol;\n int lastState;\n \n if (lineReader_ != 0) {\n while ((charIdx >= line_.length() || spaceOnlyLine()) && lineReader_->hasNext()) {\n lineReader_->sendNextLine(*this);\n }\n }\n \n if ((charIdx < line_.length()) && (automata_ != 0) && (keywords_ != 0)) {\n lastState = getTokenString(symbol);\n if (keywords_->isKeyword(symbol)) {\n token = new Token(keywords_->getKeywordId(symbol), tokenStartIndex,\n tokenLineNumber_, symbol);\n } else if (automata_->isAcceptState(lastState)) {\n token = new Token(automata_->getTokenType(lastState), tokenStartIndex,\n tokenLineNumber_, symbol);\n }\n }\n \n return token;\n}\n\n\/**\n * @details Checks if an error has ocurred during the execution\n * of the tokenizer.\n *\n * @return A boolean value indicating if an error has occur.\n *\/\nbool Tokenizer::hasError() const\n{\n bool errorExists = false;\n \n if (errorKeeper_ != 0) {\n errorExists = errorKeeper_->hasError();\n }\n \n return errorExists;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Private \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/**\n * @details Algorithm used to build the substring of the\n * input string to be included on the next token.\n *\n * @param[out] symbol The string on which to copy the token's symbol.\n *\n * @return Returns the state at which the algorithm stopped. If\n * an error ocurred, -1 is returned. If the algorithm \n * stopped because the end of the string was reached\n * before a full token was found, the last state is\n * returned.\n *\/\nint Tokenizer::getTokenString(string & symbol)\n{\n int state = 0;\n unsigned lineLength = line_.length();\n bool done = false;\n bool error = false;\n bool gotFirstChar = false;\n \n while ((!done) && (!error) && (charIdx < lineLength)) {\n state = automata_->nextState(state, line_[charIdx]);\n if (state > 0) {\n if (!gotFirstChar) {\n gotFirstChar = true;\n tokenStartIndex = charIdx;\n }\n symbol.push_back(line_[charIdx]);\n if (automata_->isAcceptState(state)) {\n if (!automata_->includeNextChar(state, line_, charIdx)) {\n done = true;\n }\n }\n } else if (state < 0) {\n error = true;\n }\n charIdx++;\n }\n \n if (error) {\n if (errorKeeper_ != 0) {\n errorKeeper_->addError(LEXIC_INPUT_ERROR, \"Lexic Error: Wrong token formation | Unexpected symbol.\");\n }\n } else if (!done) {\n if (errorKeeper_ != 0) {\n errorKeeper_->addError(TOKEN_NO_END_ERROR, \"Lexic Error: Could not finish building last token.\");\n }\n }\n \n return state;\n}\n\n\/**\n * @details Checks if the line to be tokenized only has whitespaces.\n *\n * @return A boolean value indicating if a whitespace only line has\n * been set or read.\n *\/\nbool Tokenizer::spaceOnlyLine()\n{\n int size = line_.size();\n bool spaceOnly = true;\n \n for (int i = 0; i < size && spaceOnly; i++) {\n if (!isspace(line_[i])) {\n spaceOnly = false;\n }\n }\n \n return spaceOnly;\n}\n<|endoftext|>"} {"text":"\/\/ condition.cxx - Declarations and inline methods for property conditions.\n\/\/\n\/\/ Written by David Megginson, started 2000.\n\/\/ CLO May 2003 - Split out condition specific code.\n\/\/\n\/\/ This file is in the Public Domain, and comes with no warranty.\n\/\/\n\/\/ $Id$\n\n#ifdef HAVE_CONFIG_H\n# include \n#endif\n\n\/\/ #include \n\n#include \n\n#include \"props.hxx\"\n#include \"condition.hxx\"\n\nusing std::istream;\nusing std::ostream;\n\n\n\n\f\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Implementation of SGCondition.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSGCondition::SGCondition ()\n{\n}\n\nSGCondition::~SGCondition ()\n{\n}\n\n\n\f\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Implementation of SGPropertyCondition.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSGPropertyCondition::SGPropertyCondition ( SGPropertyNode *prop_root,\n const char *propname )\n : _node( prop_root->getNode(propname, true) )\n{\n}\n\nSGPropertyCondition::~SGPropertyCondition ()\n{\n}\n\n\n\f\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Implementation of SGNotCondition.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSGNotCondition::SGNotCondition (SGCondition * condition)\n : _condition(condition)\n{\n}\n\nSGNotCondition::~SGNotCondition ()\n{\n}\n\nbool\nSGNotCondition::test () const\n{\n return !(_condition->test());\n}\n\n\n\f\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Implementation of SGAndCondition.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSGAndCondition::SGAndCondition ()\n{\n}\n\nSGAndCondition::~SGAndCondition ()\n{\n}\n\nbool\nSGAndCondition::test () const\n{\n int nConditions = _conditions.size();\n for (int i = 0; i < nConditions; i++) {\n if (!_conditions[i]->test())\n return false;\n }\n return true;\n}\n\nvoid\nSGAndCondition::addCondition (SGCondition * condition)\n{\n _conditions.push_back(condition);\n}\n\n\n\f\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Implementation of SGOrCondition.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSGOrCondition::SGOrCondition ()\n{\n}\n\nSGOrCondition::~SGOrCondition ()\n{\n}\n\nbool\nSGOrCondition::test () const\n{\n int nConditions = _conditions.size();\n for (int i = 0; i < nConditions; i++) {\n if (_conditions[i]->test())\n return true;\n }\n return false;\n}\n\nvoid\nSGOrCondition::addCondition (SGCondition * condition)\n{\n _conditions.push_back(condition);\n}\n\n\n\f\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Implementation of SGComparisonCondition.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic int\ndoComparison (const SGPropertyNode * left, const SGPropertyNode *right)\n{\n switch (left->getType()) {\n case SGPropertyNode::BOOL: {\n bool v1 = left->getBoolValue();\n bool v2 = right->getBoolValue();\n if (v1 < v2)\n return SGComparisonCondition::LESS_THAN;\n else if (v1 > v2)\n return SGComparisonCondition::GREATER_THAN;\n else\n return SGComparisonCondition::EQUALS;\n break;\n }\n case SGPropertyNode::INT: {\n int v1 = left->getIntValue();\n int v2 = right->getIntValue();\n if (v1 < v2)\n return SGComparisonCondition::LESS_THAN;\n else if (v1 > v2)\n return SGComparisonCondition::GREATER_THAN;\n else\n return SGComparisonCondition::EQUALS;\n break;\n }\n case SGPropertyNode::LONG: {\n long v1 = left->getLongValue();\n long v2 = right->getLongValue();\n if (v1 < v2)\n return SGComparisonCondition::LESS_THAN;\n else if (v1 > v2)\n return SGComparisonCondition::GREATER_THAN;\n else\n return SGComparisonCondition::EQUALS;\n break;\n }\n case SGPropertyNode::FLOAT: {\n float v1 = left->getFloatValue();\n float v2 = right->getFloatValue();\n if (v1 < v2)\n return SGComparisonCondition::LESS_THAN;\n else if (v1 > v2)\n return SGComparisonCondition::GREATER_THAN;\n else\n return SGComparisonCondition::EQUALS;\n break;\n }\n case SGPropertyNode::DOUBLE: {\n double v1 = left->getDoubleValue();\n double v2 = right->getDoubleValue();\n if (v1 < v2)\n return SGComparisonCondition::LESS_THAN;\n else if (v1 > v2)\n return SGComparisonCondition::GREATER_THAN;\n else\n return SGComparisonCondition::EQUALS;\n break;\n }\n case SGPropertyNode::STRING: \n case SGPropertyNode::NONE:\n case SGPropertyNode::UNSPECIFIED: {\n string v1 = left->getStringValue();\n string v2 = right->getStringValue();\n if (v1 < v2)\n return SGComparisonCondition::LESS_THAN;\n else if (v1 > v2)\n return SGComparisonCondition::GREATER_THAN;\n else\n return SGComparisonCondition::EQUALS;\n break;\n }\n }\n throw sg_exception(\"condition: unrecognized node type in comparison\");\n return 0;\n}\n\n\nSGComparisonCondition::SGComparisonCondition (Type type, bool reverse)\n : _type(type),\n _reverse(reverse),\n _left_property(0),\n _right_property(0),\n _right_value(0)\n{\n}\n\nSGComparisonCondition::~SGComparisonCondition ()\n{\n}\n\nbool\nSGComparisonCondition::test () const\n{\n\t\t\t\t\/\/ Always fail if incompletely specified\n if (_left_property == 0 ||\n (_right_property == 0 && _right_value == 0))\n return false;\n\n\t\t\t\t\/\/ Get LESS_THAN, EQUALS, or GREATER_THAN\n int cmp =\n doComparison(_left_property,\n\t\t (_right_property != 0 ? _right_property : _right_value));\n if (!_reverse)\n return (cmp == _type);\n else\n return (cmp != _type);\n}\n\nvoid\nSGComparisonCondition::setLeftProperty( SGPropertyNode *prop_root,\n const char * propname )\n{\n _left_property = prop_root->getNode(propname, true);\n}\n\nvoid\nSGComparisonCondition::setRightProperty( SGPropertyNode *prop_root,\n const char * propname )\n{\n _right_value = 0;\n _right_property = prop_root->getNode(propname, true);\n}\n\nvoid\nSGComparisonCondition::setRightValue (const SGPropertyNode *node)\n{\n _right_property = 0;\n _right_value = new SGPropertyNode(*node);\n}\n\n\n\f\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Read a condition and use it if necessary.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ Forward declaration\nstatic SGCondition * readCondition( SGPropertyNode *prop_root,\n const SGPropertyNode *node );\n\nstatic SGCondition *\nreadPropertyCondition( SGPropertyNode *prop_root,\n const SGPropertyNode *node )\n{\n return new SGPropertyCondition( prop_root, node->getStringValue() );\n}\n\nstatic SGCondition *\nreadNotCondition( SGPropertyNode *prop_root, const SGPropertyNode *node )\n{\n int nChildren = node->nChildren();\n for (int i = 0; i < nChildren; i++) {\n const SGPropertyNode * child = node->getChild(i);\n SGCondition * condition = readCondition(prop_root, child);\n if (condition != 0)\n return new SGNotCondition(condition);\n }\n SG_LOG(SG_COCKPIT, SG_ALERT, \"empty 'not' condition\");\n return 0;\n}\n\nstatic SGCondition *\nreadAndConditions( SGPropertyNode *prop_root, const SGPropertyNode *node )\n{\n SGAndCondition * andCondition = new SGAndCondition;\n int nChildren = node->nChildren();\n for (int i = 0; i < nChildren; i++) {\n const SGPropertyNode * child = node->getChild(i);\n SGCondition * condition = readCondition(prop_root, child);\n if (condition != 0)\n andCondition->addCondition(condition);\n }\n return andCondition;\n}\n\nstatic SGCondition *\nreadOrConditions( SGPropertyNode *prop_root, const SGPropertyNode *node )\n{\n SGOrCondition * orCondition = new SGOrCondition;\n int nChildren = node->nChildren();\n for (int i = 0; i < nChildren; i++) {\n const SGPropertyNode * child = node->getChild(i);\n SGCondition * condition = readCondition(prop_root, child);\n if (condition != 0)\n orCondition->addCondition(condition);\n }\n return orCondition;\n}\n\nstatic SGCondition *\nreadComparison( SGPropertyNode *prop_root,\n const SGPropertyNode *node,\n SGComparisonCondition::Type type,\n\t\tbool reverse)\n{\n SGComparisonCondition * condition = new SGComparisonCondition(type, reverse);\n condition->setLeftProperty(prop_root, node->getStringValue(\"property[0]\"));\n if (node->hasValue(\"property[1]\"))\n condition->setRightProperty(prop_root, node->getStringValue(\"property[1]\"));\n else if (node->hasValue(\"value\"))\n condition->setRightValue(node->getChild(\"value\", 0));\n else\n throw sg_exception(\"condition: comparison without property[1] or value\");\n\n return condition;\n}\n\nstatic SGCondition *\nreadCondition( SGPropertyNode *prop_root, const SGPropertyNode *node )\n{\n const string &name = node->getName();\n if (name == \"property\")\n return readPropertyCondition(prop_root, node);\n else if (name == \"not\")\n return readNotCondition(prop_root, node);\n else if (name == \"and\")\n return readAndConditions(prop_root, node);\n else if (name == \"or\")\n return readOrConditions(prop_root, node);\n else if (name == \"less-than\")\n return readComparison(prop_root, node, SGComparisonCondition::LESS_THAN,\n false);\n else if (name == \"less-than-equals\")\n return readComparison(prop_root, node, SGComparisonCondition::GREATER_THAN,\n true);\n else if (name == \"greater-than\")\n return readComparison(prop_root, node, SGComparisonCondition::GREATER_THAN,\n false);\n else if (name == \"greater-than-equals\")\n return readComparison(prop_root, node, SGComparisonCondition::LESS_THAN,\n true);\n else if (name == \"equals\")\n return readComparison(prop_root, node, SGComparisonCondition::EQUALS,\n false);\n else if (name == \"not-equals\")\n return readComparison(prop_root, node, SGComparisonCondition::EQUALS, true);\n else\n return 0;\n}\n\n\n\f\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Implementation of SGConditional.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSGConditional::SGConditional ()\n : _condition (0)\n{\n}\n\nSGConditional::~SGConditional ()\n{\n}\n\nvoid\nSGConditional::setCondition (SGCondition * condition)\n{\n _condition = condition;\n}\n\nbool\nSGConditional::test () const\n{\n return ((_condition == 0) || _condition->test());\n}\n\n\n\f\n\/\/ The top-level is always an implicit 'and' group\nSGCondition *\nsgReadCondition( SGPropertyNode *prop_root, const SGPropertyNode *node )\n{\n return readAndConditions(prop_root, node);\n}\n\n\n\/\/ end of condition.cxx\nFix a warning from GCC - 'ALIAS' was unhandled in the switch stmt.\/\/ condition.cxx - Declarations and inline methods for property conditions.\n\/\/\n\/\/ Written by David Megginson, started 2000.\n\/\/ CLO May 2003 - Split out condition specific code.\n\/\/\n\/\/ This file is in the Public Domain, and comes with no warranty.\n\/\/\n\/\/ $Id$\n\n#ifdef HAVE_CONFIG_H\n# include \n#endif\n\n\/\/ #include \n\n#include \n\n#include \"props.hxx\"\n#include \"condition.hxx\"\n\nusing std::istream;\nusing std::ostream;\n\n\n\n\f\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Implementation of SGCondition.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSGCondition::SGCondition ()\n{\n}\n\nSGCondition::~SGCondition ()\n{\n}\n\n\n\f\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Implementation of SGPropertyCondition.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSGPropertyCondition::SGPropertyCondition ( SGPropertyNode *prop_root,\n const char *propname )\n : _node( prop_root->getNode(propname, true) )\n{\n}\n\nSGPropertyCondition::~SGPropertyCondition ()\n{\n}\n\n\n\f\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Implementation of SGNotCondition.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSGNotCondition::SGNotCondition (SGCondition * condition)\n : _condition(condition)\n{\n}\n\nSGNotCondition::~SGNotCondition ()\n{\n}\n\nbool\nSGNotCondition::test () const\n{\n return !(_condition->test());\n}\n\n\n\f\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Implementation of SGAndCondition.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSGAndCondition::SGAndCondition ()\n{\n}\n\nSGAndCondition::~SGAndCondition ()\n{\n}\n\nbool\nSGAndCondition::test () const\n{\n int nConditions = _conditions.size();\n for (int i = 0; i < nConditions; i++) {\n if (!_conditions[i]->test())\n return false;\n }\n return true;\n}\n\nvoid\nSGAndCondition::addCondition (SGCondition * condition)\n{\n _conditions.push_back(condition);\n}\n\n\n\f\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Implementation of SGOrCondition.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSGOrCondition::SGOrCondition ()\n{\n}\n\nSGOrCondition::~SGOrCondition ()\n{\n}\n\nbool\nSGOrCondition::test () const\n{\n int nConditions = _conditions.size();\n for (int i = 0; i < nConditions; i++) {\n if (_conditions[i]->test())\n return true;\n }\n return false;\n}\n\nvoid\nSGOrCondition::addCondition (SGCondition * condition)\n{\n _conditions.push_back(condition);\n}\n\n\n\f\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Implementation of SGComparisonCondition.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic int\ndoComparison (const SGPropertyNode * left, const SGPropertyNode *right)\n{\n switch (left->getType()) {\n case SGPropertyNode::BOOL: {\n bool v1 = left->getBoolValue();\n bool v2 = right->getBoolValue();\n if (v1 < v2)\n return SGComparisonCondition::LESS_THAN;\n else if (v1 > v2)\n return SGComparisonCondition::GREATER_THAN;\n else\n return SGComparisonCondition::EQUALS;\n break;\n }\n case SGPropertyNode::INT: {\n int v1 = left->getIntValue();\n int v2 = right->getIntValue();\n if (v1 < v2)\n return SGComparisonCondition::LESS_THAN;\n else if (v1 > v2)\n return SGComparisonCondition::GREATER_THAN;\n else\n return SGComparisonCondition::EQUALS;\n break;\n }\n case SGPropertyNode::LONG: {\n long v1 = left->getLongValue();\n long v2 = right->getLongValue();\n if (v1 < v2)\n return SGComparisonCondition::LESS_THAN;\n else if (v1 > v2)\n return SGComparisonCondition::GREATER_THAN;\n else\n return SGComparisonCondition::EQUALS;\n break;\n }\n case SGPropertyNode::FLOAT: {\n float v1 = left->getFloatValue();\n float v2 = right->getFloatValue();\n if (v1 < v2)\n return SGComparisonCondition::LESS_THAN;\n else if (v1 > v2)\n return SGComparisonCondition::GREATER_THAN;\n else\n return SGComparisonCondition::EQUALS;\n break;\n }\n case SGPropertyNode::DOUBLE: {\n double v1 = left->getDoubleValue();\n double v2 = right->getDoubleValue();\n if (v1 < v2)\n return SGComparisonCondition::LESS_THAN;\n else if (v1 > v2)\n return SGComparisonCondition::GREATER_THAN;\n else\n return SGComparisonCondition::EQUALS;\n break;\n }\n case SGPropertyNode::STRING: \n case SGPropertyNode::NONE:\n case SGPropertyNode::UNSPECIFIED: {\n string v1 = left->getStringValue();\n string v2 = right->getStringValue();\n if (v1 < v2)\n return SGComparisonCondition::LESS_THAN;\n else if (v1 > v2)\n return SGComparisonCondition::GREATER_THAN;\n else\n return SGComparisonCondition::EQUALS;\n break;\n }\n default:\n throw sg_exception(\"condition: unrecognized node type in comparison\");\n }\n \n return 0;\n}\n\n\nSGComparisonCondition::SGComparisonCondition (Type type, bool reverse)\n : _type(type),\n _reverse(reverse),\n _left_property(0),\n _right_property(0),\n _right_value(0)\n{\n}\n\nSGComparisonCondition::~SGComparisonCondition ()\n{\n}\n\nbool\nSGComparisonCondition::test () const\n{\n\t\t\t\t\/\/ Always fail if incompletely specified\n if (_left_property == 0 ||\n (_right_property == 0 && _right_value == 0))\n return false;\n\n\t\t\t\t\/\/ Get LESS_THAN, EQUALS, or GREATER_THAN\n int cmp =\n doComparison(_left_property,\n\t\t (_right_property != 0 ? _right_property : _right_value));\n if (!_reverse)\n return (cmp == _type);\n else\n return (cmp != _type);\n}\n\nvoid\nSGComparisonCondition::setLeftProperty( SGPropertyNode *prop_root,\n const char * propname )\n{\n _left_property = prop_root->getNode(propname, true);\n}\n\nvoid\nSGComparisonCondition::setRightProperty( SGPropertyNode *prop_root,\n const char * propname )\n{\n _right_value = 0;\n _right_property = prop_root->getNode(propname, true);\n}\n\nvoid\nSGComparisonCondition::setRightValue (const SGPropertyNode *node)\n{\n _right_property = 0;\n _right_value = new SGPropertyNode(*node);\n}\n\n\n\f\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Read a condition and use it if necessary.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ Forward declaration\nstatic SGCondition * readCondition( SGPropertyNode *prop_root,\n const SGPropertyNode *node );\n\nstatic SGCondition *\nreadPropertyCondition( SGPropertyNode *prop_root,\n const SGPropertyNode *node )\n{\n return new SGPropertyCondition( prop_root, node->getStringValue() );\n}\n\nstatic SGCondition *\nreadNotCondition( SGPropertyNode *prop_root, const SGPropertyNode *node )\n{\n int nChildren = node->nChildren();\n for (int i = 0; i < nChildren; i++) {\n const SGPropertyNode * child = node->getChild(i);\n SGCondition * condition = readCondition(prop_root, child);\n if (condition != 0)\n return new SGNotCondition(condition);\n }\n SG_LOG(SG_COCKPIT, SG_ALERT, \"empty 'not' condition\");\n return 0;\n}\n\nstatic SGCondition *\nreadAndConditions( SGPropertyNode *prop_root, const SGPropertyNode *node )\n{\n SGAndCondition * andCondition = new SGAndCondition;\n int nChildren = node->nChildren();\n for (int i = 0; i < nChildren; i++) {\n const SGPropertyNode * child = node->getChild(i);\n SGCondition * condition = readCondition(prop_root, child);\n if (condition != 0)\n andCondition->addCondition(condition);\n }\n return andCondition;\n}\n\nstatic SGCondition *\nreadOrConditions( SGPropertyNode *prop_root, const SGPropertyNode *node )\n{\n SGOrCondition * orCondition = new SGOrCondition;\n int nChildren = node->nChildren();\n for (int i = 0; i < nChildren; i++) {\n const SGPropertyNode * child = node->getChild(i);\n SGCondition * condition = readCondition(prop_root, child);\n if (condition != 0)\n orCondition->addCondition(condition);\n }\n return orCondition;\n}\n\nstatic SGCondition *\nreadComparison( SGPropertyNode *prop_root,\n const SGPropertyNode *node,\n SGComparisonCondition::Type type,\n\t\tbool reverse)\n{\n SGComparisonCondition * condition = new SGComparisonCondition(type, reverse);\n condition->setLeftProperty(prop_root, node->getStringValue(\"property[0]\"));\n if (node->hasValue(\"property[1]\"))\n condition->setRightProperty(prop_root, node->getStringValue(\"property[1]\"));\n else if (node->hasValue(\"value\"))\n condition->setRightValue(node->getChild(\"value\", 0));\n else\n throw sg_exception(\"condition: comparison without property[1] or value\");\n\n return condition;\n}\n\nstatic SGCondition *\nreadCondition( SGPropertyNode *prop_root, const SGPropertyNode *node )\n{\n const string &name = node->getName();\n if (name == \"property\")\n return readPropertyCondition(prop_root, node);\n else if (name == \"not\")\n return readNotCondition(prop_root, node);\n else if (name == \"and\")\n return readAndConditions(prop_root, node);\n else if (name == \"or\")\n return readOrConditions(prop_root, node);\n else if (name == \"less-than\")\n return readComparison(prop_root, node, SGComparisonCondition::LESS_THAN,\n false);\n else if (name == \"less-than-equals\")\n return readComparison(prop_root, node, SGComparisonCondition::GREATER_THAN,\n true);\n else if (name == \"greater-than\")\n return readComparison(prop_root, node, SGComparisonCondition::GREATER_THAN,\n false);\n else if (name == \"greater-than-equals\")\n return readComparison(prop_root, node, SGComparisonCondition::LESS_THAN,\n true);\n else if (name == \"equals\")\n return readComparison(prop_root, node, SGComparisonCondition::EQUALS,\n false);\n else if (name == \"not-equals\")\n return readComparison(prop_root, node, SGComparisonCondition::EQUALS, true);\n else\n return 0;\n}\n\n\n\f\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Implementation of SGConditional.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nSGConditional::SGConditional ()\n : _condition (0)\n{\n}\n\nSGConditional::~SGConditional ()\n{\n}\n\nvoid\nSGConditional::setCondition (SGCondition * condition)\n{\n _condition = condition;\n}\n\nbool\nSGConditional::test () const\n{\n return ((_condition == 0) || _condition->test());\n}\n\n\n\f\n\/\/ The top-level is always an implicit 'and' group\nSGCondition *\nsgReadCondition( SGPropertyNode *prop_root, const SGPropertyNode *node )\n{\n return readAndConditions(prop_root, node);\n}\n\n\n\/\/ end of condition.cxx\n<|endoftext|>"} {"text":"\/****************************************************************************\r\n**\r\n** Copyright (C) 2016 The Qt Company Ltd.\r\n** Contact: https:\/\/www.qt.io\/licensing\/\r\n**\r\n** This file is part of the examples of the Qt Toolkit.\r\n**\r\n** $QT_BEGIN_LICENSE:BSD$\r\n** Commercial License Usage\r\n** Licensees holding valid commercial Qt licenses may use this file in\r\n** accordance with the commercial license agreement provided with the\r\n** Software or, alternatively, in accordance with the terms contained in\r\n** a written agreement between you and The Qt Company. For licensing terms\r\n** and conditions see https:\/\/www.qt.io\/terms-conditions. For further\r\n** information use the contact form at https:\/\/www.qt.io\/contact-us.\r\n**\r\n** BSD License Usage\r\n** Alternatively, you may use this file under the terms of the BSD license\r\n** as follows:\r\n**\r\n** \"Redistribution and use in source and binary forms, with or without\r\n** modification, are permitted provided that the following conditions are\r\n** met:\r\n** * Redistributions of source code must retain the above copyright\r\n** notice, this list of conditions and the following disclaimer.\r\n** * Redistributions in binary form must reproduce the above copyright\r\n** notice, this list of conditions and the following disclaimer in\r\n** the documentation and\/or other materials provided with the\r\n** distribution.\r\n** * Neither the name of The Qt Company Ltd nor the names of its\r\n** contributors may be used to endorse or promote products derived\r\n** from this software without specific prior written permission.\r\n**\r\n**\r\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r\n** \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r\n** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r\n** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\r\n** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r\n** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\r\n** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\r\n** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r\n** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\"\r\n**\r\n** $QT_END_LICENSE$\r\n**\r\n****************************************************************************\/\r\n\r\n\/*\r\n treeitem.cpp\r\n\r\n A container for items of data supplied by the simple tree model.\r\n*\/\r\n\r\n#include \"treeitem.h\"\r\n\r\n#include \r\n#include \r\n\r\n\r\n\r\n\/\/! [0]\r\nTreeItem::TreeItem(const QVector &data, TreeItem *parent, QObject *qparent, bool header_item)\r\n\t: QObject(qparent)\r\n\t, is_header_item(header_item)\r\n\t, forbidden_tag_name_characters(R\"(^:\\-\\+\\.\\,!@#$%&*;~`\"'<>\\^\\(\\)\\\\\/\\|\\?\\[\\]\\{\\})\")\r\n\t, tag_name_validator(QRegularExpression(\"[^0-9\" + forbidden_tag_name_characters + \"][\" + forbidden_tag_name_characters + \"]*\"))\r\n{\r\n\tparentItem = parent;\r\n itemData = data;\r\n}\r\n\/\/! [0]\r\n\r\n\/\/! [1]\r\nTreeItem::~TreeItem()\r\n{\r\n qDeleteAll(childItems);\r\n}\r\n\/\/! [1]\r\n\r\n\/\/! [2]\r\nTreeItem *TreeItem::child(int number)\r\n{\r\n return childItems.value(number);\r\n}\r\n\/\/! [2]\r\n\r\n\/\/! [3]\r\nint TreeItem::childCount() const\r\n{\r\n return childItems.count();\r\n}\r\n\/\/! [3]\r\n\r\n\/\/! [4]\r\nint TreeItem::childNumber() const\r\n{\r\n if (parentItem)\r\n return parentItem->childItems.indexOf(const_cast(this));\r\n\r\n return 0;\r\n}\r\n\/\/! [4]\r\n\r\n\/\/! [5]\r\nint TreeItem::columnCount() const\r\n{\r\n return itemData.count();\r\n}\r\n\/\/! [5]\r\n\r\n\/\/! [6]\r\nQVariant TreeItem::data(int column) const\r\n{\r\n return itemData.value(column);\r\n}\r\n\/\/! [6]\r\n\r\n\/\/! [7]\r\nbool TreeItem::insertChildren(int position, int count, int columns)\r\n{\r\n if (position < 0 || position > childItems.size())\r\n return false;\r\n\tif (childItems.size() == 0 && !is_header_item)\r\n\t\tthis->setData(1, QVariant(\"\"));\r\n\r\n for (int row = 0; row < count; ++row) {\r\n QVector data(columns);\r\n TreeItem *item = new TreeItem(data, this);\r\n childItems.insert(position, item);\r\n }\r\n\r\n return true;\r\n}\r\n\/\/! [7]\r\n\r\n\/\/! [8]\r\nbool TreeItem::insertColumns(int position, int columns)\r\n{\r\n if (position < 0 || position > itemData.size())\r\n return false;\r\n\r\n for (int column = 0; column < columns; ++column)\r\n itemData.insert(position, QVariant());\r\n\r\n foreach (TreeItem *child, childItems)\r\n child->insertColumns(position, columns);\r\n\r\n return true;\r\n}\r\n\/\/! [8]\r\n\r\n\/\/! [9]\r\nTreeItem *TreeItem::parent()\r\n{\r\n return parentItem;\r\n}\r\n\/\/! [9]\r\n\r\n\/\/! [10]\r\nbool TreeItem::removeChildren(int position, int count)\r\n{\r\n if (position < 0 || position + count > childItems.size())\r\n return false;\r\n\r\n for (int row = 0; row < count; ++row)\r\n delete childItems.takeAt(position);\r\n\r\n return true;\r\n}\r\n\/\/! [10]\r\n\r\nbool TreeItem::removeColumns(int position, int columns)\r\n{\r\n if (position < 0 || position + columns > itemData.size())\r\n return false;\r\n\r\n for (int column = 0; column < columns; ++column)\r\n itemData.remove(position);\r\n\r\n foreach (TreeItem *child, childItems)\r\n child->removeColumns(position, columns);\r\n\r\n return true;\r\n}\r\n\r\n\/\/! [11]\r\nbool TreeItem::setData(int column, const QVariant &value)\r\n{\r\n if (column < 0 || column >= itemData.size())\r\n return false;\r\n\r\n\tbool success = true;\r\n\tif (childCount() == 0 || column != 1)\r\n\t{\r\n\t\tif (column == 0)\r\n\t\t{\r\n\t\t\tint pos = 0;\r\n\t\t\tQValidator::State state = tag_name_validator.validate(value.toString(), pos);\r\n\t\t\tif (state == QValidator::Acceptable)\r\n\t\t\t\titemData[column] = value;\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tQMessageBox::information(nullptr, \"XKMLGen\", tr(\"Incorrect tag name.\"));\r\n\t\t\t\tsuccess = false;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\titemData[column] = value;\r\n\t\t}\r\n\t}\r\n\telse \r\n\t{\r\n\t\temit changeOfNodeValueAttempted(itemData[0]);\r\n\t\tsuccess = false;\r\n\t}\r\n\treturn success;\r\n}\r\n\/\/! [11]\r\nAdded whitespace to the list of forbidden tag name characters.\/****************************************************************************\r\n**\r\n** Copyright (C) 2016 The Qt Company Ltd.\r\n** Contact: https:\/\/www.qt.io\/licensing\/\r\n**\r\n** This file is part of the examples of the Qt Toolkit.\r\n**\r\n** $QT_BEGIN_LICENSE:BSD$\r\n** Commercial License Usage\r\n** Licensees holding valid commercial Qt licenses may use this file in\r\n** accordance with the commercial license agreement provided with the\r\n** Software or, alternatively, in accordance with the terms contained in\r\n** a written agreement between you and The Qt Company. For licensing terms\r\n** and conditions see https:\/\/www.qt.io\/terms-conditions. For further\r\n** information use the contact form at https:\/\/www.qt.io\/contact-us.\r\n**\r\n** BSD License Usage\r\n** Alternatively, you may use this file under the terms of the BSD license\r\n** as follows:\r\n**\r\n** \"Redistribution and use in source and binary forms, with or without\r\n** modification, are permitted provided that the following conditions are\r\n** met:\r\n** * Redistributions of source code must retain the above copyright\r\n** notice, this list of conditions and the following disclaimer.\r\n** * Redistributions in binary form must reproduce the above copyright\r\n** notice, this list of conditions and the following disclaimer in\r\n** the documentation and\/or other materials provided with the\r\n** distribution.\r\n** * Neither the name of The Qt Company Ltd nor the names of its\r\n** contributors may be used to endorse or promote products derived\r\n** from this software without specific prior written permission.\r\n**\r\n**\r\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\r\n** \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\r\n** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\r\n** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\r\n** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\r\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\r\n** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\r\n** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\r\n** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\r\n** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\"\r\n**\r\n** $QT_END_LICENSE$\r\n**\r\n****************************************************************************\/\r\n\r\n\/*\r\n treeitem.cpp\r\n\r\n A container for items of data supplied by the simple tree model.\r\n*\/\r\n\r\n#include \"treeitem.h\"\r\n\r\n#include \r\n#include \r\n\r\n\r\n\r\n\/\/! [0]\r\nTreeItem::TreeItem(const QVector &data, TreeItem *parent, QObject *qparent, bool header_item)\r\n\t: QObject(qparent)\r\n\t, is_header_item(header_item)\r\n\t, forbidden_tag_name_characters(R\"(^:\\-\\+\\.\\,!@#$%&*;~`\"'<>\\^\\(\\)\\\\\/\\|\\?\\[\\]\\{\\} )\")\r\n\t, tag_name_validator(QRegularExpression(\"[^0-9\" + forbidden_tag_name_characters + \"][\" + forbidden_tag_name_characters + \"]*\"))\r\n{\r\n\tparentItem = parent;\r\n itemData = data;\r\n}\r\n\/\/! [0]\r\n\r\n\/\/! [1]\r\nTreeItem::~TreeItem()\r\n{\r\n qDeleteAll(childItems);\r\n}\r\n\/\/! [1]\r\n\r\n\/\/! [2]\r\nTreeItem *TreeItem::child(int number)\r\n{\r\n return childItems.value(number);\r\n}\r\n\/\/! [2]\r\n\r\n\/\/! [3]\r\nint TreeItem::childCount() const\r\n{\r\n return childItems.count();\r\n}\r\n\/\/! [3]\r\n\r\n\/\/! [4]\r\nint TreeItem::childNumber() const\r\n{\r\n if (parentItem)\r\n return parentItem->childItems.indexOf(const_cast(this));\r\n\r\n return 0;\r\n}\r\n\/\/! [4]\r\n\r\n\/\/! [5]\r\nint TreeItem::columnCount() const\r\n{\r\n return itemData.count();\r\n}\r\n\/\/! [5]\r\n\r\n\/\/! [6]\r\nQVariant TreeItem::data(int column) const\r\n{\r\n return itemData.value(column);\r\n}\r\n\/\/! [6]\r\n\r\n\/\/! [7]\r\nbool TreeItem::insertChildren(int position, int count, int columns)\r\n{\r\n if (position < 0 || position > childItems.size())\r\n return false;\r\n\tif (childItems.size() == 0 && !is_header_item)\r\n\t\tthis->setData(1, QVariant(\"\"));\r\n\r\n for (int row = 0; row < count; ++row) {\r\n QVector data(columns);\r\n TreeItem *item = new TreeItem(data, this);\r\n childItems.insert(position, item);\r\n }\r\n\r\n return true;\r\n}\r\n\/\/! [7]\r\n\r\n\/\/! [8]\r\nbool TreeItem::insertColumns(int position, int columns)\r\n{\r\n if (position < 0 || position > itemData.size())\r\n return false;\r\n\r\n for (int column = 0; column < columns; ++column)\r\n itemData.insert(position, QVariant());\r\n\r\n foreach (TreeItem *child, childItems)\r\n child->insertColumns(position, columns);\r\n\r\n return true;\r\n}\r\n\/\/! [8]\r\n\r\n\/\/! [9]\r\nTreeItem *TreeItem::parent()\r\n{\r\n return parentItem;\r\n}\r\n\/\/! [9]\r\n\r\n\/\/! [10]\r\nbool TreeItem::removeChildren(int position, int count)\r\n{\r\n if (position < 0 || position + count > childItems.size())\r\n return false;\r\n\r\n for (int row = 0; row < count; ++row)\r\n delete childItems.takeAt(position);\r\n\r\n return true;\r\n}\r\n\/\/! [10]\r\n\r\nbool TreeItem::removeColumns(int position, int columns)\r\n{\r\n if (position < 0 || position + columns > itemData.size())\r\n return false;\r\n\r\n for (int column = 0; column < columns; ++column)\r\n itemData.remove(position);\r\n\r\n foreach (TreeItem *child, childItems)\r\n child->removeColumns(position, columns);\r\n\r\n return true;\r\n}\r\n\r\n\/\/! [11]\r\nbool TreeItem::setData(int column, const QVariant &value)\r\n{\r\n if (column < 0 || column >= itemData.size())\r\n return false;\r\n\r\n\tbool success = true;\r\n\tif (childCount() == 0 || column != 1)\r\n\t{\r\n\t\tif (column == 0)\r\n\t\t{\r\n\t\t\tint pos = 0;\r\n\t\t\tQValidator::State state = tag_name_validator.validate(value.toString(), pos);\r\n\t\t\tif (state == QValidator::Acceptable)\r\n\t\t\t\titemData[column] = value;\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tQMessageBox::information(nullptr, \"XKMLGen\", tr(\"Incorrect tag name.\"));\r\n\t\t\t\tsuccess = false;\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\titemData[column] = value;\r\n\t\t}\r\n\t}\r\n\telse \r\n\t{\r\n\t\temit changeOfNodeValueAttempted(itemData[0]);\r\n\t\tsuccess = false;\r\n\t}\r\n\treturn success;\r\n}\r\n\/\/! [11]\r\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (c) 2017. See AUTHORS file.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\n#include \n#include \n\n#include \"iostream\"\n\n#include \"operation.h\"\n#include \"image.h\"\n#include \"types.h\"\n#include \"utils.h\"\n\nnamespace pixl {\n\n \/\/ ----------------------------------------------------------------------------\n void flip_vertically(Image* img, i32 startColumn, i32 endColumn) {\n const auto lineSizeInBytes = img->width * img->channels;\n for (i32 column = startColumn; column < endColumn; column++) {\n u8* start = img->data + (column * img->channels);\n u8* end = start + (img->height * lineSizeInBytes);\n\n while (start <= end) {\n aswap(start, end, img->channels);\n start += lineSizeInBytes;\n end -= lineSizeInBytes;\n }\n }\n }\n\n \/\/ ----------------------------------------------------------------------------\n void flip_horizontally(Image* img, i32 startLine, i32 endLine) {\n const auto lineSizeInBytes = img->width * img->channels;\n for (i32 line = startLine; line < endLine; line++) {\n u8* start = img->data + (line * lineSizeInBytes);\n u8* end = start + lineSizeInBytes - img->channels;\n\n while (start <= end) {\n aswap(start, end, img->channels);\n start += img->channels;\n end -= img->channels;\n }\n }\n }\n\n \/\/ ----------------------------------------------------------------------------\n void FlipTransformation::apply(Image* image) {\n \/\/ Run operation on main thread if numThreads <= 1\n if(numThreads <= 1) {\n if (this->orientation == Orientation::HORIZONTAL) {\n flip_horizontally(image, 0, image->height);\n } else if (this->orientation == Orientation::VERTICAL) {\n flip_vertically(image, 0, image->width); \n }\n return;\n }\n\n \/\/ create n threads\n std::vector threads;\n threads.reserve(this->numThreads);\n\n \/\/ start threads\n if (this->orientation == Orientation::HORIZONTAL) {\n auto chunk = image->height \/ numThreads;\n for (i32 i = 0; i < numThreads; i++) {\n threads.emplace_back(flip_horizontally, image, chunk * i, chunk * i + chunk);\n }\n } else if (this->orientation == Orientation::VERTICAL) {\n auto chunk = image->width \/ numThreads;\n for (i32 i = 0; i < numThreads; i++) {\n threads.emplace_back(flip_vertically, image, chunk * i, chunk * i + chunk);\n }\n }\n\n \/\/ wait until everybody is finished\n for (auto& t : threads) {\n t.join();\n }\n }\n}Fixed vertical flip\/\/\n\/\/ Copyright (c) 2017. See AUTHORS file.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\n#include \n#include \n\n#include \"iostream\"\n\n#include \"operation.h\"\n#include \"image.h\"\n#include \"types.h\"\n#include \"utils.h\"\n\nnamespace pixl {\n\n \/\/ ----------------------------------------------------------------------------\n void flip_vertically(Image* img, i32 startColumn, i32 endColumn) {\n const auto lineSizeInBytes = img->width * img->channels;\n const auto lastLine = (img->height-1) * lineSizeInBytes;\n for (i32 column = startColumn; column < endColumn; column++) {\n u8* start = img->data + (column * img->channels);\n u8* end = start + lastLine;\n\n while (start <= end) {\n aswap(start, end, img->channels); \n start += lineSizeInBytes;\n end -= lineSizeInBytes;\n }\n }\n }\n\n \/\/ ----------------------------------------------------------------------------\n void flip_horizontally(Image* img, i32 startLine, i32 endLine) {\n const auto lineSizeInBytes = img->width * img->channels;\n for (i32 line = startLine; line < endLine; line++) {\n u8* start = img->data + (line * lineSizeInBytes);\n u8* end = start + lineSizeInBytes - img->channels;\n\n while (start <= end) {\n aswap(start, end, img->channels);\n start += img->channels;\n end -= img->channels;\n }\n }\n }\n\n \/\/ ----------------------------------------------------------------------------\n void FlipTransformation::apply(Image* image) {\n \/\/ Run operation on main thread if numThreads <= 1\n if(numThreads <= 1) {\n if (this->orientation == Orientation::HORIZONTAL) {\n flip_horizontally(image, 0, image->height);\n } else if (this->orientation == Orientation::VERTICAL) {\n flip_vertically(image, 0, image->width); \n }\n return;\n }\n\n \/\/ create n threads\n std::vector threads;\n threads.reserve(this->numThreads);\n\n \/\/ start threads\n if (this->orientation == Orientation::HORIZONTAL) {\n auto chunk = image->height \/ numThreads;\n for (i32 i = 0; i < numThreads; i++) {\n threads.emplace_back(flip_horizontally, image, chunk * i, chunk * i + chunk);\n }\n } else if (this->orientation == Orientation::VERTICAL) {\n auto chunk = image->width \/ numThreads;\n for (i32 i = 0; i < numThreads; i++) {\n threads.emplace_back(flip_vertically, image, chunk * i, chunk * i + chunk);\n }\n }\n\n \/\/ wait until everybody is finished\n for (auto& t : threads) {\n t.join();\n }\n }\n}<|endoftext|>"} {"text":"\/***************************************************************************\n * Copyright (C) 1998-2010 by authors (see AUTHORS.txt ) *\n * *\n * This file is part of LuxRays. *\n * *\n * LuxRays is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 3 of the License, or *\n * (at your option) any later version. *\n * *\n * LuxRays is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU General Public License *\n * along with this program. If not, see . *\n * *\n * LuxRays website: http:\/\/www.luxrender.net *\n ***************************************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"luxrays\/core\/pixel\/samplebuffer.h\"\n\n#include \"smalllux.h\"\n#include \"sppm.h\"\n#include \"renderconfig.h\"\n#include \"displayfunc.h\"\n#include \"hitpoints.h\"\n\n\/\/------------------------------------------------------------------------------\n\/\/ SPPMRenderThread\n\/\/------------------------------------------------------------------------------\n\nSPPMRenderThread::SPPMRenderThread(unsigned int index, SPPMRenderEngine *re) {\n\tthreadIndex = index;\n\trenderEngine = re;\n\tstarted = false;\n}\n\nSPPMRenderThread::~SPPMRenderThread() {\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ SPPMDeviceRenderThread\n\/\/------------------------------------------------------------------------------\n\nSPPMDeviceRenderThread::SPPMDeviceRenderThread(const unsigned int index, const unsigned long seedBase,\n\t\tIntersectionDevice *device,\tSPPMRenderEngine *re) : SPPMRenderThread(index, re) {\n\tintersectionDevice = device;\n\treportedPermissionError = false;\n\n\trenderThread = NULL;\n\n\trayBuffer = intersectionDevice->NewRayBuffer();\n\tif (threadIndex == 0)\n\t\trayBufferHitPoints = intersectionDevice->NewRayBuffer();\n\telse\n\t\trayBufferHitPoints = NULL;\n}\n\nSPPMDeviceRenderThread::~SPPMDeviceRenderThread() {\n\tif (started)\n\t\tStop();\n\n\tdelete rayBuffer;\n\tdelete rayBufferHitPoints;\n}\n\nvoid SPPMDeviceRenderThread::Start() {\n\tSPPMRenderThread::Start();\n\n\trayBuffer->Reset();\n\tif (threadIndex == 0)\n\t\trayBufferHitPoints->Reset();\n\n\t\/\/ Create the thread for the rendering\n\trenderThread = new boost::thread(boost::bind(SPPMDeviceRenderThread::RenderThreadImpl, this));\n\n\t\/\/ Set renderThread priority\n\tbool res = SetThreadRRPriority(renderThread);\n\tif (res && !reportedPermissionError) {\n\t\tcerr << \"[SPPMDeviceRenderThread::\" << threadIndex << \"] Failed to set ray intersection thread priority (you probably need root\/administrator permission to set thread realtime priority)\" << endl;\n\t\treportedPermissionError = true;\n\t}\n}\n\nvoid SPPMDeviceRenderThread::Interrupt() {\n\tif (renderThread)\n\t\trenderThread->interrupt();\n}\n\nvoid SPPMDeviceRenderThread::Stop() {\n\tif (renderThread) {\n\t\trenderThread->interrupt();\n\t\trenderThread->join();\n\t\tdelete renderThread;\n\t\trenderThread = NULL;\n\t}\n\n\tSPPMRenderThread::Stop();\n}\n\nvoid SPPMDeviceRenderThread::UpdateFilm(Film *film, HitPoints *hitPoints, SampleBuffer *sampleBuffer) {\n\tfilm->Reset();\n\n\tconst unsigned int imgWidth = film->GetWidth();\n\tfor (unsigned int i = 0; i < hitPoints->GetSize(); ++i) {\n\t\tHitPoint *hp = hitPoints->GetHitPoint(i);\n\t\tconst float scrX = i % imgWidth;\n\t\tconst float scrY = i \/ imgWidth;\n\t\tsampleBuffer->SplatSample(scrX, scrY, hp->radiance);\n\n\t\tif (sampleBuffer->IsFull()) {\n\t\t\t\/\/ Splat all samples on the film\n\t\t\tfilm->SplatSampleBuffer(true, sampleBuffer);\n\t\t\tsampleBuffer = film->GetFreeSampleBuffer();\n\t\t}\n\t}\n\n\tif (sampleBuffer->GetSampleCount() > 0) {\n\t\t\/\/ Splat all samples on the film\n\t\tfilm->SplatSampleBuffer(true, sampleBuffer);\n\t\tsampleBuffer = film->GetFreeSampleBuffer();\n\t}\n}\n\nvoid SPPMDeviceRenderThread::InitPhotonPath(Scene *scene, RandomGenerator *rndGen,\n\tPhotonPath *photonPath, Ray *ray, unsigned int *photonTracedPass) {\n\t\/\/ Select one light source\n\tfloat lpdf;\n\tconst LightSource *light = scene->SampleAllLights(rndGen->floatValue(), &lpdf);\n\n\t\/\/ Initialize the photon path\n\tfloat pdf;\n\tphotonPath->flux = light->Sample_L(scene,\n\t\trndGen->floatValue(), rndGen->floatValue(),\n\t\trndGen->floatValue(), rndGen->floatValue(),\n\t\t&pdf, ray);\n\tphotonPath->flux \/= pdf * lpdf;\n\tphotonPath->depth = 0;\n\n\tAtomicInc(photonTracedPass);\n}\n\nvoid SPPMDeviceRenderThread::RenderThreadImpl(SPPMDeviceRenderThread *renderThread) {\n\tcerr << \"[SPPMDeviceRenderThread::\" << renderThread->threadIndex << \"] Rendering thread started\" << endl;\n\n\tSPPMRenderEngine *renderEngine = renderThread->renderEngine;\n\tScene *scene = renderEngine->scene;\n\tRandomGenerator *rndGen = new RandomGenerator();\n\trndGen->init(renderThread->threadIndex + renderEngine->seedBase + 1);\n\n\tIntersectionDevice *device = renderThread->intersectionDevice;\n\tRayBuffer *rayBuffer = renderThread->rayBuffer;\n\tRayBuffer *rayBufferHitPoints = renderThread->rayBufferHitPoints;\n\n\tif (renderThread->threadIndex == 0) {\n\t\t\/\/ Build the EyePaths list\n\t\trenderEngine->hitPoints = new HitPoints(\n\t\t\t\tscene, rndGen, device,\n\t\t\t\trayBufferHitPoints, renderEngine->photonAlpha,\n\t\t\t\trenderEngine->maxEyePathDepth,\n\t\t\t\trenderEngine->film->GetWidth(), renderEngine->film->GetHeight(),\n\t\t\t\trenderEngine->accelType);\n\t}\n\n\tHitPoints *hitPoints = NULL;\n\ttry {\n\t\t\/\/ Wait for other threads\n\t\trenderEngine->barrierStart->wait();\n\n\t\thitPoints = renderEngine->hitPoints;\n\n\t\t\/\/std::cerr << \"[SPPMDeviceRenderThread::\" << renderThread->threadIndex << \"] Tracing photon paths\" << std::endl;\n\n\t\t\/\/ Generate photons from light sources\n\t\tstd::vector photonPaths(rayBuffer->GetSize());\n\t\tRay *rays = rayBuffer->GetRayBuffer();\n\t\tfor (unsigned int i = 0; i < photonPaths.size(); ++i) {\n\t\t\t\/\/ Note: there is some assumption here about how the\n\t\t\t\/\/ rayBuffer->ReserveRay() work\n\t\t\tInitPhotonPath(scene, rndGen, &photonPaths[i], &rays[rayBuffer->ReserveRay()],\n\t\t\t\t\t&renderEngine->photonTracedPass);\n\t\t}\n\n\t\twhile (!boost::this_thread::interruption_requested()) {\n\t\t\t\/\/ Trace the rays\n\t\t\tdevice->PushRayBuffer(rayBuffer);\n\t\t\trayBuffer = device->PopRayBuffer();\n\n\t\t\tfor (unsigned int i = 0; i < rayBuffer->GetRayCount(); ++i) {\n\t\t\t\tPhotonPath *photonPath = &photonPaths[i];\n\t\t\t\tRay *ray = &rayBuffer->GetRayBuffer()[i];\n\t\t\t\tconst RayHit *rayHit = &rayBuffer->GetHitBuffer()[i];\n\n\t\t\t\tif (rayHit->Miss()) {\n\t\t\t\t\t\/\/ Re-initialize the photon path\n\t\t\t\t\tInitPhotonPath(scene, rndGen, photonPath, ray,\n\t\t\t\t\t\t\t&renderEngine->photonTracedPass);\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ Something was hit\n\t\t\t\t\tPoint hitPoint;\n\t\t\t\t\tSpectrum surfaceColor;\n\t\t\t\t\tNormal N, shadeN;\n\t\t\t\t\tif (GetHitPointInformation(scene, rndGen, ray, rayHit, hitPoint,\n\t\t\t\t\t\t\tsurfaceColor, N, shadeN))\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\t\/\/ Get the material\n\t\t\t\t\tconst unsigned int currentTriangleIndex = rayHit->index;\n\t\t\t\t\tconst Material *triMat = scene->triangleMaterials[currentTriangleIndex];\n\n\t\t\t\t\tif (triMat->IsLightSource()) {\n\t\t\t\t\t\t\/\/ Re-initialize the photon path\n\t\t\t\t\t\tInitPhotonPath(scene, rndGen, photonPath, ray,\n\t\t\t\t\t\t\t\t&renderEngine->photonTracedPass);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst SurfaceMaterial *triSurfMat = (SurfaceMaterial *)triMat;\n\n\t\t\t\t\t\tfloat fPdf;\n\t\t\t\t\t\tVector wi;\n\t\t\t\t\t\tbool specularBounce;\n\t\t\t\t\t\tconst Spectrum f = triSurfMat->Sample_f(-ray->d, &wi, N, shadeN,\n\t\t\t\t\t\t\t\trndGen->floatValue(), rndGen->floatValue(), rndGen->floatValue(),\n\t\t\t\t\t\t\t\tfalse, &fPdf, specularBounce) * surfaceColor;\n\n\t\t\t\t\t\tif (!specularBounce)\n\t\t\t\t\t\t\thitPoints->AddFlux(hitPoint, shadeN, -ray->d, photonPath->flux);\n\n\t\t\t\t\t\t\/\/ Check if we reached the max. depth\n\t\t\t\t\t\tif (photonPath->depth < renderEngine->maxPhotonPathDepth) {\n\t\t\t\t\t\t\t\/\/ Build the next vertex path ray\n\t\t\t\t\t\t\tif ((fPdf <= 0.f) || f.Black()) {\n\t\t\t\t\t\t\t\t\/\/ Re-initialize the photon path\n\t\t\t\t\t\t\t\tInitPhotonPath(scene, rndGen, photonPath, ray,\n\t\t\t\t\t\t\t\t\t\t&renderEngine->photonTracedPass);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tphotonPath->depth++;\n\t\t\t\t\t\t\t\tphotonPath->flux *= f \/ fPdf;\n\n\t\t\t\t\t\t\t\t\/\/ Russian Roulette\n\t\t\t\t\t\t\t\tconst float p = 0.7f;\n\t\t\t\t\t\t\t\tif ((photonPath->depth < 2) || (specularBounce)) {\n\t\t\t\t\t\t\t\t\t*ray = Ray(hitPoint, wi);\n\t\t\t\t\t\t\t\t} else if (rndGen->floatValue() < p) {\n\t\t\t\t\t\t\t\t\tphotonPath->flux \/= p;\n\t\t\t\t\t\t\t\t\t*ray = Ray(hitPoint, wi);\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\/\/ Re-initialize the photon path\n\t\t\t\t\t\t\t\t\tInitPhotonPath(scene, rndGen, photonPath, ray,\n\t\t\t\t\t\t\t\t\t\t\t&renderEngine->photonTracedPass);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\/\/ Re-initialize the photon path\n\t\t\t\t\t\t\tInitPhotonPath(scene, rndGen, photonPath, ray,\n\t\t\t\t\t\t\t\t\t&renderEngine->photonTracedPass);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Check if it is time to do an eye pass\n\t\t\t\/\/ TODO: add a parameter to tune rehashing intervals\n\t\t\tif (renderEngine->photonTracedPass > renderEngine->stochasticInterval) {\n\t\t\t\t\/\/ Wait for other threads\n\t\t\t\trenderEngine->barrierStop->wait();\n\n\t\t\t\t\/\/ The first thread does the eye pass\n\t\t\t\tif (renderThread->threadIndex == 0) {\n\t\t\t\t\tconst long long count = renderEngine->photonTracedTotal + renderEngine->photonTracedPass;\n\t\t\t\t\thitPoints->Recast(rndGen, rayBufferHitPoints, count);\n\n\t\t\t\t\t\/\/ Update the frame buffer\n\t\t\t\t\tUpdateFilm(renderEngine->film, hitPoints, renderEngine->sampleBuffer);\n\n\t\t\t\t\trenderEngine->photonTracedTotal = count;\n\t\t\t\t\trenderEngine->photonTracedPass = 0;\n\t\t\t\t}\n\n\t\t\t\t\/\/ Wait for other threads\n\t\t\t\trenderEngine->barrierStart->wait();\n\t\t\t\t\/\/std::cerr << \"[SPPMDeviceRenderThread::\" << renderThread->threadIndex << \"] Tracing photon paths\" << std::endl;\n\t\t\t}\n\t\t}\n\n\t\tcerr << \"[SPPMDeviceRenderThread::\" << renderThread->threadIndex << \"] Rendering thread halted\" << endl;\n\t} catch (boost::thread_interrupted) {\n\t\tcerr << \"[SPPMDeviceRenderThread::\" << renderThread->threadIndex << \"] Rendering thread halted\" << endl;\n\t}\n#if !defined(LUXRAYS_DISABLE_OPENCL)\n\tcatch (cl::Error err) {\n\t\tcerr << \"[SPPMDeviceRenderThread::\" << renderThread->threadIndex << \"] Rendering thread ERROR: \" << err.what() << \"(\" << err.err() << \")\" << endl;\n\t}\n#endif\n\n\t\/\/ Wait for other threads\n\trenderEngine->barrierExit->wait();\n\n\tif (renderThread->threadIndex == 0) {\n\t\trenderEngine->hitPoints = NULL;\n\t\tdelete hitPoints;\n\t}\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ SPPMRenderEngine\n\/\/------------------------------------------------------------------------------\n\nSPPMRenderEngine::SPPMRenderEngine(SLGScene *scn, Film *flm,\n\t\tvector intersectionDev,\n\t\tconst Properties &cfg) : RenderEngine(scn, flm) {\n\tintersectionDevices = intersectionDev;\n\n\taccelType = HASH_GRID;\n\tseedBase = (unsigned long)(WallClockTime() \/ 1000.0);\n\tphotonAlpha = 0.7f;\n\tmaxEyePathDepth = 16;\n\tmaxPhotonPathDepth = 8;\n\tstochasticInterval = cfg.GetInt(\"sppm.stochastic.count\", 10000000);\n\n\tsampleBuffer = film->GetFreeSampleBuffer();\n\n\t\/\/ Create and start render threads\n\tconst size_t renderThreadCount = intersectionDevices.size();\n\tcerr << \"Starting \"<< renderThreadCount << \" SPPM render threads\" << endl;\n\tfor (size_t i = 0; i < renderThreadCount; ++i) {\n\t\tSPPMDeviceRenderThread *t = new SPPMDeviceRenderThread(i, seedBase, intersectionDevices[i], this);\n\t\trenderThreads.push_back(t);\n\t}\n}\n\nSPPMRenderEngine::~SPPMRenderEngine() {\n\tif (started) {\n\t\tInterrupt();\n\t\tStop();\n\t}\n\n\tfor (size_t i = 0; i < renderThreads.size(); ++i)\n\t\tdelete renderThreads[i];\n\n\tfilm->FreeSampleBuffer(sampleBuffer);\n}\n\nvoid SPPMRenderEngine::Start() {\n\tRenderEngine::Start();\n\n\tphotonTracedTotal = 0;\n\tphotonTracedPass = 0;\n\n\t\/\/ Create synchronization barriers\n\tbarrierStop = new boost::barrier(renderThreads.size());\n\tbarrierStart = new boost::barrier(renderThreads.size());\n\tbarrierExit = new boost::barrier(renderThreads.size());\n\n\tfor (size_t i = 0; i < renderThreads.size(); ++i)\n\t\trenderThreads[i]->Start();\n}\n\nvoid SPPMRenderEngine::Interrupt() {\n\tfor (size_t i = 0; i < renderThreads.size(); ++i)\n\t\trenderThreads[i]->Interrupt();\n}\n\nvoid SPPMRenderEngine::Stop() {\n\tRenderEngine::Stop();\n\n\tfor (size_t i = 0; i < renderThreads.size(); ++i)\n\t\trenderThreads[i]->Stop();\n\n\tdelete barrierStop;\n\tdelete barrierStart;\n\tdelete barrierExit;\n}\n\nvoid SPPMRenderEngine::Reset() {\n\tassert (!started);\n}\n\nunsigned int SPPMRenderEngine::GetPass() const {\n\treturn (hitPoints) ? hitPoints->GetPassCount() : 0;\n}\n\nunsigned int SPPMRenderEngine::GetThreadCount() const {\n\treturn renderThreads.size();\n}\nSLG: fixed an SPPM unitialized variable\/***************************************************************************\n * Copyright (C) 1998-2010 by authors (see AUTHORS.txt ) *\n * *\n * This file is part of LuxRays. *\n * *\n * LuxRays is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 3 of the License, or *\n * (at your option) any later version. *\n * *\n * LuxRays is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU General Public License *\n * along with this program. If not, see . *\n * *\n * LuxRays website: http:\/\/www.luxrender.net *\n ***************************************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"luxrays\/core\/pixel\/samplebuffer.h\"\n\n#include \"smalllux.h\"\n#include \"sppm.h\"\n#include \"renderconfig.h\"\n#include \"displayfunc.h\"\n#include \"hitpoints.h\"\n\n\/\/------------------------------------------------------------------------------\n\/\/ SPPMRenderThread\n\/\/------------------------------------------------------------------------------\n\nSPPMRenderThread::SPPMRenderThread(unsigned int index, SPPMRenderEngine *re) {\n\tthreadIndex = index;\n\trenderEngine = re;\n\tstarted = false;\n}\n\nSPPMRenderThread::~SPPMRenderThread() {\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ SPPMDeviceRenderThread\n\/\/------------------------------------------------------------------------------\n\nSPPMDeviceRenderThread::SPPMDeviceRenderThread(const unsigned int index, const unsigned long seedBase,\n\t\tIntersectionDevice *device,\tSPPMRenderEngine *re) : SPPMRenderThread(index, re) {\n\tintersectionDevice = device;\n\treportedPermissionError = false;\n\n\trenderThread = NULL;\n\n\trayBuffer = intersectionDevice->NewRayBuffer();\n\tif (threadIndex == 0)\n\t\trayBufferHitPoints = intersectionDevice->NewRayBuffer();\n\telse\n\t\trayBufferHitPoints = NULL;\n}\n\nSPPMDeviceRenderThread::~SPPMDeviceRenderThread() {\n\tif (started)\n\t\tStop();\n\n\tdelete rayBuffer;\n\tdelete rayBufferHitPoints;\n}\n\nvoid SPPMDeviceRenderThread::Start() {\n\tSPPMRenderThread::Start();\n\n\trayBuffer->Reset();\n\tif (threadIndex == 0)\n\t\trayBufferHitPoints->Reset();\n\n\t\/\/ Create the thread for the rendering\n\trenderThread = new boost::thread(boost::bind(SPPMDeviceRenderThread::RenderThreadImpl, this));\n\n\t\/\/ Set renderThread priority\n\tbool res = SetThreadRRPriority(renderThread);\n\tif (res && !reportedPermissionError) {\n\t\tcerr << \"[SPPMDeviceRenderThread::\" << threadIndex << \"] Failed to set ray intersection thread priority (you probably need root\/administrator permission to set thread realtime priority)\" << endl;\n\t\treportedPermissionError = true;\n\t}\n}\n\nvoid SPPMDeviceRenderThread::Interrupt() {\n\tif (renderThread)\n\t\trenderThread->interrupt();\n}\n\nvoid SPPMDeviceRenderThread::Stop() {\n\tif (renderThread) {\n\t\trenderThread->interrupt();\n\t\trenderThread->join();\n\t\tdelete renderThread;\n\t\trenderThread = NULL;\n\t}\n\n\tSPPMRenderThread::Stop();\n}\n\nvoid SPPMDeviceRenderThread::UpdateFilm(Film *film, HitPoints *hitPoints, SampleBuffer *sampleBuffer) {\n\tfilm->Reset();\n\n\tconst unsigned int imgWidth = film->GetWidth();\n\tfor (unsigned int i = 0; i < hitPoints->GetSize(); ++i) {\n\t\tHitPoint *hp = hitPoints->GetHitPoint(i);\n\t\tconst float scrX = i % imgWidth;\n\t\tconst float scrY = i \/ imgWidth;\n\t\tsampleBuffer->SplatSample(scrX, scrY, hp->radiance);\n\n\t\tif (sampleBuffer->IsFull()) {\n\t\t\t\/\/ Splat all samples on the film\n\t\t\tfilm->SplatSampleBuffer(true, sampleBuffer);\n\t\t\tsampleBuffer = film->GetFreeSampleBuffer();\n\t\t}\n\t}\n\n\tif (sampleBuffer->GetSampleCount() > 0) {\n\t\t\/\/ Splat all samples on the film\n\t\tfilm->SplatSampleBuffer(true, sampleBuffer);\n\t\tsampleBuffer = film->GetFreeSampleBuffer();\n\t}\n}\n\nvoid SPPMDeviceRenderThread::InitPhotonPath(Scene *scene, RandomGenerator *rndGen,\n\tPhotonPath *photonPath, Ray *ray, unsigned int *photonTracedPass) {\n\t\/\/ Select one light source\n\tfloat lpdf;\n\tconst LightSource *light = scene->SampleAllLights(rndGen->floatValue(), &lpdf);\n\n\t\/\/ Initialize the photon path\n\tfloat pdf;\n\tphotonPath->flux = light->Sample_L(scene,\n\t\trndGen->floatValue(), rndGen->floatValue(),\n\t\trndGen->floatValue(), rndGen->floatValue(),\n\t\t&pdf, ray);\n\tphotonPath->flux \/= pdf * lpdf;\n\tphotonPath->depth = 0;\n\n\tAtomicInc(photonTracedPass);\n}\n\nvoid SPPMDeviceRenderThread::RenderThreadImpl(SPPMDeviceRenderThread *renderThread) {\n\tcerr << \"[SPPMDeviceRenderThread::\" << renderThread->threadIndex << \"] Rendering thread started\" << endl;\n\n\tSPPMRenderEngine *renderEngine = renderThread->renderEngine;\n\tScene *scene = renderEngine->scene;\n\tRandomGenerator *rndGen = new RandomGenerator();\n\trndGen->init(renderThread->threadIndex + renderEngine->seedBase + 1);\n\n\tIntersectionDevice *device = renderThread->intersectionDevice;\n\tRayBuffer *rayBuffer = renderThread->rayBuffer;\n\tRayBuffer *rayBufferHitPoints = renderThread->rayBufferHitPoints;\n\n\tif (renderThread->threadIndex == 0) {\n\t\t\/\/ Build the EyePaths list\n\t\trenderEngine->hitPoints = new HitPoints(\n\t\t\t\tscene, rndGen, device,\n\t\t\t\trayBufferHitPoints, renderEngine->photonAlpha,\n\t\t\t\trenderEngine->maxEyePathDepth,\n\t\t\t\trenderEngine->film->GetWidth(), renderEngine->film->GetHeight(),\n\t\t\t\trenderEngine->accelType);\n\t}\n\n\tHitPoints *hitPoints = NULL;\n\ttry {\n\t\t\/\/ Wait for other threads\n\t\trenderEngine->barrierStart->wait();\n\n\t\thitPoints = renderEngine->hitPoints;\n\n\t\t\/\/std::cerr << \"[SPPMDeviceRenderThread::\" << renderThread->threadIndex << \"] Tracing photon paths\" << std::endl;\n\n\t\t\/\/ Generate photons from light sources\n\t\tstd::vector photonPaths(rayBuffer->GetSize());\n\t\tRay *rays = rayBuffer->GetRayBuffer();\n\t\tfor (unsigned int i = 0; i < photonPaths.size(); ++i) {\n\t\t\t\/\/ Note: there is some assumption here about how the\n\t\t\t\/\/ rayBuffer->ReserveRay() work\n\t\t\tInitPhotonPath(scene, rndGen, &photonPaths[i], &rays[rayBuffer->ReserveRay()],\n\t\t\t\t\t&renderEngine->photonTracedPass);\n\t\t}\n\n\t\twhile (!boost::this_thread::interruption_requested()) {\n\t\t\t\/\/ Trace the rays\n\t\t\tdevice->PushRayBuffer(rayBuffer);\n\t\t\trayBuffer = device->PopRayBuffer();\n\n\t\t\tfor (unsigned int i = 0; i < rayBuffer->GetRayCount(); ++i) {\n\t\t\t\tPhotonPath *photonPath = &photonPaths[i];\n\t\t\t\tRay *ray = &rayBuffer->GetRayBuffer()[i];\n\t\t\t\tconst RayHit *rayHit = &rayBuffer->GetHitBuffer()[i];\n\n\t\t\t\tif (rayHit->Miss()) {\n\t\t\t\t\t\/\/ Re-initialize the photon path\n\t\t\t\t\tInitPhotonPath(scene, rndGen, photonPath, ray,\n\t\t\t\t\t\t\t&renderEngine->photonTracedPass);\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ Something was hit\n\t\t\t\t\tPoint hitPoint;\n\t\t\t\t\tSpectrum surfaceColor;\n\t\t\t\t\tNormal N, shadeN;\n\t\t\t\t\tif (GetHitPointInformation(scene, rndGen, ray, rayHit, hitPoint,\n\t\t\t\t\t\t\tsurfaceColor, N, shadeN))\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\t\/\/ Get the material\n\t\t\t\t\tconst unsigned int currentTriangleIndex = rayHit->index;\n\t\t\t\t\tconst Material *triMat = scene->triangleMaterials[currentTriangleIndex];\n\n\t\t\t\t\tif (triMat->IsLightSource()) {\n\t\t\t\t\t\t\/\/ Re-initialize the photon path\n\t\t\t\t\t\tInitPhotonPath(scene, rndGen, photonPath, ray,\n\t\t\t\t\t\t\t\t&renderEngine->photonTracedPass);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tconst SurfaceMaterial *triSurfMat = (SurfaceMaterial *)triMat;\n\n\t\t\t\t\t\tfloat fPdf;\n\t\t\t\t\t\tVector wi;\n\t\t\t\t\t\tbool specularBounce;\n\t\t\t\t\t\tconst Spectrum f = triSurfMat->Sample_f(-ray->d, &wi, N, shadeN,\n\t\t\t\t\t\t\t\trndGen->floatValue(), rndGen->floatValue(), rndGen->floatValue(),\n\t\t\t\t\t\t\t\tfalse, &fPdf, specularBounce) * surfaceColor;\n\n\t\t\t\t\t\tif (!specularBounce)\n\t\t\t\t\t\t\thitPoints->AddFlux(hitPoint, shadeN, -ray->d, photonPath->flux);\n\n\t\t\t\t\t\t\/\/ Check if we reached the max. depth\n\t\t\t\t\t\tif (photonPath->depth < renderEngine->maxPhotonPathDepth) {\n\t\t\t\t\t\t\t\/\/ Build the next vertex path ray\n\t\t\t\t\t\t\tif ((fPdf <= 0.f) || f.Black()) {\n\t\t\t\t\t\t\t\t\/\/ Re-initialize the photon path\n\t\t\t\t\t\t\t\tInitPhotonPath(scene, rndGen, photonPath, ray,\n\t\t\t\t\t\t\t\t\t\t&renderEngine->photonTracedPass);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tphotonPath->depth++;\n\t\t\t\t\t\t\t\tphotonPath->flux *= f \/ fPdf;\n\n\t\t\t\t\t\t\t\t\/\/ Russian Roulette\n\t\t\t\t\t\t\t\tconst float p = 0.7f;\n\t\t\t\t\t\t\t\tif ((photonPath->depth < 2) || (specularBounce)) {\n\t\t\t\t\t\t\t\t\t*ray = Ray(hitPoint, wi);\n\t\t\t\t\t\t\t\t} else if (rndGen->floatValue() < p) {\n\t\t\t\t\t\t\t\t\tphotonPath->flux \/= p;\n\t\t\t\t\t\t\t\t\t*ray = Ray(hitPoint, wi);\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\/\/ Re-initialize the photon path\n\t\t\t\t\t\t\t\t\tInitPhotonPath(scene, rndGen, photonPath, ray,\n\t\t\t\t\t\t\t\t\t\t\t&renderEngine->photonTracedPass);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\/\/ Re-initialize the photon path\n\t\t\t\t\t\t\tInitPhotonPath(scene, rndGen, photonPath, ray,\n\t\t\t\t\t\t\t\t\t&renderEngine->photonTracedPass);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ Check if it is time to do an eye pass\n\t\t\t\/\/ TODO: add a parameter to tune rehashing intervals\n\t\t\tif (renderEngine->photonTracedPass > renderEngine->stochasticInterval) {\n\t\t\t\t\/\/ Wait for other threads\n\t\t\t\trenderEngine->barrierStop->wait();\n\n\t\t\t\t\/\/ The first thread does the eye pass\n\t\t\t\tif (renderThread->threadIndex == 0) {\n\t\t\t\t\tconst long long count = renderEngine->photonTracedTotal + renderEngine->photonTracedPass;\n\t\t\t\t\thitPoints->Recast(rndGen, rayBufferHitPoints, count);\n\n\t\t\t\t\t\/\/ Update the frame buffer\n\t\t\t\t\tUpdateFilm(renderEngine->film, hitPoints, renderEngine->sampleBuffer);\n\n\t\t\t\t\trenderEngine->photonTracedTotal = count;\n\t\t\t\t\trenderEngine->photonTracedPass = 0;\n\t\t\t\t}\n\n\t\t\t\t\/\/ Wait for other threads\n\t\t\t\trenderEngine->barrierStart->wait();\n\t\t\t\t\/\/std::cerr << \"[SPPMDeviceRenderThread::\" << renderThread->threadIndex << \"] Tracing photon paths\" << std::endl;\n\t\t\t}\n\t\t}\n\n\t\tcerr << \"[SPPMDeviceRenderThread::\" << renderThread->threadIndex << \"] Rendering thread halted\" << endl;\n\t} catch (boost::thread_interrupted) {\n\t\tcerr << \"[SPPMDeviceRenderThread::\" << renderThread->threadIndex << \"] Rendering thread halted\" << endl;\n\t}\n#if !defined(LUXRAYS_DISABLE_OPENCL)\n\tcatch (cl::Error err) {\n\t\tcerr << \"[SPPMDeviceRenderThread::\" << renderThread->threadIndex << \"] Rendering thread ERROR: \" << err.what() << \"(\" << err.err() << \")\" << endl;\n\t}\n#endif\n\n\t\/\/ Wait for other threads\n\trenderEngine->barrierExit->wait();\n\n\tif (renderThread->threadIndex == 0) {\n\t\trenderEngine->hitPoints = NULL;\n\t\tdelete hitPoints;\n\t}\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ SPPMRenderEngine\n\/\/------------------------------------------------------------------------------\n\nSPPMRenderEngine::SPPMRenderEngine(SLGScene *scn, Film *flm,\n\t\tvector intersectionDev,\n\t\tconst Properties &cfg) : RenderEngine(scn, flm) {\n\tintersectionDevices = intersectionDev;\n\n\taccelType = HASH_GRID;\n\tseedBase = (unsigned long)(WallClockTime() \/ 1000.0);\n\tphotonAlpha = 0.7f;\n\tmaxEyePathDepth = 16;\n\tmaxPhotonPathDepth = 8;\n\tstochasticInterval = cfg.GetInt(\"sppm.stochastic.count\", 10000000);\n\n\thitPoints = NULL;\n\tsampleBuffer = film->GetFreeSampleBuffer();\n\n\t\/\/ Create and start render threads\n\tconst size_t renderThreadCount = intersectionDevices.size();\n\tcerr << \"Starting \"<< renderThreadCount << \" SPPM render threads\" << endl;\n\tfor (size_t i = 0; i < renderThreadCount; ++i) {\n\t\tSPPMDeviceRenderThread *t = new SPPMDeviceRenderThread(i, seedBase, intersectionDevices[i], this);\n\t\trenderThreads.push_back(t);\n\t}\n}\n\nSPPMRenderEngine::~SPPMRenderEngine() {\n\tif (started) {\n\t\tInterrupt();\n\t\tStop();\n\t}\n\n\tfor (size_t i = 0; i < renderThreads.size(); ++i)\n\t\tdelete renderThreads[i];\n\n\tfilm->FreeSampleBuffer(sampleBuffer);\n}\n\nvoid SPPMRenderEngine::Start() {\n\tRenderEngine::Start();\n\n\tphotonTracedTotal = 0;\n\tphotonTracedPass = 0;\n\n\t\/\/ Create synchronization barriers\n\tbarrierStop = new boost::barrier(renderThreads.size());\n\tbarrierStart = new boost::barrier(renderThreads.size());\n\tbarrierExit = new boost::barrier(renderThreads.size());\n\n\tfor (size_t i = 0; i < renderThreads.size(); ++i)\n\t\trenderThreads[i]->Start();\n}\n\nvoid SPPMRenderEngine::Interrupt() {\n\tfor (size_t i = 0; i < renderThreads.size(); ++i)\n\t\trenderThreads[i]->Interrupt();\n}\n\nvoid SPPMRenderEngine::Stop() {\n\tRenderEngine::Stop();\n\n\tfor (size_t i = 0; i < renderThreads.size(); ++i)\n\t\trenderThreads[i]->Stop();\n\n\tdelete barrierStop;\n\tdelete barrierStart;\n\tdelete barrierExit;\n}\n\nvoid SPPMRenderEngine::Reset() {\n\tassert (!started);\n}\n\nunsigned int SPPMRenderEngine::GetPass() const {\n\treturn (hitPoints) ? hitPoints->GetPassCount() : 0;\n}\n\nunsigned int SPPMRenderEngine::GetThreadCount() const {\n\treturn renderThreads.size();\n}\n<|endoftext|>"} {"text":"\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/perv\/p9_mem_startclocks.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/------------------------------------------------------------------------------\n\/\/\/ @file p9_mem_startclocks.C\n\/\/\/\n\/\/\/ @brief Start clocks on MBA\/MCAs\n\/\/------------------------------------------------------------------------------\n\/\/ *HWP HW Owner : Anusha Reddy Rangareddygari \n\/\/ *HWP HW Backup Owner : Srinivas V Naga \n\/\/ *HWP FW Owner : Sunil Kumar \n\/\/ *HWP Team : Perv\n\/\/ *HWP Level : 1\n\/\/ *HWP Consumed by : HB\n\/\/------------------------------------------------------------------------------\n\n\n\/\/## auto_generated\n#include \"p9_mem_startclocks.H\"\n\n\n\nfapi2::ReturnCode p9_mem_startclocks(const fapi2::Target& i_target_chiplet)\n{\n FAPI_DBG(\"Entering ...\");\n\n FAPI_DBG(\"Exiting ...\");\n\n return fapi2::FAPI2_RC_SUCCESS;\n\n}\nLevel 2 HWP p9_mem_startclocks\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/import\/chips\/p9\/procedures\/hwp\/perv\/p9_mem_startclocks.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2015,2019 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\/\/------------------------------------------------------------------------------\n\/\/\/ @file p9_mem_startclocks.C\n\/\/\/\n\/\/\/ @brief Start clocks on MBA\/MCAs\n\/\/------------------------------------------------------------------------------\n\/\/ *HWP HW Owner : Abhishek Agarwal \n\/\/ *HWP HW Backup Owner : Srinivas V Naga \n\/\/ *HWP FW Owner : Sunil kumar \n\/\/ *HWP Team : Perv\n\/\/ *HWP Level : 2\n\/\/ *HWP Consumed by : HB\n\/\/------------------------------------------------------------------------------\n\n\n\/\/## auto_generated\n#include \"p9_mem_startclocks.H\"\n#include \"p9_const_common.H\"\n#include \"p9_misc_scom_addresses_fld.H\"\n#include \"p9_perv_scom_addresses.H\"\n#include \"p9_perv_scom_addresses_fld.H\"\n#include \"p9_quad_scom_addresses_fld.H\"\n#include \"p9_sbe_common.H\"\n\n\nenum P9_MEM_STARTCLOCKS_Private_Constants\n{\n CLOCK_CMD = 0x1,\n STARTSLAVE = 0x1,\n STARTMASTER = 0x1,\n REGIONS_ALL_EXCEPT_VITAL_NESTPLL = 0x7FE,\n CLOCK_TYPES = 0x7,\n DONT_STARTMASTER = 0x0,\n DONT_STARTSLAVE = 0x0\n};\n\nstatic fapi2::ReturnCode p9_mem_startclocks_check_checkstop_function(\n const fapi2::Target& i_target_chiplet);\n\nstatic fapi2::ReturnCode p9_mem_startclocks_cplt_ctrl_action_function(\n const fapi2::Target& i_target_chiplet);\n\nstatic fapi2::ReturnCode p9_mem_startclocks_flushmode(\n const fapi2::Target& i_target_chiplet);\n\nfapi2::ReturnCode p9_mem_startclocks(const\n fapi2::Target& i_target_chip)\n{\n FAPI_DBG(\"Entering ...\");\n\n FAPI_INF(\"Switch MC meshs to Nest mesh\");\n\n for (auto l_trgt_chplt : i_target_chip.getChildren\n (fapi2::TARGET_FILTER_ALL_MC, fapi2::TARGET_STATE_FUNCTIONAL))\n {\n\n FAPI_INF(\"Call p9_mem_startclocks_cplt_ctrl_action_function for Mc chiplets\");\n FAPI_TRY(p9_mem_startclocks_cplt_ctrl_action_function(l_trgt_chplt));\n\n FAPI_INF(\"Call module align chiplets for Mc chiplets\");\n FAPI_TRY(p9_sbe_common_align_chiplets(l_trgt_chplt));\n\n FAPI_INF(\"Call module clock start stop for MC01, MC23.\");\n FAPI_TRY(p9_sbe_common_clock_start_stop(l_trgt_chplt, CLOCK_CMD,\n DONT_STARTSLAVE, DONT_STARTMASTER, REGIONS_ALL_EXCEPT_VITAL_NESTPLL,\n CLOCK_TYPES));\n\n FAPI_INF(\"Call p9_mem_startclocks_check_checkstop_function for Mc chiplets \");\n FAPI_TRY(p9_mem_startclocks_check_checkstop_function(l_trgt_chplt));\n\n FAPI_INF(\"Call p9_mem_startclocks_flushmode for Mc chiplets\");\n FAPI_TRY(p9_mem_startclocks_flushmode(l_trgt_chplt));\n\n }\n\n FAPI_DBG(\"Exiting ...\");\n\nfapi_try_exit:\n return fapi2::current_err;\n\n}\n\n\/\/\/ @brief --drop chiplet fence\n\/\/\/ --check checkstop register\n\/\/\/ --clear flush inhibit to go into flush mode\n\/\/\/\n\/\/\/ @param[in] i_target_chiplet Reference to TARGET_TYPE_PERV target\n\/\/\/ @return FAPI2_RC_SUCCESS if success, else error code.\nstatic fapi2::ReturnCode p9_mem_startclocks_check_checkstop_function(\n const fapi2::Target& i_target_chiplet)\n{\n fapi2::buffer l_read_reg;\n fapi2::buffer l_data64;\n FAPI_DBG(\"Entering ...\");\n\n FAPI_INF(\"Drop chiplet fence\");\n \/\/Setting NET_CTRL0 register value\n l_data64.flush<1>();\n l_data64.clearBit(); \/\/NET_CTRL0.FENCE_EN = 0\n FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_NET_CTRL0_WAND, l_data64));\n\n FAPI_INF(\"Check checkstop register\");\n \/\/Getting XFIR register value\n FAPI_TRY(fapi2::getScom(i_target_chiplet, PERV_XFIR,\n l_read_reg)); \/\/l_read_reg = XFIR\n\n FAPI_ASSERT(l_read_reg == 0,\n fapi2::READ_ALL_CHECKSTOP_ERR()\n .set_READ_ALL_CHECKSTOP(l_read_reg),\n \"ERROR: COMBINE ALL CHECKSTOP ERROR\");\n\n FAPI_DBG(\"Exiting ...\");\n\nfapi_try_exit:\n return fapi2::current_err;\n\n}\n\n\/\/\/ @brief --drop vital fence\n\/\/\/ --reset abstclk muxsel and syncclk muxsel\n\/\/\/\n\/\/\/ @param[in] i_target_chiplet Reference to TARGET_TYPE_PERV target\n\/\/\/ @return FAPI2_RC_SUCCESS if success, else error code.\nstatic fapi2::ReturnCode p9_mem_startclocks_cplt_ctrl_action_function(\n const fapi2::Target& i_target_chiplet)\n{\n fapi2::buffer l_data64;\n FAPI_DBG(\"Entering ...\");\n\n \/\/ Local variable and constant definition\n fapi2::buffer l_attr_pg;\n\n FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PG, i_target_chiplet, l_attr_pg));\n\n l_attr_pg.invert();\n\n FAPI_INF(\"Drop partial good fences\");\n \/\/Setting CPLT_CTRL1 register value\n l_data64.flush<0>();\n \/\/CPLT_CTRL1.TC_VITL_REGION_FENCE = l_attr_pg.getBit<19>()\n l_data64.writeBit(l_attr_pg.getBit<19>());\n \/\/CPLT_CTRL1.TC_PERV_REGION_FENCE = l_attr_pg.getBit<20>()\n l_data64.writeBit(l_attr_pg.getBit<20>());\n \/\/CPLT_CTRL1.TC_REGION1_FENCE = l_attr_pg.getBit<21>()\n l_data64.writeBit(l_attr_pg.getBit<21>());\n \/\/CPLT_CTRL1.TC_REGION2_FENCE = l_attr_pg.getBit<22>()\n l_data64.writeBit(l_attr_pg.getBit<22>());\n \/\/CPLT_CTRL1.TC_REGION3_FENCE = l_attr_pg.getBit<23>()\n l_data64.writeBit(l_attr_pg.getBit<23>());\n \/\/CPLT_CTRL1.TC_REGION4_FENCE = l_attr_pg.getBit<24>()\n l_data64.writeBit(l_attr_pg.getBit<24>());\n \/\/CPLT_CTRL1.TC_REGION5_FENCE = l_attr_pg.getBit<25>()\n l_data64.writeBit(l_attr_pg.getBit<25>());\n \/\/CPLT_CTRL1.TC_REGION6_FENCE = l_attr_pg.getBit<26>()\n l_data64.writeBit(l_attr_pg.getBit<26>());\n \/\/CPLT_CTRL1.TC_REGION7_FENCE = l_attr_pg.getBit<27>()\n l_data64.writeBit(l_attr_pg.getBit<27>());\n \/\/CPLT_CTRL1.UNUSED_12B = l_attr_pg.getBit<28>()\n l_data64.writeBit(l_attr_pg.getBit<28>());\n \/\/CPLT_CTRL1.UNUSED_13B = l_attr_pg.getBit<29>()\n l_data64.writeBit(l_attr_pg.getBit<29>());\n \/\/CPLT_CTRL1.UNUSED_14B = l_attr_pg.getBit<30>()\n l_data64.writeBit(l_attr_pg.getBit<30>());\n FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_CPLT_CTRL1_CLEAR, l_data64));\n\n FAPI_INF(\"reset abistclk_muxsel and syncclk_muxsel\");\n \/\/Setting CPLT_CTRL0 register value\n l_data64.flush<0>();\n \/\/CPLT_CTRL0.CTRL_CC_ABSTCLK_MUXSEL_DC = 1\n l_data64.writeBit(1);\n \/\/CPLT_CTRL0.TC_UNIT_SYNCCLK_MUXSEL_DC = 1\n l_data64.writeBit(1);\n FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_CPLT_CTRL0_CLEAR, l_data64));\n\n FAPI_DBG(\"Exiting ...\");\n\nfapi_try_exit:\n return fapi2::current_err;\n\n}\n\n\/\/\/ @brief will force all chiplets out of flush\n\/\/\/\n\/\/\/ @param[in] i_target_chiplet Reference to TARGET_TYPE_PERV target\n\/\/\/ @return FAPI2_RC_SUCCESS if success, else error code.\nstatic fapi2::ReturnCode p9_mem_startclocks_flushmode(\n const fapi2::Target& i_target_chiplet)\n{\n fapi2::buffer l_data64;\n FAPI_DBG(\"Entering ...\");\n\n FAPI_INF(\"Clear flush_inhibit to go in to flush mode\");\n \/\/Setting CPLT_CTRL0 register value\n l_data64.flush<0>();\n \/\/CPLT_CTRL0.CTRL_CC_FLUSHMODE_INH_DC = 0\n l_data64.setBit();\n FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_CPLT_CTRL0_CLEAR, l_data64));\n\n FAPI_DBG(\"Exiting ...\");\n\nfapi_try_exit:\n return fapi2::current_err;\n\n}\n<|endoftext|>"} {"text":"#include \"medGroupBox.h\"\n\n\nclass medGroupBoxPrivate\n{\npublic:\n bool collapsible;\n bool collapsed;\n};\n\nmedGroupBox::medGroupBox(QWidget *parent) :\n QGroupBox(parent),d(new medGroupBoxPrivate)\n{\n d->collapsible = false;\n d->collapsed = false;\n\n\n connect(this, SIGNAL(toggled(bool)), this, SLOT(setExpanded(bool)));\n\n}\n\nmedGroupBox::~medGroupBox()\n{\n}\n\nbool medGroupBox::isCollapsible()\n{\n return d->collapsible;\n}\n\n\n\nvoid medGroupBox::setCollapsible(bool collapsible)\n{\n d->collapsible = collapsible;\n \/\/change appearance if necessary:\n if (!collapsible)\n setCollapsed(false);\n else if (!isChecked())\/\/hide content\n setCollapsed(true);\n}\n\nbool medGroupBox::isCollapsed()\n{\n return d->collapsed;\n}\n\nvoid medGroupBox::setCollapsed(bool collapse)\n{\n d->collapsed = collapse;\n \/\/only collapse if collapsible,\n \/\/and show whenever it is asked.\n if (d->collapsible || !collapse)\n {\n \/\/ show\/hide children\n foreach(QObject* child, children())\n {\n if (child->isWidgetType())\n qobject_cast(child)->setVisible(!collapse);\n }\n }\n}\n\nvoid medGroupBox::setExpanded(bool expand)\n{\n setCollapsed(!expand);\n}\n\nvoid medGroupBox::childEvent(QChildEvent *event)\n{\n \/\/any added children must be hidden if we are collapsed!\n QObject* child = event->child();\n if (event->added() && child->isWidgetType())\n {\n QWidget* widget = qobject_cast(child);\n if (d->collapsible && !isChecked())\n widget->hide();\n }\n}\n\nFixes memory leak on medGroupBox#include \"medGroupBox.h\"\n\n\nclass medGroupBoxPrivate\n{\npublic:\n bool collapsible;\n bool collapsed;\n};\n\nmedGroupBox::medGroupBox(QWidget *parent) :\n QGroupBox(parent),d(new medGroupBoxPrivate)\n{\n d->collapsible = false;\n d->collapsed = false;\n\n\n connect(this, SIGNAL(toggled(bool)), this, SLOT(setExpanded(bool)));\n\n}\n\nmedGroupBox::~medGroupBox()\n{\n delete d;\n d = NULL;\n}\n\nbool medGroupBox::isCollapsible()\n{\n return d->collapsible;\n}\n\n\n\nvoid medGroupBox::setCollapsible(bool collapsible)\n{\n d->collapsible = collapsible;\n \/\/change appearance if necessary:\n if (!collapsible)\n setCollapsed(false);\n else if (!isChecked())\/\/hide content\n setCollapsed(true);\n}\n\nbool medGroupBox::isCollapsed()\n{\n return d->collapsed;\n}\n\nvoid medGroupBox::setCollapsed(bool collapse)\n{\n d->collapsed = collapse;\n \/\/only collapse if collapsible,\n \/\/and show whenever it is asked.\n if (d->collapsible || !collapse)\n {\n \/\/ show\/hide children\n foreach(QObject* child, children())\n {\n if (child->isWidgetType())\n qobject_cast(child)->setVisible(!collapse);\n }\n }\n}\n\nvoid medGroupBox::setExpanded(bool expand)\n{\n setCollapsed(!expand);\n}\n\nvoid medGroupBox::childEvent(QChildEvent *event)\n{\n \/\/any added children must be hidden if we are collapsed!\n QObject* child = event->child();\n if (event->added() && child->isWidgetType())\n {\n QWidget* widget = qobject_cast(child);\n if (d->collapsible && !isChecked())\n widget->hide();\n }\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright 2009 Google Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ Log viewer window implementation.\n#include \"sawbuck\/viewer\/log_viewer.h\"\n\n#include \n#include \n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"pcrecpp.h\" \/\/ NOLINT\n#include \"sawbuck\/viewer\/filtered_log_view.h\"\n#include \"sawbuck\/viewer\/filter_dialog.h\"\n#include \"sawbuck\/viewer\/const_config.h\"\n#include \"sawbuck\/viewer\/preferences.h\"\n\nLogViewer::LogViewer(CUpdateUIBase* update_ui)\n : log_list_view_(update_ui),\n stack_trace_list_view_(update_ui),\n log_view_(NULL),\n update_ui_(update_ui) {\n Preferences prefs;\n prefs.ReadStringValue(config::kIncludeReValue, &include_re_, \".*\");\n prefs.ReadStringValue(config::kExcludeReValue, &exclude_re_, \"\");\n}\n\nLogViewer::~LogViewer() {\n}\n\nint LogViewer::OnCreate(LPCREATESTRUCT create_struct) {\n BOOL bHandled = TRUE;\n Super::OnCreate(WM_CREATE,\n NULL,\n reinterpret_cast(create_struct),\n bHandled);\n\n \/\/ Create the log list view.\n log_list_view_.Create(m_hWnd);\n\n \/\/ Create the stack trace list view.\n stack_trace_list_view_.Create(m_hWnd);\n\n log_list_view_.set_stack_trace_view(&stack_trace_list_view_);\n\n SetDefaultActivePane(SPLIT_PANE_TOP);\n SetSplitterPanes(log_list_view_.m_hWnd, stack_trace_list_view_.m_hWnd);\n SetSplitterExtendedStyle(SPLIT_BOTTOMALIGNED);\n\n \/\/ This is enabled so long as we live.\n update_ui_->UIEnable(ID_LOG_FILTER, true);\n\n SetMsgHandled(FALSE);\n return 1;\n}\n\nLRESULT LogViewer::OnCommand(UINT msg,\n WPARAM wparam,\n LPARAM lparam,\n BOOL& handled) {\n HWND window = GetSplitterPane(GetActivePane());\n return ::SendMessage(window, msg, wparam, lparam);\n}\n\nvoid LogViewer::OnLogFilter(UINT code, int id, CWindow window) {\n FilterDialog dialog;\n\n if (dialog.DoModal(m_hWnd) == IDOK) {\n std::vector filters = dialog.get_filters();\n Preferences pref;\n pref.WriteStringValue(config::kFilterValues,\n Filter::SerializeFilters(filters));\n\n \/\/ TODO(robertshield): If dialog.get_filters() is empty, we should set it\n \/\/ back to the non filtered log view.\n scoped_ptr new_view(new FilteredLogView(log_view_,\n filters));\n log_list_view_.SetLogView(new_view.get());\n\n filtered_log_view_.reset(new_view.release());\n }\n}\nFix a merge problem that occurred when r94 got checked in.+\/\/ Copyright 2009 Google Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ Log viewer window implementation.\n#include \"sawbuck\/viewer\/log_viewer.h\"\n\n#include \n#include \n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"pcrecpp.h\" \/\/ NOLINT\n#include \"sawbuck\/viewer\/filtered_log_view.h\"\n#include \"sawbuck\/viewer\/filter_dialog.h\"\n#include \"sawbuck\/viewer\/const_config.h\"\n#include \"sawbuck\/viewer\/preferences.h\"\n\nLogViewer::LogViewer(CUpdateUIBase* update_ui)\n : log_list_view_(update_ui),\n stack_trace_list_view_(update_ui),\n log_view_(NULL),\n update_ui_(update_ui) {\n Preferences prefs;\n prefs.ReadStringValue(config::kIncludeReValue, &include_re_, \".*\");\n prefs.ReadStringValue(config::kExcludeReValue, &exclude_re_, \"\");\n}\n\nLogViewer::~LogViewer() {\n}\n\nvoid LogViewer::SetLogView(ILogView* log_view) {\n DCHECK(log_view_ == NULL);\n log_view_ = log_view;\n}\n\nint LogViewer::OnCreate(LPCREATESTRUCT create_struct) {\n BOOL bHandled = TRUE;\n Super::OnCreate(WM_CREATE,\n NULL,\n reinterpret_cast(create_struct),\n bHandled);\n\n \/\/ Create the log list view.\n log_list_view_.Create(m_hWnd);\n\n \/\/ Create the stack trace list view.\n stack_trace_list_view_.Create(m_hWnd);\n\n log_list_view_.set_stack_trace_view(&stack_trace_list_view_);\n\n SetDefaultActivePane(SPLIT_PANE_TOP);\n SetSplitterPanes(log_list_view_.m_hWnd, stack_trace_list_view_.m_hWnd);\n SetSplitterExtendedStyle(SPLIT_BOTTOMALIGNED);\n\n \/\/ This is enabled so long as we live.\n update_ui_->UIEnable(ID_LOG_FILTER, true);\n\n SetMsgHandled(FALSE);\n return 1;\n}\n\nLRESULT LogViewer::OnCommand(UINT msg,\n WPARAM wparam,\n LPARAM lparam,\n BOOL& handled) {\n HWND window = GetSplitterPane(GetActivePane());\n return ::SendMessage(window, msg, wparam, lparam);\n}\n\nvoid LogViewer::OnLogFilter(UINT code, int id, CWindow window) {\n FilterDialog dialog;\n\n if (dialog.DoModal(m_hWnd) == IDOK) {\n std::vector filters = dialog.get_filters();\n Preferences pref;\n pref.WriteStringValue(config::kFilterValues,\n Filter::SerializeFilters(filters));\n\n \/\/ TODO(robertshield): If dialog.get_filters() is empty, we should set it\n \/\/ back to the non filtered log view.\n scoped_ptr new_view(new FilteredLogView(log_view_,\n filters));\n log_list_view_.SetLogView(new_view.get());\n\n filtered_log_view_.reset(new_view.release());\n }\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \n\n#include \"base\/files\/file_path.h\"\n#include \"chrome\/browser\/search\/suggestions\/proto\/suggestions.pb.h\"\n#include \"chrome\/browser\/search\/suggestions\/thumbnail_manager.h\"\n#include \"chrome\/test\/base\/in_process_browser_test.h\"\n#include \"chrome\/test\/base\/testing_profile.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"content\/public\/test\/test_browser_thread_bundle.h\"\n#include \"content\/public\/test\/test_utils.h\"\n#include \"net\/test\/spawned_test_server\/spawned_test_server.h\"\n#include \"net\/url_request\/url_request_test_util.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"ui\/gfx\/image\/image_skia.h\"\n#include \"url\/gurl.h\"\n\nnamespace {\n\nconst char kTestUrl1[] = \"http:\/\/go.com\/\";\nconst char kTestUrl2[] = \"http:\/\/goal.com\/\";\nconst char kTestImagePath[] = \"files\/image_decoding\/droids.png\";\nconst char kInvalidImagePath[] = \"files\/DOESNOTEXIST\";\n\nconst base::FilePath::CharType kDocRoot[] =\n FILE_PATH_LITERAL(\"chrome\/test\/data\");\n\nusing content::BrowserThread;\n\nclass ThumbnailManagerBrowserTest : public InProcessBrowserTest {\n public:\n ThumbnailManagerBrowserTest()\n : num_callback_null_called_(0),\n num_callback_valid_called_(0),\n thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP),\n test_server_(net::SpawnedTestServer::TYPE_HTTP,\n net::SpawnedTestServer::kLocalhost,\n base::FilePath(kDocRoot)) {}\n\n virtual void SetUp() OVERRIDE {\n ASSERT_TRUE(test_server_.Start());\n\n context_ = new net::TestURLRequestContextGetter(\n BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));\n context_->AddRef();\n }\n\n virtual void TearDown() OVERRIDE {\n BrowserThread::ReleaseSoon(BrowserThread::IO, FROM_HERE, context_);\n }\n\n void OnThumbnailAvailable(const GURL& url, const SkBitmap* bitmap) {\n if (bitmap) {\n num_callback_valid_called_++;\n } else {\n num_callback_null_called_++;\n }\n }\n int num_callback_null_called_;\n int num_callback_valid_called_;\n content::TestBrowserThreadBundle thread_bundle_;\n net::SpawnedTestServer test_server_;\n net::TestURLRequestContextGetter* context_;\n};\n\n} \/\/ namespace\n\nnamespace suggestions {\n\nIN_PROC_BROWSER_TEST_F(ThumbnailManagerBrowserTest, FetchThumbnails) {\n SuggestionsProfile suggestions_profile;\n ChromeSuggestion* suggestion = suggestions_profile.add_suggestions();\n suggestion->set_url(kTestUrl1);\n suggestion->set_thumbnail(test_server_.GetURL(kTestImagePath).spec());\n\n TestingProfile profile;\n ThumbnailManager thumbnail_manager(profile.GetRequestContext());\n thumbnail_manager.InitializeThumbnailMap(suggestions_profile);\n\n \/\/ Fetch existing URL.\n thumbnail_manager.GetPageThumbnail(\n GURL(kTestUrl1),\n base::Bind(&ThumbnailManagerBrowserTest::OnThumbnailAvailable,\n base::Unretained(this)));\n\n content::RunMessageLoop();\n\n EXPECT_EQ(0, num_callback_null_called_);\n EXPECT_EQ(1, num_callback_valid_called_);\n\n \/\/ Fetch non-existing URL.\n thumbnail_manager.GetPageThumbnail(\n GURL(kTestUrl2),\n base::Bind(&ThumbnailManagerBrowserTest::OnThumbnailAvailable,\n base::Unretained(this)));\n\n content::RunMessageLoop();\n\n EXPECT_EQ(1, num_callback_null_called_);\n EXPECT_EQ(1, num_callback_valid_called_);\n}\n\nIN_PROC_BROWSER_TEST_F(ThumbnailManagerBrowserTest, FetchThumbnailsMultiple) {\n SuggestionsProfile suggestions_profile;\n ChromeSuggestion* suggestion = suggestions_profile.add_suggestions();\n suggestion->set_url(kTestUrl1);\n suggestion->set_thumbnail(test_server_.GetURL(kTestImagePath).spec());\n\n TestingProfile profile;\n ThumbnailManager thumbnail_manager(profile.GetRequestContext());\n thumbnail_manager.InitializeThumbnailMap(suggestions_profile);\n\n \/\/ Fetch non-existing URL, and add more while request is in flight.\n for (int i = 0 ; i < 5; i++) {\n thumbnail_manager.GetPageThumbnail(\n GURL(kTestUrl1),\n base::Bind(&ThumbnailManagerBrowserTest::OnThumbnailAvailable,\n base::Unretained(this)));\n }\n\n content::RunMessageLoop();\n\n EXPECT_EQ(0, num_callback_null_called_);\n EXPECT_EQ(5, num_callback_valid_called_);\n}\n\nIN_PROC_BROWSER_TEST_F(ThumbnailManagerBrowserTest, FetchThumbnailsInvalid) {\n SuggestionsProfile suggestions_profile;\n ChromeSuggestion* suggestion = suggestions_profile.add_suggestions();\n suggestion->set_url(kTestUrl1);\n suggestion->set_thumbnail(test_server_.GetURL(kInvalidImagePath).spec());\n\n TestingProfile profile;\n ThumbnailManager thumbnail_manager(profile.GetRequestContext());\n thumbnail_manager.InitializeThumbnailMap(suggestions_profile);\n\n \/\/ Fetch existing URL that has invalid thumbnail.\n thumbnail_manager.GetPageThumbnail(\n GURL(kTestUrl1),\n base::Bind(&ThumbnailManagerBrowserTest::OnThumbnailAvailable,\n base::Unretained(this)));\n\n content::RunMessageLoop();\n\n EXPECT_EQ(1, num_callback_null_called_);\n EXPECT_EQ(0, num_callback_valid_called_);\n}\n\n} \/\/ namespace suggestions\n[SuggestionsService] Fix ThumbnailManagerBrowserTest, which were not running\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \n\n#include \"base\/files\/file_path.h\"\n#include \"base\/run_loop.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/search\/suggestions\/proto\/suggestions.pb.h\"\n#include \"chrome\/browser\/search\/suggestions\/thumbnail_manager.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/test\/base\/in_process_browser_test.h\"\n#include \"net\/test\/spawned_test_server\/spawned_test_server.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"ui\/gfx\/image\/image_skia.h\"\n#include \"url\/gurl.h\"\n\nnamespace {\n\nconst char kTestUrl1[] = \"http:\/\/go.com\/\";\nconst char kTestUrl2[] = \"http:\/\/goal.com\/\";\nconst char kTestImagePath[] = \"files\/image_decoding\/droids.png\";\nconst char kInvalidImagePath[] = \"files\/DOESNOTEXIST\";\n\nconst base::FilePath::CharType kDocRoot[] =\n FILE_PATH_LITERAL(\"chrome\/test\/data\");\n\nclass ThumbnailManagerBrowserTest : public InProcessBrowserTest {\n public:\n ThumbnailManagerBrowserTest()\n : num_callback_null_called_(0),\n num_callback_valid_called_(0),\n test_server_(net::SpawnedTestServer::TYPE_HTTP,\n net::SpawnedTestServer::kLocalhost,\n base::FilePath(kDocRoot)) {}\n\n virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {\n ASSERT_TRUE(test_server_.Start());\n InProcessBrowserTest::SetUpInProcessBrowserTestFixture();\n }\n\n void OnThumbnailAvailable(base::RunLoop* loop, const GURL& url,\n const SkBitmap* bitmap) {\n if (bitmap) {\n num_callback_valid_called_++;\n } else {\n num_callback_null_called_++;\n }\n loop->Quit();\n }\n\n int num_callback_null_called_;\n int num_callback_valid_called_;\n net::SpawnedTestServer test_server_;\n};\n\n} \/\/ namespace\n\nnamespace suggestions {\n\nIN_PROC_BROWSER_TEST_F(ThumbnailManagerBrowserTest, FetchThumbnails) {\n SuggestionsProfile suggestions_profile;\n ChromeSuggestion* suggestion = suggestions_profile.add_suggestions();\n suggestion->set_url(kTestUrl1);\n suggestion->set_thumbnail(test_server_.GetURL(kTestImagePath).spec());\n\n ThumbnailManager thumbnail_manager(browser()->profile()->GetRequestContext());\n thumbnail_manager.InitializeThumbnailMap(suggestions_profile);\n\n base::RunLoop run_loop;\n \/\/ Fetch existing URL.\n thumbnail_manager.GetPageThumbnail(\n GURL(kTestUrl1),\n base::Bind(&ThumbnailManagerBrowserTest::OnThumbnailAvailable,\n base::Unretained(this), &run_loop));\n run_loop.Run();\n\n EXPECT_EQ(0, num_callback_null_called_);\n EXPECT_EQ(1, num_callback_valid_called_);\n\n base::RunLoop run_loop2;\n thumbnail_manager.GetPageThumbnail(\n GURL(kTestUrl2),\n base::Bind(&ThumbnailManagerBrowserTest::OnThumbnailAvailable,\n base::Unretained(this), &run_loop2));\n run_loop2.Run();\n\n EXPECT_EQ(1, num_callback_null_called_);\n EXPECT_EQ(1, num_callback_valid_called_);\n}\n\nIN_PROC_BROWSER_TEST_F(ThumbnailManagerBrowserTest, FetchThumbnailsMultiple) {\n SuggestionsProfile suggestions_profile;\n ChromeSuggestion* suggestion = suggestions_profile.add_suggestions();\n suggestion->set_url(kTestUrl1);\n suggestion->set_thumbnail(test_server_.GetURL(kTestImagePath).spec());\n\n ThumbnailManager thumbnail_manager(browser()->profile()->GetRequestContext());\n thumbnail_manager.InitializeThumbnailMap(suggestions_profile);\n\n base::RunLoop run_loop;\n \/\/ Fetch non-existing URL, and add more while request is in flight.\n for (int i = 0; i < 5; i++) {\n thumbnail_manager.GetPageThumbnail(\n GURL(kTestUrl1),\n base::Bind(&ThumbnailManagerBrowserTest::OnThumbnailAvailable,\n base::Unretained(this), &run_loop));\n }\n run_loop.Run();\n\n EXPECT_EQ(0, num_callback_null_called_);\n EXPECT_EQ(5, num_callback_valid_called_);\n}\n\nIN_PROC_BROWSER_TEST_F(ThumbnailManagerBrowserTest, FetchThumbnailsInvalid) {\n SuggestionsProfile suggestions_profile;\n ChromeSuggestion* suggestion = suggestions_profile.add_suggestions();\n suggestion->set_url(kTestUrl1);\n suggestion->set_thumbnail(test_server_.GetURL(kInvalidImagePath).spec());\n\n ThumbnailManager thumbnail_manager(browser()->profile()->GetRequestContext());\n thumbnail_manager.InitializeThumbnailMap(suggestions_profile);\n\n base::RunLoop run_loop;\n \/\/ Fetch existing URL that has invalid thumbnail.\n thumbnail_manager.GetPageThumbnail(\n GURL(kTestUrl1),\n base::Bind(&ThumbnailManagerBrowserTest::OnThumbnailAvailable,\n base::Unretained(this), &run_loop));\n run_loop.Run();\n\n EXPECT_EQ(1, num_callback_null_called_);\n EXPECT_EQ(0, num_callback_valid_called_);\n}\n\n} \/\/ namespace suggestions\n<|endoftext|>"} {"text":"Translate message to English<|endoftext|>"} {"text":"\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/common\/extensions\/manifest_handlers\/ui_overrides_handler.h\"\n\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/strings\/string_util.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"base\/values.h\"\n#include \"extensions\/common\/error_utils.h\"\n#include \"extensions\/common\/extension_messages.h\"\n#include \"extensions\/common\/feature_switch.h\"\n#include \"extensions\/common\/manifest_constants.h\"\n#include \"extensions\/common\/permissions\/manifest_permission.h\"\n#include \"extensions\/common\/permissions\/permissions_data.h\"\n#include \"extensions\/common\/permissions\/permissions_info.h\"\n#include \"grit\/generated_resources.h\"\n#include \"ipc\/ipc_message.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n\nusing extensions::api::manifest_types::ChromeUIOverrides;\n\nnamespace extensions {\n\n\/\/ The manifest permission implementation supports a permission for overriding\n\/\/ the bookmark UI.\nclass UIOverridesHandler::ManifestPermissionImpl : public ManifestPermission {\n public:\n explicit ManifestPermissionImpl(bool override_bookmarks_ui_permission)\n : override_bookmarks_ui_permission_(override_bookmarks_ui_permission) {}\n\n \/\/ extensions::ManifestPermission overrides.\n virtual std::string name() const OVERRIDE {\n return manifest_keys::kUIOverride;\n }\n\n virtual std::string id() const OVERRIDE {\n return name();\n }\n\n virtual bool HasMessages() const OVERRIDE {\n return override_bookmarks_ui_permission_;\n }\n\n virtual PermissionMessages GetMessages() const OVERRIDE {\n PermissionMessages result;\n if (override_bookmarks_ui_permission_) {\n result.push_back(PermissionMessage(\n PermissionMessage::kOverrideBookmarksUI,\n l10n_util::GetStringUTF16(\n IDS_EXTENSION_PROMPT_WARNING_OVERRIDE_BOOKMARKS_UI)));\n }\n return result;\n }\n\n virtual bool FromValue(const base::Value* value) OVERRIDE {\n return value && value->GetAsBoolean(&override_bookmarks_ui_permission_);\n }\n\n virtual scoped_ptr ToValue() const OVERRIDE {\n return scoped_ptr(\n new base::FundamentalValue(override_bookmarks_ui_permission_)).Pass();\n }\n\n virtual ManifestPermission* Clone() const OVERRIDE {\n return scoped_ptr(\n new ManifestPermissionImpl(\n override_bookmarks_ui_permission_)).release();\n }\n\n virtual ManifestPermission* Diff(const ManifestPermission* rhs) const\n OVERRIDE {\n const ManifestPermissionImpl* other =\n static_cast(rhs);\n\n return scoped_ptr(new ManifestPermissionImpl(\n override_bookmarks_ui_permission_ &&\n !other->override_bookmarks_ui_permission_)).release();\n }\n\n virtual ManifestPermission* Union(const ManifestPermission* rhs) const\n OVERRIDE {\n const ManifestPermissionImpl* other =\n static_cast(rhs);\n\n return scoped_ptr(new ManifestPermissionImpl(\n override_bookmarks_ui_permission_ ||\n other->override_bookmarks_ui_permission_)).release();\n }\n\n virtual ManifestPermission* Intersect(const ManifestPermission* rhs) const\n OVERRIDE {\n const ManifestPermissionImpl* other =\n static_cast(rhs);\n\n return scoped_ptr(new ManifestPermissionImpl(\n override_bookmarks_ui_permission_ &&\n other->override_bookmarks_ui_permission_)).release();\n }\n\n virtual bool Contains(const ManifestPermission* rhs) const OVERRIDE {\n const ManifestPermissionImpl* other =\n static_cast(rhs);\n\n return !other->override_bookmarks_ui_permission_ ||\n override_bookmarks_ui_permission_;\n }\n\n virtual bool Equal(const ManifestPermission* rhs) const OVERRIDE {\n const ManifestPermissionImpl* other =\n static_cast(rhs);\n\n return override_bookmarks_ui_permission_ ==\n other->override_bookmarks_ui_permission_;\n }\n\n virtual void Write(IPC::Message* m) const OVERRIDE {\n IPC::WriteParam(m, override_bookmarks_ui_permission_);\n }\n\n virtual bool Read(const IPC::Message* m, PickleIterator* iter) OVERRIDE {\n return IPC::ReadParam(m, iter, &override_bookmarks_ui_permission_);\n }\n\n virtual void Log(std::string* log) const OVERRIDE {\n IPC::LogParam(override_bookmarks_ui_permission_, log);\n }\n\n private:\n bool override_bookmarks_ui_permission_;\n};\n\nUIOverrides::UIOverrides() {}\n\nUIOverrides::~UIOverrides() {}\n\nconst UIOverrides* UIOverrides::Get(const Extension* extension) {\n return static_cast(\n extension->GetManifestData(manifest_keys::kUIOverride));\n}\n\nbool UIOverrides::RemovesBookmarkButton(const Extension* extension) {\n const UIOverrides* ui_overrides = Get(extension);\n return ui_overrides && ui_overrides->bookmarks_ui &&\n ui_overrides->bookmarks_ui->remove_button &&\n *ui_overrides->bookmarks_ui->remove_button;\n}\n\nbool UIOverrides::RemovesBookmarkShortcut(const Extension* extension) {\n const UIOverrides* ui_overrides = Get(extension);\n return ui_overrides && ui_overrides->bookmarks_ui &&\n ui_overrides->bookmarks_ui->remove_bookmark_shortcut &&\n *ui_overrides->bookmarks_ui->remove_bookmark_shortcut;\n}\n\nbool UIOverrides::RemovesBookmarkOpenPagesShortcut(const Extension* extension) {\n const UIOverrides* ui_overrides = Get(extension);\n return ui_overrides && ui_overrides->bookmarks_ui &&\n ui_overrides->bookmarks_ui->remove_bookmark_open_pages_shortcut &&\n *ui_overrides->bookmarks_ui->remove_bookmark_open_pages_shortcut;\n}\n\nUIOverridesHandler::UIOverridesHandler() {}\n\nUIOverridesHandler::~UIOverridesHandler() {}\n\nbool UIOverridesHandler::Parse(Extension* extension, base::string16* error) {\n const base::Value* dict = NULL;\n CHECK(extension->manifest()->Get(manifest_keys::kUIOverride, &dict));\n scoped_ptr overrides(\n ChromeUIOverrides::FromValue(*dict, error));\n if (!overrides)\n return false;\n\n scoped_ptr info(new UIOverrides);\n info->bookmarks_ui.swap(overrides->bookmarks_ui);\n if (!info->bookmarks_ui) {\n *error = ErrorUtils::FormatErrorMessageUTF16(\n manifest_errors::kInvalidEmptyDictionary,\n manifest_keys::kUIOverride);\n return false;\n }\n UIOverrides* assigned_ui_overrides = info.get();\n extension->SetManifestData(manifest_keys::kUIOverride, info.release());\n assigned_ui_overrides->manifest_permission.reset(new ManifestPermissionImpl(\n UIOverrides::RemovesBookmarkButton(extension)));\n return true;\n}\n\nbool UIOverridesHandler::Validate(const Extension* extension,\n std::string* error,\n std::vector* warnings) const {\n const UIOverrides* ui_overrides = UIOverrides::Get(extension);\n\n if (ui_overrides && ui_overrides->bookmarks_ui) {\n if (!FeatureSwitch::enable_override_bookmarks_ui()->IsEnabled()) {\n warnings->push_back(InstallWarning(\n ErrorUtils::FormatErrorMessage(\n manifest_errors::kUnrecognizedManifestProperty,\n manifest_keys::kBookmarkUI,\n manifest_keys::kUIOverride)));\n }\n }\n\n return true;\n}\n\nManifestPermission* UIOverridesHandler::CreatePermission() {\n return new ManifestPermissionImpl(false);\n}\n\nManifestPermission* UIOverridesHandler::CreateInitialRequiredPermission(\n const Extension* extension) {\n const UIOverrides* data = UIOverrides::Get(extension);\n if (data)\n return data->manifest_permission->Clone();\n return NULL;\n}\nconst std::vector UIOverridesHandler::Keys() const {\n return SingleKey(manifest_keys::kUIOverride);\n}\n\n} \/\/ namespace extensions\nEnforce \"override bookmarks UI\" manifest permissions for bookmark shortcut overrides\/\/ Copyright 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/common\/extensions\/manifest_handlers\/ui_overrides_handler.h\"\n\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/strings\/string_util.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"base\/values.h\"\n#include \"extensions\/common\/error_utils.h\"\n#include \"extensions\/common\/extension_messages.h\"\n#include \"extensions\/common\/feature_switch.h\"\n#include \"extensions\/common\/manifest_constants.h\"\n#include \"extensions\/common\/permissions\/manifest_permission.h\"\n#include \"extensions\/common\/permissions\/permissions_data.h\"\n#include \"extensions\/common\/permissions\/permissions_info.h\"\n#include \"grit\/generated_resources.h\"\n#include \"ipc\/ipc_message.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n\nusing extensions::api::manifest_types::ChromeUIOverrides;\n\nnamespace extensions {\n\n\/\/ The manifest permission implementation supports a permission for overriding\n\/\/ the bookmark UI.\nclass UIOverridesHandler::ManifestPermissionImpl : public ManifestPermission {\n public:\n explicit ManifestPermissionImpl(bool override_bookmarks_ui_permission)\n : override_bookmarks_ui_permission_(override_bookmarks_ui_permission) {}\n\n \/\/ extensions::ManifestPermission overrides.\n virtual std::string name() const OVERRIDE {\n return manifest_keys::kUIOverride;\n }\n\n virtual std::string id() const OVERRIDE {\n return name();\n }\n\n virtual bool HasMessages() const OVERRIDE {\n return override_bookmarks_ui_permission_;\n }\n\n virtual PermissionMessages GetMessages() const OVERRIDE {\n PermissionMessages result;\n if (override_bookmarks_ui_permission_) {\n result.push_back(PermissionMessage(\n PermissionMessage::kOverrideBookmarksUI,\n l10n_util::GetStringUTF16(\n IDS_EXTENSION_PROMPT_WARNING_OVERRIDE_BOOKMARKS_UI)));\n }\n return result;\n }\n\n virtual bool FromValue(const base::Value* value) OVERRIDE {\n return value && value->GetAsBoolean(&override_bookmarks_ui_permission_);\n }\n\n virtual scoped_ptr ToValue() const OVERRIDE {\n return scoped_ptr(\n new base::FundamentalValue(override_bookmarks_ui_permission_)).Pass();\n }\n\n virtual ManifestPermission* Clone() const OVERRIDE {\n return scoped_ptr(\n new ManifestPermissionImpl(\n override_bookmarks_ui_permission_)).release();\n }\n\n virtual ManifestPermission* Diff(const ManifestPermission* rhs) const\n OVERRIDE {\n const ManifestPermissionImpl* other =\n static_cast(rhs);\n\n return scoped_ptr(new ManifestPermissionImpl(\n override_bookmarks_ui_permission_ &&\n !other->override_bookmarks_ui_permission_)).release();\n }\n\n virtual ManifestPermission* Union(const ManifestPermission* rhs) const\n OVERRIDE {\n const ManifestPermissionImpl* other =\n static_cast(rhs);\n\n return scoped_ptr(new ManifestPermissionImpl(\n override_bookmarks_ui_permission_ ||\n other->override_bookmarks_ui_permission_)).release();\n }\n\n virtual ManifestPermission* Intersect(const ManifestPermission* rhs) const\n OVERRIDE {\n const ManifestPermissionImpl* other =\n static_cast(rhs);\n\n return scoped_ptr(new ManifestPermissionImpl(\n override_bookmarks_ui_permission_ &&\n other->override_bookmarks_ui_permission_)).release();\n }\n\n virtual bool Contains(const ManifestPermission* rhs) const OVERRIDE {\n const ManifestPermissionImpl* other =\n static_cast(rhs);\n\n return !other->override_bookmarks_ui_permission_ ||\n override_bookmarks_ui_permission_;\n }\n\n virtual bool Equal(const ManifestPermission* rhs) const OVERRIDE {\n const ManifestPermissionImpl* other =\n static_cast(rhs);\n\n return override_bookmarks_ui_permission_ ==\n other->override_bookmarks_ui_permission_;\n }\n\n virtual void Write(IPC::Message* m) const OVERRIDE {\n IPC::WriteParam(m, override_bookmarks_ui_permission_);\n }\n\n virtual bool Read(const IPC::Message* m, PickleIterator* iter) OVERRIDE {\n return IPC::ReadParam(m, iter, &override_bookmarks_ui_permission_);\n }\n\n virtual void Log(std::string* log) const OVERRIDE {\n IPC::LogParam(override_bookmarks_ui_permission_, log);\n }\n\n private:\n bool override_bookmarks_ui_permission_;\n};\n\nUIOverrides::UIOverrides() {}\n\nUIOverrides::~UIOverrides() {}\n\nconst UIOverrides* UIOverrides::Get(const Extension* extension) {\n return static_cast(\n extension->GetManifestData(manifest_keys::kUIOverride));\n}\n\nbool UIOverrides::RemovesBookmarkButton(const Extension* extension) {\n const UIOverrides* ui_overrides = Get(extension);\n return ui_overrides && ui_overrides->bookmarks_ui &&\n ui_overrides->bookmarks_ui->remove_button &&\n *ui_overrides->bookmarks_ui->remove_button;\n}\n\nbool UIOverrides::RemovesBookmarkShortcut(const Extension* extension) {\n const UIOverrides* ui_overrides = Get(extension);\n return ui_overrides && ui_overrides->bookmarks_ui &&\n ui_overrides->bookmarks_ui->remove_bookmark_shortcut &&\n *ui_overrides->bookmarks_ui->remove_bookmark_shortcut;\n}\n\nbool UIOverrides::RemovesBookmarkOpenPagesShortcut(const Extension* extension) {\n const UIOverrides* ui_overrides = Get(extension);\n return ui_overrides && ui_overrides->bookmarks_ui &&\n ui_overrides->bookmarks_ui->remove_bookmark_open_pages_shortcut &&\n *ui_overrides->bookmarks_ui->remove_bookmark_open_pages_shortcut;\n}\n\nUIOverridesHandler::UIOverridesHandler() {}\n\nUIOverridesHandler::~UIOverridesHandler() {}\n\nbool UIOverridesHandler::Parse(Extension* extension, base::string16* error) {\n const base::Value* dict = NULL;\n CHECK(extension->manifest()->Get(manifest_keys::kUIOverride, &dict));\n scoped_ptr overrides(\n ChromeUIOverrides::FromValue(*dict, error));\n if (!overrides)\n return false;\n\n scoped_ptr info(new UIOverrides);\n info->bookmarks_ui.swap(overrides->bookmarks_ui);\n if (!info->bookmarks_ui) {\n *error = ErrorUtils::FormatErrorMessageUTF16(\n manifest_errors::kInvalidEmptyDictionary,\n manifest_keys::kUIOverride);\n return false;\n }\n info->manifest_permission.reset(new ManifestPermissionImpl(\n info->bookmarks_ui.get() != NULL));\n extension->SetManifestData(manifest_keys::kUIOverride, info.release());\n return true;\n}\n\nbool UIOverridesHandler::Validate(const Extension* extension,\n std::string* error,\n std::vector* warnings) const {\n const UIOverrides* ui_overrides = UIOverrides::Get(extension);\n\n if (ui_overrides && ui_overrides->bookmarks_ui) {\n if (!FeatureSwitch::enable_override_bookmarks_ui()->IsEnabled()) {\n warnings->push_back(InstallWarning(\n ErrorUtils::FormatErrorMessage(\n manifest_errors::kUnrecognizedManifestProperty,\n manifest_keys::kBookmarkUI,\n manifest_keys::kUIOverride)));\n }\n }\n\n return true;\n}\n\nManifestPermission* UIOverridesHandler::CreatePermission() {\n return new ManifestPermissionImpl(false);\n}\n\nManifestPermission* UIOverridesHandler::CreateInitialRequiredPermission(\n const Extension* extension) {\n const UIOverrides* data = UIOverrides::Get(extension);\n if (data)\n return data->manifest_permission->Clone();\n return NULL;\n}\nconst std::vector UIOverridesHandler::Keys() const {\n return SingleKey(manifest_keys::kUIOverride);\n}\n\n} \/\/ namespace extensions\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2018 ASMlover. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list ofconditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in\n\/\/ the documentation and\/or other materialsprovided with the\n\/\/ distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#include \"nyx_filter_manager.h\"\n\nnamespace nyx { namespace filter {\n\nvoid filter_manager::delete_filter_randomly(void) {\n}\n\nfilter_ptr filter_manager::from_object(PyObject* v) {\n filter_ptr filter;\n return filter;\n}\n\nfilter_ptr filter_manager::from_tuple(PyObject* v) {\n filter_ptr filter;\n return filter;\n}\n\nfilter_ptr filter_manager::from_list(PyObject* v) {\n filter_ptr filter;\n return filter;\n}\n\nint filter_manager::add_filter(const py::object& args) {\n return 0;\n}\n\nint filter_manager::add_str_filter(\n const std::string& s, const py::object& args) {\n return 0;\n}\n\nvoid filter_manager::del_filter(int filter) {\n filters_.erase(filter);\n auto it = int_filters_.find(filter);\n if (it != int_filters_.end()) {\n str_filters_.erase(it->second);\n int_filters_.erase(it);\n }\n}\n\nfilter_ptr filter_manager::get_filter(int index) const {\n filter_ptr filter;\n auto it = filters_.find(index);\n if (it != filters_.end())\n filter = it->second;\n return filter;\n}\n\nint filter_manager::get_filter_index(const std::string& s) const {\n auto it = str_filters_.find(s);\n if (it != str_filters_.end())\n return it->second;\n return -1;\n}\n\nvoid filter_manager::print_filter(int index) {\n auto it = filters_.find(index);\n if (it != filters_.end())\n it->second->print();\n}\n\n}}\n:construction: chore(filter): updated the implementation of filter manager\/\/ Copyright (c) 2018 ASMlover. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list ofconditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in\n\/\/ the documentation and\/or other materialsprovided with the\n\/\/ distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#include \n#include \n#include \"nyx_int_filter.h\"\n#include \"nyx_float_filter.h\"\n#include \"nyx_str_filter.h\"\n#include \"nyx_filter_manager.h\"\n\nnamespace nyx { namespace filter {\n\nstatic const char* kUsageError = \"Usage Error\";\n\nvoid filter_manager::delete_filter_randomly(void) {\n if (str_filters_.empty())\n return;\n\n std::srand(std::time(0));\n int bucket;\n int bucket_size;\n do {\n bucket = std::rand() % str_filters_.bucket_count();\n } while ((bucket_size = str_filters_.bucket_size(bucket)) == 0);\n auto it = str_filters_.begin(bucket);\n std::advance(it, std::rand() % bucket_size);\n del_filter(it->second);\n}\n\nfilter_ptr filter_manager::from_object(PyObject* v) {\n filter_ptr filter;\n if (!PyTuple_Check(v) || (Py_SIZE(v) != 3)) {\n PyErr_SetString(PyExc_TypeError, kUsageError);\n return filter;\n }\n auto* type = PyTuple_GET_ITEM(v, 0);\n auto* key = PyTuple_GET_ITEM(v, 1);\n auto* val = PyTuple_GET_ITEM(v, 2);\n if (!PyInt_Check(type) || !PyString_Check(key)) {\n PyErr_SetString(PyExc_TypeError, kUsageError);\n return filter;\n }\n\n auto raw_type = PyInt_AsSsize_t(type);\n if (raw_type == -1)\n return filter;\n const char* raw_key = PyString_AsString(key);\n if (raw_key == nullptr)\n return filter;\n\n if (PyInt_Check(val)) {\n auto raw_val = PyInt_AsSsize_t(val);\n if (raw_val == -1 && PyErr_Occurred())\n return filter;\n filter = std::make_shared(\n static_cast(raw_type), raw_key, raw_val);\n return filter;\n }\n else if (PyFloat_Check(val)) {\n auto raw_val = PyFloat_AsDouble(val);\n if (raw_val == -1.f && PyErr_Occurred())\n return filter;\n filter = std::make_shared(\n static_cast(raw_type), raw_key, raw_val);\n return filter;\n }\n else if (PyString_Check(val)) {\n auto raw_val = PyString_AsString(val);\n if (raw_val == nullptr)\n return filter;\n filter = std::make_shared(\n static_cast(raw_type), raw_key, raw_val);\n return filter;\n }\n else {\n PyErr_SetString(PyExc_TypeError, kUsageError);\n return filter;\n }\n\n return filter;\n}\n\nfilter_ptr filter_manager::from_tuple(PyObject* v) {\n filter_ptr filter;\n return filter;\n}\n\nfilter_ptr filter_manager::from_list(PyObject* v) {\n filter_ptr filter;\n return filter;\n}\n\nint filter_manager::add_filter(const py::object& args) {\n return 0;\n}\n\nint filter_manager::add_str_filter(\n const std::string& s, const py::object& args) {\n return 0;\n}\n\nvoid filter_manager::del_filter(int filter) {\n filters_.erase(filter);\n auto it = int_filters_.find(filter);\n if (it != int_filters_.end()) {\n str_filters_.erase(it->second);\n int_filters_.erase(it);\n }\n}\n\nfilter_ptr filter_manager::get_filter(int index) const {\n filter_ptr filter;\n auto it = filters_.find(index);\n if (it != filters_.end())\n filter = it->second;\n return filter;\n}\n\nint filter_manager::get_filter_index(const std::string& s) const {\n auto it = str_filters_.find(s);\n if (it != str_filters_.end())\n return it->second;\n return -1;\n}\n\nvoid filter_manager::print_filter(int index) {\n auto it = filters_.find(index);\n if (it != filters_.end())\n it->second->print();\n}\n\n}}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: autofmt.hxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: rt $ $Date: 2004-08-23 09:33:03 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SC_AUTOFMT_HXX\n#define SC_AUTOFMT_HXX\n\n#ifndef _VIRDEV_HXX \/\/autogen\n#include \n#endif\n#ifndef SV_FIXED_HXX\n#include \n#endif\n#ifndef SV_LSTBOX_HXX\n#include \n#endif\n#ifndef SV_BUTTON_HXX\n#include \n#endif\n#ifndef SV_MOREBTN_HXX\n#include \n#endif\n#ifndef _DIALOG_HXX \/\/autogen\n#include \n#endif\n#ifndef _SVTOOLS_SCRIPTEDTEXT_HXX\n#include \n#endif\n#ifndef SVX_FRAMELINKARRAY_HXX\n#include \n#endif\n\n#ifndef INCLUDED_SCDLLAPI_H\n#include \"scdllapi.h\"\n#endif\n\n\/\/------------------------------------------------------------------------\n\nclass ScAutoFormat;\nclass ScAutoFormatData;\nclass SvxBoxItem;\nclass SvxLineItem;\nclass AutoFmtPreview; \/\/ s.u.\nclass SvNumberFormatter;\nclass ScDocument;\n\n\/\/------------------------------------------------------------------------\n\nenum AutoFmtLine { TOP_LINE, BOTTOM_LINE, LEFT_LINE, RIGHT_LINE };\n\n\/\/========================================================================\n\n\/\/CHINA001 class ScAutoFormatDlg : public ModalDialog\n\/\/CHINA001 {\n\/\/CHINA001 public:\n\/\/CHINA001 ScAutoFormatDlg( Window* pParent,\n\/\/CHINA001 ScAutoFormat* pAutoFormat,\n\/\/CHINA001 const ScAutoFormatData* pSelFormatData,\n\/\/CHINA001 ScDocument* pDoc );\n\/\/CHINA001 ~ScAutoFormatDlg();\n\/\/CHINA001\n\/\/CHINA001 USHORT GetIndex() const { return nIndex; }\n\/\/CHINA001 String GetCurrFormatName();\n\/\/CHINA001\n\/\/CHINA001 private:\n\/\/CHINA001 FixedLine aFlFormat;\n\/\/CHINA001 ListBox aLbFormat;\n\/\/CHINA001 AutoFmtPreview* pWndPreview;\n\/\/CHINA001 OKButton aBtnOk;\n\/\/CHINA001 CancelButton aBtnCancel;\n\/\/CHINA001 HelpButton aBtnHelp;\n\/\/CHINA001 PushButton aBtnAdd;\n\/\/CHINA001 PushButton aBtnRemove;\n\/\/CHINA001 MoreButton aBtnMore;\n\/\/CHINA001 FixedLine aFlFormatting;\n\/\/CHINA001 CheckBox aBtnNumFormat;\n\/\/CHINA001 CheckBox aBtnBorder;\n\/\/CHINA001 CheckBox aBtnFont;\n\/\/CHINA001 CheckBox aBtnPattern;\n\/\/CHINA001 CheckBox aBtnAlignment;\n\/\/CHINA001 CheckBox aBtnAdjust;\n\/\/CHINA001 PushButton aBtnRename;\n\/\/CHINA001 String aStrTitle;\n\/\/CHINA001 String aStrLabel;\n\/\/CHINA001 String aStrClose;\n\/\/CHINA001 String aStrDelTitle;\n\/\/CHINA001 String aStrDelMsg;\n\/\/CHINA001 String aStrRename;\n\/\/CHINA001\n\/\/CHINA001 \/\/------------------------\n\/\/CHINA001 ScAutoFormat* pFormat;\n\/\/CHINA001 const ScAutoFormatData* pSelFmtData;\n\/\/CHINA001 USHORT nIndex;\n\/\/CHINA001 BOOL bCoreDataChanged;\n\/\/CHINA001 BOOL bFmtInserted;\n\/\/CHINA001\n\/\/CHINA001 void Init ();\n\/\/CHINA001 void UpdateChecks ();\n\/\/CHINA001 \/\/------------------------\n\/\/CHINA001 DECL_LINK( CheckHdl, Button * );\n\/\/CHINA001 DECL_LINK( AddHdl, void * );\n\/\/CHINA001 DECL_LINK( RemoveHdl, void * );\n\/\/CHINA001 DECL_LINK( SelFmtHdl, void * );\n\/\/CHINA001 DECL_LINK( CloseHdl, PushButton * );\n\/\/CHINA001 DECL_LINK( DblClkHdl, void * );\n\/\/CHINA001 DECL_LINK( RenameHdl, void *);\n\/\/CHINA001\n\/\/CHINA001 };\n\/\/CHINA001\n\/\/========================================================================\n\nclass SC_DLLPUBLIC AutoFmtPreview : public Window\n{\npublic:\n AutoFmtPreview( Window* pParent, const ResId& rRes, ScDocument* pDoc );\n ~AutoFmtPreview();\n\n void NotifyChange( ScAutoFormatData* pNewData );\n\nprotected:\n virtual void Paint( const Rectangle& rRect );\n\nprivate:\n ScAutoFormatData* pCurData;\n VirtualDevice aVD;\n SvtScriptedTextHelper aScriptedText;\n ::com::sun::star::uno::Reference< ::com::sun::star::i18n::XBreakIterator > xBreakIter;\n BOOL bFitWidth;\n svx::frame::Array maArray; \/\/\/ Implementation to draw the frame borders.\n Size aPrvSize;\n long mnLabelColWidth;\n long mnDataColWidth1;\n long mnDataColWidth2;\n long mnRowHeight;\n const String aStrJan;\n const String aStrFeb;\n const String aStrMar;\n const String aStrNorth;\n const String aStrMid;\n const String aStrSouth;\n const String aStrSum;\n SvNumberFormatter* pNumFmt;\n \/\/-------------------------------------------\n SC_DLLPRIVATE void Init ();\n SC_DLLPRIVATE void DoPaint ( const Rectangle& rRect );\n SC_DLLPRIVATE void CalcCellArray ( BOOL bFitWidth );\n SC_DLLPRIVATE void CalcLineMap ();\n SC_DLLPRIVATE void PaintCells ();\n\n\/* Usage of type size_t instead of SCCOL\/SCROW is correct here - used in\n conjunction with class svx::frame::Array (svx\/framelinkarray.hxx), which\n expects size_t coordinates. *\/\n\n SC_DLLPRIVATE USHORT GetFormatIndex( size_t nCol, size_t nRow ) const;\n SC_DLLPRIVATE const SvxBoxItem& GetBoxItem( size_t nCol, size_t nRow ) const;\n SC_DLLPRIVATE const SvxLineItem& GetDiagItem( size_t nCol, size_t nRow, bool bTLBR ) const;\n\n SC_DLLPRIVATE void DrawString( size_t nCol, size_t nRow );\n SC_DLLPRIVATE void DrawStrings();\n SC_DLLPRIVATE void DrawBackground();\n\n SC_DLLPRIVATE void MakeFonts ( USHORT nIndex,\n Font& rFont,\n Font& rCJKFont,\n Font& rCTLFont );\n\n SC_DLLPRIVATE String MakeNumberString( String cellString, BOOL bAddDec );\n SC_DLLPRIVATE void DrawFrameLine ( const SvxBorderLine& rLineD,\n Point from,\n Point to,\n BOOL bHorizontal,\n const SvxBorderLine& rLineLT,\n const SvxBorderLine& rLineL,\n const SvxBorderLine& rLineLB,\n const SvxBorderLine& rLineRT,\n const SvxBorderLine& rLineR,\n const SvxBorderLine& rLineRB );\n SC_DLLPRIVATE void CheckPriority ( USHORT nCurLine,\n AutoFmtLine eLine,\n SvxBorderLine& rLine );\n SC_DLLPRIVATE void GetLines ( USHORT nIndex, AutoFmtLine eLine,\n SvxBorderLine& rLineD,\n SvxBorderLine& rLineLT,\n SvxBorderLine& rLineL,\n SvxBorderLine& rLineLB,\n SvxBorderLine& rLineRT,\n SvxBorderLine& rLineR,\n SvxBorderLine& rLineRB );\n};\n\n#endif \/\/ SC_AUTOFMT_HXX\n\n\nINTEGRATION: CWS ooo19126 (1.7.346); FILE MERGED 2005\/09\/05 15:05:07 rt 1.7.346.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: autofmt.hxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 21:13:27 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef SC_AUTOFMT_HXX\n#define SC_AUTOFMT_HXX\n\n#ifndef _VIRDEV_HXX \/\/autogen\n#include \n#endif\n#ifndef SV_FIXED_HXX\n#include \n#endif\n#ifndef SV_LSTBOX_HXX\n#include \n#endif\n#ifndef SV_BUTTON_HXX\n#include \n#endif\n#ifndef SV_MOREBTN_HXX\n#include \n#endif\n#ifndef _DIALOG_HXX \/\/autogen\n#include \n#endif\n#ifndef _SVTOOLS_SCRIPTEDTEXT_HXX\n#include \n#endif\n#ifndef SVX_FRAMELINKARRAY_HXX\n#include \n#endif\n\n#ifndef INCLUDED_SCDLLAPI_H\n#include \"scdllapi.h\"\n#endif\n\n\/\/------------------------------------------------------------------------\n\nclass ScAutoFormat;\nclass ScAutoFormatData;\nclass SvxBoxItem;\nclass SvxLineItem;\nclass AutoFmtPreview; \/\/ s.u.\nclass SvNumberFormatter;\nclass ScDocument;\n\n\/\/------------------------------------------------------------------------\n\nenum AutoFmtLine { TOP_LINE, BOTTOM_LINE, LEFT_LINE, RIGHT_LINE };\n\n\/\/========================================================================\n\n\/\/CHINA001 class ScAutoFormatDlg : public ModalDialog\n\/\/CHINA001 {\n\/\/CHINA001 public:\n\/\/CHINA001 ScAutoFormatDlg( Window* pParent,\n\/\/CHINA001 ScAutoFormat* pAutoFormat,\n\/\/CHINA001 const ScAutoFormatData* pSelFormatData,\n\/\/CHINA001 ScDocument* pDoc );\n\/\/CHINA001 ~ScAutoFormatDlg();\n\/\/CHINA001\n\/\/CHINA001 USHORT GetIndex() const { return nIndex; }\n\/\/CHINA001 String GetCurrFormatName();\n\/\/CHINA001\n\/\/CHINA001 private:\n\/\/CHINA001 FixedLine aFlFormat;\n\/\/CHINA001 ListBox aLbFormat;\n\/\/CHINA001 AutoFmtPreview* pWndPreview;\n\/\/CHINA001 OKButton aBtnOk;\n\/\/CHINA001 CancelButton aBtnCancel;\n\/\/CHINA001 HelpButton aBtnHelp;\n\/\/CHINA001 PushButton aBtnAdd;\n\/\/CHINA001 PushButton aBtnRemove;\n\/\/CHINA001 MoreButton aBtnMore;\n\/\/CHINA001 FixedLine aFlFormatting;\n\/\/CHINA001 CheckBox aBtnNumFormat;\n\/\/CHINA001 CheckBox aBtnBorder;\n\/\/CHINA001 CheckBox aBtnFont;\n\/\/CHINA001 CheckBox aBtnPattern;\n\/\/CHINA001 CheckBox aBtnAlignment;\n\/\/CHINA001 CheckBox aBtnAdjust;\n\/\/CHINA001 PushButton aBtnRename;\n\/\/CHINA001 String aStrTitle;\n\/\/CHINA001 String aStrLabel;\n\/\/CHINA001 String aStrClose;\n\/\/CHINA001 String aStrDelTitle;\n\/\/CHINA001 String aStrDelMsg;\n\/\/CHINA001 String aStrRename;\n\/\/CHINA001\n\/\/CHINA001 \/\/------------------------\n\/\/CHINA001 ScAutoFormat* pFormat;\n\/\/CHINA001 const ScAutoFormatData* pSelFmtData;\n\/\/CHINA001 USHORT nIndex;\n\/\/CHINA001 BOOL bCoreDataChanged;\n\/\/CHINA001 BOOL bFmtInserted;\n\/\/CHINA001\n\/\/CHINA001 void Init ();\n\/\/CHINA001 void UpdateChecks ();\n\/\/CHINA001 \/\/------------------------\n\/\/CHINA001 DECL_LINK( CheckHdl, Button * );\n\/\/CHINA001 DECL_LINK( AddHdl, void * );\n\/\/CHINA001 DECL_LINK( RemoveHdl, void * );\n\/\/CHINA001 DECL_LINK( SelFmtHdl, void * );\n\/\/CHINA001 DECL_LINK( CloseHdl, PushButton * );\n\/\/CHINA001 DECL_LINK( DblClkHdl, void * );\n\/\/CHINA001 DECL_LINK( RenameHdl, void *);\n\/\/CHINA001\n\/\/CHINA001 };\n\/\/CHINA001\n\/\/========================================================================\n\nclass SC_DLLPUBLIC AutoFmtPreview : public Window\n{\npublic:\n AutoFmtPreview( Window* pParent, const ResId& rRes, ScDocument* pDoc );\n ~AutoFmtPreview();\n\n void NotifyChange( ScAutoFormatData* pNewData );\n\nprotected:\n virtual void Paint( const Rectangle& rRect );\n\nprivate:\n ScAutoFormatData* pCurData;\n VirtualDevice aVD;\n SvtScriptedTextHelper aScriptedText;\n ::com::sun::star::uno::Reference< ::com::sun::star::i18n::XBreakIterator > xBreakIter;\n BOOL bFitWidth;\n svx::frame::Array maArray; \/\/\/ Implementation to draw the frame borders.\n Size aPrvSize;\n long mnLabelColWidth;\n long mnDataColWidth1;\n long mnDataColWidth2;\n long mnRowHeight;\n const String aStrJan;\n const String aStrFeb;\n const String aStrMar;\n const String aStrNorth;\n const String aStrMid;\n const String aStrSouth;\n const String aStrSum;\n SvNumberFormatter* pNumFmt;\n \/\/-------------------------------------------\n SC_DLLPRIVATE void Init ();\n SC_DLLPRIVATE void DoPaint ( const Rectangle& rRect );\n SC_DLLPRIVATE void CalcCellArray ( BOOL bFitWidth );\n SC_DLLPRIVATE void CalcLineMap ();\n SC_DLLPRIVATE void PaintCells ();\n\n\/* Usage of type size_t instead of SCCOL\/SCROW is correct here - used in\n conjunction with class svx::frame::Array (svx\/framelinkarray.hxx), which\n expects size_t coordinates. *\/\n\n SC_DLLPRIVATE USHORT GetFormatIndex( size_t nCol, size_t nRow ) const;\n SC_DLLPRIVATE const SvxBoxItem& GetBoxItem( size_t nCol, size_t nRow ) const;\n SC_DLLPRIVATE const SvxLineItem& GetDiagItem( size_t nCol, size_t nRow, bool bTLBR ) const;\n\n SC_DLLPRIVATE void DrawString( size_t nCol, size_t nRow );\n SC_DLLPRIVATE void DrawStrings();\n SC_DLLPRIVATE void DrawBackground();\n\n SC_DLLPRIVATE void MakeFonts ( USHORT nIndex,\n Font& rFont,\n Font& rCJKFont,\n Font& rCTLFont );\n\n SC_DLLPRIVATE String MakeNumberString( String cellString, BOOL bAddDec );\n SC_DLLPRIVATE void DrawFrameLine ( const SvxBorderLine& rLineD,\n Point from,\n Point to,\n BOOL bHorizontal,\n const SvxBorderLine& rLineLT,\n const SvxBorderLine& rLineL,\n const SvxBorderLine& rLineLB,\n const SvxBorderLine& rLineRT,\n const SvxBorderLine& rLineR,\n const SvxBorderLine& rLineRB );\n SC_DLLPRIVATE void CheckPriority ( USHORT nCurLine,\n AutoFmtLine eLine,\n SvxBorderLine& rLine );\n SC_DLLPRIVATE void GetLines ( USHORT nIndex, AutoFmtLine eLine,\n SvxBorderLine& rLineD,\n SvxBorderLine& rLineLT,\n SvxBorderLine& rLineL,\n SvxBorderLine& rLineLB,\n SvxBorderLine& rLineRT,\n SvxBorderLine& rLineR,\n SvxBorderLine& rLineRB );\n};\n\n#endif \/\/ SC_AUTOFMT_HXX\n\n\n<|endoftext|>"} {"text":"\/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\n#include \n#include \n#include \"paddle\/fluid\/inference\/tests\/api\/tester_helper.h\"\n\nnamespace paddle {\nnamespace inference {\nnamespace analysis {\n\nvoid SetConfig(AnalysisConfig *cfg) {\n cfg->param_file = FLAGS_infer_model + \"\/params\";\n cfg->prog_file = FLAGS_infer_model + \"\/model\";\n cfg->use_gpu = false;\n cfg->device = 0;\n cfg->enable_ir_optim = true;\n cfg->specify_input_name = true;\n#ifdef PADDLE_WITH_MKLDNN\n cfg->_use_mkldnn = true;\n#endif\n}\n\nvoid SetInput(std::vector> *inputs) {\n PADDLE_ENFORCE_EQ(FLAGS_test_all_data, 0, \"Only have single batch of data.\");\n\n PaddleTensor input;\n \/\/ channel=3, height\/width=318\n std::vector shape({FLAGS_batch_size, 3, 318, 318});\n input.shape = shape;\n input.dtype = PaddleDType::FLOAT32;\n\n \/\/ fill input data, for profile easily, do not use random data here.\n size_t size = FLAGS_batch_size * 3 * 318 * 318;\n input.data.Resize(size * sizeof(float));\n float *input_data = static_cast(input.data.data());\n for (size_t i = 0; i < size; i++) {\n *(input_data + i) = static_cast(i) \/ size;\n }\n\n std::vector input_slots;\n input_slots.assign({input});\n (*inputs).emplace_back(input_slots);\n}\n\n\/\/ Easy for profiling independently.\nvoid profile(bool use_mkldnn = false) {\n AnalysisConfig cfg;\n SetConfig(&cfg);\n cfg._use_mkldnn = use_mkldnn;\n std::vector outputs;\n\n std::vector> input_slots_all;\n SetInput(&input_slots_all);\n TestPrediction(cfg, input_slots_all, &outputs, FLAGS_num_threads);\n\n if (FLAGS_num_threads == 1 && !FLAGS_test_all_data) {\n PADDLE_ENFORCE_EQ(outputs.size(), 1UL);\n size_t size = GetSize(outputs[0]);\n \/\/ output is a 512-dimension feature\n EXPECT_EQ(size, 512 * FLAGS_batch_size);\n }\n}\n\nTEST(Analyzer_resnet50, profile) { profile(); }\n#ifndef PADDLE_WITH_MKLDNN\nTEST(Analyzer_resnet50, profile_mkldnn) { profile(true \/* use_mkldnn *\/); }\n#endif\n\n\/\/ Check the fuse status\nTEST(Analyzer_resnet50, fuse_statis) {\n AnalysisConfig cfg;\n SetConfig(&cfg);\n int num_ops;\n auto predictor = CreatePaddlePredictor(cfg);\n auto fuse_statis = GetFuseStatis(\n static_cast(predictor.get()), &num_ops);\n ASSERT_TRUE(fuse_statis.count(\"fc_fuse\"));\n EXPECT_EQ(fuse_statis.at(\"fc_fuse\"), 1);\n}\n\n\/\/ Compare result of NativeConfig and AnalysisConfig\nvoid compare(bool use_mkldnn = false) {\n AnalysisConfig cfg;\n SetConfig(&cfg);\n cfg._use_mkldnn = use_mkldnn;\n\n std::vector> input_slots_all;\n SetInput(&input_slots_all);\n CompareNativeAndAnalysis(cfg, input_slots_all);\n}\n\nTEST(Analyzer_resnet50, compare) { compare(); }\n#ifdef PADDLE_WITH_MKLDNN\nTEST(Analyzer_resnet50, compare_mkldnn) { compare(true \/* use_mkldnn *\/); }\n#endif\n\n} \/\/ namespace analysis\n} \/\/ namespace inference\n} \/\/ namespace paddle\nRemove use mkldnn from config in resnet50 test\/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License. *\/\n\n#include \n#include \n#include \"paddle\/fluid\/inference\/tests\/api\/tester_helper.h\"\n\nnamespace paddle {\nnamespace inference {\nnamespace analysis {\n\nvoid SetConfig(AnalysisConfig *cfg) {\n cfg->param_file = FLAGS_infer_model + \"\/params\";\n cfg->prog_file = FLAGS_infer_model + \"\/model\";\n cfg->use_gpu = false;\n cfg->device = 0;\n cfg->enable_ir_optim = true;\n cfg->specify_input_name = true;\n}\n\nvoid SetInput(std::vector> *inputs) {\n PADDLE_ENFORCE_EQ(FLAGS_test_all_data, 0, \"Only have single batch of data.\");\n\n PaddleTensor input;\n \/\/ channel=3, height\/width=318\n std::vector shape({FLAGS_batch_size, 3, 318, 318});\n input.shape = shape;\n input.dtype = PaddleDType::FLOAT32;\n\n \/\/ fill input data, for profile easily, do not use random data here.\n size_t size = FLAGS_batch_size * 3 * 318 * 318;\n input.data.Resize(size * sizeof(float));\n float *input_data = static_cast(input.data.data());\n for (size_t i = 0; i < size; i++) {\n *(input_data + i) = static_cast(i) \/ size;\n }\n\n std::vector input_slots;\n input_slots.assign({input});\n (*inputs).emplace_back(input_slots);\n}\n\n\/\/ Easy for profiling independently.\nvoid profile(bool use_mkldnn = false) {\n AnalysisConfig cfg;\n SetConfig(&cfg);\n cfg._use_mkldnn = use_mkldnn;\n std::vector outputs;\n\n std::vector> input_slots_all;\n SetInput(&input_slots_all);\n TestPrediction(cfg, input_slots_all, &outputs, FLAGS_num_threads);\n\n if (FLAGS_num_threads == 1 && !FLAGS_test_all_data) {\n PADDLE_ENFORCE_EQ(outputs.size(), 1UL);\n size_t size = GetSize(outputs[0]);\n \/\/ output is a 512-dimension feature\n EXPECT_EQ(size, 512 * FLAGS_batch_size);\n }\n}\n\nTEST(Analyzer_resnet50, profile) { profile(); }\n#ifndef PADDLE_WITH_MKLDNN\nTEST(Analyzer_resnet50, profile_mkldnn) { profile(true \/* use_mkldnn *\/); }\n#endif\n\n\/\/ Check the fuse status\nTEST(Analyzer_resnet50, fuse_statis) {\n AnalysisConfig cfg;\n SetConfig(&cfg);\n int num_ops;\n auto predictor = CreatePaddlePredictor(cfg);\n auto fuse_statis = GetFuseStatis(\n static_cast(predictor.get()), &num_ops);\n ASSERT_TRUE(fuse_statis.count(\"fc_fuse\"));\n EXPECT_EQ(fuse_statis.at(\"fc_fuse\"), 1);\n}\n\n\/\/ Compare result of NativeConfig and AnalysisConfig\nvoid compare(bool use_mkldnn = false) {\n AnalysisConfig cfg;\n SetConfig(&cfg);\n cfg._use_mkldnn = use_mkldnn;\n\n std::vector> input_slots_all;\n SetInput(&input_slots_all);\n CompareNativeAndAnalysis(cfg, input_slots_all);\n}\n\nTEST(Analyzer_resnet50, compare) { compare(); }\n#ifdef PADDLE_WITH_MKLDNN\nTEST(Analyzer_resnet50, compare_mkldnn) { compare(true \/* use_mkldnn *\/); }\n#endif\n\n} \/\/ namespace analysis\n} \/\/ namespace inference\n} \/\/ namespace paddle\n<|endoftext|>"} {"text":"\/\/ Copyright 2019 The Pigweed Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n\/\/ use this file except in compliance with the License. You may obtain a copy of\n\/\/ the License at\n\/\/\n\/\/ https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n\/\/ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n\/\/ License for the specific language governing permissions and limitations under\n\/\/ the License.\n\n#include \"pw_string\/string_builder.h\"\n\n#include \n\n#include \"pw_string\/format.h\"\n#include \"pw_string\/util.h\"\n\nnamespace pw {\n\nvoid StringBuilder::clear() {\n *size_ = 0;\n NullTerminate();\n status_ = StatusCode(OkStatus());\n last_status_ = StatusCode(OkStatus());\n}\n\nStringBuilder& StringBuilder::append(size_t count, char ch) {\n char* const append_destination = buffer_.data() + size();\n std::fill_n(append_destination, ResizeAndTerminate(count), ch);\n return *this;\n}\n\nStringBuilder& StringBuilder::append(const char* str, size_t count) {\n char* const append_destination = buffer_.data() + size();\n std::copy_n(str, ResizeAndTerminate(count), append_destination);\n return *this;\n}\n\nStringBuilder& StringBuilder::append(const char* str) {\n \/\/ Use buffer_.size() - size() as the maximum length so that strings too long\n \/\/ to fit in the buffer will request one character too many, which sets the\n \/\/ status to RESOURCE_EXHAUSTED.\n return append(string::ClampedCString(str, buffer_.size() - size()));\n}\n\nStringBuilder& StringBuilder::append(const std::string_view& str) {\n return append(str.data(), str.size());\n}\n\nStringBuilder& StringBuilder::append(const std::string_view& str,\n size_t pos,\n size_t count) {\n if (pos > str.size()) {\n SetErrorStatus(Status::OutOfRange());\n return *this;\n }\n\n return append(str.data() + pos, std::min(str.size() - pos, count));\n}\n\nsize_t StringBuilder::ResizeAndTerminate(size_t chars_to_append) {\n const size_t copied = std::min(chars_to_append, max_size() - size());\n *size_ += copied;\n NullTerminate();\n\n if (buffer_.empty() || chars_to_append != copied) {\n SetErrorStatus(Status::ResourceExhausted());\n } else {\n last_status_ = StatusCode(OkStatus());\n }\n return copied;\n}\n\nvoid StringBuilder::resize(size_t new_size) {\n if (new_size <= size()) {\n *size_ = new_size;\n NullTerminate();\n last_status_ = StatusCode(OkStatus());\n } else {\n SetErrorStatus(Status::OutOfRange());\n }\n}\n\nStringBuilder& StringBuilder::Format(const char* format, ...) {\n va_list args;\n va_start(args, format);\n FormatVaList(format, args);\n va_end(args);\n\n return *this;\n}\n\nStringBuilder& StringBuilder::FormatVaList(const char* format, va_list args) {\n HandleStatusWithSize(\n string::FormatVaList(buffer_.subspan(size()), format, args));\n return *this;\n}\n\nvoid StringBuilder::WriteBytes(span data) {\n if (size() + data.size() * 2 > max_size()) {\n SetErrorStatus(Status::ResourceExhausted());\n } else {\n for (std::byte val : data) {\n *this << val;\n }\n }\n}\n\nvoid StringBuilder::CopySizeAndStatus(const StringBuilder& other) {\n *size_ = other.size();\n status_ = other.status_;\n last_status_ = other.last_status_;\n}\n\nvoid StringBuilder::HandleStatusWithSize(StatusWithSize written) {\n const Status status = written.status();\n last_status_ = StatusCode(status);\n if (!status.ok()) {\n status_ = StatusCode(status);\n }\n\n *size_ += written.size();\n}\n\nvoid StringBuilder::SetErrorStatus(Status status) {\n last_status_ = StatusCode(status);\n status_ = StatusCode(status);\n}\n\n} \/\/ namespace pw\npw_string: Make narrowing conversions explicit\/\/ Copyright 2019 The Pigweed Authors\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n\/\/ use this file except in compliance with the License. You may obtain a copy of\n\/\/ the License at\n\/\/\n\/\/ https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n\/\/ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n\/\/ License for the specific language governing permissions and limitations under\n\/\/ the License.\n\n#include \"pw_string\/string_builder.h\"\n\n#include \n\n#include \"pw_string\/format.h\"\n#include \"pw_string\/util.h\"\n\nnamespace pw {\n\nvoid StringBuilder::clear() {\n *size_ = 0;\n NullTerminate();\n status_ = StatusCode(OkStatus());\n last_status_ = StatusCode(OkStatus());\n}\n\nStringBuilder& StringBuilder::append(size_t count, char ch) {\n char* const append_destination = buffer_.data() + size();\n std::fill_n(append_destination, ResizeAndTerminate(count), ch);\n return *this;\n}\n\nStringBuilder& StringBuilder::append(const char* str, size_t count) {\n char* const append_destination = buffer_.data() + size();\n std::copy_n(str, ResizeAndTerminate(count), append_destination);\n return *this;\n}\n\nStringBuilder& StringBuilder::append(const char* str) {\n \/\/ Use buffer_.size() - size() as the maximum length so that strings too long\n \/\/ to fit in the buffer will request one character too many, which sets the\n \/\/ status to RESOURCE_EXHAUSTED.\n return append(string::ClampedCString(str, buffer_.size() - size()));\n}\n\nStringBuilder& StringBuilder::append(const std::string_view& str) {\n return append(str.data(), str.size());\n}\n\nStringBuilder& StringBuilder::append(const std::string_view& str,\n size_t pos,\n size_t count) {\n if (pos > str.size()) {\n SetErrorStatus(Status::OutOfRange());\n return *this;\n }\n\n return append(str.data() + pos, std::min(str.size() - pos, count));\n}\n\nsize_t StringBuilder::ResizeAndTerminate(size_t chars_to_append) {\n const size_t copied = std::min(chars_to_append, max_size() - size());\n *size_ += copied;\n NullTerminate();\n\n if (buffer_.empty() || chars_to_append != copied) {\n SetErrorStatus(Status::ResourceExhausted());\n } else {\n last_status_ = StatusCode(OkStatus());\n }\n return copied;\n}\n\nvoid StringBuilder::resize(size_t new_size) {\n if (new_size <= size()) {\n *size_ = static_cast::size_type>(new_size);\n NullTerminate();\n last_status_ = StatusCode(OkStatus());\n } else {\n SetErrorStatus(Status::OutOfRange());\n }\n}\n\nStringBuilder& StringBuilder::Format(const char* format, ...) {\n va_list args;\n va_start(args, format);\n FormatVaList(format, args);\n va_end(args);\n\n return *this;\n}\n\nStringBuilder& StringBuilder::FormatVaList(const char* format, va_list args) {\n HandleStatusWithSize(\n string::FormatVaList(buffer_.subspan(size()), format, args));\n return *this;\n}\n\nvoid StringBuilder::WriteBytes(span data) {\n if (size() + data.size() * 2 > max_size()) {\n SetErrorStatus(Status::ResourceExhausted());\n } else {\n for (std::byte val : data) {\n *this << val;\n }\n }\n}\n\nvoid StringBuilder::CopySizeAndStatus(const StringBuilder& other) {\n *size_ = static_cast::size_type>(other.size());\n status_ = other.status_;\n last_status_ = other.last_status_;\n}\n\nvoid StringBuilder::HandleStatusWithSize(StatusWithSize written) {\n const Status status = written.status();\n last_status_ = StatusCode(status);\n if (!status.ok()) {\n status_ = StatusCode(status);\n }\n\n *size_ += written.size();\n}\n\nvoid StringBuilder::SetErrorStatus(Status status) {\n last_status_ = StatusCode(status);\n status_ = StatusCode(status);\n}\n\n} \/\/ namespace pw\n<|endoftext|>"} {"text":"\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Qt Software Information (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at qt-sales@nokia.com.\n**\n**************************************************************************\/\n\n#include \"qt4buildconfigwidget.h\"\n\n#include \"makestep.h\"\n#include \"qmakestep.h\"\n#include \"qt4project.h\"\n#include \"qt4projectmanagerconstants.h\"\n#include \"qt4projectmanager.h\"\n#include \"ui_qt4buildconfigwidget.h\"\n\n#include \n#include \n\n#include \n\nnamespace {\nbool debug = false;\n}\n\nusing namespace Qt4ProjectManager;\nusing namespace Qt4ProjectManager::Internal;\n\nQt4BuildConfigWidget::Qt4BuildConfigWidget(Qt4Project *project)\n : BuildStepConfigWidget(),\n m_pro(project)\n{\n m_ui = new Ui::Qt4BuildConfigWidget();\n m_ui->setupUi(this);\n m_ui->shadowBuildDirEdit->setPromptDialogTitle(tr(\"Shadow Build Directory\"));\n m_ui->shadowBuildDirEdit->setExpectedKind(Core::Utils::PathChooser::Directory);\n m_ui->invalidQtWarningLabel->setVisible(false);\n\n connect(m_ui->nameLineEdit, SIGNAL(textEdited(QString)),\n this, SLOT(changeConfigName(QString)));\n\n connect(m_ui->shadowBuildCheckBox, SIGNAL(clicked(bool)),\n this, SLOT(shadowBuildCheckBoxClicked(bool)));\n\n connect(m_ui->shadowBuildDirEdit, SIGNAL(beforeBrowsing()),\n this, SLOT(onBeforeBeforeShadowBuildDirBrowsed()));\n\n connect(m_ui->shadowBuildDirEdit, SIGNAL(changed()),\n this, SLOT(shadowBuildLineEditTextChanged()));\n\n connect(m_ui->qtVersionComboBox, SIGNAL(currentIndexChanged(QString)),\n this, SLOT(qtVersionComboBoxCurrentIndexChanged(QString)));\n\n connect(m_ui->importLabel, SIGNAL(linkActivated(QString)),\n this, SLOT(importLabelClicked()));\n\n connect(m_ui->manageQtVersionPushButtons, SIGNAL(clicked()),\n this, SLOT(manageQtVersions()));\n\n connect(m_pro->qt4ProjectManager()->versionManager(), SIGNAL(qtVersionsChanged()),\n this, SLOT(setupQtVersionsComboBox()));\n}\n\nQt4BuildConfigWidget::~Qt4BuildConfigWidget()\n{\n delete m_ui;\n}\n\nvoid Qt4BuildConfigWidget::manageQtVersions()\n{\n Core::ICore *core = Core::ICore::instance();\n core->showOptionsDialog(Constants::QT_CATEGORY, Constants::QTVERSION_PAGE);\n}\n\n\nQString Qt4BuildConfigWidget::displayName() const\n{\n return tr(\"General\");\n}\n\nvoid Qt4BuildConfigWidget::init(const QString &buildConfiguration)\n{\n if (debug)\n qDebug() << \"Qt4BuildConfigWidget::init()\";\n\n m_buildConfiguration = buildConfiguration;\n\n m_ui->nameLineEdit->setText(m_pro->displayNameFor(m_buildConfiguration));\n\n setupQtVersionsComboBox();\n\n bool shadowBuild = m_pro->value(buildConfiguration, \"useShadowBuild\").toBool();\n m_ui->shadowBuildCheckBox->setChecked(shadowBuild);\n m_ui->shadowBuildDirEdit->setEnabled(shadowBuild);\n m_ui->shadowBuildDirEdit->setPath(m_pro->buildDirectory(buildConfiguration));\n updateImportLabel();\n}\n\nvoid Qt4BuildConfigWidget::changeConfigName(const QString &newName)\n{\n m_pro->setDisplayNameFor(m_buildConfiguration, newName);\n}\n\nvoid Qt4BuildConfigWidget::setupQtVersionsComboBox()\n{\n if (m_buildConfiguration.isEmpty()) \/\/ not yet initialized\n return;\n\n disconnect(m_ui->qtVersionComboBox, SIGNAL(currentIndexChanged(QString)),\n this, SLOT(qtVersionComboBoxCurrentIndexChanged(QString)));\n\n m_ui->qtVersionComboBox->clear();\n m_ui->qtVersionComboBox->addItem(tr(\"Default Qt Version\"), 0);\n\n if (m_pro->qtVersionId(m_buildConfiguration) == 0) {\n m_ui->qtVersionComboBox->setCurrentIndex(0);\n m_ui->invalidQtWarningLabel->setVisible(false);\n }\n \/\/ Add Qt Versions to the combo box\n QtVersionManager *vm = m_pro->qt4ProjectManager()->versionManager();\n const QList &versions = vm->versions();\n for (int i = 0; i < versions.size(); ++i) {\n m_ui->qtVersionComboBox->addItem(versions.at(i)->name(), versions.at(i)->uniqueId());\n\n if (versions.at(i)->uniqueId() == m_pro->qtVersionId(m_buildConfiguration)) {\n m_ui->qtVersionComboBox->setCurrentIndex(i + 1);\n m_ui->invalidQtWarningLabel->setVisible(!versions.at(i)->isValid());\n }\n }\n\n \/\/ And connect again\n connect(m_ui->qtVersionComboBox, SIGNAL(currentIndexChanged(QString)),\n this, SLOT(qtVersionComboBoxCurrentIndexChanged(QString)));\n}\n\nvoid Qt4BuildConfigWidget::onBeforeBeforeShadowBuildDirBrowsed()\n{\n QString initialDirectory = QFileInfo(m_pro->file()->fileName()).absolutePath();\n if (!initialDirectory.isEmpty())\n m_ui->shadowBuildDirEdit->setInitialBrowsePathBackup(initialDirectory);\n}\n\nvoid Qt4BuildConfigWidget::shadowBuildCheckBoxClicked(bool checked)\n{\n m_ui->shadowBuildDirEdit->setEnabled(checked);\n bool b = m_ui->shadowBuildCheckBox->isChecked();\n m_pro->setValue(m_buildConfiguration, \"useShadowBuild\", b);\n if (b)\n m_pro->setValue(m_buildConfiguration, \"buildDirectory\", m_ui->shadowBuildDirEdit->path());\n else\n m_pro->setValue(m_buildConfiguration, \"buildDirectory\", QVariant(QString::null));\n}\n\nvoid Qt4BuildConfigWidget::updateImportLabel()\n{\n m_ui->importLabel->setVisible(false);\n if (m_ui->shadowBuildCheckBox->isChecked()) {\n QString qtPath = m_pro->qt4ProjectManager()->versionManager()->findQtVersionFromMakefile(m_ui->shadowBuildDirEdit->path());\n if (!qtPath.isEmpty()) {\n m_ui->importLabel->setVisible(true);\n }\n }\n}\n\nvoid Qt4BuildConfigWidget::shadowBuildLineEditTextChanged()\n{\n if (m_pro->value(m_buildConfiguration, \"buildDirectory\").toString() == m_ui->shadowBuildDirEdit->path())\n m_pro->setValue(m_buildConfiguration, \"buildDirectory\", m_ui->shadowBuildDirEdit->path());\n \/\/ if the directory already exists\n \/\/ check if we have a build in there and\n \/\/ offer to import it\n updateImportLabel();\n\n m_pro->invalidateCachedTargetInformation();\n\n\/\/ QFileInfo fi(m_ui->shadowBuildDirEdit->path());\n\/\/ if (fi.exists()) {\n\/\/ m_ui->shadowBuildLineEdit->setStyleSheet(\"\");\n\/\/ m_ui->shadowBuildLineEdit->setToolTip(\"\");\n\/\/ } else {\n\/\/ m_ui->shadowBuildLineEdit->setStyleSheet(\"background: red;\");\n\/\/ m_ui->shadowBuildLineEdit->setToolTip(tr(\"Directory does not exist.\"));\n\/\/ }\n}\n\nvoid Qt4BuildConfigWidget::importLabelClicked()\n{\n if (m_ui->shadowBuildCheckBox->isChecked()) {\n QString directory = m_ui->shadowBuildDirEdit->path();\n if (!directory.isEmpty()) {\n QtVersionManager *vm = m_pro->qt4ProjectManager()->versionManager();\n QString qtPath = vm->findQtVersionFromMakefile(directory);\n if (!qtPath.isEmpty()) {\n QtVersion *version = vm->qtVersionForDirectory(qtPath);\n if (!version) {\n version = new QtVersion(QFileInfo(qtPath).baseName(), qtPath);\n vm->addVersion(version);\n }\n QtVersion::QmakeBuildConfig qmakeBuildConfig = version->defaultBuildConfig();\n qmakeBuildConfig = vm->scanMakefileForQmakeConfig(directory, qmakeBuildConfig);\n\n \/\/ So we got all the information now apply it...\n m_pro->setQtVersion(m_buildConfiguration, version->uniqueId());\n \/\/ Combo box will be updated at the end\n\n \/\/ Find qmakestep...\n QMakeStep *qmakeStep = m_pro->qmakeStep();\n MakeStep *makeStep = m_pro->makeStep();\n\n qmakeStep->setValue(m_buildConfiguration, \"buildConfiguration\", int(qmakeBuildConfig));\n \/\/ Adjust command line arguments, this is ugly as hell\n \/\/ If we are switching to BuildAll we want \"release\" in there and no \"debug\"\n \/\/ or \"debug\" in there and no \"release\"\n \/\/ If we are switching to not BuildAl we want neither \"release\" nor \"debug\" in there\n QStringList makeCmdArguments = makeStep->value(m_buildConfiguration, \"makeargs\").toStringList();\n bool debug = qmakeBuildConfig & QtVersion::DebugBuild;\n if (qmakeBuildConfig & QtVersion::BuildAll) {\n makeCmdArguments.removeAll(debug ? \"release\" : \"debug\");\n if (!makeCmdArguments.contains(debug ? \"debug\" : \"release\"))\n makeCmdArguments.append(debug ? \"debug\" : \"release\");\n } else {\n makeCmdArguments.removeAll(\"debug\");\n makeCmdArguments.removeAll(\"remove\");\n }\n makeStep->setValue(m_buildConfiguration, \"makeargs\", makeCmdArguments);\n }\n }\n }\n setupQtVersionsComboBox();\n}\n\nvoid Qt4BuildConfigWidget::qtVersionComboBoxCurrentIndexChanged(const QString &)\n{\n \/\/Qt Version\n int newQtVersion;\n if (m_ui->qtVersionComboBox->currentIndex() == 0) {\n newQtVersion = 0;\n } else {\n newQtVersion = m_ui->qtVersionComboBox->itemData(m_ui->qtVersionComboBox->currentIndex()).toInt();\n }\n bool isValid = m_pro->qt4ProjectManager()->versionManager()->version(newQtVersion)->isValid();\n m_ui->invalidQtWarningLabel->setVisible(!isValid);\n if (newQtVersion != m_pro->qtVersionId(m_buildConfiguration)) {\n m_pro->setQtVersion(m_buildConfiguration, newQtVersion);\n m_pro->update();\n }\n}\nShadow build directory setting not used \"right away\".\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Qt Software Information (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at qt-sales@nokia.com.\n**\n**************************************************************************\/\n\n#include \"qt4buildconfigwidget.h\"\n\n#include \"makestep.h\"\n#include \"qmakestep.h\"\n#include \"qt4project.h\"\n#include \"qt4projectmanagerconstants.h\"\n#include \"qt4projectmanager.h\"\n#include \"ui_qt4buildconfigwidget.h\"\n\n#include \n#include \n\n#include \n\nnamespace {\nbool debug = false;\n}\n\nusing namespace Qt4ProjectManager;\nusing namespace Qt4ProjectManager::Internal;\n\nQt4BuildConfigWidget::Qt4BuildConfigWidget(Qt4Project *project)\n : BuildStepConfigWidget(),\n m_pro(project)\n{\n m_ui = new Ui::Qt4BuildConfigWidget();\n m_ui->setupUi(this);\n m_ui->shadowBuildDirEdit->setPromptDialogTitle(tr(\"Shadow Build Directory\"));\n m_ui->shadowBuildDirEdit->setExpectedKind(Core::Utils::PathChooser::Directory);\n m_ui->invalidQtWarningLabel->setVisible(false);\n\n connect(m_ui->nameLineEdit, SIGNAL(textEdited(QString)),\n this, SLOT(changeConfigName(QString)));\n\n connect(m_ui->shadowBuildCheckBox, SIGNAL(clicked(bool)),\n this, SLOT(shadowBuildCheckBoxClicked(bool)));\n\n connect(m_ui->shadowBuildDirEdit, SIGNAL(beforeBrowsing()),\n this, SLOT(onBeforeBeforeShadowBuildDirBrowsed()));\n\n connect(m_ui->shadowBuildDirEdit, SIGNAL(changed()),\n this, SLOT(shadowBuildLineEditTextChanged()));\n\n connect(m_ui->qtVersionComboBox, SIGNAL(currentIndexChanged(QString)),\n this, SLOT(qtVersionComboBoxCurrentIndexChanged(QString)));\n\n connect(m_ui->importLabel, SIGNAL(linkActivated(QString)),\n this, SLOT(importLabelClicked()));\n\n connect(m_ui->manageQtVersionPushButtons, SIGNAL(clicked()),\n this, SLOT(manageQtVersions()));\n\n connect(m_pro->qt4ProjectManager()->versionManager(), SIGNAL(qtVersionsChanged()),\n this, SLOT(setupQtVersionsComboBox()));\n}\n\nQt4BuildConfigWidget::~Qt4BuildConfigWidget()\n{\n delete m_ui;\n}\n\nvoid Qt4BuildConfigWidget::manageQtVersions()\n{\n Core::ICore *core = Core::ICore::instance();\n core->showOptionsDialog(Constants::QT_CATEGORY, Constants::QTVERSION_PAGE);\n}\n\n\nQString Qt4BuildConfigWidget::displayName() const\n{\n return tr(\"General\");\n}\n\nvoid Qt4BuildConfigWidget::init(const QString &buildConfiguration)\n{\n if (debug)\n qDebug() << \"Qt4BuildConfigWidget::init()\";\n\n m_buildConfiguration = buildConfiguration;\n\n m_ui->nameLineEdit->setText(m_pro->displayNameFor(m_buildConfiguration));\n\n setupQtVersionsComboBox();\n\n bool shadowBuild = m_pro->value(buildConfiguration, \"useShadowBuild\").toBool();\n m_ui->shadowBuildCheckBox->setChecked(shadowBuild);\n m_ui->shadowBuildDirEdit->setEnabled(shadowBuild);\n m_ui->shadowBuildDirEdit->setPath(m_pro->buildDirectory(buildConfiguration));\n updateImportLabel();\n}\n\nvoid Qt4BuildConfigWidget::changeConfigName(const QString &newName)\n{\n m_pro->setDisplayNameFor(m_buildConfiguration, newName);\n}\n\nvoid Qt4BuildConfigWidget::setupQtVersionsComboBox()\n{\n if (m_buildConfiguration.isEmpty()) \/\/ not yet initialized\n return;\n\n disconnect(m_ui->qtVersionComboBox, SIGNAL(currentIndexChanged(QString)),\n this, SLOT(qtVersionComboBoxCurrentIndexChanged(QString)));\n\n m_ui->qtVersionComboBox->clear();\n m_ui->qtVersionComboBox->addItem(tr(\"Default Qt Version\"), 0);\n\n if (m_pro->qtVersionId(m_buildConfiguration) == 0) {\n m_ui->qtVersionComboBox->setCurrentIndex(0);\n m_ui->invalidQtWarningLabel->setVisible(false);\n }\n \/\/ Add Qt Versions to the combo box\n QtVersionManager *vm = m_pro->qt4ProjectManager()->versionManager();\n const QList &versions = vm->versions();\n for (int i = 0; i < versions.size(); ++i) {\n m_ui->qtVersionComboBox->addItem(versions.at(i)->name(), versions.at(i)->uniqueId());\n\n if (versions.at(i)->uniqueId() == m_pro->qtVersionId(m_buildConfiguration)) {\n m_ui->qtVersionComboBox->setCurrentIndex(i + 1);\n m_ui->invalidQtWarningLabel->setVisible(!versions.at(i)->isValid());\n }\n }\n\n \/\/ And connect again\n connect(m_ui->qtVersionComboBox, SIGNAL(currentIndexChanged(QString)),\n this, SLOT(qtVersionComboBoxCurrentIndexChanged(QString)));\n}\n\nvoid Qt4BuildConfigWidget::onBeforeBeforeShadowBuildDirBrowsed()\n{\n QString initialDirectory = QFileInfo(m_pro->file()->fileName()).absolutePath();\n if (!initialDirectory.isEmpty())\n m_ui->shadowBuildDirEdit->setInitialBrowsePathBackup(initialDirectory);\n}\n\nvoid Qt4BuildConfigWidget::shadowBuildCheckBoxClicked(bool checked)\n{\n m_ui->shadowBuildDirEdit->setEnabled(checked);\n bool b = m_ui->shadowBuildCheckBox->isChecked();\n m_pro->setValue(m_buildConfiguration, \"useShadowBuild\", b);\n if (b)\n m_pro->setValue(m_buildConfiguration, \"buildDirectory\", m_ui->shadowBuildDirEdit->path());\n else\n m_pro->setValue(m_buildConfiguration, \"buildDirectory\", QVariant(QString::null));\n}\n\nvoid Qt4BuildConfigWidget::updateImportLabel()\n{\n m_ui->importLabel->setVisible(false);\n if (m_ui->shadowBuildCheckBox->isChecked()) {\n QString qtPath = m_pro->qt4ProjectManager()->versionManager()->findQtVersionFromMakefile(m_ui->shadowBuildDirEdit->path());\n if (!qtPath.isEmpty()) {\n m_ui->importLabel->setVisible(true);\n }\n }\n}\n\nvoid Qt4BuildConfigWidget::shadowBuildLineEditTextChanged()\n{\n if (m_pro->value(m_buildConfiguration, \"buildDirectory\").toString() == m_ui->shadowBuildDirEdit->path())\n return;\n m_pro->setValue(m_buildConfiguration, \"buildDirectory\", m_ui->shadowBuildDirEdit->path());\n \/\/ if the directory already exists\n \/\/ check if we have a build in there and\n \/\/ offer to import it\n updateImportLabel();\n\n m_pro->invalidateCachedTargetInformation();\n\n\/\/ QFileInfo fi(m_ui->shadowBuildDirEdit->path());\n\/\/ if (fi.exists()) {\n\/\/ m_ui->shadowBuildLineEdit->setStyleSheet(\"\");\n\/\/ m_ui->shadowBuildLineEdit->setToolTip(\"\");\n\/\/ } else {\n\/\/ m_ui->shadowBuildLineEdit->setStyleSheet(\"background: red;\");\n\/\/ m_ui->shadowBuildLineEdit->setToolTip(tr(\"Directory does not exist.\"));\n\/\/ }\n}\n\nvoid Qt4BuildConfigWidget::importLabelClicked()\n{\n if (m_ui->shadowBuildCheckBox->isChecked()) {\n QString directory = m_ui->shadowBuildDirEdit->path();\n if (!directory.isEmpty()) {\n QtVersionManager *vm = m_pro->qt4ProjectManager()->versionManager();\n QString qtPath = vm->findQtVersionFromMakefile(directory);\n if (!qtPath.isEmpty()) {\n QtVersion *version = vm->qtVersionForDirectory(qtPath);\n if (!version) {\n version = new QtVersion(QFileInfo(qtPath).baseName(), qtPath);\n vm->addVersion(version);\n }\n QtVersion::QmakeBuildConfig qmakeBuildConfig = version->defaultBuildConfig();\n qmakeBuildConfig = vm->scanMakefileForQmakeConfig(directory, qmakeBuildConfig);\n\n \/\/ So we got all the information now apply it...\n m_pro->setQtVersion(m_buildConfiguration, version->uniqueId());\n \/\/ Combo box will be updated at the end\n\n \/\/ Find qmakestep...\n QMakeStep *qmakeStep = m_pro->qmakeStep();\n MakeStep *makeStep = m_pro->makeStep();\n\n qmakeStep->setValue(m_buildConfiguration, \"buildConfiguration\", int(qmakeBuildConfig));\n \/\/ Adjust command line arguments, this is ugly as hell\n \/\/ If we are switching to BuildAll we want \"release\" in there and no \"debug\"\n \/\/ or \"debug\" in there and no \"release\"\n \/\/ If we are switching to not BuildAl we want neither \"release\" nor \"debug\" in there\n QStringList makeCmdArguments = makeStep->value(m_buildConfiguration, \"makeargs\").toStringList();\n bool debug = qmakeBuildConfig & QtVersion::DebugBuild;\n if (qmakeBuildConfig & QtVersion::BuildAll) {\n makeCmdArguments.removeAll(debug ? \"release\" : \"debug\");\n if (!makeCmdArguments.contains(debug ? \"debug\" : \"release\"))\n makeCmdArguments.append(debug ? \"debug\" : \"release\");\n } else {\n makeCmdArguments.removeAll(\"debug\");\n makeCmdArguments.removeAll(\"remove\");\n }\n makeStep->setValue(m_buildConfiguration, \"makeargs\", makeCmdArguments);\n }\n }\n }\n setupQtVersionsComboBox();\n}\n\nvoid Qt4BuildConfigWidget::qtVersionComboBoxCurrentIndexChanged(const QString &)\n{\n \/\/Qt Version\n int newQtVersion;\n if (m_ui->qtVersionComboBox->currentIndex() == 0) {\n newQtVersion = 0;\n } else {\n newQtVersion = m_ui->qtVersionComboBox->itemData(m_ui->qtVersionComboBox->currentIndex()).toInt();\n }\n bool isValid = m_pro->qt4ProjectManager()->versionManager()->version(newQtVersion)->isValid();\n m_ui->invalidQtWarningLabel->setVisible(!isValid);\n if (newQtVersion != m_pro->qtVersionId(m_buildConfiguration)) {\n m_pro->setQtVersion(m_buildConfiguration, newQtVersion);\n m_pro->update();\n }\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright © 2019 Arm Ltd. All rights reserved.\n\/\/ SPDX-License-Identifier: MIT\n\/\/\n\n#include \"..\/FileOnlyProfilingConnection.hpp\"\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nusing namespace armnn::profiling;\nusing namespace armnn;\n\nusing namespace std::chrono_literals;\n\nclass FileOnlyHelperService : public ProfilingService\n{\n public:\n \/\/ Wait for a notification from the send thread\n bool WaitForPacketsSent(uint32_t timeout = 1000)\n {\n return ProfilingService::WaitForPacketSent(ProfilingService::Instance(), timeout);\n }\n};\n\nBOOST_AUTO_TEST_SUITE(FileOnlyProfilingDecoratorTests)\n\nBOOST_AUTO_TEST_CASE(DumpOutgoingValidFileEndToEnd)\n{\n \/\/ Create a temporary file name.\n boost::filesystem::path tempPath = boost::filesystem::temp_directory_path();\n boost::filesystem::path tempFile = boost::filesystem::unique_path();\n tempPath = tempPath \/ tempFile;\n armnn::Runtime::CreationOptions::ExternalProfilingOptions options;\n options.m_EnableProfiling = true;\n options.m_FileOnly = true;\n options.m_IncomingCaptureFile = \"\";\n options.m_OutgoingCaptureFile = tempPath.string();\n options.m_CapturePeriod = 100;\n\n FileOnlyHelperService helper;\n\n \/\/ Enable the profiling service\n ProfilingService& profilingService = ProfilingService::Instance();\n profilingService.ResetExternalProfilingOptions(options, true);\n \/\/ Bring the profiling service to the \"WaitingForAck\" state\n profilingService.Update();\n profilingService.Update();\n\n\n BOOST_CHECK(profilingService.GetCurrentState() == ProfilingState::WaitingForAck);\n\n profilingService.Update();\n \/\/ First packet sent will be the SendStreamMetaDataPacket, it's possible though unlikely that it will be sent twice\n \/\/ The second or possibly third packet will be the CounterDirectoryPacket which means the\n \/\/ ConnectionAcknowledgedCommandHandler has set the state to active\n uint32_t packetCount = 0;\n while(profilingService.GetCurrentState() != ProfilingState::Active && packetCount < 3)\n {\n if(!helper.WaitForPacketsSent())\n {\n BOOST_FAIL(\"Timeout waiting for packets\");\n }\n packetCount++;\n }\n\n BOOST_CHECK(profilingService.GetCurrentState() == ProfilingState::Active);\n \/\/ Minimum test here is to check that the file was created.\n BOOST_CHECK(boost::filesystem::exists(tempPath.c_str()) == true);\n\n \/\/ Increment a counter.\n BOOST_CHECK(profilingService.IsCounterRegistered(0) == true);\n profilingService.IncrementCounterValue(0);\n BOOST_CHECK(profilingService.GetCounterValue(0) > 0);\n\n \/\/ At this point the profiling service is active and we've activated all the counters. Waiting a collection\n \/\/ period should be enough to have some data in the file.\n\n \/\/ Wait for 1 collection period plus a bit of overhead..\n helper.WaitForPacketsSent();\n\n \/\/ In order to flush the files we need to gracefully close the profiling service.\n options.m_EnableProfiling = false;\n profilingService.ResetExternalProfilingOptions(options, true);\n\n \/\/ The output file size should be greater than 0.\n BOOST_CHECK(armnnUtils::Filesystem::GetFileSize(tempPath.string().c_str()) > 0);\n\n \/\/ Delete the tmp file.\n BOOST_CHECK(armnnUtils::Filesystem::Remove(tempPath.string().c_str()));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\nIVGCVSW-4171 Temporarily disable DumpOutgoingValidFileEndToEnd unit test\/\/\n\/\/ Copyright © 2019 Arm Ltd. All rights reserved.\n\/\/ SPDX-License-Identifier: MIT\n\/\/\n\n#include \"..\/FileOnlyProfilingConnection.hpp\"\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nusing namespace armnn::profiling;\nusing namespace armnn;\n\nusing namespace std::chrono_literals;\n\nclass FileOnlyHelperService : public ProfilingService\n{\n public:\n \/\/ Wait for a notification from the send thread\n bool WaitForPacketsSent(uint32_t timeout = 1000)\n {\n return ProfilingService::WaitForPacketSent(ProfilingService::Instance(), timeout);\n }\n};\n\nBOOST_AUTO_TEST_SUITE(FileOnlyProfilingDecoratorTests)\n\nBOOST_AUTO_TEST_CASE(DumpOutgoingValidFileEndToEnd, * boost::unit_test::disabled())\n{\n \/\/ Create a temporary file name.\n boost::filesystem::path tempPath = boost::filesystem::temp_directory_path();\n boost::filesystem::path tempFile = boost::filesystem::unique_path();\n tempPath = tempPath \/ tempFile;\n armnn::Runtime::CreationOptions::ExternalProfilingOptions options;\n options.m_EnableProfiling = true;\n options.m_FileOnly = true;\n options.m_IncomingCaptureFile = \"\";\n options.m_OutgoingCaptureFile = tempPath.string();\n options.m_CapturePeriod = 100;\n\n FileOnlyHelperService helper;\n\n \/\/ Enable the profiling service\n ProfilingService& profilingService = ProfilingService::Instance();\n profilingService.ResetExternalProfilingOptions(options, true);\n \/\/ Bring the profiling service to the \"WaitingForAck\" state\n profilingService.Update();\n profilingService.Update();\n\n\n BOOST_CHECK(profilingService.GetCurrentState() == ProfilingState::WaitingForAck);\n\n profilingService.Update();\n \/\/ First packet sent will be the SendStreamMetaDataPacket, it's possible though unlikely that it will be sent twice\n \/\/ The second or possibly third packet will be the CounterDirectoryPacket which means the\n \/\/ ConnectionAcknowledgedCommandHandler has set the state to active\n uint32_t packetCount = 0;\n while(profilingService.GetCurrentState() != ProfilingState::Active && packetCount < 3)\n {\n if(!helper.WaitForPacketsSent())\n {\n BOOST_FAIL(\"Timeout waiting for packets\");\n }\n packetCount++;\n }\n\n BOOST_CHECK(profilingService.GetCurrentState() == ProfilingState::Active);\n \/\/ Minimum test here is to check that the file was created.\n BOOST_CHECK(boost::filesystem::exists(tempPath.c_str()) == true);\n\n \/\/ Increment a counter.\n BOOST_CHECK(profilingService.IsCounterRegistered(0) == true);\n profilingService.IncrementCounterValue(0);\n BOOST_CHECK(profilingService.GetCounterValue(0) > 0);\n\n \/\/ At this point the profiling service is active and we've activated all the counters. Waiting a collection\n \/\/ period should be enough to have some data in the file.\n\n \/\/ Wait for 1 collection period plus a bit of overhead..\n helper.WaitForPacketsSent();\n\n \/\/ In order to flush the files we need to gracefully close the profiling service.\n options.m_EnableProfiling = false;\n profilingService.ResetExternalProfilingOptions(options, true);\n\n \/\/ The output file size should be greater than 0.\n BOOST_CHECK(armnnUtils::Filesystem::GetFileSize(tempPath.string().c_str()) > 0);\n\n \/\/ Delete the tmp file.\n BOOST_CHECK(armnnUtils::Filesystem::Remove(tempPath.string().c_str()));\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2009 Scientific Computing and Imaging Institute,\n University of Utah.\n\n \n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n#include \n#include \n#include \n#include \n#include \n\n\nusing namespace SCIRun;\nusing namespace SCIRun::Core::Datatypes;\nusing namespace SCIRun::Core::Algorithms;\nusing namespace SCIRun::Core::Algorithms::Fields;\nusing namespace SCIRun::Dataflow::Networks;\nusing namespace SCIRun::Modules::Fields;\n\nModuleLookupInfo SplitFieldByConnectedRegion::staticInfo_(\"SplitFieldByConnectedRegion\", \"NewField\", \"SCIRun\");\n\nSplitFieldByConnectedRegion::SplitFieldByConnectedRegion() \n : Module(staticInfo_)\n{\n INITIALIZE_PORT(InputField);\n INITIALIZE_PORT(OutputField1);\n}\n\nvoid SplitFieldByConnectedRegion::setStateDefaults()\n{\n\/*\n setStateBoolFromAlgo(Parameters::NoInnerBoundary);\n setStateBoolFromAlgo(Parameters::DisconnectBoundaries); *\/\n}\n\n\n\nvoid SplitFieldByConnectedRegion::execute()\n{\n \/\/ Define local handles of data objects:\n\/* auto ifield = getRequiredInput(InputField);\n auto elemLink = getOptionalInput(ElemLink);\n auto minValue = getOptionalInput(MinValue);\n auto maxValue = getOptionalInput(MaxValue);\n\n if (needToExecute())\n {\n update_state(Executing);\n\n if (minValue && *minValue)\n {\n double minrange = (*minValue)->value();\n get_state()->setValue(Parameters::MinRange, minrange);\n get_state()->setValue(Parameters::Domain, minrange); \/\/??\n }\n if (maxValue && *maxValue)\n {\n double maxrange = (*maxValue)->value();\n get_state()->setValue(Parameters::MaxRange, maxrange);\n }\n\n auto state = get_state();\n\n setAlgoIntFromState(Parameters::MinRange);\n setAlgoIntFromState(Parameters::MaxRange);\n setAlgoIntFromState(Parameters::Domain);\n setAlgoBoolFromState(Parameters::UseRange);\n setAlgoBoolFromState(Parameters::AddOuterBoundary);\n setAlgoBoolFromState(Parameters::InnerBoundaryOnly);\n setAlgoBoolFromState(Parameters::NoInnerBoundary);\n setAlgoBoolFromState(Parameters::DisconnectBoundaries);\n\n if (!state->getValue(Parameters::UseRange).getBool())\n {\n int guiValue = state->getValue(Parameters::Domain).getInt();\n algo().set(Parameters::UseRange, true);\n algo().set(Parameters::MinRange, guiValue);\n algo().set(Parameters::MaxRange, guiValue);\n }\n \n auto output = algo().run_generic(make_input((InputField, ifield)(ElemLink, optionalAlgoInput(elemLink))));\n *\/\n if (needToExecute())\n {\n update_state(Executing);\n AlgorithmOutput output;\n sendOutputFromAlgorithm(OutputField1, output);\n }\n}\n\n\n\n\n\n\n\n\n\n\n\n#ifdef SCIRUN4_CODE_TO_BE_ENABLED_LATER\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\nnamespace ModelCreation {\n\nusing namespace SCIRun;\n\nclass SplitFieldByConnectedRegion : public Module {\n public:\n SplitFieldByConnectedRegion(GuiContext*);\n ~SplitFieldByConnectedRegion() {}\n virtual void execute();\n\n private:\n GuiInt gui_sort_by_size_;\n GuiDouble gui_sort_ascending_;\n SCIRunAlgo::SplitByConnectedRegionAlgo algo_;\n};\n\n\nDECLARE_MAKER(SplitFieldByConnectedRegion)\nSplitFieldByConnectedRegion::SplitFieldByConnectedRegion(GuiContext* ctx)\n : Module(\"SplitFieldByConnectedRegion\", ctx, Source, \"NewField\", \"SCIRun\"),\n gui_sort_by_size_(get_ctx()->subVar(\"sort-by-size\"),0),\n gui_sort_ascending_(get_ctx()->subVar(\"sort-ascending\"),0)\n{\n algo_.set_progress_reporter(this);\n}\n\n\nvoid SplitFieldByConnectedRegion::execute()\n{\n \/\/ Define local handles of data objects: \n FieldHandle input;\n BundleHandle boutput;\n std::vector output;\n FieldHandle nofield = 0;\n\n \/\/ Get the new input data: \n get_input_handle(\"Field\",input,true);\n \n \/\/ Only reexecute if the input changed. SCIRun uses simple scheduling\n \/\/ that executes every module downstream even if no data has changed: \n if (inputs_changed_ || !oport_cached(\"All Fields\") || !oport_cached(\"Field1\")\n || !oport_cached(\"Field2\") || !oport_cached(\"Field3\") || !oport_cached(\"Field4\")\n || !oport_cached(\"Field5\") || !oport_cached(\"Field6\") || !oport_cached(\"Field7\") \n || !oport_cached(\"Field8\") || gui_sort_by_size_.changed() \n || gui_sort_ascending_.changed())\n {\n update_state(Executing);\n\n algo_.set_bool(\"sort_by_size\",gui_sort_by_size_.get());\n algo_.set_bool(\"sort_ascending\",gui_sort_ascending_.get());\n \n if(!(algo_.run(input,output))) return;\n \n boutput = new Bundle;\n for (size_t j=0; j< output.size(); j++)\n {\n std::ostringstream oss;\n oss << \"Field\" << j;\n boutput->setField(oss.str(),output[j]);\n }\n \n send_output_handle(\"All Fields\",boutput);\n if (output.size() > 0) send_output_handle(\"Field1\",output[0]); \n else send_output_handle(\"Field1\",nofield); \n if (output.size() > 1) send_output_handle(\"Field2\",output[1]);\n else send_output_handle(\"Field2\",nofield); \n if (output.size() > 2) send_output_handle(\"Field3\",output[2]);\n else send_output_handle(\"Field3\",nofield); \n if (output.size() > 3) send_output_handle(\"Field4\",output[3]);\n else send_output_handle(\"Field4\",nofield); \n if (output.size() > 4) send_output_handle(\"Field5\",output[4]);\n else send_output_handle(\"Field5\",nofield); \n if (output.size() > 5) send_output_handle(\"Field6\",output[5]);\n else send_output_handle(\"Field6\",nofield); \n if (output.size() > 6) send_output_handle(\"Field7\",output[6]);\n else send_output_handle(\"Field7\",nofield); \n if (output.size() > 7) send_output_handle(\"Field8\",output[7]);\n else send_output_handle(\"Field8\",nofield); \n }\n}\n\n} \/\/ End namespace ModelCreation\n #endif\n\nintermediate commit\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2009 Scientific Computing and Imaging Institute,\n University of Utah.\n\n \n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n#include \n#include \n#include \n#include \n#include \n\n\nusing namespace SCIRun;\nusing namespace SCIRun::Core::Datatypes;\nusing namespace SCIRun::Core::Algorithms;\nusing namespace SCIRun::Core::Algorithms::Fields;\nusing namespace SCIRun::Dataflow::Networks;\nusing namespace SCIRun::Modules::Fields;\n\nModuleLookupInfo SplitFieldByConnectedRegion::staticInfo_(\"SplitFieldByConnectedRegion\", \"NewField\", \"SCIRun\");\n\nSplitFieldByConnectedRegion::SplitFieldByConnectedRegion() \n : Module(staticInfo_)\n{\n INITIALIZE_PORT(InputField);\n INITIALIZE_PORT(OutputField1);\n}\n\nvoid SplitFieldByConnectedRegion::setStateDefaults()\n{\n\/*\n setStateBoolFromAlgo(Parameters::NoInnerBoundary);\n setStateBoolFromAlgo(Parameters::DisconnectBoundaries); *\/\n}\n\n\n\nvoid SplitFieldByConnectedRegion::execute()\n{\n \n\/* auto ifield = getRequiredInput(InputField);\n auto elemLink = getOptionalInput(ElemLink);\n auto minValue = getOptionalInput(MinValue);\n auto maxValue = getOptionalInput(MaxValue);\n\n if (needToExecute())\n {\n update_state(Executing);\n\n if (minValue && *minValue)\n {\n double minrange = (*minValue)->value();\n get_state()->setValue(Parameters::MinRange, minrange);\n get_state()->setValue(Parameters::Domain, minrange); \/\/??\n }\n if (maxValue && *maxValue)\n {\n double maxrange = (*maxValue)->value();\n get_state()->setValue(Parameters::MaxRange, maxrange);\n }\n\n auto state = get_state();\n\n setAlgoIntFromState(Parameters::MinRange);\n setAlgoIntFromState(Parameters::MaxRange);\n setAlgoIntFromState(Parameters::Domain);\n setAlgoBoolFromState(Parameters::UseRange);\n setAlgoBoolFromState(Parameters::AddOuterBoundary);\n setAlgoBoolFromState(Parameters::InnerBoundaryOnly);\n setAlgoBoolFromState(Parameters::NoInnerBoundary);\n setAlgoBoolFromState(Parameters::DisconnectBoundaries);\n\n if (!state->getValue(Parameters::UseRange).getBool())\n {\n int guiValue = state->getValue(Parameters::Domain).getInt();\n algo().set(Parameters::UseRange, true);\n algo().set(Parameters::MinRange, guiValue);\n algo().set(Parameters::MaxRange, guiValue);\n }\n \n auto output = algo().run_generic(make_input((InputField, ifield)(ElemLink, optionalAlgoInput(elemLink))));\n *\/\n if (needToExecute())\n {\n update_state(Executing);\n AlgorithmOutput output;\n sendOutputFromAlgorithm(OutputField1, output);\n }\n}\n\n\n\n\n\n\n\n\n\n\n\n#ifdef SCIRUN4_CODE_TO_BE_ENABLED_LATER\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\nnamespace ModelCreation {\n\nusing namespace SCIRun;\n\nclass SplitFieldByConnectedRegion : public Module {\n public:\n SplitFieldByConnectedRegion(GuiContext*);\n ~SplitFieldByConnectedRegion() {}\n virtual void execute();\n\n private:\n GuiInt gui_sort_by_size_;\n GuiDouble gui_sort_ascending_;\n SCIRunAlgo::SplitByConnectedRegionAlgo algo_;\n};\n\n\nDECLARE_MAKER(SplitFieldByConnectedRegion)\nSplitFieldByConnectedRegion::SplitFieldByConnectedRegion(GuiContext* ctx)\n : Module(\"SplitFieldByConnectedRegion\", ctx, Source, \"NewField\", \"SCIRun\"),\n gui_sort_by_size_(get_ctx()->subVar(\"sort-by-size\"),0),\n gui_sort_ascending_(get_ctx()->subVar(\"sort-ascending\"),0)\n{\n algo_.set_progress_reporter(this);\n}\n\n\nvoid SplitFieldByConnectedRegion::execute()\n{\n \/\/ Define local handles of data objects: \n FieldHandle input;\n BundleHandle boutput;\n std::vector output;\n FieldHandle nofield = 0;\n\n \/\/ Get the new input data: \n get_input_handle(\"Field\",input,true);\n \n \/\/ Only reexecute if the input changed. SCIRun uses simple scheduling\n \/\/ that executes every module downstream even if no data has changed: \n if (inputs_changed_ || !oport_cached(\"All Fields\") || !oport_cached(\"Field1\")\n || !oport_cached(\"Field2\") || !oport_cached(\"Field3\") || !oport_cached(\"Field4\")\n || !oport_cached(\"Field5\") || !oport_cached(\"Field6\") || !oport_cached(\"Field7\") \n || !oport_cached(\"Field8\") || gui_sort_by_size_.changed() \n || gui_sort_ascending_.changed())\n {\n update_state(Executing);\n\n algo_.set_bool(\"sort_by_size\",gui_sort_by_size_.get());\n algo_.set_bool(\"sort_ascending\",gui_sort_ascending_.get());\n \n if(!(algo_.run(input,output))) return;\n \n boutput = new Bundle;\n for (size_t j=0; j< output.size(); j++)\n {\n std::ostringstream oss;\n oss << \"Field\" << j;\n boutput->setField(oss.str(),output[j]);\n }\n \n send_output_handle(\"All Fields\",boutput);\n if (output.size() > 0) send_output_handle(\"Field1\",output[0]); \n else send_output_handle(\"Field1\",nofield); \n if (output.size() > 1) send_output_handle(\"Field2\",output[1]);\n else send_output_handle(\"Field2\",nofield); \n if (output.size() > 2) send_output_handle(\"Field3\",output[2]);\n else send_output_handle(\"Field3\",nofield); \n if (output.size() > 3) send_output_handle(\"Field4\",output[3]);\n else send_output_handle(\"Field4\",nofield); \n if (output.size() > 4) send_output_handle(\"Field5\",output[4]);\n else send_output_handle(\"Field5\",nofield); \n if (output.size() > 5) send_output_handle(\"Field6\",output[5]);\n else send_output_handle(\"Field6\",nofield); \n if (output.size() > 6) send_output_handle(\"Field7\",output[6]);\n else send_output_handle(\"Field7\",nofield); \n if (output.size() > 7) send_output_handle(\"Field8\",output[7]);\n else send_output_handle(\"Field8\",nofield); \n }\n}\n\n} \/\/ End namespace ModelCreation\n #endif\n\n<|endoftext|>"} {"text":"\/\/ Copyright eeGeo Ltd (2012-2015), All Rights Reserved\n\n#include \"PoiRingController.h\"\n#include \"InteriorsFloorModel.h\"\n#include \"InteriorsModel.h\"\n#include \"InteriorId.h\"\n#include \"TtyHandler.h\"\n#include \"CameraHelpers.h\"\n#include \"RenderCamera.h\"\n#include \"IRayPicker.h\"\n#include \"PoiRingView.h\"\n#include \"RenderContext.h\"\n#include \"MathFunc.h\"\n#include \"MathsHelpers.h\"\n#include \"IMyPinCreationInitiationViewModel.h\"\n#include \"IMyPinCreationModel.h\"\n#include \"EarthConstants.h\"\n#include \"TerrainHeightProvider.h\"\n#include \"TransformHelpers.h\"\n#include \"VectorMath.h\"\n#include \"InteriorController.h\"\n\n#include \"InteriorHeightHelpers.h\"\n#include \"ScreenProperties.h\"\n\nnamespace ExampleApp\n{\n namespace MyPinCreation\n {\n namespace PoiRing\n {\n namespace SdkModel\n {\n namespace\n {\n \n float CalculateAltitudeBasedSphereOuterScale(float altitude)\n {\n const float minAltitude = 50.f;\n const float maxAltitude = 1500.f;\n const float lowAltitudeScale = 0.05f;\n const float highAltitudeScale = 1.0f;\n float t = Eegeo::Math::Clamp01((altitude - minAltitude)\/(maxAltitude-minAltitude));\n return Eegeo::Math::Lerp(lowAltitudeScale, highAltitudeScale, t);\n }\n \n float CalculateAltitudeBasedSphereScale(float altitude, float outerRingRadiusInMeters)\n {\n const float minAltitude = 100.f;\n const float maxAltitude = 18000.f;\n const float lowAltitudeSphereScale = outerRingRadiusInMeters - 0.5f;\n const float highAltitudeSphereScale = outerRingRadiusInMeters - 100.f;\n return lowAltitudeSphereScale + (((altitude - minAltitude)\/maxAltitude) * (highAltitudeSphereScale - lowAltitudeSphereScale));\n }\n\n bool RingIsOnScreen(const Eegeo::Camera::RenderCamera& renderCamera, const Eegeo::dv3& position, float radius)\n {\n const Eegeo::Geometry::Frustum& frustum = renderCamera.GetFrustum();\n const Eegeo::dv3 cameraRelativePosition = position - renderCamera.GetEcefLocation();\n\n for (int i = 0; i < Eegeo::Geometry::Frustum::PLANES_COUNT; ++i)\n {\n const Eegeo::Geometry::Plane& p = frustum.planes[i];\n double signedDist = p.a * cameraRelativePosition.GetX() + p.b * cameraRelativePosition.GetY() + p.c * cameraRelativePosition.GetZ() + p.d;\n\n if (signedDist < -radius)\n {\n return false;\n }\n }\n\n return true;\n }\n }\n\n PoiRingController::PoiRingController(MyPinCreation::SdkModel::IMyPinCreationModel& myPinCreationModel,\n PoiRingView& poiRingView,\n Eegeo::Rendering::EnvironmentFlatteningService& environmentFlatteningService,\n Eegeo::Resources::Terrain::Heights::TerrainHeightProvider& terrainHeightProvider,\n Eegeo::Resources::Interiors::InteriorController& interiorController,\n Eegeo::Rendering::ScreenProperties& screenProperties)\n : m_myPinCreationModel(myPinCreationModel)\n , m_poiRingView(poiRingView)\n , m_scaleInterpolationParam(0.f)\n , m_easeDurationInSeconds(1.2f)\n , m_environmentFlatteningService(environmentFlatteningService)\n , m_terrainHeightProvider(terrainHeightProvider)\n , m_iconPosition(Eegeo::dv3::Zero())\n , m_iconSize(0.0f)\n , m_ringRadius(0.0f)\n , m_interiorController(interiorController)\n , m_screenProperties(screenProperties)\n {\n\n }\n\n void PoiRingController::Update(float dt, const Eegeo::Camera::RenderCamera& renderCamera, const Eegeo::dv3& cameraEcefInterestPoint)\n {\n const bool showingInterior = m_interiorController.InteriorIsVisible();\n float interiorDownScale = showingInterior ? 0.5f : 1.0f;\n const float altitude = (float)(renderCamera.GetAltitude() - (m_myPinCreationModel.GetPosition().Length() - Eegeo::Space::EarthConstants::Radius));\n const float outerRingRadiusInMeters = 120.f * interiorDownScale;\n const float altitudeScale = CalculateAltitudeBasedSphereOuterScale(altitude);\n const float transitionScale = CalculateTransitionScale(dt);\n m_ringRadius = outerRingRadiusInMeters * altitudeScale * transitionScale;\n \n const bool ringIsOnScreen = RingIsOnScreen(renderCamera, m_myPinCreationModel.GetPosition(), m_ringRadius);\n\n m_poiRingView.SetShouldRenderRing(m_scaleInterpolationParam > 0.f && ringIsOnScreen);\n\n if (m_myPinCreationModel.GetCreationStage() == Inactive && !ringIsOnScreen)\n {\n m_scaleInterpolationParam = 0.f;\n }\n\n if (m_scaleInterpolationParam < 0.01f && m_myPinCreationModel.GetCreationStage() != Details)\n {\n m_myPinCreationModel.SetPosition(cameraEcefInterestPoint);\n }\n\n if(m_myPinCreationModel.NeedsTerrainHeight())\n {\n float terrainHeight;\n if(m_terrainHeightProvider.TryGetHeight(m_myPinCreationModel.GetPosition(), 11, terrainHeight))\n {\n m_myPinCreationModel.SetTerrainHeight(terrainHeight);\n }\n }\n \n if(m_myPinCreationModel.GetCreationStage() == Ring)\n {\n m_myPinCreationModel.SetInterior(showingInterior);\n if(showingInterior)\n {\n const Eegeo::Resources::Interiors::InteriorsModel *pModel = NULL;\n bool success = m_interiorController.TryGetCurrentModel(pModel);\n if(success)\n {\n const Eegeo::Resources::Interiors::InteriorId& buildingId = pModel->GetId();\n m_myPinCreationModel.SetBuildingId(buildingId);\n }\n\n m_myPinCreationModel.SetFloor(m_interiorController.GetCurrentFloorIndex());\n float floorHeightAboveSeaLevel = Helpers::InteriorHeightHelpers::GetFloorHeightAboveSeaLevel(*pModel, m_interiorController.GetCurrentFloorIndex());\n const float floorHeightAboveTerrain = floorHeightAboveSeaLevel - m_myPinCreationModel.GetTerrainHeight();\n m_myPinCreationModel.SetHeightAboveTerrain(floorHeightAboveTerrain);\n }\n else\n {\n m_myPinCreationModel.SetHeightAboveTerrain(0);\n }\n }\n\n Eegeo::m44 sphereTransformMatrix;\n sphereTransformMatrix.Scale(m_ringRadius);\n\n Eegeo::dv3 scaledPoint = Eegeo::Rendering::EnvironmentFlatteningService::GetScaledPointEcef(m_myPinCreationModel.GetPosition(), m_environmentFlatteningService.GetCurrentScale());\n\n Eegeo::dv3 cameraRelativePosition = scaledPoint - renderCamera.GetEcefLocation();\n sphereTransformMatrix.SetRow(3, Eegeo::v4(cameraRelativePosition.ToSingle(), 1.f));\n\n m_poiRingView.SetRingTransforms(sphereTransformMatrix);\n\n float altitudeBasedScale = CalculateAltitudeBasedSphereScale(altitude, m_ringRadius);\n m_poiRingView.SetInnerSphereScale(altitudeBasedScale);\n\n Eegeo::dv3 unflattenedIconPosition = m_myPinCreationModel.GetPosition();\n Eegeo::dv3 iconPosition = Eegeo::Rendering::EnvironmentFlatteningService::GetScaledPointEcef(\n unflattenedIconPosition,\n m_environmentFlatteningService.GetCurrentScale());\n\n const float assetSize = 75.f;\n const float iconScale = Eegeo::Helpers::TransformHelpers::ComputeModelScaleForConstantScreenSizeWithVerticalFoV(renderCamera, iconPosition) \/ (m_screenProperties.GetScreenHeight()* 0.5f)*m_screenProperties.GetPixelScale() * assetSize;\n \n m_iconSize = Eegeo::Max(iconScale * transitionScale, 0.0f);\n m_poiRingView.AddIconSprite(renderCamera, iconPosition, m_iconSize);\n\n m_iconPosition = iconPosition + (Eegeo::dv3)renderCamera.GetModelMatrix().GetRow(1) * m_iconSize * 0.5f;\n }\n\n float PoiRingController::CalculateTransitionScale(float dt)\n {\n float delta = m_myPinCreationModel.GetCreationStage() == Ring ? dt : -dt;\n delta \/= m_easeDurationInSeconds;\n m_scaleInterpolationParam = Eegeo::Clamp(m_scaleInterpolationParam + delta, 0.f, 1.f);\n return Eegeo::Helpers::MathsHelpers::PennerElasticEaseInOut(0.f, 1.f, m_scaleInterpolationParam);\n }\n\n void PoiRingController::GetIconPositionAndSize(Eegeo::dv3& out_positionEcef, float& out_sizeMeters) const\n {\n out_positionEcef = m_iconPosition;\n out_sizeMeters = m_iconSize;\n }\n \n void PoiRingController::GetSpherePositionAndRadius(Eegeo::dv3& out_sphereCenterEcef, float& out_sphereRadius) const\n {\n out_sphereCenterEcef = m_myPinCreationModel.GetPosition();\n out_sphereRadius = m_ringRadius;\n }\n }\n }\n }\n}\nFix for https:\/\/bugs.eegeo.com\/browse\/MPLY-6031 - mitigate error in PinCreationModel, where PoiRingController SetHeightAboveTerrain causes refresh of position with invalid cached height. Must go back and fix PinCreationModel internals. Discussed with TJ and FM, buddy: MB.\/\/ Copyright eeGeo Ltd (2012-2015), All Rights Reserved\n\n#include \"PoiRingController.h\"\n#include \"InteriorsFloorModel.h\"\n#include \"InteriorsModel.h\"\n#include \"InteriorId.h\"\n#include \"TtyHandler.h\"\n#include \"CameraHelpers.h\"\n#include \"RenderCamera.h\"\n#include \"IRayPicker.h\"\n#include \"PoiRingView.h\"\n#include \"RenderContext.h\"\n#include \"MathFunc.h\"\n#include \"MathsHelpers.h\"\n#include \"IMyPinCreationInitiationViewModel.h\"\n#include \"IMyPinCreationModel.h\"\n#include \"EarthConstants.h\"\n#include \"TerrainHeightProvider.h\"\n#include \"TransformHelpers.h\"\n#include \"VectorMath.h\"\n#include \"InteriorController.h\"\n\n#include \"InteriorHeightHelpers.h\"\n#include \"ScreenProperties.h\"\n\nnamespace ExampleApp\n{\n namespace MyPinCreation\n {\n namespace PoiRing\n {\n namespace SdkModel\n {\n namespace\n {\n \n float CalculateAltitudeBasedSphereOuterScale(float altitude)\n {\n const float minAltitude = 50.f;\n const float maxAltitude = 1500.f;\n const float lowAltitudeScale = 0.05f;\n const float highAltitudeScale = 1.0f;\n float t = Eegeo::Math::Clamp01((altitude - minAltitude)\/(maxAltitude-minAltitude));\n return Eegeo::Math::Lerp(lowAltitudeScale, highAltitudeScale, t);\n }\n \n float CalculateAltitudeBasedSphereScale(float altitude, float outerRingRadiusInMeters)\n {\n const float minAltitude = 100.f;\n const float maxAltitude = 18000.f;\n const float lowAltitudeSphereScale = outerRingRadiusInMeters - 0.5f;\n const float highAltitudeSphereScale = outerRingRadiusInMeters - 100.f;\n return lowAltitudeSphereScale + (((altitude - minAltitude)\/maxAltitude) * (highAltitudeSphereScale - lowAltitudeSphereScale));\n }\n\n bool RingIsOnScreen(const Eegeo::Camera::RenderCamera& renderCamera, const Eegeo::dv3& position, float radius)\n {\n const Eegeo::Geometry::Frustum& frustum = renderCamera.GetFrustum();\n const Eegeo::dv3 cameraRelativePosition = position - renderCamera.GetEcefLocation();\n\n for (int i = 0; i < Eegeo::Geometry::Frustum::PLANES_COUNT; ++i)\n {\n const Eegeo::Geometry::Plane& p = frustum.planes[i];\n double signedDist = p.a * cameraRelativePosition.GetX() + p.b * cameraRelativePosition.GetY() + p.c * cameraRelativePosition.GetZ() + p.d;\n\n if (signedDist < -radius)\n {\n return false;\n }\n }\n\n return true;\n }\n }\n\n PoiRingController::PoiRingController(MyPinCreation::SdkModel::IMyPinCreationModel& myPinCreationModel,\n PoiRingView& poiRingView,\n Eegeo::Rendering::EnvironmentFlatteningService& environmentFlatteningService,\n Eegeo::Resources::Terrain::Heights::TerrainHeightProvider& terrainHeightProvider,\n Eegeo::Resources::Interiors::InteriorController& interiorController,\n Eegeo::Rendering::ScreenProperties& screenProperties)\n : m_myPinCreationModel(myPinCreationModel)\n , m_poiRingView(poiRingView)\n , m_scaleInterpolationParam(0.f)\n , m_easeDurationInSeconds(1.2f)\n , m_environmentFlatteningService(environmentFlatteningService)\n , m_terrainHeightProvider(terrainHeightProvider)\n , m_iconPosition(Eegeo::dv3::Zero())\n , m_iconSize(0.0f)\n , m_ringRadius(0.0f)\n , m_interiorController(interiorController)\n , m_screenProperties(screenProperties)\n {\n\n }\n\n void PoiRingController::Update(float dt, const Eegeo::Camera::RenderCamera& renderCamera, const Eegeo::dv3& cameraEcefInterestPoint)\n {\n const bool showingInterior = m_interiorController.InteriorIsVisible();\n float interiorDownScale = showingInterior ? 0.5f : 1.0f;\n const float altitude = (float)(renderCamera.GetAltitude() - (m_myPinCreationModel.GetPosition().Length() - Eegeo::Space::EarthConstants::Radius));\n const float outerRingRadiusInMeters = 120.f * interiorDownScale;\n const float altitudeScale = CalculateAltitudeBasedSphereOuterScale(altitude);\n const float transitionScale = CalculateTransitionScale(dt);\n m_ringRadius = outerRingRadiusInMeters * altitudeScale * transitionScale;\n \n const bool ringIsOnScreen = RingIsOnScreen(renderCamera, m_myPinCreationModel.GetPosition(), m_ringRadius);\n\n m_poiRingView.SetShouldRenderRing(m_scaleInterpolationParam > 0.f && ringIsOnScreen);\n\n if (m_myPinCreationModel.GetCreationStage() == Inactive && !ringIsOnScreen)\n {\n m_scaleInterpolationParam = 0.f;\n }\n\n if (m_scaleInterpolationParam < 0.01f && m_myPinCreationModel.GetCreationStage() != Details)\n {\n m_myPinCreationModel.SetPosition(cameraEcefInterestPoint);\n }\n\n if(m_myPinCreationModel.NeedsTerrainHeight())\n {\n float terrainHeight;\n if(m_terrainHeightProvider.TryGetHeight(m_myPinCreationModel.GetPosition(), 11, terrainHeight))\n {\n m_myPinCreationModel.SetTerrainHeight(terrainHeight);\n }\n }\n \n if(m_myPinCreationModel.GetCreationStage() == Ring)\n {\n m_myPinCreationModel.SetInterior(showingInterior);\n if(showingInterior)\n {\n const Eegeo::Resources::Interiors::InteriorsModel *pModel = NULL;\n bool success = m_interiorController.TryGetCurrentModel(pModel);\n if(success)\n {\n const Eegeo::Resources::Interiors::InteriorId& buildingId = pModel->GetId();\n m_myPinCreationModel.SetBuildingId(buildingId);\n }\n\n m_myPinCreationModel.SetFloor(m_interiorController.GetCurrentFloorIndex());\n float floorHeightAboveSeaLevel = Helpers::InteriorHeightHelpers::GetFloorHeightAboveSeaLevel(*pModel, m_interiorController.GetCurrentFloorIndex());\n const float floorHeightAboveTerrain = floorHeightAboveSeaLevel - m_myPinCreationModel.GetTerrainHeight();\n m_myPinCreationModel.SetHeightAboveTerrain(floorHeightAboveTerrain);\n }\n }\n\n Eegeo::m44 sphereTransformMatrix;\n sphereTransformMatrix.Scale(m_ringRadius);\n\n Eegeo::dv3 scaledPoint = Eegeo::Rendering::EnvironmentFlatteningService::GetScaledPointEcef(m_myPinCreationModel.GetPosition(), m_environmentFlatteningService.GetCurrentScale());\n\n Eegeo::dv3 cameraRelativePosition = scaledPoint - renderCamera.GetEcefLocation();\n sphereTransformMatrix.SetRow(3, Eegeo::v4(cameraRelativePosition.ToSingle(), 1.f));\n\n m_poiRingView.SetRingTransforms(sphereTransformMatrix);\n\n float altitudeBasedScale = CalculateAltitudeBasedSphereScale(altitude, m_ringRadius);\n m_poiRingView.SetInnerSphereScale(altitudeBasedScale);\n\n Eegeo::dv3 unflattenedIconPosition = m_myPinCreationModel.GetPosition();\n Eegeo::dv3 iconPosition = Eegeo::Rendering::EnvironmentFlatteningService::GetScaledPointEcef(\n unflattenedIconPosition,\n m_environmentFlatteningService.GetCurrentScale());\n\n const float assetSize = 75.f;\n const float iconScale = Eegeo::Helpers::TransformHelpers::ComputeModelScaleForConstantScreenSizeWithVerticalFoV(renderCamera, iconPosition) \/ (m_screenProperties.GetScreenHeight()* 0.5f)*m_screenProperties.GetPixelScale() * assetSize;\n \n m_iconSize = Eegeo::Max(iconScale * transitionScale, 0.0f);\n m_poiRingView.AddIconSprite(renderCamera, iconPosition, m_iconSize);\n\n m_iconPosition = iconPosition + (Eegeo::dv3)renderCamera.GetModelMatrix().GetRow(1) * m_iconSize * 0.5f;\n }\n\n float PoiRingController::CalculateTransitionScale(float dt)\n {\n float delta = m_myPinCreationModel.GetCreationStage() == Ring ? dt : -dt;\n delta \/= m_easeDurationInSeconds;\n m_scaleInterpolationParam = Eegeo::Clamp(m_scaleInterpolationParam + delta, 0.f, 1.f);\n return Eegeo::Helpers::MathsHelpers::PennerElasticEaseInOut(0.f, 1.f, m_scaleInterpolationParam);\n }\n\n void PoiRingController::GetIconPositionAndSize(Eegeo::dv3& out_positionEcef, float& out_sizeMeters) const\n {\n out_positionEcef = m_iconPosition;\n out_sizeMeters = m_iconSize;\n }\n \n void PoiRingController::GetSpherePositionAndRadius(Eegeo::dv3& out_sphereCenterEcef, float& out_sphereRadius) const\n {\n out_sphereCenterEcef = m_myPinCreationModel.GetPosition();\n out_sphereRadius = m_ringRadius;\n }\n }\n }\n }\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2008, Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"config.h\"\n\n#include \"webkit\/glue\/npruntime_util.h\"\n\n\/\/ Import the definition of PrivateIdentifier\n#if USE(V8_BINDING)\n#include \"webkit\/port\/bindings\/v8\/np_v8object.h\"\n#elif USE(JAVASCRIPTCORE_BINDINGS)\n#include \"third_party\/npapi\/bindings\/c\/c_utility.h\"\nusing KJS::Bindings::PrivateIdentifier;\n#endif\n\n#include \"base\/pickle.h\"\n\nnamespace webkit_glue {\n\nbool SerializeNPIdentifier(NPIdentifier identifier, Pickle* pickle) {\n PrivateIdentifier* priv = static_cast(identifier);\n\n \/\/ If the identifier was null, then we just send a numeric 0. This is to\n \/\/ support cases where the other end doesn't care about the NPIdentifier\n \/\/ being serialized, so the bogus value of 0 is really inconsequential.\n PrivateIdentifier null_id;\n if (!priv) {\n priv = &null_id;\n priv->isString = false;\n priv->value.number = 0;\n }\n\n if (!pickle->WriteBool(priv->isString))\n return false;\n if (priv->isString) {\n \/\/ Write the null byte for efficiency on the other end.\n return pickle->WriteData(\n priv->value.string, strlen(priv->value.string) + 1);\n }\n return pickle->WriteInt(priv->value.number);\n}\n\nbool DeserializeNPIdentifier(const Pickle& pickle, void** pickle_iter,\n NPIdentifier* identifier) {\n bool is_string;\n if (!pickle.ReadBool(pickle_iter, &is_string))\n return false;\n\n if (is_string) {\n const char* data;\n int data_len;\n if (!pickle.ReadData(pickle_iter, &data, &data_len))\n return false;\n DCHECK_EQ(data_len, strlen(data) + 1);\n *identifier = NPN_GetStringIdentifier(data);\n } else {\n int number;\n if (!pickle.ReadInt(pickle_iter, &number))\n return false;\n *identifier = NPN_GetIntIdentifier(number);\n }\n return true;\n}\n\n} \/\/ namespace webkit_glue\nRevert my change for c_utility so that the JSC build will compile\/\/ Copyright 2008, Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"config.h\"\n\n#include \"webkit\/glue\/npruntime_util.h\"\n\n\/\/ Import the definition of PrivateIdentifier\n#if USE(V8_BINDING)\n#include \"webkit\/port\/bindings\/v8\/np_v8object.h\"\n#elif USE(JAVASCRIPTCORE_BINDINGS)\n#include \"bindings\/c\/c_utility.h\"\nusing KJS::Bindings::PrivateIdentifier;\n#endif\n\n#include \"base\/pickle.h\"\n\nnamespace webkit_glue {\n\nbool SerializeNPIdentifier(NPIdentifier identifier, Pickle* pickle) {\n PrivateIdentifier* priv = static_cast(identifier);\n\n \/\/ If the identifier was null, then we just send a numeric 0. This is to\n \/\/ support cases where the other end doesn't care about the NPIdentifier\n \/\/ being serialized, so the bogus value of 0 is really inconsequential.\n PrivateIdentifier null_id;\n if (!priv) {\n priv = &null_id;\n priv->isString = false;\n priv->value.number = 0;\n }\n\n if (!pickle->WriteBool(priv->isString))\n return false;\n if (priv->isString) {\n \/\/ Write the null byte for efficiency on the other end.\n return pickle->WriteData(\n priv->value.string, strlen(priv->value.string) + 1);\n }\n return pickle->WriteInt(priv->value.number);\n}\n\nbool DeserializeNPIdentifier(const Pickle& pickle, void** pickle_iter,\n NPIdentifier* identifier) {\n bool is_string;\n if (!pickle.ReadBool(pickle_iter, &is_string))\n return false;\n\n if (is_string) {\n const char* data;\n int data_len;\n if (!pickle.ReadData(pickle_iter, &data, &data_len))\n return false;\n DCHECK_EQ(data_len, strlen(data) + 1);\n *identifier = NPN_GetStringIdentifier(data);\n } else {\n int number;\n if (!pickle.ReadInt(pickle_iter, &number))\n return false;\n *identifier = NPN_GetIntIdentifier(number);\n }\n return true;\n}\n\n} \/\/ namespace webkit_glue\n<|endoftext|>"} {"text":"\/*\n* blinkyBlocksSimulator.cpp\n*\n* Created on: 23 mars 2013\n* Author: dom\n*\/\n\n#include \n#include \"blinkyBlocksSimulator.h\"\n#include \n#include \"trace.h\"\n\nusing namespace std;\n\nnamespace BlinkyBlocks {\n\nBlinkyBlocksBlockCode*(* BlinkyBlocksSimulator::buildNewBlockCode)(BlinkyBlocksBlock*)=NULL;\n\nBlinkyBlocksSimulator::BlinkyBlocksSimulator(int argc, char *argv[], BlinkyBlocksBlockCode *(*blinkyBlocksBlockCodeBuildingFunction)(BlinkyBlocksBlock*)) : BaseSimulator::Simulator(argc, argv) {\n\tOUTPUT << \"\\033[1;34m\" << \"BlinkyBlocksSimulator constructor\" << \"\\033[0m\" << endl;\n\n\tint currentID = 1;\n\tBlinkyBlocksWorld *world = NULL;\n\tbuildNewBlockCode = blinkyBlocksBlockCodeBuildingFunction;\n\n\tTiXmlNode *node = xmlDoc->FirstChild(\"world\");\n\tif (node) {\n\t\tTiXmlElement* worldElement = node->ToElement();\n\t\tconst char *attr= worldElement->Attribute(\"gridsize\");\n\t\tint lx,ly,lz;\n\t\tif (attr) {\n\t\t\tstring str=attr;\n\t\t\tint pos1 = str.find_first_of(','),\n\t\t\t\tpos2 = str.find_last_of(',');\n\t\t\tlx = atoi(str.substr(0,pos1).c_str());\n\t\t\tly = atoi(str.substr(pos1+1,pos2-pos1-1).c_str());\n\t\t\tlz = atoi(str.substr(pos2+1,str.length()-pos1-1).c_str());\n\t\t\tOUTPUT << \"grid size : \" << lx << \" x \" << ly << \" x \" << lz << endl;\n\t\t} else {\n\t\t\tOUTPUT << \"WARNING No grid size in XML file\" << endl;\n\t\t}\n\t\tattr=worldElement->Attribute(\"windowSize\");\n\t\tif (attr) {\n\t\t\tstring str=attr;\n\t \t\tint pos = str.find_first_of(',');\n\t\t\tGlutContext::initialScreenWidth = atoi(str.substr(0,pos).c_str());\n\t\t\tGlutContext::initialScreenHeight = atoi(str.substr(pos+1,str.length()-pos-1).c_str());\n\t\t\tGlutContext::screenWidth = GlutContext::initialScreenWidth;\n\t\t\tGlutContext::screenHeight = GlutContext::initialScreenHeight;\n\t\t}\n\n\t\tcreateWorld(lx, ly, lz, argc, argv);\n\t\tworld = getWorld();\n\t\tworld->loadTextures(\"..\/..\/simulatorCore\/blinkyBlocksTextures\");\n\n\t} else {\n\t\tERRPUT << \"ERROR : NO world in XML file\" << endl;\n\t\texit(1);\n\t}\n\n\tcreateScheduler();\n\n\t\/\/ loading the camera parameters\n\tTiXmlNode *nodeConfig = node->FirstChild(\"camera\");\n\tif (nodeConfig) {\n\t\tTiXmlElement* cameraElement = nodeConfig->ToElement();\n\t\tconst char *attr=cameraElement->Attribute(\"target\");\n\t\tif (attr) {\n\t\t\tstring str(attr);\n\t\t\tint pos1 = str.find_first_of(','),\n\t\t\tpos2 = str.find_last_of(',');\n\t\t\tVecteur target;\n\t\t\ttarget.pt[0] = atof(str.substr(0,pos1).c_str());\n\t\t\ttarget.pt[1] = atof(str.substr(pos1+1,pos2-pos1-1).c_str());\n\t\t\ttarget.pt[2] = atof(str.substr(pos2+1,str.length()-pos1-1).c_str());\n\t\t\tworld->getCamera()->setTarget(target);\n\t\t}\n\t\tattr=cameraElement->Attribute(\"directionSpherical\");\n\t\tif (attr) {\n\t\t\tstring str(attr);\n\t\t\tint pos1 = str.find_first_of(','),\n\t\t\tpos2 = str.find_last_of(',');\n\t\t\tfloat az,ele,dist;\n\t\t\taz = -90.0+atof(str.substr(0,pos1).c_str());\n\t\t\tele = atof(str.substr(pos1+1,pos2-pos1-1).c_str());\n\t\t\tdist = atof(str.substr(pos2+1,str.length()-pos1-1).c_str());\n\t\t\tworld->getCamera()->setDirection(az,ele);\n\t\t\tworld->getCamera()->setDistance(dist);\n\t\t}\n\t\tattr=cameraElement->Attribute(\"angle\");\n\t\tif (attr) {\n\t\t\tfloat angle = atof(attr);\n\t\t\tworld->getCamera()->setAngle(angle);\n\t\t}\n\t\tdouble def_near=1,def_far=1500;\n\t\tattr=cameraElement->Attribute(\"near\");\n\t\tif (attr) {\n\t\t\tdef_near = atof(attr);\n\t\t}\n\t\tattr=cameraElement->Attribute(\"far\");\n\t\tif (attr) {\n\t\t\tdef_far = atof(attr);\n\t\t}\n\t\tworld->getCamera()->setNearFar(def_near,def_far);\n\t}\n\n\t\/\/ loading the spotlight parameters\n\tnodeConfig = node->FirstChild(\"spotlight\");\n\tif (nodeConfig) {\n\t\tVecteur target;\n\t\tfloat az=0,ele=60,dist=1000,angle=50;\n\t\tTiXmlElement* lightElement = nodeConfig->ToElement();\n\t\tconst char *attr=lightElement->Attribute(\"target\");\n\t\tif (attr) {\n\t\t\tstring str(attr);\n\t\t\tint pos1 = str.find_first_of(','),\n\t\t\tpos2 = str.find_last_of(',');\n\t\t\ttarget.pt[0] = atof(str.substr(0,pos1).c_str());\n\t\t\ttarget.pt[1] = atof(str.substr(pos1+1,pos2-pos1-1).c_str());\n\t\t\ttarget.pt[2] = atof(str.substr(pos2+1,str.length()-pos1-1).c_str());\n\t\t}\n\t\tattr=lightElement->Attribute(\"directionSpherical\");\n\t\tif (attr) {\n\t\t\tstring str(attr);\n\t\t\tint pos1 = str.find_first_of(','),\n\t\t\tpos2 = str.find_last_of(',');\n\t\t\taz = -90.0+atof(str.substr(0,pos1).c_str());\n\t\t\tele = atof(str.substr(pos1+1,pos2-pos1-1).c_str());\n\t\t\tdist = atof(str.substr(pos2+1,str.length()-pos1-1).c_str());\n\t\t}\n\t\tattr=lightElement->Attribute(\"angle\");\n\t\tif (attr) {\n\t\t\tangle = atof(attr);\n\t\t}\n\t\tfloat farplane=2.0*dist*tan(angle*M_PI\/180.0);\n\t\tworld->getCamera()->setLightParameters(target,az,ele,dist,angle,10.0,farplane);\n\n\t}\n\n\t\/\/ loading the blocks\n\tTiXmlNode *nodeBlock = node->FirstChild(\"blockList\");\n\tif (nodeBlock) {\n\t\tColor defaultColor = DARKGREY;\n\t\tTiXmlElement* element = nodeBlock->ToElement();\n\t\tconst char *attr= element->Attribute(\"color\");\n\t\tif (attr) {\n\t\t\tstring str(attr);\n\t\t\tint pos1 = str.find_first_of(','),\n\t\t\tpos2 = str.find_last_of(',');\n\t\t\tdefaultColor.rgba[0] = atof(str.substr(0,pos1).c_str())\/255.0;\n\t\t\tdefaultColor.rgba[1] = atof(str.substr(pos1+1,pos2-pos1-1).c_str())\/255.0;\n\t\t\tdefaultColor.rgba[2] = atof(str.substr(pos2+1,str.length()-pos1-1).c_str())\/255.0;\n\t\t}\n\t\tattr= element->Attribute(\"blocksize\");\n\t\tif (attr) {\n\t\t\tstring str(attr);\n\t\t\tint pos1 = str.find_first_of(','),\n\t\t\tpos2 = str.find_last_of(',');\n\t\t\tfloat siz[3];\n\t\t\tsiz[0] = atof(str.substr(0,pos1).c_str());\n\t\t\tsiz[1] = atof(str.substr(pos1+1,pos2-pos1-1).c_str());\n\t\t\tsiz[2] = atof(str.substr(pos2+1,str.length()-pos1-1).c_str());\n\t\t\tOUTPUT << \"blocksize =\" << siz[0] <<\",\" << siz[1] <<\",\" << siz[2]<< endl;\n\t\t\tworld->setBlocksSize(siz);\n\t\t}\n\n\t\t\/* Reading a blinkyblock *\/\n\t\tOUTPUT << \"default color :\" << defaultColor << endl;\n\t\tnodeBlock = nodeBlock->FirstChild(\"block\");\n\t\tVecteur position;\n\t\tColor color;\n\t\twhile (nodeBlock) {\n\t\t\telement = nodeBlock->ToElement();\n\t\t\tcolor=defaultColor;\n\t\t\tattr = element->Attribute(\"color\");\n\t\t\tif (attr) {\n\t\t\t\tstring str(attr);\n\t\t\t\tint pos1 = str.find_first_of(','),\n\t\t\t\tpos2 = str.find_last_of(',');\n\t\t\t\t color.set(atof(str.substr(0,pos1).c_str())\/255.0,\n atof(str.substr(pos1+1,pos2-pos1-1).c_str())\/255.0,\n atof(str.substr(pos2+1,str.length()-pos1-1).c_str())\/255.0);\n\t\t\t\tOUTPUT << \"color :\" << color << endl;\n\t\t\t}\n\t\t\tattr = element->Attribute(\"position\");\n\t\t\tif (attr) {\n\t\t\t\tstring str(attr);\n\t\t\t\tint pos1 = str.find_first_of(','),\n\t\t\t\tpos2 = str.find_last_of(',');\n\t\t\t\tposition.pt[0] = atoi(str.substr(0,pos1).c_str());\n\t\t\t\tposition.pt[1] = atoi(str.substr(pos1+1,pos2-pos1-1).c_str());\n\t\t\t\tposition.pt[2] = atoi(str.substr(pos2+1,str.length()-pos1-1).c_str());\n\t\t\t\tOUTPUT << \"position : \" << position << endl;\n\t\t\t}\n\t\t\tworld->addBlock(currentID++, BlinkyBlocksSimulator::buildNewBlockCode, position, color);\n\t\t\tnodeBlock = nodeBlock->NextSibling(\"block\");\n\t\t} \/\/ end while (nodeBlock)\n\t} else { \/\/ end if(nodeBlock)\n\t\tERRPUT << \"no Block List\" << endl;\n\t}\n\n\t\/\/ loading the scenario\n\tTiXmlNode *nodeScenario = node->FirstChild(\"scenario\");\n\tif (nodeScenario) {\n\t\tbool autostart=false;\n\t\tTiXmlElement* element = nodeScenario->ToElement();\n\t\tconst char *attr= element->Attribute(\"autostart\");\n\t\tif (attr) {\n\t\t\tstring str(attr);\n\t\t\tautostart=(str==\"True\" || str==\"true\");\n\t\t}\n\t\tOUTPUT << \"SCENARIO: Autostart=\" << autostart << endl;\n\t\t\/* Reading an event *\/\n\t\tnodeScenario = nodeScenario->FirstChild(\"event\");\n\t\tfloat eventTime =0.0;\n\t\tint eventBlockId=-1;\n\t\twhile (nodeScenario) {\n\t\t\telement = nodeScenario->ToElement();\n\t\t\tattr = element->Attribute(\"time\");\n\t\t\tif (attr) {\n\t\t\t\teventTime = atof(attr);\n\t\t\t}\n\t\t\tattr = element->Attribute(\"type\");\n\t\t\tif (attr) {\n\t\t\t\tstring strAttr(attr);\n\t\t\t\tif (strAttr==\"tap\") {\n\t\t\t\t\tattr = element->Attribute(\"id\");\n\t\t\t\t\teventBlockId=-1;\n\t\t\t\t\tif (attr) {\n\t\t\t\t\t\teventBlockId=atoi(attr);\n\t\t\t\t\t}\n\t\t\t\t\tif (eventBlockId==-1) {\n\t\t\t\t\t\tERRPUT << \"SCENARIO:No id for tap event\" << endl;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tOUTPUT << \"SCENARIO: tap(\" << eventTime << \",\" << eventBlockId << \")\" << endl;\n\t\t\t\t\t\tworld->addScenarioEvent(new ScenarioTappEvent(eventTime,eventBlockId));\n\t\t\t\t\t}\n\t\t\t\t} else if (strAttr==\"debug\") {\n\t\t\t\t\tattr = element->Attribute(\"id\");\n\t\t\t\t\tbool open=true;\n\t\t\t\t\tif (attr) {\n\t\t\t\t\t\tstring str(attr);\n\t\t\t\t\t\topen = (str==\"true\" || str==\"True\");\n\t\t\t\t\t}\n\t\t\t\t\tOUTPUT << \"SCENARIO: debug(\" << eventTime << \",\" << open << \")\" << endl;\n\t\t\t\t\tworld->addScenarioEvent(new ScenarioDebugEvent(eventTime,open));\n\t\t\t\t} else if (strAttr==\"selectBlock\") {\n\t\t\t\t\tattr = element->Attribute(\"id\");\n\t\t\t\t\teventBlockId=-1;\n\t\t\t\t\tif (attr) {\n\t\t\t\t\t\teventBlockId=atoi(attr);\n\t\t\t\t\t}\n\t\t\t\t\tOUTPUT << \"SCENARIO: selectBlock(\" << eventTime << \",\" << eventBlockId << \")\" << endl;\n\t\t\t\t\tworld->addScenarioEvent(new ScenarioSelectBlockEvent(eventTime,eventBlockId));\n\t\t\t\t} else if (strAttr==\"addBlock\") {\n\t\t\t\t\tattr = element->Attribute(\"position\");\n\t\t\t\t\tif (attr) {\n\t\t\t\t\t\tstring str(attr);\n\t\t\t\t\t\tint pos1 = str.find_first_of(','),\n\t\t\t\t\t\tpos2 = str.find_last_of(',');\n\t\t\t\t\t\tVecteur position;\n\t\t\t\t\t\tposition.pt[0] = atoi(str.substr(0,pos1).c_str());\n\t\t\t\t\t\tposition.pt[1] = atoi(str.substr(pos1+1,pos2-pos1-1).c_str());\n\t\t\t\t\t\tposition.pt[2] = atoi(str.substr(pos2+1,str.length()-pos1-1).c_str());\n\t\t\t\t\t\tOUTPUT << \"SCENARIO: addBlock(\" << eventTime << \",\" << position << \")\" << endl;\n\t\t\t\t\t\tworld->addScenarioEvent(new ScenarioAddBlockEvent(eventTime,position));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tERRPUT << \"SCENARIO: No position for addBlock event\" << endl;\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\t\t\t\t\tERRPUT << \"SCENARIO: event '\" << attr << \"': unknown !\" << endl;\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tERRPUT << \"SCENARIO: no Event type \" << endl;\n\t\t\t}\n\t\t\tnodeScenario = nodeScenario->NextSibling(\"event\");\n\t\t} \/\/ while(nodeScenario)\n\t}\n\tworld->linkBlocks();\n\n\t\/\/getScheduler()->sem_schedulerStart->post();\n\tgetScheduler()->setState(Scheduler::NOTSTARTED);\n\n\tGlutContext::mainLoop();\n\n}\n\nBlinkyBlocksSimulator::~BlinkyBlocksSimulator() {\n\tOUTPUT << \"\\033[1;34m\" << \"BlinkyBlocksSimulator destructor\" << \"\\033[0m\" <Add some comment reminders to BB files to mark locations needing to be checked for conflicts\/*\n* blinkyBlocksSimulator.cpp\n*\n* Created on: 23 mars 2013\n* Author: dom\n*\/\n\n#include \n#include \"blinkyBlocksSimulator.h\"\n#include \n#include \"trace.h\"\n\nusing namespace std;\n\nnamespace BlinkyBlocks {\n\nBlinkyBlocksBlockCode*(* BlinkyBlocksSimulator::buildNewBlockCode)(BlinkyBlocksBlock*)=NULL;\n\nBlinkyBlocksSimulator::BlinkyBlocksSimulator(int argc, char *argv[], BlinkyBlocksBlockCode *(*blinkyBlocksBlockCodeBuildingFunction)(BlinkyBlocksBlock*)) : BaseSimulator::Simulator(argc, argv) {\n\tOUTPUT << \"\\033[1;34m\" << \"BlinkyBlocksSimulator constructor\" << \"\\033[0m\" << endl;\n\n\tint currentID = 1;\n\tBlinkyBlocksWorld *world = NULL;\n\tbuildNewBlockCode = blinkyBlocksBlockCodeBuildingFunction;\n\n \/\/ PThy: Reading the command line may be needed at this time to enable debugging.\n \n\tTiXmlNode *node = xmlDoc->FirstChild(\"world\");\n if (node) {\n\t\tTiXmlElement* worldElement = node->ToElement();\n\t\tconst char *attr= worldElement->Attribute(\"gridsize\");\n\t\tint lx,ly,lz;\n\t\tif (attr) {\n\t\t\tstring str=attr;\n\t\t\tint pos1 = str.find_first_of(','),\n\t\t\t\tpos2 = str.find_last_of(',');\n\t\t\tlx = atoi(str.substr(0,pos1).c_str());\n\t\t\tly = atoi(str.substr(pos1+1,pos2-pos1-1).c_str());\n\t\t\tlz = atoi(str.substr(pos2+1,str.length()-pos1-1).c_str());\n\t\t\tOUTPUT << \"grid size : \" << lx << \" x \" << ly << \" x \" << lz << endl;\n\t\t} else {\n\t\t\tOUTPUT << \"WARNING No grid size in XML file\" << endl;\n\t\t}\n\t\tattr=worldElement->Attribute(\"windowSize\");\n\t\tif (attr) {\n\t\t\tstring str=attr;\n\t \t\tint pos = str.find_first_of(',');\n\t\t\tGlutContext::initialScreenWidth = atoi(str.substr(0,pos).c_str());\n\t\t\tGlutContext::initialScreenHeight = atoi(str.substr(pos+1,str.length()-pos-1).c_str());\n\t\t\tGlutContext::screenWidth = GlutContext::initialScreenWidth;\n\t\t\tGlutContext::screenHeight = GlutContext::initialScreenHeight;\n\t\t}\n\n\t\tcreateWorld(lx, ly, lz, argc, argv);\n\t\tworld = getWorld();\n\t\tworld->loadTextures(\"..\/..\/simulatorCore\/blinkyBlocksTextures\");\n\n\t} else {\n\t\tERRPUT << \"ERROR : NO world in XML file\" << endl;\n\t\texit(1);\n\t}\n\n\tcreateScheduler();\n\n \/\/ Pthy: Not sure if we should be keeping that debugging part, perhaps it has to be located somewhere else now that MeldInterpreter has been embedded into VSim\n\/\/ if(debugging) {\n\/\/\t\tcreateDebugger();\n\/\/\t}\n\n\t\/\/ loading the camera parameters\n\tTiXmlNode *nodeConfig = node->FirstChild(\"camera\");\n\tif (nodeConfig) {\n\t\tTiXmlElement* cameraElement = nodeConfig->ToElement();\n\t\tconst char *attr=cameraElement->Attribute(\"target\");\n\t\tif (attr) {\n\t\t\tstring str(attr);\n\t\t\tint pos1 = str.find_first_of(','),\n\t\t\tpos2 = str.find_last_of(',');\n\t\t\tVecteur target;\n\t\t\ttarget.pt[0] = atof(str.substr(0,pos1).c_str());\n\t\t\ttarget.pt[1] = atof(str.substr(pos1+1,pos2-pos1-1).c_str());\n\t\t\ttarget.pt[2] = atof(str.substr(pos2+1,str.length()-pos1-1).c_str());\n\t\t\tworld->getCamera()->setTarget(target);\n\t\t}\n\t\tattr=cameraElement->Attribute(\"directionSpherical\");\n\t\tif (attr) {\n\t\t\tstring str(attr);\n\t\t\tint pos1 = str.find_first_of(','),\n\t\t\tpos2 = str.find_last_of(',');\n\t\t\tfloat az,ele,dist;\n\t\t\taz = -90.0+atof(str.substr(0,pos1).c_str());\n\t\t\tele = atof(str.substr(pos1+1,pos2-pos1-1).c_str());\n\t\t\tdist = atof(str.substr(pos2+1,str.length()-pos1-1).c_str());\n\t\t\tworld->getCamera()->setDirection(az,ele);\n\t\t\tworld->getCamera()->setDistance(dist);\n\t\t}\n\t\tattr=cameraElement->Attribute(\"angle\");\n\t\tif (attr) {\n\t\t\tfloat angle = atof(attr);\n\t\t\tworld->getCamera()->setAngle(angle);\n\t\t}\n\t\tdouble def_near=1,def_far=1500;\n\t\tattr=cameraElement->Attribute(\"near\");\n\t\tif (attr) {\n\t\t\tdef_near = atof(attr);\n\t\t}\n\t\tattr=cameraElement->Attribute(\"far\");\n\t\tif (attr) {\n\t\t\tdef_far = atof(attr);\n\t\t}\n\t\tworld->getCamera()->setNearFar(def_near,def_far);\n\t}\n\n\t\/\/ loading the spotlight parameters\n\tnodeConfig = node->FirstChild(\"spotlight\");\n\tif (nodeConfig) {\n\t\tVecteur target;\n\t\tfloat az=0,ele=60,dist=1000,angle=50;\n\t\tTiXmlElement* lightElement = nodeConfig->ToElement();\n\t\tconst char *attr=lightElement->Attribute(\"target\");\n\t\tif (attr) {\n\t\t\tstring str(attr);\n\t\t\tint pos1 = str.find_first_of(','),\n\t\t\tpos2 = str.find_last_of(',');\n\t\t\ttarget.pt[0] = atof(str.substr(0,pos1).c_str());\n\t\t\ttarget.pt[1] = atof(str.substr(pos1+1,pos2-pos1-1).c_str());\n\t\t\ttarget.pt[2] = atof(str.substr(pos2+1,str.length()-pos1-1).c_str());\n\t\t}\n\t\tattr=lightElement->Attribute(\"directionSpherical\");\n\t\tif (attr) {\n\t\t\tstring str(attr);\n\t\t\tint pos1 = str.find_first_of(','),\n\t\t\tpos2 = str.find_last_of(',');\n\t\t\taz = -90.0+atof(str.substr(0,pos1).c_str());\n\t\t\tele = atof(str.substr(pos1+1,pos2-pos1-1).c_str());\n\t\t\tdist = atof(str.substr(pos2+1,str.length()-pos1-1).c_str());\n\t\t}\n\t\tattr=lightElement->Attribute(\"angle\");\n\t\tif (attr) {\n\t\t\tangle = atof(attr);\n\t\t}\n\t\tfloat farplane=2.0*dist*tan(angle*M_PI\/180.0);\n\t\tworld->getCamera()->setLightParameters(target,az,ele,dist,angle,10.0,farplane);\n\n\t}\n\n\t\/\/ loading the blocks\n\tTiXmlNode *nodeBlock = node->FirstChild(\"blockList\");\n\tif (nodeBlock) {\n\t\tColor defaultColor = DARKGREY;\n\t\tTiXmlElement* element = nodeBlock->ToElement();\n\t\tconst char *attr= element->Attribute(\"color\");\n\t\tif (attr) {\n\t\t\tstring str(attr);\n\t\t\tint pos1 = str.find_first_of(','),\n\t\t\tpos2 = str.find_last_of(',');\n\t\t\tdefaultColor.rgba[0] = atof(str.substr(0,pos1).c_str())\/255.0;\n\t\t\tdefaultColor.rgba[1] = atof(str.substr(pos1+1,pos2-pos1-1).c_str())\/255.0;\n\t\t\tdefaultColor.rgba[2] = atof(str.substr(pos2+1,str.length()-pos1-1).c_str())\/255.0;\n\t\t}\n\t\tattr= element->Attribute(\"blocksize\");\n\t\tif (attr) {\n\t\t\tstring str(attr);\n\t\t\tint pos1 = str.find_first_of(','),\n\t\t\tpos2 = str.find_last_of(',');\n\t\t\tfloat siz[3];\n\t\t\tsiz[0] = atof(str.substr(0,pos1).c_str());\n\t\t\tsiz[1] = atof(str.substr(pos1+1,pos2-pos1-1).c_str());\n\t\t\tsiz[2] = atof(str.substr(pos2+1,str.length()-pos1-1).c_str());\n\t\t\tOUTPUT << \"blocksize =\" << siz[0] <<\",\" << siz[1] <<\",\" << siz[2]<< endl;\n\t\t\tworld->setBlocksSize(siz);\n\t\t}\n\n\t\t\/* Reading a blinkyblock *\/\n\t\tOUTPUT << \"default color :\" << defaultColor << endl;\n\t\tnodeBlock = nodeBlock->FirstChild(\"block\");\n\t\tVecteur position;\n\t\tColor color;\n\t\twhile (nodeBlock) {\n\t\t\telement = nodeBlock->ToElement();\n\t\t\tcolor=defaultColor;\n\t\t\tattr = element->Attribute(\"color\");\n\t\t\tif (attr) {\n\t\t\t\tstring str(attr);\n\t\t\t\tint pos1 = str.find_first_of(','),\n\t\t\t\tpos2 = str.find_last_of(',');\n\t\t\t\t color.set(atof(str.substr(0,pos1).c_str())\/255.0,\n atof(str.substr(pos1+1,pos2-pos1-1).c_str())\/255.0,\n atof(str.substr(pos2+1,str.length()-pos1-1).c_str())\/255.0);\n\t\t\t\tOUTPUT << \"color :\" << color << endl;\n\t\t\t}\n\t\t\tattr = element->Attribute(\"position\");\n\t\t\tif (attr) {\n\t\t\t\tstring str(attr);\n\t\t\t\tint pos1 = str.find_first_of(','),\n\t\t\t\tpos2 = str.find_last_of(',');\n\t\t\t\tposition.pt[0] = atoi(str.substr(0,pos1).c_str());\n\t\t\t\tposition.pt[1] = atoi(str.substr(pos1+1,pos2-pos1-1).c_str());\n\t\t\t\tposition.pt[2] = atoi(str.substr(pos2+1,str.length()-pos1-1).c_str());\n\t\t\t\tOUTPUT << \"position : \" << position << endl;\n\t\t\t}\n\t\t\tworld->addBlock(currentID++, BlinkyBlocksSimulator::buildNewBlockCode, position, color);\n\t\t\tnodeBlock = nodeBlock->NextSibling(\"block\");\n\t\t} \/\/ end while (nodeBlock)\n\t} else { \/\/ end if(nodeBlock)\n\t\tERRPUT << \"no Block List\" << endl;\n\t}\n\n\t\/\/ loading the scenario\n\tTiXmlNode *nodeScenario = node->FirstChild(\"scenario\");\n\tif (nodeScenario) {\n\t\tbool autostart=false;\n\t\tTiXmlElement* element = nodeScenario->ToElement();\n\t\tconst char *attr= element->Attribute(\"autostart\");\n\t\tif (attr) {\n\t\t\tstring str(attr);\n\t\t\tautostart=(str==\"True\" || str==\"true\");\n\t\t}\n\t\tOUTPUT << \"SCENARIO: Autostart=\" << autostart << endl;\n\t\t\/* Reading an event *\/\n\t\tnodeScenario = nodeScenario->FirstChild(\"event\");\n\t\tfloat eventTime =0.0;\n\t\tint eventBlockId=-1;\n\t\twhile (nodeScenario) {\n\t\t\telement = nodeScenario->ToElement();\n\t\t\tattr = element->Attribute(\"time\");\n\t\t\tif (attr) {\n\t\t\t\teventTime = atof(attr);\n\t\t\t}\n\t\t\tattr = element->Attribute(\"type\");\n\t\t\tif (attr) {\n\t\t\t\tstring strAttr(attr);\n\t\t\t\tif (strAttr==\"tap\") {\n\t\t\t\t\tattr = element->Attribute(\"id\");\n\t\t\t\t\teventBlockId=-1;\n\t\t\t\t\tif (attr) {\n\t\t\t\t\t\teventBlockId=atoi(attr);\n\t\t\t\t\t}\n\t\t\t\t\tif (eventBlockId==-1) {\n\t\t\t\t\t\tERRPUT << \"SCENARIO:No id for tap event\" << endl;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tOUTPUT << \"SCENARIO: tap(\" << eventTime << \",\" << eventBlockId << \")\" << endl;\n\t\t\t\t\t\tworld->addScenarioEvent(new ScenarioTappEvent(eventTime,eventBlockId));\n\t\t\t\t\t}\n\t\t\t\t} else if (strAttr==\"debug\") {\n\t\t\t\t\tattr = element->Attribute(\"id\");\n\t\t\t\t\tbool open=true;\n\t\t\t\t\tif (attr) {\n\t\t\t\t\t\tstring str(attr);\n\t\t\t\t\t\topen = (str==\"true\" || str==\"True\");\n\t\t\t\t\t}\n\t\t\t\t\tOUTPUT << \"SCENARIO: debug(\" << eventTime << \",\" << open << \")\" << endl;\n\t\t\t\t\tworld->addScenarioEvent(new ScenarioDebugEvent(eventTime,open));\n\t\t\t\t} else if (strAttr==\"selectBlock\") {\n\t\t\t\t\tattr = element->Attribute(\"id\");\n\t\t\t\t\teventBlockId=-1;\n\t\t\t\t\tif (attr) {\n\t\t\t\t\t\teventBlockId=atoi(attr);\n\t\t\t\t\t}\n\t\t\t\t\tOUTPUT << \"SCENARIO: selectBlock(\" << eventTime << \",\" << eventBlockId << \")\" << endl;\n\t\t\t\t\tworld->addScenarioEvent(new ScenarioSelectBlockEvent(eventTime,eventBlockId));\n\t\t\t\t} else if (strAttr==\"addBlock\") {\n\t\t\t\t\tattr = element->Attribute(\"position\");\n\t\t\t\t\tif (attr) {\n\t\t\t\t\t\tstring str(attr);\n\t\t\t\t\t\tint pos1 = str.find_first_of(','),\n\t\t\t\t\t\tpos2 = str.find_last_of(',');\n\t\t\t\t\t\tVecteur position;\n\t\t\t\t\t\tposition.pt[0] = atoi(str.substr(0,pos1).c_str());\n\t\t\t\t\t\tposition.pt[1] = atoi(str.substr(pos1+1,pos2-pos1-1).c_str());\n\t\t\t\t\t\tposition.pt[2] = atoi(str.substr(pos2+1,str.length()-pos1-1).c_str());\n\t\t\t\t\t\tOUTPUT << \"SCENARIO: addBlock(\" << eventTime << \",\" << position << \")\" << endl;\n\t\t\t\t\t\tworld->addScenarioEvent(new ScenarioAddBlockEvent(eventTime,position));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tERRPUT << \"SCENARIO: No position for addBlock event\" << endl;\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\t\t\t\t\tERRPUT << \"SCENARIO: event '\" << attr << \"': unknown !\" << endl;\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tERRPUT << \"SCENARIO: no Event type \" << endl;\n\t\t\t}\n\t\t\tnodeScenario = nodeScenario->NextSibling(\"event\");\n\t\t} \/\/ while(nodeScenario)\n\t}\n\tworld->linkBlocks();\n\n\t\/\/getScheduler()->sem_schedulerStart->post();\n\tgetScheduler()->setState(Scheduler::NOTSTARTED);\n\n\tGlutContext::mainLoop();\n\n}\n\nBlinkyBlocksSimulator::~BlinkyBlocksSimulator() {\n\tOUTPUT << \"\\033[1;34m\" << \"BlinkyBlocksSimulator destructor\" << \"\\033[0m\" <"} {"text":"\/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/tpu\/tpu_embedding_optimization_parameters_utils.h\"\n#include \"tensorflow\/core\/lib\/core\/errors.h\"\n\nnamespace tensorflow {\nnamespace tpu {\n\nstring GetOptimizationAlgorithmName(OptimizationAlgorithm alg) {\n switch (alg) {\n case OptimizationAlgorithm::kAdagrad:\n return \"Adagrad\";\n case OptimizationAlgorithm::kStochasticGradientDescent:\n return \"StochasticGradientDescent\";\n case OptimizationAlgorithm::kFtrl:\n return \"FTRL\";\n case OptimizationAlgorithm::kAdam:\n return \"ADAM\";\n case OptimizationAlgorithm::kMomentum:\n return \"Momentum\";\n case OptimizationAlgorithm::kRmsProp:\n return \"RMSProp\";\n case OptimizationAlgorithm::kCenteredRmsProp:\n return \"CenteredRMSProp\";\n case OptimizationAlgorithm::kMdlAdagradLight:\n return \"MDLAdagradLight\";\n case OptimizationAlgorithm::kAdadelta:\n return \"Adadelta\";\n case OptimizationAlgorithm::kProximalAdagrad:\n return \"ProximalAdagrad\";\n case OptimizationAlgorithm::PARAMETERS_NOT_SET:\n return \"*** Not set ***\";\n }\n}\n\nstring GetOptimizationAlgorithmFriendlyName(OptimizationAlgorithm alg) {\n switch (alg) {\n case OptimizationAlgorithm::kAdagrad:\n return \"Adagrad\";\n case OptimizationAlgorithm::kStochasticGradientDescent:\n return \"stochastic gradient descent\";\n case OptimizationAlgorithm::kFtrl:\n return \"FTRL\";\n case OptimizationAlgorithm::kAdam:\n return \"ADAM\";\n case OptimizationAlgorithm::kMomentum:\n return \"Momentum\";\n case OptimizationAlgorithm::kRmsProp:\n return \"RMSProp\";\n case OptimizationAlgorithm::kCenteredRmsProp:\n return \"centered RMSProp\";\n case OptimizationAlgorithm::kMdlAdagradLight:\n return \"MDL Adagrad Light\";\n case OptimizationAlgorithm::kAdadelta:\n return \"Adadelta\";\n case OptimizationAlgorithm::kProximalAdagrad:\n return \"proximal Adagrad\";\n case OptimizationAlgorithm::PARAMETERS_NOT_SET:\n return \"unknown (not specified)\";\n }\n}\n\n\/\/ Returns the number of optimization parameter vectors used by the optimization\n\/\/ algorithm, excluding the weights themselves and assuming no gradient\n\/\/ accumulation.\nStatus GetBaseAuxiliaryParameterCount(OptimizationAlgorithm alg, int* count) {\n switch (alg) {\n case OptimizationAlgorithm::kAdagrad:\n *count = 1;\n return Status::OK();\n case OptimizationAlgorithm::kStochasticGradientDescent:\n *count = 0;\n return Status::OK();\n case OptimizationAlgorithm::kFtrl:\n *count = 2;\n return Status::OK();\n case OptimizationAlgorithm::kAdam:\n *count = 2;\n return Status::OK();\n case OptimizationAlgorithm::kMomentum:\n *count = 1;\n return Status::OK();\n case OptimizationAlgorithm::kRmsProp:\n *count = 2;\n return Status::OK();\n case OptimizationAlgorithm::kCenteredRmsProp:\n *count = 3;\n return Status::OK();\n case OptimizationAlgorithm::kMdlAdagradLight:\n *count = 3;\n return Status::OK();\n case OptimizationAlgorithm::kAdadelta:\n *count = 2;\n return Status::OK();\n case OptimizationAlgorithm::kProximalAdagrad:\n *count = 1;\n return Status::OK();\n case OptimizationAlgorithm::PARAMETERS_NOT_SET:\n return errors::InvalidArgument(\"No optimization algorithm specified\");\n }\n}\n\nStatus GetGradientAccumulationSupport(OptimizationAlgorithm alg,\n GradientAccumulationSupport* support) {\n switch (alg) {\n case OptimizationAlgorithm::kAdagrad:\n *support = GradientAccumulationSupport::kSupported;\n return Status::OK();\n case OptimizationAlgorithm::kStochasticGradientDescent:\n *support = GradientAccumulationSupport::kUnnecessary;\n return Status::OK();\n default: {\n int auxiliary_parameter_count;\n TF_RETURN_IF_ERROR(\n GetBaseAuxiliaryParameterCount(alg, &auxiliary_parameter_count));\n *support = auxiliary_parameter_count + 1 <= kMaxAuxiliaryParameterCount\n ? GradientAccumulationSupport::kSupported\n : GradientAccumulationSupport::kNotSupported;\n return Status::OK();\n }\n }\n}\nnamespace {\n\/\/ Make a normal state variable specification. Please refer to\n\/\/ \/\/tensorflow\/core\/protobuf\/tpu\/optimization_parameters.proto\n\/\/ (StateVariableSpecification message) for instructions on how to set the\n\/\/ padding_initial_value field.\nStateVariableSpecification MakeStandardStateVariableSpecification(\n const string& name, double padding_initial_value) {\n StateVariableSpecification result;\n result.set_name(name);\n result.mutable_user_defined()->set_padding_initial_value(\n padding_initial_value);\n return result;\n}\n} \/\/ namespace\n\nStatus GetOptimizationAlgorithmStateVariables(\n OptimizationAlgorithm alg, bool use_gradient_accumulation,\n std::vector* state_variables) {\n \/\/ The first parameter set is always the weights themselves.\n state_variables->push_back(\n MakeStandardStateVariableSpecification(\"parameters\", 0.0));\n \/\/ The order of the returned parameters needs to match the offsets used by\n \/\/ the algorithm implementations in test_util.cc and\n \/\/ address_handler_program_creator.cc.\n switch (alg) {\n case OptimizationAlgorithm::kAdagrad: {\n state_variables->push_back(\n MakeStandardStateVariableSpecification(\"accumulators\", 0.1));\n break;\n }\n case OptimizationAlgorithm::kStochasticGradientDescent: {\n \/\/ None.\n break;\n }\n case OptimizationAlgorithm::kFtrl: {\n state_variables->push_back(\n MakeStandardStateVariableSpecification(\"accumulators\", 0.1));\n state_variables->push_back(\n MakeStandardStateVariableSpecification(\"linears\", 0.0));\n break;\n }\n case OptimizationAlgorithm::kAdam: {\n state_variables->push_back(\n MakeStandardStateVariableSpecification(\"momenta\", 0.0));\n state_variables->push_back(\n MakeStandardStateVariableSpecification(\"velocities\", 0.0));\n break;\n }\n case OptimizationAlgorithm::kMomentum: {\n state_variables->push_back(\n MakeStandardStateVariableSpecification(\"momenta\", 0.0));\n break;\n }\n case OptimizationAlgorithm::kRmsProp: {\n state_variables->push_back(\n MakeStandardStateVariableSpecification(\"ms\", 1.0));\n state_variables->push_back(\n MakeStandardStateVariableSpecification(\"mom\", 0.0));\n break;\n }\n case OptimizationAlgorithm::kCenteredRmsProp: {\n state_variables->push_back(\n MakeStandardStateVariableSpecification(\"ms\", 1.0));\n state_variables->push_back(\n MakeStandardStateVariableSpecification(\"mom\", 0.0));\n state_variables->push_back(\n MakeStandardStateVariableSpecification(\"mg\", 0.0));\n break;\n }\n case OptimizationAlgorithm::kMdlAdagradLight: {\n state_variables->push_back(\n MakeStandardStateVariableSpecification(\"accumulators\", 0.1));\n state_variables->push_back(\n MakeStandardStateVariableSpecification(\"weights\", 0.0));\n state_variables->push_back(\n MakeStandardStateVariableSpecification(\"benefits\", 0.0));\n break;\n }\n case OptimizationAlgorithm::kAdadelta: {\n state_variables->push_back(\n MakeStandardStateVariableSpecification(\"accumulators\", 0.0));\n state_variables->push_back(\n MakeStandardStateVariableSpecification(\"updates\", 0.0));\n break;\n }\n case OptimizationAlgorithm::kProximalAdagrad: {\n state_variables->push_back(\n MakeStandardStateVariableSpecification(\"accumulators\", 0.1));\n break;\n }\n case OptimizationAlgorithm::PARAMETERS_NOT_SET: {\n return errors::InvalidArgument(\"No optimization algorithm specified\");\n }\n }\n \/\/ This needs to be last so that the save\/restore ops do not need to know\n \/\/ about gradient accumulation.\n if (use_gradient_accumulation) {\n StateVariableSpecification gradient_acc;\n gradient_acc.set_name(\"gradient_accumulators\");\n gradient_acc.mutable_fill_with_constant()->set_initial_value(\n kGradientAccumulatorInitialValue);\n state_variables->push_back(std::move(gradient_acc));\n }\n if (state_variables->size() > kMaxAuxiliaryParameterCount + 1) {\n return errors::InvalidArgument(\n \"Optimization algorithm\", GetOptimizationAlgorithmName(alg),\n \"does not support gradient accumulation because it \"\n \"already has too many other accumulators\");\n }\n return Status::OK();\n} \/\/ namespace tpu\n\nstd::vector GetOptimizationAlgorithms() {\n return {\n OptimizationAlgorithm::kAdagrad,\n OptimizationAlgorithm::kStochasticGradientDescent,\n OptimizationAlgorithm::kFtrl,\n OptimizationAlgorithm::kAdam,\n OptimizationAlgorithm::kMomentum,\n OptimizationAlgorithm::kRmsProp,\n OptimizationAlgorithm::kCenteredRmsProp,\n OptimizationAlgorithm::kMdlAdagradLight,\n OptimizationAlgorithm::kAdadelta,\n OptimizationAlgorithm::kProximalAdagrad,\n };\n}\n\n} \/\/ namespace tpu\n} \/\/ namespace tensorflow\nFixed the warning in the file\/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/tpu\/tpu_embedding_optimization_parameters_utils.h\"\n#include \"tensorflow\/core\/lib\/core\/errors.h\"\n\nnamespace tensorflow {\nnamespace tpu {\n\nstring GetOptimizationAlgorithmName(OptimizationAlgorithm alg) {\n switch (alg) {\n case OptimizationAlgorithm::kAdagrad:\n return \"Adagrad\";\n case OptimizationAlgorithm::kStochasticGradientDescent:\n return \"StochasticGradientDescent\";\n case OptimizationAlgorithm::kFtrl:\n return \"FTRL\";\n case OptimizationAlgorithm::kAdam:\n return \"ADAM\";\n case OptimizationAlgorithm::kMomentum:\n return \"Momentum\";\n case OptimizationAlgorithm::kRmsProp:\n return \"RMSProp\";\n case OptimizationAlgorithm::kCenteredRmsProp:\n return \"CenteredRMSProp\";\n case OptimizationAlgorithm::kMdlAdagradLight:\n return \"MDLAdagradLight\";\n case OptimizationAlgorithm::kAdadelta:\n return \"Adadelta\";\n case OptimizationAlgorithm::kProximalAdagrad:\n return \"ProximalAdagrad\";\n case OptimizationAlgorithm::PARAMETERS_NOT_SET:\n return \"*** Not set ***\";\n }\n return \"*** Not set ***\";\n}\n\nstring GetOptimizationAlgorithmFriendlyName(OptimizationAlgorithm alg) {\n switch (alg) {\n case OptimizationAlgorithm::kAdagrad:\n return \"Adagrad\";\n case OptimizationAlgorithm::kStochasticGradientDescent:\n return \"stochastic gradient descent\";\n case OptimizationAlgorithm::kFtrl:\n return \"FTRL\";\n case OptimizationAlgorithm::kAdam:\n return \"ADAM\";\n case OptimizationAlgorithm::kMomentum:\n return \"Momentum\";\n case OptimizationAlgorithm::kRmsProp:\n return \"RMSProp\";\n case OptimizationAlgorithm::kCenteredRmsProp:\n return \"centered RMSProp\";\n case OptimizationAlgorithm::kMdlAdagradLight:\n return \"MDL Adagrad Light\";\n case OptimizationAlgorithm::kAdadelta:\n return \"Adadelta\";\n case OptimizationAlgorithm::kProximalAdagrad:\n return \"proximal Adagrad\";\n case OptimizationAlgorithm::PARAMETERS_NOT_SET:\n return \"unknown (not specified)\";\n }\n return \"unknown (not specified)\";\n}\n\n\/\/ Returns the number of optimization parameter vectors used by the optimization\n\/\/ algorithm, excluding the weights themselves and assuming no gradient\n\/\/ accumulation.\nStatus GetBaseAuxiliaryParameterCount(OptimizationAlgorithm alg, int* count) {\n switch (alg) {\n case OptimizationAlgorithm::kAdagrad:\n *count = 1;\n return Status::OK();\n case OptimizationAlgorithm::kStochasticGradientDescent:\n *count = 0;\n return Status::OK();\n case OptimizationAlgorithm::kFtrl:\n *count = 2;\n return Status::OK();\n case OptimizationAlgorithm::kAdam:\n *count = 2;\n return Status::OK();\n case OptimizationAlgorithm::kMomentum:\n *count = 1;\n return Status::OK();\n case OptimizationAlgorithm::kRmsProp:\n *count = 2;\n return Status::OK();\n case OptimizationAlgorithm::kCenteredRmsProp:\n *count = 3;\n return Status::OK();\n case OptimizationAlgorithm::kMdlAdagradLight:\n *count = 3;\n return Status::OK();\n case OptimizationAlgorithm::kAdadelta:\n *count = 2;\n return Status::OK();\n case OptimizationAlgorithm::kProximalAdagrad:\n *count = 1;\n return Status::OK();\n case OptimizationAlgorithm::PARAMETERS_NOT_SET:\n return errors::InvalidArgument(\"No optimization algorithm specified\");\n }\n return errors::InvalidArgument(\"No optimization algorithm specified\");\n}\n\nStatus GetGradientAccumulationSupport(OptimizationAlgorithm alg,\n GradientAccumulationSupport* support) {\n switch (alg) {\n case OptimizationAlgorithm::kAdagrad:\n *support = GradientAccumulationSupport::kSupported;\n return Status::OK();\n case OptimizationAlgorithm::kStochasticGradientDescent:\n *support = GradientAccumulationSupport::kUnnecessary;\n return Status::OK();\n default: {\n int auxiliary_parameter_count;\n TF_RETURN_IF_ERROR(\n GetBaseAuxiliaryParameterCount(alg, &auxiliary_parameter_count));\n *support = auxiliary_parameter_count + 1 <= kMaxAuxiliaryParameterCount\n ? GradientAccumulationSupport::kSupported\n : GradientAccumulationSupport::kNotSupported;\n return Status::OK();\n }\n }\n}\nnamespace {\n\/\/ Make a normal state variable specification. Please refer to\n\/\/ \/\/tensorflow\/core\/protobuf\/tpu\/optimization_parameters.proto\n\/\/ (StateVariableSpecification message) for instructions on how to set the\n\/\/ padding_initial_value field.\nStateVariableSpecification MakeStandardStateVariableSpecification(\n const string& name, double padding_initial_value) {\n StateVariableSpecification result;\n result.set_name(name);\n result.mutable_user_defined()->set_padding_initial_value(\n padding_initial_value);\n return result;\n}\n} \/\/ namespace\n\nStatus GetOptimizationAlgorithmStateVariables(\n OptimizationAlgorithm alg, bool use_gradient_accumulation,\n std::vector* state_variables) {\n \/\/ The first parameter set is always the weights themselves.\n state_variables->push_back(\n MakeStandardStateVariableSpecification(\"parameters\", 0.0));\n \/\/ The order of the returned parameters needs to match the offsets used by\n \/\/ the algorithm implementations in test_util.cc and\n \/\/ address_handler_program_creator.cc.\n switch (alg) {\n case OptimizationAlgorithm::kAdagrad: {\n state_variables->push_back(\n MakeStandardStateVariableSpecification(\"accumulators\", 0.1));\n break;\n }\n case OptimizationAlgorithm::kStochasticGradientDescent: {\n \/\/ None.\n break;\n }\n case OptimizationAlgorithm::kFtrl: {\n state_variables->push_back(\n MakeStandardStateVariableSpecification(\"accumulators\", 0.1));\n state_variables->push_back(\n MakeStandardStateVariableSpecification(\"linears\", 0.0));\n break;\n }\n case OptimizationAlgorithm::kAdam: {\n state_variables->push_back(\n MakeStandardStateVariableSpecification(\"momenta\", 0.0));\n state_variables->push_back(\n MakeStandardStateVariableSpecification(\"velocities\", 0.0));\n break;\n }\n case OptimizationAlgorithm::kMomentum: {\n state_variables->push_back(\n MakeStandardStateVariableSpecification(\"momenta\", 0.0));\n break;\n }\n case OptimizationAlgorithm::kRmsProp: {\n state_variables->push_back(\n MakeStandardStateVariableSpecification(\"ms\", 1.0));\n state_variables->push_back(\n MakeStandardStateVariableSpecification(\"mom\", 0.0));\n break;\n }\n case OptimizationAlgorithm::kCenteredRmsProp: {\n state_variables->push_back(\n MakeStandardStateVariableSpecification(\"ms\", 1.0));\n state_variables->push_back(\n MakeStandardStateVariableSpecification(\"mom\", 0.0));\n state_variables->push_back(\n MakeStandardStateVariableSpecification(\"mg\", 0.0));\n break;\n }\n case OptimizationAlgorithm::kMdlAdagradLight: {\n state_variables->push_back(\n MakeStandardStateVariableSpecification(\"accumulators\", 0.1));\n state_variables->push_back(\n MakeStandardStateVariableSpecification(\"weights\", 0.0));\n state_variables->push_back(\n MakeStandardStateVariableSpecification(\"benefits\", 0.0));\n break;\n }\n case OptimizationAlgorithm::kAdadelta: {\n state_variables->push_back(\n MakeStandardStateVariableSpecification(\"accumulators\", 0.0));\n state_variables->push_back(\n MakeStandardStateVariableSpecification(\"updates\", 0.0));\n break;\n }\n case OptimizationAlgorithm::kProximalAdagrad: {\n state_variables->push_back(\n MakeStandardStateVariableSpecification(\"accumulators\", 0.1));\n break;\n }\n case OptimizationAlgorithm::PARAMETERS_NOT_SET: {\n return errors::InvalidArgument(\"No optimization algorithm specified\");\n }\n }\n \/\/ This needs to be last so that the save\/restore ops do not need to know\n \/\/ about gradient accumulation.\n if (use_gradient_accumulation) {\n StateVariableSpecification gradient_acc;\n gradient_acc.set_name(\"gradient_accumulators\");\n gradient_acc.mutable_fill_with_constant()->set_initial_value(\n kGradientAccumulatorInitialValue);\n state_variables->push_back(std::move(gradient_acc));\n }\n if (state_variables->size() > kMaxAuxiliaryParameterCount + 1) {\n return errors::InvalidArgument(\n \"Optimization algorithm\", GetOptimizationAlgorithmName(alg),\n \"does not support gradient accumulation because it \"\n \"already has too many other accumulators\");\n }\n return Status::OK();\n} \/\/ namespace tpu\n\nstd::vector GetOptimizationAlgorithms() {\n return {\n OptimizationAlgorithm::kAdagrad,\n OptimizationAlgorithm::kStochasticGradientDescent,\n OptimizationAlgorithm::kFtrl,\n OptimizationAlgorithm::kAdam,\n OptimizationAlgorithm::kMomentum,\n OptimizationAlgorithm::kRmsProp,\n OptimizationAlgorithm::kCenteredRmsProp,\n OptimizationAlgorithm::kMdlAdagradLight,\n OptimizationAlgorithm::kAdadelta,\n OptimizationAlgorithm::kProximalAdagrad,\n };\n}\n\n} \/\/ namespace tpu\n} \/\/ namespace tensorflow\n<|endoftext|>"} {"text":"#include \"stan\/math\/functions\/rising_factorial.hpp\"\r\n#include \r\n\r\nTEST(MathFunctions, rising_factorial) {\r\n using stan::math::rising_factorial;\r\n \r\n EXPECT_FLOAT_EQ(120, rising_factorial(4.0,3));\r\n EXPECT_FLOAT_EQ(360, rising_factorial(3.0,4));\r\n EXPECT_THROW(rising_factorial(-1, 4),std::domain_error);\r\n}\r\nadded NaN test for rising_factorial#include \n#include \n#include \n\nTEST(MathFunctions, rising_factorial) {\n using stan::math::rising_factorial;\n \n EXPECT_FLOAT_EQ(120, rising_factorial(4.0,3));\n EXPECT_FLOAT_EQ(360, rising_factorial(3.0,4));\n EXPECT_THROW(rising_factorial(-1, 4),std::domain_error);\n}\n\nTEST(MathFunctions, rising_factorial_nan) {\n double nan = std::numeric_limits::quiet_NaN();\n \n EXPECT_PRED1(boost::math::isnan,\n stan::math::rising_factorial(4.0, nan));\n EXPECT_PRED1(boost::math::isnan,\n stan::math::rising_factorial(nan, 3.0));\n EXPECT_PRED1(boost::math::isnan,\n stan::math::rising_factorial(nan, nan));\n}\n<|endoftext|>"} {"text":"\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2015-2016 Francois Beaune, The appleseedhq Organization\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"appleseedrenderer.h\"\n\n\/\/ appleseed-max headers.\n#include \"renderer\/appleseedrendererparamdlg.h\"\n#include \"renderer\/datachunks.h\"\n#include \"renderer\/projectbuilder.h\"\n#include \"renderer\/renderercontroller.h\"\n#include \"renderer\/tilecallback.h\"\n#include \"utilities.h\"\n#include \"version.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/api\/frame.h\"\n#include \"renderer\/api\/project.h\"\n#include \"renderer\/api\/rendering.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/image\/canvasproperties.h\"\n#include \"foundation\/image\/image.h\"\n#include \"foundation\/platform\/types.h\"\n#include \"foundation\/utility\/autoreleaseptr.h\"\n\n\/\/ 3ds Max headers.\n#include \n#include \n\n\/\/ Standard headers.\n#include \n\nnamespace asf = foundation;\nnamespace asr = renderer;\n\nnamespace\n{\n const Class_ID AppleseedRendererClassId(0x72651b24, 0x5da32e1d);\n const TCHAR* AppleseedRendererClassName = _T(\"appleseed Renderer\");\n}\n\nAppleseedRendererClassDesc g_appleseed_renderer_classdesc;\n\n\n\/\/\n\/\/ AppleseedRenderer class implementation.\n\/\/\n\nAppleseedRenderer::AppleseedRenderer()\n : m_settings(RendererSettings::defaults())\n{\n clear();\n}\n\nClass_ID AppleseedRenderer::ClassID()\n{\n return AppleseedRendererClassId;\n}\n\nvoid AppleseedRenderer::GetClassName(MSTR& s)\n{\n s = AppleseedRendererClassName;\n}\n\nvoid AppleseedRenderer::DeleteThis()\n{\n delete this;\n}\n\nRefResult AppleseedRenderer::NotifyRefChanged(\n const Interval& changeInt,\n RefTargetHandle hTarget,\n PartID& partID,\n RefMessage message,\n BOOL propagate)\n{\n return REF_SUCCEED;\n}\n\nint AppleseedRenderer::Open(\n INode* scene,\n INode* view_node,\n ViewParams* view_params,\n RendParams& rend_params,\n HWND hwnd,\n DefaultLight* default_lights,\n int default_light_count,\n RendProgressCallback* progress_cb)\n{\n SuspendAll suspend(TRUE, TRUE, TRUE, TRUE, TRUE, TRUE);\n\n m_scene = scene;\n m_view_node = view_node;\n if (view_params)\n m_view_params = *view_params;\n m_rend_params = rend_params;\n\n \/\/ Copy the default lights as the 'default_lights' pointer is no longer valid in Render().\n m_default_lights.clear();\n m_default_lights.reserve(default_light_count);\n for (int i = 0; i < default_light_count; ++i)\n m_default_lights.push_back(default_lights[i]);\n\n return 1; \/\/ success\n}\n\nnamespace\n{\n void get_view_params_from_view_node(\n ViewParams& view_params,\n INode* view_node,\n const TimeValue time)\n {\n const ObjectState& os = view_node->EvalWorldState(time);\n switch (os.obj->SuperClassID())\n {\n case CAMERA_CLASS_ID:\n {\n CameraObject* cam = static_cast(os.obj);\n\n Interval validity_interval;\n validity_interval.SetInfinite();\n\n Matrix3 cam_to_world = view_node->GetObjTMAfterWSM(time, &validity_interval);\n cam_to_world.NoScale();\n\n view_params.affineTM = Inverse(cam_to_world);\n\n CameraState cam_state;\n cam->EvalCameraState(time, validity_interval, &cam_state);\n\n view_params.projType = PROJ_PERSPECTIVE;\n view_params.fov = cam_state.fov;\n\n if (cam_state.manualClip)\n {\n view_params.hither = cam_state.hither;\n view_params.yon = cam_state.yon;\n }\n else\n {\n view_params.hither = 0.001f;\n view_params.yon = 1.0e38f;\n }\n }\n break;\n\n case LIGHT_CLASS_ID:\n {\n DbgAssert(!\"Not implemented yet.\");\n }\n break;\n\n default:\n DbgAssert(!\"Unexpected super class ID for camera.\");\n }\n }\n\n class RenderBeginProc\n : public RefEnumProc\n {\n public:\n explicit RenderBeginProc(const TimeValue time)\n : m_time(time)\n {\n }\n\n virtual int proc(ReferenceMaker* rm) override\n {\n rm->RenderBegin(m_time);\n return REF_ENUM_CONTINUE;\n }\n\n private:\n const TimeValue m_time;\n };\n\n class RenderEndProc\n : public RefEnumProc\n {\n public:\n explicit RenderEndProc(const TimeValue time)\n : m_time(time)\n {\n }\n\n virtual int proc(ReferenceMaker* rm) override\n {\n rm->RenderEnd(m_time);\n return REF_ENUM_CONTINUE;\n }\n\n private:\n const TimeValue m_time;\n };\n\n void render_begin(\n std::vector& nodes,\n const TimeValue time)\n {\n RenderBeginProc proc(time);\n proc.BeginEnumeration();\n\n for (auto node : nodes)\n node->EnumRefHierarchy(proc);\n\n proc.EndEnumeration();\n }\n\n void render_end(\n std::vector& nodes,\n const TimeValue time)\n {\n RenderEndProc proc(time);\n proc.BeginEnumeration();\n\n for (auto node : nodes)\n node->EnumRefHierarchy(proc);\n\n proc.EndEnumeration();\n }\n\n void render(\n asr::Project& project,\n const RendererSettings& settings,\n Bitmap* bitmap,\n RendProgressCallback* progress_cb)\n {\n \/\/ Number of rendered tiles, shared counter accessed atomically.\n volatile asf::uint32 rendered_tile_count = 0;\n\n \/\/ Create the renderer controller.\n const size_t total_tile_count =\n static_cast(settings.m_passes)\n * project.get_frame()->image().properties().m_tile_count;\n RendererController renderer_controller(\n progress_cb,\n &rendered_tile_count,\n total_tile_count);\n\n \/\/ Create the tile callback.\n TileCallback tile_callback(bitmap, &rendered_tile_count);\n\n \/\/ Create the master renderer.\n std::auto_ptr renderer(\n new asr::MasterRenderer(\n project,\n project.configurations().get_by_name(\"final\")->get_inherited_parameters(),\n &renderer_controller,\n &tile_callback));\n\n \/\/ Render the frame.\n renderer->render();\n\n \/\/ Make sure the master renderer is deleted before the project.\n }\n}\n\nint AppleseedRenderer::Render(\n TimeValue time,\n Bitmap* bitmap,\n FrameRendParams& frame_rend_params,\n HWND hwnd,\n RendProgressCallback* progress_cb,\n ViewParams* view_params)\n{\n SuspendAll suspend(TRUE, TRUE, TRUE, TRUE, TRUE, TRUE);\n\n m_time = time;\n\n if (view_params)\n m_view_params = *view_params;\n\n if (m_view_node)\n get_view_params_from_view_node(m_view_params, m_view_node, time);\n\n \/\/ Retrieve and tweak renderer settings.\n RendererSettings renderer_settings = m_settings;\n if (m_rend_params.inMtlEdit)\n {\n renderer_settings.m_pixel_samples = m_rend_params.mtlEditAA ? 32 : 4;\n renderer_settings.m_passes = 1;\n renderer_settings.m_gi = false;\n renderer_settings.m_background_emits_light = false;\n }\n\n \/\/ Collect the entities we're interested in.\n if (progress_cb)\n progress_cb->SetTitle(_T(\"Collecting Entities...\"));\n MaxSceneEntityCollector collector(m_entities);\n collector.collect(m_scene);\n\n \/\/ Call RenderBegin() on all object instances.\n render_begin(m_entities.m_objects, m_time);\n\n \/\/ Build the project.\n if (progress_cb)\n progress_cb->SetTitle(_T(\"Building Project...\"));\n asf::auto_release_ptr project(\n build_project(\n m_entities,\n m_default_lights,\n m_view_params,\n m_rend_params,\n frame_rend_params,\n renderer_settings,\n bitmap,\n time));\n\n if (m_rend_params.inMtlEdit)\n {\n \/\/ Render the project.\n if (progress_cb)\n progress_cb->SetTitle(_T(\"Rendering...\"));\n render(project.ref(), m_settings, bitmap, progress_cb);\n }\n else\n {\n \/\/ Write the project to disk.\n if (m_settings.m_output_mode == RendererSettings::OutputMode::SaveProjectOnly ||\n m_settings.m_output_mode == RendererSettings::OutputMode::SaveProjectAndRender)\n {\n if (progress_cb)\n progress_cb->SetTitle(_T(\"Writing Project To Disk...\"));\n asr::ProjectFileWriter::write(\n project.ref(),\n wide_to_utf8(m_settings.m_project_file_path).c_str());\n }\n\n \/\/ Render the project.\n if (m_settings.m_output_mode == RendererSettings::OutputMode::RenderOnly ||\n m_settings.m_output_mode == RendererSettings::OutputMode::SaveProjectAndRender)\n {\n if (progress_cb)\n progress_cb->SetTitle(_T(\"Rendering...\"));\n render(project.ref(), m_settings, bitmap, progress_cb);\n }\n }\n\n if (progress_cb)\n progress_cb->SetTitle(_T(\"Done.\"));\n\n \/\/ Success.\n return 1;\n}\n\nvoid AppleseedRenderer::Close(\n HWND hwnd,\n RendProgressCallback* progress_cb)\n{\n \/\/ Call RenderEnd() on all object instances.\n render_end(m_entities.m_objects, m_time);\n\n clear();\n}\n\nRendParamDlg* AppleseedRenderer::CreateParamDialog(\n IRendParams* rend_params,\n BOOL in_progress)\n{\n return\n new AppleseedRendererParamDlg(\n rend_params,\n in_progress,\n m_settings);\n}\n\nvoid AppleseedRenderer::ResetParams()\n{\n clear();\n}\n\nIOResult AppleseedRenderer::Save(ISave* isave)\n{\n bool success = true;\n\n isave->BeginChunk(ChunkFileFormatVersion);\n success &= write(isave, FileFormatVersion);\n isave->EndChunk();\n\n isave->BeginChunk(ChunkSettings);\n success &= m_settings.save(isave);\n isave->EndChunk();\n\n return success ? IO_OK : IO_ERROR;\n}\n\nIOResult AppleseedRenderer::Load(ILoad* iload)\n{\n IOResult result = IO_OK;\n\n while (true)\n {\n result = iload->OpenChunk();\n if (result == IO_END)\n return IO_OK;\n if (result != IO_OK)\n break;\n\n switch (iload->CurChunkID())\n {\n case ChunkFileFormatVersion:\n {\n USHORT version;\n result = read(iload, &version);\n }\n break;\n\n case ChunkSettings:\n result = m_settings.load(iload);\n break;\n }\n\n if (result != IO_OK)\n break;\n\n result = iload->CloseChunk();\n if (result != IO_OK)\n break;\n }\n\n return result;\n}\n\nvoid AppleseedRenderer::clear()\n{\n m_scene = nullptr;\n m_view_node = nullptr;\n m_default_lights.clear();\n m_time = 0;\n m_entities.clear();\n}\n\n\n\/\/\n\/\/ AppleseedRendererClassDesc class implementation.\n\/\/\n\nint AppleseedRendererClassDesc::IsPublic()\n{\n return TRUE;\n}\n\nvoid* AppleseedRendererClassDesc::Create(BOOL loading)\n{\n return new AppleseedRenderer();\n}\n\nconst MCHAR* AppleseedRendererClassDesc::ClassName()\n{\n return AppleseedRendererClassName;\n}\n\nSClass_ID AppleseedRendererClassDesc::SuperClassID()\n{\n return RENDERER_CLASS_ID;\n}\n\nClass_ID AppleseedRendererClassDesc::ClassID()\n{\n return AppleseedRendererClassId;\n}\n\nconst MCHAR* AppleseedRendererClassDesc::Category()\n{\n return _T(\"\");\n}\n\nconst MCHAR* AppleseedRendererClassDesc::InternalName()\n{\n \/\/ Parsable name used by MAXScript.\n return _T(\"appleseed_renderer\");\n}\nFix scene accumulation bug when rendering animations\n\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2015-2016 Francois Beaune, The appleseedhq Organization\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Interface header.\n#include \"appleseedrenderer.h\"\n\n\/\/ appleseed-max headers.\n#include \"renderer\/appleseedrendererparamdlg.h\"\n#include \"renderer\/datachunks.h\"\n#include \"renderer\/projectbuilder.h\"\n#include \"renderer\/renderercontroller.h\"\n#include \"renderer\/tilecallback.h\"\n#include \"utilities.h\"\n#include \"version.h\"\n\n\/\/ appleseed.renderer headers.\n#include \"renderer\/api\/frame.h\"\n#include \"renderer\/api\/project.h\"\n#include \"renderer\/api\/rendering.h\"\n\n\/\/ appleseed.foundation headers.\n#include \"foundation\/image\/canvasproperties.h\"\n#include \"foundation\/image\/image.h\"\n#include \"foundation\/platform\/types.h\"\n#include \"foundation\/utility\/autoreleaseptr.h\"\n\n\/\/ 3ds Max headers.\n#include \n#include \n\n\/\/ Standard headers.\n#include \n\nnamespace asf = foundation;\nnamespace asr = renderer;\n\nnamespace\n{\n const Class_ID AppleseedRendererClassId(0x72651b24, 0x5da32e1d);\n const TCHAR* AppleseedRendererClassName = _T(\"appleseed Renderer\");\n}\n\nAppleseedRendererClassDesc g_appleseed_renderer_classdesc;\n\n\n\/\/\n\/\/ AppleseedRenderer class implementation.\n\/\/\n\nAppleseedRenderer::AppleseedRenderer()\n : m_settings(RendererSettings::defaults())\n{\n clear();\n}\n\nClass_ID AppleseedRenderer::ClassID()\n{\n return AppleseedRendererClassId;\n}\n\nvoid AppleseedRenderer::GetClassName(MSTR& s)\n{\n s = AppleseedRendererClassName;\n}\n\nvoid AppleseedRenderer::DeleteThis()\n{\n delete this;\n}\n\nRefResult AppleseedRenderer::NotifyRefChanged(\n const Interval& changeInt,\n RefTargetHandle hTarget,\n PartID& partID,\n RefMessage message,\n BOOL propagate)\n{\n return REF_SUCCEED;\n}\n\nint AppleseedRenderer::Open(\n INode* scene,\n INode* view_node,\n ViewParams* view_params,\n RendParams& rend_params,\n HWND hwnd,\n DefaultLight* default_lights,\n int default_light_count,\n RendProgressCallback* progress_cb)\n{\n SuspendAll suspend(TRUE, TRUE, TRUE, TRUE, TRUE, TRUE);\n\n m_scene = scene;\n m_view_node = view_node;\n if (view_params)\n m_view_params = *view_params;\n m_rend_params = rend_params;\n\n \/\/ Copy the default lights as the 'default_lights' pointer is no longer valid in Render().\n m_default_lights.clear();\n m_default_lights.reserve(default_light_count);\n for (int i = 0; i < default_light_count; ++i)\n m_default_lights.push_back(default_lights[i]);\n\n return 1; \/\/ success\n}\n\nnamespace\n{\n void get_view_params_from_view_node(\n ViewParams& view_params,\n INode* view_node,\n const TimeValue time)\n {\n const ObjectState& os = view_node->EvalWorldState(time);\n switch (os.obj->SuperClassID())\n {\n case CAMERA_CLASS_ID:\n {\n CameraObject* cam = static_cast(os.obj);\n\n Interval validity_interval;\n validity_interval.SetInfinite();\n\n Matrix3 cam_to_world = view_node->GetObjTMAfterWSM(time, &validity_interval);\n cam_to_world.NoScale();\n\n view_params.affineTM = Inverse(cam_to_world);\n\n CameraState cam_state;\n cam->EvalCameraState(time, validity_interval, &cam_state);\n\n view_params.projType = PROJ_PERSPECTIVE;\n view_params.fov = cam_state.fov;\n\n if (cam_state.manualClip)\n {\n view_params.hither = cam_state.hither;\n view_params.yon = cam_state.yon;\n }\n else\n {\n view_params.hither = 0.001f;\n view_params.yon = 1.0e38f;\n }\n }\n break;\n\n case LIGHT_CLASS_ID:\n {\n DbgAssert(!\"Not implemented yet.\");\n }\n break;\n\n default:\n DbgAssert(!\"Unexpected super class ID for camera.\");\n }\n }\n\n class RenderBeginProc\n : public RefEnumProc\n {\n public:\n explicit RenderBeginProc(const TimeValue time)\n : m_time(time)\n {\n }\n\n virtual int proc(ReferenceMaker* rm) override\n {\n rm->RenderBegin(m_time);\n return REF_ENUM_CONTINUE;\n }\n\n private:\n const TimeValue m_time;\n };\n\n class RenderEndProc\n : public RefEnumProc\n {\n public:\n explicit RenderEndProc(const TimeValue time)\n : m_time(time)\n {\n }\n\n virtual int proc(ReferenceMaker* rm) override\n {\n rm->RenderEnd(m_time);\n return REF_ENUM_CONTINUE;\n }\n\n private:\n const TimeValue m_time;\n };\n\n void render_begin(\n std::vector& nodes,\n const TimeValue time)\n {\n RenderBeginProc proc(time);\n proc.BeginEnumeration();\n\n for (auto node : nodes)\n node->EnumRefHierarchy(proc);\n\n proc.EndEnumeration();\n }\n\n void render_end(\n std::vector& nodes,\n const TimeValue time)\n {\n RenderEndProc proc(time);\n proc.BeginEnumeration();\n\n for (auto node : nodes)\n node->EnumRefHierarchy(proc);\n\n proc.EndEnumeration();\n }\n\n void render(\n asr::Project& project,\n const RendererSettings& settings,\n Bitmap* bitmap,\n RendProgressCallback* progress_cb)\n {\n \/\/ Number of rendered tiles, shared counter accessed atomically.\n volatile asf::uint32 rendered_tile_count = 0;\n\n \/\/ Create the renderer controller.\n const size_t total_tile_count =\n static_cast(settings.m_passes)\n * project.get_frame()->image().properties().m_tile_count;\n RendererController renderer_controller(\n progress_cb,\n &rendered_tile_count,\n total_tile_count);\n\n \/\/ Create the tile callback.\n TileCallback tile_callback(bitmap, &rendered_tile_count);\n\n \/\/ Create the master renderer.\n std::auto_ptr renderer(\n new asr::MasterRenderer(\n project,\n project.configurations().get_by_name(\"final\")->get_inherited_parameters(),\n &renderer_controller,\n &tile_callback));\n\n \/\/ Render the frame.\n renderer->render();\n\n \/\/ Make sure the master renderer is deleted before the project.\n }\n}\n\nint AppleseedRenderer::Render(\n TimeValue time,\n Bitmap* bitmap,\n FrameRendParams& frame_rend_params,\n HWND hwnd,\n RendProgressCallback* progress_cb,\n ViewParams* view_params)\n{\n SuspendAll suspend(TRUE, TRUE, TRUE, TRUE, TRUE, TRUE);\n\n m_time = time;\n\n if (view_params)\n m_view_params = *view_params;\n\n if (m_view_node)\n get_view_params_from_view_node(m_view_params, m_view_node, time);\n\n \/\/ Retrieve and tweak renderer settings.\n RendererSettings renderer_settings = m_settings;\n if (m_rend_params.inMtlEdit)\n {\n renderer_settings.m_pixel_samples = m_rend_params.mtlEditAA ? 32 : 4;\n renderer_settings.m_passes = 1;\n renderer_settings.m_gi = false;\n renderer_settings.m_background_emits_light = false;\n }\n\n \/\/ Collect the entities we're interested in.\n if (progress_cb)\n progress_cb->SetTitle(_T(\"Collecting Entities...\"));\n m_entities.clear();\n MaxSceneEntityCollector collector(m_entities);\n collector.collect(m_scene);\n\n \/\/ Call RenderBegin() on all object instances.\n render_begin(m_entities.m_objects, m_time);\n\n \/\/ Build the project.\n if (progress_cb)\n progress_cb->SetTitle(_T(\"Building Project...\"));\n asf::auto_release_ptr project(\n build_project(\n m_entities,\n m_default_lights,\n m_view_params,\n m_rend_params,\n frame_rend_params,\n renderer_settings,\n bitmap,\n time));\n\n if (m_rend_params.inMtlEdit)\n {\n \/\/ Render the project.\n if (progress_cb)\n progress_cb->SetTitle(_T(\"Rendering...\"));\n render(project.ref(), m_settings, bitmap, progress_cb);\n }\n else\n {\n \/\/ Write the project to disk.\n if (m_settings.m_output_mode == RendererSettings::OutputMode::SaveProjectOnly ||\n m_settings.m_output_mode == RendererSettings::OutputMode::SaveProjectAndRender)\n {\n if (progress_cb)\n progress_cb->SetTitle(_T(\"Writing Project To Disk...\"));\n asr::ProjectFileWriter::write(\n project.ref(),\n wide_to_utf8(m_settings.m_project_file_path).c_str());\n }\n\n \/\/ Render the project.\n if (m_settings.m_output_mode == RendererSettings::OutputMode::RenderOnly ||\n m_settings.m_output_mode == RendererSettings::OutputMode::SaveProjectAndRender)\n {\n if (progress_cb)\n progress_cb->SetTitle(_T(\"Rendering...\"));\n render(project.ref(), m_settings, bitmap, progress_cb);\n }\n }\n\n if (progress_cb)\n progress_cb->SetTitle(_T(\"Done.\"));\n\n \/\/ Success.\n return 1;\n}\n\nvoid AppleseedRenderer::Close(\n HWND hwnd,\n RendProgressCallback* progress_cb)\n{\n \/\/ Call RenderEnd() on all object instances.\n render_end(m_entities.m_objects, m_time);\n\n clear();\n}\n\nRendParamDlg* AppleseedRenderer::CreateParamDialog(\n IRendParams* rend_params,\n BOOL in_progress)\n{\n return\n new AppleseedRendererParamDlg(\n rend_params,\n in_progress,\n m_settings);\n}\n\nvoid AppleseedRenderer::ResetParams()\n{\n clear();\n}\n\nIOResult AppleseedRenderer::Save(ISave* isave)\n{\n bool success = true;\n\n isave->BeginChunk(ChunkFileFormatVersion);\n success &= write(isave, FileFormatVersion);\n isave->EndChunk();\n\n isave->BeginChunk(ChunkSettings);\n success &= m_settings.save(isave);\n isave->EndChunk();\n\n return success ? IO_OK : IO_ERROR;\n}\n\nIOResult AppleseedRenderer::Load(ILoad* iload)\n{\n IOResult result = IO_OK;\n\n while (true)\n {\n result = iload->OpenChunk();\n if (result == IO_END)\n return IO_OK;\n if (result != IO_OK)\n break;\n\n switch (iload->CurChunkID())\n {\n case ChunkFileFormatVersion:\n {\n USHORT version;\n result = read(iload, &version);\n }\n break;\n\n case ChunkSettings:\n result = m_settings.load(iload);\n break;\n }\n\n if (result != IO_OK)\n break;\n\n result = iload->CloseChunk();\n if (result != IO_OK)\n break;\n }\n\n return result;\n}\n\nvoid AppleseedRenderer::clear()\n{\n m_scene = nullptr;\n m_view_node = nullptr;\n m_default_lights.clear();\n m_time = 0;\n m_entities.clear();\n}\n\n\n\/\/\n\/\/ AppleseedRendererClassDesc class implementation.\n\/\/\n\nint AppleseedRendererClassDesc::IsPublic()\n{\n return TRUE;\n}\n\nvoid* AppleseedRendererClassDesc::Create(BOOL loading)\n{\n return new AppleseedRenderer();\n}\n\nconst MCHAR* AppleseedRendererClassDesc::ClassName()\n{\n return AppleseedRendererClassName;\n}\n\nSClass_ID AppleseedRendererClassDesc::SuperClassID()\n{\n return RENDERER_CLASS_ID;\n}\n\nClass_ID AppleseedRendererClassDesc::ClassID()\n{\n return AppleseedRendererClassId;\n}\n\nconst MCHAR* AppleseedRendererClassDesc::Category()\n{\n return _T(\"\");\n}\n\nconst MCHAR* AppleseedRendererClassDesc::InternalName()\n{\n \/\/ Parsable name used by MAXScript.\n return _T(\"appleseed_renderer\");\n}\n<|endoftext|>"} {"text":"\/* Copyright 2020 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow_serving\/servables\/tensorflow\/tflite_interpreter_pool.h\"\n\n#include \n#include \n#include \n\n#include \"tensorflow\/core\/platform\/errors.h\"\n#include \"tensorflow\/lite\/kernels\/parse_example\/parse_example.h\"\n#include \"tensorflow\/lite\/kernels\/register.h\"\n\nnamespace tensorflow {\nnamespace serving {\nnamespace internal {\n\nTfLiteInterpreterWrapper::TfLiteInterpreterWrapper(\n std::unique_ptr interpreter)\n :\n#ifdef TFLITE_PROFILE\n interpreter_(std::move(interpreter)),\n fixed_batch_size_(fixed_batch_size),\n max_num_entries_(TFLITE_PROFILE_EVENTS),\n profiler_(max_num_entries_)\n#else\n interpreter_(std::move(interpreter))\n#endif\n{\n#ifdef TFLITE_PROFILE\n interpreter_->SetProfiler(&profiler_);\n#endif\n for (const int& idx : interpreter_->inputs()) {\n const auto* tflite_tensor = interpreter_->tensor(idx);\n if (tflite_tensor->type == kTfLiteString) {\n tensor_buffer_.emplace(idx,\n std::unique_ptr(tflite_tensor->data.raw));\n tensor_buffer_max_bytes_[idx] = 0;\n }\n }\n}\n\ntensorflow::Status TfLiteInterpreterWrapper::SetStringData(\n const gtl::ArraySlice& batch,\n TfLiteTensor* tflite_tensor, int tensor_index) {\n \/\/ Format of the buffer for tflite:\n \/\/ [0] number of strings (int32_t)\n \/\/ [4] offset of each string (int32_t)\n \/\/ [sizeof(int32_t) * (num_strings + 1)]] total size of strings\n \/\/ [sizeof(int32_t) * (num_strings + 2)] batch.data()\n int32_t num_strings = batch.size();\n offset_.clear();\n size_t total_size = 0;\n offset_.push_back(static_cast(total_size));\n for (int i = 0; i < num_strings; i++) {\n total_size += batch[i].size();\n offset_.push_back(static_cast(total_size));\n }\n size_t required_bytes = total_size + sizeof(int32_t) * (num_strings + 2);\n if (tensor_buffer_.find(tensor_index) == tensor_buffer_.end()) {\n return errors::Internal(\"Tensor input for index not found: \", tensor_index);\n }\n if (tensor_buffer_max_bytes_[tensor_index] > 0 &&\n required_bytes > tensor_buffer_max_bytes_[tensor_index]) {\n tensor_buffer_max_bytes_[tensor_index] = 0;\n }\n\n if (tensor_buffer_max_bytes_[tensor_index] == 0) {\n tensor_buffer_[tensor_index].reset(\n reinterpret_cast(malloc(required_bytes)));\n tensor_buffer_max_bytes_[tensor_index] = required_bytes;\n } else {\n tensor_buffer_[tensor_index].reset(tflite_tensor->data.raw);\n }\n memcpy(tensor_buffer_[tensor_index].get(), &num_strings, sizeof(int32_t));\n int32_t start = sizeof(int32_t) * (num_strings + 2);\n for (size_t i = 0; i < offset_.size(); i++) {\n size_t size_offset_i = start + offset_[i];\n if (size_offset_i > std::numeric_limits::max()) {\n return errors::Internal(\"Invalid size, string input too large:\",\n size_offset_i);\n }\n int32_t offset_i = static_cast(size_offset_i);\n memcpy(tensor_buffer_[tensor_index].get() + sizeof(int32_t) * (i + 1),\n &offset_i, sizeof(int32_t));\n }\n for (int i = 0; i < num_strings; i++) {\n memcpy(tensor_buffer_[tensor_index].get() + start, batch[i].data(),\n batch[i].size());\n start += batch[i].size();\n }\n\n \/\/ tflite_tensor will take ownership of the pointer.\n tflite_tensor->data.raw = tensor_buffer_[tensor_index].release();\n tflite_tensor->bytes = required_bytes;\n tflite_tensor->allocation_type = kTfLiteDynamic;\n return Status::OK();\n}\n\nTfLiteStatus TfLiteInterpreterWrapper::Invoke() {\n#ifdef TFLITE_PROFILE\n if (invocation_count_ > 0) {\n profiler_.Reset();\n profiler_.StartProfiling();\n }\n#endif\n auto status = interpreter_->Invoke();\n#ifdef TFLITE_PROFILE\n if (invocation_count_ > 0) {\n profiler_.StopProfiling();\n auto profile_events = profiler_.GetProfileEvents();\n run_summarizer_.ProcessProfiles(profile_events, *interpreter_);\n }\n if (invocation_count_++ >= MAX_PROFILE_EVENTS) {\n WriteProfileData();\n run_summarizer_.Clear();\n invocation_count_ = 0;\n }\n#endif\n return status;\n}\n\ntensorflow::Status TfLiteInterpreterPool::CreateTfLiteInterpreterPool(\n const tflite::FlatBufferModel& model, bool run_in_caller,\n bool use_batch_parallelism, int batch_pool_size, int id,\n const tensorflow::SessionOptions& options,\n std::unique_ptr& pool) {\n \/\/ If can't use_batch_parallelism or pool size is 1,\n \/\/ just use 1 interpreter and run in caller.\n if (!use_batch_parallelism || batch_pool_size == 1) {\n run_in_caller = true;\n batch_pool_size = 1;\n use_batch_parallelism = false;\n }\n std::unique_ptr thread_pool;\n int num_interpreters = run_in_caller ? 1 : 0;\n if (!run_in_caller || use_batch_parallelism) {\n thread_pool.reset(new tensorflow::thread::ThreadPool(\n options.env, tensorflow::ThreadOptions(),\n absl::StrCat(kTfLiteThreadPoolName, id), batch_pool_size, false,\n nullptr));\n num_interpreters += thread_pool->NumThreads();\n }\n\n \/\/ TODO(b\/140959776): Add support for non-builtin ops (flex or custom ops).\n tflite::ops::builtin::BuiltinOpResolver resolver;\n tflite::ops::custom::AddParseExampleOp(&resolver);\n int fixed_batch_size = 1;\n if (use_batch_parallelism) {\n if (num_interpreters < 1) {\n return errors::InvalidArgument(\n \"CreateTfLiteInterpreterPool requested \",\n \"invalid number of interpreters: \", num_interpreters);\n }\n fixed_batch_size =\n (kInitialBatchSize + num_interpreters - 1) \/ num_interpreters;\n }\n std::vector> interpreters;\n\n for (int i = 0; i < num_interpreters; i++) {\n std::unique_ptr interpreter;\n if (tflite::InterpreterBuilder(model, resolver)(\n &interpreter, \/*num_threads=*\/1) != kTfLiteOk) {\n return errors::Internal(\n \"Failed to create a TFLite interpreter with the given model\");\n }\n const int idx = interpreter->inputs()[0];\n const auto* tensor = interpreter->tensor(idx);\n if (tensor->type == kTfLiteString) {\n interpreter->ResizeInputTensor(idx, {fixed_batch_size});\n }\n if (interpreter->AllocateTensors() != kTfLiteOk) {\n return errors::Internal(\"Failed to allocate tensors\");\n }\n interpreters.push_back(\n std::make_unique(std::move(interpreter)));\n interpreters.back()->SetMiniBatchSize(fixed_batch_size);\n }\n pool.reset(new TfLiteInterpreterPool(\n id, std::move(interpreters), std::move(thread_pool), num_interpreters,\n fixed_batch_size, use_batch_parallelism));\n return tensorflow::Status::OK();\n}\n\nTfLiteInterpreterPool::TfLiteInterpreterPool(\n int id, std::vector> interpreters,\n std::unique_ptr thread_pool,\n int num_interpreters, int fixed_batch_size, bool use_batch_parallelism)\n : id_(id),\n interpreters_(std::move(interpreters)),\n thread_pool_(std::move(thread_pool)),\n num_interpreters_(num_interpreters),\n fixed_batch_size_(fixed_batch_size),\n use_batch_parallelism_(use_batch_parallelism) {}\n\nstd::unique_ptr&\nTfLiteInterpreterPool::GetInterpreter(int interpreter_idx) {\n return interpreters_[interpreter_idx];\n}\n\nnamespace {\n\nbool IsBatchParallelizable(const tflite::Model* model) {\n auto tflite_model = absl::make_unique();\n model->UnPackTo(tflite_model.get(), nullptr);\n if (tflite_model->subgraphs.empty()) {\n return false;\n }\n const auto& subgraph = tflite_model->subgraphs[0];\n if (subgraph->inputs.size() != 1) {\n return false;\n }\n int input_tensor_id = subgraph->inputs[0];\n const std::vector supported_ops = {\"ParseExample\", \"ParseExampleV2\"};\n for (size_t op_idx = 0; op_idx < subgraph->operators.size(); op_idx++) {\n tflite::OperatorT* op = subgraph->operators[op_idx].get();\n if (std::find(op->inputs.begin(), op->inputs.end(), input_tensor_id) !=\n op->inputs.end()) {\n const std::string& custom_code =\n tflite_model->operator_codes[op->opcode_index]->custom_code;\n return std::find(supported_ops.begin(), supported_ops.end(),\n custom_code) != supported_ops.end();\n }\n }\n return false;\n}\n\n} \/\/ namespace\n\ntensorflow::Status TfLiteSessionPool::CreateTfLiteSessionPool(\n const tflite::FlatBufferModel* model,\n const tensorflow::SessionOptions& options, bool run_in_caller,\n int pool_size, int batch_pool_size,\n std::unique_ptr& tflite_session_pool) {\n bool use_batch_parallelism = IsBatchParallelizable(model->GetModel());\n std::vector> pools;\n for (int i = 0; i < pool_size; i++) {\n std::unique_ptr pool;\n TF_RETURN_IF_ERROR(TfLiteInterpreterPool::CreateTfLiteInterpreterPool(\n *model, run_in_caller, use_batch_parallelism, batch_pool_size, i,\n options, pool));\n pools.push_back(std::move(pool));\n }\n tflite_session_pool.reset(new TfLiteSessionPool(std::move(pools)));\n return tensorflow::Status::OK();\n}\n\n} \/\/ namespace internal\n} \/\/ namespace serving\n} \/\/ namespace tensorflow\nFix memory leak from allocating input tensors\/* Copyright 2020 Google Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow_serving\/servables\/tensorflow\/tflite_interpreter_pool.h\"\n\n#include \n#include \n#include \n\n#include \"tensorflow\/core\/platform\/errors.h\"\n#include \"tensorflow\/lite\/kernels\/parse_example\/parse_example.h\"\n#include \"tensorflow\/lite\/kernels\/register.h\"\n\nnamespace tensorflow {\nnamespace serving {\nnamespace internal {\n\nTfLiteInterpreterWrapper::TfLiteInterpreterWrapper(\n std::unique_ptr interpreter)\n :\n#ifdef TFLITE_PROFILE\n interpreter_(std::move(interpreter)),\n fixed_batch_size_(fixed_batch_size),\n max_num_entries_(TFLITE_PROFILE_EVENTS),\n profiler_(max_num_entries_)\n#else\n interpreter_(std::move(interpreter))\n#endif\n{\n#ifdef TFLITE_PROFILE\n interpreter_->SetProfiler(&profiler_);\n#endif\n for (const int& idx : interpreter_->inputs()) {\n const auto* tflite_tensor = interpreter_->tensor(idx);\n if (tflite_tensor->type == kTfLiteString) {\n tensor_buffer_.emplace(idx,\n std::unique_ptr(tflite_tensor->data.raw));\n tensor_buffer_max_bytes_[idx] = 0;\n }\n }\n}\n\ntensorflow::Status TfLiteInterpreterWrapper::SetStringData(\n const gtl::ArraySlice& batch,\n TfLiteTensor* tflite_tensor, int tensor_index) {\n \/\/ Format of the buffer for tflite:\n \/\/ [0] number of strings (int32_t)\n \/\/ [4] offset of each string (int32_t)\n \/\/ [sizeof(int32_t) * (num_strings + 1)]] total size of strings\n \/\/ [sizeof(int32_t) * (num_strings + 2)] batch.data()\n int32_t num_strings = batch.size();\n offset_.clear();\n size_t total_size = 0;\n offset_.push_back(static_cast(total_size));\n for (int i = 0; i < num_strings; i++) {\n total_size += batch[i].size();\n offset_.push_back(static_cast(total_size));\n }\n size_t required_bytes = total_size + sizeof(int32_t) * (num_strings + 2);\n if (tensor_buffer_.find(tensor_index) == tensor_buffer_.end()) {\n return errors::Internal(\"Tensor input for index not found: \", tensor_index);\n }\n if (required_bytes > tensor_buffer_max_bytes_[tensor_index]) {\n if (tflite_tensor->data.raw) {\n free(tflite_tensor->data.raw);\n }\n tflite_tensor->data.raw = reinterpret_cast(malloc(required_bytes));\n tensor_buffer_max_bytes_[tensor_index] = required_bytes;\n }\n tensor_buffer_[tensor_index].reset(tflite_tensor->data.raw);\n memcpy(tensor_buffer_[tensor_index].get(), &num_strings, sizeof(int32_t));\n int32_t start = sizeof(int32_t) * (num_strings + 2);\n for (size_t i = 0; i < offset_.size(); i++) {\n size_t size_offset_i = start + offset_[i];\n if (size_offset_i > std::numeric_limits::max()) {\n return errors::Internal(\"Invalid size, string input too large:\",\n size_offset_i);\n }\n int32_t offset_i = static_cast(size_offset_i);\n memcpy(tensor_buffer_[tensor_index].get() + sizeof(int32_t) * (i + 1),\n &offset_i, sizeof(int32_t));\n }\n for (int i = 0; i < num_strings; i++) {\n memcpy(tensor_buffer_[tensor_index].get() + start, batch[i].data(),\n batch[i].size());\n start += batch[i].size();\n }\n\n \/\/ tflite_tensor will take ownership of the pointer.\n tflite_tensor->data.raw = tensor_buffer_[tensor_index].release();\n tflite_tensor->bytes = required_bytes;\n tflite_tensor->allocation_type = kTfLiteDynamic;\n return Status::OK();\n}\n\nTfLiteStatus TfLiteInterpreterWrapper::Invoke() {\n#ifdef TFLITE_PROFILE\n if (invocation_count_ > 0) {\n profiler_.Reset();\n profiler_.StartProfiling();\n }\n#endif\n auto status = interpreter_->Invoke();\n#ifdef TFLITE_PROFILE\n if (invocation_count_ > 0) {\n profiler_.StopProfiling();\n auto profile_events = profiler_.GetProfileEvents();\n run_summarizer_.ProcessProfiles(profile_events, *interpreter_);\n }\n if (invocation_count_++ >= MAX_PROFILE_EVENTS) {\n WriteProfileData();\n run_summarizer_.Clear();\n invocation_count_ = 0;\n }\n#endif\n return status;\n}\n\ntensorflow::Status TfLiteInterpreterPool::CreateTfLiteInterpreterPool(\n const tflite::FlatBufferModel& model, bool run_in_caller,\n bool use_batch_parallelism, int batch_pool_size, int id,\n const tensorflow::SessionOptions& options,\n std::unique_ptr& pool) {\n \/\/ If can't use_batch_parallelism or pool size is 1,\n \/\/ just use 1 interpreter and run in caller.\n if (!use_batch_parallelism || batch_pool_size == 1) {\n run_in_caller = true;\n batch_pool_size = 1;\n use_batch_parallelism = false;\n }\n std::unique_ptr thread_pool;\n int num_interpreters = run_in_caller ? 1 : 0;\n if (!run_in_caller || use_batch_parallelism) {\n thread_pool.reset(new tensorflow::thread::ThreadPool(\n options.env, tensorflow::ThreadOptions(),\n absl::StrCat(kTfLiteThreadPoolName, id), batch_pool_size, false,\n nullptr));\n num_interpreters += thread_pool->NumThreads();\n }\n\n \/\/ TODO(b\/140959776): Add support for non-builtin ops (flex or custom ops).\n tflite::ops::builtin::BuiltinOpResolver resolver;\n tflite::ops::custom::AddParseExampleOp(&resolver);\n int fixed_batch_size = 1;\n if (use_batch_parallelism) {\n if (num_interpreters < 1) {\n return errors::InvalidArgument(\n \"CreateTfLiteInterpreterPool requested \",\n \"invalid number of interpreters: \", num_interpreters);\n }\n fixed_batch_size =\n (kInitialBatchSize + num_interpreters - 1) \/ num_interpreters;\n }\n std::vector> interpreters;\n\n for (int i = 0; i < num_interpreters; i++) {\n std::unique_ptr interpreter;\n if (tflite::InterpreterBuilder(model, resolver)(\n &interpreter, \/*num_threads=*\/1) != kTfLiteOk) {\n return errors::Internal(\n \"Failed to create a TFLite interpreter with the given model\");\n }\n const int idx = interpreter->inputs()[0];\n const auto* tensor = interpreter->tensor(idx);\n if (tensor->type == kTfLiteString) {\n interpreter->ResizeInputTensor(idx, {fixed_batch_size});\n }\n if (interpreter->AllocateTensors() != kTfLiteOk) {\n return errors::Internal(\"Failed to allocate tensors\");\n }\n interpreters.push_back(\n std::make_unique(std::move(interpreter)));\n interpreters.back()->SetMiniBatchSize(fixed_batch_size);\n }\n pool.reset(new TfLiteInterpreterPool(\n id, std::move(interpreters), std::move(thread_pool), num_interpreters,\n fixed_batch_size, use_batch_parallelism));\n return tensorflow::Status::OK();\n}\n\nTfLiteInterpreterPool::TfLiteInterpreterPool(\n int id, std::vector> interpreters,\n std::unique_ptr thread_pool,\n int num_interpreters, int fixed_batch_size, bool use_batch_parallelism)\n : id_(id),\n interpreters_(std::move(interpreters)),\n thread_pool_(std::move(thread_pool)),\n num_interpreters_(num_interpreters),\n fixed_batch_size_(fixed_batch_size),\n use_batch_parallelism_(use_batch_parallelism) {}\n\nstd::unique_ptr&\nTfLiteInterpreterPool::GetInterpreter(int interpreter_idx) {\n return interpreters_[interpreter_idx];\n}\n\nnamespace {\n\nbool IsBatchParallelizable(const tflite::Model* model) {\n auto tflite_model = absl::make_unique();\n model->UnPackTo(tflite_model.get(), nullptr);\n if (tflite_model->subgraphs.empty()) {\n return false;\n }\n const auto& subgraph = tflite_model->subgraphs[0];\n if (subgraph->inputs.size() != 1) {\n return false;\n }\n int input_tensor_id = subgraph->inputs[0];\n const std::vector supported_ops = {\"ParseExample\", \"ParseExampleV2\"};\n for (size_t op_idx = 0; op_idx < subgraph->operators.size(); op_idx++) {\n tflite::OperatorT* op = subgraph->operators[op_idx].get();\n if (std::find(op->inputs.begin(), op->inputs.end(), input_tensor_id) !=\n op->inputs.end()) {\n const std::string& custom_code =\n tflite_model->operator_codes[op->opcode_index]->custom_code;\n return std::find(supported_ops.begin(), supported_ops.end(),\n custom_code) != supported_ops.end();\n }\n }\n return false;\n}\n\n} \/\/ namespace\n\ntensorflow::Status TfLiteSessionPool::CreateTfLiteSessionPool(\n const tflite::FlatBufferModel* model,\n const tensorflow::SessionOptions& options, bool run_in_caller,\n int pool_size, int batch_pool_size,\n std::unique_ptr& tflite_session_pool) {\n bool use_batch_parallelism = IsBatchParallelizable(model->GetModel());\n std::vector> pools;\n for (int i = 0; i < pool_size; i++) {\n std::unique_ptr pool;\n TF_RETURN_IF_ERROR(TfLiteInterpreterPool::CreateTfLiteInterpreterPool(\n *model, run_in_caller, use_batch_parallelism, batch_pool_size, i,\n options, pool));\n pools.push_back(std::move(pool));\n }\n tflite_session_pool.reset(new TfLiteSessionPool(std::move(pools)));\n return tensorflow::Status::OK();\n}\n\n} \/\/ namespace internal\n} \/\/ namespace serving\n} \/\/ namespace tensorflow\n<|endoftext|>"} {"text":"#include \"self_youhua.h\"\n\nself_youhua::self_youhua()\n{\n\n}\n\n开始自优化#include \"self_youhua.h\"\n\nself_youhua::self_youhua()\n{\n\n}\nself_youhua::initUser()\n{\n userList.clear();\n for (int i=0;i<19;i++)\n {\n\n }\n}\n\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \"wallItem.h\"\n\n#include \"..\/..\/..\/..\/..\/qrkernel\/settingsManager.h\"\n#include \"d2ModelScene.h\"\n\nusing namespace qReal::interpreters::robots;\nusing namespace details::d2Model;\nusing namespace graphicsUtils;\n\nWallItem::WallItem(QPointF const &begin, QPointF const &end)\n\t: LineItem(begin, end)\n\t, mDragged(false)\n\t, mImage(\":\/icons\/2d_wall.png\")\n\t, mOldX1(0)\n\t, mOldY1(0)\n{\n\tsetPrivateData();\n\tsetAcceptDrops(true);\n}\n\nvoid WallItem::setPrivateData()\n{\n\tsetZValue(1);\n\n\tmPen.setWidth(10);\n\tmPen.setStyle(Qt::NoPen);\n\tmBrush.setStyle(Qt::SolidPattern);\n\tmBrush.setTextureImage(mImage);\n\tmSerializeName = \"wall\";\n}\n\nQPointF WallItem::begin()\n{\n\treturn QPointF(mX1, mY1) + scenePos();\n}\n\nQPointF WallItem::end()\n{\n\treturn QPointF(mX2, mY2) + scenePos();\n}\n\nvoid WallItem::drawItem(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)\n{\n\tQ_UNUSED(option);\n\tQ_UNUSED(widget);\n\tpainter->drawPath(shape());\n}\n\nvoid WallItem::drawExtractionForItem(QPainter *painter)\n{\n\tif (!isSelected()) {\n\t\treturn;\n\t}\n\n\tpainter->setPen(QPen(Qt::green));\n\tmLineImpl.drawExtractionForItem(painter, mX1, mY1, mX2, mY2, drift);\n\tmLineImpl.drawFieldForResizeItem(painter, resizeDrift, mX1, mY1, mX2, mY2);\n}\n\nvoid WallItem::mousePressEvent(QGraphicsSceneMouseEvent * event)\n{\n\tAbstractItem::mousePressEvent(event);\n\tmDragged = (flags() & ItemIsMovable) || mOverlappedWithRobot;\n\tmOldX1 = qAbs(mX1 - event->scenePos().x());\n\tmOldY1 = qAbs(mY1 - event->scenePos().y());\n}\n\nvoid WallItem::mouseMoveEvent(QGraphicsSceneMouseEvent * event)\n{\n\tQPointF const oldPos = pos();\n\tif (SettingsManager::value(\"2dShowGrid\").toBool() && mDragged && ((flags() & ItemIsMovable) || mOverlappedWithRobot)){\n\t\tQPointF const pos = event->scenePos();\n\t\tqreal const deltaX = (mX1 - mX2);\n\t\tqreal const deltaY = (mY1 - mY2);\n\t\tmX1 = pos.x() - mOldX1;\n\t\tmY1 = pos.y() - mOldY1;\n\t\tthis->reshapeBeginWithGrid(SettingsManager::value(\"2dGridCellSize\").toInt());\n\t\tthis->setDraggedEndWithGrid(deltaX, deltaY);\n\t} else {\n\t\tQGraphicsItem::mouseMoveEvent(event);\n\t}\n\t\/\/ Items under cursor cannot be dragged when adding new item,\n\t\/\/ but it mustn`t confuse the case when item is unmovable\n\t\/\/ because overapped with robot\n\tif (mDragged && ((flags() & ItemIsMovable) || mOverlappedWithRobot)) {\n\t\temit wallDragged(this, realShape(), oldPos);\n\t}\n\tevent->accept();\n}\n\nbool WallItem::isDragged()\n{\n\treturn mDragged;\n}\n\nvoid WallItem::mouseReleaseEvent(QGraphicsSceneMouseEvent * event)\n{\n\tQGraphicsItem::mouseReleaseEvent(event);\n\tmDragged = false;\n}\n\nQDomElement WallItem::serialize(QDomDocument &document, QPoint const &topLeftPicture)\n{\n\tQDomElement wallNode = document.createElement(mSerializeName);\n\twallNode.setAttribute(\"begin\", QString::number(mX1 + scenePos().x() - topLeftPicture.x())\n\t\t\t+ \":\" + QString::number(mY1 + scenePos().y() - topLeftPicture.y()));\n\twallNode.setAttribute(\"end\", QString::number(mX2 + scenePos().x() - topLeftPicture.x())\n\t\t\t+ \":\" + QString::number(mY2 + scenePos().y() - topLeftPicture.y()));\n\treturn wallNode;\n}\n\nvoid WallItem::deserializePenBrush(QDomElement const &element)\n{\n\tQ_UNUSED(element)\n\tsetPrivateData();\n}\n\nvoid WallItem::onOverlappedWithRobot(bool overlapped)\n{\n\tmOverlappedWithRobot = overlapped;\n}\nLittle fix in drag#include \n#include \n\n#include \"wallItem.h\"\n\n#include \"..\/..\/..\/..\/..\/qrkernel\/settingsManager.h\"\n#include \"d2ModelScene.h\"\n\nusing namespace qReal::interpreters::robots;\nusing namespace details::d2Model;\nusing namespace graphicsUtils;\n\nWallItem::WallItem(QPointF const &begin, QPointF const &end)\n\t: LineItem(begin, end)\n\t, mDragged(false)\n\t, mImage(\":\/icons\/2d_wall.png\")\n\t, mOldX1(0)\n\t, mOldY1(0)\n{\n\tsetPrivateData();\n\tsetAcceptDrops(true);\n}\n\nvoid WallItem::setPrivateData()\n{\n\tsetZValue(1);\n\n\tmPen.setWidth(10);\n\tmPen.setStyle(Qt::NoPen);\n\tmBrush.setStyle(Qt::SolidPattern);\n\tmBrush.setTextureImage(mImage);\n\tmSerializeName = \"wall\";\n}\n\nQPointF WallItem::begin()\n{\n\treturn QPointF(mX1, mY1) + scenePos();\n}\n\nQPointF WallItem::end()\n{\n\treturn QPointF(mX2, mY2) + scenePos();\n}\n\nvoid WallItem::drawItem(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget)\n{\n\tQ_UNUSED(option);\n\tQ_UNUSED(widget);\n\tpainter->drawPath(shape());\n}\n\nvoid WallItem::drawExtractionForItem(QPainter *painter)\n{\n\tif (!isSelected()) {\n\t\treturn;\n\t}\n\n\tpainter->setPen(QPen(Qt::green));\n\tmLineImpl.drawExtractionForItem(painter, mX1, mY1, mX2, mY2, drift);\n\tmLineImpl.drawFieldForResizeItem(painter, resizeDrift, mX1, mY1, mX2, mY2);\n}\n\nvoid WallItem::mousePressEvent(QGraphicsSceneMouseEvent * event)\n{\n\tAbstractItem::mousePressEvent(event);\n\tmDragged = (flags() & ItemIsMovable) || mOverlappedWithRobot;\n\tmOldX1 = qAbs(mX1 - event->scenePos().x());\n\tmOldY1 = qAbs(mY1 - event->scenePos().y());\n}\n\nvoid WallItem::mouseMoveEvent(QGraphicsSceneMouseEvent * event)\n{\n\tQPointF const oldPos = pos();\n\tif (SettingsManager::value(\"2dShowGrid\").toBool() && mDragged && ((flags() & ItemIsMovable) || mOverlappedWithRobot)){\n\t\tQPointF const pos = event->scenePos();\n\t\tint indexGrid = SettingsManager::value(\"2dGridCellSize\").toInt();\n\t\tqreal const deltaX = (mX1 - mX2);\n\t\tqreal const deltaY = (mY1 - mY2);\n\t\tmX1 = pos.x() - mOldX1;\n\t\tmY1 = pos.y() - mOldY1;\n\t\tthis->reshapeBeginWithGrid(indexGrid);\n\t\tthis->setDraggedEndWithGrid(deltaX, deltaY);\n\t\tmCellNumbX1 = mX1\/indexGrid;\n\t\tmCellNumbY1 = mY1\/indexGrid;\n\t\tmCellNumbX2 = mX2\/indexGrid;\n\t\tmCellNumbY2 = mY2\/indexGrid;\n\t} else {\n\t\tQGraphicsItem::mouseMoveEvent(event);\n\t}\n\t\/\/ Items under cursor cannot be dragged when adding new item,\n\t\/\/ but it mustn`t confuse the case when item is unmovable\n\t\/\/ because overapped with robot\n\tif (mDragged && ((flags() & ItemIsMovable) || mOverlappedWithRobot)) {\n\t\temit wallDragged(this, realShape(), oldPos);\n\t}\n\tevent->accept();\n}\n\nbool WallItem::isDragged()\n{\n\treturn mDragged;\n}\n\nvoid WallItem::mouseReleaseEvent(QGraphicsSceneMouseEvent * event)\n{\n\tQGraphicsItem::mouseReleaseEvent(event);\n\tmDragged = false;\n}\n\nQDomElement WallItem::serialize(QDomDocument &document, QPoint const &topLeftPicture)\n{\n\tQDomElement wallNode = document.createElement(mSerializeName);\n\twallNode.setAttribute(\"begin\", QString::number(mX1 + scenePos().x() - topLeftPicture.x())\n\t\t\t+ \":\" + QString::number(mY1 + scenePos().y() - topLeftPicture.y()));\n\twallNode.setAttribute(\"end\", QString::number(mX2 + scenePos().x() - topLeftPicture.x())\n\t\t\t+ \":\" + QString::number(mY2 + scenePos().y() - topLeftPicture.y()));\n\treturn wallNode;\n}\n\nvoid WallItem::deserializePenBrush(QDomElement const &element)\n{\n\tQ_UNUSED(element)\n\tsetPrivateData();\n}\n\nvoid WallItem::onOverlappedWithRobot(bool overlapped)\n{\n\tmOverlappedWithRobot = overlapped;\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: RecentlyUsedMasterPages.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2004-08-04 08:59:59 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SD_TOOLPANEL_CONTROLS_RECENTLY_USED_MASTER_PAGES_HXX\n#define SD_TOOLPANEL_CONTROLS_RECENTLY_USED_MASTER_PAGES_HXX\n\n#include \"tools\/SdGlobalResourceContainer.hxx\"\n#include \n#include \n#include \n#include \n#include \n\n#include \"DrawDocShell.hxx\"\n#include \"MasterPageContainer.hxx\"\n\n#ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_\n#include \n#endif\n\nclass SdPage;\n\nnamespace sd {\nclass MasterPageObserverEvent;\n}\n\n\nnamespace sd { namespace toolpanel { namespace controls {\n\n\/** This singleton holds a list of the most recently used master pages.\n*\/\nclass RecentlyUsedMasterPages\n : public SdGlobalResource\n{\npublic:\n \/** Return the single instance of this class.\n *\/\n static RecentlyUsedMasterPages& Instance (void);\n\n void AddEventListener (const Link& rEventListener);\n void RemoveEventListener (const Link& rEventListener);\n\n int GetMasterPageCount (void) const;\n String GetURL (int nIndex) const;\n String GetMasterPageName (int nIndex) const;\n SdPage* GetSlide (int nIndex) const;\n SdPage* GetMasterPage (int nIndex) const;\n Image GetMasterPagePreview (int nIndex, int nWidth) const;\n\nprivate:\n \/** The single instance of this class. It is created on demand when\n Instance() is called for the first time.\n *\/\n static RecentlyUsedMasterPages* mpInstance;\n\n ::std::vector maListeners;\n\n typedef ::std::vector MasterPageList;\n class PageByNameFinder;\n MasterPageList maMasterPages;\n unsigned long int mnMaxListSize;\n\n RecentlyUsedMasterPages (void);\n virtual ~RecentlyUsedMasterPages (void);\n\n \/** Call this method after a new object has been created.\n *\/\n void LateInit (void);\n\n \/\/\/ The copy constructor is not implemented. Do not use!\n RecentlyUsedMasterPages (const RecentlyUsedMasterPages&);\n\n \/\/\/ The assignment operator is not implemented. Do not use!\n RecentlyUsedMasterPages& operator= (const RecentlyUsedMasterPages&);\n\n void SendEvent (void);\n DECL_LINK(MasterPageChangeListener, MasterPageObserverEvent*);\n\n \/** Add a descriptor for the specified master page to the end of the\n list of most recently used master pages. When the page is already a\n member of that list the associated descriptor is moved to the end of\n the list to make it the most recently used entry.\n @param bMakePersistent\n When is given then the new list of recently used master\n pages is written back into the configuration to make it\n persistent. Giving to ommit this is used while loading\n the persistent list from the configuration.\n *\/\n void AddMasterPage (\n const String& rsName,\n bool bMakePersistent = true);\n\n \/** Load the list of recently used master pages from the registry where\n it was saved to make it persistent.\n *\/\n void LoadPersistentValues (void);\n\n \/** Save the list of recently used master pages to the registry to make\n it presistent.\n *\/\n void SavePersistentValues (void);\n\n ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface>\n OpenConfiguration (\n const ::rtl::OUString& rsRootName,\n bool bReadOnly);\n ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface>\n GetConfigurationNode (\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::uno::XInterface>& xRoot,\n const ::rtl::OUString& sPathToNode);\n};\n\n\n\n} } } \/\/ end of namespace ::sd::toolpanel::controls\n\n#endif\nINTEGRATION: CWS impress19 (1.3.94); FILE MERGED 2004\/11\/16 10:29:36 af 1.3.94.1: #i37233# AddMasterPage() uses a token instead of a master page name.\/*************************************************************************\n *\n * $RCSfile: RecentlyUsedMasterPages.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: hr $ $Date: 2004-11-26 15:10:00 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SD_TOOLPANEL_CONTROLS_RECENTLY_USED_MASTER_PAGES_HXX\n#define SD_TOOLPANEL_CONTROLS_RECENTLY_USED_MASTER_PAGES_HXX\n\n#include \"tools\/SdGlobalResourceContainer.hxx\"\n#include \n#include \n#include \n#include \n#include \n\n#include \"DrawDocShell.hxx\"\n#include \"MasterPageContainer.hxx\"\n\n#ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_\n#include \n#endif\n\nclass SdPage;\n\nnamespace sd {\nclass MasterPageObserverEvent;\n}\n\n\nnamespace sd { namespace toolpanel { namespace controls {\n\n\/** This singleton holds a list of the most recently used master pages.\n*\/\nclass RecentlyUsedMasterPages\n : public SdGlobalResource\n{\npublic:\n \/** Return the single instance of this class.\n *\/\n static RecentlyUsedMasterPages& Instance (void);\n\n void AddEventListener (const Link& rEventListener);\n void RemoveEventListener (const Link& rEventListener);\n\n int GetMasterPageCount (void) const;\n String GetURL (int nIndex) const;\n String GetMasterPageName (int nIndex) const;\n SdPage* GetSlide (int nIndex) const;\n SdPage* GetMasterPage (int nIndex) const;\n Image GetMasterPagePreview (int nIndex, int nWidth) const;\n\nprivate:\n \/** The single instance of this class. It is created on demand when\n Instance() is called for the first time.\n *\/\n static RecentlyUsedMasterPages* mpInstance;\n\n ::std::vector maListeners;\n\n typedef ::std::vector MasterPageList;\n class PageByNameFinder;\n MasterPageList maMasterPages;\n unsigned long int mnMaxListSize;\n\n RecentlyUsedMasterPages (void);\n virtual ~RecentlyUsedMasterPages (void);\n\n \/** Call this method after a new object has been created.\n *\/\n void LateInit (void);\n\n \/\/\/ The copy constructor is not implemented. Do not use!\n RecentlyUsedMasterPages (const RecentlyUsedMasterPages&);\n\n \/\/\/ The assignment operator is not implemented. Do not use!\n RecentlyUsedMasterPages& operator= (const RecentlyUsedMasterPages&);\n\n void SendEvent (void);\n DECL_LINK(MasterPageChangeListener, MasterPageObserverEvent*);\n\n \/** Add a descriptor for the specified master page to the end of the\n list of most recently used master pages. When the page is already a\n member of that list the associated descriptor is moved to the end of\n the list to make it the most recently used entry.\n @param bMakePersistent\n When is given then the new list of recently used master\n pages is written back into the configuration to make it\n persistent. Giving to ommit this is used while loading\n the persistent list from the configuration.\n *\/\n void AddMasterPage (\n MasterPageContainer::Token aToken,\n bool bMakePersistent = true);\n\n \/** Load the list of recently used master pages from the registry where\n it was saved to make it persistent.\n *\/\n void LoadPersistentValues (void);\n\n \/** Save the list of recently used master pages to the registry to make\n it presistent.\n *\/\n void SavePersistentValues (void);\n\n ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface>\n OpenConfiguration (\n const ::rtl::OUString& rsRootName,\n bool bReadOnly);\n ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface>\n GetConfigurationNode (\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::uno::XInterface>& xRoot,\n const ::rtl::OUString& sPathToNode);\n};\n\n\n\n} } } \/\/ end of namespace ::sd::toolpanel::controls\n\n#endif\n<|endoftext|>"} {"text":"\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"isearchcontext.h\"\n#include \"match_master.h\"\n#include \"match_context.h\"\n#include \"match_tools.h\"\n#include \"match_params.h\"\n#include \"matcher.h\"\n#include \"sessionmanager.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \nLOG_SETUP(\".proton.matching.matcher\");\n\nusing search::fef::Properties;\nusing namespace search::fef::indexproperties::matching;\nusing namespace search::engine;\nusing namespace search::grouping;\nusing search::DocumentMetaData;\nusing search::LidUsageStats;\nusing search::FeatureSet;\nusing search::attribute::IAttributeContext;\nusing search::fef::MatchDataLayout;\nusing search::fef::MatchData;\nusing search::queryeval::Blueprint;\nusing search::queryeval::SearchIterator;\nusing vespalib::Doom;\n\nnamespace proton::matching {\n\nnamespace {\n\n\/\/ used to give out empty blacklist blueprints\nstruct StupidMetaStore : search::IDocumentMetaStore {\n bool getGid(DocId, GlobalId &) const override { return false; }\n bool getGidEvenIfMoved(DocId, GlobalId &) const override { return false; }\n bool getLid(const GlobalId &, DocId &) const override { return false; }\n DocumentMetaData getMetaData(const GlobalId &) const override { return DocumentMetaData(); }\n void getMetaData(const BucketId &, DocumentMetaData::Vector &) const override { }\n DocId getCommittedDocIdLimit() const override { return 1; }\n DocId getNumUsedLids() const override { return 0; }\n DocId getNumActiveLids() const override { return 0; }\n uint64_t getCurrentGeneration() const override { return 0; }\n LidUsageStats getLidUsageStats() const override { return LidUsageStats(); }\n Blueprint::UP createBlackListBlueprint() const override { return Blueprint::UP(); }\n};\n\nFeatureSet::SP findFeatureSet(const DocsumRequest &req,\n MatchToolsFactory &mtf, bool summaryFeatures) {\n std::vector docs;\n for (size_t i = 0; i < req.hits.size(); ++i) {\n if (req.hits[i].docid != search::endDocId) {\n docs.push_back(req.hits[i].docid);\n }\n }\n std::sort(docs.begin(), docs.end());\n return MatchMaster::getFeatureSet(mtf, docs, summaryFeatures);\n}\n\nsize_t numThreads(size_t hits, size_t minHits) {\n return static_cast(std::ceil(double(hits) \/ double(minHits)));\n}\n\nclass LimitedThreadBundleWrapper final : public vespalib::ThreadBundle\n{\npublic:\n LimitedThreadBundleWrapper(vespalib::ThreadBundle &threadBundle, uint32_t maxThreads) :\n _threadBundle(threadBundle),\n _maxThreads(std::min(maxThreads, static_cast(threadBundle.size())))\n { }\nprivate:\n size_t size() const override { return _maxThreads; }\n void run(const std::vector &targets) override {\n _threadBundle.run(targets);\n }\n vespalib::ThreadBundle &_threadBundle;\n const uint32_t _maxThreads;\n};\n\nbool willNotNeedRanking(const SearchRequest & request, const GroupingContext & groupingContext) {\n return (!groupingContext.needRanking() && (request.maxhits == 0))\n || (!request.sortSpec.empty() && (request.sortSpec.find(\"[rank]\") == vespalib::string::npos));\n}\n\n} \/\/ namespace proton::matching::\n\nFeatureSet::SP\nMatcher::getFeatureSet(const DocsumRequest & req, ISearchContext & searchCtx, IAttributeContext & attrCtx,\n SessionManager & sessionMgr, bool summaryFeatures)\n{\n SessionId sessionId(&req.sessionId[0], req.sessionId.size());\n if (!sessionId.empty()) {\n const Properties &cache_props = req.propertiesMap.cacheProperties();\n bool searchSessionCached = cache_props.lookup(\"query\").found();\n if (searchSessionCached) {\n SearchSession::SP session(sessionMgr.pickSearch(sessionId));\n if (session.get()) {\n MatchToolsFactory &mtf = session->getMatchToolsFactory();\n FeatureSet::SP result = findFeatureSet(req, mtf, summaryFeatures);\n session->releaseEnumGuards();\n return result;\n }\n }\n }\n\n StupidMetaStore metaStore;\n MatchToolsFactory::UP mtf = create_match_tools_factory(req, searchCtx, attrCtx, metaStore,\n req.propertiesMap.featureOverrides());\n if (!mtf->valid()) {\n LOG(warning, \"getFeatureSet(%s): query execution failed (invalid query). Returning empty feature set\",\n (summaryFeatures ? \"summary features\" : \"rank features\"));\n return FeatureSet::SP(new FeatureSet());\n }\n return findFeatureSet(req, *mtf, summaryFeatures);\n}\n\nMatcher::Matcher(const search::index::Schema &schema, const Properties &props, const vespalib::Clock &clock,\n QueryLimiter &queryLimiter, const IConstantValueRepo &constantValueRepo, uint32_t distributionKey)\n : _indexEnv(schema, props, constantValueRepo),\n _blueprintFactory(),\n _rankSetup(),\n _viewResolver(ViewResolver::createFromSchema(schema)),\n _statsLock(),\n _stats(),\n _clock(clock),\n _queryLimiter(queryLimiter),\n _distributionKey(distributionKey)\n{\n search::features::setup_search_features(_blueprintFactory);\n search::fef::test::setup_fef_test_plugin(_blueprintFactory);\n _rankSetup.reset(new search::fef::RankSetup(_blueprintFactory, _indexEnv));\n _rankSetup->configure(); \/\/ reads config values from the property map\n if (!_rankSetup->compile()) {\n throw vespalib::IllegalArgumentException(\"failed to compile rank setup\", VESPA_STRLOC);\n }\n}\n\nMatchingStats\nMatcher::getStats()\n{\n std::lock_guard guard(_statsLock);\n MatchingStats stats = std::move(_stats);\n _stats = std::move(MatchingStats());\n _stats.softDoomFactor(stats.softDoomFactor());\n return stats;\n}\n\nusing search::fef::indexproperties::softtimeout::Enabled;\nusing search::fef::indexproperties::softtimeout::Factor;\n\nstd::unique_ptr\nMatcher::create_match_tools_factory(const search::engine::Request &request, ISearchContext &searchContext,\n IAttributeContext &attrContext, const search::IDocumentMetaStore &metaStore,\n const Properties &feature_overrides) const\n{\n const Properties & rankProperties = request.propertiesMap.rankProperties();\n bool softTimeoutEnabled = Enabled::lookup(rankProperties, _rankSetup->getSoftTimeoutEnabled());\n double factor = softTimeoutEnabled\n ? Factor::lookup(rankProperties, _stats.softDoomFactor())\n : 0.95;\n int64_t safeLeft = request.getTimeLeft() * factor;\n fastos::TimeStamp safeDoom(fastos::ClockSystem::now() + safeLeft);\n if (softTimeoutEnabled) {\n LOG(debug, \"Soft-timeout computed factor=%1.3f, used factor=%1.3f, softTimeout=%lu softDoom=%ld hardDoom=%ld\",\n _stats.softDoomFactor(), factor, safeLeft, safeDoom.ns(), request.getTimeOfDoom().ns());\n }\n return std::make_unique(_queryLimiter, vespalib::Doom(_clock, safeDoom),\n vespalib::Doom(_clock, request.getTimeOfDoom()), searchContext,\n attrContext, request.getStackRef(), request.location, _viewResolver,\n metaStore, _indexEnv, *_rankSetup, rankProperties, feature_overrides);\n}\n\nSearchReply::UP\nMatcher::handleGroupingSession(SessionManager &sessionMgr, GroupingContext & groupingContext,\n GroupingSession::UP groupingSession)\n{\n SearchReply::UP reply = std::make_unique();\n groupingSession->continueExecution(groupingContext);\n groupingContext.getResult().swap(reply->groupResult);\n if (!groupingSession->finished()) {\n sessionMgr.insert(std::move(groupingSession));\n }\n return reply;\n}\n\nsize_t\nMatcher::computeNumThreadsPerSearch(Blueprint::HitEstimate hits, const Properties & rankProperties) const {\n size_t threads = NumThreadsPerSearch::lookup(rankProperties, _rankSetup->getNumThreadsPerSearch());\n uint32_t minHitsPerThread = MinHitsPerThread::lookup(rankProperties, _rankSetup->getMinHitsPerThread());\n if ((threads > 1) && (minHitsPerThread > 0)) {\n threads = (hits.empty) ? 1 : std::min(threads, numThreads(hits.estHits, minHitsPerThread));\n }\n return threads;\n}\n\nSearchReply::UP\nMatcher::match(const SearchRequest &request, vespalib::ThreadBundle &threadBundle,\n ISearchContext &searchContext, IAttributeContext &attrContext,\n SessionManager &sessionMgr, const search::IDocumentMetaStore &metaStore,\n SearchSession::OwnershipBundle &&owned_objects)\n{\n fastos::StopWatch total_matching_time;\n total_matching_time.start();\n MatchingStats my_stats;\n SearchReply::UP reply = std::make_unique();\n { \/\/ we want to measure full set-up and tear-down time as part of\n \/\/ collateral time\n GroupingContext groupingContext(_clock, request.getTimeOfDoom(),\n &request.groupSpec[0], request.groupSpec.size());\n SessionId sessionId(&request.sessionId[0], request.sessionId.size());\n bool shouldCacheSearchSession = false;\n bool shouldCacheGroupingSession = false;\n if (!sessionId.empty()) {\n const Properties &cache_props = request.propertiesMap.cacheProperties();\n shouldCacheGroupingSession = cache_props.lookup(\"grouping\").found();\n shouldCacheSearchSession = cache_props.lookup(\"query\").found();\n if (shouldCacheGroupingSession) {\n GroupingSession::UP session(sessionMgr.pickGrouping(sessionId));\n if (session.get()) {\n return handleGroupingSession(sessionMgr, groupingContext, std::move(session));\n }\n }\n }\n const Properties *feature_overrides = &request.propertiesMap.featureOverrides();\n if (shouldCacheSearchSession) {\n owned_objects.feature_overrides.reset(new Properties(*feature_overrides));\n feature_overrides = owned_objects.feature_overrides.get();\n }\n MatchToolsFactory::UP mtf = create_match_tools_factory(request, searchContext, attrContext,\n metaStore, *feature_overrides);\n if (!mtf->valid()) {\n reply->errorCode = ECODE_QUERY_PARSE_ERROR;\n reply->errorMessage = \"query execution failed (invalid query)\";\n return reply;\n }\n\n MatchParams params(searchContext.getDocIdLimit(), _rankSetup->getHeapSize(), _rankSetup->getArraySize(),\n _rankSetup->getRankScoreDropLimit(), request.offset, request.maxhits,\n !_rankSetup->getSecondPhaseRank().empty(), !willNotNeedRanking(request, groupingContext));\n\n ResultProcessor rp(attrContext, metaStore, sessionMgr, groupingContext, sessionId,\n request.sortSpec, params.offset, params.hits);\n\n const Properties & rankProperties = request.propertiesMap.rankProperties();\n size_t numThreadsPerSearch = computeNumThreadsPerSearch(mtf->estimate(), rankProperties);\n LimitedThreadBundleWrapper limitedThreadBundle(threadBundle, numThreadsPerSearch);\n MatchMaster master;\n uint32_t numSearchPartitions = NumSearchPartitions::lookup(rankProperties,\n _rankSetup->getNumSearchPartitions());\n ResultProcessor::Result::UP result = master.match(params, limitedThreadBundle, *mtf, rp,\n _distributionKey, numSearchPartitions);\n my_stats = MatchMaster::getStats(std::move(master));\n\n bool wasLimited = mtf->match_limiter().was_limited();\n size_t spaceEstimate = mtf->match_limiter().getDocIdSpaceEstimate();\n uint32_t estHits = mtf->estimate().estHits;\n if (shouldCacheSearchSession && ((result->_numFs4Hits != 0) || shouldCacheGroupingSession)) {\n SearchSession::SP session = std::make_shared(sessionId, request.getTimeOfDoom(),\n std::move(mtf), std::move(owned_objects));\n session->releaseEnumGuards();\n sessionMgr.insert(std::move(session));\n }\n reply = std::move(result->_reply);\n\n uint32_t numActiveLids = metaStore.getNumActiveLids();\n \/\/ note: this is actually totalSpace+1, since 0 is reserved\n uint32_t totalSpace = metaStore.getCommittedDocIdLimit();\n LOG(debug, \"docid limit = %d\", totalSpace);\n LOG(debug, \"num active lids = %d\", numActiveLids);\n LOG(debug, \"space Estimate = %zd\", spaceEstimate);\n if (spaceEstimate >= totalSpace) {\n \/\/ estimate is too high, clamp it\n spaceEstimate = totalSpace;\n } else {\n \/\/ account for docid 0 reserved\n spaceEstimate += 1;\n }\n size_t covered = (spaceEstimate * numActiveLids) \/ totalSpace;\n LOG(debug, \"covered = %zd\", covered);\n\n SearchReply::Coverage & coverage = reply->coverage;\n coverage.setActive(numActiveLids);\n \/\/TODO this should be calculated with ClusterState calculator.\n coverage.setSoonActive(numActiveLids);\n coverage.setCovered(covered);\n if (wasLimited) {\n coverage.degradeMatchPhase();\n LOG(debug, \"was limited, degraded from match phase\");\n }\n if (my_stats.softDoomed()) {\n coverage.degradeTimeout();\n coverage.setCovered(my_stats.docsCovered());\n LOG(debug, \"soft doomed, degraded from timeout covered = %lu\", coverage.getCovered()); }\n LOG(debug, \"numThreadsPerSearch = %zu. Configured = %d, estimated hits=%d, totalHits=%ld\",\n numThreadsPerSearch, _rankSetup->getNumThreadsPerSearch(), estHits, reply->totalHitCount);\n }\n total_matching_time.stop();\n my_stats.queryCollateralTime(total_matching_time.elapsed().sec() - my_stats.queryLatencyAvg());\n {\n fastos::TimeStamp softLimit = uint64_t((1.0 - _rankSetup->getSoftTimeoutTailCost()) * request.getTimeout());\n fastos::TimeStamp duration = request.getTimeUsed();\n std::lock_guard guard(_statsLock);\n _stats.add(my_stats);\n if (my_stats.softDoomed()) {\n LOG(info, \"Triggered softtimeout limit=%1.3f and duration=%1.3f\", softLimit.sec(), duration.sec());\n _stats.updatesoftDoomFactor(request.getTimeout(), softLimit, duration);\n }\n }\n return reply;\n}\n\nFeatureSet::SP\nMatcher::getSummaryFeatures(const DocsumRequest & req, ISearchContext & searchCtx,\n IAttributeContext & attrCtx, SessionManager &sessionMgr)\n{\n return getFeatureSet(req, searchCtx, attrCtx, sessionMgr, true);\n}\n\nFeatureSet::SP\nMatcher::getRankFeatures(const DocsumRequest & req, ISearchContext & searchCtx,\n IAttributeContext & attrCtx, SessionManager &sessionMgr)\n{\n return getFeatureSet(req, searchCtx, attrCtx, sessionMgr, false);\n}\n\n}\nIll placed brace.\/\/ Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n\n#include \"isearchcontext.h\"\n#include \"match_master.h\"\n#include \"match_context.h\"\n#include \"match_tools.h\"\n#include \"match_params.h\"\n#include \"matcher.h\"\n#include \"sessionmanager.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \nLOG_SETUP(\".proton.matching.matcher\");\n\nusing search::fef::Properties;\nusing namespace search::fef::indexproperties::matching;\nusing namespace search::engine;\nusing namespace search::grouping;\nusing search::DocumentMetaData;\nusing search::LidUsageStats;\nusing search::FeatureSet;\nusing search::attribute::IAttributeContext;\nusing search::fef::MatchDataLayout;\nusing search::fef::MatchData;\nusing search::queryeval::Blueprint;\nusing search::queryeval::SearchIterator;\nusing vespalib::Doom;\n\nnamespace proton::matching {\n\nnamespace {\n\n\/\/ used to give out empty blacklist blueprints\nstruct StupidMetaStore : search::IDocumentMetaStore {\n bool getGid(DocId, GlobalId &) const override { return false; }\n bool getGidEvenIfMoved(DocId, GlobalId &) const override { return false; }\n bool getLid(const GlobalId &, DocId &) const override { return false; }\n DocumentMetaData getMetaData(const GlobalId &) const override { return DocumentMetaData(); }\n void getMetaData(const BucketId &, DocumentMetaData::Vector &) const override { }\n DocId getCommittedDocIdLimit() const override { return 1; }\n DocId getNumUsedLids() const override { return 0; }\n DocId getNumActiveLids() const override { return 0; }\n uint64_t getCurrentGeneration() const override { return 0; }\n LidUsageStats getLidUsageStats() const override { return LidUsageStats(); }\n Blueprint::UP createBlackListBlueprint() const override { return Blueprint::UP(); }\n};\n\nFeatureSet::SP findFeatureSet(const DocsumRequest &req,\n MatchToolsFactory &mtf, bool summaryFeatures) {\n std::vector docs;\n for (size_t i = 0; i < req.hits.size(); ++i) {\n if (req.hits[i].docid != search::endDocId) {\n docs.push_back(req.hits[i].docid);\n }\n }\n std::sort(docs.begin(), docs.end());\n return MatchMaster::getFeatureSet(mtf, docs, summaryFeatures);\n}\n\nsize_t numThreads(size_t hits, size_t minHits) {\n return static_cast(std::ceil(double(hits) \/ double(minHits)));\n}\n\nclass LimitedThreadBundleWrapper final : public vespalib::ThreadBundle\n{\npublic:\n LimitedThreadBundleWrapper(vespalib::ThreadBundle &threadBundle, uint32_t maxThreads) :\n _threadBundle(threadBundle),\n _maxThreads(std::min(maxThreads, static_cast(threadBundle.size())))\n { }\nprivate:\n size_t size() const override { return _maxThreads; }\n void run(const std::vector &targets) override {\n _threadBundle.run(targets);\n }\n vespalib::ThreadBundle &_threadBundle;\n const uint32_t _maxThreads;\n};\n\nbool willNotNeedRanking(const SearchRequest & request, const GroupingContext & groupingContext) {\n return (!groupingContext.needRanking() && (request.maxhits == 0))\n || (!request.sortSpec.empty() && (request.sortSpec.find(\"[rank]\") == vespalib::string::npos));\n}\n\n} \/\/ namespace proton::matching::\n\nFeatureSet::SP\nMatcher::getFeatureSet(const DocsumRequest & req, ISearchContext & searchCtx, IAttributeContext & attrCtx,\n SessionManager & sessionMgr, bool summaryFeatures)\n{\n SessionId sessionId(&req.sessionId[0], req.sessionId.size());\n if (!sessionId.empty()) {\n const Properties &cache_props = req.propertiesMap.cacheProperties();\n bool searchSessionCached = cache_props.lookup(\"query\").found();\n if (searchSessionCached) {\n SearchSession::SP session(sessionMgr.pickSearch(sessionId));\n if (session.get()) {\n MatchToolsFactory &mtf = session->getMatchToolsFactory();\n FeatureSet::SP result = findFeatureSet(req, mtf, summaryFeatures);\n session->releaseEnumGuards();\n return result;\n }\n }\n }\n\n StupidMetaStore metaStore;\n MatchToolsFactory::UP mtf = create_match_tools_factory(req, searchCtx, attrCtx, metaStore,\n req.propertiesMap.featureOverrides());\n if (!mtf->valid()) {\n LOG(warning, \"getFeatureSet(%s): query execution failed (invalid query). Returning empty feature set\",\n (summaryFeatures ? \"summary features\" : \"rank features\"));\n return FeatureSet::SP(new FeatureSet());\n }\n return findFeatureSet(req, *mtf, summaryFeatures);\n}\n\nMatcher::Matcher(const search::index::Schema &schema, const Properties &props, const vespalib::Clock &clock,\n QueryLimiter &queryLimiter, const IConstantValueRepo &constantValueRepo, uint32_t distributionKey)\n : _indexEnv(schema, props, constantValueRepo),\n _blueprintFactory(),\n _rankSetup(),\n _viewResolver(ViewResolver::createFromSchema(schema)),\n _statsLock(),\n _stats(),\n _clock(clock),\n _queryLimiter(queryLimiter),\n _distributionKey(distributionKey)\n{\n search::features::setup_search_features(_blueprintFactory);\n search::fef::test::setup_fef_test_plugin(_blueprintFactory);\n _rankSetup.reset(new search::fef::RankSetup(_blueprintFactory, _indexEnv));\n _rankSetup->configure(); \/\/ reads config values from the property map\n if (!_rankSetup->compile()) {\n throw vespalib::IllegalArgumentException(\"failed to compile rank setup\", VESPA_STRLOC);\n }\n}\n\nMatchingStats\nMatcher::getStats()\n{\n std::lock_guard guard(_statsLock);\n MatchingStats stats = std::move(_stats);\n _stats = std::move(MatchingStats());\n _stats.softDoomFactor(stats.softDoomFactor());\n return stats;\n}\n\nusing search::fef::indexproperties::softtimeout::Enabled;\nusing search::fef::indexproperties::softtimeout::Factor;\n\nstd::unique_ptr\nMatcher::create_match_tools_factory(const search::engine::Request &request, ISearchContext &searchContext,\n IAttributeContext &attrContext, const search::IDocumentMetaStore &metaStore,\n const Properties &feature_overrides) const\n{\n const Properties & rankProperties = request.propertiesMap.rankProperties();\n bool softTimeoutEnabled = Enabled::lookup(rankProperties, _rankSetup->getSoftTimeoutEnabled());\n double factor = softTimeoutEnabled\n ? Factor::lookup(rankProperties, _stats.softDoomFactor())\n : 0.95;\n int64_t safeLeft = request.getTimeLeft() * factor;\n fastos::TimeStamp safeDoom(fastos::ClockSystem::now() + safeLeft);\n if (softTimeoutEnabled) {\n LOG(debug, \"Soft-timeout computed factor=%1.3f, used factor=%1.3f, softTimeout=%lu softDoom=%ld hardDoom=%ld\",\n _stats.softDoomFactor(), factor, safeLeft, safeDoom.ns(), request.getTimeOfDoom().ns());\n }\n return std::make_unique(_queryLimiter, vespalib::Doom(_clock, safeDoom),\n vespalib::Doom(_clock, request.getTimeOfDoom()), searchContext,\n attrContext, request.getStackRef(), request.location, _viewResolver,\n metaStore, _indexEnv, *_rankSetup, rankProperties, feature_overrides);\n}\n\nSearchReply::UP\nMatcher::handleGroupingSession(SessionManager &sessionMgr, GroupingContext & groupingContext,\n GroupingSession::UP groupingSession)\n{\n SearchReply::UP reply = std::make_unique();\n groupingSession->continueExecution(groupingContext);\n groupingContext.getResult().swap(reply->groupResult);\n if (!groupingSession->finished()) {\n sessionMgr.insert(std::move(groupingSession));\n }\n return reply;\n}\n\nsize_t\nMatcher::computeNumThreadsPerSearch(Blueprint::HitEstimate hits, const Properties & rankProperties) const {\n size_t threads = NumThreadsPerSearch::lookup(rankProperties, _rankSetup->getNumThreadsPerSearch());\n uint32_t minHitsPerThread = MinHitsPerThread::lookup(rankProperties, _rankSetup->getMinHitsPerThread());\n if ((threads > 1) && (minHitsPerThread > 0)) {\n threads = (hits.empty) ? 1 : std::min(threads, numThreads(hits.estHits, minHitsPerThread));\n }\n return threads;\n}\n\nSearchReply::UP\nMatcher::match(const SearchRequest &request, vespalib::ThreadBundle &threadBundle,\n ISearchContext &searchContext, IAttributeContext &attrContext,\n SessionManager &sessionMgr, const search::IDocumentMetaStore &metaStore,\n SearchSession::OwnershipBundle &&owned_objects)\n{\n fastos::StopWatch total_matching_time;\n total_matching_time.start();\n MatchingStats my_stats;\n SearchReply::UP reply = std::make_unique();\n { \/\/ we want to measure full set-up and tear-down time as part of\n \/\/ collateral time\n GroupingContext groupingContext(_clock, request.getTimeOfDoom(),\n &request.groupSpec[0], request.groupSpec.size());\n SessionId sessionId(&request.sessionId[0], request.sessionId.size());\n bool shouldCacheSearchSession = false;\n bool shouldCacheGroupingSession = false;\n if (!sessionId.empty()) {\n const Properties &cache_props = request.propertiesMap.cacheProperties();\n shouldCacheGroupingSession = cache_props.lookup(\"grouping\").found();\n shouldCacheSearchSession = cache_props.lookup(\"query\").found();\n if (shouldCacheGroupingSession) {\n GroupingSession::UP session(sessionMgr.pickGrouping(sessionId));\n if (session.get()) {\n return handleGroupingSession(sessionMgr, groupingContext, std::move(session));\n }\n }\n }\n const Properties *feature_overrides = &request.propertiesMap.featureOverrides();\n if (shouldCacheSearchSession) {\n owned_objects.feature_overrides.reset(new Properties(*feature_overrides));\n feature_overrides = owned_objects.feature_overrides.get();\n }\n MatchToolsFactory::UP mtf = create_match_tools_factory(request, searchContext, attrContext,\n metaStore, *feature_overrides);\n if (!mtf->valid()) {\n reply->errorCode = ECODE_QUERY_PARSE_ERROR;\n reply->errorMessage = \"query execution failed (invalid query)\";\n return reply;\n }\n\n MatchParams params(searchContext.getDocIdLimit(), _rankSetup->getHeapSize(), _rankSetup->getArraySize(),\n _rankSetup->getRankScoreDropLimit(), request.offset, request.maxhits,\n !_rankSetup->getSecondPhaseRank().empty(), !willNotNeedRanking(request, groupingContext));\n\n ResultProcessor rp(attrContext, metaStore, sessionMgr, groupingContext, sessionId,\n request.sortSpec, params.offset, params.hits);\n\n const Properties & rankProperties = request.propertiesMap.rankProperties();\n size_t numThreadsPerSearch = computeNumThreadsPerSearch(mtf->estimate(), rankProperties);\n LimitedThreadBundleWrapper limitedThreadBundle(threadBundle, numThreadsPerSearch);\n MatchMaster master;\n uint32_t numSearchPartitions = NumSearchPartitions::lookup(rankProperties,\n _rankSetup->getNumSearchPartitions());\n ResultProcessor::Result::UP result = master.match(params, limitedThreadBundle, *mtf, rp,\n _distributionKey, numSearchPartitions);\n my_stats = MatchMaster::getStats(std::move(master));\n\n bool wasLimited = mtf->match_limiter().was_limited();\n size_t spaceEstimate = mtf->match_limiter().getDocIdSpaceEstimate();\n uint32_t estHits = mtf->estimate().estHits;\n if (shouldCacheSearchSession && ((result->_numFs4Hits != 0) || shouldCacheGroupingSession)) {\n SearchSession::SP session = std::make_shared(sessionId, request.getTimeOfDoom(),\n std::move(mtf), std::move(owned_objects));\n session->releaseEnumGuards();\n sessionMgr.insert(std::move(session));\n }\n reply = std::move(result->_reply);\n\n uint32_t numActiveLids = metaStore.getNumActiveLids();\n \/\/ note: this is actually totalSpace+1, since 0 is reserved\n uint32_t totalSpace = metaStore.getCommittedDocIdLimit();\n LOG(debug, \"docid limit = %d\", totalSpace);\n LOG(debug, \"num active lids = %d\", numActiveLids);\n LOG(debug, \"space Estimate = %zd\", spaceEstimate);\n if (spaceEstimate >= totalSpace) {\n \/\/ estimate is too high, clamp it\n spaceEstimate = totalSpace;\n } else {\n \/\/ account for docid 0 reserved\n spaceEstimate += 1;\n }\n size_t covered = (spaceEstimate * numActiveLids) \/ totalSpace;\n LOG(debug, \"covered = %zd\", covered);\n\n SearchReply::Coverage & coverage = reply->coverage;\n coverage.setActive(numActiveLids);\n \/\/TODO this should be calculated with ClusterState calculator.\n coverage.setSoonActive(numActiveLids);\n coverage.setCovered(covered);\n if (wasLimited) {\n coverage.degradeMatchPhase();\n LOG(debug, \"was limited, degraded from match phase\");\n }\n if (my_stats.softDoomed()) {\n coverage.degradeTimeout();\n coverage.setCovered(my_stats.docsCovered());\n LOG(debug, \"soft doomed, degraded from timeout covered = %lu\", coverage.getCovered());\n }\n LOG(debug, \"numThreadsPerSearch = %zu. Configured = %d, estimated hits=%d, totalHits=%ld\",\n numThreadsPerSearch, _rankSetup->getNumThreadsPerSearch(), estHits, reply->totalHitCount);\n }\n total_matching_time.stop();\n my_stats.queryCollateralTime(total_matching_time.elapsed().sec() - my_stats.queryLatencyAvg());\n {\n fastos::TimeStamp softLimit = uint64_t((1.0 - _rankSetup->getSoftTimeoutTailCost()) * request.getTimeout());\n fastos::TimeStamp duration = request.getTimeUsed();\n std::lock_guard guard(_statsLock);\n _stats.add(my_stats);\n if (my_stats.softDoomed()) {\n LOG(info, \"Triggered softtimeout limit=%1.3f and duration=%1.3f\", softLimit.sec(), duration.sec());\n _stats.updatesoftDoomFactor(request.getTimeout(), softLimit, duration);\n }\n }\n return reply;\n}\n\nFeatureSet::SP\nMatcher::getSummaryFeatures(const DocsumRequest & req, ISearchContext & searchCtx,\n IAttributeContext & attrCtx, SessionManager &sessionMgr)\n{\n return getFeatureSet(req, searchCtx, attrCtx, sessionMgr, true);\n}\n\nFeatureSet::SP\nMatcher::getRankFeatures(const DocsumRequest & req, ISearchContext & searchCtx,\n IAttributeContext & attrCtx, SessionManager &sessionMgr)\n{\n return getFeatureSet(req, searchCtx, attrCtx, sessionMgr, false);\n}\n\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: fuhhconv.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2004-07-13 13:51:33 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \n#include \"drawdoc.hxx\"\n#include \"Outliner.hxx\"\n#include \"DrawViewShell.hxx\"\n#include \"OutlineViewShell.hxx\"\n\n#ifndef SD_VIEW_SHELL_BASE_HXX\n#include \"ViewShellBase.hxx\"\n#endif\n\n#include \"sdresid.hxx\"\n#include \"strings.hrc\"\n\nclass SfxRequest;\n\nnamespace sd {\n\nclass ViewShell;\n\nTYPEINIT1( FuHangulHanjaConversion, FuPoor );\n\n\/*************************************************************************\n|*\n|* Konstruktor\n|*\n\\************************************************************************\/\n\nFuHangulHanjaConversion::FuHangulHanjaConversion (\n ViewShell* pViewSh,\n ::sd::Window* pWin,\n ::sd::View* pView,\n SdDrawDocument* pDocument,\n SfxRequest& rReq )\n : FuPoor(pViewSh, pWin, pView, pDocument, rReq),\n pSdOutliner(NULL),\n bOwnOutliner(FALSE)\n{\n if ( pViewShell->ISA(DrawViewShell) )\n {\n bOwnOutliner = TRUE;\n pSdOutliner = new Outliner( pDoc, OUTLINERMODE_TEXTOBJECT );\n }\n else if ( pViewShell->ISA(OutlineViewShell) )\n {\n bOwnOutliner = FALSE;\n pSdOutliner = pDoc->GetOutliner();\n }\n\n if (pSdOutliner)\n pSdOutliner->PrepareSpelling();\n}\n\n\n\n\/*************************************************************************\n|*\n|* Destruktor\n|*\n\\************************************************************************\/\n\nFuHangulHanjaConversion::~FuHangulHanjaConversion()\n{\n if (pSdOutliner)\n pSdOutliner->EndConversion();\n\n if (bOwnOutliner)\n delete pSdOutliner;\n}\n\n\n\/*************************************************************************\n|*\n|* Suchen&Ersetzen\n|*\n\\************************************************************************\/\n\nvoid FuHangulHanjaConversion::StartConversion( INT16 nLanguage )\n{\n\n String aString( SdResId(STR_UNDO_HANGULHANJACONVERSION) );\n pView->BegUndo( aString );\n\n ViewShellBase* pBase = PTR_CAST(ViewShellBase, SfxViewShell::Current());\n if (pBase != NULL)\n pViewShell = pBase->GetMainViewShell();\n\n if( pViewShell )\n {\n if ( pSdOutliner && pViewShell->ISA(DrawViewShell) && !bOwnOutliner )\n {\n pSdOutliner->EndConversion();\n\n bOwnOutliner = TRUE;\n pSdOutliner = new Outliner( pDoc, OUTLINERMODE_TEXTOBJECT );\n pSdOutliner->BeginConversion();\n }\n else if ( pSdOutliner && pViewShell->ISA(OutlineViewShell) && bOwnOutliner )\n {\n pSdOutliner->EndConversion();\n delete pSdOutliner;\n\n bOwnOutliner = FALSE;\n pSdOutliner = pDoc->GetOutliner();\n pSdOutliner->BeginConversion();\n }\n\n if (pSdOutliner)\n pSdOutliner->StartTextConversion(nLanguage);\n }\n\n pView->EndUndo();\n}\n\n} \/\/ end of namespace\nINTEGRATION: CWS os34 (1.2.18); FILE MERGED 2004\/08\/06 18:18:29 tl 1.2.18.3: RESYNC: (1.2-1.3); FILE MERGED 2004\/08\/04 13:51:28 tl 1.2.18.2: #i30301# simplified\/traditional Chinese conversion 2004\/07\/27 13:58:14 tl 1.2.18.1: #i30303# preparational changes for simplified\/traditional Chinese conversion\/*************************************************************************\n *\n * $RCSfile: fuhhconv.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2004-09-17 13:24:47 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \n#include \"drawdoc.hxx\"\n#include \"Outliner.hxx\"\n#include \"DrawViewShell.hxx\"\n#include \"OutlineViewShell.hxx\"\n\n#ifndef SD_VIEW_SHELL_BASE_HXX\n#include \"ViewShellBase.hxx\"\n#endif\n\n#include \"sdresid.hxx\"\n#include \"strings.hrc\"\n\nclass SfxRequest;\n\nnamespace sd {\n\nclass ViewShell;\n\nTYPEINIT1( FuHangulHanjaConversion, FuPoor );\n\n\/*************************************************************************\n|*\n|* Konstruktor\n|*\n\\************************************************************************\/\n\nFuHangulHanjaConversion::FuHangulHanjaConversion (\n ViewShell* pViewSh,\n ::sd::Window* pWin,\n ::sd::View* pView,\n SdDrawDocument* pDocument,\n SfxRequest& rReq )\n : FuPoor(pViewSh, pWin, pView, pDocument, rReq),\n pSdOutliner(NULL),\n bOwnOutliner(FALSE)\n{\n if ( pViewShell->ISA(DrawViewShell) )\n {\n bOwnOutliner = TRUE;\n pSdOutliner = new Outliner( pDoc, OUTLINERMODE_TEXTOBJECT );\n }\n else if ( pViewShell->ISA(OutlineViewShell) )\n {\n bOwnOutliner = FALSE;\n pSdOutliner = pDoc->GetOutliner();\n }\n\n if (pSdOutliner)\n pSdOutliner->PrepareSpelling();\n}\n\n\n\n\/*************************************************************************\n|*\n|* Destruktor\n|*\n\\************************************************************************\/\n\nFuHangulHanjaConversion::~FuHangulHanjaConversion()\n{\n if (pSdOutliner)\n pSdOutliner->EndConversion();\n\n if (bOwnOutliner)\n delete pSdOutliner;\n}\n\n\n\/*************************************************************************\n|*\n|* Suchen&Ersetzen\n|*\n\\************************************************************************\/\n\nvoid FuHangulHanjaConversion::StartConversion( INT16 nSourceLanguage, INT16 nTargetLanguage,\n const Font *pTargetFont, INT32 nOptions, BOOL bIsInteractive )\n{\n\n String aString( SdResId(STR_UNDO_HANGULHANJACONVERSION) );\n pView->BegUndo( aString );\n\n ViewShellBase* pBase = PTR_CAST(ViewShellBase, SfxViewShell::Current());\n if (pBase != NULL)\n pViewShell = pBase->GetMainViewShell();\n\n if( pViewShell )\n {\n if ( pSdOutliner && pViewShell->ISA(DrawViewShell) && !bOwnOutliner )\n {\n pSdOutliner->EndConversion();\n\n bOwnOutliner = TRUE;\n pSdOutliner = new Outliner( pDoc, OUTLINERMODE_TEXTOBJECT );\n pSdOutliner->BeginConversion();\n }\n else if ( pSdOutliner && pViewShell->ISA(OutlineViewShell) && bOwnOutliner )\n {\n pSdOutliner->EndConversion();\n delete pSdOutliner;\n\n bOwnOutliner = FALSE;\n pSdOutliner = pDoc->GetOutliner();\n pSdOutliner->BeginConversion();\n }\n\n if (pSdOutliner)\n pSdOutliner->StartConversion(nSourceLanguage, nTargetLanguage, pTargetFont, nOptions, bIsInteractive );\n }\n\n pView->EndUndo();\n}\n\n} \/\/ end of namespace\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n\/\/\n\/\/ vie_autotest_image_process.cc\n\/\/\n\n\/\/ Settings\n#include \"vie_autotest_defines.h\"\n#include \"vie_autotest.h\"\n#include \"engine_configurations.h\"\n\n#include \"tb_interfaces.h\"\n#include \"tb_video_channel.h\"\n#include \"tb_capture_device.h\"\n\nclass MyEffectFilter: public webrtc::ViEEffectFilter\n{\npublic:\n MyEffectFilter() {}\n\n ~MyEffectFilter() {}\n\n virtual int Transform(int size, unsigned char* frameBuffer,\n unsigned int timeStamp90KHz, unsigned int width,\n unsigned int height)\n {\n \/\/ Black and white\n memset(frameBuffer + (2 * size) \/ 3, 0x7f, size \/ 3);\n return 0;\n }\n};\n\nvoid ViEAutoTest::ViEImageProcessStandardTest()\n{\n \/\/***************************************************************\n \/\/\tBegin create\/initialize WebRTC Video Engine for testing\n \/\/***************************************************************\n int rtpPort = 6000;\n \/\/ Create VIE\n TbInterfaces ViE(\"ViEImageProcessAPITest\");\n \/\/ Create a video channel\n TbVideoChannel tbChannel(ViE, webrtc::kVideoCodecVP8);\n \/\/ Create a capture device\n TbCaptureDevice tbCapture(ViE);\n\n tbCapture.ConnectTo(tbChannel.videoChannel);\n tbChannel.StartReceive(rtpPort);\n tbChannel.StartSend(rtpPort);\n\n MyEffectFilter effectFilter;\n\n RenderCaptureDeviceAndOutputStream(&ViE, &tbChannel, &tbCapture);\n\n ViETest::Log(\"Capture device is renderered in Window 1\");\n ViETest::Log(\"Remote stream is renderered in Window 2\");\n AutoTestSleep(KAutoTestSleepTimeMs);\n\n \/\/***************************************************************\n \/\/\tEngine ready. Begin testing class\n \/\/***************************************************************\n\n\n EXPECT_EQ(0, ViE.image_process->RegisterCaptureEffectFilter(\n tbCapture.captureId, effectFilter));\n\n ViETest::Log(\"Black and white filter registered for capture device, \"\n \"affects both windows\");\n AutoTestSleep(KAutoTestSleepTimeMs);\n\n EXPECT_EQ(0, ViE.image_process->DeregisterCaptureEffectFilter(\n tbCapture.captureId));\n\n EXPECT_EQ(0, ViE.image_process->RegisterRenderEffectFilter(\n tbChannel.videoChannel, effectFilter));\n\n ViETest::Log(\"Remove capture effect filter, adding filter for incoming \"\n \"stream\");\n ViETest::Log(\"Only Window 2 should be black and white\");\n AutoTestSleep(KAutoTestSleepTimeMs);\n\n EXPECT_EQ(0, ViE.render->StopRender(tbCapture.captureId));\n EXPECT_EQ(0, ViE.render->RemoveRenderer(tbCapture.captureId));\n\n int rtpPort2 = rtpPort + 100;\n \/\/ Create a video channel\n TbVideoChannel tbChannel2(ViE, webrtc::kVideoCodecVP8);\n\n tbCapture.ConnectTo(tbChannel2.videoChannel);\n tbChannel2.StartReceive(rtpPort2);\n tbChannel2.StartSend(rtpPort2);\n\n EXPECT_EQ(0, ViE.render->AddRenderer(\n tbChannel2.videoChannel, _window1, 1, 0.0, 0.0, 1.0, 1.0));\n EXPECT_EQ(0, ViE.render->StartRender(tbChannel2.videoChannel));\n EXPECT_EQ(0, ViE.image_process->DeregisterRenderEffectFilter(\n tbChannel.videoChannel));\n\n ViETest::Log(\"Local renderer removed, added new channel and rendering in \"\n \"Window1.\");\n\n EXPECT_EQ(0, ViE.image_process->RegisterCaptureEffectFilter(\n tbCapture.captureId, effectFilter));\n\n ViETest::Log(\"Black and white filter registered for capture device, \"\n \"affects both windows\");\n AutoTestSleep(KAutoTestSleepTimeMs);\n\n EXPECT_EQ(0, ViE.image_process->DeregisterCaptureEffectFilter(\n tbCapture.captureId));\n\n EXPECT_EQ(0, ViE.image_process->RegisterSendEffectFilter(\n tbChannel.videoChannel, effectFilter));\n\n ViETest::Log(\"Capture filter removed.\");\n ViETest::Log(\"Black and white filter registered for one channel, Window2 \"\n \"should be black and white\");\n AutoTestSleep(KAutoTestSleepTimeMs);\n\n EXPECT_EQ(0, ViE.image_process->DeregisterSendEffectFilter(\n tbChannel.videoChannel));\n\n \/\/***************************************************************\n \/\/\tTesting finished. Tear down Video Engine\n \/\/***************************************************************\n}\n\nvoid ViEAutoTest::ViEImageProcessExtendedTest()\n{\n ViEImageProcessStandardTest();\n}\n\nvoid ViEAutoTest::ViEImageProcessAPITest()\n{\n TbInterfaces ViE(\"ViEImageProcessAPITest\");\n TbVideoChannel tbChannel(ViE, webrtc::kVideoCodecVP8);\n TbCaptureDevice tbCapture(ViE);\n\n tbCapture.ConnectTo(tbChannel.videoChannel);\n\n MyEffectFilter effectFilter;\n\n \/\/\n \/\/ Capture effect filter\n \/\/\n \/\/ Add effect filter\n EXPECT_EQ(0, ViE.image_process->RegisterCaptureEffectFilter(\n tbCapture.captureId, effectFilter));\n \/\/ Add again -> error\n EXPECT_NE(0, ViE.image_process->RegisterCaptureEffectFilter(\n tbCapture.captureId, effectFilter));\n EXPECT_EQ(0, ViE.image_process->DeregisterCaptureEffectFilter(\n tbCapture.captureId));\n\n \/\/ Double deregister\n EXPECT_NE(0, ViE.image_process->DeregisterCaptureEffectFilter(\n tbCapture.captureId));\n \/\/ Non-existing capture device\n EXPECT_NE(0, ViE.image_process->RegisterCaptureEffectFilter(\n tbChannel.videoChannel, effectFilter));\n\n \/\/\n \/\/ Render effect filter\n \/\/\n EXPECT_EQ(0, ViE.image_process->RegisterRenderEffectFilter(\n tbChannel.videoChannel, effectFilter));\n EXPECT_NE(0, ViE.image_process->RegisterRenderEffectFilter(\n tbChannel.videoChannel, effectFilter));\n EXPECT_EQ(0, ViE.image_process->DeregisterRenderEffectFilter(\n tbChannel.videoChannel));\n EXPECT_NE(0, ViE.image_process->DeregisterRenderEffectFilter(\n tbChannel.videoChannel));\n\n \/\/ Non-existing channel id\n EXPECT_NE(0, ViE.image_process->RegisterRenderEffectFilter(\n tbCapture.captureId, effectFilter));\n\n \/\/\n \/\/ Send effect filter\n \/\/\n EXPECT_EQ(0, ViE.image_process->RegisterSendEffectFilter(\n tbChannel.videoChannel, effectFilter));\n EXPECT_NE(0, ViE.image_process->RegisterSendEffectFilter(\n tbChannel.videoChannel, effectFilter));\n EXPECT_EQ(0, ViE.image_process->DeregisterSendEffectFilter(\n tbChannel.videoChannel));\n EXPECT_NE(0, ViE.image_process->DeregisterSendEffectFilter(\n tbChannel.videoChannel));\n EXPECT_NE(0, ViE.image_process->RegisterSendEffectFilter(\n tbCapture.captureId, effectFilter));\n\n \/\/\n \/\/ Denoising\n \/\/\n EXPECT_EQ(0, ViE.image_process->EnableDenoising(tbCapture.captureId, true));\n \/\/ If the denoising is already enabled, it will just reuturn 0.\n EXPECT_EQ(0, ViE.image_process->EnableDenoising(tbCapture.captureId, true));\n EXPECT_EQ(0, ViE.image_process->EnableDenoising(\n tbCapture.captureId, false));\n \/\/ If the denoising is already disabled, it will just reuturn 0.\n EXPECT_EQ(0, ViE.image_process->EnableDenoising(\n tbCapture.captureId, false));\n EXPECT_NE(0, ViE.image_process->EnableDenoising(\n tbChannel.videoChannel, true));\n\n \/\/\n \/\/ Deflickering\n \/\/\n EXPECT_EQ(0, ViE.image_process->EnableDeflickering(\n tbCapture.captureId, true));\n EXPECT_NE(0, ViE.image_process->EnableDeflickering(\n tbCapture.captureId, true));\n EXPECT_EQ(0, ViE.image_process->EnableDeflickering(\n tbCapture.captureId, false));\n EXPECT_NE(0, ViE.image_process->EnableDeflickering(\n tbCapture.captureId, false));\n EXPECT_NE(0, ViE.image_process->EnableDeflickering(\n tbChannel.videoChannel, true));\n\n \/\/\n \/\/ Color enhancement\n \/\/\n EXPECT_EQ(0, ViE.image_process->EnableColorEnhancement(\n tbChannel.videoChannel, false));\n EXPECT_EQ(0, ViE.image_process->EnableColorEnhancement(\n tbChannel.videoChannel, true));\n EXPECT_NE(0, ViE.image_process->EnableColorEnhancement(\n tbChannel.videoChannel, true));\n EXPECT_EQ(0, ViE.image_process->EnableColorEnhancement(\n tbChannel.videoChannel, false));\n EXPECT_NE(0, ViE.image_process->EnableColorEnhancement(\n tbChannel.videoChannel, false));\n EXPECT_NE(0, ViE.image_process->EnableColorEnhancement(\n tbCapture.captureId, true));\n}\nFix color enhancement test. Review URL: https:\/\/webrtc-codereview.appspot.com\/553007\/*\n * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n\/\/\n\/\/ vie_autotest_image_process.cc\n\/\/\n\n\/\/ Settings\n#include \"vie_autotest_defines.h\"\n#include \"vie_autotest.h\"\n#include \"engine_configurations.h\"\n\n#include \"tb_interfaces.h\"\n#include \"tb_video_channel.h\"\n#include \"tb_capture_device.h\"\n\nclass MyEffectFilter: public webrtc::ViEEffectFilter\n{\npublic:\n MyEffectFilter() {}\n\n ~MyEffectFilter() {}\n\n virtual int Transform(int size, unsigned char* frameBuffer,\n unsigned int timeStamp90KHz, unsigned int width,\n unsigned int height)\n {\n \/\/ Black and white\n memset(frameBuffer + (2 * size) \/ 3, 0x7f, size \/ 3);\n return 0;\n }\n};\n\nvoid ViEAutoTest::ViEImageProcessStandardTest()\n{\n \/\/***************************************************************\n \/\/\tBegin create\/initialize WebRTC Video Engine for testing\n \/\/***************************************************************\n int rtpPort = 6000;\n \/\/ Create VIE\n TbInterfaces ViE(\"ViEImageProcessAPITest\");\n \/\/ Create a video channel\n TbVideoChannel tbChannel(ViE, webrtc::kVideoCodecVP8);\n \/\/ Create a capture device\n TbCaptureDevice tbCapture(ViE);\n\n tbCapture.ConnectTo(tbChannel.videoChannel);\n tbChannel.StartReceive(rtpPort);\n tbChannel.StartSend(rtpPort);\n\n MyEffectFilter effectFilter;\n\n RenderCaptureDeviceAndOutputStream(&ViE, &tbChannel, &tbCapture);\n\n ViETest::Log(\"Capture device is renderered in Window 1\");\n ViETest::Log(\"Remote stream is renderered in Window 2\");\n AutoTestSleep(KAutoTestSleepTimeMs);\n\n \/\/***************************************************************\n \/\/\tEngine ready. Begin testing class\n \/\/***************************************************************\n\n\n EXPECT_EQ(0, ViE.image_process->RegisterCaptureEffectFilter(\n tbCapture.captureId, effectFilter));\n\n ViETest::Log(\"Black and white filter registered for capture device, \"\n \"affects both windows\");\n AutoTestSleep(KAutoTestSleepTimeMs);\n\n EXPECT_EQ(0, ViE.image_process->DeregisterCaptureEffectFilter(\n tbCapture.captureId));\n\n EXPECT_EQ(0, ViE.image_process->RegisterRenderEffectFilter(\n tbChannel.videoChannel, effectFilter));\n\n ViETest::Log(\"Remove capture effect filter, adding filter for incoming \"\n \"stream\");\n ViETest::Log(\"Only Window 2 should be black and white\");\n AutoTestSleep(KAutoTestSleepTimeMs);\n\n EXPECT_EQ(0, ViE.render->StopRender(tbCapture.captureId));\n EXPECT_EQ(0, ViE.render->RemoveRenderer(tbCapture.captureId));\n\n int rtpPort2 = rtpPort + 100;\n \/\/ Create a video channel\n TbVideoChannel tbChannel2(ViE, webrtc::kVideoCodecVP8);\n\n tbCapture.ConnectTo(tbChannel2.videoChannel);\n tbChannel2.StartReceive(rtpPort2);\n tbChannel2.StartSend(rtpPort2);\n\n EXPECT_EQ(0, ViE.render->AddRenderer(\n tbChannel2.videoChannel, _window1, 1, 0.0, 0.0, 1.0, 1.0));\n EXPECT_EQ(0, ViE.render->StartRender(tbChannel2.videoChannel));\n EXPECT_EQ(0, ViE.image_process->DeregisterRenderEffectFilter(\n tbChannel.videoChannel));\n\n ViETest::Log(\"Local renderer removed, added new channel and rendering in \"\n \"Window1.\");\n\n EXPECT_EQ(0, ViE.image_process->RegisterCaptureEffectFilter(\n tbCapture.captureId, effectFilter));\n\n ViETest::Log(\"Black and white filter registered for capture device, \"\n \"affects both windows\");\n AutoTestSleep(KAutoTestSleepTimeMs);\n\n EXPECT_EQ(0, ViE.image_process->DeregisterCaptureEffectFilter(\n tbCapture.captureId));\n\n EXPECT_EQ(0, ViE.image_process->RegisterSendEffectFilter(\n tbChannel.videoChannel, effectFilter));\n\n ViETest::Log(\"Capture filter removed.\");\n ViETest::Log(\"Black and white filter registered for one channel, Window2 \"\n \"should be black and white\");\n AutoTestSleep(KAutoTestSleepTimeMs);\n\n EXPECT_EQ(0, ViE.image_process->DeregisterSendEffectFilter(\n tbChannel.videoChannel));\n\n \/\/***************************************************************\n \/\/\tTesting finished. Tear down Video Engine\n \/\/***************************************************************\n}\n\nvoid ViEAutoTest::ViEImageProcessExtendedTest()\n{\n ViEImageProcessStandardTest();\n}\n\nvoid ViEAutoTest::ViEImageProcessAPITest()\n{\n TbInterfaces ViE(\"ViEImageProcessAPITest\");\n TbVideoChannel tbChannel(ViE, webrtc::kVideoCodecVP8);\n TbCaptureDevice tbCapture(ViE);\n\n tbCapture.ConnectTo(tbChannel.videoChannel);\n\n MyEffectFilter effectFilter;\n\n \/\/\n \/\/ Capture effect filter\n \/\/\n \/\/ Add effect filter\n EXPECT_EQ(0, ViE.image_process->RegisterCaptureEffectFilter(\n tbCapture.captureId, effectFilter));\n \/\/ Add again -> error\n EXPECT_NE(0, ViE.image_process->RegisterCaptureEffectFilter(\n tbCapture.captureId, effectFilter));\n EXPECT_EQ(0, ViE.image_process->DeregisterCaptureEffectFilter(\n tbCapture.captureId));\n\n \/\/ Double deregister\n EXPECT_NE(0, ViE.image_process->DeregisterCaptureEffectFilter(\n tbCapture.captureId));\n \/\/ Non-existing capture device\n EXPECT_NE(0, ViE.image_process->RegisterCaptureEffectFilter(\n tbChannel.videoChannel, effectFilter));\n\n \/\/\n \/\/ Render effect filter\n \/\/\n EXPECT_EQ(0, ViE.image_process->RegisterRenderEffectFilter(\n tbChannel.videoChannel, effectFilter));\n EXPECT_NE(0, ViE.image_process->RegisterRenderEffectFilter(\n tbChannel.videoChannel, effectFilter));\n EXPECT_EQ(0, ViE.image_process->DeregisterRenderEffectFilter(\n tbChannel.videoChannel));\n EXPECT_NE(0, ViE.image_process->DeregisterRenderEffectFilter(\n tbChannel.videoChannel));\n\n \/\/ Non-existing channel id\n EXPECT_NE(0, ViE.image_process->RegisterRenderEffectFilter(\n tbCapture.captureId, effectFilter));\n\n \/\/\n \/\/ Send effect filter\n \/\/\n EXPECT_EQ(0, ViE.image_process->RegisterSendEffectFilter(\n tbChannel.videoChannel, effectFilter));\n EXPECT_NE(0, ViE.image_process->RegisterSendEffectFilter(\n tbChannel.videoChannel, effectFilter));\n EXPECT_EQ(0, ViE.image_process->DeregisterSendEffectFilter(\n tbChannel.videoChannel));\n EXPECT_NE(0, ViE.image_process->DeregisterSendEffectFilter(\n tbChannel.videoChannel));\n EXPECT_NE(0, ViE.image_process->RegisterSendEffectFilter(\n tbCapture.captureId, effectFilter));\n\n \/\/\n \/\/ Denoising\n \/\/\n EXPECT_EQ(0, ViE.image_process->EnableDenoising(tbCapture.captureId, true));\n \/\/ If the denoising is already enabled, it will just reuturn 0.\n EXPECT_EQ(0, ViE.image_process->EnableDenoising(tbCapture.captureId, true));\n EXPECT_EQ(0, ViE.image_process->EnableDenoising(\n tbCapture.captureId, false));\n \/\/ If the denoising is already disabled, it will just reuturn 0.\n EXPECT_EQ(0, ViE.image_process->EnableDenoising(\n tbCapture.captureId, false));\n EXPECT_NE(0, ViE.image_process->EnableDenoising(\n tbChannel.videoChannel, true));\n\n \/\/\n \/\/ Deflickering\n \/\/\n EXPECT_EQ(0, ViE.image_process->EnableDeflickering(\n tbCapture.captureId, true));\n EXPECT_NE(0, ViE.image_process->EnableDeflickering(\n tbCapture.captureId, true));\n EXPECT_EQ(0, ViE.image_process->EnableDeflickering(\n tbCapture.captureId, false));\n EXPECT_NE(0, ViE.image_process->EnableDeflickering(\n tbCapture.captureId, false));\n EXPECT_NE(0, ViE.image_process->EnableDeflickering(\n tbChannel.videoChannel, true));\n\n \/\/\n \/\/ Color enhancement\n \/\/\n EXPECT_EQ(0, ViE.image_process->EnableColorEnhancement(\n tbChannel.videoChannel, false));\n EXPECT_EQ(0, ViE.image_process->EnableColorEnhancement(\n tbChannel.videoChannel, true));\n EXPECT_EQ(0, ViE.image_process->EnableColorEnhancement(\n tbChannel.videoChannel, false));\n EXPECT_NE(0, ViE.image_process->EnableColorEnhancement(\n tbCapture.captureId, true));\n}\n<|endoftext|>"} {"text":"#include \"ImagePyramid.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n#ifdef WIN32\n#include \n#else\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#endif\n\nnamespace fast {\n\nint ImagePyramid::m_counter = 0;\n\nImagePyramid::ImagePyramid(int width, int height, int channels, int patchWidth, int patchHeight) {\n if(channels <= 0 || channels > 4)\n throw Exception(\"Nr of channels must be between 1 and 4\");\n\n \/\/ Determine how many levels\n int currentLevel = 0;\n int currentWidth = width;\n int currentHeight = height;\n m_channels = channels;\n\n#ifdef WIN32\n m_tiffPath = \"C:\/windows\/temp\/fast_image_pyramid_\" + std::to_string(m_counter) + \".tiff\";\n#else\n m_tiffPath = \"\/tmp\/fast_image_pyramid_\" + std::to_string(m_counter) + \".tiff\";\n#endif\n TIFFSetErrorHandler([](const char* module, const char* fmt, va_list ap) {\n auto str = make_uninitialized_unique(512);\n sprintf(str.get(), fmt, ap);\n Reporter::warning() << \"TIFF: \" << module << \": \" << str.get() << Reporter::end();\n });\n TIFFSetWarningHandler([](const char* module, const char* fmt, va_list ap) {\n auto str = make_uninitialized_unique(512);\n sprintf(str.get(), fmt, ap);\n Reporter::warning() << \"TIFF: \" << module << \": \" << str.get() << Reporter::end();\n });\n m_tiffHandle = TIFFOpen(m_tiffPath.c_str(), \"w8\");\n auto tiff = m_tiffHandle;\n m_counter += 1;\n\n ImageCompression compression = ImageCompression::LZW;\n\n uint photometric = PHOTOMETRIC_RGB;\n uint bitsPerSample = 8;\n uint samplesPerPixel = 3; \/\/ RGBA image pyramid is converted to RGB with getPatchAsImage\n if(channels == 1) {\n photometric = PHOTOMETRIC_MINISBLACK; \/\/ Photometric mask causes crash..\n samplesPerPixel = 1;\n }\n\n while(true) {\n\t\tcurrentWidth = width \/ std::pow(2, currentLevel);\n\t\tcurrentHeight = height \/ std::pow(2, currentLevel);\n\n if(currentWidth < 4096 && currentHeight < 4096) \/\/ IMPORTANT: This should be the same as in PatchStitcher.\n break;\n\n reportInfo() << \"Processing level \" << currentLevel << reportEnd();\n std::size_t bytes = (std::size_t)currentWidth * currentHeight * m_channels * sizeof(char);\n\n \/\/ Get total size of image\n float sizeInMB = (float)bytes \/ (1024 * 1024);\n reportInfo() << \"WSI level size: \" << currentWidth << \", \" << currentHeight << \", \" << m_channels << reportEnd();\n reportInfo() << \"WSI level size: \" << sizeInMB << \" MBs\" << reportEnd();\n\n\t\tImagePyramidLevel levelData;\n\t\tlevelData.width = currentWidth;\n\t\tlevelData.height = currentHeight;\n\t\tlevelData.tileWidth = patchWidth;\n levelData.tileHeight = patchHeight;\n levelData.tilesX = std::ceil((float)levelData.width \/ levelData.tileWidth);\n levelData.tilesY = std::ceil((float)levelData.height \/ levelData.tileHeight);\n\n \/\/ Write base tags\n TIFFSetField(tiff, TIFFTAG_PHOTOMETRIC, photometric);\n TIFFSetField(tiff, TIFFTAG_BITSPERSAMPLE, bitsPerSample);\n TIFFSetField(tiff, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);\n TIFFSetField(tiff, TIFFTAG_SAMPLESPERPIXEL, samplesPerPixel);\n TIFFSetField(tiff, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);\n TIFFSetField(tiff, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);\n\n if(currentLevel > 0) {\n \/\/ All levels except highest res level should have this tag?\n TIFFSetField(tiff, TIFFTAG_SUBFILETYPE, FILETYPE_REDUCEDIMAGE);\n }\n switch(compression) {\n case ImageCompression::RAW:\n TIFFSetField(tiff, TIFFTAG_COMPRESSION, COMPRESSION_NONE);\n break;\n case ImageCompression::LZW:\n TIFFSetField(tiff, TIFFTAG_COMPRESSION, COMPRESSION_LZW);\n break;\n case ImageCompression::JPEG:\n TIFFSetField(tiff, TIFFTAG_COMPRESSION, COMPRESSION_JPEG);\n break;\n case ImageCompression::JPEG2000:\n \/\/ TODO NOT IMPLEMENTED\n throw NotImplementedException();\n TIFFSetField(tiff, TIFFTAG_COMPRESSION, COMPRESSION_JP2000);\n break;\n }\n\n TIFFSetField(tiff, TIFFTAG_TILEWIDTH, levelData.tileWidth);\n TIFFSetField(tiff, TIFFTAG_TILELENGTH, levelData.tileHeight);\n TIFFSetField(tiff, TIFFTAG_IMAGEWIDTH, levelData.width);\n TIFFSetField(tiff, TIFFTAG_IMAGELENGTH, levelData.height);\n\n\t\tm_levels.push_back(levelData);\n\n \/\/ TODO need to initialize somehow?\n\t\t\/\/ We need to write the first tile for some reason... or we will get an error saying it is missing required\n\t\t\/\/ TileOffsets\n\t\tauto data = std::make_unique(levelData.tileWidth*levelData.tileHeight*samplesPerPixel); \/\/ Is initialized to zeros\n TIFFWriteTile(tiff, data.get(), 0, 0, 0, 0);\n \/*\n \/\/ TODO Do we really need to inititalize all tiles? This takes time..\n for(int y = 0; y < levelData.tilesY; ++y) {\n for(int x = 0; x < levelData.tilesX; ++x) {\n TIFFWriteTile(tiff, data.get(), x*levelData.tileWidth, y*levelData.tileHeight, 0, 0);\n }\n\t\t}*\/\n \/\/ END\n\n\t\treportInfo() << \"Done creating level \" << currentLevel << reportEnd();\n\t\t++currentLevel;\n\t\tTIFFWriteDirectory(m_tiffHandle);\n }\n\n mBoundingBox = DataBoundingBox(Vector3f(getFullWidth(), getFullHeight(), 0));\n m_initialized = true;\n m_pyramidFullyInitialized = false;\n\tm_counter += 1;\n}\n\nImagePyramid::ImagePyramid(openslide_t *fileHandle, std::vector levels) {\n m_fileHandle = fileHandle;\n m_levels = std::move(levels);\n m_channels = 4;\n for(int i = 0; i < m_levels.size(); ++i) {\n\t\tm_levels[i].tilesX = std::ceil((float)m_levels[i].width \/ m_levels[i].tileWidth);\n m_levels[i].tilesY = std::ceil((float)m_levels[i].height \/ m_levels[i].tileHeight);\n }\n mBoundingBox = DataBoundingBox(Vector3f(getFullWidth(), getFullHeight(), 0));\n m_initialized = true;\n m_pyramidFullyInitialized = true;\n\tm_counter += 1;\n}\n\nImagePyramid::ImagePyramid() {\n m_initialized = false;\n m_pyramidFullyInitialized = false;\n}\n\nImagePyramidLevel ImagePyramid::getLevelInfo(int level) {\n \/*if(!m_initialized)\n throw Exception(\"ImagePyramid has not been initialized.\");*\/ \/\/ TODO why does this fail?\n if(level < 0 || level > m_levels.size()-1)\n throw Exception(\"Level \" + std::to_string(level) + \" doesn't exist in ImagePyramid. Pyramid has \" + std::to_string(m_levels.size()) + \" levels\");\n return m_levels[level];\n}\n\nint ImagePyramid::getNrOfLevels() {\n return m_levels.size();\n}\n\nint ImagePyramid::getLevelWidth(int level) {\n return getLevelInfo(level).width;\n}\n\nint ImagePyramid::getLevelHeight(int level) {\n return getLevelInfo(level).height;\n}\n\nint ImagePyramid::getLevelTileWidth(int level) {\n return getLevelInfo(level).tileWidth;\n}\n\nint ImagePyramid::getLevelTileHeight(int level) {\n return getLevelInfo(level).tileHeight;\n}\n\nint ImagePyramid::getLevelTilesX(int level) {\n return getLevelInfo(level).tilesX;\n}\n\nint ImagePyramid::getLevelTilesY(int level) {\n return getLevelInfo(level).tilesY;\n}\n\nint ImagePyramid::getFullWidth() {\n return getLevelInfo(0).width;\n}\n\nint ImagePyramid::getFullHeight() {\n return getLevelInfo(0).height;\n}\n\nvoid ImagePyramid::free(ExecutionDevice::pointer device) {\n freeAll();\n}\n\nvoid ImagePyramid::freeAll() {\n if(m_fileHandle != nullptr) {\n m_levels.clear();\n openslide_close(m_fileHandle);\n } else if(m_tiffHandle != nullptr) {\n m_levels.clear();\n TIFFClose(m_tiffHandle);\n } else {\n\t\tfor(auto& item : m_levels) {\n\t\t\tif(item.memoryMapped) {\n#ifdef WIN32\n\t\t\t\tUnmapViewOfFile(item.data);\n\t\t\t\tCloseHandle(item.fileHandle);\n#else\n\t\t\t\tmunmap(item.data, item.width*item.height*m_channels);\n\t\t\t\tclose(item.fileHandle);\n#endif\n\t\t\t} else {\n\t\t\t\tdelete[] item.data;\n\t\t\t}\n\t\t}\n m_levels.clear();\n }\n\n\tm_initialized = false;\n\tm_fileHandle = nullptr;\n}\n\nImagePyramid::~ImagePyramid() {\n freeAll();\n}\nint ImagePyramid::getNrOfChannels() const {\n return m_channels;\n}\n\nImagePyramidAccess::pointer ImagePyramid::getAccess(accessType type) {\n if(!m_initialized)\n throw Exception(\"ImagePyramid has not been initialized.\");\n\n blockIfBeingWrittenTo();\n\n if(type == ACCESS_READ_WRITE) {\n \tblockIfBeingAccessed();\n std::unique_lock lock(mDataIsBeingWrittenToMutex);\n mDataIsBeingWrittenTo = true;\n }\n \/\/updateHostData();\n if(type == ACCESS_READ_WRITE) {\n \/\/setAllDataToOutOfDate();\n updateModifiedTimestamp();\n }\n \/\/mHostDataIsUpToDate = true;\n {\n std::unique_lock lock(mDataIsBeingAccessedMutex);\n mDataIsBeingAccessed = true;\n }\n return std::make_unique(m_levels, m_fileHandle, m_tiffHandle, std::static_pointer_cast(mPtr.lock()), type == ACCESS_READ_WRITE, m_initializedPatchList);\n}\n\nvoid ImagePyramid::setDirtyPatch(int level, int patchIdX, int patchIdY) {\n\tstd::lock_guard lock(m_dirtyPatchMutex);\n\tconst std::string tileString =\n\t\tstd::to_string(level) + \"_\" + std::to_string(patchIdX) + \"_\" + std::to_string(patchIdY);\n\tm_dirtyPatches.insert(tileString);\n}\n\nstd::unordered_set ImagePyramid::getDirtyPatches() {\n\tstd::lock_guard lock(m_dirtyPatchMutex);\n\treturn m_dirtyPatches;\n}\n\nbool ImagePyramid::isDirtyPatch(const std::string& tileID) {\n\tstd::lock_guard lock(m_dirtyPatchMutex);\n\treturn m_dirtyPatches.count(tileID);\n}\n\nvoid ImagePyramid::clearDirtyPatches(std::set patches) {\n\tstd::lock_guard lock(m_dirtyPatchMutex);\n\tfor(auto&& patch : patches)\n\t\tm_dirtyPatches.erase(patch);\n}\n\nvoid ImagePyramid::setSpacing(Vector3f spacing) {\n\tm_spacing = spacing;\n if(m_tiffHandle != nullptr) {\n \/\/ Write spacing to TIFF file\n\t\tif(spacing.x() != 1 && spacing.y() != 1) { \/\/ Spacing == 1 means not set.\n auto access = getAccess(ACCESS_READ_WRITE); \/\/ Ensure we have exclusive access to TIFF\n for(int level = 0; level < getNrOfLevels(); ++level) {\n TIFFSetDirectory(m_tiffHandle, level);\n TIFFSetField(m_tiffHandle, TIFFTAG_RESOLUTIONUNIT, RESUNIT_CENTIMETER);\n float scaleX = (float)getFullWidth() \/ getLevelWidth(level);\n float scaleY = (float)getFullHeight() \/ getLevelHeight(level);\n TIFFSetField(m_tiffHandle, TIFFTAG_XRESOLUTION,\n 1.0f \/ (spacing.x() \/ 10) * scaleX); \/\/ Convert to cm, and adjust for level\n TIFFSetField(m_tiffHandle, TIFFTAG_YRESOLUTION,\n 1.0f \/ (spacing.y() \/ 10) * scaleY); \/\/ Convert to cm, and adjust for level\n }\n }\n }\n}\n\nVector3f ImagePyramid::getSpacing() const {\n\treturn m_spacing;\n}\n\nImagePyramid::ImagePyramid(TIFF *fileHandle, std::vector levels, int channels) {\n if(channels <= 0 || channels > 4)\n throw Exception(\"Nr of channels must be between 1 and 4 in ImagePyramid when importing from TIFF\");\n m_tiffHandle = fileHandle;\n m_levels = levels;\n m_channels = channels;\n for(int i = 0; i < m_levels.size(); ++i) {\n m_levels[i].tilesX = std::ceil((float)m_levels[i].width \/ m_levels[i].tileWidth);\n m_levels[i].tilesY = std::ceil((float)m_levels[i].height \/ m_levels[i].tileHeight);\n }\n mBoundingBox = DataBoundingBox(Vector3f(getFullWidth(), getFullHeight(), 0));\n m_initialized = true;\n m_pyramidFullyInitialized = true;\n m_counter += 1;\n}\n\nbool ImagePyramid::isBGRA() const {\n return m_fileHandle != nullptr;\n}\n\nbool ImagePyramid::usesTIFF() const {\n return m_tiffHandle != nullptr;\n}\n\nstd::string ImagePyramid::getTIFFPath() const {\n return m_tiffPath;\n}\n\nbool ImagePyramid::usesOpenSlide() const {\n return m_fileHandle != nullptr;\n}\n\nbool ImagePyramid::isPyramidFullyInitialized() const {\n return m_pyramidFullyInitialized;\n}\n\n}\nFixed spacing issue when writing\/reading from TIFF in ImagePyramid#include \"ImagePyramid.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n#ifdef WIN32\n#include \n#else\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#endif\n\nnamespace fast {\n\nint ImagePyramid::m_counter = 0;\n\nImagePyramid::ImagePyramid(int width, int height, int channels, int patchWidth, int patchHeight) {\n if(channels <= 0 || channels > 4)\n throw Exception(\"Nr of channels must be between 1 and 4\");\n\n \/\/ Determine how many levels\n int currentLevel = 0;\n int currentWidth = width;\n int currentHeight = height;\n m_channels = channels;\n\n#ifdef WIN32\n m_tiffPath = \"C:\/windows\/temp\/fast_image_pyramid_\" + std::to_string(m_counter) + \".tiff\";\n#else\n m_tiffPath = \"\/tmp\/fast_image_pyramid_\" + std::to_string(m_counter) + \".tiff\";\n#endif\n TIFFSetErrorHandler([](const char* module, const char* fmt, va_list ap) {\n auto str = make_uninitialized_unique(512);\n sprintf(str.get(), fmt, ap);\n Reporter::warning() << \"TIFF: \" << module << \": \" << str.get() << Reporter::end();\n });\n TIFFSetWarningHandler([](const char* module, const char* fmt, va_list ap) {\n auto str = make_uninitialized_unique(512);\n sprintf(str.get(), fmt, ap);\n Reporter::warning() << \"TIFF: \" << module << \": \" << str.get() << Reporter::end();\n });\n m_tiffHandle = TIFFOpen(m_tiffPath.c_str(), \"w8\");\n auto tiff = m_tiffHandle;\n m_counter += 1;\n\n ImageCompression compression = ImageCompression::LZW;\n\n uint photometric = PHOTOMETRIC_RGB;\n uint bitsPerSample = 8;\n uint samplesPerPixel = 3; \/\/ RGBA image pyramid is converted to RGB with getPatchAsImage\n if(channels == 1) {\n photometric = PHOTOMETRIC_MINISBLACK; \/\/ Photometric mask causes crash..\n samplesPerPixel = 1;\n }\n\n while(true) {\n\t\tcurrentWidth = width \/ std::pow(2, currentLevel);\n\t\tcurrentHeight = height \/ std::pow(2, currentLevel);\n\n if(currentWidth < 4096 && currentHeight < 4096) \/\/ IMPORTANT: This should be the same as in PatchStitcher.\n break;\n\n reportInfo() << \"Processing level \" << currentLevel << reportEnd();\n std::size_t bytes = (std::size_t)currentWidth * currentHeight * m_channels * sizeof(char);\n\n \/\/ Get total size of image\n float sizeInMB = (float)bytes \/ (1024 * 1024);\n reportInfo() << \"WSI level size: \" << currentWidth << \", \" << currentHeight << \", \" << m_channels << reportEnd();\n reportInfo() << \"WSI level size: \" << sizeInMB << \" MBs\" << reportEnd();\n\n\t\tImagePyramidLevel levelData;\n\t\tlevelData.width = currentWidth;\n\t\tlevelData.height = currentHeight;\n\t\tlevelData.tileWidth = patchWidth;\n levelData.tileHeight = patchHeight;\n levelData.tilesX = std::ceil((float)levelData.width \/ levelData.tileWidth);\n levelData.tilesY = std::ceil((float)levelData.height \/ levelData.tileHeight);\n\n \/\/ Write base tags\n TIFFSetField(tiff, TIFFTAG_PHOTOMETRIC, photometric);\n TIFFSetField(tiff, TIFFTAG_BITSPERSAMPLE, bitsPerSample);\n TIFFSetField(tiff, TIFFTAG_SAMPLEFORMAT, SAMPLEFORMAT_UINT);\n TIFFSetField(tiff, TIFFTAG_SAMPLESPERPIXEL, samplesPerPixel);\n TIFFSetField(tiff, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);\n TIFFSetField(tiff, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);\n\n if(currentLevel > 0) {\n \/\/ All levels except highest res level should have this tag?\n TIFFSetField(tiff, TIFFTAG_SUBFILETYPE, FILETYPE_REDUCEDIMAGE);\n }\n switch(compression) {\n case ImageCompression::RAW:\n TIFFSetField(tiff, TIFFTAG_COMPRESSION, COMPRESSION_NONE);\n break;\n case ImageCompression::LZW:\n TIFFSetField(tiff, TIFFTAG_COMPRESSION, COMPRESSION_LZW);\n break;\n case ImageCompression::JPEG:\n TIFFSetField(tiff, TIFFTAG_COMPRESSION, COMPRESSION_JPEG);\n break;\n case ImageCompression::JPEG2000:\n \/\/ TODO NOT IMPLEMENTED\n throw NotImplementedException();\n TIFFSetField(tiff, TIFFTAG_COMPRESSION, COMPRESSION_JP2000);\n break;\n }\n\n TIFFSetField(tiff, TIFFTAG_TILEWIDTH, levelData.tileWidth);\n TIFFSetField(tiff, TIFFTAG_TILELENGTH, levelData.tileHeight);\n TIFFSetField(tiff, TIFFTAG_IMAGEWIDTH, levelData.width);\n TIFFSetField(tiff, TIFFTAG_IMAGELENGTH, levelData.height);\n\n\t\tm_levels.push_back(levelData);\n\n \/\/ TODO need to initialize somehow?\n\t\t\/\/ We need to write the first tile for some reason... or we will get an error saying it is missing required\n\t\t\/\/ TileOffsets\n\t\tauto data = std::make_unique(levelData.tileWidth*levelData.tileHeight*samplesPerPixel); \/\/ Is initialized to zeros\n TIFFWriteTile(tiff, data.get(), 0, 0, 0, 0);\n \/*\n \/\/ TODO Do we really need to inititalize all tiles? This takes time..\n for(int y = 0; y < levelData.tilesY; ++y) {\n for(int x = 0; x < levelData.tilesX; ++x) {\n TIFFWriteTile(tiff, data.get(), x*levelData.tileWidth, y*levelData.tileHeight, 0, 0);\n }\n\t\t}*\/\n \/\/ END\n\n\t\treportInfo() << \"Done creating level \" << currentLevel << reportEnd();\n\t\t++currentLevel;\n\t\tTIFFWriteDirectory(m_tiffHandle);\n }\n\n mBoundingBox = DataBoundingBox(Vector3f(getFullWidth(), getFullHeight(), 0));\n m_initialized = true;\n m_pyramidFullyInitialized = false;\n\tm_counter += 1;\n}\n\nImagePyramid::ImagePyramid(openslide_t *fileHandle, std::vector levels) {\n m_fileHandle = fileHandle;\n m_levels = std::move(levels);\n m_channels = 4;\n for(int i = 0; i < m_levels.size(); ++i) {\n\t\tm_levels[i].tilesX = std::ceil((float)m_levels[i].width \/ m_levels[i].tileWidth);\n m_levels[i].tilesY = std::ceil((float)m_levels[i].height \/ m_levels[i].tileHeight);\n }\n mBoundingBox = DataBoundingBox(Vector3f(getFullWidth(), getFullHeight(), 0));\n m_initialized = true;\n m_pyramidFullyInitialized = true;\n\tm_counter += 1;\n}\n\nImagePyramid::ImagePyramid() {\n m_initialized = false;\n m_pyramidFullyInitialized = false;\n}\n\nImagePyramidLevel ImagePyramid::getLevelInfo(int level) {\n \/*if(!m_initialized)\n throw Exception(\"ImagePyramid has not been initialized.\");*\/ \/\/ TODO why does this fail?\n if(level < 0 || level > m_levels.size()-1)\n throw Exception(\"Level \" + std::to_string(level) + \" doesn't exist in ImagePyramid. Pyramid has \" + std::to_string(m_levels.size()) + \" levels\");\n return m_levels[level];\n}\n\nint ImagePyramid::getNrOfLevels() {\n return m_levels.size();\n}\n\nint ImagePyramid::getLevelWidth(int level) {\n return getLevelInfo(level).width;\n}\n\nint ImagePyramid::getLevelHeight(int level) {\n return getLevelInfo(level).height;\n}\n\nint ImagePyramid::getLevelTileWidth(int level) {\n return getLevelInfo(level).tileWidth;\n}\n\nint ImagePyramid::getLevelTileHeight(int level) {\n return getLevelInfo(level).tileHeight;\n}\n\nint ImagePyramid::getLevelTilesX(int level) {\n return getLevelInfo(level).tilesX;\n}\n\nint ImagePyramid::getLevelTilesY(int level) {\n return getLevelInfo(level).tilesY;\n}\n\nint ImagePyramid::getFullWidth() {\n return getLevelInfo(0).width;\n}\n\nint ImagePyramid::getFullHeight() {\n return getLevelInfo(0).height;\n}\n\nvoid ImagePyramid::free(ExecutionDevice::pointer device) {\n freeAll();\n}\n\nvoid ImagePyramid::freeAll() {\n if(m_fileHandle != nullptr) {\n m_levels.clear();\n openslide_close(m_fileHandle);\n } else if(m_tiffHandle != nullptr) {\n m_levels.clear();\n TIFFClose(m_tiffHandle);\n } else {\n\t\tfor(auto& item : m_levels) {\n\t\t\tif(item.memoryMapped) {\n#ifdef WIN32\n\t\t\t\tUnmapViewOfFile(item.data);\n\t\t\t\tCloseHandle(item.fileHandle);\n#else\n\t\t\t\tmunmap(item.data, item.width*item.height*m_channels);\n\t\t\t\tclose(item.fileHandle);\n#endif\n\t\t\t} else {\n\t\t\t\tdelete[] item.data;\n\t\t\t}\n\t\t}\n m_levels.clear();\n }\n\n\tm_initialized = false;\n\tm_fileHandle = nullptr;\n}\n\nImagePyramid::~ImagePyramid() {\n freeAll();\n}\nint ImagePyramid::getNrOfChannels() const {\n return m_channels;\n}\n\nImagePyramidAccess::pointer ImagePyramid::getAccess(accessType type) {\n if(!m_initialized)\n throw Exception(\"ImagePyramid has not been initialized.\");\n\n blockIfBeingWrittenTo();\n\n if(type == ACCESS_READ_WRITE) {\n \tblockIfBeingAccessed();\n std::unique_lock lock(mDataIsBeingWrittenToMutex);\n mDataIsBeingWrittenTo = true;\n }\n \/\/updateHostData();\n if(type == ACCESS_READ_WRITE) {\n \/\/setAllDataToOutOfDate();\n updateModifiedTimestamp();\n }\n \/\/mHostDataIsUpToDate = true;\n {\n std::unique_lock lock(mDataIsBeingAccessedMutex);\n mDataIsBeingAccessed = true;\n }\n return std::make_unique(m_levels, m_fileHandle, m_tiffHandle, std::static_pointer_cast(mPtr.lock()), type == ACCESS_READ_WRITE, m_initializedPatchList);\n}\n\nvoid ImagePyramid::setDirtyPatch(int level, int patchIdX, int patchIdY) {\n\tstd::lock_guard lock(m_dirtyPatchMutex);\n\tconst std::string tileString =\n\t\tstd::to_string(level) + \"_\" + std::to_string(patchIdX) + \"_\" + std::to_string(patchIdY);\n\tm_dirtyPatches.insert(tileString);\n}\n\nstd::unordered_set ImagePyramid::getDirtyPatches() {\n\tstd::lock_guard lock(m_dirtyPatchMutex);\n\treturn m_dirtyPatches;\n}\n\nbool ImagePyramid::isDirtyPatch(const std::string& tileID) {\n\tstd::lock_guard lock(m_dirtyPatchMutex);\n\treturn m_dirtyPatches.count(tileID);\n}\n\nvoid ImagePyramid::clearDirtyPatches(std::set patches) {\n\tstd::lock_guard lock(m_dirtyPatchMutex);\n\tfor(auto&& patch : patches)\n\t\tm_dirtyPatches.erase(patch);\n}\n\nvoid ImagePyramid::setSpacing(Vector3f spacing) {\n\tm_spacing = spacing;\n if(m_tiffHandle != nullptr) {\n \/\/ Write spacing to TIFF file\n\t\tif(spacing.x() != 1 && spacing.y() != 1) { \/\/ Spacing == 1 means not set.\n auto access = getAccess(ACCESS_READ_WRITE); \/\/ Ensure we have exclusive access to TIFF\n for(int level = 0; level < getNrOfLevels(); ++level) {\n TIFFSetDirectory(m_tiffHandle, level);\n TIFFSetField(m_tiffHandle, TIFFTAG_RESOLUTIONUNIT, RESUNIT_CENTIMETER);\n float scaleX = (float)getFullWidth() \/ getLevelWidth(level);\n float scaleY = (float)getFullHeight() \/ getLevelHeight(level);\n TIFFSetField(m_tiffHandle, TIFFTAG_XRESOLUTION,\n 1.0f \/ (spacing.x() \/ 10.0f) * scaleX); \/\/ Convert to cm, and adjust for level\n TIFFSetField(m_tiffHandle, TIFFTAG_YRESOLUTION,\n 1.0f \/ (spacing.y() \/ 10.0f) * scaleY); \/\/ Convert to cm, and adjust for level\n TIFFRewriteDirectory(m_tiffHandle); \/\/ Write changes\n }\n }\n }\n}\n\nVector3f ImagePyramid::getSpacing() const {\n\treturn m_spacing;\n}\n\nImagePyramid::ImagePyramid(TIFF *fileHandle, std::vector levels, int channels) {\n if(channels <= 0 || channels > 4)\n throw Exception(\"Nr of channels must be between 1 and 4 in ImagePyramid when importing from TIFF\");\n m_tiffHandle = fileHandle;\n m_levels = levels;\n m_channels = channels;\n for(int i = 0; i < m_levels.size(); ++i) {\n m_levels[i].tilesX = std::ceil((float)m_levels[i].width \/ m_levels[i].tileWidth);\n m_levels[i].tilesY = std::ceil((float)m_levels[i].height \/ m_levels[i].tileHeight);\n }\n \/\/ Get spacing from TIFF\n float spacingX;\n float spacingY;\n TIFFSetDirectory(fileHandle, 0);\n int resX = TIFFGetField(fileHandle, TIFFTAG_XRESOLUTION, &spacingX);\n int resY = TIFFGetField(fileHandle, TIFFTAG_YRESOLUTION, &spacingY);\n if(resX == 1 && resY == 1) {\n \/\/ Convert from cm\n spacingX = 1.0f\/(spacingX\/10.0f);\n spacingY = 1.0f\/(spacingY\/10.0f);\n reportInfo() << \"Spacing from TIFF was\" << spacingX << \" \" << spacingY << reportEnd();\n m_spacing = Vector3f(spacingX, spacingY, 1.0f);\n }\n mBoundingBox = DataBoundingBox(Vector3f(getFullWidth(), getFullHeight(), 0));\n m_initialized = true;\n m_pyramidFullyInitialized = true;\n m_counter += 1;\n}\n\nbool ImagePyramid::isBGRA() const {\n return m_fileHandle != nullptr;\n}\n\nbool ImagePyramid::usesTIFF() const {\n return m_tiffHandle != nullptr;\n}\n\nstd::string ImagePyramid::getTIFFPath() const {\n return m_tiffPath;\n}\n\nbool ImagePyramid::usesOpenSlide() const {\n return m_fileHandle != nullptr;\n}\n\nbool ImagePyramid::isPyramidFullyInitialized() const {\n return m_pyramidFullyInitialized;\n}\n\n}\n<|endoftext|>"} {"text":"\/* bzflag\n * Copyright (c) 1993 - 2004 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n#include \"ErrorHandler.h\"\n#include \"BzfWindow.h\"\n\nBzfWindow::BzfWindow(const BzfDisplay* _display) : display(_display)\n{\n#ifdef HAVE_SDL\n if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) == -1) {\n std::vector args;\n args.push_back(SDL_GetError());\n printError(\"Could not initialize SDL Joystick subsystem: %s.\\n\", &args);\n };\n#endif\n}\n\nBzfWindow::~BzfWindow()\n{\n#ifdef HAVE_SDL\n SDL_QuitSubSystem(SDL_INIT_JOYSTICK);\n#endif\n}\n\nvoid\t\t\tBzfWindow::callExposeCallbacks() const\n{\n const int count = exposeCallbacks.size();\n for (int i = 0; i < count; i++) {\n const BzfWindowCB& cb = exposeCallbacks[i];\n (*cb.cb)(cb.data);\n }\n}\n\nvoid\t\t\tBzfWindow::addExposeCallback(\n\t\t\t\tvoid (*_cb)(void*), void* data)\n{\n BzfWindowCB cb;\n cb.cb = _cb;\n cb.data = data;\n exposeCallbacks.push_back(cb);\n}\n\nvoid\t\t\tBzfWindow::removeExposeCallback(\n\t\t\t\tvoid (*_cb)(void*), void* data)\n{\n std::vector::iterator it = exposeCallbacks.begin();\n for(; it != exposeCallbacks.end(); it++) {\n if((it->cb == _cb) && (it->data == data)) {\n exposeCallbacks.erase(it);\n break;\n }\n }\n}\n\nvoid\t\t\tBzfWindow::callResizeCallbacks() const\n{\n const int count = resizeCallbacks.size();\n for (int i = 0; i < count; i++) {\n const BzfWindowCB& cb = resizeCallbacks[i];\n (*cb.cb)(cb.data);\n }\n}\n\nvoid\t\t\tBzfWindow::addResizeCallback(\n\t\t\t\tvoid (*_cb)(void*), void* data)\n{\n BzfWindowCB cb;\n cb.cb = _cb;\n cb.data = data;\n resizeCallbacks.push_back(cb);\n}\n\nvoid\t\t\tBzfWindow::removeResizeCallback(\n\t\t\t\tvoid (*_cb)(void*), void* data)\n{\n std::vector::iterator it = resizeCallbacks.begin();\n for(; it != resizeCallbacks.end(); it++) {\n if((it->cb == _cb) && (it->data == data)) {\n resizeCallbacks.erase(it);\n break;\n }\n }\n}\n\nvoid\t\t\tBzfWindow::initJoystick(const char* joystickName)\n{\n#ifdef HAVE_SDL\n if (!strcmp(joystickName, \"off\")) {\n joystickID = NULL;\n return;\n }\n int numJoystick = SDL_NumJoysticks();\n if (!numJoystick) {\n printError(\"no joystick is supported...\");\n return;\n }\n int i;\n for (i = 0; i < numJoystick; i++)\n if (strcmp(SDL_JoystickName(i), joystickName) == 0)\n break;\n if (i >= numJoystick)\n i = 0;\n joystickID = SDL_JoystickOpen(i);\n if (SDL_JoystickNumAxes(joystickID) < 2) {\n SDL_JoystickClose(joystickID);\n printError(\"joystick has less then 2 axis:\\n\");\n joystickID = NULL;\n return;\n }\n joystickButtons = SDL_JoystickNumButtons(joystickID);\n#else\n if (strcmp(joystickName, \"off\") && strcmp(joystickName, \"\")) {\n std::vector args;\n args.push_back(joystickName);\n printError(\"joystick '{1}' not supported...\", &args);\n }\n#endif\n}\n\nbool\t\t\tBzfWindow::joystick() const\n{\n#ifdef HAVE_SDL\n return joystickID != NULL;\n#else\n return false;\n#endif\n}\n\nvoid\t\t\tBzfWindow::getJoy(int& x, int& y) const\n{\n#ifdef HAVE_SDL\n if (!joystickID)\n return;\n\n SDL_JoystickUpdate();\n x = SDL_JoystickGetAxis(joystickID, 0);\n y = SDL_JoystickGetAxis(joystickID, 1);\n\n x = x * 1000 \/ 32768;\n y = y * 1000 \/ 32768;\n\n \/* balistic *\/\n x = (x * abs(x))\/1000;\n y = (y * abs(y))\/1000;\n#else\n x = 0;\n y = 0;\n#endif\n}\n\nunsigned long\t\tBzfWindow::getJoyButtons() const\n{\n#ifdef HAVE_SDL\n unsigned long buttons = 0;\n\n if (!joystickID)\n return 0;\n\n SDL_JoystickUpdate();\n for (int i = 0; i < joystickButtons; i++)\n if (SDL_JoystickGetButton(joystickID, i) == 1)\n if (i == 1)\n\tbuttons |= 1 << 9;\n else\n\tif ((i > 1) && (i < 10))\n\t buttons |= 1 << (i - 1);\n\telse\n\t buttons |= 1 << i; \n return buttons;\n#else\n return 0;\n#endif\n}\n\nvoid BzfWindow::getJoyDevices(std::vector\n\t\t\t\t\t\t &) const {\n#ifdef HAVE_SDL\n \n int numJoystick = SDL_NumJoysticks();\n int i;\n for (i = 0; i < numJoystick; i++)\n list.push_back(SDL_JoystickName(i));\n#endif\n}\n\nvoid\t\t\tBzfWindow::yieldCurrent(void)\n{\n\t\/\/ do nothing\n}\n\nvoid\t\t\tBzfWindow::releaseCurrent(void)\n{\n\t\/\/ do nothing\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n\nDidn't mean to update that file\/* bzflag\n * Copyright (c) 1993 - 2004 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n#include \"ErrorHandler.h\"\n#include \"BzfWindow.h\"\n\nBzfWindow::BzfWindow(const BzfDisplay* _display) : display(_display)\n{\n#ifdef HAVE_SDL\n if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) == -1) {\n std::vector args;\n args.push_back(SDL_GetError());\n printError(\"Could not initialize SDL Joystick subsystem: %s.\\n\", &args);\n };\n#endif\n}\n\nBzfWindow::~BzfWindow()\n{\n#ifdef HAVE_SDL\n SDL_QuitSubSystem(SDL_INIT_JOYSTICK);\n#endif\n}\n\nvoid\t\t\tBzfWindow::callExposeCallbacks() const\n{\n const int count = exposeCallbacks.size();\n for (int i = 0; i < count; i++) {\n const BzfWindowCB& cb = exposeCallbacks[i];\n (*cb.cb)(cb.data);\n }\n}\n\nvoid\t\t\tBzfWindow::addExposeCallback(\n\t\t\t\tvoid (*_cb)(void*), void* data)\n{\n BzfWindowCB cb;\n cb.cb = _cb;\n cb.data = data;\n exposeCallbacks.push_back(cb);\n}\n\nvoid\t\t\tBzfWindow::removeExposeCallback(\n\t\t\t\tvoid (*_cb)(void*), void* data)\n{\n std::vector::iterator it = exposeCallbacks.begin();\n for(; it != exposeCallbacks.end(); it++) {\n if((it->cb == _cb) && (it->data == data)) {\n exposeCallbacks.erase(it);\n break;\n }\n }\n}\n\nvoid\t\t\tBzfWindow::callResizeCallbacks() const\n{\n const int count = resizeCallbacks.size();\n for (int i = 0; i < count; i++) {\n const BzfWindowCB& cb = resizeCallbacks[i];\n (*cb.cb)(cb.data);\n }\n}\n\nvoid\t\t\tBzfWindow::addResizeCallback(\n\t\t\t\tvoid (*_cb)(void*), void* data)\n{\n BzfWindowCB cb;\n cb.cb = _cb;\n cb.data = data;\n resizeCallbacks.push_back(cb);\n}\n\nvoid\t\t\tBzfWindow::removeResizeCallback(\n\t\t\t\tvoid (*_cb)(void*), void* data)\n{\n std::vector::iterator it = resizeCallbacks.begin();\n for(; it != resizeCallbacks.end(); it++) {\n if((it->cb == _cb) && (it->data == data)) {\n resizeCallbacks.erase(it);\n break;\n }\n }\n}\n\nvoid\t\t\tBzfWindow::initJoystick(const char* joystickName)\n{\n#ifdef HAVE_SDL\n if (!strcmp(joystickName, \"off\")) {\n joystickID = NULL;\n return;\n }\n int numJoystick = SDL_NumJoysticks();\n if (!numJoystick) {\n printError(\"no joystick is supported...\");\n return;\n }\n int i;\n for (i = 0; i < numJoystick; i++)\n if (strcmp(SDL_JoystickName(i), joystickName) == 0)\n break;\n if (i >= numJoystick)\n i = 0;\n joystickID = SDL_JoystickOpen(i);\n if (SDL_JoystickNumAxes(joystickID) < 2) {\n SDL_JoystickClose(joystickID);\n printError(\"joystick has less then 2 axis:\\n\");\n joystickID = NULL;\n return;\n }\n joystickButtons = SDL_JoystickNumButtons(joystickID);\n#else\n if (strcmp(joystickName, \"off\") && strcmp(joystickName, \"\")) {\n std::vector args;\n args.push_back(joystickName);\n printError(\"joystick '{1}' not supported...\", &args);\n }\n#endif\n}\n\nbool\t\t\tBzfWindow::joystick() const\n{\n#ifdef HAVE_SDL\n return joystickID != NULL;\n#else\n return false;\n#endif\n}\n\nvoid\t\t\tBzfWindow::getJoy(int& x, int& y) const\n{\n#ifdef HAVE_SDL\n if (!joystickID)\n return;\n\n SDL_JoystickUpdate();\n x = SDL_JoystickGetAxis(joystickID, 0);\n y = SDL_JoystickGetAxis(joystickID, 1);\n\n x = x * 1000 \/ 32768;\n y = y * 1000 \/ 32768;\n\n \/* balistic *\/\n x = (x * abs(x))\/1000;\n y = (y * abs(y))\/1000;\n#else\n x = 0;\n y = 0;\n#endif\n}\n\nunsigned long\t\tBzfWindow::getJoyButtons() const\n{\n#ifdef HAVE_SDL\n unsigned long buttons = 0;\n\n if (!joystickID)\n return 0;\n\n SDL_JoystickUpdate();\n for (int i = 0; i < joystickButtons; i++)\n if (SDL_JoystickGetButton(joystickID, i) == 1)\n if (i == 1)\n\tbuttons |= 1 << 9;\n else\n\tif ((i > 1) && (i < 10))\n\t buttons |= 1 << (i - 1);\n\telse\n\t buttons |= 1 << i; \n return buttons;\n#else\n return 0;\n#endif\n}\n\nvoid BzfWindow::getJoyDevices(std::vector\n\t\t\t\t\t\t &list) const {\n#ifdef HAVE_SDL\n \n int numJoystick = SDL_NumJoysticks();\n int i;\n for (i = 0; i < numJoystick; i++)\n list.push_back(SDL_JoystickName(i));\n#endif\n}\n\nvoid\t\t\tBzfWindow::yieldCurrent(void)\n{\n\t\/\/ do nothing\n}\n\nvoid\t\t\tBzfWindow::releaseCurrent(void)\n{\n\t\/\/ do nothing\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"content\/browser\/accessibility\/browser_accessibility_manager_win.h\"\n\n#include \"content\/browser\/accessibility\/browser_accessibility_win.h\"\n#include \"content\/common\/view_messages.h\"\n\nusing webkit_glue::WebAccessibility;\n\n\/\/ static\nBrowserAccessibilityManager* BrowserAccessibilityManager::Create(\n gfx::NativeView parent_view,\n const WebAccessibility& src,\n BrowserAccessibilityDelegate* delegate,\n BrowserAccessibilityFactory* factory) {\n return new BrowserAccessibilityManagerWin(\n parent_view,\n src,\n delegate,\n factory);\n}\n\nBrowserAccessibilityManagerWin*\nBrowserAccessibilityManager::toBrowserAccessibilityManagerWin() {\n return static_cast(this);\n}\n\nBrowserAccessibilityManagerWin::BrowserAccessibilityManagerWin(\n HWND parent_view,\n const WebAccessibility& src,\n BrowserAccessibilityDelegate* delegate,\n BrowserAccessibilityFactory* factory)\n : BrowserAccessibilityManager(parent_view, src, delegate, factory) {\n \/\/ Allow NULL parent_view for unit testing.\n if (parent_view == NULL) {\n window_iaccessible_ = NULL;\n return;\n }\n\n HRESULT hr = ::CreateStdAccessibleObject(\n parent_view, OBJID_WINDOW, IID_IAccessible,\n reinterpret_cast(&window_iaccessible_));\n DCHECK(SUCCEEDED(hr));\n}\n\nBrowserAccessibilityManagerWin::~BrowserAccessibilityManagerWin() {\n}\n\nIAccessible* BrowserAccessibilityManagerWin::GetParentWindowIAccessible() {\n return window_iaccessible_;\n}\n\nvoid BrowserAccessibilityManagerWin::NotifyAccessibilityEvent(\n int type,\n BrowserAccessibility* node) {\n LONG event_id = EVENT_MIN;\n switch (type) {\n case ViewHostMsg_AccEvent::ACTIVE_DESCENDANT_CHANGED:\n event_id = IA2_EVENT_ACTIVE_DESCENDANT_CHANGED;\n break;\n case ViewHostMsg_AccEvent::CHECK_STATE_CHANGED:\n event_id = EVENT_OBJECT_STATECHANGE;\n break;\n case ViewHostMsg_AccEvent::CHILDREN_CHANGED:\n event_id = EVENT_OBJECT_REORDER;\n break;\n case ViewHostMsg_AccEvent::FOCUS_CHANGED:\n event_id = EVENT_OBJECT_FOCUS;\n break;\n case ViewHostMsg_AccEvent::LOAD_COMPLETE:\n event_id = IA2_EVENT_DOCUMENT_LOAD_COMPLETE;\n break;\n case ViewHostMsg_AccEvent::VALUE_CHANGED:\n event_id = EVENT_OBJECT_VALUECHANGE;\n break;\n case ViewHostMsg_AccEvent::SELECTED_TEXT_CHANGED:\n event_id = IA2_EVENT_TEXT_CARET_MOVED;\n break;\n case ViewHostMsg_AccEvent::LIVE_REGION_CHANGED:\n event_id = EVENT_OBJECT_REORDER;\n break;\n case ViewHostMsg_AccEvent::TEXT_INSERTED:\n event_id = IA2_EVENT_TEXT_INSERTED;\n break;\n case ViewHostMsg_AccEvent::TEXT_REMOVED:\n event_id = IA2_EVENT_TEXT_REMOVED;\n break;\n case ViewHostMsg_AccEvent::OBJECT_SHOW:\n event_id = EVENT_OBJECT_SHOW;\n break;\n case ViewHostMsg_AccEvent::OBJECT_HIDE:\n event_id = EVENT_OBJECT_HIDE;\n break;\n case ViewHostMsg_AccEvent::ALERT:\n event_id = EVENT_SYSTEM_ALERT;\n break;\n default:\n \/\/ Not all WebKit accessibility events result in a Windows\n \/\/ accessibility notification.\n return;\n }\n\n NotifyWinEvent(event_id, GetParentView(), OBJID_CLIENT, node->child_id());\n}\nAdd Windows accessibility notifications used by