text
stringlengths
54
60.6k
<commit_before>#include "aerial_autonomy/controllers/constant_heading_depth_controller.h" #include "aerial_autonomy/common/math.h" #include "aerial_autonomy/log/log.h" #include <glog/logging.h> bool ConstantHeadingDepthController::runImplementation( PositionYaw sensor_data, Position goal, VelocityYawRate &control) { tf::Vector3 current_tracking_vector(sensor_data.x, sensor_data.y, sensor_data.z); tf::Vector3 desired_tracking_vector(goal.x, goal.y, goal.z); tf::Vector3 desired_tracking_direction = desired_tracking_vector / desired_tracking_vector.length(); tf::Vector3 tracking_error = (current_tracking_vector - desired_tracking_vector); tf::Vector3 tracking_error_radial = desired_tracking_direction * (tracking_error.dot(desired_tracking_direction)); tf::Vector3 tracking_error_tangential = tracking_error - tracking_error_radial; tf::Vector3 desired_vel_tf = tracking_error_radial * config_.radial_gain() + tracking_error_tangential * config_.tangential_gain(); if (desired_vel_tf.length() > config_.max_velocity()) { desired_vel_tf *= config_.max_velocity() / desired_vel_tf.length(); } else if (desired_vel_tf.length() < config_.min_velocity()) { desired_vel_tf *= config_.min_velocity() / desired_vel_tf.length(); } double error_yaw = math::angleWrap(std::atan2(desired_tracking_direction.getY(), desired_tracking_direction.getX()) - sensor_data.yaw); double yaw_rate = math::clamp(config_.yaw_gain() * error_yaw, -config_.max_yaw_rate(), config_.max_yaw_rate()); control = VelocityYawRate(desired_vel_tf.getX(), desired_vel_tf.getY(), desired_vel_tf.getZ(), yaw_rate); return true; } ControllerStatus ConstantHeadingDepthController::isConvergedImplementation( PositionYaw sensor_data, Position goal) { double error_yaw = math::angleWrap(std::atan2(goal.y, goal.x) - sensor_data.yaw); Position error = Position(sensor_data.x, sensor_data.y, sensor_data.z) - goal; ControllerStatus status(ControllerStatus::Active); status << " Error Position, Yaw: " << error.x << error.y << error.z << error_yaw; DATA_LOG("constant_heading_depth_controller") << error.x << error.y << error.z << error_yaw << DataStream::endl; const PositionControllerConfig &position_controller_config = config_.position_controller_config(); const config::Position &tolerance_pos = position_controller_config.goal_position_tolerance(); const double &tolerance_yaw = position_controller_config.goal_yaw_tolerance(); // Compare if (std::abs(error.x) < tolerance_pos.x() && std::abs(error.y) < tolerance_pos.y() && std::abs(error.z) < tolerance_pos.z() && std::abs(error_yaw) < tolerance_yaw) { VLOG_EVERY_N(1, 50) << "Reached goal"; status.setStatus(ControllerStatus::Completed, "Reached Goal"); } return status; } <commit_msg>Add tracking vector to ConstantHeadingDepthController data log<commit_after>#include "aerial_autonomy/controllers/constant_heading_depth_controller.h" #include "aerial_autonomy/common/math.h" #include "aerial_autonomy/log/log.h" #include <glog/logging.h> bool ConstantHeadingDepthController::runImplementation( PositionYaw sensor_data, Position goal, VelocityYawRate &control) { tf::Vector3 current_tracking_vector(sensor_data.x, sensor_data.y, sensor_data.z); tf::Vector3 desired_tracking_vector(goal.x, goal.y, goal.z); tf::Vector3 desired_tracking_direction = desired_tracking_vector / desired_tracking_vector.length(); tf::Vector3 tracking_error = (current_tracking_vector - desired_tracking_vector); tf::Vector3 tracking_error_radial = desired_tracking_direction * (tracking_error.dot(desired_tracking_direction)); tf::Vector3 tracking_error_tangential = tracking_error - tracking_error_radial; tf::Vector3 desired_vel_tf = tracking_error_radial * config_.radial_gain() + tracking_error_tangential * config_.tangential_gain(); if (desired_vel_tf.length() > config_.max_velocity()) { desired_vel_tf *= config_.max_velocity() / desired_vel_tf.length(); } else if (desired_vel_tf.length() < config_.min_velocity()) { desired_vel_tf *= config_.min_velocity() / desired_vel_tf.length(); } double error_yaw = math::angleWrap(std::atan2(desired_tracking_direction.getY(), desired_tracking_direction.getX()) - sensor_data.yaw); double yaw_rate = math::clamp(config_.yaw_gain() * error_yaw, -config_.max_yaw_rate(), config_.max_yaw_rate()); control = VelocityYawRate(desired_vel_tf.getX(), desired_vel_tf.getY(), desired_vel_tf.getZ(), yaw_rate); return true; } ControllerStatus ConstantHeadingDepthController::isConvergedImplementation( PositionYaw sensor_data, Position goal) { double error_yaw = math::angleWrap(std::atan2(goal.y, goal.x) - sensor_data.yaw); Position error = Position(sensor_data.x, sensor_data.y, sensor_data.z) - goal; ControllerStatus status(ControllerStatus::Active); status << " Error Position, Yaw: " << error.x << error.y << error.z << error_yaw; DATA_LOG("constant_heading_depth_controller") << error.x << error.y << error.z << error_yaw << sensor_data.x << sensor_data.y << sensor_data.z << sensor_data.yaw << DataStream::endl; const PositionControllerConfig &position_controller_config = config_.position_controller_config(); const config::Position &tolerance_pos = position_controller_config.goal_position_tolerance(); const double &tolerance_yaw = position_controller_config.goal_yaw_tolerance(); // Compare if (std::abs(error.x) < tolerance_pos.x() && std::abs(error.y) < tolerance_pos.y() && std::abs(error.z) < tolerance_pos.z() && std::abs(error_yaw) < tolerance_yaw) { VLOG_EVERY_N(1, 50) << "Reached goal"; status.setStatus(ControllerStatus::Completed, "Reached Goal"); } return status; } <|endoftext|>
<commit_before>#pragma once #include "event_queue.hpp" namespace krbn { namespace manipulator { namespace detail { class base { public: virtual ~base(void) { } virtual manipulate(event_queue& event_queue) = 0; }; } // namespace detail } // namespace manipulator } // namespace krbn <commit_msg>detail -> details<commit_after>#pragma once #include "manipulator/event_queue.hpp" namespace krbn { namespace manipulator { namespace details { class base { public: virtual ~base(void) { } virtual void manipulate(event_queue& event_queue) = 0; }; } // namespace details } // namespace manipulator } // namespace krbn <|endoftext|>
<commit_before>// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // // // Code that is used by both the Unix corerun and coreconsole. // #include <assert.h> #include <dirent.h> #include <dlfcn.h> #include <limits.h> #include <set> #include <string> #include <string.h> #include <sys/stat.h> // The name of the CoreCLR native runtime DLL #if defined(__APPLE__) static const char * const coreClrDll = "libcoreclr.dylib"; #else static const char * const coreClrDll = "libcoreclr.so"; #endif // Windows types used by the ExecuteAssembly function typedef unsigned int DWORD; typedef const char16_t* LPCWSTR; typedef const char* LPCSTR; typedef int32_t HRESULT; #define SUCCEEDED(Status) ((HRESULT)(Status) >= 0) // Prototype of the ExecuteAssembly function from the libcoreclr.do typedef HRESULT (*ExecuteAssemblyFunction)( LPCSTR exePath, LPCSTR coreClrPath, LPCSTR appDomainFriendlyName, int propertyCount, LPCSTR* propertyKeys, LPCSTR* propertyValues, int argc, LPCSTR* argv, LPCSTR managedAssemblyPath, LPCSTR entryPointAssemblyName, LPCSTR entryPointTypeName, LPCSTR entryPointMethodsName, DWORD* exitCode); bool GetAbsolutePath(const char* path, std::string& absolutePath) { bool result = false; char realPath[PATH_MAX]; if (realpath(path, realPath) != nullptr && realPath[0] != '\0') { absolutePath.assign(realPath); // realpath should return canonicalized path without the trailing slash assert(absolutePath.back() != '/'); result = true; } return result; } bool GetDirectory(const char* absolutePath, std::string& directory) { directory.assign(absolutePath); size_t lastSlash = directory.rfind('/'); if (lastSlash != std::string::npos) { directory.erase(lastSlash); return true; } return false; } bool GetClrFilesAbsolutePath(const char* currentExePath, const char* clrFilesPath, std::string& clrFilesAbsolutePath) { std::string clrFilesRelativePath; const char* clrFilesPathLocal = clrFilesPath; if (clrFilesPathLocal == nullptr) { // There was no CLR files path specified, use the folder of the corerun/coreconsole if (!GetDirectory(currentExePath, clrFilesRelativePath)) { perror("Failed to get directory from argv[0]"); return false; } clrFilesPathLocal = clrFilesRelativePath.c_str(); // TODO: consider using an env variable (if defined) as a fall-back. // The windows version of the corerun uses core_root env variable } if (!GetAbsolutePath(clrFilesPathLocal, clrFilesAbsolutePath)) { perror("Failed to convert CLR files path to absolute path"); return false; } return true; } void AddFilesFromDirectoryToTpaList(const char* directory, std::string& tpaList) { const char * const tpaExtensions[] = { ".ni.dll", // Probe for .ni.dll first so that it's preferred if ni and il coexist in the same dir ".dll", ".ni.exe", ".exe", }; DIR* dir = opendir(directory); if (dir == nullptr) { return; } std::set<std::string> addedAssemblies; // Walk the directory for each extension separately so that we first get files with .ni.dll extension, // then files with .dll extension, etc. for (int extIndex = 0; extIndex < sizeof(tpaExtensions) / sizeof(tpaExtensions[0]); extIndex++) { const char* ext = tpaExtensions[extIndex]; int extLength = strlen(ext); struct dirent* entry; // For all entries in the directory while ((entry = readdir(dir)) != nullptr) { // We are interested in files only switch (entry->d_type) { case DT_REG: break; // Handle symlinks and file systems that do not support d_type case DT_LNK: case DT_UNKNOWN: { std::string fullFilename; fullFilename.append(directory); fullFilename.append("/"); fullFilename.append(entry->d_name); struct stat sb; if (stat(fullFilename.c_str(), &sb) == -1) { continue; } if (!S_ISREG(sb.st_mode)) { continue; } } break; default: continue; } std::string filename(entry->d_name); // Check if the extension matches the one we are looking for int extPos = filename.length() - extLength; if ((extPos <= 0) || (filename.compare(extPos, extLength, ext) != 0)) { continue; } std::string filenameWithoutExt(filename.substr(0, extPos)); // Make sure if we have an assembly with multiple extensions present, // we insert only one version of it. if (addedAssemblies.find(filenameWithoutExt) == addedAssemblies.end()) { addedAssemblies.insert(filenameWithoutExt); tpaList.append(directory); tpaList.append("/"); tpaList.append(filename); tpaList.append(":"); } } // Rewind the directory stream to be able to iterate over it for the next extension rewinddir(dir); } closedir(dir); } int ExecuteManagedAssembly( const char* currentExeAbsolutePath, const char* clrFilesAbsolutePath, const char* managedAssemblyAbsolutePath, int managedAssemblyArgc, const char** managedAssemblyArgv) { // Indicates failure int exitCode = -1; std::string coreClrDllPath(clrFilesAbsolutePath); coreClrDllPath.append("/"); coreClrDllPath.append(coreClrDll); if (coreClrDllPath.length() >= PATH_MAX) { fprintf(stderr, "Absolute path to libcoreclr.so too long\n"); return -1; } // Get just the path component of the managed assembly path std::string appPath; GetDirectory(managedAssemblyAbsolutePath, appPath); std::string nativeDllSearchDirs(appPath); nativeDllSearchDirs.append(":"); nativeDllSearchDirs.append(clrFilesAbsolutePath); std::string tpaList; AddFilesFromDirectoryToTpaList(clrFilesAbsolutePath, tpaList); void* coreclrLib = dlopen(coreClrDllPath.c_str(), RTLD_NOW | RTLD_LOCAL); if (coreclrLib != nullptr) { ExecuteAssemblyFunction executeAssembly = (ExecuteAssemblyFunction)dlsym(coreclrLib, "ExecuteAssembly"); if (executeAssembly != nullptr) { // Allowed property names: // APPBASE // - The base path of the application from which the exe and other assemblies will be loaded // // TRUSTED_PLATFORM_ASSEMBLIES // - The list of complete paths to each of the fully trusted assemblies // // APP_PATHS // - The list of paths which will be probed by the assembly loader // // APP_NI_PATHS // - The list of additional paths that the assembly loader will probe for ngen images // // NATIVE_DLL_SEARCH_DIRECTORIES // - The list of paths that will be probed for native DLLs called by PInvoke // const char *propertyKeys[] = { "TRUSTED_PLATFORM_ASSEMBLIES", "APP_PATHS", "APP_NI_PATHS", "NATIVE_DLL_SEARCH_DIRECTORIES", "AppDomainCompatSwitch" }; const char *propertyValues[] = { // TRUSTED_PLATFORM_ASSEMBLIES tpaList.c_str(), // APP_PATHS appPath.c_str(), // APP_NI_PATHS appPath.c_str(), // NATIVE_DLL_SEARCH_DIRECTORIES nativeDllSearchDirs.c_str(), // AppDomainCompatSwitch "UseLatestBehaviorWhenTFMNotSpecified" }; HRESULT st = executeAssembly( currentExeAbsolutePath, coreClrDllPath.c_str(), "unixcorerun", sizeof(propertyKeys) / sizeof(propertyKeys[0]), propertyKeys, propertyValues, managedAssemblyArgc, managedAssemblyArgv, managedAssemblyAbsolutePath, NULL, NULL, NULL, (DWORD*)&exitCode); if (!SUCCEEDED(st)) { fprintf(stderr, "ExecuteAssembly failed - status: 0x%08x\n", st); } } else { fprintf(stderr, "Function ExecuteAssembly not found in the libcoreclr.so\n"); } if (dlclose(coreclrLib) != 0) { fprintf(stderr, "Warning - dlclose failed\n"); } } else { char* error = dlerror(); fprintf(stderr, "dlopen failed to open the libcoreclr.so with error %s\n", error); } return exitCode; } <commit_msg>Fix unixcoreruncommon build error on FreeBSD Needed cstdlib to build properly<commit_after>// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // // // Code that is used by both the Unix corerun and coreconsole. // #include <cstdlib> #include <assert.h> #include <dirent.h> #include <dlfcn.h> #include <limits.h> #include <set> #include <string> #include <string.h> #include <sys/stat.h> // The name of the CoreCLR native runtime DLL #if defined(__APPLE__) static const char * const coreClrDll = "libcoreclr.dylib"; #else static const char * const coreClrDll = "libcoreclr.so"; #endif // Windows types used by the ExecuteAssembly function typedef unsigned int DWORD; typedef const char16_t* LPCWSTR; typedef const char* LPCSTR; typedef int32_t HRESULT; #define SUCCEEDED(Status) ((HRESULT)(Status) >= 0) // Prototype of the ExecuteAssembly function from the libcoreclr.do typedef HRESULT (*ExecuteAssemblyFunction)( LPCSTR exePath, LPCSTR coreClrPath, LPCSTR appDomainFriendlyName, int propertyCount, LPCSTR* propertyKeys, LPCSTR* propertyValues, int argc, LPCSTR* argv, LPCSTR managedAssemblyPath, LPCSTR entryPointAssemblyName, LPCSTR entryPointTypeName, LPCSTR entryPointMethodsName, DWORD* exitCode); bool GetAbsolutePath(const char* path, std::string& absolutePath) { bool result = false; char realPath[PATH_MAX]; if (realpath(path, realPath) != nullptr && realPath[0] != '\0') { absolutePath.assign(realPath); // realpath should return canonicalized path without the trailing slash assert(absolutePath.back() != '/'); result = true; } return result; } bool GetDirectory(const char* absolutePath, std::string& directory) { directory.assign(absolutePath); size_t lastSlash = directory.rfind('/'); if (lastSlash != std::string::npos) { directory.erase(lastSlash); return true; } return false; } bool GetClrFilesAbsolutePath(const char* currentExePath, const char* clrFilesPath, std::string& clrFilesAbsolutePath) { std::string clrFilesRelativePath; const char* clrFilesPathLocal = clrFilesPath; if (clrFilesPathLocal == nullptr) { // There was no CLR files path specified, use the folder of the corerun/coreconsole if (!GetDirectory(currentExePath, clrFilesRelativePath)) { perror("Failed to get directory from argv[0]"); return false; } clrFilesPathLocal = clrFilesRelativePath.c_str(); // TODO: consider using an env variable (if defined) as a fall-back. // The windows version of the corerun uses core_root env variable } if (!GetAbsolutePath(clrFilesPathLocal, clrFilesAbsolutePath)) { perror("Failed to convert CLR files path to absolute path"); return false; } return true; } void AddFilesFromDirectoryToTpaList(const char* directory, std::string& tpaList) { const char * const tpaExtensions[] = { ".ni.dll", // Probe for .ni.dll first so that it's preferred if ni and il coexist in the same dir ".dll", ".ni.exe", ".exe", }; DIR* dir = opendir(directory); if (dir == nullptr) { return; } std::set<std::string> addedAssemblies; // Walk the directory for each extension separately so that we first get files with .ni.dll extension, // then files with .dll extension, etc. for (int extIndex = 0; extIndex < sizeof(tpaExtensions) / sizeof(tpaExtensions[0]); extIndex++) { const char* ext = tpaExtensions[extIndex]; int extLength = strlen(ext); struct dirent* entry; // For all entries in the directory while ((entry = readdir(dir)) != nullptr) { // We are interested in files only switch (entry->d_type) { case DT_REG: break; // Handle symlinks and file systems that do not support d_type case DT_LNK: case DT_UNKNOWN: { std::string fullFilename; fullFilename.append(directory); fullFilename.append("/"); fullFilename.append(entry->d_name); struct stat sb; if (stat(fullFilename.c_str(), &sb) == -1) { continue; } if (!S_ISREG(sb.st_mode)) { continue; } } break; default: continue; } std::string filename(entry->d_name); // Check if the extension matches the one we are looking for int extPos = filename.length() - extLength; if ((extPos <= 0) || (filename.compare(extPos, extLength, ext) != 0)) { continue; } std::string filenameWithoutExt(filename.substr(0, extPos)); // Make sure if we have an assembly with multiple extensions present, // we insert only one version of it. if (addedAssemblies.find(filenameWithoutExt) == addedAssemblies.end()) { addedAssemblies.insert(filenameWithoutExt); tpaList.append(directory); tpaList.append("/"); tpaList.append(filename); tpaList.append(":"); } } // Rewind the directory stream to be able to iterate over it for the next extension rewinddir(dir); } closedir(dir); } int ExecuteManagedAssembly( const char* currentExeAbsolutePath, const char* clrFilesAbsolutePath, const char* managedAssemblyAbsolutePath, int managedAssemblyArgc, const char** managedAssemblyArgv) { // Indicates failure int exitCode = -1; std::string coreClrDllPath(clrFilesAbsolutePath); coreClrDllPath.append("/"); coreClrDllPath.append(coreClrDll); if (coreClrDllPath.length() >= PATH_MAX) { fprintf(stderr, "Absolute path to libcoreclr.so too long\n"); return -1; } // Get just the path component of the managed assembly path std::string appPath; GetDirectory(managedAssemblyAbsolutePath, appPath); std::string nativeDllSearchDirs(appPath); nativeDllSearchDirs.append(":"); nativeDllSearchDirs.append(clrFilesAbsolutePath); std::string tpaList; AddFilesFromDirectoryToTpaList(clrFilesAbsolutePath, tpaList); void* coreclrLib = dlopen(coreClrDllPath.c_str(), RTLD_NOW | RTLD_LOCAL); if (coreclrLib != nullptr) { ExecuteAssemblyFunction executeAssembly = (ExecuteAssemblyFunction)dlsym(coreclrLib, "ExecuteAssembly"); if (executeAssembly != nullptr) { // Allowed property names: // APPBASE // - The base path of the application from which the exe and other assemblies will be loaded // // TRUSTED_PLATFORM_ASSEMBLIES // - The list of complete paths to each of the fully trusted assemblies // // APP_PATHS // - The list of paths which will be probed by the assembly loader // // APP_NI_PATHS // - The list of additional paths that the assembly loader will probe for ngen images // // NATIVE_DLL_SEARCH_DIRECTORIES // - The list of paths that will be probed for native DLLs called by PInvoke // const char *propertyKeys[] = { "TRUSTED_PLATFORM_ASSEMBLIES", "APP_PATHS", "APP_NI_PATHS", "NATIVE_DLL_SEARCH_DIRECTORIES", "AppDomainCompatSwitch" }; const char *propertyValues[] = { // TRUSTED_PLATFORM_ASSEMBLIES tpaList.c_str(), // APP_PATHS appPath.c_str(), // APP_NI_PATHS appPath.c_str(), // NATIVE_DLL_SEARCH_DIRECTORIES nativeDllSearchDirs.c_str(), // AppDomainCompatSwitch "UseLatestBehaviorWhenTFMNotSpecified" }; HRESULT st = executeAssembly( currentExeAbsolutePath, coreClrDllPath.c_str(), "unixcorerun", sizeof(propertyKeys) / sizeof(propertyKeys[0]), propertyKeys, propertyValues, managedAssemblyArgc, managedAssemblyArgv, managedAssemblyAbsolutePath, NULL, NULL, NULL, (DWORD*)&exitCode); if (!SUCCEEDED(st)) { fprintf(stderr, "ExecuteAssembly failed - status: 0x%08x\n", st); } } else { fprintf(stderr, "Function ExecuteAssembly not found in the libcoreclr.so\n"); } if (dlclose(coreclrLib) != 0) { fprintf(stderr, "Warning - dlclose failed\n"); } } else { char* error = dlerror(); fprintf(stderr, "dlopen failed to open the libcoreclr.so with error %s\n", error); } return exitCode; } <|endoftext|>
<commit_before>/* * opencog/atoms/base/Link.cc * * Copyright (C) 2008-2010 OpenCog Foundation * Copyright (C) 2002-2007 Novamente LLC * All Rights Reserved * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <stdio.h> #include <opencog/util/exceptions.h> #include <opencog/util/Logger.h> #include <opencog/atoms/base/ClassServer.h> #include <opencog/atoms/base/Node.h> #include <opencog/atomspace/AtomTable.h> #include <boost/range/algorithm.hpp> #include "Link.h" //#define DPRINTF printf #define DPRINTF(...) using namespace opencog; void Link::resort(void) { // Caution: this comparison function MUST BE EXACTLY THE SAME as // the one in AtomTable.cc, used for Unordered links. Changing // this without changing the other one will break things! std::sort(_outgoing.begin(), _outgoing.end(), handle_less()); } void Link::init(const HandleSeq& outgoingVector) { if (not classserver().isA(_type, LINK)) { throw InvalidParamException(TRACE_INFO, "Link ctor: Atom type is not a Link: '%d' %s.", _type, classserver().getTypeName(_type).c_str()); } _outgoing = outgoingVector; // If the link is unordered, it will be normalized by sorting the // elements in the outgoing list. if (classserver().isA(_type, UNORDERED_LINK)) { resort(); } } Link::~Link() { DPRINTF("Deleting link:\n%s\n", this->toString().c_str()); } std::string Link::toShortString(const std::string& indent) const { std::stringstream answer; std::string more_indent = indent + " "; answer << indent << "(" << classserver().getTypeName(_type); if (not getTruthValue()->isDefaultTV()) answer << " " << getTruthValue()->toString(); answer << "\n"; // Here the target string is made. If a target is a node, its name is // concatenated. If it's a link, all its properties are concatenated. for (const Handle& h : _outgoing) { if (h.operator->() != NULL) answer << h->toShortString(more_indent); else answer << more_indent << "Undefined Atom!\n"; } answer << indent << ") ; [" << _uuid << "]"; if (_atomTable) answer << "[" << _atomTable->get_uuid() << "]\n"; else answer << "[NULL]\n"; return answer.str(); } std::string Link::toString(const std::string& indent) const { std::string answer = indent; std::string more_indent = indent + " "; answer += "(" + classserver().getTypeName(_type); // Print the TV and AV only if its not the default. if (not getAttentionValue()->isDefaultAV()) answer += " (av " + std::to_string(getAttentionValue()->getSTI()) + " " + std::to_string(getAttentionValue()->getLTI()) + " " + std::to_string(getAttentionValue()->getVLTI()) + ")"; if (not getTruthValue()->isDefaultTV()) answer += " " + getTruthValue()->toString(); answer += "\n"; // Here, the outset string is made. If a target is a node, // its name is concatenated. If it's a link, then recurse. for (const Handle& h : _outgoing) { if (h.operator->() != NULL) answer += h->toString(more_indent); else answer += more_indent + "Undefined Atom!\n"; } answer += indent + ") ; [" + std::to_string(_uuid) + "][" + std::to_string(_atomTable? _atomTable->get_uuid() : -1) + "]\n"; return answer; } // Content-based comparison. bool Link::operator==(const Atom& other) const { // If other points to this, then have equality. if (this == &other) return true; // Rule out obvious mis-matches, based on the hash. if (get_hash() != other.get_hash()) return false; if (getType() != other.getType()) return false; Arity sz = getArity(); if (sz != other.getArity()) return false; // Perform a content-compare on the outgoing set. const HandleSeq& rhs = other.getOutgoingSet(); for (Arity i = 0; i < sz; i++) { if (*((AtomPtr)_outgoing[i]) != *((AtomPtr)rhs[i])) return false; } return true; } // Content-based ordering. bool Link::operator<(const Atom& other) const { if (get_hash() < other.get_hash()) return true; if (other.get_hash() < get_hash()) return false; // We get to here only if the hashes are equal. // Compare the contents directly, for this // (hopefully rare) case. if (getType() == other.getType()) { const HandleSeq& outgoing = getOutgoingSet(); const HandleSeq& other_outgoing = other.getOutgoingSet(); Arity arity = outgoing.size(); Arity other_arity = other_outgoing.size(); if (arity == other_arity) { Arity i = 0; while (i < arity) { Handle ll = outgoing[i]; Handle rl = other_outgoing[i]; if (ll == rl) i++; else return ll->operator<(*rl.atom_ptr()); } return false; } else return arity < other_arity; } else return getType() < other.getType(); } /// Returns a Merkle tree hash -- that is, the hash of this link /// chains the hash values of the child atoms, as well. ContentHash Link::compute_hash() const { // djb hash ContentHash hsh = 5381; hsh += (hsh <<5) + getType(); for (const Handle& h: _outgoing) { hsh += (hsh <<5) + h->get_hash(); // recursive! } // Links will always have the MSB set. ContentHash mask = ((ContentHash) 1UL) << (8*sizeof(ContentHash) - 1); hsh |= mask; if (Handle::INVALID_HASH == hsh) hsh -= 1; _content_hash = hsh; return _content_hash; } <commit_msg>Simplify the content-ordering function.<commit_after>/* * opencog/atoms/base/Link.cc * * Copyright (C) 2008-2010 OpenCog Foundation * Copyright (C) 2002-2007 Novamente LLC * All Rights Reserved * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <stdio.h> #include <opencog/util/exceptions.h> #include <opencog/util/Logger.h> #include <opencog/atoms/base/ClassServer.h> #include <opencog/atoms/base/Node.h> #include <opencog/atomspace/AtomTable.h> #include <boost/range/algorithm.hpp> #include "Link.h" //#define DPRINTF printf #define DPRINTF(...) using namespace opencog; void Link::resort(void) { // Caution: this comparison function MUST BE EXACTLY THE SAME as // the one in AtomTable.cc, used for Unordered links. Changing // this without changing the other one will break things! std::sort(_outgoing.begin(), _outgoing.end(), handle_less()); } void Link::init(const HandleSeq& outgoingVector) { if (not classserver().isA(_type, LINK)) { throw InvalidParamException(TRACE_INFO, "Link ctor: Atom type is not a Link: '%d' %s.", _type, classserver().getTypeName(_type).c_str()); } _outgoing = outgoingVector; // If the link is unordered, it will be normalized by sorting the // elements in the outgoing list. if (classserver().isA(_type, UNORDERED_LINK)) { resort(); } } Link::~Link() { DPRINTF("Deleting link:\n%s\n", this->toString().c_str()); } std::string Link::toShortString(const std::string& indent) const { std::stringstream answer; std::string more_indent = indent + " "; answer << indent << "(" << classserver().getTypeName(_type); if (not getTruthValue()->isDefaultTV()) answer << " " << getTruthValue()->toString(); answer << "\n"; // Here the target string is made. If a target is a node, its name is // concatenated. If it's a link, all its properties are concatenated. for (const Handle& h : _outgoing) { if (h.operator->() != NULL) answer << h->toShortString(more_indent); else answer << more_indent << "Undefined Atom!\n"; } answer << indent << ") ; [" << _uuid << "]"; if (_atomTable) answer << "[" << _atomTable->get_uuid() << "]\n"; else answer << "[NULL]\n"; return answer.str(); } std::string Link::toString(const std::string& indent) const { std::string answer = indent; std::string more_indent = indent + " "; answer += "(" + classserver().getTypeName(_type); // Print the TV and AV only if its not the default. if (not getAttentionValue()->isDefaultAV()) answer += " (av " + std::to_string(getAttentionValue()->getSTI()) + " " + std::to_string(getAttentionValue()->getLTI()) + " " + std::to_string(getAttentionValue()->getVLTI()) + ")"; if (not getTruthValue()->isDefaultTV()) answer += " " + getTruthValue()->toString(); answer += "\n"; // Here, the outset string is made. If a target is a node, // its name is concatenated. If it's a link, then recurse. for (const Handle& h : _outgoing) { if (h.operator->() != NULL) answer += h->toString(more_indent); else answer += more_indent + "Undefined Atom!\n"; } answer += indent + ") ; [" + std::to_string(_uuid) + "][" + std::to_string(_atomTable? _atomTable->get_uuid() : -1) + "]\n"; return answer; } // Content-based comparison. bool Link::operator==(const Atom& other) const { // If other points to this, then have equality. if (this == &other) return true; // Rule out obvious mis-matches, based on the hash. if (get_hash() != other.get_hash()) return false; if (getType() != other.getType()) return false; Arity sz = getArity(); if (sz != other.getArity()) return false; // Perform a content-compare on the outgoing set. const HandleSeq& rhs = other.getOutgoingSet(); for (Arity i = 0; i < sz; i++) { if (*((AtomPtr)_outgoing[i]) != *((AtomPtr)rhs[i])) return false; } return true; } // Content-based ordering. bool Link::operator<(const Atom& other) const { if (get_hash() < other.get_hash()) return true; if (other.get_hash() < get_hash()) return false; // We get to here only if the hashes are equal. // Compare the contents directly, for this // (hopefully rare) case. if (getType() != other.getType()) return getType() < other.getType(); const HandleSeq& outgoing = getOutgoingSet(); const HandleSeq& other_outgoing = other.getOutgoingSet(); Arity arity = outgoing.size(); Arity other_arity = other_outgoing.size(); if (arity != other_arity) return arity < other_arity; for (Arity i=0; i < arity; i++) { const Handle& ll(outgoing[i]); const AtomPtr& rl(other_outgoing[i]); if (ll->operator!=(*rl)) return ll->operator<(*rl); } return false; } /// Returns a Merkle tree hash -- that is, the hash of this link /// chains the hash values of the child atoms, as well. ContentHash Link::compute_hash() const { // djb hash ContentHash hsh = 5381; hsh += (hsh <<5) + getType(); for (const Handle& h: _outgoing) { hsh += (hsh <<5) + h->get_hash(); // recursive! } // Links will always have the MSB set. ContentHash mask = ((ContentHash) 1UL) << (8*sizeof(ContentHash) - 1); hsh |= mask; if (Handle::INVALID_HASH == hsh) hsh -= 1; _content_hash = hsh; return _content_hash; } <|endoftext|>
<commit_before>/** * Touhou Community Reliant Automatic Patcher * Main DLL * * ---- * * Persistent string storage, and translation of hardcoded strings. */ #include "thcrap.h" #include <unordered_map> /// Detour chains /// ------------- W32U8_DETOUR_CHAIN_DEF(MessageBox); /// ------------- // Length-prefixed string object used for persistent storage typedef struct { size_t len; char str; } storage_string_t; static json_t *strings_storage = NULL; SRWLOCK stringlocs_srwlock = {SRWLOCK_INIT}; std::unordered_map<const char *, const char *> stringlocs; #define addr_key_len 2 + (sizeof(void*) * 2) + 1 void stringlocs_reparse(void) { // Since we can't use the jsondata module to make this repatchable, // we only need to keep the last parsed JSON object around to // provide the "backing memory" for the ID strings. static json_t *backing_obj = NULL; json_t* new_obj = stack_game_json_resolve("stringlocs.js", NULL); const char *key; const json_t *val; AcquireSRWLockExclusive(&stringlocs_srwlock); stringlocs.clear(); json_object_foreach(new_obj, key, val) { // TODO: For now, we're nagging developers with one message box for // every single parse error. It'd certainly be better if we gathered // all errors into a single message box to be printed at the end of // the parsing, and even had a somewhat generic solution if we do // more of these conversions. #define stringlocs_log_error(msg) \ log_mboxf(NULL, MB_OK | MB_ICONEXCLAMATION, \ "Error parsing stringlocs.js: \"%s\" " msg".", key, sizeof(size_t) * 8 \ ) if(!json_is_string(val)) { stringlocs_log_error("must be a JSON string"); continue; } uint8_t error; const char *addr = (const char *)str_address_value(key, &error); if(error == STR_ADDRESS_ERROR_NONE) { stringlocs[addr] = json_string_value(val); } if(error & STR_ADDRESS_ERROR_OVERFLOW) { stringlocs_log_error("exceeds %d bits"); } if(error & STR_ADDRESS_ERROR_GARBAGE) { stringlocs_log_error("has garbage at the end"); } #undef stringlocs_log_error } json_decref(backing_obj); backing_obj = new_obj; ReleaseSRWLockExclusive(&stringlocs_srwlock); } const json_t* strings_get(const char *id) { return json_object_get(jsondata_get("stringdefs.js"), id); } const char* strings_lookup(const char *in, size_t *out_len) { const char *ret = in; if(!in) { return in; } AcquireSRWLockShared(&stringlocs_srwlock); auto id_key = stringlocs.find(in); if(id_key != stringlocs.end()) { const char *new_str = json_string_value(strings_get(id_key->second)); if(new_str && new_str[0]) { ret = new_str; } } ReleaseSRWLockShared(&stringlocs_srwlock); if(out_len) { *out_len = strlen(ret) + 1; } return ret; } void strings_va_lookup(va_list va, const char *format) { const char *p = format; while(*p) { printf_format_t fmt; int i; // Skip characters before '%' for(; *p && *p != '%'; p++); if(!*p) { break; } // *p == '%' here p++; // output a single '%' character if(*p == '%') { p++; continue; } p = printf_format_parse(&fmt, p); for(i = 0; i < fmt.argc_before_type; i++) { va_arg(va, int); } if(fmt.type == 's' || fmt.type == 'S') { *(const char**)va = strings_lookup(*(const char**)va, NULL); } for(i = 0; i < fmt.type_size_in_ints; i++) { va_arg(va, int); } } } char* strings_storage_get(const size_t slot, size_t min_len) { storage_string_t *ret = NULL; char addr_key[addr_key_len]; itoa(slot, addr_key, 16); ret = (storage_string_t*)json_object_get_hex(strings_storage, addr_key); // MSVCRT's realloc implementation moves the buffer every time, even if the // new length is shorter... if(!ret || (min_len && ret->len < min_len)) { storage_string_t *ret_new = (storage_string_t*)realloc(ret, min_len + sizeof(storage_string_t)); // Yes, this correctly handles a realloc failure. if(ret_new) { ret_new->len = min_len; if(!ret) { ret_new->str = 0; } json_object_set_new(strings_storage, addr_key, json_integer((size_t)ret_new)); ret = ret_new; } } if(ret) { return &ret->str; } return NULL; } const char* strings_vsprintf(const size_t slot, const char *format, va_list va) { char *ret = NULL; size_t str_len; format = strings_lookup(format, NULL); strings_va_lookup(va, format); if(!format) { return NULL; } str_len = _vscprintf(format, va) + 1; ret = strings_storage_get(slot, str_len); if(ret) { vsprintf(ret, format, va); return ret; } // Try to save the situation at least somewhat... return format; } const char* strings_vsprintf_msvcrt14(const char *format, const size_t slot, va_list va) { return strings_vsprintf(slot, format, va); } const char* strings_sprintf(const size_t slot, const char *format, ...) { va_list va; const char *ret; va_start(va, format); ret = strings_vsprintf(slot, format, va); return ret; } const char* strings_strclr(const size_t slot) { char *ret = strings_storage_get(slot, 0); if(ret) { ret[0] = 0; } return ret; } const char* strings_strcat(const size_t slot, const char *src) { char *ret = strings_storage_get(slot, 0); size_t ret_len = strlen(ret); size_t src_len; src = strings_lookup(src, &src_len); ret = strings_storage_get(slot, ret_len + src_len); if(ret) { strncpy(ret + ret_len, src, src_len); return ret; } // Try to save the situation at least somewhat... return src; } const char* strings_replace(const size_t slot, const char *src, const char *dst) { char *ret = strings_storage_get(slot, 0); dst = dst ? dst : ""; if(src && ret) { size_t src_len = strlen(src); size_t dst_len = strlen(dst); while(ret) { char *src_pos = NULL; char *copy_pos = NULL; char *rest_pos = NULL; size_t ret_len = strlen(ret); // We do this first since the string address might change after // reallocation, thus invalidating the strstr() result ret = strings_storage_get(slot, ret_len + dst_len); if(!ret) { break; } src_pos = strstr(ret, src); if(!src_pos) { break; } copy_pos = src_pos + dst_len; rest_pos = src_pos + src_len; memmove(copy_pos, rest_pos, strlen(rest_pos) + 1); memcpy(src_pos, dst, dst_len); } } // Try to save the situation at least somewhat... return ret ? ret : dst; } /// String lookup hooks /// ------------------- int WINAPI strings_MessageBoxA( HWND hWnd, LPCSTR lpText, LPCSTR lpCaption, UINT uType ) { lpText = strings_lookup(lpText, NULL); lpCaption = strings_lookup(lpCaption, NULL); return chain_MessageBoxU(hWnd, lpText, lpCaption, uType); } /// ------------------- void strings_mod_init(void) { jsondata_add("stringdefs.js"); stringlocs_reparse(); strings_storage = json_object(); } void strings_mod_detour(void) { detour_chain("user32.dll", 1, "MessageBoxA", strings_MessageBoxA, &chain_MessageBoxU, NULL ); } void strings_mod_repatch(json_t *files_changed) { const char *key; const json_t *val; json_object_foreach(files_changed, key, val) { if(strstr(key, "/stringlocs.")) { stringlocs_reparse(); } } } void strings_mod_exit(void) { const char *key; json_t *val; json_object_foreach(strings_storage, key, val) { storage_string_t *p = (storage_string_t*)json_hex_value(val); SAFE_FREE(p); } strings_storage = json_decref_safe(strings_storage); } <commit_msg>Use a std::unordered_map for persistent storage strings.<commit_after>/** * Touhou Community Reliant Automatic Patcher * Main DLL * * ---- * * Persistent string storage, and translation of hardcoded strings. */ #include "thcrap.h" #include <unordered_map> /// Detour chains /// ------------- W32U8_DETOUR_CHAIN_DEF(MessageBox); /// ------------- // Length-prefixed string object used for persistent storage typedef struct { size_t len; char str; } storage_string_t; std::unordered_map<size_t, storage_string_t *> strings_storage; SRWLOCK stringlocs_srwlock = {SRWLOCK_INIT}; std::unordered_map<const char *, const char *> stringlocs; #define addr_key_len 2 + (sizeof(void*) * 2) + 1 void stringlocs_reparse(void) { // Since we can't use the jsondata module to make this repatchable, // we only need to keep the last parsed JSON object around to // provide the "backing memory" for the ID strings. static json_t *backing_obj = NULL; json_t* new_obj = stack_game_json_resolve("stringlocs.js", NULL); const char *key; const json_t *val; AcquireSRWLockExclusive(&stringlocs_srwlock); stringlocs.clear(); json_object_foreach(new_obj, key, val) { // TODO: For now, we're nagging developers with one message box for // every single parse error. It'd certainly be better if we gathered // all errors into a single message box to be printed at the end of // the parsing, and even had a somewhat generic solution if we do // more of these conversions. #define stringlocs_log_error(msg) \ log_mboxf(NULL, MB_OK | MB_ICONEXCLAMATION, \ "Error parsing stringlocs.js: \"%s\" " msg".", key, sizeof(size_t) * 8 \ ) if(!json_is_string(val)) { stringlocs_log_error("must be a JSON string"); continue; } uint8_t error; const char *addr = (const char *)str_address_value(key, &error); if(error == STR_ADDRESS_ERROR_NONE) { stringlocs[addr] = json_string_value(val); } if(error & STR_ADDRESS_ERROR_OVERFLOW) { stringlocs_log_error("exceeds %d bits"); } if(error & STR_ADDRESS_ERROR_GARBAGE) { stringlocs_log_error("has garbage at the end"); } #undef stringlocs_log_error } json_decref(backing_obj); backing_obj = new_obj; ReleaseSRWLockExclusive(&stringlocs_srwlock); } const json_t* strings_get(const char *id) { return json_object_get(jsondata_get("stringdefs.js"), id); } const char* strings_lookup(const char *in, size_t *out_len) { const char *ret = in; if(!in) { return in; } AcquireSRWLockShared(&stringlocs_srwlock); auto id_key = stringlocs.find(in); if(id_key != stringlocs.end()) { const char *new_str = json_string_value(strings_get(id_key->second)); if(new_str && new_str[0]) { ret = new_str; } } ReleaseSRWLockShared(&stringlocs_srwlock); if(out_len) { *out_len = strlen(ret) + 1; } return ret; } void strings_va_lookup(va_list va, const char *format) { const char *p = format; while(*p) { printf_format_t fmt; int i; // Skip characters before '%' for(; *p && *p != '%'; p++); if(!*p) { break; } // *p == '%' here p++; // output a single '%' character if(*p == '%') { p++; continue; } p = printf_format_parse(&fmt, p); for(i = 0; i < fmt.argc_before_type; i++) { va_arg(va, int); } if(fmt.type == 's' || fmt.type == 'S') { *(const char**)va = strings_lookup(*(const char**)va, NULL); } for(i = 0; i < fmt.type_size_in_ints; i++) { va_arg(va, int); } } } char* strings_storage_get(const size_t slot, size_t min_len) { storage_string_t *ret = nullptr; auto stored = strings_storage.find(slot); // MSVCRT's realloc implementation moves the buffer every time, even if the // new length is shorter... if(stored == strings_storage.end() || (min_len && stored->second->len < min_len)) { auto *ret_new = (storage_string_t*)realloc(ret, min_len + sizeof(storage_string_t)); // Yes, this correctly handles a realloc failure. if(ret_new) { ret_new->len = min_len; if(!ret) { ret_new->str = 0; } strings_storage[slot] = ret_new; ret = ret_new; } } else { ret = stored->second; } if(ret) { return &ret->str; } return nullptr; } const char* strings_vsprintf(const size_t slot, const char *format, va_list va) { char *ret = NULL; size_t str_len; format = strings_lookup(format, NULL); strings_va_lookup(va, format); if(!format) { return NULL; } str_len = _vscprintf(format, va) + 1; ret = strings_storage_get(slot, str_len); if(ret) { vsprintf(ret, format, va); return ret; } // Try to save the situation at least somewhat... return format; } const char* strings_vsprintf_msvcrt14(const char *format, const size_t slot, va_list va) { return strings_vsprintf(slot, format, va); } const char* strings_sprintf(const size_t slot, const char *format, ...) { va_list va; const char *ret; va_start(va, format); ret = strings_vsprintf(slot, format, va); return ret; } const char* strings_strclr(const size_t slot) { char *ret = strings_storage_get(slot, 0); if(ret) { ret[0] = 0; } return ret; } const char* strings_strcat(const size_t slot, const char *src) { char *ret = strings_storage_get(slot, 0); size_t ret_len = strlen(ret); size_t src_len; src = strings_lookup(src, &src_len); ret = strings_storage_get(slot, ret_len + src_len); if(ret) { strncpy(ret + ret_len, src, src_len); return ret; } // Try to save the situation at least somewhat... return src; } const char* strings_replace(const size_t slot, const char *src, const char *dst) { char *ret = strings_storage_get(slot, 0); dst = dst ? dst : ""; if(src && ret) { size_t src_len = strlen(src); size_t dst_len = strlen(dst); while(ret) { char *src_pos = NULL; char *copy_pos = NULL; char *rest_pos = NULL; size_t ret_len = strlen(ret); // We do this first since the string address might change after // reallocation, thus invalidating the strstr() result ret = strings_storage_get(slot, ret_len + dst_len); if(!ret) { break; } src_pos = strstr(ret, src); if(!src_pos) { break; } copy_pos = src_pos + dst_len; rest_pos = src_pos + src_len; memmove(copy_pos, rest_pos, strlen(rest_pos) + 1); memcpy(src_pos, dst, dst_len); } } // Try to save the situation at least somewhat... return ret ? ret : dst; } /// String lookup hooks /// ------------------- int WINAPI strings_MessageBoxA( HWND hWnd, LPCSTR lpText, LPCSTR lpCaption, UINT uType ) { lpText = strings_lookup(lpText, NULL); lpCaption = strings_lookup(lpCaption, NULL); return chain_MessageBoxU(hWnd, lpText, lpCaption, uType); } /// ------------------- void strings_mod_init(void) { jsondata_add("stringdefs.js"); stringlocs_reparse(); } void strings_mod_detour(void) { detour_chain("user32.dll", 1, "MessageBoxA", strings_MessageBoxA, &chain_MessageBoxU, NULL ); } void strings_mod_repatch(json_t *files_changed) { const char *key; const json_t *val; json_object_foreach(files_changed, key, val) { if(strstr(key, "/stringlocs.")) { stringlocs_reparse(); } } } void strings_mod_exit(void) { for(auto& i : strings_storage) { SAFE_FREE(i.second); } strings_storage.clear(); } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkExtractSelectedGraph.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*---------------------------------------------------------------------------- Copyright (c) Sandia Corporation See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details. ----------------------------------------------------------------------------*/ #include "vtkExtractSelectedGraph.h" #include "vtkCellData.h" #include "vtkCommand.h" #include "vtkConvertSelection.h" #include "vtkDataArray.h" #include "vtkEdgeListIterator.h" #include "vtkEventForwarderCommand.h" #include "vtkExtractSelection.h" #include "vtkGraph.h" #include "vtkIdTypeArray.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkMutableDirectedGraph.h" #include "vtkMutableUndirectedGraph.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPoints.h" #include "vtkSelection.h" #include "vtkSignedCharArray.h" #include "vtkSmartPointer.h" #include "vtkStringArray.h" #include "vtkTree.h" #include "vtkVertexListIterator.h" #include <vtksys/stl/map> vtkCxxRevisionMacro(vtkExtractSelectedGraph, "1.18"); vtkStandardNewMacro(vtkExtractSelectedGraph); //---------------------------------------------------------------------------- vtkExtractSelectedGraph::vtkExtractSelectedGraph() { this->SetNumberOfInputPorts(2); this->RemoveIsolatedVertices = true; } //---------------------------------------------------------------------------- vtkExtractSelectedGraph::~vtkExtractSelectedGraph() { } //---------------------------------------------------------------------------- int vtkExtractSelectedGraph::FillInputPortInformation(int port, vtkInformation* info) { if (port == 0) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkGraph"); return 1; } else if (port == 1) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkSelection"); return 1; } return 0; } //---------------------------------------------------------------------------- void vtkExtractSelectedGraph::SetSelectionConnection(vtkAlgorithmOutput* in) { this->SetInputConnection(1, in); } //---------------------------------------------------------------------------- int vtkExtractSelectedGraph::RequestDataObject( vtkInformation*, vtkInformationVector** inputVector , vtkInformationVector* outputVector) { vtkInformation* inInfo = inputVector[0]->GetInformationObject(0); if (!inInfo) { return 0; } vtkGraph *input = vtkGraph::SafeDownCast( inInfo->Get(vtkDataObject::DATA_OBJECT())); if (input) { vtkInformation* info = outputVector->GetInformationObject(0); vtkGraph *output = vtkGraph::SafeDownCast( info->Get(vtkDataObject::DATA_OBJECT())); // Output a vtkDirectedGraph if the input is a tree. if (!output || (vtkTree::SafeDownCast(input) && !vtkDirectedGraph::SafeDownCast(output)) || (!vtkTree::SafeDownCast(input) && !output->IsA(input->GetClassName()))) { if (vtkTree::SafeDownCast(input)) { output = vtkDirectedGraph::New(); } else { output = input->NewInstance(); } output->SetPipelineInformation(info); output->Delete(); this->GetOutputPortInformation(0)->Set( vtkDataObject::DATA_EXTENT_TYPE(), output->GetExtentType()); } return 1; } return 0; } //---------------------------------------------------------------------------- int vtkExtractSelectedGraph::RequestData( vtkInformation* vtkNotUsed(request), vtkInformationVector** inputVector, vtkInformationVector* outputVector) { vtkGraph* input = vtkGraph::GetData(inputVector[0]); vtkSelection* selection = vtkSelection::GetData(inputVector[1]); // If there is nothing in the list, there is nothing to select. vtkAbstractArray* list = selection->GetSelectionList(); if (!list || list->GetNumberOfTuples() == 0) { return 1; } int inverse = 0; if(selection->GetProperties()->Has(vtkSelection::INVERSE())) { inverse = selection->GetProperties()->Get(vtkSelection::INVERSE()); } // If it is a selection with multiple parts, find a point or cell // child selection, with preference to points. if (selection->GetContentType() == vtkSelection::SELECTIONS) { vtkSelection* child = 0; for (unsigned int i = 0; i < selection->GetNumberOfChildren(); i++) { vtkSelection* cur = selection->GetChild(i); if (cur->GetFieldType() == vtkSelection::POINT) { child = cur; break; } else if (cur->GetFieldType() == vtkSelection::CELL) { child = cur; } } selection = child; } // Convert the selection to an INDICES selection vtkSmartPointer<vtkSelection> indexSelection; indexSelection.TakeReference( vtkConvertSelection::ToIndexSelection(selection, input)); if (!indexSelection) { vtkErrorMacro("Selection conversion to INDICES failed."); indexSelection->Delete(); return 0; } vtkAbstractArray* arr = indexSelection->GetSelectionList(); if (arr == NULL) { vtkErrorMacro("Selection list not found."); return 0; } vtkIdTypeArray* selectArr = vtkIdTypeArray::SafeDownCast(arr); if (selectArr == NULL) { vtkErrorMacro("Selection list must be of type vtkIdTypeArray."); return 0; } vtkIdType selectSize = selectArr->GetNumberOfTuples(); bool directed = false; if (vtkDirectedGraph::SafeDownCast(input)) { directed = true; } vtkSmartPointer<vtkMutableDirectedGraph> dirBuilder = vtkSmartPointer<vtkMutableDirectedGraph>::New(); vtkSmartPointer<vtkMutableUndirectedGraph> undirBuilder = vtkSmartPointer<vtkMutableUndirectedGraph>::New(); if (selection->GetProperties()->Has(vtkSelection::FIELD_TYPE()) && selection->GetProperties()->Get(vtkSelection::FIELD_TYPE()) == vtkSelection::EDGE) { // // Edge selection // // Copy all vertices for (vtkIdType v = 0; v < input->GetNumberOfVertices(); ++v) { if (directed) { dirBuilder->AddVertex(); } else { undirBuilder->AddVertex(); } } vtkDataSetAttributes *inputEdgeData = input->GetEdgeData(); vtkDataSetAttributes *builderEdgeData = 0; if (directed) { builderEdgeData = dirBuilder->GetEdgeData(); } else { builderEdgeData = undirBuilder->GetEdgeData(); } builderEdgeData->CopyAllocate(inputEdgeData); // Copy unselected edges vtkSmartPointer<vtkEdgeListIterator> edges = vtkSmartPointer<vtkEdgeListIterator>::New(); input->GetEdges(edges); while (edges->HasNext()) { vtkEdgeType e = edges->Next(); if ((inverse && selectArr->LookupValue(e.Id) < 0) || (!inverse && selectArr->LookupValue(e.Id) >= 0)) { vtkEdgeType outputEdge; if (directed) { outputEdge = dirBuilder->AddEdge(e.Source, e.Target); } else { outputEdge = undirBuilder->AddEdge(e.Source, e.Target); } builderEdgeData->CopyData(inputEdgeData, e.Id, outputEdge.Id); } } // Remove isolated vertices if (this->RemoveIsolatedVertices) { // TODO: Implement this (requires rebuilding the graph without the // isolated vertices). vtkErrorMacro(<<"RemoveIsolatedVertices is not implemented."); } else { if (directed) { dirBuilder->GetVertexData()->PassData(input->GetVertexData()); dirBuilder->GetPoints()->ShallowCopy(input->GetPoints()); } else { undirBuilder->GetVertexData()->PassData(input->GetVertexData()); undirBuilder->GetPoints()->ShallowCopy(input->GetPoints()); } } } else { // // Vertex selection // double pt[3]; vtkPoints *inputPoints = input->GetPoints(); vtkSmartPointer<vtkPoints> outputPoints = vtkSmartPointer<vtkPoints>::New(); vtkDataSetAttributes *inputVertexData = input->GetVertexData(); vtkDataSetAttributes *builderVertexData = 0; if (directed) { builderVertexData = dirBuilder->GetVertexData(); } else { builderVertexData = undirBuilder->GetVertexData(); } builderVertexData->CopyAllocate(inputVertexData); vtksys_stl::map<vtkIdType, vtkIdType> idMap; // Copy unselected vertices if(inverse) { vtkSmartPointer<vtkVertexListIterator> vertices = vtkSmartPointer<vtkVertexListIterator>::New(); input->GetVertices(vertices); while (vertices->HasNext()) { vtkIdType i = vertices->Next(); if(selectArr->LookupValue(i) < 0) { vtkIdType outputVertex = -1; if (directed) { outputVertex = dirBuilder->AddVertex(); } else { outputVertex = undirBuilder->AddVertex(); } builderVertexData->CopyData(inputVertexData, i, outputVertex); idMap[i] = outputVertex; inputPoints->GetPoint(i, pt); outputPoints->InsertNextPoint(pt); } } } // Copy selected vertices else { for (vtkIdType i = 0; i < selectSize; i++) { vtkIdType inputVertex = selectArr->GetValue(i); if (inputVertex < input->GetNumberOfVertices()) { vtkIdType outputVertex = -1; if (directed) { outputVertex = dirBuilder->AddVertex(); } else { outputVertex = undirBuilder->AddVertex(); } builderVertexData->CopyData(inputVertexData, inputVertex, outputVertex); idMap[inputVertex] = outputVertex; inputPoints->GetPoint(inputVertex, pt); outputPoints->InsertNextPoint(pt); } } } if (directed) { dirBuilder->SetPoints(outputPoints); } else { undirBuilder->SetPoints(outputPoints); } // Copy edges whose source and target are selected. vtkDataSetAttributes *inputEdgeData = input->GetEdgeData(); vtkDataSetAttributes *builderEdgeData = 0; if (directed) { builderEdgeData = dirBuilder->GetEdgeData(); } else { builderEdgeData = undirBuilder->GetEdgeData(); } builderEdgeData->CopyAllocate(inputEdgeData); vtkSmartPointer<vtkEdgeListIterator> edges = vtkSmartPointer<vtkEdgeListIterator>::New(); input->GetEdges(edges); while (edges->HasNext()) { vtkEdgeType e = edges->Next(); if (idMap.count(e.Source) > 0 && idMap.count(e.Target) > 0) { vtkEdgeType outputEdge; if (directed) { outputEdge = dirBuilder->AddEdge(idMap[e.Source], idMap[e.Target]); } else { outputEdge = undirBuilder->AddEdge(idMap[e.Source], idMap[e.Target]); } builderEdgeData->CopyData(inputEdgeData, e.Id, outputEdge.Id); } } } // Pass constructed graph to output. vtkGraph* output = vtkGraph::GetData(outputVector); if (directed) { if (!output->CheckedShallowCopy(dirBuilder)) { vtkErrorMacro(<<"Invalid graph structure."); return 0; } } else { if (!output->CheckedShallowCopy(undirBuilder)) { vtkErrorMacro(<<"Invalid graph structure."); return 0; } } output->GetFieldData()->PassData(input->GetFieldData()); // Clean up output->Squeeze(); return 1; } //---------------------------------------------------------------------------- void vtkExtractSelectedGraph::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "RemoveIsolatedVertices: " << (this->RemoveIsolatedVertices ? "on" : "off") << endl; } <commit_msg>ENH: Implement RemoveIsolatedVertices feature.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkExtractSelectedGraph.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*---------------------------------------------------------------------------- Copyright (c) Sandia Corporation See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details. ----------------------------------------------------------------------------*/ #include "vtkExtractSelectedGraph.h" #include "vtkCellData.h" #include "vtkCommand.h" #include "vtkConvertSelection.h" #include "vtkDataArray.h" #include "vtkEdgeListIterator.h" #include "vtkEventForwarderCommand.h" #include "vtkExtractSelection.h" #include "vtkGraph.h" #include "vtkIdTypeArray.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkMutableDirectedGraph.h" #include "vtkMutableUndirectedGraph.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPoints.h" #include "vtkSelection.h" #include "vtkSignedCharArray.h" #include "vtkSmartPointer.h" #include "vtkStringArray.h" #include "vtkTree.h" #include "vtkVertexListIterator.h" #include <vtksys/stl/map> #include <vtkstd/vector> vtkCxxRevisionMacro(vtkExtractSelectedGraph, "1.19"); vtkStandardNewMacro(vtkExtractSelectedGraph); //---------------------------------------------------------------------------- vtkExtractSelectedGraph::vtkExtractSelectedGraph() { this->SetNumberOfInputPorts(2); this->RemoveIsolatedVertices = true; } //---------------------------------------------------------------------------- vtkExtractSelectedGraph::~vtkExtractSelectedGraph() { } //---------------------------------------------------------------------------- int vtkExtractSelectedGraph::FillInputPortInformation(int port, vtkInformation* info) { if (port == 0) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkGraph"); return 1; } else if (port == 1) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkSelection"); return 1; } return 0; } //---------------------------------------------------------------------------- void vtkExtractSelectedGraph::SetSelectionConnection(vtkAlgorithmOutput* in) { this->SetInputConnection(1, in); } //---------------------------------------------------------------------------- int vtkExtractSelectedGraph::RequestDataObject( vtkInformation*, vtkInformationVector** inputVector , vtkInformationVector* outputVector) { vtkInformation* inInfo = inputVector[0]->GetInformationObject(0); if (!inInfo) { return 0; } vtkGraph *input = vtkGraph::SafeDownCast( inInfo->Get(vtkDataObject::DATA_OBJECT())); if (input) { vtkInformation* info = outputVector->GetInformationObject(0); vtkGraph *output = vtkGraph::SafeDownCast( info->Get(vtkDataObject::DATA_OBJECT())); // Output a vtkDirectedGraph if the input is a tree. if (!output || (vtkTree::SafeDownCast(input) && !vtkDirectedGraph::SafeDownCast(output)) || (!vtkTree::SafeDownCast(input) && !output->IsA(input->GetClassName()))) { if (vtkTree::SafeDownCast(input)) { output = vtkDirectedGraph::New(); } else { output = input->NewInstance(); } output->SetPipelineInformation(info); output->Delete(); this->GetOutputPortInformation(0)->Set( vtkDataObject::DATA_EXTENT_TYPE(), output->GetExtentType()); } return 1; } return 0; } //---------------------------------------------------------------------------- int vtkExtractSelectedGraph::RequestData( vtkInformation* vtkNotUsed(request), vtkInformationVector** inputVector, vtkInformationVector* outputVector) { vtkGraph* input = vtkGraph::GetData(inputVector[0]); vtkSelection* selection = vtkSelection::GetData(inputVector[1]); // If there is nothing in the list, there is nothing to select. vtkAbstractArray* list = selection->GetSelectionList(); if (!list || list->GetNumberOfTuples() == 0) { return 1; } int inverse = 0; if(selection->GetProperties()->Has(vtkSelection::INVERSE())) { inverse = selection->GetProperties()->Get(vtkSelection::INVERSE()); } // If it is a selection with multiple parts, find a point or cell // child selection, with preference to points. if (selection->GetContentType() == vtkSelection::SELECTIONS) { vtkSelection* child = 0; for (unsigned int i = 0; i < selection->GetNumberOfChildren(); i++) { vtkSelection* cur = selection->GetChild(i); if (cur->GetFieldType() == vtkSelection::VERTEX) { child = cur; break; } else if (cur->GetFieldType() == vtkSelection::EDGE) { child = cur; } } selection = child; } // Convert the selection to an INDICES selection vtkSmartPointer<vtkSelection> indexSelection; indexSelection.TakeReference( vtkConvertSelection::ToIndexSelection(selection, input)); if (!indexSelection) { vtkErrorMacro("Selection conversion to INDICES failed."); indexSelection->Delete(); return 0; } vtkAbstractArray* arr = indexSelection->GetSelectionList(); if (arr == NULL) { vtkErrorMacro("Selection list not found."); return 0; } vtkIdTypeArray* selectArr = vtkIdTypeArray::SafeDownCast(arr); if (selectArr == NULL) { vtkErrorMacro("Selection list must be of type vtkIdTypeArray."); return 0; } vtkIdType selectSize = selectArr->GetNumberOfTuples(); bool directed = false; if (vtkDirectedGraph::SafeDownCast(input)) { directed = true; } vtkSmartPointer<vtkMutableDirectedGraph> dirBuilder = vtkSmartPointer<vtkMutableDirectedGraph>::New(); vtkSmartPointer<vtkMutableUndirectedGraph> undirBuilder = vtkSmartPointer<vtkMutableUndirectedGraph>::New(); if (selection->GetProperties()->Has(vtkSelection::FIELD_TYPE()) && selection->GetProperties()->Get(vtkSelection::FIELD_TYPE()) == vtkSelection::EDGE) { // // Edge selection // vtkDataSetAttributes *inputEdgeData = input->GetEdgeData(); vtkDataSetAttributes *builderEdgeData = 0; if (directed) { builderEdgeData = dirBuilder->GetEdgeData(); } else { builderEdgeData = undirBuilder->GetEdgeData(); } builderEdgeData->CopyAllocate(inputEdgeData); // Handle the case where we are not outputing isolated vertices separately: if(this->RemoveIsolatedVertices) { // Create and initialize vector that keeps track of which // vertices are connected by an edge (1) and which aren't (0). unsigned int idx; vtkstd::vector<int> connectedVertices; for(int j=0; j<input->GetNumberOfVertices(); ++j) { connectedVertices.push_back(0); } vtkSmartPointer<vtkEdgeListIterator> edgeIter = vtkSmartPointer<vtkEdgeListIterator>::New(); input->GetEdges(edgeIter); while (edgeIter->HasNext()) { vtkEdgeType e = edgeIter->Next(); if ((inverse && selectArr->LookupValue(e.Id) < 0) || (!inverse && selectArr->LookupValue(e.Id) >= 0)) { connectedVertices[e.Source] = 1; connectedVertices[e.Target] = 1; } } // Create a mapping between the input vertex id and the output vertex id. // Right now we rely on the fact that the input vertex ids are consecutive // integers from 0 to NUMBER_OF_VERTICES -1. So the index into the // vertexMap vector below actually represents the input vertex id. int numConnected = 0; vtkstd::vector<int> vertexMap; for(idx=0; idx<connectedVertices.size(); ++idx) { vertexMap.push_back(numConnected); if(connectedVertices[idx] == 1) { numConnected++; } } // Copy only the connected vertices for (int j = 0; j < numConnected; ++j) { if (directed) { dirBuilder->AddVertex(); } else { undirBuilder->AddVertex(); } } // Construct the output vertex data and vtkPoints using the new vertex ids vtkPoints* newPoints = vtkPoints::New(); newPoints->SetNumberOfPoints(numConnected); if (directed) { dirBuilder->GetVertexData()->SetNumberOfTuples(numConnected); for (idx = 0; idx<connectedVertices.size(); idx++) { if(connectedVertices[idx]==1) { dirBuilder->GetVertexData()->SetTuple(vertexMap[idx], idx, input->GetVertexData()); newPoints->SetPoint(vertexMap[idx], input->GetPoints()->GetPoint(idx)); } } dirBuilder->SetPoints(newPoints); } else { undirBuilder->GetVertexData()->SetNumberOfTuples(numConnected); for (idx = 0; idx<connectedVertices.size(); idx++) { if(connectedVertices[idx]==1) { undirBuilder->GetVertexData()->SetTuple(vertexMap[idx], idx, input->GetVertexData()); newPoints->SetPoint(vertexMap[idx], input->GetPoints()->GetPoint(idx)); } } undirBuilder->SetPoints(newPoints); } newPoints->Delete(); // Now actually copy the edges (only the selected ones) // using the new vertex ids. vtkSmartPointer<vtkEdgeListIterator> edges = vtkSmartPointer<vtkEdgeListIterator>::New(); input->GetEdges(edges); while (edges->HasNext()) { vtkEdgeType e = edges->Next(); if ((inverse && selectArr->LookupValue(e.Id) < 0) || (!inverse && selectArr->LookupValue(e.Id) >= 0)) { vtkEdgeType outputEdge; if (directed) { outputEdge = dirBuilder->AddEdge(vertexMap[e.Source], vertexMap[e.Target]); } else { outputEdge = undirBuilder->AddEdge(vertexMap[e.Source], vertexMap[e.Target]); } builderEdgeData->CopyData(inputEdgeData, e.Id, outputEdge.Id); } } } else // !this->RemoveIsolatedVertices { // Copy all vertices for (vtkIdType v = 0; v < input->GetNumberOfVertices(); ++v) { if (directed) { dirBuilder->AddVertex(); } else { undirBuilder->AddVertex(); } } // Copy unselected edges vtkSmartPointer<vtkEdgeListIterator> edges = vtkSmartPointer<vtkEdgeListIterator>::New(); input->GetEdges(edges); while (edges->HasNext()) { vtkEdgeType e = edges->Next(); if ((inverse && selectArr->LookupValue(e.Id) < 0) || (!inverse && selectArr->LookupValue(e.Id) >= 0)) { vtkEdgeType outputEdge; if (directed) { outputEdge = dirBuilder->AddEdge(e.Source, e.Target); } else { outputEdge = undirBuilder->AddEdge(e.Source, e.Target); } builderEdgeData->CopyData(inputEdgeData, e.Id, outputEdge.Id); } } if (directed) { dirBuilder->GetVertexData()->PassData(input->GetVertexData()); dirBuilder->GetPoints()->ShallowCopy(input->GetPoints()); } else { undirBuilder->GetVertexData()->PassData(input->GetVertexData()); undirBuilder->GetPoints()->ShallowCopy(input->GetPoints()); } } } else { // // Vertex selection // double pt[3]; vtkPoints *inputPoints = input->GetPoints(); vtkSmartPointer<vtkPoints> outputPoints = vtkSmartPointer<vtkPoints>::New(); vtkDataSetAttributes *inputVertexData = input->GetVertexData(); vtkDataSetAttributes *builderVertexData = 0; if (directed) { builderVertexData = dirBuilder->GetVertexData(); } else { builderVertexData = undirBuilder->GetVertexData(); } builderVertexData->CopyAllocate(inputVertexData); vtksys_stl::map<vtkIdType, vtkIdType> idMap; // Copy unselected vertices if(inverse) { vtkSmartPointer<vtkVertexListIterator> vertices = vtkSmartPointer<vtkVertexListIterator>::New(); input->GetVertices(vertices); while (vertices->HasNext()) { vtkIdType i = vertices->Next(); if(selectArr->LookupValue(i) < 0) { vtkIdType outputVertex = -1; if (directed) { outputVertex = dirBuilder->AddVertex(); } else { outputVertex = undirBuilder->AddVertex(); } builderVertexData->CopyData(inputVertexData, i, outputVertex); idMap[i] = outputVertex; inputPoints->GetPoint(i, pt); outputPoints->InsertNextPoint(pt); } } } // Copy selected vertices else { for (vtkIdType i = 0; i < selectSize; i++) { vtkIdType inputVertex = selectArr->GetValue(i); if (inputVertex < input->GetNumberOfVertices()) { vtkIdType outputVertex = -1; if (directed) { outputVertex = dirBuilder->AddVertex(); } else { outputVertex = undirBuilder->AddVertex(); } builderVertexData->CopyData(inputVertexData, inputVertex, outputVertex); idMap[inputVertex] = outputVertex; inputPoints->GetPoint(inputVertex, pt); outputPoints->InsertNextPoint(pt); } } } if (directed) { dirBuilder->SetPoints(outputPoints); } else { undirBuilder->SetPoints(outputPoints); } // Copy edges whose source and target are selected. vtkDataSetAttributes *inputEdgeData = input->GetEdgeData(); vtkDataSetAttributes *builderEdgeData = 0; if (directed) { builderEdgeData = dirBuilder->GetEdgeData(); } else { builderEdgeData = undirBuilder->GetEdgeData(); } builderEdgeData->CopyAllocate(inputEdgeData); vtkSmartPointer<vtkEdgeListIterator> edges = vtkSmartPointer<vtkEdgeListIterator>::New(); input->GetEdges(edges); while (edges->HasNext()) { vtkEdgeType e = edges->Next(); if (idMap.count(e.Source) > 0 && idMap.count(e.Target) > 0) { vtkEdgeType outputEdge; if (directed) { outputEdge = dirBuilder->AddEdge(idMap[e.Source], idMap[e.Target]); } else { outputEdge = undirBuilder->AddEdge(idMap[e.Source], idMap[e.Target]); } builderEdgeData->CopyData(inputEdgeData, e.Id, outputEdge.Id); } } } // Pass constructed graph to output. vtkGraph* output = vtkGraph::GetData(outputVector); if (directed) { if (!output->CheckedShallowCopy(dirBuilder)) { vtkErrorMacro(<<"Invalid graph structure."); return 0; } } else { if (!output->CheckedShallowCopy(undirBuilder)) { vtkErrorMacro(<<"Invalid graph structure."); return 0; } } output->GetFieldData()->PassData(input->GetFieldData()); // Clean up output->Squeeze(); return 1; } //---------------------------------------------------------------------------- void vtkExtractSelectedGraph::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "RemoveIsolatedVertices: " << (this->RemoveIsolatedVertices ? "on" : "off") << endl; } <|endoftext|>
<commit_before>#include "predicator.h" #include "planning_tool.h" #include <boost/bind/bind.hpp> namespace predicator_planning { Planner::Planner(PredicateContext *_context, unsigned int _max_iter, unsigned int _children, double _step) : context(_context), max_iter(_max_iter), children(_children), step(_step) { ros::NodeHandle nh; planServer = nh.advertiseService < predicator_planning::PredicatePlan::Request, predicator_planning::PredicatePlan::Response> ("/predicator/plan", boost::bind(&Planner::plan, *this, _1, _2)); } bool Planner::plan(predicator_planning::PredicatePlan::Request &req, predicator_planning::PredicatePlan::Response &res) { // get starting states // these are the states as recorded in the context // they will be updated as we go on if this takes a while -- might be bad std::vector<RobotState *> starting_states = context->states; // find the index of the current robot state unsigned int idx = 0; for (RobotModelPtr &ptr: context->robots) { std::cout << ptr->getName() << std::endl; if (ptr->getName().compare(req.robot)) { break; } ++idx; } // loop over for (unsigned int iter = 0; iter < max_iter; ++iter) { // either generate a starting position at random or... // step in a direction from a "good" position (as determined by high heuristics) for (unsigned int i = 0; i < children; ++i) { } } return true; } } <commit_msg>cleaned up constructor<commit_after>#include "predicator.h" #include "planning_tool.h" #include <boost/bind/bind.hpp> namespace predicator_planning { Planner::Planner(PredicateContext *_context, unsigned int _max_iter, unsigned int _children, double _step) : context(_context), max_iter(_max_iter), children(_children), step(_step) { ros::NodeHandle nh; planServer = nh.advertiseService("predicator/plan", &Planner::plan, this); } bool Planner::plan(predicator_planning::PredicatePlan::Request &req, predicator_planning::PredicatePlan::Response &res) { // get starting states // these are the states as recorded in the context // they will be updated as we go on if this takes a while -- might be bad std::vector<RobotState *> starting_states = context->states; // find the index of the current robot state unsigned int idx = 0; for (RobotModelPtr &ptr: context->robots) { std::cout << ptr->getName() << std::endl; if (ptr->getName().compare(req.robot)) { break; } ++idx; } // loop over for (unsigned int iter = 0; iter < max_iter; ++iter) { // either generate a starting position at random or... // step in a direction from a "good" position (as determined by high heuristics) for (unsigned int i = 0; i < children; ++i) { } } return true; } } <|endoftext|>
<commit_before>// demo.cpp : ̨Ӧóڵ㡣 // #include <stdio.h> #include <assert.h> #include <map> #include <vector> #include "CodeAddress.h" #include "ThreadPool.h" #ifdef WIN32 #ifdef _DEBUG #pragma comment(lib, "../lib/ThreadLib_d.lib") #else #pragma comment(lib, "../lib/ThreadLib.lib") #endif #else #include <unistd.h> #endif class CTest { public: CTest() :m_Thread(NULL) ,m_bStop(false) ,m_nThreadParam(5) ,m_nThreadPoolParam(10) { } ~CTest() { if (m_Thread != NULL) { delete m_Thread; m_Thread = NULL; } } void *ThreadFunc(void* param) { int *pNum = (int*)param; while (!m_bStop) { printf("\n\tthe param is a number : \"%i\"\n", *pNum); #ifdef WIN32 Sleep(500); #else usleep(500*1000); #endif } return NULL; } void *ThreadPoolFunc(void* pParam) { int *pNum = (int*)pParam; while (!m_bStop) { printf("\n\tThreadPoolFunc Number is : \"%i\"\n", *pNum); #ifdef WIN32 Sleep(500); #else usleep(500*1000); #endif } return NULL; } void StartTest() { if (m_Thread == NULL) { int *param = &m_nThreadParam; m_Thread = new ThreadLib::Thread(); m_Thread->Run((DWORD)GET_MEMBER_CALLBACK(CTest,ThreadFunc), (DWORD)this, (DWORD)param); } int *pool = &m_nThreadPoolParam; for (int i = 0; i < 2; i++) m_ThreadPool.PushTask((DWORD)GET_MEMBER_CALLBACK(CTest,ThreadPoolFunc), (DWORD)this, (DWORD)pool); m_ThreadPool.Start(2); } void StopTest() { m_bStop = true; m_ThreadPool.Stop(); } ThreadLib::Thread *m_Thread; ThreadLib::ThreadPool m_ThreadPool; bool m_bStop; int m_nThreadParam; int m_nThreadPoolParam; }; int main(int argc, char* argv[]) { CTest a; a.StartTest(); getchar(); a.StopTest(); return 0; } <commit_msg>更新demo<commit_after>// demo.cpp : ̨Ӧóڵ㡣 // #include <stdio.h> #include <assert.h> #include <map> #include <vector> #ifdef WIN32 #include <Windows.h> #ifdef _DEBUG #pragma comment(lib, "../lib/ThreadLib_d.lib") #else #pragma comment(lib, "../lib/ThreadLib.lib") #endif #else #include <unistd.h> #endif #include "CodeAddress.h" #include "ThreadPool.h" class CTest { public: CTest() :m_Thread(NULL) ,m_bStop(false) ,m_nThreadParam(5) ,m_nThreadPoolParam(10) { } ~CTest() { if (m_Thread != NULL) { delete m_Thread; m_Thread = NULL; } } void *ThreadFunc(void* param) { int *pNum = (int*)param; while (true) { bool bRet = m_Event.WaitEvent(1000); if (bRet) { printf("\n\t thread func break\n"); break; }else{ printf("\n\tthe param is a number : \"%i\"\n", *pNum); } } return NULL; } void *ThreadPoolFunc(void* pParam) { int *pNum = (int*)pParam; { printf("\n\tThreadPoolFunc Number is : \"%i\"\n", *pNum); } return NULL; } void StartTest() { if (m_Thread == NULL) { int *param = &m_nThreadParam; m_Thread = new ThreadLib::Thread(); m_Thread->Run((DWORD)GET_MEMBER_CALLBACK(CTest,ThreadFunc), (DWORD)this, (DWORD)param); } int *pool = &m_nThreadPoolParam; for (int i = 0; i < 2; i++) m_ThreadPool.PushTask((DWORD)GET_MEMBER_CALLBACK(CTest,ThreadPoolFunc), (DWORD)this, (DWORD)pool); m_ThreadPool.Start(2); } void StopTest() { m_bStop = true; m_Event.Set(); m_ThreadPool.Stop(); } ThreadLib::Thread *m_Thread; ThreadLib::ThreadPool m_ThreadPool; ThreadLib::Event m_Event; bool m_bStop; int m_nThreadParam; int m_nThreadPoolParam; }; int main(int argc, char* argv[]) { CTest a; a.StartTest(); getchar(); a.StopTest(); getchar(); return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2016-2017 dresden elektronik ingenieurtechnik gmbh. * All rights reserved. * * The software in this package is published under the terms of the BSD * style license a copy of which has been included with this distribution in * the LICENSE.txt file. * */ #include <QFile> #include <QHostInfo> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QNetworkProxy> #include <QSysInfo> #include "de_web_plugin_private.h" #include "json.h" #ifdef Q_OS_LINUX #include <unistd.h> #endif /*! Inits the internet discovery manager. */ void DeRestPluginPrivate::initInternetDicovery() { Q_ASSERT(inetDiscoveryManager == 0); inetDiscoveryManager = new QNetworkAccessManager; connect(inetDiscoveryManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(internetDiscoveryFinishedRequest(QNetworkReply*))); DBG_Assert(gwAnnounceInterval >= 0); if (gwAnnounceInterval < 0) { gwAnnounceInterval = 15; } gwAnnounceVital = 0; inetDiscoveryTimer = new QTimer(this); inetDiscoveryTimer->setSingleShot(false); { QList<QNetworkProxy> proxies = QNetworkProxyFactory::systemProxyForQuery(QNetworkProxyQuery(gwAnnounceUrl)); if (!proxies.isEmpty()) { const QNetworkProxy &proxy = proxies.first(); if (proxy.type() == QNetworkProxy::HttpProxy || proxy.type() == QNetworkProxy::HttpCachingProxy) { gwProxyPort = proxy.port(); gwProxyAddress = proxy.hostName(); inetDiscoveryManager->setProxy(proxy); QHostInfo::lookupHost(proxy.hostName(), this, SLOT(inetProxyHostLookupDone(QHostInfo))); } } } connect(inetDiscoveryTimer, SIGNAL(timeout()), this, SLOT(internetDiscoveryTimerFired())); setInternetDiscoveryInterval(gwAnnounceInterval); // force first run if (gwAnnounceInterval > 0) { QTimer::singleShot(5000, this, SLOT(internetDiscoveryTimerFired())); } #ifdef Q_OS_LINUX // check if we run from shell script QFile pproc(QString("/proc/%1/cmdline").arg(getppid())); if (pproc.exists() && pproc.open(QIODevice::ReadOnly)) { QByteArray name = pproc.readAll(); if (name.endsWith(".sh")) { DBG_Printf(DBG_INFO, "runs in shell script %s\n", qPrintable(name)); gwRunFromShellScript = true; } else { gwRunFromShellScript = false; DBG_Printf(DBG_INFO, "parent process %s\n", qPrintable(name)); } } #else gwRunFromShellScript = false; #endif { QFile f("/etc/os-release"); if (f.exists() && f.open(QFile::ReadOnly)) { QTextStream stream(&f); while (!stream.atEnd()) { QString line = stream.readLine(200); QStringList lineLs = line.split(QChar('=')); if (lineLs.size() != 2) { continue; } if (lineLs[0] == QLatin1String("PRETTY_NAME")) { osPrettyName = lineLs[1]; osPrettyName.remove(QChar('"')); } } } } #ifdef ARCH_ARM { // get raspberry pi revision QFile f("/proc/cpuinfo"); if (f.exists() && f.open(QFile::ReadOnly)) { QByteArray arr = f.readAll(); QTextStream stream(arr); while (!stream.atEnd()) { QString line = stream.readLine(200); QStringList lineLs = line.split(QChar(':')); if (lineLs.size() != 2) { continue; } if (lineLs[0].startsWith(QLatin1String("Revision"))) { piRevision = lineLs[1].trimmed(); break; } } } } #endif // ARCH_ARM if (osPrettyName.isEmpty()) { #ifdef Q_OS_WIN switch (QSysInfo::WindowsVersion) { case QSysInfo::WV_XP: osPrettyName = QLatin1String("WinXP"); break; case QSysInfo::WV_WINDOWS7: osPrettyName = QLatin1String("Win7"); break; case QSysInfo::WV_WINDOWS8: osPrettyName = QLatin1String("Win8"); break; case QSysInfo::WV_WINDOWS8_1: osPrettyName = QLatin1String("Win8.1"); break; case QSysInfo::WV_WINDOWS10: osPrettyName = QLatin1String("Win10"); break; default: osPrettyName = QLatin1String("Win"); break; } #endif #ifdef Q_OS_OSX osPrettyName = "Mac"; #endif #ifdef Q_OS_LINUX osPrettyName = "Linux"; #endif } } /*! Sets the announce interval for internet discovery. \param minutes a value between 0..180 min \return true on success */ bool DeRestPluginPrivate::setInternetDiscoveryInterval(int minutes) { if ((minutes < 0) || (minutes > 180)) { DBG_Printf(DBG_INFO, "discovery ignored invalid announce interval (%d minutes)\n", minutes); return false; } inetDiscoveryTimer->stop(); gwAnnounceInterval = minutes; if (gwAnnounceInterval > 0) { int msec = 1000 * 60 * gwAnnounceInterval; inetDiscoveryTimer->start(msec); DBG_Printf(DBG_INFO, "discovery updated announce interval to %d minutes\n", minutes); } return true; } /*! Handle announce trigger timer. */ void DeRestPluginPrivate::internetDiscoveryTimerFired() { if (gwAnnounceInterval > 0) { QString str = QString("{ \"name\": \"%1\", \"mac\": \"%2\", \"internal_ip\":\"%3\", \"internal_port\":%4, \"interval\":%5, \"swversion\":\"%6\", \"fwversion\":\"%7\", \"nodecount\":%8, \"uptime\":%9, \"updatechannel\":\"%10\"") .arg(gwName) .arg(gwBridgeId) .arg(gwConfig["ipaddress"].toString()) .arg(gwConfig["port"].toDouble()) .arg(gwAnnounceInterval) .arg(gwConfig["swversion"].toString()) .arg(gwConfig["fwversion"].toString()) .arg(nodes.size()) .arg(getUptime()) .arg(gwUpdateChannel); str.append(QString(",\"os\": \"%1\"").arg(osPrettyName)); if (!piRevision.isEmpty()) { str.append(QString(",\"pirev\": \"%1\"").arg(piRevision)); } str.append(QChar('}')); QByteArray data(qPrintable(str)); inetDiscoveryManager->put(QNetworkRequest(QUrl(gwAnnounceUrl)), data); } } /*! Callback for finished HTTP requests. \param reply the reply to a HTTP request */ void DeRestPluginPrivate::internetDiscoveryFinishedRequest(QNetworkReply *reply) { DBG_Assert(reply != 0); if (!reply) { return; } if (reply->error() == QNetworkReply::NoError) { DBG_Printf(DBG_INFO, "Announced to internet\n"); #ifdef ARCH_ARM // currently this is only supported for the RaspBee Gateway internetDiscoveryExtractVersionInfo(reply); #endif // ARCH_ARM } else { DBG_Printf(DBG_INFO, "discovery network reply error: %s\n", qPrintable(reply->errorString())); } reply->deleteLater(); } /*! Extracts the update channels version info about the deCONZ/WebApp. \param reply which holds the version info in JSON format */ void DeRestPluginPrivate::internetDiscoveryExtractVersionInfo(QNetworkReply *reply) { bool ok; QByteArray content = reply->readAll(); QVariant var = Json::parse(content, ok); QVariantMap map = var.toMap(); if (!ok || map.isEmpty()) { DBG_Printf(DBG_ERROR, "discovery couldn't extract version info from reply\n"); } if (map.contains("versions") && (map["versions"].type() == QVariant::Map)) { QString version; QVariantMap versions = map["versions"].toMap(); if (versions.contains(gwUpdateChannel) && (versions[gwUpdateChannel].type() == QVariant::String)) { version = versions[gwUpdateChannel].toString(); if (!version.isEmpty()) { if (gwUpdateVersion != version) { DBG_Printf(DBG_INFO, "discovery found version %s for update channel %s\n", qPrintable(version), qPrintable(gwUpdateChannel)); gwUpdateVersion = version; gwSwUpdateState = swUpdateState.readyToInstall; updateEtag(gwConfigEtag); } } else { DBG_Printf(DBG_ERROR, "discovery reply doesn't contain valid version info for update channel %s\n", qPrintable(gwUpdateChannel)); } } else { DBG_Printf(DBG_ERROR, "discovery reply doesn't contain version info for update channel %s\n", qPrintable(gwUpdateChannel)); } } else { DBG_Printf(DBG_ERROR, "discovery reply doesn't contain valid version info\n"); } } /*! Finished Lookup of http proxy IP address. \param host holds the proxy host info */ void DeRestPluginPrivate::inetProxyHostLookupDone(const QHostInfo &host) { if (host.error() != QHostInfo::NoError) { DBG_Printf(DBG_ERROR, "Proxy host lookup failed: %s\n", qPrintable(host.errorString())); return; } foreach (const QHostAddress &address, host.addresses()) { QString addr = address.toString(); if (address.protocol() == QAbstractSocket::IPv4Protocol && !addr.isEmpty() && gwProxyAddress != address.toString()) { DBG_Printf(DBG_INFO, "Found proxy IP address: %s\n", qPrintable(address.toString())); gwProxyAddress = address.toString(); updateEtag(gwConfigEtag); return; } } } <commit_msg>Proxy (2)<commit_after>/* * Copyright (c) 2016-2017 dresden elektronik ingenieurtechnik gmbh. * All rights reserved. * * The software in this package is published under the terms of the BSD * style license a copy of which has been included with this distribution in * the LICENSE.txt file. * */ #include <QFile> #include <QHostInfo> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QNetworkProxy> #include <QSysInfo> #include "de_web_plugin_private.h" #include "json.h" #ifdef Q_OS_LINUX #include <unistd.h> #endif /*! Inits the internet discovery manager. */ void DeRestPluginPrivate::initInternetDicovery() { Q_ASSERT(inetDiscoveryManager == 0); inetDiscoveryManager = new QNetworkAccessManager; connect(inetDiscoveryManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(internetDiscoveryFinishedRequest(QNetworkReply*))); DBG_Assert(gwAnnounceInterval >= 0); if (gwAnnounceInterval < 0) { gwAnnounceInterval = 15; } gwAnnounceVital = 0; inetDiscoveryTimer = new QTimer(this); inetDiscoveryTimer->setSingleShot(false); { QList<QNetworkProxy> proxies = QNetworkProxyFactory::systemProxyForQuery(QNetworkProxyQuery(gwAnnounceUrl)); if (!proxies.isEmpty()) { const QNetworkProxy &proxy = proxies.first(); if (proxy.type() == QNetworkProxy::HttpProxy || proxy.type() == QNetworkProxy::HttpCachingProxy) { gwProxyPort = proxy.port(); gwProxyAddress = proxy.hostName(); inetDiscoveryManager->setProxy(proxy); QHostInfo::lookupHost(proxy.hostName(), this, SLOT(inetProxyHostLookupDone(QHostInfo))); } } } connect(inetDiscoveryTimer, SIGNAL(timeout()), this, SLOT(internetDiscoveryTimerFired())); setInternetDiscoveryInterval(gwAnnounceInterval); // force first run if (gwAnnounceInterval > 0) { QTimer::singleShot(5000, this, SLOT(internetDiscoveryTimerFired())); } #ifdef Q_OS_LINUX // check if we run from shell script QFile pproc(QString("/proc/%1/cmdline").arg(getppid())); if (pproc.exists() && pproc.open(QIODevice::ReadOnly)) { QByteArray name = pproc.readAll(); if (name.endsWith(".sh")) { DBG_Printf(DBG_INFO, "runs in shell script %s\n", qPrintable(name)); gwRunFromShellScript = true; } else { gwRunFromShellScript = false; DBG_Printf(DBG_INFO, "parent process %s\n", qPrintable(name)); } } #else gwRunFromShellScript = false; #endif { QFile f("/etc/os-release"); if (f.exists() && f.open(QFile::ReadOnly)) { QTextStream stream(&f); while (!stream.atEnd()) { QString line = stream.readLine(200); QStringList lineLs = line.split(QChar('=')); if (lineLs.size() != 2) { continue; } if (lineLs[0] == QLatin1String("PRETTY_NAME")) { osPrettyName = lineLs[1]; osPrettyName.remove(QChar('"')); } } } } #ifdef ARCH_ARM { // get raspberry pi revision QFile f("/proc/cpuinfo"); if (f.exists() && f.open(QFile::ReadOnly)) { QByteArray arr = f.readAll(); QTextStream stream(arr); while (!stream.atEnd()) { QString line = stream.readLine(200); QStringList lineLs = line.split(QChar(':')); if (lineLs.size() != 2) { continue; } if (lineLs[0].startsWith(QLatin1String("Revision"))) { piRevision = lineLs[1].trimmed(); break; } } } } #endif // ARCH_ARM if (osPrettyName.isEmpty()) { #ifdef Q_OS_WIN switch (QSysInfo::WindowsVersion) { case QSysInfo::WV_XP: osPrettyName = QLatin1String("WinXP"); break; case QSysInfo::WV_WINDOWS7: osPrettyName = QLatin1String("Win7"); break; case QSysInfo::WV_WINDOWS8: osPrettyName = QLatin1String("Win8"); break; case QSysInfo::WV_WINDOWS8_1: osPrettyName = QLatin1String("Win8.1"); break; case QSysInfo::WV_WINDOWS10: osPrettyName = QLatin1String("Win10"); break; default: osPrettyName = QLatin1String("Win"); break; } #endif #ifdef Q_OS_OSX osPrettyName = "Mac"; #endif #ifdef Q_OS_LINUX osPrettyName = "Linux"; #endif } } /*! Sets the announce interval for internet discovery. \param minutes a value between 0..180 min \return true on success */ bool DeRestPluginPrivate::setInternetDiscoveryInterval(int minutes) { if ((minutes < 0) || (minutes > 180)) { DBG_Printf(DBG_INFO, "discovery ignored invalid announce interval (%d minutes)\n", minutes); return false; } inetDiscoveryTimer->stop(); gwAnnounceInterval = minutes; if (gwAnnounceInterval > 0) { int msec = 1000 * 60 * gwAnnounceInterval; inetDiscoveryTimer->start(msec); DBG_Printf(DBG_INFO, "discovery updated announce interval to %d minutes\n", minutes); } return true; } /*! Handle announce trigger timer. */ void DeRestPluginPrivate::internetDiscoveryTimerFired() { if (gwAnnounceInterval > 0) { QString str = QString("{ \"name\": \"%1\", \"mac\": \"%2\", \"internal_ip\":\"%3\", \"internal_port\":%4, \"interval\":%5, \"swversion\":\"%6\", \"fwversion\":\"%7\", \"nodecount\":%8, \"uptime\":%9, \"updatechannel\":\"%10\"") .arg(gwName) .arg(gwBridgeId) .arg(gwConfig["ipaddress"].toString()) .arg(gwConfig["port"].toDouble()) .arg(gwAnnounceInterval) .arg(gwConfig["swversion"].toString()) .arg(gwConfig["fwversion"].toString()) .arg(nodes.size()) .arg(getUptime()) .arg(gwUpdateChannel); str.append(QString(",\"os\": \"%1\"").arg(osPrettyName)); if (!piRevision.isEmpty()) { str.append(QString(",\"pirev\": \"%1\"").arg(piRevision)); } str.append(QChar('}')); QByteArray data(qPrintable(str)); inetDiscoveryManager->put(QNetworkRequest(QUrl(gwAnnounceUrl)), data); } } /*! Callback for finished HTTP requests. \param reply the reply to a HTTP request */ void DeRestPluginPrivate::internetDiscoveryFinishedRequest(QNetworkReply *reply) { DBG_Assert(reply != 0); if (!reply) { return; } if (reply->error() == QNetworkReply::NoError) { if (gwAnnounceVital < 0) { gwAnnounceVital = 0; } gwAnnounceVital++; DBG_Printf(DBG_INFO, "Announced to internet\n"); #ifdef ARCH_ARM // currently this is only supported for the RaspBee Gateway internetDiscoveryExtractVersionInfo(reply); #endif // ARCH_ARM } else { DBG_Printf(DBG_INFO, "discovery network reply error: %s\n", qPrintable(reply->errorString())); if (gwAnnounceVital > 0) { gwAnnounceVital = 0; } gwAnnounceVital--; } reply->deleteLater(); } /*! Extracts the update channels version info about the deCONZ/WebApp. \param reply which holds the version info in JSON format */ void DeRestPluginPrivate::internetDiscoveryExtractVersionInfo(QNetworkReply *reply) { bool ok; QByteArray content = reply->readAll(); QVariant var = Json::parse(content, ok); QVariantMap map = var.toMap(); if (!ok || map.isEmpty()) { DBG_Printf(DBG_ERROR, "discovery couldn't extract version info from reply\n"); } if (map.contains("versions") && (map["versions"].type() == QVariant::Map)) { QString version; QVariantMap versions = map["versions"].toMap(); if (versions.contains(gwUpdateChannel) && (versions[gwUpdateChannel].type() == QVariant::String)) { version = versions[gwUpdateChannel].toString(); if (!version.isEmpty()) { if (gwUpdateVersion != version) { DBG_Printf(DBG_INFO, "discovery found version %s for update channel %s\n", qPrintable(version), qPrintable(gwUpdateChannel)); gwUpdateVersion = version; gwSwUpdateState = swUpdateState.readyToInstall; updateEtag(gwConfigEtag); } } else { DBG_Printf(DBG_ERROR, "discovery reply doesn't contain valid version info for update channel %s\n", qPrintable(gwUpdateChannel)); } } else { DBG_Printf(DBG_ERROR, "discovery reply doesn't contain version info for update channel %s\n", qPrintable(gwUpdateChannel)); } } else { DBG_Printf(DBG_ERROR, "discovery reply doesn't contain valid version info\n"); } } /*! Finished Lookup of http proxy IP address. \param host holds the proxy host info */ void DeRestPluginPrivate::inetProxyHostLookupDone(const QHostInfo &host) { if (host.error() != QHostInfo::NoError) { DBG_Printf(DBG_ERROR, "Proxy host lookup failed: %s\n", qPrintable(host.errorString())); return; } foreach (const QHostAddress &address, host.addresses()) { QString addr = address.toString(); if (address.protocol() == QAbstractSocket::IPv4Protocol && !addr.isEmpty() && gwProxyAddress != address.toString()) { DBG_Printf(DBG_INFO, "Found proxy IP address: %s\n", qPrintable(address.toString())); gwProxyAddress = address.toString(); updateEtag(gwConfigEtag); return; } } } /*! Check if a received via field contains a usable proxy. \param via holds the proxy host info received by http request header */ void DeRestPluginPrivate::inetProxyCheckHttpVia(const QString &via) { if (via.isEmpty()) { return; } if (gwProxyPort != 0) { return; // already configured? } // https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.45 // 1.1 proxy.some-domain.com:3128 (squid/2.7.STABLE9) DBG_Printf(DBG_INFO, "Test proxy: \t%s\n", qPrintable(via)); for (QString &entry : via.split(',')) // there might be multiple proxied in the chain { QStringList ls = entry.split(' '); if (ls.size() < 2) { continue; } if (!ls[0].contains(QLatin1String("1.1"))) { continue; } QStringList recvBy = ls[1].split(':'); if (ls.size() < 1) // at least host must be specified { continue; } quint16 port = 8080; if (recvBy.size() == 2) // optional { port = recvBy[1].toUInt(); } DBG_Printf(DBG_INFO, "\t --> %s:%u\n", qPrintable(recvBy[0]), port); if (gwProxyPort != 0) { continue; } if (gwAnnounceVital >= 0) { continue; } gwProxyAddress = recvBy[0]; gwProxyPort = port; QNetworkProxy proxy(QNetworkProxy::HttpProxy, gwProxyAddress, gwProxyPort); inetDiscoveryManager->setProxy(proxy); QHostInfo::lookupHost(proxy.hostName(), this, SLOT(inetProxyHostLookupDone(QHostInfo))); updateEtag(gwConfigEtag); if (gwAnnounceInterval > 0) { QTimer::singleShot(5000, this, SLOT(internetDiscoveryTimerFired())); } } } <|endoftext|>
<commit_before>// Copyright 2017 Sebastien Ronsse #include "ImGuiHUD.h" #include "MyImGuiHUD.h" const struct FKey *KeyMap[] = { &EKeys::Tab, &EKeys::Left, &EKeys::Right, &EKeys::Up, &EKeys::Down, &EKeys::PageUp, &EKeys::PageDown, &EKeys::Home, &EKeys::End, &EKeys::Delete, &EKeys::BackSpace, &EKeys::Enter, &EKeys::Escape, &EKeys::A, &EKeys::C, &EKeys::V, &EKeys::X, &EKeys::Y, &EKeys::Z, }; AMyImGuiHUD::AMyImGuiHUD() : Super(), FontTexture(NULL) { } void AMyImGuiHUD::PostInitializeComponents() { Super::PostInitializeComponents(); // Setup ImGui binding ImGui_ImplUE_Init(); } void AMyImGuiHUD::BeginDestroy() { Super::BeginDestroy(); // Cleanup ImGui_ImplUE_Shutdown(); } void AMyImGuiHUD::DrawHUD() { // Process events ImGui_ImplUE_ProcessEvent(); // Prepare new frame ImGui_ImplUE_NewFrame(); // Rendering ImGui::Render(); } bool AMyImGuiHUD::ImGui_ImplUE_Init() { ImGuiIO &io = ImGui::GetIO(); // Keyboard mapping for (int i = 0; i < ImGuiKey_COUNT; i++) io.KeyMap[i] = i; // Fill callbacks io.RenderDrawListsFn = ImGui_ImplUE_RenderDrawLists; io.SetClipboardTextFn = ImGui_ImplUE_SetClipboardText; io.GetClipboardTextFn = ImGui_ImplUE_GetClipboardText; io.UserData = this; return true; } void AMyImGuiHUD::ImGui_ImplUE_Shutdown() { ImGui_ImplUE_InvalidateDeviceObjects(); ImGui::Shutdown(); } bool AMyImGuiHUD::ImGui_ImplUE_CreateDeviceObjects() { // Build texture atlas ImGuiIO &io = ImGui::GetIO(); unsigned char *pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Upload texture to graphics system FontTexture = UTexture2D::CreateTransient(width, height, PF_R8G8B8A8); FTexture2DMipMap &mip = FontTexture->PlatformData->Mips[0]; void *data = mip.BulkData.Lock(LOCK_READ_WRITE); FMemory::Memcpy(data, pixels, width * height * 4); mip.BulkData.Unlock(); FontTexture->UpdateResource(); // Store our identifier io.Fonts->TexID = (void *)FontTexture; return true; } void AMyImGuiHUD::ImGui_ImplUE_InvalidateDeviceObjects() { FontTexture = NULL; } void AMyImGuiHUD::ImGui_ImplUE_ProcessEvent() { } void AMyImGuiHUD::ImGui_ImplUE_NewFrame() { } void AMyImGuiHUD::ImGui_ImplUE_RenderDrawLists(ImDrawData *draw_data) { } const char *AMyImGuiHUD::ImGui_ImplUE_GetClipboardText() { return NULL; } void AMyImGuiHUD::ImGui_ImplUE_SetClipboardText(const char *text) { } <commit_msg>Filled ImGui frame preparation function<commit_after>// Copyright 2017 Sebastien Ronsse #include "ImGuiHUD.h" #include "MyImGuiHUD.h" const struct FKey *KeyMap[] = { &EKeys::Tab, &EKeys::Left, &EKeys::Right, &EKeys::Up, &EKeys::Down, &EKeys::PageUp, &EKeys::PageDown, &EKeys::Home, &EKeys::End, &EKeys::Delete, &EKeys::BackSpace, &EKeys::Enter, &EKeys::Escape, &EKeys::A, &EKeys::C, &EKeys::V, &EKeys::X, &EKeys::Y, &EKeys::Z, }; AMyImGuiHUD::AMyImGuiHUD() : Super(), FontTexture(NULL) { } void AMyImGuiHUD::PostInitializeComponents() { Super::PostInitializeComponents(); // Setup ImGui binding ImGui_ImplUE_Init(); } void AMyImGuiHUD::BeginDestroy() { Super::BeginDestroy(); // Cleanup ImGui_ImplUE_Shutdown(); } void AMyImGuiHUD::DrawHUD() { // Process events ImGui_ImplUE_ProcessEvent(); // Prepare new frame ImGui_ImplUE_NewFrame(); // Rendering ImGui::Render(); } bool AMyImGuiHUD::ImGui_ImplUE_Init() { ImGuiIO &io = ImGui::GetIO(); // Keyboard mapping for (int i = 0; i < ImGuiKey_COUNT; i++) io.KeyMap[i] = i; // Fill callbacks io.RenderDrawListsFn = ImGui_ImplUE_RenderDrawLists; io.SetClipboardTextFn = ImGui_ImplUE_SetClipboardText; io.GetClipboardTextFn = ImGui_ImplUE_GetClipboardText; io.UserData = this; return true; } void AMyImGuiHUD::ImGui_ImplUE_Shutdown() { ImGui_ImplUE_InvalidateDeviceObjects(); ImGui::Shutdown(); } bool AMyImGuiHUD::ImGui_ImplUE_CreateDeviceObjects() { // Build texture atlas ImGuiIO &io = ImGui::GetIO(); unsigned char *pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Upload texture to graphics system FontTexture = UTexture2D::CreateTransient(width, height, PF_R8G8B8A8); FTexture2DMipMap &mip = FontTexture->PlatformData->Mips[0]; void *data = mip.BulkData.Lock(LOCK_READ_WRITE); FMemory::Memcpy(data, pixels, width * height * 4); mip.BulkData.Unlock(); FontTexture->UpdateResource(); // Store our identifier io.Fonts->TexID = (void *)FontTexture; return true; } void AMyImGuiHUD::ImGui_ImplUE_InvalidateDeviceObjects() { FontTexture = NULL; } void AMyImGuiHUD::ImGui_ImplUE_ProcessEvent() { } void AMyImGuiHUD::ImGui_ImplUE_NewFrame() { if (!FontTexture) ImGui_ImplUE_CreateDeviceObjects(); ImGuiIO &io = ImGui::GetIO(); // Setup display size io.DisplaySize = ImVec2((float)Canvas->SizeX, (float)Canvas->SizeY); io.DisplayFramebufferScale = ImVec2(1, 1); // Setup inputs APlayerController *pc = GetOwningPlayerController(); pc->GetMousePosition(io.MousePos.x, io.MousePos.y); io.MouseDown[0] = pc->IsInputKeyDown(EKeys::LeftMouseButton); io.MouseDown[1] = pc->IsInputKeyDown(EKeys::RightMouseButton); io.MouseDown[2] = pc->IsInputKeyDown(EKeys::MiddleMouseButton); ImGui::NewFrame(); } void AMyImGuiHUD::ImGui_ImplUE_RenderDrawLists(ImDrawData *draw_data) { } const char *AMyImGuiHUD::ImGui_ImplUE_GetClipboardText() { return NULL; } void AMyImGuiHUD::ImGui_ImplUE_SetClipboardText(const char *text) { } <|endoftext|>
<commit_before>#include <ODLib/ODLib.hpp> #include <ODLib/Logger/Logger.hpp> ODLib::Logger::Logger::Logger(ODLib::Logger::Settings Settings) : m_settings(Settings) , m_nextRotation(GetNextRotation()) { CreateFileIfNeeded(); } ODLib::Logger::Logger::~Logger() { m_file.close(); } void ODLib::Logger::Logger::WriteLine(const ODLib::Logger::Record::Record& Record) { if (m_settings.DailyRotation == true && std::chrono::system_clock::now() >= m_nextRotation) { CreateFileIfNeeded(); m_nextRotation = GetNextRotation(); } auto Result = L"[" + ODLib::Logger::Record::Level::ToString(Record.GetLevel()) + L"] " + Record.GetText(); std::wcout << Result << std::flush; m_file << L"[" << Record.GetTime() << L"] " << Result; m_file.flush(); } void ODLib::Logger::Logger::CreateFileIfNeeded() { if (m_file.is_open() == true) { m_file.close(); m_file.clear(); } // Format the time for the file. std::wostringstream Result; auto Time = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); Result << std::put_time(std::localtime(&Time), m_settings.FileName.c_str()); auto FileName = Result.str(); // Create the directory if needed. std::experimental::filesystem::path Path(FileName); auto FileDirectory = Path.parent_path(); if (FileDirectory.empty() == false && std::experimental::filesystem::exists(FileDirectory) == false) { std::experimental::filesystem::create_directories(FileDirectory); } m_file.open(FileName, m_settings.FileMode); // Move the input position indicator to the end of the file. m_file.seekg(0, std::ios::end); // Is the file content empty? if (m_file.tellg() > 0) { // Append a line to separate a the old content from the new content. m_file << std::endl; m_file << L"-----------------------------------------------------" << std::endl; } } std::chrono::system_clock::time_point ODLib::Logger::Logger::GetNextRotation() { auto Now = std::chrono::system_clock::now(); auto Time = std::chrono::system_clock::to_time_t(Now); auto Date = std::localtime(&Time); // Set midnight time. Date->tm_hour = 0; Date->tm_min = 0; Date->tm_sec = 0; // Calculate next rotation. auto NextRotation = std::chrono::system_clock::from_time_t(std::mktime(Date)); if (NextRotation > Now) { return NextRotation; } else { return NextRotation + 24h; } } <commit_msg>Fix Linux build<commit_after>#include <ODLib/ODLib.hpp> #include <ODLib/Logger/Logger.hpp> ODLib::Logger::Logger::Logger(ODLib::Logger::Settings Settings) : m_settings(Settings) , m_nextRotation(GetNextRotation()) { CreateFileIfNeeded(); } ODLib::Logger::Logger::~Logger() { m_file.close(); } void ODLib::Logger::Logger::WriteLine(const ODLib::Logger::Record::Record& Record) { if (m_settings.DailyRotation == true && std::chrono::system_clock::now() >= m_nextRotation) { CreateFileIfNeeded(); m_nextRotation = GetNextRotation(); } auto Result = L"[" + ODLib::Logger::Record::Level::ToString(Record.GetLevel()) + L"] " + Record.GetText(); std::wcout << Result << std::flush; m_file << L"[" << Record.GetTime() << L"] " << Result; m_file.flush(); } void ODLib::Logger::Logger::CreateFileIfNeeded() { if (m_file.is_open() == true) { m_file.close(); m_file.clear(); } // Format the time for the file. std::wostringstream Result; auto Time = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); Result << std::put_time(std::localtime(&Time), m_settings.FileName.c_str()); auto FileName = Result.str(); // Create the directory if needed. std::experimental::filesystem::path Path(FileName); auto FileDirectory = Path.parent_path(); if (FileDirectory.empty() == false && std::experimental::filesystem::exists(FileDirectory) == false) { std::experimental::filesystem::create_directories(FileDirectory); } m_file.open(std::wstring_convert<std::codecvt_utf8<wchar_t>>().to_bytes(FileName).c_str(), m_settings.FileMode); // Move the input position indicator to the end of the file. m_file.seekg(0, std::ios::end); // Is the file content empty? if (m_file.tellg() > 0) { // Append a line to separate a the old content from the new content. m_file << std::endl; m_file << L"-----------------------------------------------------" << std::endl; } } std::chrono::system_clock::time_point ODLib::Logger::Logger::GetNextRotation() { auto Now = std::chrono::system_clock::now(); auto Time = std::chrono::system_clock::to_time_t(Now); auto Date = std::localtime(&Time); // Set midnight time. Date->tm_hour = 0; Date->tm_min = 0; Date->tm_sec = 0; // Calculate next rotation. auto NextRotation = std::chrono::system_clock::from_time_t(std::mktime(Date)); if (NextRotation > Now) { return NextRotation; } else { return NextRotation + 24h; } } <|endoftext|>
<commit_before>#ifndef ITER_FILTER_H_ #define ITER_FILTER_H_ #include "iterbase.hpp" #include <utility> #include <iterator> #include <initializer_list> namespace iter { //Forward declarations of Filter and filter template <typename FilterFunc, typename Container> class Filter; template <typename FilterFunc, typename Container> Filter<FilterFunc, Container> filter(FilterFunc, Container&&); template <typename FilterFunc, typename T> Filter<FilterFunc, std::initializer_list<T>> filter( FilterFunc, std::initializer_list<T>); template <typename FilterFunc, typename Container> class Filter { private: Container container; FilterFunc filter_func; // The filter function is the only thing allowed to create a Filter friend Filter filter<FilterFunc, Container>( FilterFunc, Container&&); template <typename FF, typename T> friend Filter<FF, std::initializer_list<T>> filter( FF, std::initializer_list<T>); // Value constructor for use only in the filter function Filter(FilterFunc filter_func, Container container) : container(std::forward<Container>(container)), filter_func(filter_func) { } Filter() = delete; Filter& operator=(const Filter&) = delete; public: Filter(const Filter&) = default; class Iterator : public std::iterator<std::input_iterator_tag, iterator_traits_deref<Container>> { protected: iterator_type<Container> sub_iter; const iterator_type<Container> sub_end; FilterFunc filter_func; // increment until the iterator points to is true on the // predicate. Called by constructor and operator++ void skip_failures() { while (this->sub_iter != this->sub_end && !this->filter_func(*this->sub_iter)) { ++this->sub_iter; } } public: Iterator (iterator_type<Container> iter, iterator_type<Container> end, FilterFunc filter_func) : sub_iter{iter}, sub_end{end}, filter_func(filter_func) { this->skip_failures(); } iterator_deref<Container> operator*() { return *this->sub_iter; } Iterator& operator++() { ++this->sub_iter; this->skip_failures(); return *this; } Iterator operator++(int) { auto ret = *this; ++*this; return ret; } bool operator!=(const Iterator& other) const { return this->sub_iter != other.sub_iter; } }; Iterator begin() { return {std::begin(this->container), std::end(this->container), this->filter_func}; } Iterator end() { return {std::end(this->container), std::end(this->container), this->filter_func}; } }; // Helper function to instantiate a Filter template <typename FilterFunc, typename Container> Filter<FilterFunc, Container> filter( FilterFunc filter_func, Container&& container) { return {filter_func, std::forward<Container>(container)}; } template <typename FilterFunc, typename T> Filter<FilterFunc, std::initializer_list<T>> filter( FilterFunc filter_func, std::initializer_list<T> il) { return {filter_func, std::move(il)}; } namespace detail { template <typename T> bool boolean_cast(const T& t) { return bool(t); } template <typename Container> class BoolTester { public: bool operator() (const iterator_deref<Container> item) const { return bool(item); } }; } template <typename Container> auto filter(Container&& container) -> decltype(filter( detail::BoolTester<Container>(), std::forward<Container>(container))) { return filter( detail::BoolTester<Container>(), std::forward<Container>(container)); } template <typename T> auto filter(std::initializer_list<T> il) -> decltype(filter( detail::BoolTester<std::initializer_list<T>>(), std::move(il))) { return filter( detail::BoolTester<std::initializer_list<T>>(), std::move(il)); } } #endif // #ifndef ITER_FILTER_H_ <commit_msg>adds filter iter ==<commit_after>#ifndef ITER_FILTER_H_ #define ITER_FILTER_H_ #include "iterbase.hpp" #include <utility> #include <iterator> #include <initializer_list> namespace iter { //Forward declarations of Filter and filter template <typename FilterFunc, typename Container> class Filter; template <typename FilterFunc, typename Container> Filter<FilterFunc, Container> filter(FilterFunc, Container&&); template <typename FilterFunc, typename T> Filter<FilterFunc, std::initializer_list<T>> filter( FilterFunc, std::initializer_list<T>); template <typename FilterFunc, typename Container> class Filter { private: Container container; FilterFunc filter_func; // The filter function is the only thing allowed to create a Filter friend Filter filter<FilterFunc, Container>( FilterFunc, Container&&); template <typename FF, typename T> friend Filter<FF, std::initializer_list<T>> filter( FF, std::initializer_list<T>); // Value constructor for use only in the filter function Filter(FilterFunc filter_func, Container container) : container(std::forward<Container>(container)), filter_func(filter_func) { } Filter() = delete; Filter& operator=(const Filter&) = delete; public: Filter(const Filter&) = default; class Iterator : public std::iterator<std::input_iterator_tag, iterator_traits_deref<Container>> { protected: iterator_type<Container> sub_iter; const iterator_type<Container> sub_end; FilterFunc filter_func; // increment until the iterator points to is true on the // predicate. Called by constructor and operator++ void skip_failures() { while (this->sub_iter != this->sub_end && !this->filter_func(*this->sub_iter)) { ++this->sub_iter; } } public: Iterator (iterator_type<Container> iter, iterator_type<Container> end, FilterFunc filter_func) : sub_iter{iter}, sub_end{end}, filter_func(filter_func) { this->skip_failures(); } iterator_deref<Container> operator*() { return *this->sub_iter; } Iterator& operator++() { ++this->sub_iter; this->skip_failures(); return *this; } Iterator operator++(int) { auto ret = *this; ++*this; return ret; } bool operator!=(const Iterator& other) const { return this->sub_iter != other.sub_iter; } bool operator==(const Iterator& other) const { return !(*this != other); } }; Iterator begin() { return {std::begin(this->container), std::end(this->container), this->filter_func}; } Iterator end() { return {std::end(this->container), std::end(this->container), this->filter_func}; } }; // Helper function to instantiate a Filter template <typename FilterFunc, typename Container> Filter<FilterFunc, Container> filter( FilterFunc filter_func, Container&& container) { return {filter_func, std::forward<Container>(container)}; } template <typename FilterFunc, typename T> Filter<FilterFunc, std::initializer_list<T>> filter( FilterFunc filter_func, std::initializer_list<T> il) { return {filter_func, std::move(il)}; } namespace detail { template <typename T> bool boolean_cast(const T& t) { return bool(t); } template <typename Container> class BoolTester { public: bool operator() (const iterator_deref<Container> item) const { return bool(item); } }; } template <typename Container> auto filter(Container&& container) -> decltype(filter( detail::BoolTester<Container>(), std::forward<Container>(container))) { return filter( detail::BoolTester<Container>(), std::forward<Container>(container)); } template <typename T> auto filter(std::initializer_list<T> il) -> decltype(filter( detail::BoolTester<std::initializer_list<T>>(), std::move(il))) { return filter( detail::BoolTester<std::initializer_list<T>>(), std::move(il)); } } #endif // #ifndef ITER_FILTER_H_ <|endoftext|>
<commit_before>// // __ParseBridge-Android.cpp // roll-eat // // Created by Zinge on 5/16/16. // // #include "ee/internal/MessageBridge.hpp" #include "ee/JniUtils.hpp" #include "ee/internal/JniMethodInfo.hpp" #include "ee/internal/JniString.hpp" #include "ee/Logger.hpp" namespace ee { std::string MessageBridge::call(const std::string& tag, const std::string& msg) { auto methodInfo = JniUtils::getStaticMethodInfo( "com/ee/core/internal/MessageBridge", "staticCall", "(Ljava/lang/String;Ljava/lang/String;"); if (methodInfo == nullptr) { throw std::runtime_error("Method not found!"); } auto tag_java = JniUtils::toJavaString(tag.c_str()); auto msg_java = JniUtils::toJavaString(msg.c_str()); jobject response = methodInfo->getEnv()->CallStaticObjectMethod( methodInfo->getClass(), methodInfo->getMethodId(), tag_java->get(), msg_java->get()); jstring response_java = static_cast<jstring>(response); auto result = JniUtils::toString(response_java); methodInfo->getEnv()->DeleteLocalRef(response); return result; } } // namespace ee <commit_msg>Fix incorrect JNI call.<commit_after>// // __ParseBridge-Android.cpp // roll-eat // // Created by Zinge on 5/16/16. // // #include "ee/internal/MessageBridge.hpp" #include "ee/JniUtils.hpp" #include "ee/internal/JniMethodInfo.hpp" #include "ee/internal/JniString.hpp" #include "ee/Logger.hpp" namespace ee { std::string MessageBridge::call(const std::string& tag, const std::string& msg) { auto methodInfo = JniUtils::getStaticMethodInfo( "com/ee/internal/MessageBridge", "staticCall", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;"); if (methodInfo == nullptr) { throw std::runtime_error("Method not found!"); } auto tag_java = JniUtils::toJavaString(tag.c_str()); auto msg_java = JniUtils::toJavaString(msg.c_str()); jobject response = methodInfo->getEnv()->CallStaticObjectMethod( methodInfo->getClass(), methodInfo->getMethodId(), tag_java->get(), msg_java->get()); jstring response_java = static_cast<jstring>(response); auto result = JniUtils::toString(response_java); methodInfo->getEnv()->DeleteLocalRef(response); return result; } } // namespace ee <|endoftext|>
<commit_before>/*ckwg +5 * Copyright 2012 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include "read_video_gravl_process.h" #include <processes/helpers/image/format.h> #include <processes/helpers/image/read.h> #include <vistk/pipeline/config.h> #include <vistk/pipeline/datum.h> #include <vistk/pipeline/process_exception.h> #include <gravl/core/api/data_block.h> #include <gravl/core/api/frame_ptr.h> #include <gravl/core/api/image.h> #include <gravl/core/api/image_data.h> #include <gravl/core/api/resource_ptr.h> #include <gravl/raf/raf.h> #include <vil/vil_image_view.h> #include <string> /** * \file read_video_gravl_process.cxx * * \brief Implementation of the read video gravl process. */ static size_t sabs(ptrdiff_t a); static size_t compute_block_size(gravl::image::dimension dim, gravl::image::stride s); static ptrdiff_t compute_offset(gravl::image::dimension dim, gravl::image::stride s); template <typename T> static T* compute_block_start( T* top_left, gravl::image::dimension dim, gravl::image::stride s); template <typename T> static T* compute_top_left( T* top_left, gravl::image::dimension dim, gravl::image::stride s); namespace vistk { class read_video_gravl_process::priv { public: priv(std::string const& input_uri); ~priv(); std::string const uri; gravl::resource_ptr resource; gravl::data_block* video; static config::key_t const config_pixtype; static config::key_t const config_pixfmt; static config::key_t const config_uri; static config::key_t const config_verify; static config::value_t const default_pixtype; static config::value_t const default_pixfmt; static config::value_t const default_verify; static port_t const port_output; }; config::key_t const read_video_gravl_process::priv::config_pixtype = config::key_t("pixtype"); config::key_t const read_video_gravl_process::priv::config_pixfmt = config::key_t("pixfmt"); config::key_t const read_video_gravl_process::priv::config_uri = config::key_t("input"); config::value_t const read_video_gravl_process::priv::default_pixtype = config::value_t(pixtypes::pixtype_byte()); config::value_t const read_video_gravl_process::priv::default_pixfmt = config::value_t(pixfmts::pixfmt_rgb()); process::port_t const read_video_gravl_process::priv::port_output = port_t("image"); read_video_gravl_process ::read_video_gravl_process(config_t const& config) : process(config) { declare_configuration_key( priv::config_pixtype, priv::default_pixtype, config::description_t("The pixel type of the input images.")); declare_configuration_key( priv::config_pixfmt, priv::default_pixfmt, config::description_t("The pixel format of the input images.")); declare_configuration_key( priv::config_uri, config::value_t(), config::description_t("The URI of the resource.")); pixtype_t const pixtype = config_value<pixtype_t>(priv::config_pixtype); pixfmt_t const pixfmt = config_value<pixfmt_t>(priv::config_pixfmt); port_type_t const port_type_output = port_type_for_pixtype(pixtype, pixfmt); port_flags_t required; required.insert(flag_required); declare_output_port( priv::port_output, port_type_output, required, port_description_t("The images that are read in.")); } read_video_gravl_process ::~read_video_gravl_process() { } void read_video_gravl_process ::_configure() { // Configure the process. { pixtype_t const pixtype = config_value<pixtype_t>(priv::config_pixtype); std::string const uri = config_value<std::string>(priv::config_uri); d.reset(new priv(uri)); } if (d->uri.empty()) { static std::string const reason = "The URI given was empty"; config::value_t const value = config::value_t(d->uri); throw invalid_configuration_value_exception(name(), priv::config_uri, value, reason); } d->resource = gravl::raf::get_resource(d->uri.c_str()); if (!d->resource) { std::string const reason = "Failed to open the resource: " + d->uri; throw invalid_configuration_exception(name(), reason); } d->video = d->resource.get_data<gravl::data_block>(); if (!d->video) { static std::string const reason = "Failed to obtain data_block from resource"; throw invalid_configuration_exception(name(), reason); } process::_configure(); } void read_video_gravl_process ::_init() { d->video->rewind(); process::_init(); } void read_video_gravl_process ::_step() { datum_t dat; if (d->video->at_end()) { mark_process_as_complete(); dat = datum::complete_datum(); } else if (!d->video) { static datum::error_t const err_string = datum::error_t("Error with input file stream."); dat = datum::error_datum(err_string); } else { gravl::frame_ptr const frame = d->video->current_frame(); gravl::image_data const* const image_data = frame.get_const_data<gravl::image_data>(); gravl::image const image = (image_data ? image_data->pixels() : gravl::image()); if (!image || image.format() != gravl::image::format_of<uint8_t>()) { dat = datum::empty_datum(); } else { gravl::image::dimension const dim = image.dimensions(); gravl::image::stride const ps = image.strides(); uint8_t const* const top_left = image.data<uint8_t>(); size_t const size = compute_block_size(dim, ps); // Ugh, there is no way to create a vil_image_view from existing data // without arranging for said existing data to stick around, so stuck // having to copy the data (again) :-( vil_memory_chunk* const mem = new vil_memory_chunk(size, VIL_PIXEL_FORMAT_BYTE); uint8_t* const buffer = reinterpret_cast<uint8_t*>(mem->data()); memcpy(buffer, compute_block_start(top_left, dim, ps), size); vil_image_view<vxl_byte> const vil(vil_memory_chunk_sptr(mem), compute_top_left(buffer, dim, ps), dim.width, dim.height, dim.planes, ps.width, ps.height, ps.planes); dat = datum::new_datum(vil); } d->video->advance(); } push_datum_to_port(priv::port_output, dat); process::_step(); } read_video_gravl_process::priv ::priv(std::string const& input_uri) : uri(input_uri) { } read_video_gravl_process::priv ::~priv() { } } size_t sabs(ptrdiff_t a) { return static_cast<size_t>((a < 0 ? -a : a)); } size_t compute_block_size(gravl::image::dimension dim, gravl::image::stride s) { return ((dim.width - 1) * sabs(s.width)) + ((dim.height - 1) * sabs(s.height)) + ((dim.planes - 1) * sabs(s.planes)) + 1; } ptrdiff_t compute_offset(gravl::image::dimension dim, gravl::image::stride s) { ptrdiff_t result = 0; if (s.width < 0) { result -= s.width * (dim.width - 1); } if (s.height < 0) { result -= s.height * (dim.height - 1); } if (s.planes < 0) { result -= s.planes * (dim.planes - 1); } return result; } template <typename T> T* compute_block_start( T* top_left, gravl::image::dimension dim, gravl::image::stride s) { return top_left - compute_offset(dim, s); } template <typename T> T* compute_top_left( T* top_left, gravl::image::dimension dim, gravl::image::stride s) { return top_left + compute_offset(dim, s); } <commit_msg>Remove unneeded forward declarations<commit_after>/*ckwg +5 * Copyright 2012 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include "read_video_gravl_process.h" #include <processes/helpers/image/format.h> #include <processes/helpers/image/read.h> #include <vistk/pipeline/config.h> #include <vistk/pipeline/datum.h> #include <vistk/pipeline/process_exception.h> #include <gravl/core/api/data_block.h> #include <gravl/core/api/frame_ptr.h> #include <gravl/core/api/image.h> #include <gravl/core/api/image_data.h> #include <gravl/core/api/resource_ptr.h> #include <gravl/raf/raf.h> #include <vil/vil_image_view.h> #include <string> /** * \file read_video_gravl_process.cxx * * \brief Implementation of the read video gravl process. */ static size_t compute_block_size(gravl::image::dimension dim, gravl::image::stride s); template <typename T> static T* compute_block_start( T* top_left, gravl::image::dimension dim, gravl::image::stride s); template <typename T> static T* compute_top_left( T* top_left, gravl::image::dimension dim, gravl::image::stride s); namespace vistk { class read_video_gravl_process::priv { public: priv(std::string const& input_uri); ~priv(); std::string const uri; gravl::resource_ptr resource; gravl::data_block* video; static config::key_t const config_pixtype; static config::key_t const config_pixfmt; static config::key_t const config_uri; static config::key_t const config_verify; static config::value_t const default_pixtype; static config::value_t const default_pixfmt; static config::value_t const default_verify; static port_t const port_output; }; config::key_t const read_video_gravl_process::priv::config_pixtype = config::key_t("pixtype"); config::key_t const read_video_gravl_process::priv::config_pixfmt = config::key_t("pixfmt"); config::key_t const read_video_gravl_process::priv::config_uri = config::key_t("input"); config::value_t const read_video_gravl_process::priv::default_pixtype = config::value_t(pixtypes::pixtype_byte()); config::value_t const read_video_gravl_process::priv::default_pixfmt = config::value_t(pixfmts::pixfmt_rgb()); process::port_t const read_video_gravl_process::priv::port_output = port_t("image"); read_video_gravl_process ::read_video_gravl_process(config_t const& config) : process(config) { declare_configuration_key( priv::config_pixtype, priv::default_pixtype, config::description_t("The pixel type of the input images.")); declare_configuration_key( priv::config_pixfmt, priv::default_pixfmt, config::description_t("The pixel format of the input images.")); declare_configuration_key( priv::config_uri, config::value_t(), config::description_t("The URI of the resource.")); pixtype_t const pixtype = config_value<pixtype_t>(priv::config_pixtype); pixfmt_t const pixfmt = config_value<pixfmt_t>(priv::config_pixfmt); port_type_t const port_type_output = port_type_for_pixtype(pixtype, pixfmt); port_flags_t required; required.insert(flag_required); declare_output_port( priv::port_output, port_type_output, required, port_description_t("The images that are read in.")); } read_video_gravl_process ::~read_video_gravl_process() { } void read_video_gravl_process ::_configure() { // Configure the process. { pixtype_t const pixtype = config_value<pixtype_t>(priv::config_pixtype); std::string const uri = config_value<std::string>(priv::config_uri); d.reset(new priv(uri)); } if (d->uri.empty()) { static std::string const reason = "The URI given was empty"; config::value_t const value = config::value_t(d->uri); throw invalid_configuration_value_exception(name(), priv::config_uri, value, reason); } d->resource = gravl::raf::get_resource(d->uri.c_str()); if (!d->resource) { std::string const reason = "Failed to open the resource: " + d->uri; throw invalid_configuration_exception(name(), reason); } d->video = d->resource.get_data<gravl::data_block>(); if (!d->video) { static std::string const reason = "Failed to obtain data_block from resource"; throw invalid_configuration_exception(name(), reason); } process::_configure(); } void read_video_gravl_process ::_init() { d->video->rewind(); process::_init(); } void read_video_gravl_process ::_step() { datum_t dat; if (d->video->at_end()) { mark_process_as_complete(); dat = datum::complete_datum(); } else if (!d->video) { static datum::error_t const err_string = datum::error_t("Error with input file stream."); dat = datum::error_datum(err_string); } else { gravl::frame_ptr const frame = d->video->current_frame(); gravl::image_data const* const image_data = frame.get_const_data<gravl::image_data>(); gravl::image const image = (image_data ? image_data->pixels() : gravl::image()); if (!image || image.format() != gravl::image::format_of<uint8_t>()) { dat = datum::empty_datum(); } else { gravl::image::dimension const dim = image.dimensions(); gravl::image::stride const ps = image.strides(); uint8_t const* const top_left = image.data<uint8_t>(); size_t const size = compute_block_size(dim, ps); // Ugh, there is no way to create a vil_image_view from existing data // without arranging for said existing data to stick around, so stuck // having to copy the data (again) :-( vil_memory_chunk* const mem = new vil_memory_chunk(size, VIL_PIXEL_FORMAT_BYTE); uint8_t* const buffer = reinterpret_cast<uint8_t*>(mem->data()); memcpy(buffer, compute_block_start(top_left, dim, ps), size); vil_image_view<vxl_byte> const vil(vil_memory_chunk_sptr(mem), compute_top_left(buffer, dim, ps), dim.width, dim.height, dim.planes, ps.width, ps.height, ps.planes); dat = datum::new_datum(vil); } d->video->advance(); } push_datum_to_port(priv::port_output, dat); process::_step(); } read_video_gravl_process::priv ::priv(std::string const& input_uri) : uri(input_uri) { } read_video_gravl_process::priv ::~priv() { } } size_t sabs(ptrdiff_t a) { return static_cast<size_t>((a < 0 ? -a : a)); } size_t compute_block_size(gravl::image::dimension dim, gravl::image::stride s) { return ((dim.width - 1) * sabs(s.width)) + ((dim.height - 1) * sabs(s.height)) + ((dim.planes - 1) * sabs(s.planes)) + 1; } ptrdiff_t compute_offset(gravl::image::dimension dim, gravl::image::stride s) { ptrdiff_t result = 0; if (s.width < 0) { result -= s.width * (dim.width - 1); } if (s.height < 0) { result -= s.height * (dim.height - 1); } if (s.planes < 0) { result -= s.planes * (dim.planes - 1); } return result; } template <typename T> T* compute_block_start( T* top_left, gravl::image::dimension dim, gravl::image::stride s) { return top_left - compute_offset(dim, s); } template <typename T> T* compute_top_left( T* top_left, gravl::image::dimension dim, gravl::image::stride s) { return top_left + compute_offset(dim, s); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: collelem.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hr $ $Date: 2007-06-27 14:27:08 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_basic.hxx" #ifndef _ERRCODE_HXX //autogen #include <tools/errcode.hxx> #endif #ifndef _SV_MSGBOX_HXX //autogen #include <vcl/msgbox.hxx> #endif #ifndef _SBXCLASS_HXX //autogen #include <basic/sbx.hxx> #endif #include "collelem.hxx" // Das Sample-Element ist ein kleines Objekt, das die Properties // Name und Value enthlt sowie die Methode Say, die den bergebenen // Text mit dem eigenen Namen verkoppelt und ausgibt. SampleElement::SampleElement( const String& r ) : SbxObject( r ) { // Methode Say mit einem String-Parameter SbxVariable* pMeth = Make( String( RTL_CONSTASCII_USTRINGPARAM("Say") ), SbxCLASS_METHOD, SbxEMPTY ); pMeth->SetUserData( 0x12345678 ); pMeth->ResetFlag( SBX_FIXED ); SbxInfo* pInfo_ = new SbxInfo; pInfo_->AddParam( String( RTL_CONSTASCII_USTRINGPARAM("text") ), SbxSTRING, SBX_READ ); pMeth->SetInfo( pInfo_ ); } void SampleElement::SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType ) { const SbxHint* pHint = PTR_CAST(SbxHint,&rHint); if( pHint ) { SbxVariable* pVar = pHint->GetVar(); SbxArray* pPar_ = pVar->GetParameters(); ULONG t = pHint->GetId(); if( t == SBX_HINT_DATAWANTED && pVar->GetUserData() == 0x12345678 ) { // Die Say-Methode: // 1 Parameter + Returnwert if( !pPar_ || pPar_->Count() != 2 ) SetError( SbxERR_WRONG_ARGS ); else { String s( GetName() ); s.AppendAscii( " says: " ); s += pPar_->Get( 1 )->GetString(); pPar_->Get( 0 )->SetType(SbxSTRING); pPar_->Get( 0 )->PutString( s ); InfoBox( NULL, s ).Execute(); } return; } SbxObject::SFX_NOTIFY( rBC, rBCType, rHint, rHintType ); } } <commit_msg>INTEGRATION: CWS changefileheader (1.6.88); FILE MERGED 2008/04/01 15:01:57 thb 1.6.88.3: #i85898# Stripping all external header guards 2008/04/01 10:48:43 thb 1.6.88.2: #i85898# Stripping all external header guards 2008/03/28 16:07:37 rt 1.6.88.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: collelem.cxx,v $ * $Revision: 1.7 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_basic.hxx" #include <tools/errcode.hxx> #include <vcl/msgbox.hxx> #include <basic/sbx.hxx> #include "collelem.hxx" // Das Sample-Element ist ein kleines Objekt, das die Properties // Name und Value enthlt sowie die Methode Say, die den bergebenen // Text mit dem eigenen Namen verkoppelt und ausgibt. SampleElement::SampleElement( const String& r ) : SbxObject( r ) { // Methode Say mit einem String-Parameter SbxVariable* pMeth = Make( String( RTL_CONSTASCII_USTRINGPARAM("Say") ), SbxCLASS_METHOD, SbxEMPTY ); pMeth->SetUserData( 0x12345678 ); pMeth->ResetFlag( SBX_FIXED ); SbxInfo* pInfo_ = new SbxInfo; pInfo_->AddParam( String( RTL_CONSTASCII_USTRINGPARAM("text") ), SbxSTRING, SBX_READ ); pMeth->SetInfo( pInfo_ ); } void SampleElement::SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType ) { const SbxHint* pHint = PTR_CAST(SbxHint,&rHint); if( pHint ) { SbxVariable* pVar = pHint->GetVar(); SbxArray* pPar_ = pVar->GetParameters(); ULONG t = pHint->GetId(); if( t == SBX_HINT_DATAWANTED && pVar->GetUserData() == 0x12345678 ) { // Die Say-Methode: // 1 Parameter + Returnwert if( !pPar_ || pPar_->Count() != 2 ) SetError( SbxERR_WRONG_ARGS ); else { String s( GetName() ); s.AppendAscii( " says: " ); s += pPar_->Get( 1 )->GetString(); pPar_->Get( 0 )->SetType(SbxSTRING); pPar_->Get( 0 )->PutString( s ); InfoBox( NULL, s ).Execute(); } return; } SbxObject::SFX_NOTIFY( rBC, rBCType, rHint, rHintType ); } } <|endoftext|>
<commit_before>//===- BugDriver.cpp - Top-Level BugPoint class implementation ------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This class contains all of the shared state and information that is used by // the BugPoint tool to track down errors in optimizations. This class is the // main driver class that invokes all sub-functionality. // //===----------------------------------------------------------------------===// #include "BugDriver.h" #include "llvm/Linker.h" #include "llvm/Module.h" #include "llvm/Pass.h" #include "llvm/Assembly/Parser.h" #include "llvm/Bytecode/Reader.h" #include "llvm/Support/ToolRunner.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/FileUtilities.h" #include <iostream> #include <memory> using namespace llvm; // Anonymous namespace to define command line options for debugging. // namespace { // Output - The user can specify a file containing the expected output of the // program. If this filename is set, it is used as the reference diff source, // otherwise the raw input run through an interpreter is used as the reference // source. // cl::opt<std::string> OutputFile("output", cl::desc("Specify a reference program output " "(for miscompilation detection)")); } /// setNewProgram - If we reduce or update the program somehow, call this method /// to update bugdriver with it. This deletes the old module and sets the /// specified one as the current program. void BugDriver::setNewProgram(Module *M) { delete Program; Program = M; } /// getPassesString - Turn a list of passes into a string which indicates the /// command line options that must be passed to add the passes. /// std::string llvm::getPassesString(const std::vector<const PassInfo*> &Passes) { std::string Result; for (unsigned i = 0, e = Passes.size(); i != e; ++i) { if (i) Result += " "; Result += "-"; Result += Passes[i]->getPassArgument(); } return Result; } BugDriver::BugDriver(const char *toolname, bool as_child) : ToolName(toolname), ReferenceOutputFile(OutputFile), Program(0), Interpreter(0), cbe(0), gcc(0), run_as_child(as_child) {} /// ParseInputFile - Given a bytecode or assembly input filename, parse and /// return it, or return null if not possible. /// Module *llvm::ParseInputFile(const std::string &InputFilename) { Module *Result = 0; try { Result = ParseBytecodeFile(InputFilename); if (!Result && !(Result = ParseAssemblyFile(InputFilename))){ std::cerr << "bugpoint: could not read input file '" << InputFilename << "'!\n"; } } catch (const ParseException &E) { std::cerr << "bugpoint: " << E.getMessage() << '\n'; Result = 0; } return Result; } // This method takes the specified list of LLVM input files, attempts to load // them, either as assembly or bytecode, then link them together. It returns // true on failure (if, for example, an input bytecode file could not be // parsed), and false on success. // bool BugDriver::addSources(const std::vector<std::string> &Filenames) { assert(Program == 0 && "Cannot call addSources multiple times!"); assert(!Filenames.empty() && "Must specify at least on input filename!"); // Load the first input file... Program = ParseInputFile(Filenames[0]); if (Program == 0) return true; if (!run_as_child) std::cout << "Read input file : '" << Filenames[0] << "'\n"; for (unsigned i = 1, e = Filenames.size(); i != e; ++i) { std::auto_ptr<Module> M(ParseInputFile(Filenames[i])); if (M.get() == 0) return true; if (!run_as_child) std::cout << "Linking in input file: '" << Filenames[i] << "'\n"; std::string ErrorMessage; if (Linker::LinkModules(Program, M.get(), &ErrorMessage)) { std::cerr << ToolName << ": error linking in '" << Filenames[i] << "': " << ErrorMessage << '\n'; return true; } } if (!run_as_child) std::cout << "*** All input ok\n"; // All input files read successfully! return false; } /// run - The top level method that is invoked after all of the instance /// variables are set up from command line arguments. /// bool BugDriver::run() { // The first thing to do is determine if we're running as a child. If we are, // then what to do is very narrow. This form of invocation is only called // from the runPasses method to actually run those passes in a child process. if (run_as_child) { // Execute the passes return runPassesAsChild(PassesToRun); } // If we're not running as a child, the first thing that we must do is // determine what the problem is. Does the optimization series crash the // compiler, or does it produce illegal code? We make the top-level // decision by trying to run all of the passes on the the input program, // which should generate a bytecode file. If it does generate a bytecode // file, then we know the compiler didn't crash, so try to diagnose a // miscompilation. if (!PassesToRun.empty()) { std::cout << "Running selected passes on program to test for crash: "; if (runPasses(PassesToRun)) return debugOptimizerCrash(); } // Set up the execution environment, selecting a method to run LLVM bytecode. if (initializeExecutionEnvironment()) return true; // Test to see if we have a code generator crash. std::cout << "Running the code generator to test for a crash: "; try { compileProgram(Program); std::cout << '\n'; } catch (ToolExecutionError &TEE) { std::cout << TEE.what(); return debugCodeGeneratorCrash(); } // Run the raw input to see where we are coming from. If a reference output // was specified, make sure that the raw output matches it. If not, it's a // problem in the front-end or the code generator. // bool CreatedOutput = false; if (ReferenceOutputFile.empty()) { std::cout << "Generating reference output from raw program: "; try { ReferenceOutputFile = executeProgramWithCBE("bugpoint.reference.out"); CreatedOutput = true; std::cout << "Reference output is: " << ReferenceOutputFile << '\n'; } catch (ToolExecutionError &TEE) { std::cerr << TEE.what(); if (Interpreter != cbe) { std::cerr << "*** There is a bug running the C backend. Either debug" << " it (use the -run-cbe bugpoint option), or fix the error" << " some other way.\n"; return 1; } return debugCodeGeneratorCrash(); } } // Make sure the reference output file gets deleted on exit from this // function, if appropriate. sys::Path ROF(ReferenceOutputFile); FileRemover RemoverInstance(ROF, CreatedOutput); // Diff the output of the raw program against the reference output. If it // matches, then we have a miscompilation bug. std::cout << "*** Checking the code generator...\n"; try { if (!diffProgram()) { std::cout << "\n*** Debugging miscompilation!\n"; return debugMiscompilation(); } } catch (ToolExecutionError &TEE) { std::cerr << TEE.what(); return debugCodeGeneratorCrash(); } std::cout << "\n*** Input program does not match reference diff!\n"; std::cout << "Debugging code generator problem!\n"; try { return debugCodeGenerator(); } catch (ToolExecutionError &TEE) { std::cerr << TEE.what(); return debugCodeGeneratorCrash(); } } void llvm::PrintFunctionList(const std::vector<Function*> &Funcs) { unsigned NumPrint = Funcs.size(); if (NumPrint > 10) NumPrint = 10; for (unsigned i = 0; i != NumPrint; ++i) std::cout << " " << Funcs[i]->getName(); if (NumPrint < Funcs.size()) std::cout << "... <" << Funcs.size() << " total>"; std::cout << std::flush; } <commit_msg>print a nice error if bugpoint gets an error reading inputs. Bug identified by coverity.<commit_after>//===- BugDriver.cpp - Top-Level BugPoint class implementation ------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This class contains all of the shared state and information that is used by // the BugPoint tool to track down errors in optimizations. This class is the // main driver class that invokes all sub-functionality. // //===----------------------------------------------------------------------===// #include "BugDriver.h" #include "llvm/Linker.h" #include "llvm/Module.h" #include "llvm/Pass.h" #include "llvm/Assembly/Parser.h" #include "llvm/Bytecode/Reader.h" #include "llvm/Support/ToolRunner.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/FileUtilities.h" #include <iostream> #include <memory> using namespace llvm; // Anonymous namespace to define command line options for debugging. // namespace { // Output - The user can specify a file containing the expected output of the // program. If this filename is set, it is used as the reference diff source, // otherwise the raw input run through an interpreter is used as the reference // source. // cl::opt<std::string> OutputFile("output", cl::desc("Specify a reference program output " "(for miscompilation detection)")); } /// setNewProgram - If we reduce or update the program somehow, call this method /// to update bugdriver with it. This deletes the old module and sets the /// specified one as the current program. void BugDriver::setNewProgram(Module *M) { delete Program; Program = M; } /// getPassesString - Turn a list of passes into a string which indicates the /// command line options that must be passed to add the passes. /// std::string llvm::getPassesString(const std::vector<const PassInfo*> &Passes) { std::string Result; for (unsigned i = 0, e = Passes.size(); i != e; ++i) { if (i) Result += " "; Result += "-"; Result += Passes[i]->getPassArgument(); } return Result; } BugDriver::BugDriver(const char *toolname, bool as_child) : ToolName(toolname), ReferenceOutputFile(OutputFile), Program(0), Interpreter(0), cbe(0), gcc(0), run_as_child(as_child) {} /// ParseInputFile - Given a bytecode or assembly input filename, parse and /// return it, or return null if not possible. /// Module *llvm::ParseInputFile(const std::string &InputFilename) { Module *Result = 0; try { Result = ParseBytecodeFile(InputFilename); if (!Result && !(Result = ParseAssemblyFile(InputFilename))){ std::cerr << "bugpoint: could not read input file '" << InputFilename << "'!\n"; } } catch (const ParseException &E) { std::cerr << "bugpoint: " << E.getMessage() << '\n'; Result = 0; } return Result; } // This method takes the specified list of LLVM input files, attempts to load // them, either as assembly or bytecode, then link them together. It returns // true on failure (if, for example, an input bytecode file could not be // parsed), and false on success. // bool BugDriver::addSources(const std::vector<std::string> &Filenames) { assert(Program == 0 && "Cannot call addSources multiple times!"); assert(!Filenames.empty() && "Must specify at least on input filename!"); try { // Load the first input file. Program = ParseInputFile(Filenames[0]); if (Program == 0) return true; if (!run_as_child) std::cout << "Read input file : '" << Filenames[0] << "'\n"; for (unsigned i = 1, e = Filenames.size(); i != e; ++i) { std::auto_ptr<Module> M(ParseInputFile(Filenames[i])); if (M.get() == 0) return true; if (!run_as_child) std::cout << "Linking in input file: '" << Filenames[i] << "'\n"; std::string ErrorMessage; if (Linker::LinkModules(Program, M.get(), &ErrorMessage)) { std::cerr << ToolName << ": error linking in '" << Filenames[i] << "': " << ErrorMessage << '\n'; return true; } } } catch (const std::string &Error) { std::cerr << ToolName << ": error reading input '" << Error << "'\n"; return true; } if (!run_as_child) std::cout << "*** All input ok\n"; // All input files read successfully! return false; } /// run - The top level method that is invoked after all of the instance /// variables are set up from command line arguments. /// bool BugDriver::run() { // The first thing to do is determine if we're running as a child. If we are, // then what to do is very narrow. This form of invocation is only called // from the runPasses method to actually run those passes in a child process. if (run_as_child) { // Execute the passes return runPassesAsChild(PassesToRun); } // If we're not running as a child, the first thing that we must do is // determine what the problem is. Does the optimization series crash the // compiler, or does it produce illegal code? We make the top-level // decision by trying to run all of the passes on the the input program, // which should generate a bytecode file. If it does generate a bytecode // file, then we know the compiler didn't crash, so try to diagnose a // miscompilation. if (!PassesToRun.empty()) { std::cout << "Running selected passes on program to test for crash: "; if (runPasses(PassesToRun)) return debugOptimizerCrash(); } // Set up the execution environment, selecting a method to run LLVM bytecode. if (initializeExecutionEnvironment()) return true; // Test to see if we have a code generator crash. std::cout << "Running the code generator to test for a crash: "; try { compileProgram(Program); std::cout << '\n'; } catch (ToolExecutionError &TEE) { std::cout << TEE.what(); return debugCodeGeneratorCrash(); } // Run the raw input to see where we are coming from. If a reference output // was specified, make sure that the raw output matches it. If not, it's a // problem in the front-end or the code generator. // bool CreatedOutput = false; if (ReferenceOutputFile.empty()) { std::cout << "Generating reference output from raw program: "; try { ReferenceOutputFile = executeProgramWithCBE("bugpoint.reference.out"); CreatedOutput = true; std::cout << "Reference output is: " << ReferenceOutputFile << '\n'; } catch (ToolExecutionError &TEE) { std::cerr << TEE.what(); if (Interpreter != cbe) { std::cerr << "*** There is a bug running the C backend. Either debug" << " it (use the -run-cbe bugpoint option), or fix the error" << " some other way.\n"; return 1; } return debugCodeGeneratorCrash(); } } // Make sure the reference output file gets deleted on exit from this // function, if appropriate. sys::Path ROF(ReferenceOutputFile); FileRemover RemoverInstance(ROF, CreatedOutput); // Diff the output of the raw program against the reference output. If it // matches, then we have a miscompilation bug. std::cout << "*** Checking the code generator...\n"; try { if (!diffProgram()) { std::cout << "\n*** Debugging miscompilation!\n"; return debugMiscompilation(); } } catch (ToolExecutionError &TEE) { std::cerr << TEE.what(); return debugCodeGeneratorCrash(); } std::cout << "\n*** Input program does not match reference diff!\n"; std::cout << "Debugging code generator problem!\n"; try { return debugCodeGenerator(); } catch (ToolExecutionError &TEE) { std::cerr << TEE.what(); return debugCodeGeneratorCrash(); } } void llvm::PrintFunctionList(const std::vector<Function*> &Funcs) { unsigned NumPrint = Funcs.size(); if (NumPrint > 10) NumPrint = 10; for (unsigned i = 0; i != NumPrint; ++i) std::cout << " " << Funcs[i]->getName(); if (NumPrint < Funcs.size()) std::cout << "... <" << Funcs.size() << " total>"; std::cout << std::flush; } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <string> #include <queue> #include <vector> #include <bitset> using namespace std; string inFileName; int frequencyList[256]; struct huffNode { int frequency; char character; huffNode* left; huffNode* right; }; struct node_comparison { bool operator () (const huffNode* A, const huffNode* B) const { return A->frequency > B->frequency; } }; void generateEncodings(huffNode *root, vector<bool> & encoding, vector<vector<bool>> & encodingTable) { if (root != NULL) { if (root->character != -1) { encodingTable[root->character] = encoding; } vector<bool> leftEncoding = encoding; leftEncoding.push_back(false); vector<bool> rightEncoding = encoding; rightEncoding.push_back(true); generateEncodings(root->left,leftEncoding,encodingTable); generateEncodings(root->right,rightEncoding,encodingTable); } } void generateInitialPQueue(int frequencyList[256], priority_queue<huffNode*, vector<huffNode*>, node_comparison> &nodeHeap) { for (int i = 0; i < 256; i++) { if (frequencyList[i] != 0) { huffNode* tempNode; tempNode = new huffNode; tempNode->frequency=frequencyList[i]; tempNode->character = (char)i; tempNode->left = NULL; tempNode->right = NULL; nodeHeap.push(tempNode); } } } void printPQueue(priority_queue<huffNode*, vector<huffNode*>, node_comparison> &nodeHeap) { if (nodeHeap.empty()) { cout << "There's nothing in the heap!" << endl; } while (!nodeHeap.empty()) { huffNode* tempNode; tempNode = nodeHeap.top(); cout << tempNode->character << endl; nodeHeap.pop(); } } void initializeFrequencyList(int frequencyList[256]) { for (int i = 0; i < 256; i++) frequencyList[i] = 0; } void generateFrequencyList(ifstream& fin, int frequencyList[256]) { string line = ""; while (!fin.eof()) { getline(fin,line); for (int i = 0; i < line.length(); i++) { frequencyList[line[i]] += 1; } frequencyList[10] += 1; line = ""; } frequencyList[26] = 1; } void printFrequencyList(int frequencyList[256]) { for (int i = 0; i < 256; i++) { if (frequencyList[i] != 0) { cout << "Character " << (char)i << ": " << frequencyList[i] << endl; } } } void getEncoding(vector<bool> bitString, string &encoding) { for (int i = 0; i < bitString.size(); i++) { encoding += bitString[i]; } } void printEncodings(vector<vector<bool>> encodingTable) { string encoding = ""; for (int i = 0; i < 256; i++) { if (!(encodingTable[i].empty())) { getEncoding(encodingTable[i], encoding); cout << "Character " << (char)i << " encoding: " << encoding << endl; encoding = ""; } } } void generateHuffmanTree(priority_queue <huffNode*, vector<huffNode*>, node_comparison> &heap) { if (heap.size() <= 1) return; else { huffNode *node1, *node2; node1 = new huffNode; node2 = new huffNode; node1 = heap.top(); heap.pop(); node2 = heap.top(); heap.pop(); int totalFreq = node1->frequency + node2->frequency; huffNode* newNode; newNode = new huffNode; newNode->frequency = totalFreq; newNode->character = (char)255; newNode->left = node1; newNode->right = node2; heap.push(newNode); totalFreq = 0; generateHuffmanTree(heap); } } void streamFrequencyList(ofstream &fout) { for (int i = 0; i < 256; i++) { if (frequencyList[i] != 0) { fout << i << ':' << frequencyList[i] << '!'; } } } void convertBuffer(vector<bool> & ogBuffer, bitset<8> &newBuffer) { for (int i = 0; i < ogBuffer.size(); i++) { newBuffer[i] = ogBuffer[i]; } } void checkBuffer(vector<bool> & bitBuffer, vector<bool> & encoding, ofstream &fout) { while (encoding.size() != 0 ) { int availableSpace = 8 - bitBuffer.size(); for (int i = 0; i < availableSpace; i++) { if (!encoding.empty()) { bitBuffer.push_back(encoding[0]); encoding.erase(encoding.begin()); } } if (bitBuffer.size() == 8) { //convert vector<bool> to bitbuffer for output bitset<8> outputBuffer; convertBuffer(bitBuffer, outputBuffer); unsigned char n = outputBuffer.to_ulong(); fout << n; bitBuffer.clear(); } } } void streamEncoding(ifstream &fin, ofstream &fout, vector<bool> & bitBuffer, vector<vector<bool>> encodingTable) { fout << "BIZCOMPRESS" << endl; //Printing "magic number fout << inFileName << endl; streamFrequencyList(fout); //need to output frequency list/table fout << endl; string line = ""; vector<bool> currentEncoding; while (!fin.eof()) { getline(fin, line); for (int i = 0; i < line.length(); i++) { currentEncoding = encodingTable[line[i]]; checkBuffer(bitBuffer, currentEncoding, fout); while (!currentEncoding.empty()) { bitBuffer.push_back(currentEncoding[0]); currentEncoding.erase(currentEncoding.begin()); } } currentEncoding = encodingTable[10]; checkBuffer(bitBuffer, currentEncoding, fout); while (!currentEncoding.empty()) { bitBuffer.push_back(currentEncoding[0]); currentEncoding.erase(currentEncoding.begin()); } line = ""; } currentEncoding = encodingTable[26]; checkBuffer(bitBuffer, currentEncoding, fout); checkBuffer(bitBuffer, currentEncoding, fout); } int main(int argc, char* argv[]) { if (argc != 2) { cout << "Please rerun the program and type a source file to be compressed." << endl; } else { //argv[1] contains the filename to be provided inFileName = argv[1]; ifstream fin(inFileName); if (fin.fail()) cout << "Could not open target file, please rerun the program with a valid text file (.txt)." << endl; else { string outFileName = inFileName.substr(0, inFileName.length() - 3) + "mcp"; //assumes a .txt file (changes output to a .mcp) ofstream fout(outFileName, ios::binary | ios::out); priority_queue<huffNode*, vector<huffNode*>, node_comparison> nodeHeap; vector<bool> startEncoding; vector<vector<bool>> encodingTable(256, vector<bool>(0)); vector<bool> bitBuffer; initializeFrequencyList(frequencyList); generateFrequencyList(fin, frequencyList); fin.close(); //printFrequencyList(frequencyList); generateInitialPQueue(frequencyList, nodeHeap); generateHuffmanTree(nodeHeap); huffNode *root; root = nodeHeap.top(); nodeHeap.pop(); //create the encoding for each leaf node (character) generateEncodings(root, startEncoding, encodingTable); fin.open(inFileName); streamEncoding(fin, fout, bitBuffer, encodingTable); } } cout << "Done." << endl; cin.get(); cin.get(); return 0; }<commit_msg>Adjusted some of the output to make decompression easier.<commit_after>#include <iostream> #include <fstream> #include <string> #include <queue> #include <vector> #include <bitset> using namespace std; string inFileName; int frequencyList[256]; struct huffNode { int frequency; char character; huffNode* left; huffNode* right; }; struct node_comparison { bool operator () (const huffNode* A, const huffNode* B) const { return A->frequency > B->frequency; } }; void generateEncodings(huffNode *root, vector<bool> & encoding, vector<vector<bool>> & encodingTable) { if (root != NULL) { if (root->character != -1) { encodingTable[root->character] = encoding; } vector<bool> leftEncoding = encoding; leftEncoding.push_back(false); vector<bool> rightEncoding = encoding; rightEncoding.push_back(true); generateEncodings(root->left,leftEncoding,encodingTable); generateEncodings(root->right,rightEncoding,encodingTable); } } void generateInitialPQueue(int frequencyList[256], priority_queue<huffNode*, vector<huffNode*>, node_comparison> &nodeHeap) { for (int i = 0; i < 256; i++) { if (frequencyList[i] != 0) { huffNode* tempNode; tempNode = new huffNode; tempNode->frequency=frequencyList[i]; tempNode->character = (char)i; tempNode->left = NULL; tempNode->right = NULL; nodeHeap.push(tempNode); } } } void printPQueue(priority_queue<huffNode*, vector<huffNode*>, node_comparison> &nodeHeap) { if (nodeHeap.empty()) { cout << "There's nothing in the heap!" << endl; } while (!nodeHeap.empty()) { huffNode* tempNode; tempNode = nodeHeap.top(); cout << tempNode->character << endl; nodeHeap.pop(); } } void initializeFrequencyList(int frequencyList[256]) { for (int i = 0; i < 256; i++) frequencyList[i] = 0; } void generateFrequencyList(ifstream& fin, int frequencyList[256]) { string line = ""; while (!fin.eof()) { getline(fin,line); for (int i = 0; i < line.length(); i++) { frequencyList[line[i]] += 1; } frequencyList[10] += 1; line = ""; } frequencyList[26] = 1; } void printFrequencyList(int frequencyList[256]) { for (int i = 0; i < 256; i++) { if (frequencyList[i] != 0) { cout << "Character " << (char)i << ": " << frequencyList[i] << endl; } } } void getEncoding(vector<bool> bitString, string &encoding) { for (int i = 0; i < bitString.size(); i++) { encoding += bitString[i]; } } void printEncodings(vector<vector<bool>> encodingTable) { string encoding = ""; for (int i = 0; i < 256; i++) { if (!(encodingTable[i].empty())) { getEncoding(encodingTable[i], encoding); cout << "Character " << (char)i << " encoding: " << encoding << endl; encoding = ""; } } } void generateHuffmanTree(priority_queue <huffNode*, vector<huffNode*>, node_comparison> &heap) { if (heap.size() <= 1) return; else { huffNode *node1, *node2; node1 = new huffNode; node2 = new huffNode; node1 = heap.top(); heap.pop(); node2 = heap.top(); heap.pop(); int totalFreq = node1->frequency + node2->frequency; huffNode* newNode; newNode = new huffNode; newNode->frequency = totalFreq; newNode->character = (char)255; newNode->left = node1; newNode->right = node2; heap.push(newNode); totalFreq = 0; generateHuffmanTree(heap); } } void streamFrequencyList(ofstream &fout) { for (int i = 0; i < 256; i++) { fout << i << endl << frequencyList[i] << endl; } } void convertBuffer(vector<bool> & ogBuffer, bitset<8> &newBuffer) { for (int i = 0; i < ogBuffer.size(); i++) { newBuffer[i] = ogBuffer[i]; } } void checkBuffer(vector<bool> & bitBuffer, vector<bool> & encoding, ofstream &fout) { while (encoding.size() != 0 ) { int availableSpace = 8 - bitBuffer.size(); for (int i = 0; i < availableSpace; i++) { if (!encoding.empty()) { bitBuffer.push_back(encoding[0]); encoding.erase(encoding.begin()); } } if (bitBuffer.size() == 8) { //convert vector<bool> to bitbuffer for output bitset<8> outputBuffer; convertBuffer(bitBuffer, outputBuffer); unsigned char n = outputBuffer.to_ulong(); fout << n; bitBuffer.clear(); } } } void streamEncoding(ifstream &fin, ofstream &fout, vector<bool> & bitBuffer, vector<vector<bool>> encodingTable) { fout << "BIZCOMPRESS" << endl; //Printing "magic number fout << inFileName << endl; streamFrequencyList(fout); //need to output frequency list/table fout << endl; string line = ""; vector<bool> currentEncoding; while (!fin.eof()) { getline(fin, line); for (int i = 0; i < line.length(); i++) { currentEncoding = encodingTable[line[i]]; checkBuffer(bitBuffer, currentEncoding, fout); while (!currentEncoding.empty()) { bitBuffer.push_back(currentEncoding[0]); currentEncoding.erase(currentEncoding.begin()); } } currentEncoding = encodingTable[10]; checkBuffer(bitBuffer, currentEncoding, fout); while (!currentEncoding.empty()) { bitBuffer.push_back(currentEncoding[0]); currentEncoding.erase(currentEncoding.begin()); } line = ""; } currentEncoding = encodingTable[26]; checkBuffer(bitBuffer, currentEncoding, fout); checkBuffer(bitBuffer, currentEncoding, fout); } int main(int argc, char* argv[]) { if (argc != 2) { cout << "Please rerun the program and type a source file to be compressed." << endl; } else { //argv[1] contains the filename to be provided inFileName = argv[1]; ifstream fin(inFileName); if (fin.fail()) cout << "Could not open target file, please rerun the program with a valid text file (.txt)." << endl; else { string outFileName = inFileName.substr(0, inFileName.length() - 3) + "mcp"; //assumes a .txt file (changes output to a .mcp) ofstream fout(outFileName, ios::binary | ios::out); priority_queue<huffNode*, vector<huffNode*>, node_comparison> nodeHeap; vector<bool> startEncoding; vector<vector<bool>> encodingTable(256, vector<bool>(0)); vector<bool> bitBuffer; initializeFrequencyList(frequencyList); generateFrequencyList(fin, frequencyList); fin.close(); //printFrequencyList(frequencyList); generateInitialPQueue(frequencyList, nodeHeap); generateHuffmanTree(nodeHeap); huffNode *root; root = nodeHeap.top(); nodeHeap.pop(); //create the encoding for each leaf node (character) generateEncodings(root, startEncoding, encodingTable); fin.open(inFileName); streamEncoding(fin, fout, bitBuffer, encodingTable); } } cout << "Done." << endl; cin.get(); cin.get(); return 0; }<|endoftext|>
<commit_before>/**********************************************************\ Auto-generated KSenseJSAPI.cpp \**********************************************************/ #include "JSObject.h" #include "variant_list.h" #include "DOM/Document.h" #include "global/config.h" #include <cmath> #include "KSenseJSAPI.h" /////////////////////////////////////////////////////////////////////////////// /// @fn KSenseJSPtr KSenseJSAPI::getPlugin() /// /// @brief Gets a reference to the plugin that was passed in when the object /// was created. If the plugin has already been released then this /// will throw a FB::script_error that will be translated into a /// javascript exception in the page. /////////////////////////////////////////////////////////////////////////////// KSenseJSPtr KSenseJSAPI::getPlugin() { KSenseJSPtr plugin(m_plugin.lock()); if (!plugin) { throw FB::script_error("The plugin is invalid"); } return plugin; } /* Get the number of skeletons tracked by the Kinect. */ int KSenseJSAPI::get_tracked_skeletons_count() { int tracked_skeleton_count = 0; KSenseJSPtr plugin = getPlugin(); SkeletonDataPtr skeleton_data = plugin->getCurrentSkeletonDataPtr(); if ( !skeleton_data ) { return 0; } for ( int i = 0; i < NUI_SKELETON_COUNT; i++ ) { if ( skeleton_data->SkeletonData[i].eTrackingState == NUI_SKELETON_TRACKED ) { tracked_skeleton_count++; } } return tracked_skeleton_count; } /* Get a list of tracking IDs for the currently tracked skeletons. */ FB::VariantList KSenseJSAPI::get_valid_tracking_ids() { KSenseJSPtr plugin = getPlugin(); SkeletonDataPtr skeleton_data = plugin->getCurrentSkeletonDataPtr(); FB::VariantList tracking_ids; if ( !skeleton_data ) { return tracking_ids; } for ( int i = 0; i < NUI_SKELETON_COUNT; i++ ) { if ( skeleton_data->SkeletonData[i].eTrackingState == NUI_SKELETON_TRACKED ) { tracking_ids.push_back(skeleton_data->SkeletonData[i].dwTrackingID); } } return tracking_ids; } /* Get the skeleton data that corresponds to the given tracking ID. If the tracking ID is invalid, throw an error. */ NUI_SKELETON_DATA const* KSenseJSAPI::getDataByTrackingID(const int tracking_id) { KSenseJSPtr plugin = getPlugin(); SkeletonDataPtr skeleton_data = plugin->getCurrentSkeletonDataPtr(); FB::VariantList skeleton_data_output (NUI_SKELETON_POSITION_COUNT, 0); bool found_data = false; if ( !skeleton_data ) { throw FB::script_error("No skeleton data."); } for ( int i = 0; i < NUI_SKELETON_COUNT; i++ ) { if ( skeleton_data->SkeletonData[i].eTrackingState == NUI_SKELETON_TRACKED && skeleton_data->SkeletonData[i].dwTrackingID == tracking_id ) { return &skeleton_data->SkeletonData[i]; } } throw FB::script_error("Invalid tracking ID"); } /* Get the skeleton data that corresponds to the given tracking ID. If the tracking ID is invalid, throw an error. This version checks the given frame for data. */ NUI_SKELETON_DATA const* KSenseJSAPI::getDataByTrackingID(const int tracking_id, SkeletonDataPtr data) { SkeletonDataPtr skeleton_data = data; FB::VariantList skeleton_data_output (NUI_SKELETON_POSITION_COUNT, 0); bool found_data = false; if ( !skeleton_data ) { throw FB::script_error("No skeleton data."); } for ( int i = 0; i < NUI_SKELETON_COUNT; i++ ) { if ( skeleton_data->SkeletonData[i].eTrackingState == NUI_SKELETON_TRACKED && skeleton_data->SkeletonData[i].dwTrackingID == tracking_id ) { return &skeleton_data->SkeletonData[i]; } } throw FB::script_error("Invalid tracking ID"); } /* Format the raw skeleton data and output using the JSAPI. */ FB::VariantList KSenseJSAPI::get_skeleton_data(const int tracking_id) { FB::VariantList skeleton_data_output (NUI_SKELETON_POSITION_COUNT, 0); NUI_SKELETON_DATA const* skeleton_data = getDataByTrackingID(tracking_id); for ( int j = 0; j < NUI_SKELETON_POSITION_COUNT; j++ ) { FB::VariantList position (3,0); position[0] = skeleton_data->SkeletonPositions[j].x; position[1] = skeleton_data->SkeletonPositions[j].y; position[2] = skeleton_data->SkeletonPositions[j].z; skeleton_data_output[j] = position; } return skeleton_data_output; } inline float square(float x) { return x*x; } FB::VariantList KSenseJSAPI::getJointVelocity(const int tracking_id) { FB::VariantList joint_velocity (NUI_SKELETON_POSITION_COUNT, 0); KSenseJSPtr plugin = getPlugin(); SkeletonDataPtr current_ptr = plugin->getCurrentSkeletonDataPtr(); SkeletonDataPtr previous_ptr = plugin->getPreviousSkeletonDataPtr(); NUI_SKELETON_DATA const* current = getDataByTrackingID(tracking_id, current_ptr); NUI_SKELETON_DATA const* previous = getDataByTrackingID(tracking_id, previous_ptr); float v_x, v_y, v_z; for ( int j = 0; j < NUI_SKELETON_POSITION_COUNT; j++ ) { FB::VariantList velocity (4,0); velocity[1] = v_x = current->SkeletonPositions[j].x - previous->SkeletonPositions[j].x; velocity[2] = v_y = current->SkeletonPositions[j].y - previous->SkeletonPositions[j].y; velocity[3] = v_z = current->SkeletonPositions[j].z - previous->SkeletonPositions[j].z; velocity[0] = sqrt(square(v_x)+square(v_y)+square(v_z)); joint_velocity[j] = velocity; } return joint_velocity; } void KSenseJSAPI::new_skeleton_data_event() { fire_newskeletondata(); }<commit_msg>Only get velocity if both previous and current pointers are valid.<commit_after>/**********************************************************\ Auto-generated KSenseJSAPI.cpp \**********************************************************/ #include "JSObject.h" #include "variant_list.h" #include "DOM/Document.h" #include "global/config.h" #include <cmath> #include "KSenseJSAPI.h" /////////////////////////////////////////////////////////////////////////////// /// @fn KSenseJSPtr KSenseJSAPI::getPlugin() /// /// @brief Gets a reference to the plugin that was passed in when the object /// was created. If the plugin has already been released then this /// will throw a FB::script_error that will be translated into a /// javascript exception in the page. /////////////////////////////////////////////////////////////////////////////// KSenseJSPtr KSenseJSAPI::getPlugin() { KSenseJSPtr plugin(m_plugin.lock()); if (!plugin) { throw FB::script_error("The plugin is invalid"); } return plugin; } /* Get the number of skeletons tracked by the Kinect. */ int KSenseJSAPI::get_tracked_skeletons_count() { int tracked_skeleton_count = 0; KSenseJSPtr plugin = getPlugin(); SkeletonDataPtr skeleton_data = plugin->getCurrentSkeletonDataPtr(); if ( !skeleton_data ) { return 0; } for ( int i = 0; i < NUI_SKELETON_COUNT; i++ ) { if ( skeleton_data->SkeletonData[i].eTrackingState == NUI_SKELETON_TRACKED ) { tracked_skeleton_count++; } } return tracked_skeleton_count; } /* Get a list of tracking IDs for the currently tracked skeletons. */ FB::VariantList KSenseJSAPI::get_valid_tracking_ids() { KSenseJSPtr plugin = getPlugin(); SkeletonDataPtr skeleton_data = plugin->getCurrentSkeletonDataPtr(); FB::VariantList tracking_ids; if ( !skeleton_data ) { return tracking_ids; } for ( int i = 0; i < NUI_SKELETON_COUNT; i++ ) { if ( skeleton_data->SkeletonData[i].eTrackingState == NUI_SKELETON_TRACKED ) { tracking_ids.push_back(skeleton_data->SkeletonData[i].dwTrackingID); } } return tracking_ids; } /* Get the skeleton data that corresponds to the given tracking ID. If the tracking ID is invalid, throw an error. */ NUI_SKELETON_DATA const* KSenseJSAPI::getDataByTrackingID(const int tracking_id) { KSenseJSPtr plugin = getPlugin(); SkeletonDataPtr skeleton_data = plugin->getCurrentSkeletonDataPtr(); FB::VariantList skeleton_data_output (NUI_SKELETON_POSITION_COUNT, 0); bool found_data = false; if ( !skeleton_data ) { throw FB::script_error("No skeleton data."); } for ( int i = 0; i < NUI_SKELETON_COUNT; i++ ) { if ( skeleton_data->SkeletonData[i].eTrackingState == NUI_SKELETON_TRACKED && skeleton_data->SkeletonData[i].dwTrackingID == tracking_id ) { return &skeleton_data->SkeletonData[i]; } } throw FB::script_error("Invalid tracking ID"); } /* Get the skeleton data that corresponds to the given tracking ID. If the tracking ID is invalid, throw an error. This version checks the given frame for data. */ NUI_SKELETON_DATA const* KSenseJSAPI::getDataByTrackingID(const int tracking_id, SkeletonDataPtr data) { SkeletonDataPtr skeleton_data = data; FB::VariantList skeleton_data_output (NUI_SKELETON_POSITION_COUNT, 0); bool found_data = false; if ( !skeleton_data ) { throw FB::script_error("No skeleton data."); } for ( int i = 0; i < NUI_SKELETON_COUNT; i++ ) { if ( skeleton_data->SkeletonData[i].eTrackingState == NUI_SKELETON_TRACKED && skeleton_data->SkeletonData[i].dwTrackingID == tracking_id ) { return &skeleton_data->SkeletonData[i]; } } throw FB::script_error("Invalid tracking ID"); } /* Format the raw skeleton data and output using the JSAPI. */ FB::VariantList KSenseJSAPI::get_skeleton_data(const int tracking_id) { FB::VariantList skeleton_data_output (NUI_SKELETON_POSITION_COUNT, 0); NUI_SKELETON_DATA const* skeleton_data = getDataByTrackingID(tracking_id); for ( int j = 0; j < NUI_SKELETON_POSITION_COUNT; j++ ) { FB::VariantList position (3,0); position[0] = skeleton_data->SkeletonPositions[j].x; position[1] = skeleton_data->SkeletonPositions[j].y; position[2] = skeleton_data->SkeletonPositions[j].z; skeleton_data_output[j] = position; } return skeleton_data_output; } //FB::VariantList KSenseJSAPI::getBoneLengths(const int tracking_id) //{ // FB::VariantList bone_lengths_output (NUI_SKELETON_POSITION_COUNT, 0); // NUI_SKELETON_DATA const* skeleton_data = getDataByTrackingID(tracking_id); // // for ( int i = 0; i < NUI_SKELETON_POSITION_COUNT; i++ ) { // //} inline float square(float x) { return x*x; } /* Calculate the velocity since the last frame of skeleton data and send to the javascript. */ FB::VariantList KSenseJSAPI::getJointVelocity(const int tracking_id) { FB::VariantList joint_velocity (NUI_SKELETON_POSITION_COUNT, 0); KSenseJSPtr plugin = getPlugin(); SkeletonDataPtr current_ptr = plugin->getCurrentSkeletonDataPtr(); SkeletonDataPtr previous_ptr = plugin->getPreviousSkeletonDataPtr(); NUI_SKELETON_DATA const* current = getDataByTrackingID(tracking_id, current_ptr); NUI_SKELETON_DATA const* previous = getDataByTrackingID(tracking_id, previous_ptr); float v_x, v_y, v_z; for ( int j = 0; j < NUI_SKELETON_POSITION_COUNT; j++ ) { FB::VariantList velocity (4,0.0f); if (current && previous) { velocity[1] = v_x = current->SkeletonPositions[j].x - previous->SkeletonPositions[j].x; velocity[2] = v_y = current->SkeletonPositions[j].y - previous->SkeletonPositions[j].y; velocity[3] = v_z = current->SkeletonPositions[j].z - previous->SkeletonPositions[j].z; velocity[0] = sqrt(square(v_x)+square(v_y)+square(v_z)); } joint_velocity[j] = velocity; } return joint_velocity; } void KSenseJSAPI::new_skeleton_data_event() { fire_newskeletondata(); }<|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved */ #ifndef _Stroika_Foundation_Containers_SortedCollection_inl_ #define _Stroika_Foundation_Containers_SortedCollection_inl_ #include "../Debug/Assertions.h" #include "Factory/SortedCollection_Factory.h" namespace Stroika { namespace Foundation { namespace Containers { /* ******************************************************************************** ***************************** SortedCollection<T> ****************************** ******************************************************************************** */ template <typename T> inline SortedCollection<T>::SortedCollection () : SortedCollection (std::less<T>{}) { _AssertRepValidType (); } template <typename T> template <typename INORDER_COMPARER, typename ENABLE_IF_IS_COMPARER> inline SortedCollection<T>::SortedCollection (const INORDER_COMPARER& inorderComparer, ENABLE_IF_IS_COMPARER*) : inherited (move (Factory::SortedCollection_Factory<T, INORDER_COMPARER> (inorderComparer) ())) { static_assert (Common::IsInOrderComparer<INORDER_COMPARER> (), "InOrder comparer required with SortedCollection"); _AssertRepValidType (); } template <typename T> inline SortedCollection<T>::SortedCollection (const _SortedCollectionRepSharedPtr& src) noexcept : inherited (src) { RequireNotNull (src); _AssertRepValidType (); } template <typename T> inline SortedCollection<T>::SortedCollection (_SortedCollectionRepSharedPtr&& src) noexcept : inherited ((RequireNotNull (src), move (src))) { _AssertRepValidType (); } template <typename T> inline SortedCollection<T>::SortedCollection (const initializer_list<T>& src) : SortedCollection () { this->AddAll (src); _AssertRepValidType (); } template <typename T> inline SortedCollection<T>::SortedCollection (const InOrderComparerType& inOrderComparer, const initializer_list<T>& src) : SortedCollection (inOrderComparer) { this->AddAll (src); _AssertRepValidType (); } template <typename T> template <typename CONTAINER_OF_T, typename ENABLE_IF> inline SortedCollection<T>::SortedCollection (const CONTAINER_OF_T& src) : SortedCollection () { this->AddAll (src); _AssertRepValidType (); } template <typename T> template <typename CONTAINER_OF_T, typename ENABLE_IF> inline SortedCollection<T>::SortedCollection (const InOrderComparerType& inOrderComparer, const CONTAINER_OF_T& src) : SortedCollection (inOrderComparer) { this->AddAll (src); _AssertRepValidType (); } template <typename T> template <typename COPY_FROM_ITERATOR_OF_T> inline SortedCollection<T>::SortedCollection (COPY_FROM_ITERATOR_OF_T start, COPY_FROM_ITERATOR_OF_T end) : SortedCollection () { this->AddAll (start, end); _AssertRepValidType (); } template <typename T> template <typename COPY_FROM_ITERATOR_OF_T> inline SortedCollection<T>::SortedCollection (const InOrderComparerType& inOrderComparer, COPY_FROM_ITERATOR_OF_T start, COPY_FROM_ITERATOR_OF_T end) : SortedCollection (inOrderComparer) { this->AddAll (start, end); _AssertRepValidType (); } template <typename T> inline void SortedCollection<T>::_AssertRepValidType () const { #if qDebug _SafeReadRepAccessor<_IRep>{this}; #endif } } } } #endif /* _Stroika_Foundation_Containers_SortedCollection_inl_ */ <commit_msg>SortedCollection more overloads for inorder comparer<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved */ #ifndef _Stroika_Foundation_Containers_SortedCollection_inl_ #define _Stroika_Foundation_Containers_SortedCollection_inl_ #include "../Debug/Assertions.h" #include "Factory/SortedCollection_Factory.h" namespace Stroika { namespace Foundation { namespace Containers { /* ******************************************************************************** ***************************** SortedCollection<T> ****************************** ******************************************************************************** */ template <typename T> inline SortedCollection<T>::SortedCollection () : SortedCollection (std::less<T>{}) { _AssertRepValidType (); } template <typename T> template <typename INORDER_COMPARER, typename ENABLE_IF_IS_COMPARER> inline SortedCollection<T>::SortedCollection (const INORDER_COMPARER& inorderComparer, ENABLE_IF_IS_COMPARER*) : inherited (move (Factory::SortedCollection_Factory<T, INORDER_COMPARER> (inorderComparer) ())) { static_assert (Common::IsInOrderComparer<INORDER_COMPARER> (), "InOrder comparer required with SortedCollection"); _AssertRepValidType (); } template <typename T> inline SortedCollection<T>::SortedCollection (const _SortedCollectionRepSharedPtr& src) noexcept : inherited (src) { RequireNotNull (src); _AssertRepValidType (); } template <typename T> inline SortedCollection<T>::SortedCollection (_SortedCollectionRepSharedPtr&& src) noexcept : inherited ((RequireNotNull (src), move (src))) { _AssertRepValidType (); } template <typename T> inline SortedCollection<T>::SortedCollection (const initializer_list<T>& src) : SortedCollection () { this->AddAll (src); _AssertRepValidType (); } template <typename T> inline SortedCollection<T>::SortedCollection (const InOrderComparerType& inOrderComparer, const initializer_list<T>& src) : SortedCollection (inOrderComparer) { this->AddAll (src); _AssertRepValidType (); } template <typename T> template <typename CONTAINER_OF_T, typename ENABLE_IF> inline SortedCollection<T>::SortedCollection (const CONTAINER_OF_T& src) : SortedCollection () { this->AddAll (src); _AssertRepValidType (); } template <typename T> template <typename CONTAINER_OF_T, typename ENABLE_IF> inline SortedCollection<T>::SortedCollection (const InOrderComparerType& inOrderComparer, const CONTAINER_OF_T& src) : SortedCollection (inOrderComparer) { this->AddAll (src); _AssertRepValidType (); } template <typename T> template <typename COPY_FROM_ITERATOR_OF_T> inline SortedCollection<T>::SortedCollection (COPY_FROM_ITERATOR_OF_T start, COPY_FROM_ITERATOR_OF_T end) : SortedCollection () { this->AddAll (start, end); _AssertRepValidType (); } template <typename T> template <typename COPY_FROM_ITERATOR_OF_T> inline SortedCollection<T>::SortedCollection (const InOrderComparerType& inOrderComparer, COPY_FROM_ITERATOR_OF_T start, COPY_FROM_ITERATOR_OF_T end) : SortedCollection (inOrderComparer) { this->AddAll (start, end); _AssertRepValidType (); } template <typename T> inline void SortedCollection<T>::_AssertRepValidType () const { #if qDebug _SafeReadRepAccessor<_IRep>{this}; #endif } } } } #endif /* _Stroika_Foundation_Containers_SortedCollection_inl_ */ <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved */ #ifndef _Stroika_Foundation_Traversal_DelegatedIterator_inl_ #define _Stroika_Foundation_Traversal_DelegatedIterator_inl_ #include "../Debug/Assertions.h" namespace Stroika { namespace Foundation { namespace Traversal { /* ******************************************************************************** *********************** DelegatedIterator<T, EXTRA_DATA>::Rep ****************** ******************************************************************************** */ template <typename T, typename EXTRA_DATA> DelegatedIterator<T, EXTRA_DATA>::Rep::Rep (const Iterator<T>& delegateTo, const EXTRA_DATA& extraData) : fDelegateTo (delegateTo) , fExtraData (extraData) { } template <typename T, typename EXTRA_DATA> typename Iterator<T>::SharedIRepPtr DelegatedIterator<T, EXTRA_DATA>::Rep::Clone () const { return SharedIRepPtr (new Rep (*this)); } template <typename T, typename EXTRA_DATA> void DelegatedIterator<T, EXTRA_DATA>::Rep::More (Memory::Optional<T>* result, bool advance) { fDelegateTo.GetRep ().More (result, advance); } template <typename T, typename EXTRA_DATA> bool DelegatedIterator<T, EXTRA_DATA>::Rep::Equals (const IRep* rhs) const { return fDelegateTo.GetRep ().Equals (rhs); } template <typename T> DelegatedIterator<T, void>::Rep::Rep (const Iterator<T>& delegateTo) : fDelegateTo (delegateTo) { } /* ******************************************************************************** *********************** DelegatedIterator<T, EXTRA_DATA> *********************** ******************************************************************************** */ template <typename T, typename EXTRA_DATA> DelegatedIterator<T, EXTRA_DATA>::DelegatedIterator (const Iterator<T>& delegateTo, const EXTRA_DATA& extraData) : Iterator<T> (SharedIRepPtr (new Rep (delegateTo, extraData))) { } } } } #endif /* _Stroika_Foundation_Traversal_DelegatedIterator_inl_ */ <commit_msg>minor tweaks for DelegatedIterator/gcc<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2013. All rights reserved */ #ifndef _Stroika_Foundation_Traversal_DelegatedIterator_inl_ #define _Stroika_Foundation_Traversal_DelegatedIterator_inl_ #include "../Debug/Assertions.h" namespace Stroika { namespace Foundation { namespace Traversal { /* ******************************************************************************** *********************** DelegatedIterator<T, EXTRA_DATA>::Rep ****************** ******************************************************************************** */ template <typename T, typename EXTRA_DATA> DelegatedIterator<T, EXTRA_DATA>::Rep::Rep (const Iterator<T>& delegateTo, const EXTRA_DATA& extraData) : fDelegateTo (delegateTo) , fExtraData (extraData) { } template <typename T, typename EXTRA_DATA> typename Iterator<T>::SharedIRepPtr DelegatedIterator<T, EXTRA_DATA>::Rep::Clone () const { return SharedIRepPtr (new Rep (*this)); } template <typename T, typename EXTRA_DATA> void DelegatedIterator<T, EXTRA_DATA>::Rep::More (Memory::Optional<T>* result, bool advance) { fDelegateTo.GetRep ().More (result, advance); } template <typename T, typename EXTRA_DATA> bool DelegatedIterator<T, EXTRA_DATA>::Rep::Equals (const IRep* rhs) const { return fDelegateTo.GetRep ().Equals (rhs); } template <typename T> DelegatedIterator<T, void>::Rep::Rep (const Iterator<T>& delegateTo) : fDelegateTo (delegateTo) { } /* ******************************************************************************** *********************** DelegatedIterator<T, EXTRA_DATA> *********************** ******************************************************************************** */ template <typename T, typename EXTRA_DATA> DelegatedIterator<T, EXTRA_DATA>::DelegatedIterator (const Iterator<T>& delegateTo, const EXTRA_DATA& extraData) : Iterator<T> (typename Iterator<T>::SharedIRepPtr (new Rep (delegateTo, extraData))) { } } } } #endif /* _Stroika_Foundation_Traversal_DelegatedIterator_inl_ */ <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) CS Systemes d'information. All rights reserved. See CSCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "otbBandMathImageFilter.h" #include "itkComplexToPhaseImageFilter.h" #include "itkComplexToModulusImageFilter.h" #include <itkMacro.h> namespace otb { // Application class is defined in Wrapper namespace. namespace Wrapper { // ComputeModulusAndPhase class is derived from Application class. class ComputeModulusAndPhase: public Application { public: // Class declaration is followed by ITK public types for the class, the superclass and smart pointers. typedef ComputeModulusAndPhase Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Standard macro */ itkNewMacro (Self); itkTypeMacro(ComputeModulusAndPhase, otb::Application); //typedefs for the application typedef otb::BandMathImageFilter<FloatImageType> BandMathType; typedef itk::ComplexToModulusImageFilter<ComplexFloatImageType, FloatImageType> ModulusFilterType; typedef itk::ComplexToPhaseImageFilter<ComplexFloatImageType, FloatImageType> PhaseFilterType; private: void DoInit() { SetName("ComputeModulusAndPhase"); SetDescription("This application computes the modulus and the phase of a complex SAR data."); SetDocName("Compute Modulus And Phase"); SetDocLongDescription("This application computes the modulus and the phase of a complex SAR data. This complex SAR data could be provided as a monoband complex pixel type image or a 2 bands real pixel type image or two monobands (first one real part and second one imaginary part) real pixel type images."); SetDocLimitations("None"); SetDocAuthors("Alexia Mondot ([email protected]) and Mickael Savinaud ([email protected])"); SetDocSeeAlso(" "); AddDocTag(Tags::SAR); // Choice of number of entries AddParameter(ParameterType_Choice, "nbinput", "Number Of inputs"); SetParameterDescription( "nbinput", "Choice about the number of input files used to store the real and imaginary part of the SAR image"); AddChoice("nbinput.one", "One input"); SetParameterDescription("nbinput.one", "One input: one band (complex pixel type) SAR image or two bands (real complex type) SAR image."); AddChoice("nbinput.two", "Two inputs"); SetParameterDescription("nbinput.two", "Two inputs: the first one is considered as real part and the second one as the imaginary part of the SAR image."); // Inputs // Real part of a complex image AddParameter(ParameterType_InputImage, "nbinput.two.re", "Real part input"); SetParameterDescription("nbinput.two.re", "Image file with real part of the SAR data."); // Imaginary part of a complex image AddParameter(ParameterType_InputImage, "nbinput.two.im", "Imaginary part input"); SetParameterDescription("nbinput.two.im", "Image file with imaginary part of the SAR data."); // Complex image AddParameter(ParameterType_ComplexInputImage, "nbinput.one.in", "Input image"); SetParameterDescription("nbinput.one.in", "Image file with SAR data."); // Outputs AddParameter(ParameterType_OutputImage, "mod", "Modulus"); SetParameterDescription("mod", "Modulus of the input: sqrt(real*real + imag*imag)."); AddParameter(ParameterType_OutputImage, "pha", "Phase"); SetParameterDescription("pha", "Phase of the input: atan2(imag, real)."); AddRAMParameter(); // Doc example parameter settings SetDocExampleParameterValue("nbinput.one.in", "monobandComplexFloat.tif"); SetDocExampleParameterValue("mod", "modulus.tif"); SetDocExampleParameterValue("pha", "phase.tif"); } // DoUpdateParameters() is called as soon as a parameter value change. void DoUpdateParameters() { // If one entry is choosen, disabled the re and im part // else disable complex const std::string numberOfInputs = GetParameterString("nbinput"); if (numberOfInputs == "one") { MandatoryOn("nbinput.one.in"); MandatoryOff("nbinput.two.re"); DisableParameter("nbinput.two.re"); MandatoryOff("nbinput.two.im"); DisableParameter("nbinput.two.im"); EnableParameter("nbinput.one.in"); } else { MandatoryOff("nbinput.one.in"); DisableParameter("nbinput.one.in"); MandatoryOn("nbinput.two.re"); MandatoryOn("nbinput.two.im"); EnableParameter("nbinput.two.re"); EnableParameter("nbinput.two.im"); } } // DoExecute() contains the application core. void DoExecute() { m_modulus2 = BandMathType::New(); m_phase2 = BandMathType::New(); m_modulus1 = ModulusFilterType::New(); m_phase1 = PhaseFilterType::New(); const std::string numberOfInputs = GetParameterString("nbinput"); if (numberOfInputs == "one") { // Get the input image ComplexFloatImageType::Pointer inImage = this->GetParameterComplexFloatImage("nbinput.one.in"); m_modulus1->SetInput(inImage); m_phase1->SetInput(inImage); SetParameterOutputImage("mod", m_modulus1->GetOutput() ); SetParameterOutputImage("pha", m_phase1->GetOutput()); } else if (numberOfInputs == "two") { // Get the input image re FloatImageType::Pointer inImageRe = this->GetParameterFloatImage("nbinput.two.re"); // Get the input image im FloatImageType::Pointer inImageIm = this->GetParameterFloatImage("nbinput.two.im"); m_modulus2->SetNthInput(0, inImageRe,"real"); m_modulus2->SetNthInput(1, inImageIm,"imag"); m_modulus2->SetExpression("sqrt(real * real + imag * imag)"); m_phase2->SetNthInput(0, inImageRe,"real"); m_phase2->SetNthInput(1, inImageIm,"imag"); m_phase2->SetExpression("atan2( imag , real )"); SetParameterOutputImage("mod", m_modulus2->GetOutput() ); SetParameterOutputImage("pha", m_phase2->GetOutput()); } } BandMathType::Pointer m_modulus2; BandMathType::Pointer m_phase2; ModulusFilterType::Pointer m_modulus1; PhaseFilterType::Pointer m_phase1; } ;} // namespace Wrapper } // namespace otb OTB_APPLICATION_EXPORT(otb::Wrapper::ComputeModulusAndPhase) <commit_msg>DOC: Proof read ComputeModulusAndPhase doc<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) CS Systemes d'information. All rights reserved. See CSCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "otbBandMathImageFilter.h" #include "itkComplexToPhaseImageFilter.h" #include "itkComplexToModulusImageFilter.h" #include <itkMacro.h> namespace otb { // Application class is defined in Wrapper namespace. namespace Wrapper { // ComputeModulusAndPhase class is derived from Application class. class ComputeModulusAndPhase: public Application { public: // Class declaration is followed by ITK public types for the class, the superclass and smart pointers. typedef ComputeModulusAndPhase Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Standard macro */ itkNewMacro (Self); itkTypeMacro(ComputeModulusAndPhase, otb::Application); //typedefs for the application typedef otb::BandMathImageFilter<FloatImageType> BandMathType; typedef itk::ComplexToModulusImageFilter<ComplexFloatImageType, FloatImageType> ModulusFilterType; typedef itk::ComplexToPhaseImageFilter<ComplexFloatImageType, FloatImageType> PhaseFilterType; private: void DoInit() { SetName("ComputeModulusAndPhase"); SetDescription("This application computes the modulus and the phase of a complex SAR image."); SetDocName("Compute Modulus And Phase"); SetDocLongDescription("This application computes the modulus and the phase of a complex SAR image. This complex SAR image can be provided as either: a monoband image with complex pixels, a 2 bands image with real and imaginary channels, or 2 monoband images (first one real part and second one imaginary part)"); SetDocLimitations("None"); SetDocAuthors("Alexia Mondot ([email protected]) and Mickael Savinaud ([email protected])"); SetDocSeeAlso(" "); AddDocTag(Tags::SAR); // Choice of number of entries AddParameter(ParameterType_Choice, "nbinput", "Number Of inputs"); SetParameterDescription( "nbinput", "Choice about the number of input files used to store the real and imaginary part of the SAR image"); AddChoice("nbinput.one", "One input"); SetParameterDescription("nbinput.one", "One input: one band (complex pixel type) SAR image or two bands (real complex type) SAR image."); AddChoice("nbinput.two", "Two inputs"); SetParameterDescription("nbinput.two", "Two inputs: the first one is considered as real part and the second one as the imaginary part of the SAR image."); // Inputs // Real part of a complex image AddParameter(ParameterType_InputImage, "nbinput.two.re", "Real part input"); SetParameterDescription("nbinput.two.re", "Image file with real part of the SAR data."); // Imaginary part of a complex image AddParameter(ParameterType_InputImage, "nbinput.two.im", "Imaginary part input"); SetParameterDescription("nbinput.two.im", "Image file with imaginary part of the SAR data."); // Complex image AddParameter(ParameterType_ComplexInputImage, "nbinput.one.in", "Input image"); SetParameterDescription("nbinput.one.in", "Image file with SAR data."); // Outputs AddParameter(ParameterType_OutputImage, "mod", "Modulus"); SetParameterDescription("mod", "Modulus of the input: sqrt(real*real + imag*imag)."); AddParameter(ParameterType_OutputImage, "pha", "Phase"); SetParameterDescription("pha", "Phase of the input: atan2(imag, real)."); AddRAMParameter(); // Doc example parameter settings SetDocExampleParameterValue("nbinput.one.in", "monobandComplexFloat.tif"); SetDocExampleParameterValue("mod", "modulus.tif"); SetDocExampleParameterValue("pha", "phase.tif"); } // DoUpdateParameters() is called as soon as a parameter value change. void DoUpdateParameters() { // If one entry is choosen, disabled the re and im part // else disable complex const std::string numberOfInputs = GetParameterString("nbinput"); if (numberOfInputs == "one") { MandatoryOn("nbinput.one.in"); MandatoryOff("nbinput.two.re"); DisableParameter("nbinput.two.re"); MandatoryOff("nbinput.two.im"); DisableParameter("nbinput.two.im"); EnableParameter("nbinput.one.in"); } else { MandatoryOff("nbinput.one.in"); DisableParameter("nbinput.one.in"); MandatoryOn("nbinput.two.re"); MandatoryOn("nbinput.two.im"); EnableParameter("nbinput.two.re"); EnableParameter("nbinput.two.im"); } } // DoExecute() contains the application core. void DoExecute() { m_modulus2 = BandMathType::New(); m_phase2 = BandMathType::New(); m_modulus1 = ModulusFilterType::New(); m_phase1 = PhaseFilterType::New(); const std::string numberOfInputs = GetParameterString("nbinput"); if (numberOfInputs == "one") { // Get the input image ComplexFloatImageType::Pointer inImage = this->GetParameterComplexFloatImage("nbinput.one.in"); m_modulus1->SetInput(inImage); m_phase1->SetInput(inImage); SetParameterOutputImage("mod", m_modulus1->GetOutput() ); SetParameterOutputImage("pha", m_phase1->GetOutput()); } else if (numberOfInputs == "two") { // Get the input image re FloatImageType::Pointer inImageRe = this->GetParameterFloatImage("nbinput.two.re"); // Get the input image im FloatImageType::Pointer inImageIm = this->GetParameterFloatImage("nbinput.two.im"); m_modulus2->SetNthInput(0, inImageRe,"real"); m_modulus2->SetNthInput(1, inImageIm,"imag"); m_modulus2->SetExpression("sqrt(real * real + imag * imag)"); m_phase2->SetNthInput(0, inImageRe,"real"); m_phase2->SetNthInput(1, inImageIm,"imag"); m_phase2->SetExpression("atan2( imag , real )"); SetParameterOutputImage("mod", m_modulus2->GetOutput() ); SetParameterOutputImage("pha", m_phase2->GetOutput()); } } BandMathType::Pointer m_modulus2; BandMathType::Pointer m_phase2; ModulusFilterType::Pointer m_modulus1; PhaseFilterType::Pointer m_phase1; } ;} // namespace Wrapper } // namespace otb OTB_APPLICATION_EXPORT(otb::Wrapper::ComputeModulusAndPhase) <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "itkFilterWatcher.h" #include "itkGaussianImageSource.h" int itkGaussianImageSourceTest(int, char* [] ) { // This can be changed! const unsigned int dim = 3; // Image typedef typedef itk::Image< unsigned char, dim > ImageType; // Create a gaussian image source typedef itk::GaussianImageSource< ImageType > GaussianSourceType; GaussianSourceType::Pointer pSource = GaussianSourceType::New(); FilterWatcher watcher(pSource, "pSource"); ImageType::SpacingValueType spacing[] = { 1.2f, 1.3f, 1.4f }; ImageType::PointValueType origin[] = { 1.0f, 4.0f, 2.0f }; ImageType::SizeValueType size[] = { 130, 150, 120 }; GaussianSourceType::ArrayType mean; mean[0] = size[0]/2.0f + origin[0]; mean[1] = size[1]/2.0f + origin[1]; mean[2] = size[2]/2.0f + origin[2]; GaussianSourceType::ArrayType sigma; sigma[0] = 25.0f; sigma[1] = 35.0f; sigma[2] = 55.0f; pSource->SetSize( size ); pSource->SetOrigin( origin ); pSource->SetSpacing( spacing ); pSource->SetMean( mean ); pSource->SetSigma( sigma ); // Test the get macros as well (booorrring...) pSource->GetSize(); pSource->GetSpacing(); pSource->GetOrigin(); pSource->GetDirection(); pSource->GetScale(); pSource->GetNormalized(); pSource->GetSigma(); pSource->GetMean(); // Test the get/set parameters GaussianSourceType::ParametersType params = pSource->GetParameters(); if ( params.GetSize() != 7 ) { std::cerr << "Incorrect number of parameters. Expected 7, got " << params.GetSize() << "." << std::endl; return EXIT_FAILURE; } if ( params[0] != sigma[0] || params[1] != sigma[1] || params[2] != sigma[2] ) { std::cerr << "Parameters have incorrect sigma value." << std::endl; return EXIT_FAILURE; } if ( params[3] != mean[0] || params[4] != mean[1] || params[5] != mean[2] ) { std::cerr << "Parameters have incorrect mean value." << std::endl; return EXIT_FAILURE; } if ( params[6] != pSource->GetScale() ) { std::cerr << "Parameters have incorrect scale value." << std::endl; return EXIT_FAILURE; } params[0] = 12.0; params[1] = 13.0; params[2] = 14.0; params[3] = 22.0; params[4] = 32.0; params[5] = 42.0; params[6] = 55.5; pSource->SetParameters( params ); if ( pSource->GetSigma()[0] != params[0] || pSource->GetSigma()[1] != params[1] || pSource->GetSigma()[2] != params[2] ) { std::cerr << "Sigma disagrees with parameters array." << std::endl; std::cerr << "Sigma: " << pSource->GetSigma() << ", parameters: [" << params[0] << ", " << params[1] << ", " << params[2] << "]" << std::endl; return EXIT_FAILURE; } if ( pSource->GetMean()[0] != params[3] || pSource->GetMean()[1] != params[4] || pSource->GetMean()[2] != params[5] ) { std::cerr << "Mean disagrees with parameters array." << std::endl; std::cerr << "Mean: " << pSource->GetMean() << ", parameters: [" << params[3] << ", " << params[4] << ", " << params[5] << "]" << std::endl; return EXIT_FAILURE; } if ( pSource->GetScale() != params[6] ) { std::cerr << "Scale disagrees with parameters array." << std::endl; std::cerr << "Scale: " << pSource->GetScale() << ", parameters: " << params[6] << std::endl; return EXIT_FAILURE; } // Get the output of the source ImageType::Pointer pImage = pSource->GetOutput(); // Run the pipeline pSource->Update(); std::cout << pImage << std::endl; return EXIT_SUCCESS; } <commit_msg>STYLE: Improve style in itkGaussianImageSourceTest.<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "itkFilterWatcher.h" #include "itkGaussianImageSource.h" #include "itkTestingMacros.h" int itkGaussianImageSourceTest(int, char* [] ) { // This can be changed! const unsigned int Dimension = 3; typedef unsigned char PixelType; // Image typedef typedef itk::Image< PixelType, Dimension > ImageType; // Create a gaussian image source typedef itk::GaussianImageSource< ImageType > GaussianSourceType; GaussianSourceType::Pointer source = GaussianSourceType::New(); FilterWatcher watcher(source, "source"); ImageType::SpacingValueType spacing[] = { 1.2f, 1.3f, 1.4f }; ImageType::PointValueType origin[] = { 1.0f, 4.0f, 2.0f }; ImageType::SizeValueType size[] = { 130, 150, 120 }; GaussianSourceType::ArrayType mean; mean[0] = size[0]/2.0f + origin[0]; mean[1] = size[1]/2.0f + origin[1]; mean[2] = size[2]/2.0f + origin[2]; GaussianSourceType::ArrayType sigma; sigma[0] = 25.0f; sigma[1] = 35.0f; sigma[2] = 55.0f; source->SetSize( size ); source->SetOrigin( origin ); source->SetSpacing( spacing ); source->SetMean( mean ); source->SetSigma( sigma ); // Test the get macros as well (booorrring...) source->GetSize(); source->GetSpacing(); source->GetOrigin(); source->GetDirection(); source->GetScale(); source->GetNormalized(); source->GetSigma(); source->GetMean(); // Test the get/set parameters GaussianSourceType::ParametersType params = source->GetParameters(); if ( params.GetSize() != 7 ) { std::cerr << "Incorrect number of parameters. Expected 7, got " << params.GetSize() << "." << std::endl; return EXIT_FAILURE; } if ( params[0] != sigma[0] || params[1] != sigma[1] || params[2] != sigma[2] ) { std::cerr << "Parameters have incorrect sigma value." << std::endl; return EXIT_FAILURE; } if ( params[3] != mean[0] || params[4] != mean[1] || params[5] != mean[2] ) { std::cerr << "Parameters have incorrect mean value." << std::endl; return EXIT_FAILURE; } if ( params[6] != source->GetScale() ) { std::cerr << "Parameters have incorrect scale value." << std::endl; return EXIT_FAILURE; } params[0] = 12.0; params[1] = 13.0; params[2] = 14.0; params[3] = 22.0; params[4] = 32.0; params[5] = 42.0; params[6] = 55.5; source->SetParameters( params ); if ( source->GetSigma()[0] != params[0] || source->GetSigma()[1] != params[1] || source->GetSigma()[2] != params[2] ) { std::cerr << "Sigma disagrees with parameters array." << std::endl; std::cerr << "Sigma: " << source->GetSigma() << ", parameters: [" << params[0] << ", " << params[1] << ", " << params[2] << "]" << std::endl; return EXIT_FAILURE; } if ( source->GetMean()[0] != params[3] || source->GetMean()[1] != params[4] || source->GetMean()[2] != params[5] ) { std::cerr << "Mean disagrees with parameters array." << std::endl; std::cerr << "Mean: " << source->GetMean() << ", parameters: [" << params[3] << ", " << params[4] << ", " << params[5] << "]" << std::endl; return EXIT_FAILURE; } if ( source->GetScale() != params[6] ) { std::cerr << "Scale disagrees with parameters array." << std::endl; std::cerr << "Scale: " << source->GetScale() << ", parameters: " << params[6] << std::endl; return EXIT_FAILURE; } // Get the output of the source ImageType::ConstPointer image = source->GetOutput(); // Run the pipeline TRY_EXPECT_NO_EXCEPTION( source->Update() ); // Exercise the print method std::cout << image << std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <string> #include <fstream> #include <sstream> using namespace std; vector<string> split(string str, char delimiter) { vector<string> internal; stringstream ss(str); string tok; while (getline(ss, tok, delimiter)) { internal.push_back(tok); } return internal; } int addIncludeHeader(string name, char* path) { ifstream iFile(path); string str; string fileContent = ""; if (!iFile) return 1; while (!iFile.eof()) { getline(iFile, str); str += "\n"; fileContent += str; str = ""; } iFile.close(); vector<string> befor = split(fileContent, '\n'); vector<string> after; for (unsigned int i = 0; i < befor.size(); i++) { after.push_back(befor.at(i)); if (befor.at(i) == "//HEADER") { after.push_back("#include <scripts/" + name + ".hpp>"); } } fileContent = ""; for (unsigned int i = 0; i < after.size(); i++) { fileContent += after.at(i) + "\n"; } //cout << fileContent << endl; ofstream oFile(path); oFile.write(fileContent.c_str(), fileContent.size()); oFile.close(); return 0; } int addEngineRegister(string name, char* path) { ifstream iFile(path); string str; string fileContent = ""; if (!iFile) return 1; while (!iFile.eof()) { getline(iFile, str); str += "\n"; fileContent += str; str = ""; } iFile.close(); vector<string> befor = split(fileContent, '\n'); vector<string> after; for (unsigned int i = 0; i < befor.size(); i++) { after.push_back(befor.at(i)); if (befor.at(i) == "//ENGINE_REGISTER") { string lowerName = name; for (unsigned int i = 0; i < name.size(); i++) lowerName[i] = tolower(name[i]); after.push_back(" game::" + name + "* " + lowerName + " new game::" + name + "();"); after.push_back(" fabric::Engine::vRegisteredGameObjects->push_back(" + lowerName + ");"); after.push_back(" "); } } fileContent = ""; for (unsigned int i = 0; i < after.size(); i++) { fileContent += after.at(i) + "\n"; } //cout << fileContent; ofstream oFile(path); oFile.write(fileContent.c_str(), fileContent.size()); oFile.close(); return 0; } int addSourceFile(string name, string path) { ofstream oFile(path + name + ".cpp"); string fileContent = ""; fileContent += "#include <engine.hpp>\n"; fileContent += "#include <gameobject.hpp>\n"; fileContent += "#include <behavior.hpp>\n"; fileContent += "\n"; fileContent += "using namespace fabric;\n"; fileContent += "\n"; fileContent += "namespace game{\n"; fileContent += " class " + name + " : public GameObject{\n"; fileContent += " public:\n"; fileContent += " // Use for initialization\n"; fileContent += " void setup(){\n"; fileContent += "\n"; fileContent += " }\n"; fileContent += "\n"; fileContent += " // Use for frame by frame logic\n"; fileContent += " void update (){\n"; fileContent += "\n"; fileContent += " }\n"; fileContent += " };\n"; fileContent += "}"; oFile.write(fileContent.c_str(), fileContent.size()); oFile.close(); return 0; } void waitForExit() { string input; do { cout << "Input anything to exit: "; cin >> input; } while (input == ""); } int main() { string input; int lhs; cout << "Welcome to the automated script creation tool" << endl; cout << "Is this tool beeing ran from the 'tools' directory in your project or" << endl; cout << "has been launched from the editor? [yes | no]: "; cin >> input; if (input == "no") { cout << "Please launched the tool from the 'tools' directory or the editor" << endl; waitForExit(); return 1; } cout << endl; cout << "Please enter the name of your script (no exstenion): "; cin >> input; cout << "Thank You"; cout << endl; lhs = addIncludeHeader(input, "../../game/game.cpp"); if (lhs == 0) cout << "... Include headers have been created in 'game.cpp'" << endl; else cout << "... Include header could not be written to 'game.cpp'" << endl; lhs = addEngineRegister(input, "../../game/game.cpp"); if (lhs == 0) cout << "... Engine register have been created in 'game.cpp'" << endl; else cout << "... Engine register could not be written to 'game.cpp'" << endl; lhs = addSourceFile(input, "../../game/scripts/source/"); if (lhs == 0) cout << "... .cpp file has been created in 'scripts/source'" << endl; else cout << "... .cpp file could not be created in'scripts/source'" << endl; cout << endl; cout << "Script has been added, your welcome" << endl; waitForExit(); return 0; }<commit_msg>Added automatic .hpp creation<commit_after>#include <iostream> #include <vector> #include <string> #include <fstream> #include <sstream> using namespace std; vector<string> split(string str, char delimiter) { vector<string> internal; stringstream ss(str); string tok; while (getline(ss, tok, delimiter)) { internal.push_back(tok); } return internal; } int addIncludeHeader(string name, char* path) { ifstream iFile(path); string str; string fileContent = ""; if (!iFile) return 1; while (!iFile.eof()) { getline(iFile, str); str += "\n"; fileContent += str; str = ""; } iFile.close(); vector<string> befor = split(fileContent, '\n'); vector<string> after; for (unsigned int i = 0; i < befor.size(); i++) { after.push_back(befor.at(i)); if (befor.at(i) == "//HEADER") { after.push_back("#include \"scripts/header/" + name + ".hpp\" "); } } fileContent = ""; for (unsigned int i = 0; i < after.size(); i++) { fileContent += after.at(i) + "\n"; } //cout << fileContent << endl; ofstream oFile(path); oFile.write(fileContent.c_str(), fileContent.size()); oFile.close(); return 0; } int addEngineRegister(string name, char* path) { ifstream iFile(path); string str; string fileContent = ""; if (!iFile) return 1; while (!iFile.eof()) { getline(iFile, str); str += "\n"; fileContent += str; str = ""; } iFile.close(); vector<string> befor = split(fileContent, '\n'); vector<string> after; for (unsigned int i = 0; i < befor.size(); i++) { after.push_back(befor.at(i)); if (befor.at(i) == "//ENGINE_REGISTER") { string lowerName = name; for (unsigned int i = 0; i < name.size(); i++) lowerName[i] = tolower(name[i]); after.push_back(" game::" + name + "* " + lowerName + " = new game::" + name + "();"); after.push_back(" fabric::Engine::vRegisteredGameObjects->push_back(" + lowerName + ");"); after.push_back(" "); } } fileContent = ""; for (unsigned int i = 0; i < after.size(); i++) { fileContent += after.at(i) + "\n"; } //cout << fileContent; ofstream oFile(path); oFile.write(fileContent.c_str(), fileContent.size()); oFile.close(); return 0; } int addSourceFile(string name, string path) { ofstream oFile(path + name + ".cpp"); if (!oFile) return 1; string fileContent; fileContent += "#include \"../header/" + name + ".hpp\"\n"; fileContent += "#include <engine.hpp>\n"; fileContent += "#include <gameobject.hpp>\n"; fileContent += "#include <behavior.hpp>\n"; fileContent += "\n"; fileContent += "using namespace fabric;\n"; fileContent += "\n"; fileContent += "namespace game{\n"; fileContent += "\n"; fileContent += "void " + name + "::setup(){\n"; fileContent += " // Use this for inital setup\n"; fileContent += " }\n"; fileContent += "void " + name + "::update(){\n"; fileContent += " // Use this for frame by frame logic\n"; fileContent += " }\n"; fileContent += "}"; oFile.write(fileContent.c_str(), fileContent.size()); oFile.close(); return 0; } int addHeaderFile(string name, string path) { ofstream oFile(path + name + ".hpp"); if (!oFile) return 1; string upperName = name; for (unsigned int i = 0; i < name.size(); i++) upperName[i] = toupper(name[i]); string fileContent = ""; fileContent += "#ifndef " + upperName + "_HPP" + "\n"; fileContent += "#define " + upperName + "_HPP" + "\n"; fileContent += "\n"; fileContent += "#include <engine.hpp> \n"; fileContent += "#include <gameobject.hpp>\n"; fileContent += "#include <behavior.hpp>\n"; fileContent += "\n"; fileContent += "using namespace fabric;\n"; fileContent += "\n"; fileContent += "namespace game{\n"; fileContent += " class " + name + " : public GameObject{\n"; fileContent += " public:\n"; fileContent += " void setup();\n"; fileContent += " void update ();\n"; fileContent += " };\n"; fileContent += "}\n"; fileContent += "#endif"; oFile.write(fileContent.c_str(), fileContent.size()); oFile.close(); return 0; } void waitForExit() { string input; do { cout << "Input anything to exit: "; cin >> input; } while (input == ""); } int main() { string input; int lhs; cout << "Welcome to the automated script creation tool" << endl; cout << "Is this tool beeing ran from the 'tools' directory in your project or" << endl; cout << "has been launched from the editor? [yes | no]: "; cin >> input; if (input == "no") { cout << "Please launched the tool from the 'tools' directory or the editor" << endl; waitForExit(); return 1; } cout << endl; cout << "Please enter the name of your script (no exstenion): "; cin >> input; cout << "Thank You"; cout << endl; lhs = addIncludeHeader(input, "../../game/game.cpp"); if (lhs == 0) cout << "... Include headers have been created in 'game.cpp'" << endl; else cout << "... Include header could not be written to 'game.cpp'" << endl; lhs = addEngineRegister(input, "../../game/game.cpp"); if (lhs == 0) cout << "... Engine register have been created in 'game.cpp'" << endl; else cout << "... Engine register could not be written to 'game.cpp'" << endl; lhs = addSourceFile(input, "../../game/scripts/source/"); if (lhs == 0) cout << "... .cpp file has been created in 'scripts/source'" << endl; else cout << "... .cpp file could not be created in'scripts/source'" << endl; lhs = addHeaderFile(input, "../../game/scripts/header/"); if (lhs == 0) cout << "... .hpp file has been created in 'scripts/header'" << endl; else cout << "... .hpp file could not be created in'scripts/header'" << endl; cout << endl; cout << "Script has been added, your welcome" << endl; waitForExit(); return 0; }<|endoftext|>
<commit_before>/* This file is part of the KDE project Copyright (C) 2005-2006 Matthias Kretz <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "abstractmediaproducer.h" #include "abstractmediaproducer_p.h" #include "factory.h" #include "videopath.h" #include "audiopath.h" #include "mediaproducerinterface.h" #include <QTimer> #include <kdebug.h> #include <QStringList> #define PHONON_CLASSNAME AbstractMediaProducer #define PHONON_INTERFACENAME MediaProducerInterface namespace Phonon { PHONON_ABSTRACTBASE_IMPL AbstractMediaProducer::~AbstractMediaProducer() { K_D( AbstractMediaProducer ); Phonon::State s = state(); if( s != ErrorState || s != StoppedState || s != LoadingState ) stop(); foreach(VideoPath* vp, d->videoPaths) d->removeDestructionHandler(vp, d); foreach(AudioPath* ap, d->audioPaths) d->removeDestructionHandler(ap, d); } bool AbstractMediaProducer::addVideoPath( VideoPath* videoPath ) { K_D( AbstractMediaProducer ); if( d->videoPaths.contains( videoPath ) ) return false; if( iface() ) { if( qobject_cast<MediaProducerInterface*>( d->backendObject )->addVideoPath( videoPath->iface() ) ) { d->addDestructionHandler(videoPath, d); d->videoPaths.append( videoPath ); return true; } } return false; } bool AbstractMediaProducer::addAudioPath( AudioPath* audioPath ) { K_D( AbstractMediaProducer ); if( d->audioPaths.contains( audioPath ) ) return false; if( iface() ) { if( qobject_cast<MediaProducerInterface*>( d->backendObject )->addAudioPath( audioPath->iface() ) ) { d->addDestructionHandler(audioPath, d); d->audioPaths.append( audioPath ); return true; } } return false; } PHONON_INTERFACE_SETTER( setTickInterval, tickInterval, qint32 ) PHONON_INTERFACE_GETTER( qint32, tickInterval, d->tickInterval ) PHONON_INTERFACE_GETTER( Phonon::State, state, d->state ) PHONON_INTERFACE_GETTER( bool, hasVideo, false ) PHONON_INTERFACE_GETTER( bool, isSeekable, false ) PHONON_INTERFACE_GETTER( qint64, currentTime, d->currentTime ) PHONON_INTERFACE_GETTER1( QString, selectedAudioStream, d->selectedAudioStream[ audioPath ], AudioPath*, audioPath ) PHONON_INTERFACE_GETTER1( QString, selectedVideoStream, d->selectedVideoStream[ videoPath ], VideoPath*, videoPath ) PHONON_INTERFACE_GETTER1( QString, selectedSubtitleStream, d->selectedSubtitleStream[ videoPath ], VideoPath*, videoPath ) PHONON_INTERFACE_GETTER( QStringList, availableAudioStreams, QStringList() ) PHONON_INTERFACE_GETTER( QStringList, availableVideoStreams, QStringList() ) PHONON_INTERFACE_GETTER( QStringList, availableSubtitleStreams, QStringList() ) void AbstractMediaProducer::selectAudioStream( const QString& streamName, AudioPath* audioPath ) { K_D( AbstractMediaProducer ); if( iface() ) INTERFACE_CALL(selectAudioStream, (streamName, audioPath->iface())); else d->selectedAudioStream[ audioPath ] = streamName; } void AbstractMediaProducer::selectVideoStream( const QString& streamName, VideoPath* videoPath ) { K_D( AbstractMediaProducer ); if( iface() ) INTERFACE_CALL(selectVideoStream, (streamName, videoPath->iface())); else d->selectedVideoStream[ videoPath ] = streamName; } void AbstractMediaProducer::selectSubtitleStream( const QString& streamName, VideoPath* videoPath ) { K_D( AbstractMediaProducer ); if( iface() ) INTERFACE_CALL(selectSubtitleStream, (streamName, videoPath->iface())); else d->selectedSubtitleStream[ videoPath ] = streamName; } QList<VideoPath*> AbstractMediaProducer::videoPaths() const { K_D( const AbstractMediaProducer ); return d->videoPaths; } QList<AudioPath*> AbstractMediaProducer::audioPaths() const { K_D( const AbstractMediaProducer ); return d->audioPaths; } void AbstractMediaProducer::play() { K_D( AbstractMediaProducer ); if( iface() ) INTERFACE_CALL(play, ()); } void AbstractMediaProducer::pause() { K_D( AbstractMediaProducer ); if( iface() ) INTERFACE_CALL(pause, ()); } void AbstractMediaProducer::stop() { K_D( AbstractMediaProducer ); if( iface() ) { INTERFACE_CALL(stop, ()); if( tickInterval() > 0 ) emit tick( 0 ); } } void AbstractMediaProducer::seek( qint64 time ) { K_D( AbstractMediaProducer ); State s = state(); if( iface() && ( s == Phonon::PlayingState || s == Phonon::BufferingState || s == Phonon::PausedState ) ) INTERFACE_CALL(seek, (time)); } QString AbstractMediaProducer::errorString() const { if (state() == Phonon::ErrorState) { K_D(const AbstractMediaProducer); return INTERFACE_CALL(errorString, ()); } return QString(); } ErrorType AbstractMediaProducer::errorType() const { if (state() == Phonon::ErrorState) { K_D(const AbstractMediaProducer); return INTERFACE_CALL(errorType, ()); } return Phonon::NoError; } bool AbstractMediaProducerPrivate::aboutToDeleteIface() { //kDebug( 600 ) << k_funcinfo << endl; if( backendObject ) { state = qobject_cast<MediaProducerInterface*>( backendObject )->state(); currentTime = qobject_cast<MediaProducerInterface*>( backendObject )->currentTime(); tickInterval = qobject_cast<MediaProducerInterface*>( backendObject )->tickInterval(); } return true; } void AbstractMediaProducer::setupIface() { K_D( AbstractMediaProducer ); Q_ASSERT( d->backendObject ); //kDebug( 600 ) << k_funcinfo << endl; connect( d->backendObject, SIGNAL( stateChanged( Phonon::State, Phonon::State ) ), SIGNAL( stateChanged( Phonon::State, Phonon::State ) ) ); connect( d->backendObject, SIGNAL( tick( qint64 ) ), SIGNAL( tick( qint64 ) ) ); connect( d->backendObject, SIGNAL( metaDataChanged( const QMultiMap<QString, QString>& ) ), SLOT( _k_metaDataChanged( const QMultiMap<QString, QString>& ) ) ); connect(d->backendObject, SIGNAL(seekableChanged(bool)), SIGNAL(seekableChanged(bool))); // set up attributes INTERFACE_CALL(setTickInterval, (d->tickInterval)); foreach( AudioPath* a, d->audioPaths ) { if( !qobject_cast<MediaProducerInterface*>( d->backendObject )->addAudioPath( a->iface() ) ) d->audioPaths.removeAll( a ); } foreach( VideoPath* v, d->videoPaths ) { if( !qobject_cast<MediaProducerInterface*>( d->backendObject )->addVideoPath( v->iface() ) ) d->videoPaths.removeAll( v ); } switch( d->state ) { case LoadingState: case StoppedState: case ErrorState: break; case PlayingState: case BufferingState: QTimer::singleShot( 0, this, SLOT( _k_resumePlay() ) ); break; case PausedState: QTimer::singleShot( 0, this, SLOT( _k_resumePause() ) ); break; } d->state = qobject_cast<MediaProducerInterface*>( d->backendObject )->state(); } void AbstractMediaProducerPrivate::_k_resumePlay() { qobject_cast<MediaProducerInterface*>( backendObject )->play(); if( currentTime > 0 ) qobject_cast<MediaProducerInterface*>( backendObject )->seek( currentTime ); } void AbstractMediaProducerPrivate::_k_resumePause() { qobject_cast<MediaProducerInterface*>( backendObject )->play(); if( currentTime > 0 ) qobject_cast<MediaProducerInterface*>( backendObject )->seek( currentTime ); qobject_cast<MediaProducerInterface*>( backendObject )->pause(); } void AbstractMediaProducerPrivate::_k_metaDataChanged( const QMultiMap<QString, QString>& newMetaData ) { metaData = newMetaData; emit q_func()->metaDataChanged(); } QStringList AbstractMediaProducer::metaDataKeys() const { K_D( const AbstractMediaProducer ); return d->metaData.keys(); } QString AbstractMediaProducer::metaDataItem( const QString& key ) const { K_D( const AbstractMediaProducer ); return d->metaData.value( key ); } QStringList AbstractMediaProducer::metaDataItems( const QString& key ) const { K_D( const AbstractMediaProducer ); return d->metaData.values( key ); } void AbstractMediaProducerPrivate::phononObjectDestroyed( Base* o ) { // this method is called from Phonon::Base::~Base(), meaning the AudioPath // dtor has already been called, also virtual functions don't work anymore // (therefore qobject_cast can only downcast from Base) Q_ASSERT( o ); AudioPath* audioPath = static_cast<AudioPath*>( o ); VideoPath* videoPath = static_cast<VideoPath*>( o ); if( audioPaths.contains( audioPath ) ) { if( backendObject ) qobject_cast<MediaProducerInterface*>( backendObject )->removeAudioPath( audioPath->iface() ); audioPaths.removeAll( audioPath ); } else if( videoPaths.contains( videoPath ) ) { if( backendObject ) qobject_cast<MediaProducerInterface*>( backendObject )->removeVideoPath( videoPath->iface() ); videoPaths.removeAll( videoPath ); } } } //namespace Phonon #include "abstractmediaproducer.moc" // vim: sw=4 ts=4 tw=80 <commit_msg>don't (re)create the backend object in the ctor<commit_after>/* This file is part of the KDE project Copyright (C) 2005-2006 Matthias Kretz <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "abstractmediaproducer.h" #include "abstractmediaproducer_p.h" #include "factory.h" #include "videopath.h" #include "audiopath.h" #include "mediaproducerinterface.h" #include <QTimer> #include <kdebug.h> #include <QStringList> #define PHONON_CLASSNAME AbstractMediaProducer #define PHONON_INTERFACENAME MediaProducerInterface namespace Phonon { PHONON_ABSTRACTBASE_IMPL AbstractMediaProducer::~AbstractMediaProducer() { K_D(AbstractMediaProducer); if (d->backendObject) { switch (state()) { case PlayingState: case BufferingState: case PausedState: stop(); break; case ErrorState: case StoppedState: case LoadingState: break; } } foreach(VideoPath* vp, d->videoPaths) d->removeDestructionHandler(vp, d); foreach(AudioPath* ap, d->audioPaths) d->removeDestructionHandler(ap, d); } bool AbstractMediaProducer::addVideoPath( VideoPath* videoPath ) { K_D( AbstractMediaProducer ); if( d->videoPaths.contains( videoPath ) ) return false; if( iface() ) { if( qobject_cast<MediaProducerInterface*>( d->backendObject )->addVideoPath( videoPath->iface() ) ) { d->addDestructionHandler(videoPath, d); d->videoPaths.append( videoPath ); return true; } } return false; } bool AbstractMediaProducer::addAudioPath( AudioPath* audioPath ) { K_D( AbstractMediaProducer ); if( d->audioPaths.contains( audioPath ) ) return false; if( iface() ) { if( qobject_cast<MediaProducerInterface*>( d->backendObject )->addAudioPath( audioPath->iface() ) ) { d->addDestructionHandler(audioPath, d); d->audioPaths.append( audioPath ); return true; } } return false; } PHONON_INTERFACE_SETTER( setTickInterval, tickInterval, qint32 ) PHONON_INTERFACE_GETTER( qint32, tickInterval, d->tickInterval ) PHONON_INTERFACE_GETTER( Phonon::State, state, d->state ) PHONON_INTERFACE_GETTER( bool, hasVideo, false ) PHONON_INTERFACE_GETTER( bool, isSeekable, false ) PHONON_INTERFACE_GETTER( qint64, currentTime, d->currentTime ) PHONON_INTERFACE_GETTER1( QString, selectedAudioStream, d->selectedAudioStream[ audioPath ], AudioPath*, audioPath ) PHONON_INTERFACE_GETTER1( QString, selectedVideoStream, d->selectedVideoStream[ videoPath ], VideoPath*, videoPath ) PHONON_INTERFACE_GETTER1( QString, selectedSubtitleStream, d->selectedSubtitleStream[ videoPath ], VideoPath*, videoPath ) PHONON_INTERFACE_GETTER( QStringList, availableAudioStreams, QStringList() ) PHONON_INTERFACE_GETTER( QStringList, availableVideoStreams, QStringList() ) PHONON_INTERFACE_GETTER( QStringList, availableSubtitleStreams, QStringList() ) void AbstractMediaProducer::selectAudioStream( const QString& streamName, AudioPath* audioPath ) { K_D( AbstractMediaProducer ); if( iface() ) INTERFACE_CALL(selectAudioStream, (streamName, audioPath->iface())); else d->selectedAudioStream[ audioPath ] = streamName; } void AbstractMediaProducer::selectVideoStream( const QString& streamName, VideoPath* videoPath ) { K_D( AbstractMediaProducer ); if( iface() ) INTERFACE_CALL(selectVideoStream, (streamName, videoPath->iface())); else d->selectedVideoStream[ videoPath ] = streamName; } void AbstractMediaProducer::selectSubtitleStream( const QString& streamName, VideoPath* videoPath ) { K_D( AbstractMediaProducer ); if( iface() ) INTERFACE_CALL(selectSubtitleStream, (streamName, videoPath->iface())); else d->selectedSubtitleStream[ videoPath ] = streamName; } QList<VideoPath*> AbstractMediaProducer::videoPaths() const { K_D( const AbstractMediaProducer ); return d->videoPaths; } QList<AudioPath*> AbstractMediaProducer::audioPaths() const { K_D( const AbstractMediaProducer ); return d->audioPaths; } void AbstractMediaProducer::play() { K_D( AbstractMediaProducer ); if( iface() ) INTERFACE_CALL(play, ()); } void AbstractMediaProducer::pause() { K_D( AbstractMediaProducer ); if( iface() ) INTERFACE_CALL(pause, ()); } void AbstractMediaProducer::stop() { K_D( AbstractMediaProducer ); if( iface() ) { INTERFACE_CALL(stop, ()); if( tickInterval() > 0 ) emit tick( 0 ); } } void AbstractMediaProducer::seek( qint64 time ) { K_D( AbstractMediaProducer ); State s = state(); if( iface() && ( s == Phonon::PlayingState || s == Phonon::BufferingState || s == Phonon::PausedState ) ) INTERFACE_CALL(seek, (time)); } QString AbstractMediaProducer::errorString() const { if (state() == Phonon::ErrorState) { K_D(const AbstractMediaProducer); return INTERFACE_CALL(errorString, ()); } return QString(); } ErrorType AbstractMediaProducer::errorType() const { if (state() == Phonon::ErrorState) { K_D(const AbstractMediaProducer); return INTERFACE_CALL(errorType, ()); } return Phonon::NoError; } bool AbstractMediaProducerPrivate::aboutToDeleteIface() { //kDebug( 600 ) << k_funcinfo << endl; if( backendObject ) { state = qobject_cast<MediaProducerInterface*>( backendObject )->state(); currentTime = qobject_cast<MediaProducerInterface*>( backendObject )->currentTime(); tickInterval = qobject_cast<MediaProducerInterface*>( backendObject )->tickInterval(); } return true; } void AbstractMediaProducer::setupIface() { K_D( AbstractMediaProducer ); Q_ASSERT( d->backendObject ); //kDebug( 600 ) << k_funcinfo << endl; connect( d->backendObject, SIGNAL( stateChanged( Phonon::State, Phonon::State ) ), SIGNAL( stateChanged( Phonon::State, Phonon::State ) ) ); connect( d->backendObject, SIGNAL( tick( qint64 ) ), SIGNAL( tick( qint64 ) ) ); connect( d->backendObject, SIGNAL( metaDataChanged( const QMultiMap<QString, QString>& ) ), SLOT( _k_metaDataChanged( const QMultiMap<QString, QString>& ) ) ); connect(d->backendObject, SIGNAL(seekableChanged(bool)), SIGNAL(seekableChanged(bool))); // set up attributes INTERFACE_CALL(setTickInterval, (d->tickInterval)); foreach( AudioPath* a, d->audioPaths ) { if( !qobject_cast<MediaProducerInterface*>( d->backendObject )->addAudioPath( a->iface() ) ) d->audioPaths.removeAll( a ); } foreach( VideoPath* v, d->videoPaths ) { if( !qobject_cast<MediaProducerInterface*>( d->backendObject )->addVideoPath( v->iface() ) ) d->videoPaths.removeAll( v ); } switch( d->state ) { case LoadingState: case StoppedState: case ErrorState: break; case PlayingState: case BufferingState: QTimer::singleShot( 0, this, SLOT( _k_resumePlay() ) ); break; case PausedState: QTimer::singleShot( 0, this, SLOT( _k_resumePause() ) ); break; } d->state = qobject_cast<MediaProducerInterface*>( d->backendObject )->state(); } void AbstractMediaProducerPrivate::_k_resumePlay() { qobject_cast<MediaProducerInterface*>( backendObject )->play(); if( currentTime > 0 ) qobject_cast<MediaProducerInterface*>( backendObject )->seek( currentTime ); } void AbstractMediaProducerPrivate::_k_resumePause() { qobject_cast<MediaProducerInterface*>( backendObject )->play(); if( currentTime > 0 ) qobject_cast<MediaProducerInterface*>( backendObject )->seek( currentTime ); qobject_cast<MediaProducerInterface*>( backendObject )->pause(); } void AbstractMediaProducerPrivate::_k_metaDataChanged( const QMultiMap<QString, QString>& newMetaData ) { metaData = newMetaData; emit q_func()->metaDataChanged(); } QStringList AbstractMediaProducer::metaDataKeys() const { K_D( const AbstractMediaProducer ); return d->metaData.keys(); } QString AbstractMediaProducer::metaDataItem( const QString& key ) const { K_D( const AbstractMediaProducer ); return d->metaData.value( key ); } QStringList AbstractMediaProducer::metaDataItems( const QString& key ) const { K_D( const AbstractMediaProducer ); return d->metaData.values( key ); } void AbstractMediaProducerPrivate::phononObjectDestroyed( Base* o ) { // this method is called from Phonon::Base::~Base(), meaning the AudioPath // dtor has already been called, also virtual functions don't work anymore // (therefore qobject_cast can only downcast from Base) Q_ASSERT( o ); AudioPath* audioPath = static_cast<AudioPath*>( o ); VideoPath* videoPath = static_cast<VideoPath*>( o ); if( audioPaths.contains( audioPath ) ) { if( backendObject ) qobject_cast<MediaProducerInterface*>( backendObject )->removeAudioPath( audioPath->iface() ); audioPaths.removeAll( audioPath ); } else if( videoPaths.contains( videoPath ) ) { if( backendObject ) qobject_cast<MediaProducerInterface*>( backendObject )->removeVideoPath( videoPath->iface() ); videoPaths.removeAll( videoPath ); } } } //namespace Phonon #include "abstractmediaproducer.moc" // vim: sw=4 ts=4 tw=80 <|endoftext|>
<commit_before>#ifndef LUA_FUNCTION_H #include "LuaFunction.hpp" #endif LuaFunction::LuaFunction(LuaAdapter &lua) : Lua{lua.GetLuaState()} {} LuaFunction::LuaFunction(lua_State *const lua) : Lua{lua} {} LuaFunction::~LuaFunction() {} bool LuaFunction::Call(const char *functionName, const unsigned short int argc, const int args[], int &result) { if (!this->Lua) { return false; } lua_getglobal(this->Lua, functionName); for (unsigned char i = 0; i < argc; i++) if (args + i) lua_pushnumber(this->Lua, args[i]); if (this->pcall(argc, 1, 0) == false) { return false; } if (lua_isnumber(this->Lua, -1)) { result = lua_tointeger(this->Lua, -1); } lua_pop(this->Lua, 1); return true; } bool LuaFunction::Call(const char *functionName, const char *const string, const size_t length) { if (!this->Lua) { return false; } lua_getglobal(this->Lua, functionName); lua_pushlstring(this->Lua, string, length); if (this->pcall(1, 1, 0) == false){ return false; } //lua_pop(this->Lua, 1); return true; } bool LuaFunction::Call(const char *functionName) { if (!this->Lua) { return false; } lua_getglobal(this->Lua, functionName); if (this->pcall(0, 0, 0) == false) { return false; } //lua_pop(this->Lua, 1); return true; } bool LuaFunction::Call(const char *functionName, const char *const string, size_t &length, std::string &result) { if (!this->Lua) { return false; } lua_getglobal(this->Lua, functionName); lua_pushlstring(this->Lua, string, length); if (this->pcall(1, 1, 0) == false){ return false; } if (lua_isstring(this->Lua, -1) == false) { lua_pop(this->Lua, 1); return false; } size_t l{0}; const char *buffer{lua_tolstring(this->Lua, -1, &l)}; if ((!buffer) || (l == 0)) { lua_pop(this->Lua, 1); return false; } length = l; result = std::string{buffer, length}; lua_pop(this->Lua, 1); return true; } bool LuaFunction::Call(const char *functionName, const std::string arg, std::string &result) { if (!this->Lua) { return false; } lua_getglobal(this->Lua, functionName); lua_pushlstring(this->Lua, arg.c_str(), arg.length()); if (this->pcall(1, 1, 0) == false){ return false; } if (lua_isstring(this->Lua, -1) == false) { lua_pop(this->Lua, 1); return false; } result = lua_tostring(this->Lua, -1); lua_pop(this->Lua, 1); return true; } bool LuaFunction::Call(const char *functionName, double &result) { if (!this->Lua) { return false; } lua_getglobal(this->Lua, functionName); if (this->pcall(0, 1, 0) == false) return false; if (lua_isnumber(this->Lua, -1) == false) { lua_pop(this->Lua, 1); return false; } result = lua_tonumber(this->Lua, -1); lua_pop(this->Lua, 1); return true; } bool LuaFunction::Push(Lua_callback_function function, const char *functionName) { if (!this->Lua) return false; lua_pushcfunction(this->Lua, function); lua_setglobal(this->Lua, functionName); return true; } bool LuaFunction::pcall(int nargs, int nresults, int msgh){ //luaL_traceback(this->Lua, this->Lua, nullptr, 0); const int call {lua_pcall(this->Lua, nargs, nresults, msgh)}; if (call == LUA_OK){ return true; } //std::cerr << "\tTraceback: " << lua_tostring(this->Lua, -1); // lua_pop(this->Lua, 1); std::cerr << LUA_PREFIX << "Error: pcall failed. Code: "; std::cerr << call; std::cerr << ", '" << lua_tostring(this->Lua, -1) << "'\n"; lua_pop(this->Lua, 1); return false; }<commit_msg>Added proper pcall-function for error-outputs<commit_after>#ifndef LUA_FUNCTION_H #include "LuaFunction.hpp" #endif LuaFunction::LuaFunction(LuaAdapter &lua) : Lua{lua.GetLuaState()} {} LuaFunction::LuaFunction(lua_State *const lua) : Lua{lua} {} LuaFunction::~LuaFunction() {} bool LuaFunction::Call(const char *functionName, const unsigned short int argc, const int args[], int &result) { if (!this->Lua) { return false; } lua_getglobal(this->Lua, functionName); for (unsigned char i = 0; i < argc; i++) if (args + i) lua_pushnumber(this->Lua, args[i]); if (this->pcall(argc, 1, 0) == false) { return false; } if (lua_isnumber(this->Lua, -1)) { result = lua_tointeger(this->Lua, -1); } lua_pop(this->Lua, 1); return true; } bool LuaFunction::Call(const char *functionName, const char *const string, const size_t length) { if (!this->Lua) { return false; } lua_getglobal(this->Lua, functionName); lua_pushlstring(this->Lua, string, length); if (this->pcall(1, 1, 0) == false){ return false; } //lua_pop(this->Lua, 1); return true; } bool LuaFunction::Call(const char *functionName) { if (!this->Lua) { return false; } lua_getglobal(this->Lua, functionName); if (this->pcall(0, 0, 0) == false) { return false; } //lua_pop(this->Lua, 1); return true; } bool LuaFunction::Call(const char *functionName, const char *const string, size_t &length, std::string &result) { if (!this->Lua) { return false; } lua_getglobal(this->Lua, functionName); lua_pushlstring(this->Lua, string, length); if (this->pcall(1, 1, 0) == false){ return false; } if (lua_isstring(this->Lua, -1) == false) { lua_pop(this->Lua, 1); return false; } size_t l{0}; const char *buffer{lua_tolstring(this->Lua, -1, &l)}; if ((!buffer) || (l == 0)) { lua_pop(this->Lua, 1); return false; } length = l; result = std::string{buffer, length}; lua_pop(this->Lua, 1); return true; } bool LuaFunction::Call(const char *functionName, const std::string arg, std::string &result) { if (!this->Lua) { return false; } lua_getglobal(this->Lua, functionName); lua_pushlstring(this->Lua, arg.c_str(), arg.length()); if (this->pcall(1, 1, 0) == false){ return false; } if (lua_isstring(this->Lua, -1) == false) { lua_pop(this->Lua, 1); return false; } result = lua_tostring(this->Lua, -1); lua_pop(this->Lua, 1); return true; } bool LuaFunction::Call(const char *functionName, double &result) { if (!this->Lua) { return false; } lua_getglobal(this->Lua, functionName); if (this->pcall(0, 1, 0) == false) return false; if (lua_isnumber(this->Lua, -1) == false) { lua_pop(this->Lua, 1); return false; } result = lua_tonumber(this->Lua, -1); lua_pop(this->Lua, 1); return true; } bool LuaFunction::Push(Lua_callback_function function, const char *functionName) { if (!this->Lua) return false; lua_pushcfunction(this->Lua, function); lua_setglobal(this->Lua, functionName); return true; } bool LuaFunction::pcall(int nargs, int nresults, int msgh){ const int call {lua_pcall(this->Lua, nargs, nresults, msgh)}; if (call == LUA_OK){ return true; } std::cerr << LUA_PREFIX << "Error: pcall failed. Code: "; std::cerr << call; std::cerr << ", '" << lua_tostring(this->Lua, -1) << "'\n"; lua_pop(this->Lua, 1); return false; }<|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include <AEEStdDef.h> #include <AEEStdErr.h> #include <remote.h> #include <rpcmem.h> #include <algorithm> #include <ios> #include <iostream> #include <string> #include <vector> #include "launcher_core.h" #include "launcher_rpc.h" AEEResult enable_unsigned_pd(bool enable) { remote_rpc_control_unsigned_module data{static_cast<int>(enable), CDSP_DOMAIN_ID}; AEEResult rc = remote_session_control(DSPRPC_CONTROL_UNSIGNED_MODULE, &data, sizeof(data)); if (rc != AEE_SUCCESS) { std::cout << "error " << (enable ? "enabling" : "disabling") << " unsigned PD\n"; } return rc; } AEEResult set_remote_stack_size(int size) { remote_rpc_thread_params th_data{CDSP_DOMAIN_ID, -1, size}; AEEResult rc = remote_session_control(FASTRPC_THREAD_PARAMS, &th_data, sizeof(th_data)); if (rc != AEE_SUCCESS) { std::cout << "error setting remote stack size: " << std::hex << rc << '\n'; } return rc; } struct RPCChannel : public ExecutionSession { explicit RPCChannel(const std::string& uri) { enable_unsigned_pd(true); set_remote_stack_size(128 * 1024); int rc = launcher_rpc_open(uri.c_str(), &handle); if (rc != AEE_SUCCESS) { handle = -1; } } ~RPCChannel() { if (handle == -1) { return; } for (void* ptr : allocations) { rpcmem_free(ptr); } if (model_loaded) { unload_model(); } launcher_rpc_close(handle); handle = -1; } void* alloc_mem(size_t nbytes, size_t align) override { void* host_ptr = rpcmem_alloc(RPCMEM_HEAP_ID_SYSTEM, RPCMEM_DEFAULT_FLAGS, nbytes); if (host_ptr != nullptr) { allocations.push_back(host_ptr); } return host_ptr; } void free_mem(void* addr) override { auto f = std::find(allocations.begin(), allocations.end(), addr); if (f != allocations.end()) { allocations.erase(f); rpcmem_free(addr); } } bool load_model(const std::string& model_path, const std::string& model_json) override { AEEResult rc = launcher_rpc_load(handle, model_path.c_str(), model_json.c_str()); if (rc != AEE_SUCCESS) { std::cout << "error loading graph module: " << std::hex << rc << '\n'; } else { model_loaded = true; } return rc == AEE_SUCCESS; } bool unload_model() override { AEEResult rc = launcher_rpc_unload(handle); if (rc != AEE_SUCCESS) { std::cout << "error unloading model: " << std::hex << rc << '\n'; } model_loaded = false; return rc == AEE_SUCCESS; } bool set_input(int input_idx, const tensor_meta* input_meta, const void* input_data) override { AEEResult rc = launcher_rpc_set_input( handle, input_idx, reinterpret_cast<const unsigned char*>(input_meta), input_meta->meta_size(), reinterpret_cast<const unsigned char*>(input_data), input_meta->data_size()); if (rc != AEE_SUCCESS) { std::cout << "error setting model input no." << input_idx << ": " << std::hex << rc << '\n'; } return rc == AEE_SUCCESS; } bool run(uint64_t* pcycles, uint64_t* usecs) override { AEEResult rc = launcher_rpc_run(handle, pcycles, usecs); if (rc != AEE_SUCCESS) { std::cout << "error running model: " << std::hex << rc << '\n'; } return rc == AEE_SUCCESS; } bool get_num_outputs(int* num_outputs) override { AEEResult rc = launcher_rpc_get_num_outputs(handle, num_outputs); if (rc != AEE_SUCCESS) { std::cout << "error getting number of outputs: " << std::hex << rc << '\n'; } return rc == AEE_SUCCESS; } bool get_output(int output_idx, tensor_meta* output_meta, int meta_size, void* output_data, int data_size) override { AEEResult rc = launcher_rpc_get_output( handle, output_idx, reinterpret_cast<unsigned char*>(output_meta), meta_size, reinterpret_cast<unsigned char*>(output_data), data_size); if (rc != AEE_SUCCESS) { std::cout << "error getting output no." << output_idx << ": " << std::hex << rc << '\n'; } return rc == AEE_SUCCESS; } bool model_loaded = false; remote_handle64 handle = -1; std::vector<void*> allocations; }; ExecutionSession* create_execution_session() { auto* session = new RPCChannel(launcher_rpc_URI CDSP_DOMAIN); if (session->handle == -1) { delete session; session = nullptr; std::cout << "Error opening FastRPC channel\n"; } return session; } <commit_msg>[Hexagon] Don't use {} initialization with FastRPC structures (#9033)<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include <AEEStdDef.h> #include <AEEStdErr.h> #include <remote.h> #include <rpcmem.h> #include <algorithm> #include <ios> #include <iostream> #include <string> #include <vector> #include "launcher_core.h" #include "launcher_rpc.h" AEEResult enable_unsigned_pd(bool enable) { remote_rpc_control_unsigned_module data; data.domain = CDSP_DOMAIN_ID; data.enable = static_cast<int>(enable); AEEResult rc = remote_session_control(DSPRPC_CONTROL_UNSIGNED_MODULE, &data, sizeof(data)); if (rc != AEE_SUCCESS) { std::cout << "error " << (enable ? "enabling" : "disabling") << " unsigned PD\n"; } return rc; } AEEResult set_remote_stack_size(int size) { remote_rpc_thread_params data; data.domain = CDSP_DOMAIN_ID; data.prio = -1; data.stack_size = size; AEEResult rc = remote_session_control(FASTRPC_THREAD_PARAMS, &data, sizeof(data)); if (rc != AEE_SUCCESS) { std::cout << "error setting remote stack size: " << std::hex << rc << '\n'; } return rc; } struct RPCChannel : public ExecutionSession { explicit RPCChannel(const std::string& uri) { enable_unsigned_pd(true); set_remote_stack_size(128 * 1024); int rc = launcher_rpc_open(uri.c_str(), &handle); if (rc != AEE_SUCCESS) { handle = -1; } } ~RPCChannel() { if (handle == -1) { return; } for (void* ptr : allocations) { rpcmem_free(ptr); } if (model_loaded) { unload_model(); } launcher_rpc_close(handle); handle = -1; } void* alloc_mem(size_t nbytes, size_t align) override { void* host_ptr = rpcmem_alloc(RPCMEM_HEAP_ID_SYSTEM, RPCMEM_DEFAULT_FLAGS, nbytes); if (host_ptr != nullptr) { allocations.push_back(host_ptr); } return host_ptr; } void free_mem(void* addr) override { auto f = std::find(allocations.begin(), allocations.end(), addr); if (f != allocations.end()) { allocations.erase(f); rpcmem_free(addr); } } bool load_model(const std::string& model_path, const std::string& model_json) override { AEEResult rc = launcher_rpc_load(handle, model_path.c_str(), model_json.c_str()); if (rc != AEE_SUCCESS) { std::cout << "error loading graph module: " << std::hex << rc << '\n'; } else { model_loaded = true; } return rc == AEE_SUCCESS; } bool unload_model() override { AEEResult rc = launcher_rpc_unload(handle); if (rc != AEE_SUCCESS) { std::cout << "error unloading model: " << std::hex << rc << '\n'; } model_loaded = false; return rc == AEE_SUCCESS; } bool set_input(int input_idx, const tensor_meta* input_meta, const void* input_data) override { AEEResult rc = launcher_rpc_set_input( handle, input_idx, reinterpret_cast<const unsigned char*>(input_meta), input_meta->meta_size(), reinterpret_cast<const unsigned char*>(input_data), input_meta->data_size()); if (rc != AEE_SUCCESS) { std::cout << "error setting model input no." << input_idx << ": " << std::hex << rc << '\n'; } return rc == AEE_SUCCESS; } bool run(uint64_t* pcycles, uint64_t* usecs) override { AEEResult rc = launcher_rpc_run(handle, pcycles, usecs); if (rc != AEE_SUCCESS) { std::cout << "error running model: " << std::hex << rc << '\n'; } return rc == AEE_SUCCESS; } bool get_num_outputs(int* num_outputs) override { AEEResult rc = launcher_rpc_get_num_outputs(handle, num_outputs); if (rc != AEE_SUCCESS) { std::cout << "error getting number of outputs: " << std::hex << rc << '\n'; } return rc == AEE_SUCCESS; } bool get_output(int output_idx, tensor_meta* output_meta, int meta_size, void* output_data, int data_size) override { AEEResult rc = launcher_rpc_get_output( handle, output_idx, reinterpret_cast<unsigned char*>(output_meta), meta_size, reinterpret_cast<unsigned char*>(output_data), data_size); if (rc != AEE_SUCCESS) { std::cout << "error getting output no." << output_idx << ": " << std::hex << rc << '\n'; } return rc == AEE_SUCCESS; } bool model_loaded = false; remote_handle64 handle = -1; std::vector<void*> allocations; }; ExecutionSession* create_execution_session() { auto* session = new RPCChannel(launcher_rpc_URI CDSP_DOMAIN); if (session->handle == -1) { delete session; session = nullptr; std::cout << "Error opening FastRPC channel\n"; } return session; } <|endoftext|>
<commit_before>/* * RenderItemDistanceMetric.h * * Created on: Feb 16, 2009 * Author: struktured */ #ifndef RenderItemDISTANCEMETRIC_H_ #define RenderItemDISTANCEMETRIC_H_ #include "Common.hpp" #include "Renderable.hpp" #include <limits> #include <functional> #include <map> struct TypeIdPair { TypeIdPair(const std::type_info & info1, const std::type_info & info2): id1(info1.name()), id2(info2.name()) {} TypeIdPair(const std::string & id1, const std::string & id2): id1(id1), id2(id2) {} std::string id1; std::string id2; inline bool operator<(const TypeIdPair & rhs) const { return this->id1 < rhs.id1 || (this->id1 == rhs.id1 && this->id2 < rhs.id2); } inline bool operator>(const TypeIdPair & rhs) const { return !operator<(rhs) && !operator==(rhs); } inline bool operator==(const TypeIdPair & rhs) const { return this->id1 == rhs.id1 && this->id2 == rhs.id2; } }; /// Compares two render items and returns zero if they are virtually equivalent and large values /// when they are dissimilar. If two render items cannot be compared, NOT_COMPARABLE_VALUE is returned. class RenderItemDistanceMetric : public std::binary_function<const RenderItem*, const RenderItem*, double> { public: const static double NOT_COMPARABLE_VALUE; virtual double operator()(const RenderItem * r1, const RenderItem * r2) const = 0; virtual TypeIdPair typeIdPair() const = 0; }; // A base class to construct render item distance metrics. Just specify your two concrete // render item types as template parameters and override the computeDistance() function. template <class R1, class R2> class RenderItemDistance : public RenderItemDistanceMetric { protected: // Override to create your own distance metric for your specified custom types. virtual double computeDistance(const R1 * r1, const R2 * r2) const = 0; public: inline virtual double operator()(const RenderItem * r1, const RenderItem * r2) const { if (supported(r1, r2)) return computeDistance(dynamic_cast<const R1*>(r1), dynamic_cast<const R2*>(r2)); else if (supported(r2,r1)) return computeDistance(dynamic_cast<const R2*>(r2), dynamic_cast<const R2*>(r1)); else return NOT_COMPARABLE_VALUE; } // Returns true if and only if r1 and r2 are of type R1 and R2 respectively. inline bool supported(const RenderItem * r1, const RenderItem * r2) const { return typeid(r1) == typeid(const R1 *) && typeid(r2) == typeid(const R2 *); } inline TypeIdPair typeIdPair() const { return TypeIdPair(typeid(const R1*).name(), typeid(const R2*).name()); } }; class RTIRenderItemDistance : public RenderItemDistance<RenderItem, RenderItem> { public: RTIRenderItemDistance() {} virtual ~RTIRenderItemDistance() {} protected: virtual inline double computeDistance(const RenderItem * lhs, const RenderItem * rhs) const { if (typeid(lhs) == typeid(rhs)) return 0.0; else return NOT_COMPARABLE_VALUE; } }; class ShapeXYDistance : public RenderItemDistance<Shape, Shape> { public: ShapeXYDistance() {} virtual ~ShapeXYDistance() {} protected: virtual inline double computeDistance(const Shape * lhs, const Shape * rhs) const { return (meanSquaredError(lhs->x, rhs->x) + meanSquaredError(lhs->y, rhs->y)) / 2; } }; class MasterRenderItemDistance : public RenderItemDistance<RenderItem, RenderItem> { typedef std::map<TypeIdPair, RenderItemDistanceMetric*> DistanceMetricMap; public: MasterRenderItemDistance() {} virtual ~MasterRenderItemDistance() {} inline void addMetric(RenderItemDistanceMetric * fun) { _distanceMetricMap[fun->typeIdPair()] = fun; } protected: virtual inline double computeDistance(const RenderItem * lhs, const RenderItem * rhs) const { RenderItemDistanceMetric * metric; TypeIdPair pair(typeid(lhs), typeid(rhs)); if (_distanceMetricMap.count(pair)) { metric = _distanceMetricMap[pair]; } else if (_distanceMetricMap.count(pair = TypeIdPair(typeid(lhs), typeid(rhs)))) { metric = _distanceMetricMap[pair]; } else { metric = 0; } // If specialized metric exists, use it to get higher granularity // of correctness if (metric) return (*metric)(lhs, rhs); else // Failing that, use rtti and return 0 if they match, max value otherwise return _rttiDistance(lhs,rhs); } private: mutable RTIRenderItemDistance _rttiDistance; mutable DistanceMetricMap _distanceMetricMap; }; #endif /* RenderItemDISTANCEMETRIC_H_ */ <commit_msg>bug fix<commit_after>/* * RenderItemDistanceMetric.h * * Created on: Feb 16, 2009 * Author: struktured */ #ifndef RenderItemDISTANCEMETRIC_H_ #define RenderItemDISTANCEMETRIC_H_ #include "Common.hpp" #include "Renderable.hpp" #include <limits> #include <functional> #include <map> struct TypeIdPair { TypeIdPair(const std::type_info & info1, const std::type_info & info2): id1(info1.name()), id2(info2.name()) {} TypeIdPair(const std::string & id1, const std::string & id2): id1(id1), id2(id2) {} std::string id1; std::string id2; inline bool operator<(const TypeIdPair & rhs) const { return this->id1 < rhs.id1 || (this->id1 == rhs.id1 && this->id2 < rhs.id2); } inline bool operator>(const TypeIdPair & rhs) const { return !operator<(rhs) && !operator==(rhs); } inline bool operator==(const TypeIdPair & rhs) const { return this->id1 == rhs.id1 && this->id2 == rhs.id2; } }; /// Compares two render items and returns zero if they are virtually equivalent and large values /// when they are dissimilar. If two render items cannot be compared, NOT_COMPARABLE_VALUE is returned. class RenderItemDistanceMetric : public std::binary_function<const RenderItem*, const RenderItem*, double> { public: const static double NOT_COMPARABLE_VALUE; virtual double operator()(const RenderItem * r1, const RenderItem * r2) const = 0; virtual TypeIdPair typeIdPair() const = 0; }; // A base class to construct render item distance metrics. Just specify your two concrete // render item types as template parameters and override the computeDistance() function. template <class R1, class R2> class RenderItemDistance : public RenderItemDistanceMetric { protected: // Override to create your own distance metric for your specified custom types. virtual double computeDistance(const R1 * r1, const R2 * r2) const = 0; public: inline virtual double operator()(const RenderItem * r1, const RenderItem * r2) const { if (supported(r1, r2)) return computeDistance(dynamic_cast<const R1*>(r1), dynamic_cast<const R2*>(r2)); else if (supported(r2,r1)) return computeDistance(dynamic_cast<const R2*>(r2), dynamic_cast<const R2*>(r1)); else return NOT_COMPARABLE_VALUE; } // Returns true if and only if r1 and r2 are of type R1 and R2 respectively. inline bool supported(const RenderItem * r1, const RenderItem * r2) const { return typeid(r1) == typeid(const R1 *) && typeid(r2) == typeid(const R2 *); } inline TypeIdPair typeIdPair() const { return TypeIdPair(typeid(const R1*).name(), typeid(const R2*).name()); } }; class RTIRenderItemDistance : public RenderItemDistance<RenderItem, RenderItem> { public: RTIRenderItemDistance() {} virtual ~RTIRenderItemDistance() {} protected: virtual inline double computeDistance(const RenderItem * lhs, const RenderItem * rhs) const { if (typeid(lhs) == typeid(rhs)) return 0.0; else return NOT_COMPARABLE_VALUE; } }; class ShapeXYDistance : public RenderItemDistance<Shape, Shape> { public: ShapeXYDistance() {} virtual ~ShapeXYDistance() {} protected: virtual inline double computeDistance(const Shape * lhs, const Shape * rhs) const { return (meanSquaredError(lhs->x, rhs->x) + meanSquaredError(lhs->y, rhs->y)) / 2; } }; class MasterRenderItemDistance : public RenderItemDistance<RenderItem, RenderItem> { typedef std::map<TypeIdPair, RenderItemDistanceMetric*> DistanceMetricMap; public: MasterRenderItemDistance() {} virtual ~MasterRenderItemDistance() {} inline void addMetric(RenderItemDistanceMetric * fun) { _distanceMetricMap[fun->typeIdPair()] = fun; } protected: virtual inline double computeDistance(const RenderItem * lhs, const RenderItem * rhs) const { RenderItemDistanceMetric * metric; TypeIdPair pair(typeid(lhs), typeid(rhs)); if (_distanceMetricMap.count(pair)) { metric = _distanceMetricMap[pair]; } else if (_distanceMetricMap.count(pair = TypeIdPair(typeid(rhs), typeid(lhs)))) { metric = _distanceMetricMap[pair]; } else { metric = 0; } // If specialized metric exists, use it to get higher granularity // of correctness if (metric) return (*metric)(lhs, rhs); else // Failing that, use rtti and return 0 if they match, max value otherwise return _rttiDistance(lhs,rhs); } private: mutable RTIRenderItemDistance _rttiDistance; mutable DistanceMetricMap _distanceMetricMap; }; #endif /* RenderItemDISTANCEMETRIC_H_ */ <|endoftext|>
<commit_before>#include "Logger.h" #include <sstream> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> Logger* Logger::logger_instance = NULL; Logger::Logger(): nivelDeLog(LOG_DEBUG) { string timeStamp = "output.html"; struct stat buffer; if (stat(timeStamp.c_str(), &buffer)) { archivoLog.open( timeStamp.c_str() ); archivoLog << " Fecha y hora\t\t" << " Tipo\t\t" << "Lugar del mensaje\t\t\t" << "Mensaje" << endl ; } else { archivoLog.open(timeStamp.c_str(), std::ofstream::app); } lock = new LockFile(timeStamp.c_str()); } Logger& Logger::instance() { if (!logger_instance) { logger_instance = new Logger(); } return *logger_instance; } void Logger::close() { if (logger_instance) delete logger_instance; logger_instance = NULL; } Logger::~Logger() { delete lock; } void Logger::warn(const string& tag, const string& msg){ if ((nivelDeLog & LOG_WARN) == 0) return; log(tag, msg, LOG_WARN); } void Logger::error(const string& tag, const string& msg) { if ((nivelDeLog & LOG_ERROR) == 0) return; log(tag, msg, LOG_ERROR); } void Logger::debug(const string& tag, const string& msg) { if (nivelDeLog != LOG_DEBUG) return; log(tag, msg, LOG_DEBUG); } void Logger::info(const string& tag, const string& msg) { if ((nivelDeLog & LOG_INFO) == 0) return; log(tag, msg, LOG_INFO); } void Logger::fatal(const string& tag, const string& msg) { if ((nivelDeLog & LOG_FATAL) == 0) return; log(tag, msg, LOG_FATAL); } void Logger::log(const string& tag, const string& msg, int level) { lock->tomarLock(); struct tm *p_local_t; time_t t = time(NULL); p_local_t = localtime(&t); string sNivel("[INFO]\t"); switch (level) { case LOG_FATAL: sNivel = "[FATAL]\t"; break; case LOG_ERROR: sNivel = "[ERROR]\t"; break; case LOG_WARN: sNivel = "[WARN]\t"; break; case LOG_INFO: sNivel = "[INFO]\t"; break; case LOG_DEBUG: sNivel = "[DEBUG]\t"; break; default: break; } std::stringstream str; str << "[" << p_local_t->tm_mday << "-" << 1 + p_local_t->tm_mon << "-" << 1900 + p_local_t->tm_year << " " << p_local_t->tm_hour << ":" << p_local_t->tm_min << ":" << p_local_t->tm_sec << "]"; std::string fecha; str >> fecha; printMessageFormatted(fecha, sNivel, tag, msg); archivoLog.flush(); lock->liberarLock(); } void Logger::clear() { lock->tomarLock(); string timeStamp = "output.html"; archivoLog.close(); archivoLog.open(timeStamp.c_str()); printHeader(); lock->liberarLock(); } void Logger::setLogLevel(int nivelLog){ lock->tomarLock(); nivelDeLog = nivelLog; lock->liberarLock(); } void Logger::printHeader() { archivoLog << "<table id=\"table1\" class=\"mytable\" cellspacing=\"2\" cellpadding=\"2\" >" << std::endl; archivoLog << "<tr><th>Fecha y hora</th><th>Tipo</th><th>Lugar del mensaje</th><th>Mensaje</th></tr>" << std::endl; } void Logger::printMessageFormatted(const std::string& fecha, const std::string& level, const std::string& tag, const std::string& message) { archivoLog << "<tr>" << std::endl; archivoLog << "<td>" << fecha << "</td>"<<std::endl; archivoLog << "<td>" << level << "</td>"<<std::endl; archivoLog << "<td>" << tag << "</td>" <<std::endl; archivoLog << "<td>" << message << "</td>" <<std::endl; archivoLog << "</tr>" << std::endl; } <commit_msg>logger html<commit_after>#include "Logger.h" #include <sstream> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> Logger* Logger::logger_instance = NULL; Logger::Logger(): nivelDeLog(LOG_DEBUG) { string timeStamp = "output.html"; struct stat buffer; if (stat(timeStamp.c_str(), &buffer)) { archivoLog.open( timeStamp.c_str() ); archivoLog << " Fecha y hora\t\t" << " Tipo\t\t" << "Lugar del mensaje\t\t\t" << "Mensaje" << endl ; } else { archivoLog.open(timeStamp.c_str(), std::ofstream::app); } lock = new LockFile(timeStamp.c_str()); } Logger& Logger::instance() { if (!logger_instance) { logger_instance = new Logger(); } return *logger_instance; } void Logger::close() { if (logger_instance) delete logger_instance; logger_instance = NULL; } Logger::~Logger() { delete lock; } void Logger::warn(const string& tag, const string& msg){ if ((nivelDeLog & LOG_WARN) == 0) return; log(tag, msg, LOG_WARN); } void Logger::error(const string& tag, const string& msg) { if ((nivelDeLog & LOG_ERROR) == 0) return; log(tag, msg, LOG_ERROR); } void Logger::debug(const string& tag, const string& msg) { if (nivelDeLog != LOG_DEBUG) return; log(tag, msg, LOG_DEBUG); } void Logger::info(const string& tag, const string& msg) { if ((nivelDeLog & LOG_INFO) == 0) return; log(tag, msg, LOG_INFO); } void Logger::fatal(const string& tag, const string& msg) { if ((nivelDeLog & LOG_FATAL) == 0) return; log(tag, msg, LOG_FATAL); } void Logger::log(const string& tag, const string& msg, int level) { lock->tomarLock(); struct tm *p_local_t; time_t t = time(NULL); p_local_t = localtime(&t); string sNivel("[INFO]\t"); switch (level) { case LOG_FATAL: sNivel = "[FATAL]\t"; break; case LOG_ERROR: sNivel = "[ERROR]\t"; break; case LOG_WARN: sNivel = "[WARN]\t"; break; case LOG_INFO: sNivel = "[INFO]\t"; break; case LOG_DEBUG: sNivel = "[DEBUG]\t"; break; default: break; } std::stringstream str; str << p_local_t->tm_mday << "-" << 1 + p_local_t->tm_mon << "-" << 1900 + p_local_t->tm_year << " " << p_local_t->tm_hour << ":" << p_local_t->tm_min << ":" << p_local_t->tm_sec << "]"; std::string fecha; str >> fecha; printMessageFormatted(fecha, sNivel, tag, msg); archivoLog.flush(); lock->liberarLock(); } void Logger::clear() { lock->tomarLock(); string timeStamp = "output.html"; archivoLog.close(); archivoLog.open(timeStamp.c_str()); printHeader(); lock->liberarLock(); } void Logger::setLogLevel(int nivelLog){ lock->tomarLock(); nivelDeLog = nivelLog; lock->liberarLock(); } void Logger::printHeader() { archivoLog << "<table id=\"table1\" class=\"mytable\" cellspacing=\"2\" cellpadding=\"10\" >" << std::endl; archivoLog << "<tr><th>Fecha y hora</th><th>Tipo</th><th>Lugar del mensaje</th><th align=\"left\">Mensaje</th></tr>" << std::endl; } void Logger::printMessageFormatted(const std::string& fecha, const std::string& level, const std::string& tag, const std::string& message) { archivoLog << "<tr>" << std::endl; archivoLog << "<td>" << fecha << "</td>"<<std::endl; archivoLog << "<td>" << level << "</td>"<<std::endl; archivoLog << "<td>" << tag << "</td>" <<std::endl; archivoLog << "<td>" << message << "</td>" <<std::endl; archivoLog << "</tr>" << std::endl; } <|endoftext|>
<commit_before>#include <test/utility.hpp> #include <gtest/gtest.h> #include <fstream> #include <string> #include <stdexcept> using cmdstan::test::convert_model_path; using cmdstan::test::multiple_command_separator; using cmdstan::test::run_command; using cmdstan::test::run_command_output; class CmdStan : public testing::Test { public: void SetUp() { model_path = {"src", "test", "test-models", "gq_model"}; data_file_path = {"src", "test", "test-models", "gq_model.data.json"}; model_path_2 = {"src", "test", "test-models", "test_model"}; model_path_non_scalar_gq = {"src", "test", "test-models", "gq_non_scalar"}; output_file_path = {"/dev", "null"}; fitted_params_file_path = {"src", "test", "test-models", "gq_model_output.csv"}; fitted_params_file_path_2 = {"src", "test", "test-models", "test_model_output.csv"}; fitted_params_file_path_empty = {"src", "test", "test-models", "empty.csv"}; fitted_params_non_scalar_gq = {"src", "test", "test-models", "gq_non_scalar.csv"}; default_file_path = {"src", "test", "test-models", "output.csv"}; } std::vector<std::string> model_path; std::vector<std::string> data_file_path; std::vector<std::string> model_path_2; std::vector<std::string> model_path_non_scalar_gq; std::vector<std::string> output_file_path; std::vector<std::string> fitted_params_file_path; std::vector<std::string> fitted_params_file_path_2; std::vector<std::string> fitted_params_file_path_empty; std::vector<std::string> fitted_params_non_scalar_gq; std::vector<std::string> default_file_path; }; TEST_F(CmdStan, generate_quantities_good) { std::stringstream ss; ss << convert_model_path(model_path) << " data file=" << convert_model_path(data_file_path) << " output file=" << convert_model_path(output_file_path) << " method=generate_quantities fitted_params=" << convert_model_path(fitted_params_file_path); std::string cmd = ss.str(); run_command_output out = run_command(cmd); ASSERT_FALSE(out.hasError); } TEST_F(CmdStan, generate_quantities_non_scalar_good) { std::stringstream ss; ss << convert_model_path(model_path_non_scalar_gq) << " output file=" << convert_model_path(output_file_path) << " method=generate_quantities fitted_params=" << convert_model_path(fitted_params_non_scalar_gq); std::string cmd = ss.str(); run_command_output out = run_command(cmd); ASSERT_FALSE(out.hasError); } TEST_F(CmdStan, generate_quantities_bad_nodata) { std::stringstream ss; ss << convert_model_path(model_path) << " output file=" << convert_model_path(output_file_path) << " method=generate_quantities fitted_params=" << convert_model_path(fitted_params_file_path_empty) << " 2>&1"; std::string cmd = ss.str(); run_command_output out = run_command(cmd); ASSERT_TRUE(out.hasError); } TEST_F(CmdStan, generate_quantities_bad_no_gqs) { std::stringstream ss; ss << convert_model_path(model_path_2) << " output file=" << convert_model_path(output_file_path) << " method=generate_quantities " << " fitted_params=" << convert_model_path(fitted_params_file_path_2) << " 2>&1"; std::string cmd = ss.str(); run_command_output out = run_command(cmd); ASSERT_TRUE(out.hasError); } TEST_F(CmdStan, generate_quantities_wrong_csv) { std::stringstream ss; ss << convert_model_path(model_path) << " data file=" << convert_model_path(data_file_path) << " output file=" << convert_model_path(output_file_path) << " method=generate_quantities fitted_params=" << convert_model_path(fitted_params_file_path_2) << " 2>&1"; std::string cmd = ss.str(); run_command_output out = run_command(cmd); ASSERT_TRUE(out.hasError); } TEST_F(CmdStan, generate_quantities_wrong_csv_2) { std::stringstream ss; ss << convert_model_path(model_path_2) << " data file=" << convert_model_path(data_file_path) << " output file=" << convert_model_path(output_file_path) << " method=generate_quantities fitted_params=" << convert_model_path(fitted_params_file_path) << " 2>&1"; std::string cmd = ss.str(); run_command_output out = run_command(cmd); ASSERT_TRUE(out.hasError); } TEST_F(CmdStan, generate_quantities_csv_conflict) { std::stringstream ss; ss << convert_model_path(model_path) << " data file=" << convert_model_path(data_file_path) << " output file=" << convert_model_path(default_file_path) << " method=generate_quantities fitted_params=" << convert_model_path(default_file_path); // << " 2>&1"; std::string cmd = ss.str(); run_command_output out = run_command(cmd); ASSERT_TRUE(out.hasError); } <commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2 (tags/RELEASE_600/final)<commit_after>#include <test/utility.hpp> #include <gtest/gtest.h> #include <fstream> #include <string> #include <stdexcept> using cmdstan::test::convert_model_path; using cmdstan::test::multiple_command_separator; using cmdstan::test::run_command; using cmdstan::test::run_command_output; class CmdStan : public testing::Test { public: void SetUp() { model_path = {"src", "test", "test-models", "gq_model"}; data_file_path = {"src", "test", "test-models", "gq_model.data.json"}; model_path_2 = {"src", "test", "test-models", "test_model"}; model_path_non_scalar_gq = {"src", "test", "test-models", "gq_non_scalar"}; output_file_path = {"/dev", "null"}; fitted_params_file_path = {"src", "test", "test-models", "gq_model_output.csv"}; fitted_params_file_path_2 = {"src", "test", "test-models", "test_model_output.csv"}; fitted_params_file_path_empty = {"src", "test", "test-models", "empty.csv"}; fitted_params_non_scalar_gq = {"src", "test", "test-models", "gq_non_scalar.csv"}; default_file_path = {"src", "test", "test-models", "output.csv"}; } std::vector<std::string> model_path; std::vector<std::string> data_file_path; std::vector<std::string> model_path_2; std::vector<std::string> model_path_non_scalar_gq; std::vector<std::string> output_file_path; std::vector<std::string> fitted_params_file_path; std::vector<std::string> fitted_params_file_path_2; std::vector<std::string> fitted_params_file_path_empty; std::vector<std::string> fitted_params_non_scalar_gq; std::vector<std::string> default_file_path; }; TEST_F(CmdStan, generate_quantities_good) { std::stringstream ss; ss << convert_model_path(model_path) << " data file=" << convert_model_path(data_file_path) << " output file=" << convert_model_path(output_file_path) << " method=generate_quantities fitted_params=" << convert_model_path(fitted_params_file_path); std::string cmd = ss.str(); run_command_output out = run_command(cmd); ASSERT_FALSE(out.hasError); } TEST_F(CmdStan, generate_quantities_non_scalar_good) { std::stringstream ss; ss << convert_model_path(model_path_non_scalar_gq) << " output file=" << convert_model_path(output_file_path) << " method=generate_quantities fitted_params=" << convert_model_path(fitted_params_non_scalar_gq); std::string cmd = ss.str(); run_command_output out = run_command(cmd); ASSERT_FALSE(out.hasError); } TEST_F(CmdStan, generate_quantities_bad_nodata) { std::stringstream ss; ss << convert_model_path(model_path) << " output file=" << convert_model_path(output_file_path) << " method=generate_quantities fitted_params=" << convert_model_path(fitted_params_file_path_empty) << " 2>&1"; std::string cmd = ss.str(); run_command_output out = run_command(cmd); ASSERT_TRUE(out.hasError); } TEST_F(CmdStan, generate_quantities_bad_no_gqs) { std::stringstream ss; ss << convert_model_path(model_path_2) << " output file=" << convert_model_path(output_file_path) << " method=generate_quantities " << " fitted_params=" << convert_model_path(fitted_params_file_path_2) << " 2>&1"; std::string cmd = ss.str(); run_command_output out = run_command(cmd); ASSERT_TRUE(out.hasError); } TEST_F(CmdStan, generate_quantities_wrong_csv) { std::stringstream ss; ss << convert_model_path(model_path) << " data file=" << convert_model_path(data_file_path) << " output file=" << convert_model_path(output_file_path) << " method=generate_quantities fitted_params=" << convert_model_path(fitted_params_file_path_2) << " 2>&1"; std::string cmd = ss.str(); run_command_output out = run_command(cmd); ASSERT_TRUE(out.hasError); } TEST_F(CmdStan, generate_quantities_wrong_csv_2) { std::stringstream ss; ss << convert_model_path(model_path_2) << " data file=" << convert_model_path(data_file_path) << " output file=" << convert_model_path(output_file_path) << " method=generate_quantities fitted_params=" << convert_model_path(fitted_params_file_path) << " 2>&1"; std::string cmd = ss.str(); run_command_output out = run_command(cmd); ASSERT_TRUE(out.hasError); } TEST_F(CmdStan, generate_quantities_csv_conflict) { std::stringstream ss; ss << convert_model_path(model_path) << " data file=" << convert_model_path(data_file_path) << " output file=" << convert_model_path(default_file_path) << " method=generate_quantities fitted_params=" << convert_model_path(default_file_path); // << " 2>&1"; std::string cmd = ss.str(); run_command_output out = run_command(cmd); ASSERT_TRUE(out.hasError); } <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Doxygen plugin for Qt Creator ** ** Copyright (c) 2009 Kevin Tanguy ([email protected]). ** Copyright (c) 2015 Fabien Poussin ([email protected]). ** ** This plugin is free software: you can redistribute it and/or modify ** it under the terms of the GNU Lesser General Public License as ** published by the Free Software Foundation, either version 2.1 ** of the License, or (at your option) any later version. ** ** This plugin is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU Lesser General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with Doxygen Plugin. If not, see <http://www.gnu.org/licenses/>. **/ #include "doxygensettingswidget.h" #include "ui_doxygensettingswidget.h" DoxygenSettingsWidget::DoxygenSettingsWidget(QWidget* parent) : QWidget(parent) , ui(new Ui::DoxygenSettingsWidget) { ui->setupUi(this); ui->pathChooser_doxygen->setExpectedKind(Utils::PathChooser::Command); ui->pathChooser_doxygen->setPromptDialogTitle(tr("Doxygen Command")); ui->pathChooser_wizard->setExpectedKind(Utils::PathChooser::Command); ui->pathChooser_wizard->setPromptDialogTitle(tr("DoxyWizard Command")); // Why do I *have* to call processEvents() to get my QComboBox display the right value?! qApp->processEvents(); connect(ui->styleChooser, SIGNAL(currentIndexChanged(int)), this, SLOT(updateCustomWidgetPart(int))); } DoxygenSettingsWidget::~DoxygenSettingsWidget() { delete ui; } void DoxygenSettingsWidget::changeEvent(QEvent* e) { QWidget::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: ui->retranslateUi(this); break; default: break; } } DoxygenSettingsStruct DoxygenSettingsWidget::settings() const { DoxygenSettingsStruct rc; rc.doxygenCommand = ui->pathChooser_doxygen->path(); rc.doxyfileFileName = ui->edit_doxyfileName->text(); rc.doxywizardCommand = ui->pathChooser_wizard->path(); rc.style = DoxygenStyle(ui->styleChooser->currentIndex()); rc.fcomment = Files2Comment(ui->fcommentChooser->currentIndex()); rc.printBrief = ui->printBriefTag->isChecked(); rc.shortVarDoc = ui->shortVariableDoc->isChecked(); rc.verbosePrinting = ui->verbosePrinting->isChecked(); rc.customBegin = QString(ui->edit_beginTag->text()).replace("\\n", "\n"); rc.customBrief = QString(ui->edit_briefTag->text()).replace("\\n", "\n"); rc.customEmptyLine = QString(ui->edit_emptyLineTag->text()).replace("\\n", "\n"); rc.customEnding = QString(ui->edit_endTag->text()).replace("\\n", "\n"); rc.customNewLine = QString(ui->edit_newLine->text()).replace("\\n", "\n"); rc.customShortDoc = QString(ui->edit_shortTag->text()).replace("\\n", "\n"); rc.customShortDocEnd = QString(ui->edit_shortTagEnd->text()).replace("\\\n", "\n"); rc.fileComment = ui->fileCommentText->toPlainText(); rc.fileCommentHeaders = ui->commentHeaderFiles->isChecked(); rc.fileCommentImpl = ui->commentImplementationFiles->isChecked(); rc.fileCommentsEnabled = ui->fileComments->isChecked(); rc.automaticReturnType = ui->autoAddReturnTypes->isChecked(); return rc; } void DoxygenSettingsWidget::setSettings(const DoxygenSettingsStruct& s) { ui->pathChooser_doxygen->setPath(s.doxygenCommand); ui->pathChooser_wizard->setPath(s.doxywizardCommand); ui->edit_doxyfileName->setText(s.doxyfileFileName); ui->styleChooser->setCurrentIndex(s.style); ui->fcommentChooser->setCurrentIndex(s.fcomment); ui->printBriefTag->setChecked(s.printBrief); ui->shortVariableDoc->setChecked(s.shortVarDoc); ui->verbosePrinting->setChecked(s.verbosePrinting); ui->edit_beginTag->setText(QString(s.customBegin).replace("\n", "\\n")); ui->edit_briefTag->setText(QString(s.customBrief).replace("\n", "\\n")); ui->edit_emptyLineTag->setText(QString(s.customEmptyLine).replace("\n", "\\n")); ui->edit_endTag->setText(QString(s.customEnding).replace("\n", "\\n")); ui->edit_newLine->setText(QString(s.customNewLine).replace("\n", "\\n")); ui->edit_shortTag->setText(QString(s.customShortDoc).replace("\n", "\\n")); ui->edit_shortTagEnd->setText(QString(s.customShortDocEnd).replace("\n", "\\n")); ui->fileCommentText->setPlainText(s.fileComment); ui->fileComments->setChecked(s.fileCommentsEnabled); ui->commentHeaderFiles->setChecked(s.fileCommentHeaders); ui->commentImplementationFiles->setChecked(s.fileCommentImpl); ui->autoAddReturnTypes->setChecked(s.automaticReturnType); updateCustomWidgetPart(s.style); on_fileComments_clicked(s.fileCommentsEnabled); } void DoxygenSettingsWidget::updateCustomWidgetPart(int index) { ui->customCommentsSettings->setEnabled(index == customDoc); } void DoxygenSettingsWidget::on_fileComments_clicked(bool checked) { Files2Comment toComment = Files2Comment(ui->fcommentChooser->currentIndex()); ui->fileCommentText->setEnabled(checked); if (checked == false || toComment == all) { checked = false; ui->label_filecommentHeaders->setVisible(checked); ui->label_filecommentImpl->setVisible(checked); ui->commentHeaderFiles->setVisible(checked); ui->commentImplementationFiles->setVisible(checked); } else if (toComment == headers) { ui->label_filecommentHeaders->setVisible(false); ui->label_filecommentImpl->setVisible(true); ui->commentHeaderFiles->setVisible(false); ui->commentImplementationFiles->setVisible(true); } else if (toComment == implementations) { ui->label_filecommentHeaders->setVisible(true); ui->label_filecommentImpl->setVisible(false); ui->commentHeaderFiles->setVisible(true); ui->commentImplementationFiles->setVisible(false); } } void DoxygenSettingsWidget::on_fcommentChooser_currentIndexChanged(int index) { Q_UNUSED(index) on_fileComments_clicked(ui->fileComments->isChecked()); } <commit_msg>fixed typo in rc.customShortDocEnd definition<commit_after>/************************************************************************** ** ** This file is part of Doxygen plugin for Qt Creator ** ** Copyright (c) 2009 Kevin Tanguy ([email protected]). ** Copyright (c) 2015 Fabien Poussin ([email protected]). ** ** This plugin is free software: you can redistribute it and/or modify ** it under the terms of the GNU Lesser General Public License as ** published by the Free Software Foundation, either version 2.1 ** of the License, or (at your option) any later version. ** ** This plugin is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU Lesser General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with Doxygen Plugin. If not, see <http://www.gnu.org/licenses/>. **/ #include "doxygensettingswidget.h" #include "ui_doxygensettingswidget.h" DoxygenSettingsWidget::DoxygenSettingsWidget(QWidget* parent) : QWidget(parent) , ui(new Ui::DoxygenSettingsWidget) { ui->setupUi(this); ui->pathChooser_doxygen->setExpectedKind(Utils::PathChooser::Command); ui->pathChooser_doxygen->setPromptDialogTitle(tr("Doxygen Command")); ui->pathChooser_wizard->setExpectedKind(Utils::PathChooser::Command); ui->pathChooser_wizard->setPromptDialogTitle(tr("DoxyWizard Command")); // Why do I *have* to call processEvents() to get my QComboBox display the right value?! qApp->processEvents(); connect(ui->styleChooser, SIGNAL(currentIndexChanged(int)), this, SLOT(updateCustomWidgetPart(int))); } DoxygenSettingsWidget::~DoxygenSettingsWidget() { delete ui; } void DoxygenSettingsWidget::changeEvent(QEvent* e) { QWidget::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: ui->retranslateUi(this); break; default: break; } } DoxygenSettingsStruct DoxygenSettingsWidget::settings() const { DoxygenSettingsStruct rc; rc.doxygenCommand = ui->pathChooser_doxygen->path(); rc.doxyfileFileName = ui->edit_doxyfileName->text(); rc.doxywizardCommand = ui->pathChooser_wizard->path(); rc.style = DoxygenStyle(ui->styleChooser->currentIndex()); rc.fcomment = Files2Comment(ui->fcommentChooser->currentIndex()); rc.printBrief = ui->printBriefTag->isChecked(); rc.shortVarDoc = ui->shortVariableDoc->isChecked(); rc.verbosePrinting = ui->verbosePrinting->isChecked(); rc.customBegin = QString(ui->edit_beginTag->text()).replace("\\n", "\n"); rc.customBrief = QString(ui->edit_briefTag->text()).replace("\\n", "\n"); rc.customEmptyLine = QString(ui->edit_emptyLineTag->text()).replace("\\n", "\n"); rc.customEnding = QString(ui->edit_endTag->text()).replace("\\n", "\n"); rc.customNewLine = QString(ui->edit_newLine->text()).replace("\\n", "\n"); rc.customShortDoc = QString(ui->edit_shortTag->text()).replace("\\n", "\n"); rc.customShortDocEnd = QString(ui->edit_shortTagEnd->text()).replace("\\n", "\n"); rc.fileComment = ui->fileCommentText->toPlainText(); rc.fileCommentHeaders = ui->commentHeaderFiles->isChecked(); rc.fileCommentImpl = ui->commentImplementationFiles->isChecked(); rc.fileCommentsEnabled = ui->fileComments->isChecked(); rc.automaticReturnType = ui->autoAddReturnTypes->isChecked(); return rc; } void DoxygenSettingsWidget::setSettings(const DoxygenSettingsStruct& s) { ui->pathChooser_doxygen->setPath(s.doxygenCommand); ui->pathChooser_wizard->setPath(s.doxywizardCommand); ui->edit_doxyfileName->setText(s.doxyfileFileName); ui->styleChooser->setCurrentIndex(s.style); ui->fcommentChooser->setCurrentIndex(s.fcomment); ui->printBriefTag->setChecked(s.printBrief); ui->shortVariableDoc->setChecked(s.shortVarDoc); ui->verbosePrinting->setChecked(s.verbosePrinting); ui->edit_beginTag->setText(QString(s.customBegin).replace("\n", "\\n")); ui->edit_briefTag->setText(QString(s.customBrief).replace("\n", "\\n")); ui->edit_emptyLineTag->setText(QString(s.customEmptyLine).replace("\n", "\\n")); ui->edit_endTag->setText(QString(s.customEnding).replace("\n", "\\n")); ui->edit_newLine->setText(QString(s.customNewLine).replace("\n", "\\n")); ui->edit_shortTag->setText(QString(s.customShortDoc).replace("\n", "\\n")); ui->edit_shortTagEnd->setText(QString(s.customShortDocEnd).replace("\n", "\\n")); ui->fileCommentText->setPlainText(s.fileComment); ui->fileComments->setChecked(s.fileCommentsEnabled); ui->commentHeaderFiles->setChecked(s.fileCommentHeaders); ui->commentImplementationFiles->setChecked(s.fileCommentImpl); ui->autoAddReturnTypes->setChecked(s.automaticReturnType); updateCustomWidgetPart(s.style); on_fileComments_clicked(s.fileCommentsEnabled); } void DoxygenSettingsWidget::updateCustomWidgetPart(int index) { ui->customCommentsSettings->setEnabled(index == customDoc); } void DoxygenSettingsWidget::on_fileComments_clicked(bool checked) { Files2Comment toComment = Files2Comment(ui->fcommentChooser->currentIndex()); ui->fileCommentText->setEnabled(checked); if (checked == false || toComment == all) { checked = false; ui->label_filecommentHeaders->setVisible(checked); ui->label_filecommentImpl->setVisible(checked); ui->commentHeaderFiles->setVisible(checked); ui->commentImplementationFiles->setVisible(checked); } else if (toComment == headers) { ui->label_filecommentHeaders->setVisible(false); ui->label_filecommentImpl->setVisible(true); ui->commentHeaderFiles->setVisible(false); ui->commentImplementationFiles->setVisible(true); } else if (toComment == implementations) { ui->label_filecommentHeaders->setVisible(true); ui->label_filecommentImpl->setVisible(false); ui->commentHeaderFiles->setVisible(true); ui->commentImplementationFiles->setVisible(false); } } void DoxygenSettingsWidget::on_fcommentChooser_currentIndexChanged(int index) { Q_UNUSED(index) on_fileComments_clicked(ui->fileComments->isChecked()); } <|endoftext|>
<commit_before>#include "GliderManipulator.h" #include <osg/Notify> using namespace osg; using namespace osgGA; GliderManipulator::GliderManipulator() { _modelScale = 0.01f; _velocity = 0.0f; _yawMode = YAW_AUTOMATICALLY_WHEN_BANKED; _distance = 1.0f; } GliderManipulator::~GliderManipulator() { } void GliderManipulator::setNode(osg::Node* node) { _node = node; if (_node.get()) { const osg::BoundingSphere& boundingSphere=_node->getBound(); _modelScale = boundingSphere._radius; } } const osg::Node* GliderManipulator::getNode() const { return _node.get(); } osg::Node* GliderManipulator::getNode() { return _node.get(); } void GliderManipulator::home(const GUIEventAdapter& ea,GUIActionAdapter& us) { if(_node.get()) { const osg::BoundingSphere& boundingSphere=_node->getBound(); osg::Vec3 eye = boundingSphere._center+osg::Vec3(-boundingSphere._radius*0.25f,-boundingSphere._radius*0.25f,-boundingSphere._radius*0.03f); computePosition(eye, osg::Vec3(1.0f,1.0f,-0.1f), osg::Vec3(0.0f,0.0f,1.0f)); _velocity = boundingSphere._radius*0.01f; us.requestRedraw(); us.requestWarpPointer((ea.getXmin()+ea.getXmax())/2.0f,(ea.getYmin()+ea.getYmax())/2.0f); flushMouseEventStack(); } } void GliderManipulator::init(const GUIEventAdapter& ea,GUIActionAdapter& us) { flushMouseEventStack(); us.requestContinuousUpdate(false); _velocity = 0.0f; if (ea.getEventType()!=GUIEventAdapter::RESIZE) { us.requestWarpPointer((ea.getXmin()+ea.getXmax())/2.0f,(ea.getYmin()+ea.getYmax())/2.0f); } } bool GliderManipulator::handle(const GUIEventAdapter& ea,GUIActionAdapter& us) { switch(ea.getEventType()) { case(GUIEventAdapter::PUSH): { addMouseEvent(ea); us.requestContinuousUpdate(true); if (calcMovement()) us.requestRedraw(); return true; } case(GUIEventAdapter::RELEASE): { addMouseEvent(ea); us.requestContinuousUpdate(true); if (calcMovement()) us.requestRedraw(); return true; } case(GUIEventAdapter::DRAG): { addMouseEvent(ea); us.requestContinuousUpdate(true); if (calcMovement()) us.requestRedraw(); return true; } case(GUIEventAdapter::MOVE): { addMouseEvent(ea); us.requestContinuousUpdate(true); if (calcMovement()) us.requestRedraw(); return true; } case(GUIEventAdapter::KEYDOWN): if (ea.getKey()==' ') { flushMouseEventStack(); home(ea,us); us.requestRedraw(); us.requestContinuousUpdate(false); return true; } else if (ea.getKey()=='q') { _yawMode = YAW_AUTOMATICALLY_WHEN_BANKED; return true; } else if (ea.getKey()=='a') { _yawMode = NO_AUTOMATIC_YAW; return true; } return false; case(GUIEventAdapter::FRAME): addMouseEvent(ea); if (calcMovement()) us.requestRedraw(); return true; case(GUIEventAdapter::RESIZE): init(ea,us); us.requestRedraw(); return true; default: return false; } } void GliderManipulator::getUsage(osg::ApplicationUsage& usage) const { usage.addKeyboardMouseBinding("Flight: Space","Reset the viewing position to home"); usage.addKeyboardMouseBinding("Flight: q","Automatically yaw when banked (default)"); usage.addKeyboardMouseBinding("Flight: a","No yaw when banked"); } void GliderManipulator::flushMouseEventStack() { _ga_t1 = NULL; _ga_t0 = NULL; } void GliderManipulator::addMouseEvent(const GUIEventAdapter& ea) { _ga_t1 = _ga_t0; _ga_t0 = &ea; } void GliderManipulator::setByMatrix(const osg::Matrixd& matrix) { _eye = matrix.getTrans(); matrix.get(_rotation); _distance = 1.0f; } osg::Matrixd GliderManipulator::getMatrix() const { return osg::Matrixd::rotate(_rotation)*osg::Matrixd::translate(_eye); } osg::Matrixd GliderManipulator::getInverseMatrix() const { return osg::Matrixd::translate(-_eye)*osg::Matrixd::rotate(_rotation.inverse()); } void GliderManipulator::computePosition(const osg::Vec3& eye,const osg::Vec3& lv,const osg::Vec3& up) { osg::Vec3 f(lv); f.normalize(); osg::Vec3 s(f^up); s.normalize(); osg::Vec3 u(s^f); u.normalize(); osg::Matrixd rotation_matrix(s[0], u[0], -f[0], 0.0f, s[1], u[1], -f[1], 0.0f, s[2], u[2], -f[2], 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); _eye = eye; _distance = lv.length(); rotation_matrix.get(_rotation); _rotation = _rotation.inverse(); } bool GliderManipulator::calcMovement() { //_camera->setFusionDistanceMode(osg::Camera::PROPORTIONAL_TO_SCREEN_DISTANCE); // return if less then two events have been added. if (_ga_t0.get()==NULL || _ga_t1.get()==NULL) return false; double dt = _ga_t0->time()-_ga_t1->time(); if (dt<0.0f) { notify(WARN) << "warning dt = "<<dt<< std::endl; dt = 0.0f; } unsigned int buttonMask = _ga_t1->getButtonMask(); if (buttonMask==GUIEventAdapter::LEFT_MOUSE_BUTTON) { // pan model. _velocity += dt*_modelScale*0.05f; } else if (buttonMask==GUIEventAdapter::MIDDLE_MOUSE_BUTTON || buttonMask==(GUIEventAdapter::LEFT_MOUSE_BUTTON|GUIEventAdapter::RIGHT_MOUSE_BUTTON)) { _velocity = 0.0f; } else if (buttonMask==GUIEventAdapter::RIGHT_MOUSE_BUTTON) { _velocity -= dt*_modelScale*0.05f; } float dx = _ga_t0->getXnormalized(); float dy = _ga_t0->getYnormalized(); osg::Matrixd rotation_matrix; rotation_matrix.makeRotate(_rotation); osg::Vec3 up = osg::Vec3(0.0f,1.0f,0.0) * rotation_matrix; osg::Vec3 lv = osg::Vec3(0.0f,0.0f,-1.0f) * rotation_matrix; osg::Vec3 sv = lv^up; sv.normalize(); float pitch = -inDegrees(dy*75.0f*dt); float roll = inDegrees(dx*50.0f*dt); osg::Quat delta_rotate; osg::Quat roll_rotate; osg::Quat pitch_rotate; pitch_rotate.makeRotate(pitch,sv.x(),sv.y(),sv.z()); roll_rotate.makeRotate(roll,lv.x(),lv.y(),lv.z()); delta_rotate = pitch_rotate*roll_rotate; if (_yawMode==YAW_AUTOMATICALLY_WHEN_BANKED) { float bank = asinf(sv.z()); float yaw = inRadians(bank)*dt; osg::Quat yaw_rotate; yaw_rotate.makeRotate(yaw,0.0f,0.0f,1.0f); delta_rotate = delta_rotate*yaw_rotate; } lv *= (_velocity*dt); _eye += lv; _rotation = _rotation*delta_rotate; return true; } <commit_msg>Maded debugging output write out at INFO level<commit_after>#include "GliderManipulator.h" #include <osg/Notify> using namespace osg; using namespace osgGA; GliderManipulator::GliderManipulator() { _modelScale = 0.01f; _velocity = 0.0f; _yawMode = YAW_AUTOMATICALLY_WHEN_BANKED; _distance = 1.0f; } GliderManipulator::~GliderManipulator() { } void GliderManipulator::setNode(osg::Node* node) { _node = node; if (_node.get()) { const osg::BoundingSphere& boundingSphere=_node->getBound(); _modelScale = boundingSphere._radius; } } const osg::Node* GliderManipulator::getNode() const { return _node.get(); } osg::Node* GliderManipulator::getNode() { return _node.get(); } void GliderManipulator::home(const GUIEventAdapter& ea,GUIActionAdapter& us) { if(_node.get()) { const osg::BoundingSphere& boundingSphere=_node->getBound(); osg::Vec3 eye = boundingSphere._center+osg::Vec3(-boundingSphere._radius*0.25f,-boundingSphere._radius*0.25f,-boundingSphere._radius*0.03f); computePosition(eye, osg::Vec3(1.0f,1.0f,-0.1f), osg::Vec3(0.0f,0.0f,1.0f)); _velocity = boundingSphere._radius*0.01f; us.requestRedraw(); us.requestWarpPointer((ea.getXmin()+ea.getXmax())/2.0f,(ea.getYmin()+ea.getYmax())/2.0f); flushMouseEventStack(); } } void GliderManipulator::init(const GUIEventAdapter& ea,GUIActionAdapter& us) { flushMouseEventStack(); us.requestContinuousUpdate(false); _velocity = 0.0f; if (ea.getEventType()!=GUIEventAdapter::RESIZE) { us.requestWarpPointer((ea.getXmin()+ea.getXmax())/2.0f,(ea.getYmin()+ea.getYmax())/2.0f); } } bool GliderManipulator::handle(const GUIEventAdapter& ea,GUIActionAdapter& us) { switch(ea.getEventType()) { case(GUIEventAdapter::PUSH): { addMouseEvent(ea); us.requestContinuousUpdate(true); if (calcMovement()) us.requestRedraw(); return true; } case(GUIEventAdapter::RELEASE): { addMouseEvent(ea); us.requestContinuousUpdate(true); if (calcMovement()) us.requestRedraw(); return true; } case(GUIEventAdapter::DRAG): { addMouseEvent(ea); us.requestContinuousUpdate(true); if (calcMovement()) us.requestRedraw(); return true; } case(GUIEventAdapter::MOVE): { addMouseEvent(ea); us.requestContinuousUpdate(true); if (calcMovement()) us.requestRedraw(); return true; } case(GUIEventAdapter::KEYDOWN): if (ea.getKey()==' ') { flushMouseEventStack(); home(ea,us); us.requestRedraw(); us.requestContinuousUpdate(false); return true; } else if (ea.getKey()=='q') { _yawMode = YAW_AUTOMATICALLY_WHEN_BANKED; return true; } else if (ea.getKey()=='a') { _yawMode = NO_AUTOMATIC_YAW; return true; } return false; case(GUIEventAdapter::FRAME): addMouseEvent(ea); if (calcMovement()) us.requestRedraw(); return true; case(GUIEventAdapter::RESIZE): init(ea,us); us.requestRedraw(); return true; default: return false; } } void GliderManipulator::getUsage(osg::ApplicationUsage& usage) const { usage.addKeyboardMouseBinding("Flight: Space","Reset the viewing position to home"); usage.addKeyboardMouseBinding("Flight: q","Automatically yaw when banked (default)"); usage.addKeyboardMouseBinding("Flight: a","No yaw when banked"); } void GliderManipulator::flushMouseEventStack() { _ga_t1 = NULL; _ga_t0 = NULL; } void GliderManipulator::addMouseEvent(const GUIEventAdapter& ea) { _ga_t1 = _ga_t0; _ga_t0 = &ea; } void GliderManipulator::setByMatrix(const osg::Matrixd& matrix) { _eye = matrix.getTrans(); matrix.get(_rotation); _distance = 1.0f; } osg::Matrixd GliderManipulator::getMatrix() const { return osg::Matrixd::rotate(_rotation)*osg::Matrixd::translate(_eye); } osg::Matrixd GliderManipulator::getInverseMatrix() const { return osg::Matrixd::translate(-_eye)*osg::Matrixd::rotate(_rotation.inverse()); } void GliderManipulator::computePosition(const osg::Vec3& eye,const osg::Vec3& lv,const osg::Vec3& up) { osg::Vec3 f(lv); f.normalize(); osg::Vec3 s(f^up); s.normalize(); osg::Vec3 u(s^f); u.normalize(); osg::Matrixd rotation_matrix(s[0], u[0], -f[0], 0.0f, s[1], u[1], -f[1], 0.0f, s[2], u[2], -f[2], 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); _eye = eye; _distance = lv.length(); rotation_matrix.get(_rotation); _rotation = _rotation.inverse(); } bool GliderManipulator::calcMovement() { //_camera->setFusionDistanceMode(osg::Camera::PROPORTIONAL_TO_SCREEN_DISTANCE); // return if less then two events have been added. if (_ga_t0.get()==NULL || _ga_t1.get()==NULL) return false; double dt = _ga_t0->time()-_ga_t1->time(); if (dt<0.0f) { notify(INFO) << "warning dt = "<<dt<< std::endl; dt = 0.0f; } unsigned int buttonMask = _ga_t1->getButtonMask(); if (buttonMask==GUIEventAdapter::LEFT_MOUSE_BUTTON) { // pan model. _velocity += dt*_modelScale*0.05f; } else if (buttonMask==GUIEventAdapter::MIDDLE_MOUSE_BUTTON || buttonMask==(GUIEventAdapter::LEFT_MOUSE_BUTTON|GUIEventAdapter::RIGHT_MOUSE_BUTTON)) { _velocity = 0.0f; } else if (buttonMask==GUIEventAdapter::RIGHT_MOUSE_BUTTON) { _velocity -= dt*_modelScale*0.05f; } float dx = _ga_t0->getXnormalized(); float dy = _ga_t0->getYnormalized(); osg::Matrixd rotation_matrix; rotation_matrix.makeRotate(_rotation); osg::Vec3 up = osg::Vec3(0.0f,1.0f,0.0) * rotation_matrix; osg::Vec3 lv = osg::Vec3(0.0f,0.0f,-1.0f) * rotation_matrix; osg::Vec3 sv = lv^up; sv.normalize(); float pitch = -inDegrees(dy*75.0f*dt); float roll = inDegrees(dx*50.0f*dt); osg::Quat delta_rotate; osg::Quat roll_rotate; osg::Quat pitch_rotate; pitch_rotate.makeRotate(pitch,sv.x(),sv.y(),sv.z()); roll_rotate.makeRotate(roll,lv.x(),lv.y(),lv.z()); delta_rotate = pitch_rotate*roll_rotate; if (_yawMode==YAW_AUTOMATICALLY_WHEN_BANKED) { float bank = asinf(sv.z()); float yaw = inRadians(bank)*dt; osg::Quat yaw_rotate; yaw_rotate.makeRotate(yaw,0.0f,0.0f,1.0f); delta_rotate = delta_rotate*yaw_rotate; } lv *= (_velocity*dt); _eye += lv; _rotation = _rotation*delta_rotate; return true; } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Log$ * Revision 1.8 2002/11/20 20:28:17 peiyongz * fix to warning C4018: '>' : signed/unsigned mismatch * * Revision 1.7 2002/11/12 17:27:49 tng * DOM Message: add new domain for DOM Messages. * * Revision 1.6 2002/11/04 22:24:43 peiyongz * Locale setting for message loader * * Revision 1.5 2002/11/04 15:10:40 tng * C++ Namespace Support. * * Revision 1.4 2002/10/10 21:07:55 peiyongz * load resource files using environement vars and base name * * Revision 1.3 2002/10/02 17:08:50 peiyongz * XMLString::equals() to replace XMLString::compareString() * * Revision 1.2 2002/09/30 22:20:40 peiyongz * Build with ICU MsgLoader * * Revision 1.1.1.1 2002/02/01 22:22:19 peiyongz * sane_include * * Revision 1.7 2002/01/21 14:52:25 tng * [Bug 5847] ICUMsgLoader can't be compiled with gcc 3.0.3 and ICU2. And also fix the memory leak introduced by Bug 2730 fix. * * Revision 1.6 2001/11/01 23:39:18 jasons * 2001-11-01 Jason E. Stewart <[email protected]> * * * src/util/MsgLoaders/ICU/ICUMsgLoader.hpp (Repository): * * src/util/MsgLoaders/ICU/ICUMsgLoader.cpp (Repository): * Updated to compile with ICU-1.8.1 * * Revision 1.5 2000/03/02 19:55:14 roddey * This checkin includes many changes done while waiting for the * 1.1.0 code to be finished. I can't list them all here, but a list is * available elsewhere. * * Revision 1.4 2000/02/06 07:48:21 rahulj * Year 2K copyright swat. * * Revision 1.3 2000/01/19 00:58:38 roddey * Update to support new ICU 1.4 release. * * Revision 1.2 1999/11/19 21:24:03 aruna1 * incorporated ICU 1.3.1 related changes int he file * * Revision 1.1.1.1 1999/11/09 01:07:23 twl * Initial checkin * * Revision 1.4 1999/11/08 20:45:26 rahul * Swat for adding in Product name and CVS comment log variable. * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/util/XercesDefs.hpp> #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/util/XMLMsgLoader.hpp> #include <xercesc/util/XMLString.hpp> #include <xercesc/util/XMLUniDefs.hpp> #include <xercesc/util/Janitor.hpp> #include "ICUMsgLoader.hpp" #include "string.h" #include <stdio.h> #include <stdlib.h> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // Local static methods // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // Public Constructors and Destructor // --------------------------------------------------------------------------- ICUMsgLoader::ICUMsgLoader(const XMLCh* const msgDomain) :fLocaleBundle(0) ,fDomainBundle(0) { /*** Validate msgDomain ***/ if (!XMLString::equals(msgDomain, XMLUni::fgXMLErrDomain) && !XMLString::equals(msgDomain, XMLUni::fgExceptDomain) && !XMLString::equals(msgDomain, XMLUni::fgXMLDOMMsgDomain) && !XMLString::equals(msgDomain, XMLUni::fgValidityDomain) ) { XMLPlatformUtils::panic(XMLPlatformUtils::Panic_UnknownMsgDomain); } /*** Resolve domainName ***/ int index = XMLString::lastIndexOf(msgDomain, chForwardSlash); char* domainName = XMLString::transcode(&(msgDomain[index + 1])); ArrayJanitor<char> jan1(domainName); /*** Resolve location REVISIT: another approach would be: through some system API which returns the directory of the XercescLib and that directory would be used to locate the resource bundle ***/ char locationBuf[1024]; memset(locationBuf, 0, sizeof locationBuf); char *nlsHome = getenv("XERCESC_NLS_HOME"); if (nlsHome) { strcpy(locationBuf, nlsHome); strcat(locationBuf, U_FILE_SEP_STRING); } strcat(locationBuf, "XercescErrMsg"); /*** Open the locale-specific resource bundle ***/ UErrorCode err = U_ZERO_ERROR; fLocaleBundle = ures_open(locationBuf, XMLMsgLoader::getLocale(), &err); if (!U_SUCCESS(err) || fLocaleBundle == NULL) { XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain); } /*** Open the domain specific resource bundle within the locale-specific resource bundle ***/ err = U_ZERO_ERROR; fDomainBundle = ures_getByKey(fLocaleBundle, domainName, NULL, &err); if (!U_SUCCESS(err) || fDomainBundle == NULL) { XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain); } } ICUMsgLoader::~ICUMsgLoader() { ures_close(fDomainBundle); ures_close(fLocaleBundle); } // --------------------------------------------------------------------------- // Implementation of the virtual message loader API // --------------------------------------------------------------------------- bool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad , XMLCh* const toFill , const unsigned int maxChars) { UErrorCode err = U_ZERO_ERROR; int32_t strLen = 0; // Assuming array format const UChar *name = ures_getStringByIndex(fDomainBundle, (int32_t)msgToLoad-1, &strLen, &err); if (!U_SUCCESS(err) || (name == NULL)) { return false; } int retStrLen = strLen > (int32_t)maxChars ? maxChars : strLen; if (sizeof(UChar)==sizeof(XMLCh)) { XMLString::moveChars(toFill, (XMLCh*)name, retStrLen); toFill[retStrLen] = (XMLCh) 0; } else { XMLCh* retStr = toFill; const UChar *srcPtr = name; while (retStrLen--) *retStr++ = *srcPtr++; *retStr = 0; } return true; } bool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad , XMLCh* const toFill , const unsigned int maxChars , const XMLCh* const repText1 , const XMLCh* const repText2 , const XMLCh* const repText3 , const XMLCh* const repText4) { // Call the other version to load up the message if (!loadMsg(msgToLoad, toFill, maxChars)) return false; // And do the token replacement XMLString::replaceTokens(toFill, maxChars, repText1, repText2, repText3, repText4); return true; } bool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad , XMLCh* const toFill , const unsigned int maxChars , const char* const repText1 , const char* const repText2 , const char* const repText3 , const char* const repText4) { // // Transcode the provided parameters and call the other version, // which will do the replacement work. // XMLCh* tmp1 = 0; XMLCh* tmp2 = 0; XMLCh* tmp3 = 0; XMLCh* tmp4 = 0; bool bRet = false; if (repText1) tmp1 = XMLString::transcode(repText1); if (repText2) tmp2 = XMLString::transcode(repText2); if (repText3) tmp3 = XMLString::transcode(repText3); if (repText4) tmp4 = XMLString::transcode(repText4); bRet = loadMsg(msgToLoad, toFill, maxChars, tmp1, tmp2, tmp3, tmp4); if (tmp1) delete [] tmp1; if (tmp2) delete [] tmp2; if (tmp3) delete [] tmp3; if (tmp4) delete [] tmp4; return bRet; } XERCES_CPP_NAMESPACE_END <commit_msg>use $XERCESCROOT to search for icu resource bundle if XERCESC_NLS_HOME undefined<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Log$ * Revision 1.9 2002/12/04 18:11:23 peiyongz * use $XERCESCROOT to search for icu resource bundle if XERCESC_NLS_HOME * undefined * * Revision 1.8 2002/11/20 20:28:17 peiyongz * fix to warning C4018: '>' : signed/unsigned mismatch * * Revision 1.7 2002/11/12 17:27:49 tng * DOM Message: add new domain for DOM Messages. * * Revision 1.6 2002/11/04 22:24:43 peiyongz * Locale setting for message loader * * Revision 1.5 2002/11/04 15:10:40 tng * C++ Namespace Support. * * Revision 1.4 2002/10/10 21:07:55 peiyongz * load resource files using environement vars and base name * * Revision 1.3 2002/10/02 17:08:50 peiyongz * XMLString::equals() to replace XMLString::compareString() * * Revision 1.2 2002/09/30 22:20:40 peiyongz * Build with ICU MsgLoader * * Revision 1.1.1.1 2002/02/01 22:22:19 peiyongz * sane_include * * Revision 1.7 2002/01/21 14:52:25 tng * [Bug 5847] ICUMsgLoader can't be compiled with gcc 3.0.3 and ICU2. And also fix the memory leak introduced by Bug 2730 fix. * * Revision 1.6 2001/11/01 23:39:18 jasons * 2001-11-01 Jason E. Stewart <[email protected]> * * * src/util/MsgLoaders/ICU/ICUMsgLoader.hpp (Repository): * * src/util/MsgLoaders/ICU/ICUMsgLoader.cpp (Repository): * Updated to compile with ICU-1.8.1 * * Revision 1.5 2000/03/02 19:55:14 roddey * This checkin includes many changes done while waiting for the * 1.1.0 code to be finished. I can't list them all here, but a list is * available elsewhere. * * Revision 1.4 2000/02/06 07:48:21 rahulj * Year 2K copyright swat. * * Revision 1.3 2000/01/19 00:58:38 roddey * Update to support new ICU 1.4 release. * * Revision 1.2 1999/11/19 21:24:03 aruna1 * incorporated ICU 1.3.1 related changes int he file * * Revision 1.1.1.1 1999/11/09 01:07:23 twl * Initial checkin * * Revision 1.4 1999/11/08 20:45:26 rahul * Swat for adding in Product name and CVS comment log variable. * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/util/XercesDefs.hpp> #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/util/XMLMsgLoader.hpp> #include <xercesc/util/XMLString.hpp> #include <xercesc/util/XMLUniDefs.hpp> #include <xercesc/util/Janitor.hpp> #include "ICUMsgLoader.hpp" #include "string.h" #include <stdio.h> #include <stdlib.h> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // Local static methods // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // Public Constructors and Destructor // --------------------------------------------------------------------------- ICUMsgLoader::ICUMsgLoader(const XMLCh* const msgDomain) :fLocaleBundle(0) ,fDomainBundle(0) { /*** Validate msgDomain ***/ if (!XMLString::equals(msgDomain, XMLUni::fgXMLErrDomain) && !XMLString::equals(msgDomain, XMLUni::fgExceptDomain) && !XMLString::equals(msgDomain, XMLUni::fgXMLDOMMsgDomain) && !XMLString::equals(msgDomain, XMLUni::fgValidityDomain) ) { XMLPlatformUtils::panic(XMLPlatformUtils::Panic_UnknownMsgDomain); } /*** Resolve domainName ***/ int index = XMLString::lastIndexOf(msgDomain, chForwardSlash); char* domainName = XMLString::transcode(&(msgDomain[index + 1])); ArrayJanitor<char> jan1(domainName); /*** Resolve location REVISIT: another approach would be: through some system API which returns the directory of the XercescLib and that directory would be used to locate the resource bundle ***/ char locationBuf[1024]; memset(locationBuf, 0, sizeof locationBuf); char *nlsHome = getenv("XERCESC_NLS_HOME"); if (nlsHome) { strcpy(locationBuf, nlsHome); strcat(locationBuf, U_FILE_SEP_STRING); } else { char *altHome = getenv("XERCESCROOT"); if (altHome) { strcpy(locationBuf, altHome); strcat(locationBuf, U_FILE_SEP_STRING); strcat(locationBuf, "lib"); strcat(locationBuf, U_FILE_SEP_STRING); } } strcat(locationBuf, "XercescErrMsg"); /*** Open the locale-specific resource bundle ***/ UErrorCode err = U_ZERO_ERROR; fLocaleBundle = ures_open(locationBuf, XMLMsgLoader::getLocale(), &err); if (!U_SUCCESS(err) || fLocaleBundle == NULL) { XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain); } /*** Open the domain specific resource bundle within the locale-specific resource bundle ***/ err = U_ZERO_ERROR; fDomainBundle = ures_getByKey(fLocaleBundle, domainName, NULL, &err); if (!U_SUCCESS(err) || fDomainBundle == NULL) { XMLPlatformUtils::panic(XMLPlatformUtils::Panic_CantLoadMsgDomain); } } ICUMsgLoader::~ICUMsgLoader() { ures_close(fDomainBundle); ures_close(fLocaleBundle); } // --------------------------------------------------------------------------- // Implementation of the virtual message loader API // --------------------------------------------------------------------------- bool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad , XMLCh* const toFill , const unsigned int maxChars) { UErrorCode err = U_ZERO_ERROR; int32_t strLen = 0; // Assuming array format const UChar *name = ures_getStringByIndex(fDomainBundle, (int32_t)msgToLoad-1, &strLen, &err); if (!U_SUCCESS(err) || (name == NULL)) { return false; } int retStrLen = strLen > (int32_t)maxChars ? maxChars : strLen; if (sizeof(UChar)==sizeof(XMLCh)) { XMLString::moveChars(toFill, (XMLCh*)name, retStrLen); toFill[retStrLen] = (XMLCh) 0; } else { XMLCh* retStr = toFill; const UChar *srcPtr = name; while (retStrLen--) *retStr++ = *srcPtr++; *retStr = 0; } return true; } bool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad , XMLCh* const toFill , const unsigned int maxChars , const XMLCh* const repText1 , const XMLCh* const repText2 , const XMLCh* const repText3 , const XMLCh* const repText4) { // Call the other version to load up the message if (!loadMsg(msgToLoad, toFill, maxChars)) return false; // And do the token replacement XMLString::replaceTokens(toFill, maxChars, repText1, repText2, repText3, repText4); return true; } bool ICUMsgLoader::loadMsg( const XMLMsgLoader::XMLMsgId msgToLoad , XMLCh* const toFill , const unsigned int maxChars , const char* const repText1 , const char* const repText2 , const char* const repText3 , const char* const repText4) { // // Transcode the provided parameters and call the other version, // which will do the replacement work. // XMLCh* tmp1 = 0; XMLCh* tmp2 = 0; XMLCh* tmp3 = 0; XMLCh* tmp4 = 0; bool bRet = false; if (repText1) tmp1 = XMLString::transcode(repText1); if (repText2) tmp2 = XMLString::transcode(repText2); if (repText3) tmp3 = XMLString::transcode(repText3); if (repText4) tmp4 = XMLString::transcode(repText4); bRet = loadMsg(msgToLoad, toFill, maxChars, tmp1, tmp2, tmp3, tmp4); if (tmp1) delete [] tmp1; if (tmp2) delete [] tmp2; if (tmp3) delete [] tmp3; if (tmp4) delete [] tmp4; return bRet; } XERCES_CPP_NAMESPACE_END <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_PRODUCTS_BASE_HH #define DUNE_GDT_PRODUCTS_BASE_HH #include <dune/stuff/grid/walker.hh> #include <dune/gdt/assembler/tmp-storage.hh> #include <dune/gdt/assembler/local/codim0.hh> #include "interfaces.hh" namespace Dune { namespace GDT { namespace Products { /** * \todo Derive from SystemAssembler, \see Operators::EllipticG */ template <class Traits> class LocalizableBase : public LocalizableProductInterface<Traits>, public Stuff::Grid::Functor::Codim0<typename Traits::GridViewType> { typedef LocalizableProductInterface<Traits> InterfaceType; public: typedef typename Traits::GridViewType GridViewType; typedef typename Traits::RangeType RangeType; typedef typename Traits::SourceType SourceType; typedef typename Traits::FieldType FieldType; private: typedef typename Traits::LocalOperatorType LocalOperatorType; typedef TmpStorageProvider::Matrices<FieldType> TmpMatricesProviderType; public: using typename InterfaceType::EntityType; public: LocalizableBase(const GridViewType& grd_vw, const RangeType& rng, const SourceType& src) : grid_view_(grd_vw) , range_(rng) , source_(src) , tmp_storage_(nullptr) , prepared_(false) , finalized_(false) , result_(0) { } LocalizableBase(const GridViewType& grd_vw, const RangeType& rng) : grid_view_(grd_vw) , range_(rng) , source_(range_) , tmp_storage_(nullptr) , prepared_(false) , finalized_(false) , result_(0) { } virtual ~LocalizableBase() { } const GridViewType& grid_view() const { return grid_view_; } const RangeType& range() const { return range_; } const SourceType& source() const { return source_; } private: virtual const LocalOperatorType& local_operator() const = 0; public: virtual void prepare() DS_OVERRIDE { if (!prepared_) { tmp_storage_ = std::unique_ptr<TmpMatricesProviderType>( new TmpMatricesProviderType({1, local_operator().numTmpObjectsRequired()}, 1, 1)); result_ = FieldType(0.0); prepared_ = true; } } // ... prepare() FieldType compute_locally(const EntityType& entity) { assert(prepared_); assert(tmp_storage_); auto& tmp_storage = tmp_storage_->matrices(); assert(tmp_storage.size() >= 2); assert(tmp_storage[0].size() >= 1); auto& local_operator_result = tmp_storage[0][0]; auto& tmp_matrices = tmp_storage[1]; // get the local functions const auto local_source_ptr = this->source().local_function(entity); const auto local_range_ptr = this->range().local_function(entity); // apply local operator local_operator().apply(*local_range_ptr, *local_source_ptr, local_operator_result, tmp_matrices); assert(local_operator_result.rows() == 1); assert(local_operator_result.cols() == 1); return local_operator_result[0][0]; } // ... compute_locally(...) virtual void apply_local(const EntityType& entity) DS_OVERRIDE { result_ = result_ + compute_locally(entity); } virtual void finalize() DS_OVERRIDE { if (!finalized_) { FieldType tmp = result_; result_ = grid_view_.comm().sum(tmp); finalized_ = true; } } FieldType apply2() { if (!finalized_) { Stuff::Grid::Walker<GridViewType> grid_walker(grid_view_); grid_walker.add(*this); grid_walker.walk(); } return result_; } private: const GridViewType& grid_view_; const RangeType& range_; const SourceType& source_; std::unique_ptr<TmpMatricesProviderType> tmp_storage_; bool prepared_; bool finalized_; std::atomic<FieldType> result_; }; // class LocalizableBase /** * \todo Derive from SystemAssembler, \see Operators::EllipticG */ template <class Traits> class AssemblableBase : public AssemblableProductInterface<Traits>, public Stuff::Grid::Functor::Codim0<typename Traits::GridViewType> { typedef AssemblableProductInterface<Traits> InterfaceType; public: typedef typename Traits::GridViewType GridViewType; typedef typename Traits::RangeSpaceType RangeSpaceType; typedef typename Traits::SourceSpaceType SourceSpaceType; typedef typename Traits::MatrixType MatrixType; typedef typename MatrixType::ScalarType FieldType; private: typedef TmpStorageProvider::Matrices<FieldType> TmpMatricesProviderType; typedef typename Traits::LocalOperatorType LocalOperatorType; typedef LocalAssembler::Codim0Matrix<LocalOperatorType> LocalAssemblerType; public: using typename InterfaceType::EntityType; using InterfaceType::pattern; AssemblableBase(MatrixType& mtrx, const RangeSpaceType& rng_spc, const GridViewType& grd_vw, const SourceSpaceType& src_spc) : matrix_(mtrx) , range_space_(rng_spc) , grid_view_(grd_vw) , source_space_(src_spc) , local_assembler_(nullptr) , tmp_storage_(nullptr) , prepared_(false) , assembled_(false) { } AssemblableBase(MatrixType& mtrx, const RangeSpaceType& rng_spc, const GridViewType& grd_vw) : matrix_(mtrx) , range_space_(rng_spc) , grid_view_(grd_vw) , source_space_(range_space_) , local_assembler_(nullptr) , tmp_storage_(nullptr) , prepared_(false) , assembled_(false) { } AssemblableBase(MatrixType& mtrx, const RangeSpaceType& rng_spc) : matrix_(mtrx) , range_space_(rng_spc) , grid_view_(*(range_space_->grid_view())) , source_space_(range_space_) , local_assembler_(nullptr) , tmp_storage_(nullptr) , prepared_(false) , assembled_(false) { } const GridViewType& grid_view() const { return grid_view_; } const RangeSpaceType& range_space() const { return range_space_; } const SourceSpaceType& source_space() const { return source_space_; } MatrixType& matrix() { return matrix_; } const MatrixType& matrix() const { return matrix_; } private: virtual const LocalOperatorType& local_operator() const = 0; public: virtual void prepare() DS_OVERRIDE { if (!assembled_ && !prepared_) { local_assembler_ = std::unique_ptr<LocalAssemblerType>(new LocalAssemblerType(local_operator())); tmp_storage_ = std::unique_ptr<TmpMatricesProviderType>( new TmpMatricesProviderType(local_assembler_->numTmpObjectsRequired(), range_space_.mapper().maxNumDofs(), source_space_.mapper().maxNumDofs())); prepared_ = true; } } // ... prepare() virtual void apply_local(const EntityType& entity) DS_OVERRIDE { assert(prepared_); assert(local_assembler_); assert(tmp_storage_); local_assembler_->assembleLocal( range_space_, source_space_, entity, matrix_, tmp_storage_->matrices(), tmp_storage_->indices()); } // ... apply_local(...) void assemble() { if (!assembled_) { Stuff::Grid::Walker<GridViewType> grid_walker(grid_view_); grid_walker.add(*this); grid_walker.walk(); assembled_ = true; } } // ... assemble() using InterfaceType::apply2; private: MatrixType& matrix_; const RangeSpaceType& range_space_; const GridViewType& grid_view_; const SourceSpaceType& source_space_; std::unique_ptr<LocalAssemblerType> local_assembler_; std::unique_ptr<TmpMatricesProviderType> tmp_storage_; bool prepared_; bool assembled_; }; // class AssemblableBase } // namespace Products } // namespace GDT } // namespace Dune #endif // DUNE_GDT_PRODUCTS_BASE_HH <commit_msg>[products] safer base result summation<commit_after>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_PRODUCTS_BASE_HH #define DUNE_GDT_PRODUCTS_BASE_HH #include <dune/stuff/grid/walker.hh> #include <dune/gdt/assembler/tmp-storage.hh> #include <dune/gdt/assembler/local/codim0.hh> #include "interfaces.hh" namespace Dune { namespace GDT { namespace Products { /** * \todo Derive from SystemAssembler, \see Operators::EllipticG */ template <class Traits> class LocalizableBase : public LocalizableProductInterface<Traits>, public Stuff::Grid::Functor::Codim0<typename Traits::GridViewType> { typedef LocalizableProductInterface<Traits> InterfaceType; public: typedef typename Traits::GridViewType GridViewType; typedef typename Traits::RangeType RangeType; typedef typename Traits::SourceType SourceType; typedef typename Traits::FieldType FieldType; private: typedef typename Traits::LocalOperatorType LocalOperatorType; typedef TmpStorageProvider::Matrices<FieldType> TmpMatricesProviderType; public: using typename InterfaceType::EntityType; public: LocalizableBase(const GridViewType& grd_vw, const RangeType& rng, const SourceType& src) : grid_view_(grd_vw) , range_(rng) , source_(src) , tmp_storage_(nullptr) , prepared_(false) , finalized_(false) , result_(0) { } LocalizableBase(const GridViewType& grd_vw, const RangeType& rng) : grid_view_(grd_vw) , range_(rng) , source_(range_) , tmp_storage_(nullptr) , prepared_(false) , finalized_(false) , result_(0) { } virtual ~LocalizableBase() { } const GridViewType& grid_view() const { return grid_view_; } const RangeType& range() const { return range_; } const SourceType& source() const { return source_; } private: virtual const LocalOperatorType& local_operator() const = 0; public: virtual void prepare() DS_OVERRIDE { if (!prepared_) { tmp_storage_ = std::unique_ptr<TmpMatricesProviderType>( new TmpMatricesProviderType({1, local_operator().numTmpObjectsRequired()}, 1, 1)); result_ = FieldType(0.0); prepared_ = true; } } // ... prepare() FieldType compute_locally(const EntityType& entity) { assert(prepared_); assert(tmp_storage_); auto& tmp_storage = tmp_storage_->matrices(); assert(tmp_storage.size() >= 2); assert(tmp_storage[0].size() >= 1); auto& local_operator_result = tmp_storage[0][0]; auto& tmp_matrices = tmp_storage[1]; // get the local functions const auto local_source_ptr = this->source().local_function(entity); const auto local_range_ptr = this->range().local_function(entity); // apply local operator local_operator().apply(*local_range_ptr, *local_source_ptr, local_operator_result, tmp_matrices); assert(local_operator_result.rows() == 1); assert(local_operator_result.cols() == 1); return local_operator_result[0][0]; } // ... compute_locally(...) virtual void apply_local(const EntityType& entity) DS_OVERRIDE { *result_ += compute_locally(entity); } virtual void finalize() DS_OVERRIDE { if (!finalized_) { FieldType tmp = result_.sum(); finalized_result_ = grid_view_.comm().sum(tmp); finalized_ = true; } } FieldType apply2() { if (!finalized_) { Stuff::Grid::Walker<GridViewType> grid_walker(grid_view_); grid_walker.add(*this); grid_walker.walk(); } return finalized_result_; } private: const GridViewType& grid_view_; const RangeType& range_; const SourceType& source_; std::unique_ptr<TmpMatricesProviderType> tmp_storage_; bool prepared_; bool finalized_; DS::PerThreadValue<FieldType> result_; FieldType finalized_result_; }; // class LocalizableBase /** * \todo Derive from SystemAssembler, \see Operators::EllipticG */ template <class Traits> class AssemblableBase : public AssemblableProductInterface<Traits>, public Stuff::Grid::Functor::Codim0<typename Traits::GridViewType> { typedef AssemblableProductInterface<Traits> InterfaceType; public: typedef typename Traits::GridViewType GridViewType; typedef typename Traits::RangeSpaceType RangeSpaceType; typedef typename Traits::SourceSpaceType SourceSpaceType; typedef typename Traits::MatrixType MatrixType; typedef typename MatrixType::ScalarType FieldType; private: typedef TmpStorageProvider::Matrices<FieldType> TmpMatricesProviderType; typedef typename Traits::LocalOperatorType LocalOperatorType; typedef LocalAssembler::Codim0Matrix<LocalOperatorType> LocalAssemblerType; public: using typename InterfaceType::EntityType; using InterfaceType::pattern; AssemblableBase(MatrixType& mtrx, const RangeSpaceType& rng_spc, const GridViewType& grd_vw, const SourceSpaceType& src_spc) : matrix_(mtrx) , range_space_(rng_spc) , grid_view_(grd_vw) , source_space_(src_spc) , local_assembler_(nullptr) , tmp_storage_(nullptr) , prepared_(false) , assembled_(false) { } AssemblableBase(MatrixType& mtrx, const RangeSpaceType& rng_spc, const GridViewType& grd_vw) : matrix_(mtrx) , range_space_(rng_spc) , grid_view_(grd_vw) , source_space_(range_space_) , local_assembler_(nullptr) , tmp_storage_(nullptr) , prepared_(false) , assembled_(false) { } AssemblableBase(MatrixType& mtrx, const RangeSpaceType& rng_spc) : matrix_(mtrx) , range_space_(rng_spc) , grid_view_(*(range_space_->grid_view())) , source_space_(range_space_) , local_assembler_(nullptr) , tmp_storage_(nullptr) , prepared_(false) , assembled_(false) { } const GridViewType& grid_view() const { return grid_view_; } const RangeSpaceType& range_space() const { return range_space_; } const SourceSpaceType& source_space() const { return source_space_; } MatrixType& matrix() { return matrix_; } const MatrixType& matrix() const { return matrix_; } private: virtual const LocalOperatorType& local_operator() const = 0; public: virtual void prepare() DS_OVERRIDE { if (!assembled_ && !prepared_) { local_assembler_ = std::unique_ptr<LocalAssemblerType>(new LocalAssemblerType(local_operator())); tmp_storage_ = std::unique_ptr<TmpMatricesProviderType>( new TmpMatricesProviderType(local_assembler_->numTmpObjectsRequired(), range_space_.mapper().maxNumDofs(), source_space_.mapper().maxNumDofs())); prepared_ = true; } } // ... prepare() virtual void apply_local(const EntityType& entity) DS_OVERRIDE { assert(prepared_); assert(local_assembler_); assert(tmp_storage_); local_assembler_->assembleLocal( range_space_, source_space_, entity, matrix_, tmp_storage_->matrices(), tmp_storage_->indices()); } // ... apply_local(...) void assemble() { if (!assembled_) { Stuff::Grid::Walker<GridViewType> grid_walker(grid_view_); grid_walker.add(*this); grid_walker.walk(); assembled_ = true; } } // ... assemble() using InterfaceType::apply2; private: MatrixType& matrix_; const RangeSpaceType& range_space_; const GridViewType& grid_view_; const SourceSpaceType& source_space_; std::unique_ptr<LocalAssemblerType> local_assembler_; std::unique_ptr<TmpMatricesProviderType> tmp_storage_; bool prepared_; bool assembled_; }; // class AssemblableBase } // namespace Products } // namespace GDT } // namespace Dune #endif // DUNE_GDT_PRODUCTS_BASE_HH <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_PRODUCTS_BASE_HH #define DUNE_GDT_PRODUCTS_BASE_HH #include <dune/stuff/common/memory.hh> #include <dune/stuff/common/tmp-storage.hh> #include <dune/stuff/grid/walker.hh> #include <dune/stuff/la/container/pattern.hh> #include <dune/gdt/assembler/system.hh> #include "interfaces.hh" #include "base-internal.hh" namespace Dune { namespace GDT { namespace Products { /** * \brief Base class for all localizable products. * * The purpose of this class is to facilitate the implementation of localizable products (that are based on * local operators) by implementing as much as possible. All you have to do is to implement a class * LocalOperatorProvider, derived from LocalOperatorProviderBase. See the documentation of * \sa LocalOperatorProviderBase for the requirements of your class, depending on the type of local operator you * want to use. We do not use the CRTP machinery here but trust you to implement what is necessarry. Any * additional ctor arguments given to LocalizableBase are forwarded to your implementation of * LocalOperatorProvider. Static checks of GridViewType, RangeType and SourceType are performed in * internal::LocalizableBaseTraits. You can finally implement the product by deriving from this class and * providing the appropriate LocalOperatorProvider. To get an idea see \sa Products::internal::WeightedL2Base in * weightedl2-internal.hh for an example of a LocalOperatorProvider and Products::WeightedL2Localizable in * weightedl2.hh for an example of the final product. * \note If you want to know about the internal workings of this class, take a look at \sa * internal::LocalizableBaseHelper. */ template< class LocalOperatorProvider, class RangeImp, class SourceImp > class LocalizableBase : public LocalizableProductInterface< internal::LocalizableBaseTraits< LocalOperatorProvider, RangeImp, SourceImp > > , public Stuff::Grid::Walker< typename LocalOperatorProvider::GridViewType > { typedef LocalizableProductInterface < internal::LocalizableBaseTraits< LocalOperatorProvider, RangeImp, SourceImp > > ProductBaseType; typedef Stuff::Grid::Walker< typename LocalOperatorProvider::GridViewType > WalkerBaseType; public: typedef internal::LocalizableBaseTraits< LocalOperatorProvider, RangeImp, SourceImp > Traits; typedef typename WalkerBaseType::GridViewType GridViewType; typedef typename WalkerBaseType::EntityType EntityType; typedef typename WalkerBaseType::IntersectionType IntersectionType; typedef typename ProductBaseType::RangeType RangeType; typedef typename ProductBaseType::SourceType SourceType; typedef typename ProductBaseType::FieldType FieldType; private: typedef internal::LocalizableBaseHelper< LocalOperatorProvider, RangeType, SourceType > HelperType; public: template< class... Args > LocalizableBase(const GridViewType& grd_vw, const RangeType& rng, const SourceType& src, Args&& ...args) : WalkerBaseType(grd_vw) , range_(rng) , source_(src) , local_operators_(std::forward< Args >(args)...) , helper_(*this, local_operators_, range_, source_) , walked_(false) {} template< class... Args > LocalizableBase(const GridViewType& grd_vw, const RangeType& rng, Args&& ...args) : WalkerBaseType(grd_vw) , range_(rng) , source_(rng) , local_operators_(std::forward< Args >(args)...) , helper_(*this, local_operators_, range_, source_) , walked_(false) {} using WalkerBaseType::grid_view; const RangeType& range() const { return range_; } const SourceType& source() const { return source_; } /** * This method can be used to compute a local semi product on one entity, e.g. in the context of error * estimation. * \note Calling this method should not alter the result obtained by apply2. */ FieldType compute_locally(const EntityType& entity) { return helper_.compute_locally(entity); } /** * This method can be used to compute a local semi product on one intersection, e.g. in the context of error * estimation. * \note Calling this method should not alter the result obtained by apply2. */ FieldType compute_locally(const IntersectionType& intersection, const EntityType& inside_entity, const EntityType& outside_entity) { return helper_.compute_locally(intersection, inside_entity, outside_entity); } FieldType apply2() { if (!walked_) this->walk(); return helper_.result(); } // ... apply2(...) private: const RangeType& range_; const SourceType& source_; const LocalOperatorProvider local_operators_; HelperType helper_; bool walked_; }; // class LocalizableBase /** * \brief Base class for all assembable products. * * The purpose of this class is to facilitate the implementation of assembable products (that are based on * local operators) by implementing as much as possible. All you have to do is to implement a class * LocalOperatorProvider, derived from LocalOperatorProviderBase. See the documentation of * \sa LocalOperatorProviderBase for the requirements of your class, depending on the type of local operator you * want to use. We do not use the CRTP machinery here but trust you to implement what is necessarry. Any * additional ctor arguments given to AssemblableBase are forwarded to your implementation of * LocalOperatorProvider. Static checks of MatrixType, RangeSpaceType and SourceSpaceType are performed in * internal::AssemblableBaseTraits. You can finally implement the product by deriving from this class and * providing the appropriate LocalOperatorProvider. To get an idea see \sa Products::internal::WeightedL2Base in * weightedl2-internal.hh for an example of a LocalOperatorProvider and Products::WeightedL2Assemblable in * weightedl2.hh for an example of the final product. * \note If you want to know about the internal workings of this class, take a look at \sa * internal::AssemblableBaseHelper. * \note This class proves an automatic creation of the matrix that is being assembled into. Thus each kind of ctor * exists in two variants (one taking a matrix reference, one not). If you provide an external matrix you are * responsible for the well being of the matrix: * - If this is a sparse matrix it needs to have the correct pattern (can be obtained from this class). * - During assemble values are added to the matrix (not set). Thus it should be empty beforehand or you have to * know what you are doing! */ template< class LocalOperatorProvider, class MatrixImp, class RangeSpaceImp, class SourceSpaceImp > class AssemblableBase : DSC::StorageProvider< MatrixImp > , public AssemblableProductInterface< internal::AssemblableBaseTraits< LocalOperatorProvider, MatrixImp, RangeSpaceImp, SourceSpaceImp > > , public SystemAssembler< RangeSpaceImp, typename LocalOperatorProvider::GridViewType, SourceSpaceImp > { typedef DSC::StorageProvider< MatrixImp > MatrixProvider; typedef AssemblableProductInterface< internal::AssemblableBaseTraits< LocalOperatorProvider, MatrixImp, RangeSpaceImp, SourceSpaceImp > > ProductBaseType; typedef SystemAssembler < RangeSpaceImp, typename LocalOperatorProvider::GridViewType, SourceSpaceImp > AssemblerBaseType; typedef AssemblableBase< LocalOperatorProvider, MatrixImp, RangeSpaceImp, SourceSpaceImp > ThisType; public: typedef internal::AssemblableBaseTraits < LocalOperatorProvider, MatrixImp, RangeSpaceImp, SourceSpaceImp > Traits; typedef typename ProductBaseType::GridViewType GridViewType; typedef typename ProductBaseType::RangeSpaceType RangeSpaceType; typedef typename ProductBaseType::SourceSpaceType SourceSpaceType; typedef typename ProductBaseType::MatrixType MatrixType; typedef typename ProductBaseType::FieldType FieldType; private: typedef internal::AssemblableBaseHelper< ThisType, LocalOperatorProvider > HelperType; public: using ProductBaseType::pattern; static Stuff::LA::SparsityPatternDefault pattern(const RangeSpaceType& range_space, const SourceSpaceType& source_space, const GridViewType& grid_view) { if (LocalOperatorProvider::has_coupling_operator) return range_space.compute_face_and_volume_pattern(grid_view, source_space); else if (LocalOperatorProvider::has_volume_operator || LocalOperatorProvider::has_boundary_operator) return range_space.compute_volume_pattern(grid_view, source_space); else return Stuff::LA::SparsityPatternDefault(); } template< class... Args > AssemblableBase(MatrixType& mtrx, const RangeSpaceType& rng_spc, const GridViewType& grd_vw, const SourceSpaceType& src_spc, Args&& ...args) : MatrixProvider(mtrx) , AssemblerBaseType(rng_spc, src_spc, grd_vw) , local_operators_(std::forward< Args >(args)...) , helper_(*this, MatrixProvider::storage_access(), local_operators_) , assembled_(false) {} template< class... Args > AssemblableBase(const RangeSpaceType& rng_spc, const GridViewType& grd_vw, const SourceSpaceType& src_spc, Args&& ...args) : MatrixProvider(new MatrixType(rng_spc.mapper().size(), src_spc.mapper().size(), pattern(rng_spc, src_spc, grd_vw))) , AssemblerBaseType(rng_spc, src_spc, grd_vw) , local_operators_(std::forward< Args >(args)...) , helper_(*this, MatrixProvider::storage_access(), local_operators_) , assembled_(false) {} template< class... Args > AssemblableBase(MatrixType& mtrx, const RangeSpaceType& rng_spc, const GridViewType& grd_vw, Args&& ...args) : MatrixProvider(mtrx) , AssemblerBaseType(rng_spc, grd_vw) , local_operators_(std::forward< Args >(args)...) , helper_(*this, MatrixProvider::storage_access(), local_operators_) , assembled_(false) {} template< class... Args > AssemblableBase(const RangeSpaceType& rng_spc, const GridViewType& grd_vw, Args&& ...args) : MatrixProvider(new MatrixType(rng_spc.mapper().size(), rng_spc.mapper().size(), pattern(rng_spc, grd_vw))) , AssemblerBaseType(rng_spc, grd_vw) , local_operators_(std::forward< Args >(args)...) , helper_(*this, MatrixProvider::storage_access(), local_operators_) , assembled_(false) {} template< class... Args > AssemblableBase(MatrixType& mtrx, const RangeSpaceType& rng_spc, Args&& ...args) : MatrixProvider(mtrx) , AssemblerBaseType(rng_spc) , local_operators_(std::forward< Args >(args)...) , helper_(*this, MatrixProvider::storage_access(), local_operators_) , assembled_(false) {} template< class... Args > AssemblableBase(const RangeSpaceType& rng_spc, Args&& ...args) : MatrixProvider(new MatrixType(rng_spc.mapper().size(), rng_spc.mapper().size(), pattern(rng_spc))) , AssemblerBaseType(rng_spc) , local_operators_(std::forward< Args >(args)...) , helper_(*this, MatrixProvider::storage_access(), local_operators_) , assembled_(false) {} using AssemblerBaseType::grid_view; const RangeSpaceType& range_space() const { return AssemblerBaseType::test_space(); } const SourceSpaceType& source_space() const { return AssemblerBaseType::ansatz_space(); } MatrixType& matrix() { return MatrixProvider::storage_access(); } const MatrixType& matrix() const { return MatrixProvider::storage_access(); } void assemble() { if (!assembled_) { AssemblerBaseType::assemble(); assembled_ = true; } } // ... assemble() private: const LocalOperatorProvider local_operators_; HelperType helper_; bool assembled_; }; // class AssemblableBase /** * \brief Base class for all generic products. * * The purpose of this class is to facilitate the implementation of products that are based on a local operator * that is derived from LocalOperator::Codim0Interface by implementing as much as possible. All you have to do is * to implement a class LocalOperatorProvider that provides the following in addition to the requirements of \sa * LocalizableBase: * - it has to be copyable * GenericBase derives from that provided class and forwards any additional ctor arguments to its ctor. A static * check of GridViewType is performed in internal::GenericBaseTraits. You can finally implement the product by * deriving from this class and providing the appropriate LocalOperatorProvider. To get an idea see \sa * Products::internal::WeightedL2Base in l2-internal.hh for an example of a LocalOperatorProvider and * Products::WeightedL2 in l2.hh for an example of the final product. This product is implemented by a creating a * LocalizableBase product of appropriate type for the given source and range. */ template< class LocalOperatorProvider > class GenericBase : LocalOperatorProvider , public ProductInterface< internal::GenericBaseTraits< LocalOperatorProvider > > { typedef ProductInterface< internal::GenericBaseTraits< LocalOperatorProvider > > BaseType; public: typedef internal::GenericBaseTraits< LocalOperatorProvider > Traits; typedef typename BaseType::GridViewType GridViewType; typedef typename BaseType::FieldType FieldType; typedef typename GridViewType::template Codim< 0 >::Entity EntityType; typedef typename GridViewType::ctype DomainFieldType; static const unsigned int dimDomain = GridViewType::dimension; template< class... Args > GenericBase(const GridViewType& grd_vw, Args&& ...args) : LocalOperatorProvider(std::forward< Args >(args)...) , grid_view_(grd_vw) {} const GridViewType& grid_view() const { return grid_view_; } template< class RR, int rRR, int rCR, class RS, int rRS, int rCS > FieldType apply2(const Stuff::LocalizableFunctionInterface< EntityType, DomainFieldType, dimDomain, RR, rRR, rCR >& range, const Stuff::LocalizableFunctionInterface< EntityType, DomainFieldType, dimDomain, RS, rRS, rCS >& source) const { typedef Stuff::LocalizableFunctionInterface< EntityType, DomainFieldType, dimDomain, RR, rRR, rCR > RangeType; typedef Stuff::LocalizableFunctionInterface< EntityType, DomainFieldType, dimDomain, RS, rRS, rCS > SourceType; LocalizableBase< LocalOperatorProvider, RangeType, SourceType > product(grid_view_, range, source, static_cast< const LocalOperatorProvider& >(*this)); return product.apply2(); } // ... apply2(...) private: const GridViewType& grid_view_; }; // class GenericBase } // namespace Products } // namespace GDT } // namespace Dune #endif // DUNE_GDT_PRODUCTS_BASE_HH <commit_msg>[products.base] make copyable<commit_after>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_PRODUCTS_BASE_HH #define DUNE_GDT_PRODUCTS_BASE_HH #include <dune/stuff/common/memory.hh> #include <dune/stuff/common/tmp-storage.hh> #include <dune/stuff/grid/walker.hh> #include <dune/stuff/la/container/pattern.hh> #include <dune/gdt/assembler/system.hh> #include "interfaces.hh" #include "base-internal.hh" namespace Dune { namespace GDT { namespace Products { /** * \brief Base class for all localizable products. * * The purpose of this class is to facilitate the implementation of localizable products (that are based on * local operators) by implementing as much as possible. All you have to do is to implement a class * LocalOperatorProvider, derived from LocalOperatorProviderBase. See the documentation of * \sa LocalOperatorProviderBase for the requirements of your class, depending on the type of local operator you * want to use. We do not use the CRTP machinery here but trust you to implement what is necessarry. Any * additional ctor arguments given to LocalizableBase are forwarded to your implementation of * LocalOperatorProvider. Static checks of GridViewType, RangeType and SourceType are performed in * internal::LocalizableBaseTraits. You can finally implement the product by deriving from this class and * providing the appropriate LocalOperatorProvider. To get an idea see \sa Products::internal::WeightedL2Base in * weightedl2-internal.hh for an example of a LocalOperatorProvider and Products::WeightedL2Localizable in * weightedl2.hh for an example of the final product. * \note If you want to know about the internal workings of this class, take a look at \sa * internal::LocalizableBaseHelper. */ template< class LocalOperatorProvider, class RangeImp, class SourceImp > class LocalizableBase : public LocalizableProductInterface< internal::LocalizableBaseTraits< LocalOperatorProvider, RangeImp, SourceImp > > , public Stuff::Grid::Walker< typename LocalOperatorProvider::GridViewType > { typedef LocalizableBase< LocalOperatorProvider, RangeImp, SourceImp > ThisType; typedef LocalizableProductInterface < internal::LocalizableBaseTraits< LocalOperatorProvider, RangeImp, SourceImp > > ProductBaseType; typedef Stuff::Grid::Walker< typename LocalOperatorProvider::GridViewType > WalkerBaseType; public: typedef internal::LocalizableBaseTraits< LocalOperatorProvider, RangeImp, SourceImp > Traits; typedef typename WalkerBaseType::GridViewType GridViewType; typedef typename WalkerBaseType::EntityType EntityType; typedef typename WalkerBaseType::IntersectionType IntersectionType; typedef typename ProductBaseType::RangeType RangeType; typedef typename ProductBaseType::SourceType SourceType; typedef typename ProductBaseType::FieldType FieldType; private: typedef internal::LocalizableBaseHelper< LocalOperatorProvider, RangeType, SourceType > HelperType; public: template< class... Args > LocalizableBase(const GridViewType& grd_vw, const RangeType& rng, const SourceType& src, Args&& ...args) : WalkerBaseType(grd_vw) , range_(rng) , source_(src) , local_operators_(std::forward< Args >(args)...) , helper_(*this, local_operators_, range_, source_) , walked_(false) {} template< class... Args > LocalizableBase(const GridViewType& grd_vw, const RangeType& rng, Args&& ...args) : WalkerBaseType(grd_vw) , range_(rng) , source_(rng) , local_operators_(std::forward< Args >(args)...) , helper_(*this, local_operators_, range_, source_) , walked_(false) {} LocalizableBase(const ThisType& other) : WalkerBaseType(other.grid_view()) , range_(other.range_) , source_(other.source_) , local_operators_(other.local_operators_) , helper_(*this, local_operators_, range_, source_) , walked_(false) {} using WalkerBaseType::grid_view; const RangeType& range() const { return range_; } const SourceType& source() const { return source_; } /** * This method can be used to compute a local semi product on one entity, e.g. in the context of error * estimation. * \note Calling this method should not alter the result obtained by apply2. */ FieldType compute_locally(const EntityType& entity) { return helper_.compute_locally(entity); } /** * This method can be used to compute a local semi product on one intersection, e.g. in the context of error * estimation. * \note Calling this method should not alter the result obtained by apply2. */ FieldType compute_locally(const IntersectionType& intersection, const EntityType& inside_entity, const EntityType& outside_entity) { return helper_.compute_locally(intersection, inside_entity, outside_entity); } FieldType apply2() { if (!walked_) this->walk(); return helper_.result(); } // ... apply2(...) private: const RangeType& range_; const SourceType& source_; const LocalOperatorProvider local_operators_; HelperType helper_; bool walked_; }; // class LocalizableBase /** * \brief Base class for all assembable products. * * The purpose of this class is to facilitate the implementation of assembable products (that are based on * local operators) by implementing as much as possible. All you have to do is to implement a class * LocalOperatorProvider, derived from LocalOperatorProviderBase. See the documentation of * \sa LocalOperatorProviderBase for the requirements of your class, depending on the type of local operator you * want to use. We do not use the CRTP machinery here but trust you to implement what is necessarry. Any * additional ctor arguments given to AssemblableBase are forwarded to your implementation of * LocalOperatorProvider. Static checks of MatrixType, RangeSpaceType and SourceSpaceType are performed in * internal::AssemblableBaseTraits. You can finally implement the product by deriving from this class and * providing the appropriate LocalOperatorProvider. To get an idea see \sa Products::internal::WeightedL2Base in * weightedl2-internal.hh for an example of a LocalOperatorProvider and Products::WeightedL2Assemblable in * weightedl2.hh for an example of the final product. * \note If you want to know about the internal workings of this class, take a look at \sa * internal::AssemblableBaseHelper. * \note This class proves an automatic creation of the matrix that is being assembled into. Thus each kind of ctor * exists in two variants (one taking a matrix reference, one not). If you provide an external matrix you are * responsible for the well being of the matrix: * - If this is a sparse matrix it needs to have the correct pattern (can be obtained from this class). * - During assemble values are added to the matrix (not set). Thus it should be empty beforehand or you have to * know what you are doing! */ template< class LocalOperatorProvider, class MatrixImp, class RangeSpaceImp, class SourceSpaceImp > class AssemblableBase : DSC::StorageProvider< MatrixImp > , public AssemblableProductInterface< internal::AssemblableBaseTraits< LocalOperatorProvider, MatrixImp, RangeSpaceImp, SourceSpaceImp > > , public SystemAssembler< RangeSpaceImp, typename LocalOperatorProvider::GridViewType, SourceSpaceImp > { typedef DSC::StorageProvider< MatrixImp > MatrixProvider; typedef AssemblableProductInterface< internal::AssemblableBaseTraits< LocalOperatorProvider, MatrixImp, RangeSpaceImp, SourceSpaceImp > > ProductBaseType; typedef SystemAssembler < RangeSpaceImp, typename LocalOperatorProvider::GridViewType, SourceSpaceImp > AssemblerBaseType; typedef AssemblableBase< LocalOperatorProvider, MatrixImp, RangeSpaceImp, SourceSpaceImp > ThisType; public: typedef internal::AssemblableBaseTraits < LocalOperatorProvider, MatrixImp, RangeSpaceImp, SourceSpaceImp > Traits; typedef typename ProductBaseType::GridViewType GridViewType; typedef typename ProductBaseType::RangeSpaceType RangeSpaceType; typedef typename ProductBaseType::SourceSpaceType SourceSpaceType; typedef typename ProductBaseType::MatrixType MatrixType; typedef typename ProductBaseType::FieldType FieldType; private: typedef internal::AssemblableBaseHelper< ThisType, LocalOperatorProvider > HelperType; public: using ProductBaseType::pattern; static Stuff::LA::SparsityPatternDefault pattern(const RangeSpaceType& range_space, const SourceSpaceType& source_space, const GridViewType& grid_view) { if (LocalOperatorProvider::has_coupling_operator) return range_space.compute_face_and_volume_pattern(grid_view, source_space); else if (LocalOperatorProvider::has_volume_operator || LocalOperatorProvider::has_boundary_operator) return range_space.compute_volume_pattern(grid_view, source_space); else return Stuff::LA::SparsityPatternDefault(); } template< class... Args > AssemblableBase(MatrixType& mtrx, const RangeSpaceType& rng_spc, const GridViewType& grd_vw, const SourceSpaceType& src_spc, Args&& ...args) : MatrixProvider(mtrx) , AssemblerBaseType(rng_spc, src_spc, grd_vw) , local_operators_(std::forward< Args >(args)...) , helper_(*this, MatrixProvider::storage_access(), local_operators_) , assembled_(false) {} template< class... Args > AssemblableBase(const RangeSpaceType& rng_spc, const GridViewType& grd_vw, const SourceSpaceType& src_spc, Args&& ...args) : MatrixProvider(new MatrixType(rng_spc.mapper().size(), src_spc.mapper().size(), pattern(rng_spc, src_spc, grd_vw))) , AssemblerBaseType(rng_spc, src_spc, grd_vw) , local_operators_(std::forward< Args >(args)...) , helper_(*this, MatrixProvider::storage_access(), local_operators_) , assembled_(false) {} template< class... Args > AssemblableBase(MatrixType& mtrx, const RangeSpaceType& rng_spc, const GridViewType& grd_vw, Args&& ...args) : MatrixProvider(mtrx) , AssemblerBaseType(rng_spc, grd_vw) , local_operators_(std::forward< Args >(args)...) , helper_(*this, MatrixProvider::storage_access(), local_operators_) , assembled_(false) {} template< class... Args > AssemblableBase(const RangeSpaceType& rng_spc, const GridViewType& grd_vw, Args&& ...args) : MatrixProvider(new MatrixType(rng_spc.mapper().size(), rng_spc.mapper().size(), pattern(rng_spc, grd_vw))) , AssemblerBaseType(rng_spc, grd_vw) , local_operators_(std::forward< Args >(args)...) , helper_(*this, MatrixProvider::storage_access(), local_operators_) , assembled_(false) {} template< class... Args > AssemblableBase(MatrixType& mtrx, const RangeSpaceType& rng_spc, Args&& ...args) : MatrixProvider(mtrx) , AssemblerBaseType(rng_spc) , local_operators_(std::forward< Args >(args)...) , helper_(*this, MatrixProvider::storage_access(), local_operators_) , assembled_(false) {} template< class... Args > AssemblableBase(const RangeSpaceType& rng_spc, Args&& ...args) : MatrixProvider(new MatrixType(rng_spc.mapper().size(), rng_spc.mapper().size(), pattern(rng_spc))) , AssemblerBaseType(rng_spc) , local_operators_(std::forward< Args >(args)...) , helper_(*this, MatrixProvider::storage_access(), local_operators_) , assembled_(false) {} using AssemblerBaseType::grid_view; const RangeSpaceType& range_space() const { return AssemblerBaseType::test_space(); } const SourceSpaceType& source_space() const { return AssemblerBaseType::ansatz_space(); } MatrixType& matrix() { return MatrixProvider::storage_access(); } const MatrixType& matrix() const { return MatrixProvider::storage_access(); } void assemble() { if (!assembled_) { AssemblerBaseType::assemble(); assembled_ = true; } } // ... assemble() private: const LocalOperatorProvider local_operators_; HelperType helper_; bool assembled_; }; // class AssemblableBase /** * \brief Base class for all generic products. * * The purpose of this class is to facilitate the implementation of products that are based on a local operator * that is derived from LocalOperator::Codim0Interface by implementing as much as possible. All you have to do is * to implement a class LocalOperatorProvider that provides the following in addition to the requirements of \sa * LocalizableBase: * - it has to be copyable * GenericBase derives from that provided class and forwards any additional ctor arguments to its ctor. A static * check of GridViewType is performed in internal::GenericBaseTraits. You can finally implement the product by * deriving from this class and providing the appropriate LocalOperatorProvider. To get an idea see \sa * Products::internal::WeightedL2Base in l2-internal.hh for an example of a LocalOperatorProvider and * Products::WeightedL2 in l2.hh for an example of the final product. This product is implemented by a creating a * LocalizableBase product of appropriate type for the given source and range. */ template< class LocalOperatorProvider > class GenericBase : LocalOperatorProvider , public ProductInterface< internal::GenericBaseTraits< LocalOperatorProvider > > { typedef ProductInterface< internal::GenericBaseTraits< LocalOperatorProvider > > BaseType; public: typedef internal::GenericBaseTraits< LocalOperatorProvider > Traits; typedef typename BaseType::GridViewType GridViewType; typedef typename BaseType::FieldType FieldType; typedef typename GridViewType::template Codim< 0 >::Entity EntityType; typedef typename GridViewType::ctype DomainFieldType; static const unsigned int dimDomain = GridViewType::dimension; template< class... Args > GenericBase(const GridViewType& grd_vw, Args&& ...args) : LocalOperatorProvider(std::forward< Args >(args)...) , grid_view_(grd_vw) {} const GridViewType& grid_view() const { return grid_view_; } template< class RR, int rRR, int rCR, class RS, int rRS, int rCS > FieldType apply2(const Stuff::LocalizableFunctionInterface< EntityType, DomainFieldType, dimDomain, RR, rRR, rCR >& range, const Stuff::LocalizableFunctionInterface< EntityType, DomainFieldType, dimDomain, RS, rRS, rCS >& source) const { typedef Stuff::LocalizableFunctionInterface< EntityType, DomainFieldType, dimDomain, RR, rRR, rCR > RangeType; typedef Stuff::LocalizableFunctionInterface< EntityType, DomainFieldType, dimDomain, RS, rRS, rCS > SourceType; LocalizableBase< LocalOperatorProvider, RangeType, SourceType > product(grid_view_, range, source, static_cast< const LocalOperatorProvider& >(*this)); return product.apply2(); } // ... apply2(...) private: const GridViewType& grid_view_; }; // class GenericBase } // namespace Products } // namespace GDT } // namespace Dune #endif // DUNE_GDT_PRODUCTS_BASE_HH <|endoftext|>
<commit_before>//============================================================================== // SingleCellSimulation plugin //============================================================================== #include "singlecellsimulationplugin.h" #include "cellmlmodel.h" #include "cellmlsupportplugin.h" //============================================================================== #include <QFileInfo> #include <QMainWindow> #include <QPen> //============================================================================== #include "qwt_plot.h" #include "qwt_plot_grid.h" //============================================================================== namespace OpenCOR { namespace SingleCellSimulation { //============================================================================== PLUGININFO_FUNC SingleCellSimulationPluginInfo() { Descriptions descriptions; descriptions.insert("en", "A plugin to run single cell simulations"); descriptions.insert("fr", "Une extension pour excuter des simulations unicellulaires"); return PluginInfo(PluginInfo::V001, PluginInfo::Gui, PluginInfo::Simulation, true, QStringList() << "CoreSimulation" << "CellMLSupport" << "Qwt", descriptions); } //============================================================================== Q_EXPORT_PLUGIN2(SingleCellSimulation, SingleCellSimulationPlugin) //============================================================================== SingleCellSimulationPlugin::SingleCellSimulationPlugin() { // Set our settings mGuiSettings->addView(GuiViewSettings::Simulation, 0); } //============================================================================== void SingleCellSimulationPlugin::initialize() { // Create our simulation view widget mSimulationView = new QwtPlot(mMainWindow); // Hide our simulation view widget since it may not initially be shown in // our central widget mSimulationView->setVisible(false); // Customise our simulation view widget mSimulationView->setCanvasBackground(Qt::white); // Remove the canvas' border as it otherwise looks odd, not to say ugly, // with one mSimulationView->setCanvasLineWidth(0); // Add a grid to our simulation view widget QwtPlotGrid *grid = new QwtPlotGrid; grid->setMajPen(QPen(Qt::gray, 0, Qt::DotLine)); grid->attach(mSimulationView); } //============================================================================== QWidget * SingleCellSimulationPlugin::viewWidget(const QString &pFileName, const int &) { // Check that we are dealing with a CellML file and, if so, return our // generic simulation view widget if (QFileInfo(pFileName).suffix().compare(CellMLSupport::CellmlFileExtension)) // Not the expected file extension, so... return 0; else { //--- TESTING --- BEGIN --- qDebug("======================================="); qDebug("%s:", pFileName.toLatin1().constData()); // Load the CellML model CellMLSupport::CellmlModel *cellmlModel = new CellMLSupport::CellmlModel(pFileName); // Check the model's validity if (cellmlModel->isValid()) { // The model is valid, but let's see whether warnings were generated int nbOfWarnings = cellmlModel->issues().count(); if (nbOfWarnings) qDebug(" - The model was properly loaded:"); else qDebug(" - The model was properly loaded."); } else { qDebug(" - The model was NOT properly loaded:"); } // Output any warnings/errors that were generated foreach (const CellMLSupport::CellmlModelIssue &issue, cellmlModel->issues()) { QString type = QString((issue.type() == CellMLSupport::CellmlModelIssue::Error)?"Error":"Warrning"); QString message = issue.formattedMessage(); uint32_t line = issue.line(); uint32_t column = issue.column(); QString importedModel = issue.importedModel(); if (line && column) { if (importedModel.isEmpty()) qDebug(" [%s at line %s column %s] %s", type.toLatin1().constData(), QString::number(issue.line()).toLatin1().constData(), QString::number(issue.column()).toLatin1().constData(), message.toUtf8().constData()); else qDebug(" [%s at line %s column %s from imported model %s] %s", type.toLatin1().constData(), QString::number(issue.line()).toLatin1().constData(), QString::number(issue.column()).toLatin1().constData(), importedModel.toLatin1().constData(), message.toUtf8().constData()); } else { if (importedModel.isEmpty()) qDebug(" [%s] %s", type.toLatin1().constData(), message.toUtf8().constData()); else qDebug(" [%s from imported model %s] %s", type.toLatin1().constData(), importedModel.toLatin1().constData(), message.toUtf8().constData()); } } // Get a runtime for the model CellMLSupport::CellmlModelRuntime *cellmlModelRuntime = cellmlModel->runtime(); if (cellmlModelRuntime->isValid()) { qDebug(" - The model's runtime was properly generated."); qDebug(" [Information] Model type = %s", (cellmlModelRuntime->modelType() == CellMLSupport::CellmlModelRuntime::Ode)?"ODE":"DAE"); } else { qDebug(" - The model's runtime was NOT properly generated:"); foreach (const CellMLSupport::CellmlModelIssue &issue, cellmlModelRuntime->issues()) { QString type = QString((issue.type() == CellMLSupport::CellmlModelIssue::Error)?"Error":"Warrning"); QString message = issue.formattedMessage(); qDebug(" [%s] %s", type.toLatin1().constData(), message.toUtf8().constData()); } } // Done with our testing, so... delete cellmlModel; //--- TESTING --- END --- // The expected file extension, so return our generic simulation view // widget return mSimulationView; } } //============================================================================== QString SingleCellSimulationPlugin::viewName(const int &pViewIndex) { // We have only one view, so return its name otherwise call the GuiInterface // implementation of viewName switch (pViewIndex) { case 0: return tr("Single Cell"); default: return GuiInterface::viewName(pViewIndex); } } //============================================================================== } // namespace SingleCellSimulation } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <commit_msg>Getting ready to compute a model, but only for demonstration purposes, so everything will be hard-coded.<commit_after>//============================================================================== // SingleCellSimulation plugin //============================================================================== #include "singlecellsimulationplugin.h" #include "cellmlmodel.h" #include "cellmlsupportplugin.h" //============================================================================== #include <QFileInfo> #include <QMainWindow> #include <QPen> #include <QVector> //============================================================================== #include "qwt_plot.h" #include "qwt_plot_grid.h" #include "qwt_plot_curve.h" //============================================================================== namespace OpenCOR { namespace SingleCellSimulation { //============================================================================== PLUGININFO_FUNC SingleCellSimulationPluginInfo() { Descriptions descriptions; descriptions.insert("en", "A plugin to run single cell simulations"); descriptions.insert("fr", "Une extension pour excuter des simulations unicellulaires"); return PluginInfo(PluginInfo::V001, PluginInfo::Gui, PluginInfo::Simulation, true, QStringList() << "CoreSimulation" << "CellMLSupport" << "Qwt", descriptions); } //============================================================================== Q_EXPORT_PLUGIN2(SingleCellSimulation, SingleCellSimulationPlugin) //============================================================================== SingleCellSimulationPlugin::SingleCellSimulationPlugin() { // Set our settings mGuiSettings->addView(GuiViewSettings::Simulation, 0); } //============================================================================== void SingleCellSimulationPlugin::initialize() { // Create our simulation view widget mSimulationView = new QwtPlot(mMainWindow); // Hide our simulation view widget since it may not initially be shown in // our central widget mSimulationView->setVisible(false); // Customise our simulation view widget mSimulationView->setCanvasBackground(Qt::white); // Remove the canvas' border as it otherwise looks odd, not to say ugly, // with one mSimulationView->setCanvasLineWidth(0); // Add a grid to our simulation view widget QwtPlotGrid *grid = new QwtPlotGrid; grid->setMajPen(QPen(Qt::gray, 0, Qt::DotLine)); grid->attach(mSimulationView); } //============================================================================== QWidget * SingleCellSimulationPlugin::viewWidget(const QString &pFileName, const int &) { // Check that we are dealing with a CellML file and, if so, return our // generic simulation view widget if (QFileInfo(pFileName).suffix().compare(CellMLSupport::CellmlFileExtension)) // Not the expected file extension, so... return 0; else { //--- TESTING --- BEGIN --- qDebug("======================================="); qDebug("%s:", pFileName.toLatin1().constData()); // Load the CellML model CellMLSupport::CellmlModel *cellmlModel = new CellMLSupport::CellmlModel(pFileName); // Check the model's validity if (cellmlModel->isValid()) { // The model is valid, but let's see whether warnings were generated int nbOfWarnings = cellmlModel->issues().count(); if (nbOfWarnings) qDebug(" - The model was properly loaded:"); else qDebug(" - The model was properly loaded."); } else { qDebug(" - The model was NOT properly loaded:"); } // Output any warnings/errors that were generated foreach (const CellMLSupport::CellmlModelIssue &issue, cellmlModel->issues()) { QString type = QString((issue.type() == CellMLSupport::CellmlModelIssue::Error)?"Error":"Warrning"); QString message = issue.formattedMessage(); uint32_t line = issue.line(); uint32_t column = issue.column(); QString importedModel = issue.importedModel(); if (line && column) { if (importedModel.isEmpty()) qDebug(" [%s at line %s column %s] %s", type.toLatin1().constData(), QString::number(issue.line()).toLatin1().constData(), QString::number(issue.column()).toLatin1().constData(), message.toUtf8().constData()); else qDebug(" [%s at line %s column %s from imported model %s] %s", type.toLatin1().constData(), QString::number(issue.line()).toLatin1().constData(), QString::number(issue.column()).toLatin1().constData(), importedModel.toLatin1().constData(), message.toUtf8().constData()); } else { if (importedModel.isEmpty()) qDebug(" [%s] %s", type.toLatin1().constData(), message.toUtf8().constData()); else qDebug(" [%s from imported model %s] %s", type.toLatin1().constData(), importedModel.toLatin1().constData(), message.toUtf8().constData()); } } // Get a runtime for the model CellMLSupport::CellmlModelRuntime *cellmlModelRuntime = cellmlModel->runtime(); if (cellmlModelRuntime->isValid()) { qDebug(" - The model's runtime was properly generated."); qDebug(" [Information] Model type = %s", (cellmlModelRuntime->modelType() == CellMLSupport::CellmlModelRuntime::Ode)?"ODE":"DAE"); } else { qDebug(" - The model's runtime was NOT properly generated:"); foreach (const CellMLSupport::CellmlModelIssue &issue, cellmlModelRuntime->issues()) { QString type = QString((issue.type() == CellMLSupport::CellmlModelIssue::Error)?"Error":"Warrning"); QString message = issue.formattedMessage(); qDebug(" [%s] %s", type.toLatin1().constData(), message.toUtf8().constData()); } } // Compute the model typedef QVector<double> Doubles; static const int NbOfDataPoints = 100; static const double Factor = 6.28/double(NbOfDataPoints-1); Doubles xData; Doubles yData; for (int i = 0; i < NbOfDataPoints; ++i) { xData.append(i*Factor); yData.append(sin(xData.last())); } // Add a curve to our view QwtPlotCurve *curve = new QwtPlotCurve; curve->setRenderHint(QwtPlotItem::RenderAntialiased); curve->setPen(QPen(Qt::darkBlue)); curve->setSamples(xData, yData); curve->attach(mSimulationView); // Done with our testing, so... delete cellmlModel; //--- TESTING --- END --- // The expected file extension, so return our generic simulation view // widget return mSimulationView; } } //============================================================================== QString SingleCellSimulationPlugin::viewName(const int &pViewIndex) { // We have only one view, so return its name otherwise call the GuiInterface // implementation of viewName switch (pViewIndex) { case 0: return tr("Single Cell"); default: return GuiInterface::viewName(pViewIndex); } } //============================================================================== } // namespace SingleCellSimulation } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <|endoftext|>
<commit_before>#include "gen_exported.h" namespace gen_exported { /******************************************************************************************************************* Copyright (c) 2012 Cycling '74 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *******************************************************************************************************************/ // global noise generator Noise noise; static const int GENLIB_LOOPCOUNT_BAIL = 100000; // The State struct contains all the state and procedures for the gendsp kernel typedef struct State { CommonState __commonstate; double m_resolution_1; double samplerate; int vectorsize; int __exception; // re-initialize all member variables; inline void reset(double __sr, int __vs) { __exception = 0; vectorsize = __vs; samplerate = __sr; m_resolution_1 = 6; genlib_reset_complete(this); }; // the signal processing routine; inline int perform(t_sample ** __ins, t_sample ** __outs, int __n) { vectorsize = __n; const t_sample * __in1 = __ins[0]; t_sample * __out1 = __outs[0]; t_sample * __out2 = __outs[1]; if (__exception) { return __exception; } else if (( (__in1 == 0) || (__out1 == 0) || (__out2 == 0) )) { __exception = GENLIB_ERR_NULL_BUFFER; return __exception; }; // the main sample loop; while ((__n--)) { const double in1 = (*(__in1++)); double mul_50 = (in1 * m_resolution_1); double ceil_49 = ceil(mul_50); double div_48 = safediv(ceil_49, m_resolution_1); double out1 = div_48; double add_45 = (mul_50 + 0.5); double floor_46 = floor(add_45); double sub_44 = (floor_46 - 0.5); double div_47 = safediv(sub_44, m_resolution_1); double out2 = div_47; // assign results to output buffer; (*(__out1++)) = out1; (*(__out2++)) = out2; }; return __exception; }; inline void set_resolution(double _value) { m_resolution_1 = _value; }; } State; /// /// Configuration for the genlib API /// /// Number of signal inputs and outputs int gen_kernel_numins = 1; int gen_kernel_numouts = 2; int num_inputs() { return gen_kernel_numins; } int num_outputs() { return gen_kernel_numouts; } int num_params() { return 1; } /// Assistive lables for the signal inputs and outputs const char * gen_kernel_innames[] = { "in1" }; const char * gen_kernel_outnames[] = { "out1", "out2" }; /// Invoke the signal process of a State object int perform(CommonState *cself, t_sample **ins, long numins, t_sample **outs, long numouts, long n) { State * self = (State *)cself; return self->perform(ins, outs, n); } /// Reset all parameters and stateful operators of a State object void reset(CommonState *cself) { State * self = (State *)cself; self->reset(cself->sr, cself->vs); } /// Set a parameter of a State object void setparameter(CommonState *cself, long index, double value, void *ref) { State * self = (State *)cself; switch (index) { case 0: self->set_resolution(value); break; default: break; } } /// Get the value of a parameter of a State object void getparameter(CommonState *cself, long index, double *value) { State *self = (State *)cself; switch (index) { case 0: *value = self->m_resolution_1; break; default: break; } } /// Allocate and configure a new State object and it's internal CommonState: void * create(double sr, long vs) { State *self = new State; self->reset(sr, vs); ParamInfo *pi; self->__commonstate.inputnames = gen_kernel_innames; self->__commonstate.outputnames = gen_kernel_outnames; self->__commonstate.numins = gen_kernel_numins; self->__commonstate.numouts = gen_kernel_numouts; self->__commonstate.sr = sr; self->__commonstate.vs = vs; self->__commonstate.params = (ParamInfo *)genlib_sysmem_newptr(1 * sizeof(ParamInfo)); self->__commonstate.numparams = 1; // initialize parameter 0 ("m_resolution_1") pi = self->__commonstate.params + 0; pi->name = "resolution"; pi->paramtype = GENLIB_PARAMTYPE_FLOAT; pi->defaultvalue = self->m_resolution_1; pi->defaultref = 0; pi->hasinputminmax = false; pi->inputmin = 0; pi->inputmax = 1; pi->hasminmax = true; pi->outputmin = 1; pi->outputmax = 32; pi->exp = 0; pi->units = "bits"; // no units defined return self; } /// Release all resources and memory used by a State object: void destroy(CommonState *cself) { State * self = (State *)cself; genlib_sysmem_freeptr(cself->params); delete self; } } // gen_exported:: <commit_msg>Limit bitcrusher resolution param to 16 max<commit_after>#include "gen_exported.h" namespace gen_exported { /******************************************************************************************************************* Copyright (c) 2012 Cycling '74 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *******************************************************************************************************************/ // global noise generator Noise noise; static const int GENLIB_LOOPCOUNT_BAIL = 100000; // The State struct contains all the state and procedures for the gendsp kernel typedef struct State { CommonState __commonstate; double m_resolution_1; double samplerate; int vectorsize; int __exception; // re-initialize all member variables; inline void reset(double __sr, int __vs) { __exception = 0; vectorsize = __vs; samplerate = __sr; m_resolution_1 = 6; genlib_reset_complete(this); }; // the signal processing routine; inline int perform(t_sample ** __ins, t_sample ** __outs, int __n) { vectorsize = __n; const t_sample * __in1 = __ins[0]; t_sample * __out1 = __outs[0]; t_sample * __out2 = __outs[1]; if (__exception) { return __exception; } else if (( (__in1 == 0) || (__out1 == 0) || (__out2 == 0) )) { __exception = GENLIB_ERR_NULL_BUFFER; return __exception; }; // the main sample loop; while ((__n--)) { const double in1 = (*(__in1++)); double mul_50 = (in1 * m_resolution_1); double ceil_49 = ceil(mul_50); double div_48 = safediv(ceil_49, m_resolution_1); double out1 = div_48; double add_45 = (mul_50 + 0.5); double floor_46 = floor(add_45); double sub_44 = (floor_46 - 0.5); double div_47 = safediv(sub_44, m_resolution_1); double out2 = div_47; // assign results to output buffer; (*(__out1++)) = out1; (*(__out2++)) = out2; }; return __exception; }; inline void set_resolution(double _value) { m_resolution_1 = (_value < 1 ? 1 : (_value > 16 ? 16 : _value)); }; } State; /// /// Configuration for the genlib API /// /// Number of signal inputs and outputs int gen_kernel_numins = 1; int gen_kernel_numouts = 2; int num_inputs() { return gen_kernel_numins; } int num_outputs() { return gen_kernel_numouts; } int num_params() { return 1; } /// Assistive lables for the signal inputs and outputs const char * gen_kernel_innames[] = { "in1" }; const char * gen_kernel_outnames[] = { "out1", "out2" }; /// Invoke the signal process of a State object int perform(CommonState *cself, t_sample **ins, long numins, t_sample **outs, long numouts, long n) { State * self = (State *)cself; return self->perform(ins, outs, n); } /// Reset all parameters and stateful operators of a State object void reset(CommonState *cself) { State * self = (State *)cself; self->reset(cself->sr, cself->vs); } /// Set a parameter of a State object void setparameter(CommonState *cself, long index, double value, void *ref) { State * self = (State *)cself; switch (index) { case 0: self->set_resolution(value); break; default: break; } } /// Get the value of a parameter of a State object void getparameter(CommonState *cself, long index, double *value) { State *self = (State *)cself; switch (index) { case 0: *value = self->m_resolution_1; break; default: break; } } /// Allocate and configure a new State object and it's internal CommonState: void * create(double sr, long vs) { State *self = new State; self->reset(sr, vs); ParamInfo *pi; self->__commonstate.inputnames = gen_kernel_innames; self->__commonstate.outputnames = gen_kernel_outnames; self->__commonstate.numins = gen_kernel_numins; self->__commonstate.numouts = gen_kernel_numouts; self->__commonstate.sr = sr; self->__commonstate.vs = vs; self->__commonstate.params = (ParamInfo *)genlib_sysmem_newptr(1 * sizeof(ParamInfo)); self->__commonstate.numparams = 1; // initialize parameter 0 ("m_resolution_1") pi = self->__commonstate.params + 0; pi->name = "resolution"; pi->paramtype = GENLIB_PARAMTYPE_FLOAT; pi->defaultvalue = self->m_resolution_1; pi->defaultref = 0; pi->hasinputminmax = false; pi->inputmin = 0; pi->inputmax = 1; pi->hasminmax = true; pi->outputmin = 1; pi->outputmax = 16; pi->exp = 0; pi->units = "bits"; // no units defined return self; } /// Release all resources and memory used by a State object: void destroy(CommonState *cself) { State * self = (State *)cself; genlib_sysmem_freeptr(cself->params); delete self; } } // gen_exported:: <|endoftext|>
<commit_before>// HoldTheFlag.cpp : bzfs plugin for Hold-The-flag game mode // // $Id$ #include "bzfsAPI.h" #include <map> #include <stdarg.h> BZ_GET_PLUGIN_VERSION #define HOLDTHEFLAG_VER "1.00.02" #define DO_FLAG_RESET 1 #define DEFAULT_TEAM eGreenTeam #define MAX_PLAYERID 255 #ifdef _WIN32 #ifndef strcasecmp # define strcasecmp _stricmp #endif #ifndef strncasecmp # define strncasecmp _strnicmp #endif #endif typedef struct { bool isValid; int score; char callsign[22]; double joinTime; int capNum; } HtfPlayer; HtfPlayer Players[MAX_PLAYERID+1]; std::map<std::string, HtfPlayer> leftDuringMatch; bool matchActive = false; bool htfEnabled = true; bz_eTeamType htfTeam = eNoTeam; int nextCapNum = 0; int NumPlayers=0; int Leader; class HTFscore : public bz_EventHandler, public bz_CustomSlashCommandHandler { public: virtual void process ( bz_EventData *eventData ); virtual bool handle ( int playerID, bz_ApiString, bz_ApiString, bz_APIStringList*); bz_eTeamType colorNameToDef (const char *color); const char *colorDefToName (bz_eTeamType team); protected: private: }; HTFscore htfScore; bz_eTeamType HTFscore::colorNameToDef (const char *color) { if (!color && (strlen(color)<3)) return eNoTeam; char temp[4] = {0}; strncpy(temp,color,3); if (!strcasecmp (color, "gre")) return eGreenTeam; if (!strcasecmp (color, "red")) return eRedTeam; if (!strcasecmp (color, "pur")) return ePurpleTeam; if (!strcasecmp (color, "blu")) return eBlueTeam; if (!strcasecmp (color, "rog")) return eRogueTeam; if (!strcasecmp (color, "obs")) return eObservers; return eNoTeam; } const char *HTFscore::colorDefToName (bz_eTeamType team) { switch (team){ case eGreenTeam: return ("Green"); case eBlueTeam: return ("Blue"); case eRedTeam: return ("Red"); case ePurpleTeam: return ("Purple"); case eObservers: return ("Observer"); case eRogueTeam: return ("Rogue"); case eRabbitTeam: return ("Rabbit"); case eHunterTeam: return ("Hunters"); case eAdministrators: return ("Administrators"); default: return ("No Team"); } } bool listAdd (int playerID, const char *callsign) { if (playerID>MAX_PLAYERID || playerID<0) return false; Players[playerID].score = 0; Players[playerID].isValid = true; Players[playerID].capNum = -1; strncpy (Players[playerID].callsign, callsign, 20); ++NumPlayers; return true; } bool listDel (int playerID){ if (playerID>MAX_PLAYERID || playerID<0 || !Players[playerID].isValid) return false; Players[playerID].isValid = false; --NumPlayers; return true; } int sort_compare (const void *_p1, const void *_p2){ int p1 = *(int *)_p1; int p2 = *(int *)_p2; if (Players[p1].score != Players[p2].score) return Players[p2].score - Players[p1].score; return Players[p2].capNum - Players[p1].capNum; return 0; } void dispScores (int who) { int sortList[MAX_PLAYERID+1]; // do HtfPlayer * !! int playerLastCapped = -1; int lastCapnum = -1; int x = 0; if (!htfEnabled) return; bz_sendTextMessage(BZ_SERVER, who, "**** HTF Scoreboard ****"); Leader = -1; if (NumPlayers<1) return; for (int i=0; i<MAX_PLAYERID; i++){ if (Players[i].isValid) { if (Players[i].capNum > lastCapnum){ playerLastCapped = i; lastCapnum = Players[i].capNum; } sortList[x++] = i; } } qsort (sortList, NumPlayers, sizeof(int), sort_compare); if (x != NumPlayers) bz_debugMessage(1, "++++++++++++++++++++++++ HTF INTERNAL ERROR: player count mismatch!"); for (int i=0; i<NumPlayers; i++){ x = sortList[i]; bz_sendTextMessagef(BZ_SERVER, who, "%20.20s :%3d %c", Players[x].callsign, Players[x].score, x == playerLastCapped ? '*' : ' '); } Leader = sortList[0]; } void resetScores (void) { for (int i=0; i<MAX_PLAYERID; i++){ Players[i].score = 0; Players[i].capNum = -1; } nextCapNum = 0; } void htfCapture (int who) { if (!htfEnabled) return; #if DO_FLAG_RESET bz_resetFlags ( false ); #endif bz_sendTextMessagef (BZ_SERVER, BZ_ALLUSERS, "HTF FLAG CAPTURED by %s", Players[who].callsign); ++Players[who].score; Players[who].capNum = nextCapNum++; dispScores(BZ_ALLUSERS); } void htfStartGame (void) { if (!htfEnabled) return; // TODO: clear leftDuringMatch resetScores(); matchActive = true; bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, "HTF MATCH has begun, good luck!"); } void htfEndGame (void) { if (htfEnabled && matchActive){ dispScores(BZ_ALLUSERS); bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, "HTF MATCH has ended."); if (Leader >= 0) bz_sendTextMessagef(BZ_SERVER, BZ_ALLUSERS, "%s is the WINNER !", Players[Leader].callsign); } matchActive = false; // TODO: clear leftDuringMatch } void sendHelp (int who) { bz_sendTextMessage(BZ_SERVER, who, "HTF commands: reset, off, on, stats"); } /************************** (SUB)COMMAND Implementations ... **************************/ void htfStats (int who) { bz_sendTextMessagef(BZ_SERVER, who, "HTF plugin version %s", HOLDTHEFLAG_VER); bz_sendTextMessagef(BZ_SERVER, who, " Team: %s", htfScore.colorDefToName(htfTeam)); bz_sendTextMessagef(BZ_SERVER, who, " Flag Reset: %s" , DO_FLAG_RESET ? "ENabled":"DISabled"); } void htfReset (int who) { resetScores(); bz_sendTextMessagef (BZ_SERVER, BZ_ALLUSERS, "*** HTF scores reset by %s", Players[who].callsign); } void htfEnable (bool onoff, int who) { char msg[255]; if (onoff == htfEnabled){ bz_sendTextMessage(BZ_SERVER, who, "HTF mode is already that way."); return; } htfEnabled = onoff; sprintf (msg, "*** HTF mode %s by %s", onoff?"ENabled":"DISabled", Players[who].callsign); bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, msg); } // handle events void HTFscore::process ( bz_EventData *eventData ) { // player JOIN if (eventData->eventType == bz_ePlayerJoinEvent) { char msg[255]; bz_PlayerJoinPartEventData_V1 *joinData = (bz_PlayerJoinPartEventData_V1*)eventData; bz_debugMessagef(3, "++++++ HTFscore: Player JOINED (ID:%d, TEAM:%d, CALLSIGN:%s)", joinData->playerID, joinData->record->team, joinData->record->callsign.c_str()); fflush (stdout); if (htfTeam!=eNoTeam && joinData->record->team!=htfTeam && joinData->record->team != eObservers){ sprintf (msg, "HTF mode enabled, you must join the %s team to play", htfScore.colorDefToName(htfTeam)); bz_kickUser (joinData->record->playerID, msg, true); return; } if (joinData->record->team == htfTeam) listAdd (joinData->playerID, joinData->record->callsign.c_str()); // player PART } else if (eventData->eventType == bz_ePlayerPartEvent) { bz_PlayerJoinPartEventData_V1 *joinData = (bz_PlayerJoinPartEventData_V1*)eventData; bz_debugMessagef(3, "++++++ HTFscore: Player PARTED (ID:%d, TEAM:%d, CALLSIGN:%s)", joinData->playerID, joinData->record->team, joinData->record->callsign.c_str()); fflush (stdout); if (joinData->record->team == htfTeam) listDel (joinData->playerID); // flag CAPTURE } else if (eventData->eventType == bz_eCaptureEvent) { bz_CTFCaptureEventData_V1 *capData = (bz_CTFCaptureEventData_V1*)eventData; htfCapture (capData->playerCapping); // game START } else if (eventData->eventType == bz_eGameStartEvent) { bz_GameStartEndEventData_V1 *msgData = (bz_GameStartEndEventData_V1*)eventData; bz_debugMessagef(2, "++++++ HTFscore: Game START (%f, %f)", msgData->eventTime, msgData->duration); fflush (stdout); htfStartGame (); // game END } else if (eventData->eventType == bz_eGameEndEvent) { bz_GameStartEndEventData_V1 *msgData = (bz_GameStartEndEventData_V1*)eventData; bz_debugMessagef(2, "++++++ HTFscore: Game END (%f, %f)", msgData->eventTime, msgData->duration); fflush (stdout); htfEndGame (); } } bool checkPerms (int playerID, const char *htfCmd, const char *permName) { if (bz_hasPerm (playerID, permName)) return true; bz_sendTextMessagef (BZ_SERVER, BZ_ALLUSERS, "you need \"%s\" permission to do /htf %s", permName, htfCmd); return false; } // handle /htf command bool HTFscore::handle ( int playerID, bz_ApiString cmd, bz_ApiString, bz_APIStringList* cmdParams ) { char subCmd[6]; if (strcasecmp (cmd.c_str(), "htf")) // is it for me ? return false; if (cmdParams->get(0).c_str()[0] == '\0'){ dispScores (playerID); return true; } strncpy (subCmd, cmdParams->get(0).c_str(), 5); subCmd[4] = '\0'; if (strcasecmp (subCmd, "rese") == 0){ if (checkPerms (playerID, "reset", "COUNTDOWN")) htfReset (playerID); } else if (strcasecmp (subCmd, "off") == 0){ if (checkPerms (playerID, "off", "HTFONOFF")) htfEnable (false, playerID); } else if (strcasecmp (subCmd, "on") == 0){ if (checkPerms (playerID, "off", "HTFONOFF")) htfEnable (true, playerID); } else if (strcasecmp (subCmd, "stat") == 0) htfStats (playerID); else sendHelp (playerID); return true; } bool commandLineHelp (void){ const char *help[] = { "Command line args: PLUGINNAME,[TEAM=color]", NULL }; bz_debugMessage (0, "+++ HoldTheFlag plugin command-line error"); for (int x=0; help[x]!=NULL; x++) bz_debugMessage (0, help[x]); return true; } bool parseCommandLine (const char *cmdLine) { if (cmdLine==NULL || *cmdLine=='\0' || strlen(cmdLine) < 5 ) return false; htfTeam = eGreenTeam; if (strncasecmp (cmdLine, "TEAM=", 5) == 0){ if ((htfTeam = htfScore.colorNameToDef(cmdLine+5)) == eNoTeam) return commandLineHelp (); } else return commandLineHelp (); return false; } BZF_PLUGIN_CALL int bz_Load (const char* cmdLine) { bz_BasePlayerRecord *playerRecord; if (parseCommandLine (cmdLine)) return -1; // get current list of player indices ... bz_APIIntList *playerList = bz_newIntList(); bz_getPlayerIndexList (playerList); for (unsigned int i = 0; i < playerList->size(); i++){ if ((playerRecord = bz_getPlayerByIndex (playerList->get(i))) != NULL){ listAdd (playerList->get(i), playerRecord->callsign.c_str()); bz_freePlayerRecord (playerRecord); } } bz_deleteIntList (playerList); bz_registerCustomSlashCommand ("htf", &htfScore); bz_registerEvent(bz_ePlayerJoinEvent, &htfScore); bz_registerEvent(bz_ePlayerPartEvent, &htfScore); bz_registerEvent(bz_eCaptureEvent, &htfScore); bz_registerEvent(bz_eGameStartEvent, &htfScore); bz_registerEvent(bz_eGameEndEvent, &htfScore); bz_debugMessagef(1, "HoldTheFlag plugin loaded - v%s", HOLDTHEFLAG_VER); return 0; } BZF_PLUGIN_CALL int bz_Unload (void) { bz_removeCustomSlashCommand ("htf"); bz_removeEvent (bz_ePlayerJoinEvent, &htfScore); bz_removeEvent (bz_ePlayerPartEvent, &htfScore); bz_removeEvent (bz_eCaptureEvent, &htfScore); bz_removeEvent (bz_eGameStartEvent, &htfScore); bz_removeEvent (bz_eGameEndEvent, &htfScore); bz_debugMessage(1, "HoldTheFlag plugin unloaded"); return 0; } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>More whitespace... where will it end?<commit_after>// HoldTheFlag.cpp : bzfs plugin for Hold-The-flag game mode // // $Id$ #include "bzfsAPI.h" #include <map> #include <stdarg.h> BZ_GET_PLUGIN_VERSION #define HOLDTHEFLAG_VER "1.00.02" #define DO_FLAG_RESET 1 #define DEFAULT_TEAM eGreenTeam #define MAX_PLAYERID 255 #ifdef _WIN32 #ifndef strcasecmp # define strcasecmp _stricmp #endif #ifndef strncasecmp # define strncasecmp _strnicmp #endif #endif typedef struct { bool isValid; int score; char callsign[22]; double joinTime; int capNum; } HtfPlayer; HtfPlayer Players[MAX_PLAYERID+1]; std::map<std::string, HtfPlayer> leftDuringMatch; bool matchActive = false; bool htfEnabled = true; bz_eTeamType htfTeam = eNoTeam; int nextCapNum = 0; int NumPlayers=0; int Leader; class HTFscore : public bz_EventHandler, public bz_CustomSlashCommandHandler { public: virtual void process(bz_EventData *eventData); virtual bool handle(int playerID, bz_ApiString, bz_ApiString, bz_APIStringList*); bz_eTeamType colorNameToDef(const char *color); const char *colorDefToName(bz_eTeamType team); protected: private: }; HTFscore htfScore; bz_eTeamType HTFscore::colorNameToDef(const char *color) { if (!color && (strlen(color)<3)) return eNoTeam; char temp[4] = {0}; strncpy(temp,color,3); if (!strcasecmp(color, "gre")) return eGreenTeam; if (!strcasecmp(color, "red")) return eRedTeam; if (!strcasecmp(color, "pur")) return ePurpleTeam; if (!strcasecmp(color, "blu")) return eBlueTeam; if (!strcasecmp(color, "rog")) return eRogueTeam; if (!strcasecmp(color, "obs")) return eObservers; return eNoTeam; } const char *HTFscore::colorDefToName(bz_eTeamType team) { switch (team){ case eGreenTeam: return ("Green"); case eBlueTeam: return ("Blue"); case eRedTeam: return ("Red"); case ePurpleTeam: return ("Purple"); case eObservers: return ("Observer"); case eRogueTeam: return ("Rogue"); case eRabbitTeam: return ("Rabbit"); case eHunterTeam: return ("Hunters"); case eAdministrators: return ("Administrators"); default: return ("No Team"); } } bool listAdd(int playerID, const char *callsign) { if (playerID>MAX_PLAYERID || playerID<0) return false; Players[playerID].score = 0; Players[playerID].isValid = true; Players[playerID].capNum = -1; strncpy(Players[playerID].callsign, callsign, 20); ++NumPlayers; return true; } bool listDel(int playerID){ if (playerID>MAX_PLAYERID || playerID<0 || !Players[playerID].isValid) return false; Players[playerID].isValid = false; --NumPlayers; return true; } int sort_compare(const void *_p1, const void *_p2){ int p1 = *(int *)_p1; int p2 = *(int *)_p2; if (Players[p1].score != Players[p2].score) return Players[p2].score - Players[p1].score; return Players[p2].capNum - Players[p1].capNum; return 0; } void dispScores(int who) { int sortList[MAX_PLAYERID+1]; // do HtfPlayer * !! int playerLastCapped = -1; int lastCapnum = -1; int x = 0; if (!htfEnabled) return; bz_sendTextMessage(BZ_SERVER, who, "**** HTF Scoreboard ****"); Leader = -1; if (NumPlayers<1) return; for (int i=0; i<MAX_PLAYERID; i++){ if (Players[i].isValid) { if (Players[i].capNum > lastCapnum){ playerLastCapped = i; lastCapnum = Players[i].capNum; } sortList[x++] = i; } } qsort(sortList, NumPlayers, sizeof(int), sort_compare); if (x != NumPlayers) bz_debugMessage(1, "++++++++++++++++++++++++ HTF INTERNAL ERROR: player count mismatch!"); for (int i=0; i<NumPlayers; i++){ x = sortList[i]; bz_sendTextMessagef(BZ_SERVER, who, "%20.20s :%3d %c", Players[x].callsign, Players[x].score, x == playerLastCapped ? '*' : ' '); } Leader = sortList[0]; } void resetScores(void) { for (int i=0; i<MAX_PLAYERID; i++){ Players[i].score = 0; Players[i].capNum = -1; } nextCapNum = 0; } void htfCapture(int who) { if (!htfEnabled) return; #if DO_FLAG_RESET bz_resetFlags(false); #endif bz_sendTextMessagef(BZ_SERVER, BZ_ALLUSERS, "HTF FLAG CAPTURED by %s", Players[who].callsign); ++Players[who].score; Players[who].capNum = nextCapNum++; dispScores(BZ_ALLUSERS); } void htfStartGame(void) { if (!htfEnabled) return; // TODO: clear leftDuringMatch resetScores(); matchActive = true; bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, "HTF MATCH has begun, good luck!"); } void htfEndGame(void) { if (htfEnabled && matchActive){ dispScores(BZ_ALLUSERS); bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, "HTF MATCH has ended."); if (Leader >= 0) bz_sendTextMessagef(BZ_SERVER, BZ_ALLUSERS, "%s is the WINNER !", Players[Leader].callsign); } matchActive = false; // TODO: clear leftDuringMatch } void sendHelp(int who) { bz_sendTextMessage(BZ_SERVER, who, "HTF commands: reset, off, on, stats"); } /************************** (SUB)COMMAND Implementations ... **************************/ void htfStats(int who) { bz_sendTextMessagef(BZ_SERVER, who, "HTF plugin version %s", HOLDTHEFLAG_VER); bz_sendTextMessagef(BZ_SERVER, who, " Team: %s", htfScore.colorDefToName(htfTeam)); bz_sendTextMessagef(BZ_SERVER, who, " Flag Reset: %s" , DO_FLAG_RESET ? "ENabled":"DISabled"); } void htfReset(int who) { resetScores(); bz_sendTextMessagef(BZ_SERVER, BZ_ALLUSERS, "*** HTF scores reset by %s", Players[who].callsign); } void htfEnable(bool onoff, int who) { char msg[255]; if (onoff == htfEnabled){ bz_sendTextMessage(BZ_SERVER, who, "HTF mode is already that way."); return; } htfEnabled = onoff; sprintf(msg, "*** HTF mode %s by %s", onoff?"ENabled":"DISabled", Players[who].callsign); bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, msg); } // handle events void HTFscore::process(bz_EventData *eventData) { // player JOIN if (eventData->eventType == bz_ePlayerJoinEvent) { char msg[255]; bz_PlayerJoinPartEventData_V1 *joinData = (bz_PlayerJoinPartEventData_V1*)eventData; bz_debugMessagef(3, "++++++ HTFscore: Player JOINED (ID:%d, TEAM:%d, CALLSIGN:%s)", joinData->playerID, joinData->record->team, joinData->record->callsign.c_str()); fflush(stdout); if (htfTeam!=eNoTeam && joinData->record->team!=htfTeam && joinData->record->team != eObservers) { sprintf(msg, "HTF mode enabled, you must join the %s team to play", htfScore.colorDefToName(htfTeam)); bz_kickUser(joinData->record->playerID, msg, true); return; } if (joinData->record->team == htfTeam) listAdd(joinData->playerID, joinData->record->callsign.c_str()); // player PART } else if (eventData->eventType == bz_ePlayerPartEvent) { bz_PlayerJoinPartEventData_V1 *joinData = (bz_PlayerJoinPartEventData_V1*)eventData; bz_debugMessagef(3, "++++++ HTFscore: Player PARTED (ID:%d, TEAM:%d, CALLSIGN:%s)", joinData->playerID, joinData->record->team, joinData->record->callsign.c_str()); fflush(stdout); if (joinData->record->team == htfTeam) listDel (joinData->playerID); // flag CAPTURE } else if (eventData->eventType == bz_eCaptureEvent) { bz_CTFCaptureEventData_V1 *capData = (bz_CTFCaptureEventData_V1*)eventData; htfCapture(capData->playerCapping); // game START } else if (eventData->eventType == bz_eGameStartEvent) { bz_GameStartEndEventData_V1 *msgData = (bz_GameStartEndEventData_V1*)eventData; bz_debugMessagef(2, "++++++ HTFscore: Game START (%f, %f)", msgData->eventTime, msgData->duration); fflush(stdout); htfStartGame(); // game END } else if (eventData->eventType == bz_eGameEndEvent) { bz_GameStartEndEventData_V1 *msgData = (bz_GameStartEndEventData_V1*)eventData; bz_debugMessagef(2, "++++++ HTFscore: Game END (%f, %f)", msgData->eventTime, msgData->duration); fflush(stdout); htfEndGame(); } } bool checkPerms(int playerID, const char *htfCmd, const char *permName) { if (bz_hasPerm(playerID, permName)) return true; bz_sendTextMessagef(BZ_SERVER, BZ_ALLUSERS, "you need \"%s\" permission to do /htf %s", permName, htfCmd); return false; } // handle /htf command bool HTFscore::handle(int playerID, bz_ApiString cmd, bz_ApiString, bz_APIStringList* cmdParams) { char subCmd[6]; if (strcasecmp (cmd.c_str(), "htf")) // is it for me ? return false; if (cmdParams->get(0).c_str()[0] == '\0'){ dispScores(playerID); return true; } strncpy(subCmd, cmdParams->get(0).c_str(), 5); subCmd[4] = '\0'; if (strcasecmp(subCmd, "rese") == 0){ if (checkPerms(playerID, "reset", "COUNTDOWN")) htfReset(playerID); } else if (strcasecmp(subCmd, "off") == 0){ if (checkPerms(playerID, "off", "HTFONOFF")) htfEnable(false, playerID); } else if (strcasecmp(subCmd, "on") == 0){ if (checkPerms(playerID, "off", "HTFONOFF")) htfEnable(true, playerID); } else if (strcasecmp(subCmd, "stat") == 0) { htfStats(playerID); } else { sendHelp(playerID); } return true; } bool commandLineHelp(void){ const char *help[] = { "Command line args: PLUGINNAME,[TEAM=color]", NULL }; bz_debugMessage(0, "+++ HoldTheFlag plugin command-line error"); for (int x=0; help[x]!=NULL; x++) bz_debugMessage(0, help[x]); return true; } bool parseCommandLine(const char *cmdLine) { if (cmdLine==NULL || *cmdLine=='\0' || strlen(cmdLine) < 5) return false; htfTeam = eGreenTeam; if (strncasecmp(cmdLine, "TEAM=", 5) == 0){ if ((htfTeam = htfScore.colorNameToDef(cmdLine+5)) == eNoTeam) return commandLineHelp(); } else { return commandLineHelp(); } return false; } BZF_PLUGIN_CALL int bz_Load(const char* cmdLine) { bz_BasePlayerRecord *playerRecord; if (parseCommandLine(cmdLine)) return -1; // get current list of player indices ... bz_APIIntList *playerList = bz_newIntList(); bz_getPlayerIndexList(playerList); for (unsigned int i = 0; i < playerList->size(); i++){ if ((playerRecord = bz_getPlayerByIndex(playerList->get(i))) != NULL){ listAdd (playerList->get(i), playerRecord->callsign.c_str()); bz_freePlayerRecord(playerRecord); } } bz_deleteIntList(playerList); bz_registerCustomSlashCommand("htf", &htfScore); bz_registerEvent(bz_ePlayerJoinEvent, &htfScore); bz_registerEvent(bz_ePlayerPartEvent, &htfScore); bz_registerEvent(bz_eCaptureEvent, &htfScore); bz_registerEvent(bz_eGameStartEvent, &htfScore); bz_registerEvent(bz_eGameEndEvent, &htfScore); bz_debugMessagef(1, "HoldTheFlag plugin loaded - v%s", HOLDTHEFLAG_VER); return 0; } BZF_PLUGIN_CALL int bz_Unload(void) { bz_removeCustomSlashCommand("htf"); bz_removeEvent(bz_ePlayerJoinEvent, &htfScore); bz_removeEvent(bz_ePlayerPartEvent, &htfScore); bz_removeEvent(bz_eCaptureEvent, &htfScore); bz_removeEvent(bz_eGameStartEvent, &htfScore); bz_removeEvent(bz_eGameEndEvent, &htfScore); bz_debugMessage(1, "HoldTheFlag plugin unloaded"); return 0; } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>/* * Copyright 2015 Georgia Institute of Technology * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file clear_cache.cpp * @ingroup * @author tpan * @brief clears cache on a linux system * @details for use before doing file io benchmark. * * Copyright (c) 2016 Georgia Institute of Technology. All Rights Reserved. * * TODO add License */ #include "utils/memory_usage.hpp" /** * @brief clear the disk cache in linux by allocating a bunch of memory. * @details in 1MB chunks to workaround memory fragmentation preventing allocation. * can potentially use swap, or if there is not enough physical + swap, be killed. * */ void clear_cache() { size_t avail = MemUsage::get_usable_mem(); size_t rem = avail; size_t minchunk = 1UL << 24; // 16MB chunks size_t chunk = minchunk; size_t maxchunk = std::min(1UL << 30, (avail >> 4)); for ( ;chunk < maxchunk; chunk <<= 1) ; // keep increasing chunks until larger than 1/16 of avail, or until 1GB. std::vector<size_t *> dummy; size_t nchunks; size_t i; size_t *ptr; size_t j = 0; printf("begin clearing %lu bytes\n", avail); size_t iter_cleared = 0; while ((chunk >= minchunk) && (rem > minchunk)) { nchunks = rem / chunk; iter_cleared = 0; for (i = 0; i < nchunks; ++i, ++j) { // if ((j % 16) == 0) { // printf("%lu ", j); // 16 outputs. // fflush(stdout); // } // (c|m)alloc/free seems to be optimized out. using new works. ptr = new size_t[(chunk / sizeof(size_t))]; iter_cleared += chunk; memset(ptr, 0, chunk); ptr[0] = i; dummy.push_back(ptr); } // // check for available memory, every 64 MBs // if ((i % 64) == 0) { // avail = MemUsage::get_usable_mem(); // if (avail < (64 << 20)) break; // less than 64MB available. // } rem -= iter_cleared; printf("cleared %lu bytes using %lu chunk %lu bytes. total cleared %lu bytes, rem %lu bytes \n", iter_cleared, i, chunk, avail - rem, rem); fflush(stdout); // reduce the size of the chunk by 4 chunk >>= 2; } printf("finished clearing %lu/%lu bytes with %lu remaining\n", avail - rem, avail, rem); fflush(stdout); size_t sum = 0; size_t ii = 0; for (; ii < dummy.size(); ++ii) { ptr = dummy[ii]; if (ptr != nullptr) { // if ((ii % 16) == 0) { // printf("%lu ", ii); // 16 outputs. // fflush(stdout); // } sum += ptr[ii >> 10]; delete [] ptr; //free(ptr); dummy[ii] = nullptr; } else { break; } } printf("\n"); printf("disk cache cleared (dummy %lu). %lu blocks %lu bytes\n", sum, j, avail - rem); } int main(int argc, char** argv) { clear_cache(); return 0; } <commit_msg>WIP: further testing on large memory machine<commit_after>/* * Copyright 2015 Georgia Institute of Technology * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file clear_cache.cpp * @ingroup * @author tpan * @brief clears cache on a linux system * @details for use before doing file io benchmark. * * Copyright (c) 2016 Georgia Institute of Technology. All Rights Reserved. * * TODO add License */ #include "utils/memory_usage.hpp" #ifdef USE_OPENMP #include <omp.h> #endif /** * @brief clear the disk cache in linux by allocating a bunch of memory. * @details in 1MB chunks to workaround memory fragmentation preventing allocation. * can potentially use swap, or if there is not enough physical + swap, be killed. * */ void clear_cache() { size_t avail = MemUsage::get_usable_mem(); size_t rem = avail; size_t minchunk = 1UL << 24; // 16MB chunks size_t chunk = minchunk; size_t maxchunk = std::min(1UL << 30, (avail >> 4)); for ( ;chunk < maxchunk; chunk <<= 1) ; // keep increasing chunks until larger than 1/16 of avail, or until 1GB. std::vector<size_t *> dummy; size_t nchunks; size_t j = 0, lj; printf("begin clearing %lu bytes\n", avail); size_t iter_cleared = 0; while ((chunk >= minchunk) && (rem > minchunk)) { nchunks = rem / chunk; iter_cleared = 0; lj = 0; #pragma omp parallel for shared(nchunks, chunk, dummy) reduction(+:lj, iter_cleared) for (size_t i = 0; i < nchunks; ++i) { // (c|m)alloc/free seems to be optimized out. using new works. size_t * ptr = new size_t[(chunk / sizeof(size_t))]; iter_cleared += chunk; memset(ptr, 0, chunk); ptr[0] = i; #pragma omp critical { dummy.push_back(ptr); } ++lj; } j += lj; // // check for available memory, every 64 MBs // if ((i % 64) == 0) { // avail = MemUsage::get_usable_mem(); // if (avail < (64 << 20)) break; // less than 64MB available. // } rem -= iter_cleared; printf("cleared %lu bytes using %lu chunk %lu bytes. total cleared %lu bytes, rem %lu bytes \n", iter_cleared, nchunks, chunk, avail - rem, rem); fflush(stdout); // reduce the size of the chunk by 4 chunk >>= 2; } printf("finished clearing %lu/%lu bytes with %lu remaining\n", avail - rem, avail, rem); fflush(stdout); size_t sum = 0; size_t ii = 0; size_t *ptr; for (; ii < dummy.size(); ++ii) { ptr = dummy[ii]; if (ptr != nullptr) { // if ((ii % 16) == 0) { // printf("%lu ", ii); // 16 outputs. // fflush(stdout); // } sum += ptr[ii >> 10]; delete [] ptr; //free(ptr); dummy[ii] = nullptr; } else { break; } } printf("\n"); printf("disk cache cleared (dummy %lu). %lu blocks %lu bytes\n", sum, j, avail - rem); } int main(int argc, char** argv) { clear_cache(); return 0; } <|endoftext|>
<commit_before>// The "Square Detector" program. // It loads several images sequentially and tries to find squares in // each image #include "opencv2/core/core.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include <iostream> #include <math.h> #include <string.h> #include <stdio.h> #include <ros/ros.h> #include <osuar_vision/windowCoordinates.h> using namespace cv; int thresh = 50, N = 11; // Threshold for maximum cosine between angles (x100). int maxCosineThresh = 20; // Threshold for ratio of shortest side / longest side (x100). int sideRatioThresh = 75; // Maximum square area. int maxSquareArea = 41000; // Find colors of any hue... int wallHueLow = 50; int wallHueHigh = 132; // ...of low saturation... int wallSatLow = 0; int wallSatHigh = 100; // ...ranging down to gray, but not completely dark. That is to say, white. int wallValLow = 90; int wallValHigh = 255; ros::Publisher visPub; osuar_vision::windowCoordinates winCoords; // helper function: // finds a cosine of angle between vectors // from pt0->pt1 and from pt0->pt2 static double angle( Point pt1, Point pt2, Point pt0 ) { double dx1 = pt1.x - pt0.x; double dy1 = pt1.y - pt0.y; double dx2 = pt2.x - pt0.x; double dy2 = pt2.y - pt0.y; return (dx1*dx2 + dy1*dy2)/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10); } // returns sequence of squares detected on the image. // the sequence is stored in the specified memory storage static void findSquares( const Mat& image, vector<vector<Point> >& squares ) { squares.clear(); Mat pyr, timg, gray0(image.size(), CV_8U), gray; // down-scale and upscale the image to filter out the noise pyrDown(image, pyr, Size(image.cols/2, image.rows/2)); pyrUp(pyr, timg, image.size()); vector<vector<Point> > contours; // find squares in every color plane of the image //for( int c = 0; c < 3; c++ ) //{ //int ch[] = {c, 0}; //mixChannels(&timg, 1, &gray0, 1, ch, 1); // try several threshold levels for( int l = 0; l < N; l++ ) { // hack: use Canny instead of zero threshold level. // Canny helps to catch squares with gradient shading if( l == 0 ) { // apply Canny. Take the upper threshold from slider // and set the lower to 0 (which forces edges merging) Canny(image, gray, 0, thresh, 5); // dilate canny output to remove potential // holes between edge segments dilate(gray, gray, Mat(), Point(-1,-1)); } else { // apply threshold if l!=0: // tgray(x,y) = gray(x,y) < (l+1)*255/N ? 255 : 0 gray = image >= (l+1)*255/N; } // find contours and store them all as a list findContours(gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE); vector<Point> approx; // test each contour for( size_t i = 0; i < contours.size(); i++ ) { // approximate contour with accuracy proportional // to the contour perimeter approxPolyDP(Mat(contours[i]), approx, arcLength(Mat(contours[i]), true)*0.02, true); // square contours should have 4 vertices after approximation // relatively large area (to filter out noisy contours) // and be convex. // Note: absolute value of an area is used because // area may be positive or negative - in accordance with the // contour orientation if( approx.size() == 4 && fabs(contourArea(Mat(approx))) > 1000 && fabs(contourArea(Mat(approx))) < maxSquareArea && isContourConvex(Mat(approx)) ) { double maxCosine = 0; double minSideLen = 100000; double maxSideLen = 0; double sideRatio = 0; for( int j = 2; j < 5; j++ ) { // find the maximum cosine of the angle between joint edges double cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1])); maxCosine = MAX(maxCosine, cosine); // Find the maximum difference in length of adjacent // sides double sideLen = sqrt(pow((approx[j%4].x - approx[(j+1)%4].x), 2) + pow((approx[j%4].y - approx[(j+1)%4].y), 2)); minSideLen = MIN(minSideLen, sideLen); maxSideLen = MAX(maxSideLen, sideLen); } sideRatio = minSideLen / maxSideLen; std::cout << minSideLen << " " << maxSideLen << "\n"; // if cosines of all angles are small // (all angles are ~90 degree) then write quandrange // vertices to resultant sequence if( maxCosine < ((double) maxCosineThresh)/100 && sideRatio >= (double) sideRatioThresh/100 ) squares.push_back(approx); } } } //} } // the function draws all the squares in the image static void drawSquares( Mat& image, const vector<vector<Point> >& squares ) { for( size_t i = 0; i < squares.size(); i++ ) { const Point* p = &squares[i][0]; int n = (int)squares[i].size(); polylines(image, &p, &n, 1, true, Scalar(0,255,0), 3, CV_AA); std::cout << "x: " << squares[i][0].x << " y: " << squares[i][0].y << "\n"; // Only publish coordinates for one of the squares. Coordinates are // shifted over by half the camera resolution (which itself is scaled // down by a factor of two!) on each axis. The y coordinate is inverted // so up is positive. if (i == 0) { putText(image, "0", squares[0][0], FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255,0,0)); putText(image, "1", squares[0][1], FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255,0,0)); putText(image, "2", squares[0][2], FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255,0,0)); putText(image, "3", squares[0][3], FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255,0,0)); winCoords.x = (squares[0][0].x + squares[0][2].x)/2 - 180; winCoords.y = -((squares[0][0].y + squares[0][2].y)/2 - 120); winCoords.size = fabs(squares[0][0].x - squares[0][2].x); visPub.publish(winCoords); } } } int main(int argc, char** argv) { ros::init(argc, argv, "vision"); ros::NodeHandle nh; visPub = nh.advertise<osuar_vision::windowCoordinates>("window_coordinates", 1); // Instantiate VideoCapture object. See here for details: // http://opencv.willowgarage.com/documentation/cpp/reading_and_writing_images_and_video.html VideoCapture cap(1); // Configure video. Our camera NEEDS the frame width to be set to 720 // pixels. cap.set(CV_CAP_PROP_FRAME_WIDTH, 720); cap.set(CV_CAP_PROP_FRAME_HEIGHT, 480); //cap.set(CV_CAP_PROP_FPS, 20); // Instantiate a Mat in which to store each video frame. Mat origFrame; Mat resizedFrame; // Scaled-down from origFrame by factor of 2. Mat hsvFrame; // Converted to HSV space from resizedFrame. Mat bwFrame; // Black/white image after thresholding hsvFrame. cvNamedWindow("control panel", 1); cvMoveWindow("control panel", 450, 20); cvNamedWindow("origImage", 1); cvMoveWindow("origImage", 20, 20); cvNamedWindow("bwImage", 1); cvMoveWindow("bwImage", 20, 270); cvCreateTrackbar("threshold", "control panel", &thresh, 300, NULL); cvCreateTrackbar("maxCosineThresh (x100)", "control panel", &maxCosineThresh, 100, NULL); cvCreateTrackbar("sideRatioThresh (x100)", "control panel", &sideRatioThresh, 100, NULL); cvCreateTrackbar("maxSquareArea", "control panel", &maxSquareArea, 100000, NULL); cvCreateTrackbar("wallHueLow", "control panel", &wallHueLow, 179, NULL); cvCreateTrackbar("wallHueHigh", "control panel", &wallHueHigh, 179, NULL); cvCreateTrackbar("wallSatLow", "control panel", &wallSatLow, 255, NULL); cvCreateTrackbar("wallSatHigh", "control panel", &wallSatHigh, 255, NULL); cvCreateTrackbar("wallValLow", "control panel", &wallValLow, 255, NULL); cvCreateTrackbar("wallValHigh", "control panel", &wallValHigh, 255, NULL); vector<vector<Point> > squares; while (true) { // Capture image. cap >> origFrame; // Resize the image to increase processing rate. See here for details: // http://opencv.willowgarage.com/documentation/cpp/image_filtering.html pyrDown(origFrame, resizedFrame, Size(origFrame.cols/2, origFrame.rows/2)); // Convert the frame to HSV. TODO: combine this with more filtering and // turn into function. cvtColor(resizedFrame, hsvFrame, CV_BGR2HSV); // Threshold hsvFrame for color of maze walls. inRange(hsvFrame, Scalar(wallHueLow, wallSatLow, wallValLow), Scalar(wallHueHigh, wallSatHigh, wallValHigh), bwFrame); // Find and draw squares. findSquares(bwFrame, squares); drawSquares(resizedFrame, squares); // Show the image, with the squares overlaid. imshow("origImage", resizedFrame); imshow("bwImage", bwFrame); // Wait 5 milliseconds for a keypress. int c = waitKey(5); // Exit if the spacebar is pressed. NOTE: killing the program with // Ctrl+C sometimes stops OpenCV at a bad place and effects a kernel // panic! If you really like Ctrl+C, do so at your own risk! if ((char) c == 32) { return 0; } } return 0; } <commit_msg>Move Mat instantiation to beginning of file.<commit_after>// The "Square Detector" program. // It loads several images sequentially and tries to find squares in // each image #include "opencv2/core/core.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include <iostream> #include <math.h> #include <string.h> #include <stdio.h> #include <ros/ros.h> #include <osuar_vision/windowCoordinates.h> using namespace cv; int thresh = 50, N = 11; // Threshold for maximum cosine between angles (x100). int maxCosineThresh = 20; // Threshold for ratio of shortest side / longest side (x100). int sideRatioThresh = 75; // Maximum square area. int maxSquareArea = 41000; // Find colors of any hue... int wallHueLow = 0; int wallHueHigh = 179; // ...of low saturation... int wallSatLow = 0; int wallSatHigh = 50; // ...ranging down to gray, but not completely dark. That is to say, white. int wallValLow = 90; int wallValHigh = 255; // Hough transform thresholds int minLineLen = 5; int maxLineGap = 10; // Instantiate a Mat in which to store each video frame. Mat origFrame; Mat resizedFrame; // Scaled-down from origFrame by factor of 2. Mat hsvFrame; // Converted to HSV space from resizedFrame. Mat bwFrame; // Black/white image after thresholding hsvFrame. Mat grayFrame; Mat cannyFrame; ros::Publisher visPub; osuar_vision::windowCoordinates winCoords; // helper function: // finds a cosine of angle between vectors // from pt0->pt1 and from pt0->pt2 static double angle( Point pt1, Point pt2, Point pt0 ) { double dx1 = pt1.x - pt0.x; double dy1 = pt1.y - pt0.y; double dx2 = pt2.x - pt0.x; double dy2 = pt2.y - pt0.y; return (dx1*dx2 + dy1*dy2)/sqrt((dx1*dx1 + dy1*dy1)*(dx2*dx2 + dy2*dy2) + 1e-10); } // returns sequence of squares detected on the image. // the sequence is stored in the specified memory storage static void findSquares( const Mat& image, vector<vector<Point> >& squares ) { squares.clear(); Mat pyr, timg; // down-scale and upscale the image to filter out the noise pyrDown(image, pyr, Size(image.cols/2, image.rows/2)); pyrUp(pyr, timg, image.size()); vector<vector<Point> > contours; // find squares in every color plane of the image //for( int c = 0; c < 3; c++ ) //{ //int ch[] = {c, 0}; //mixChannels(&timg, 1, &gray0, 1, ch, 1); // try several threshold levels for( int l = 0; l < N; l++ ) { // hack: use Canny instead of zero threshold level. // Canny helps to catch squares with gradient shading if( l == 0 ) { // apply Canny. Take the upper threshold from slider // and set the lower to 0 (which forces edges merging) Canny(image, gray, 0, thresh, 5); // dilate canny output to remove potential // holes between edge segments dilate(gray, gray, Mat(), Point(-1,-1)); } else { // apply threshold if l!=0: // tgray(x,y) = gray(x,y) < (l+1)*255/N ? 255 : 0 gray = image >= (l+1)*255/N; } // find contours and store them all as a list findContours(gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE); vector<Point> approx; // test each contour for( size_t i = 0; i < contours.size(); i++ ) { // approximate contour with accuracy proportional // to the contour perimeter approxPolyDP(Mat(contours[i]), approx, arcLength(Mat(contours[i]), true)*0.02, true); // square contours should have 4 vertices after approximation // relatively large area (to filter out noisy contours) // and be convex. // Note: absolute value of an area is used because // area may be positive or negative - in accordance with the // contour orientation if( approx.size() == 4 && fabs(contourArea(Mat(approx))) > 1000 && fabs(contourArea(Mat(approx))) < maxSquareArea && isContourConvex(Mat(approx)) ) { double maxCosine = 0; double minSideLen = 100000; double maxSideLen = 0; double sideRatio = 0; for( int j = 2; j < 5; j++ ) { // find the maximum cosine of the angle between joint edges double cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1])); maxCosine = MAX(maxCosine, cosine); // Find the maximum difference in length of adjacent // sides double sideLen = sqrt(pow((approx[j%4].x - approx[(j+1)%4].x), 2) + pow((approx[j%4].y - approx[(j+1)%4].y), 2)); minSideLen = MIN(minSideLen, sideLen); maxSideLen = MAX(maxSideLen, sideLen); } sideRatio = minSideLen / maxSideLen; std::cout << minSideLen << " " << maxSideLen << "\n"; // if cosines of all angles are small // (all angles are ~90 degree) then write quandrange // vertices to resultant sequence if( maxCosine < ((double) maxCosineThresh)/100 && sideRatio >= (double) sideRatioThresh/100 ) squares.push_back(approx); } } } //} } // the function draws all the squares in the image static void drawSquares( Mat& image, const vector<vector<Point> >& squares ) { for( size_t i = 0; i < squares.size(); i++ ) { const Point* p = &squares[i][0]; int n = (int)squares[i].size(); polylines(image, &p, &n, 1, true, Scalar(0,255,0), 3, CV_AA); std::cout << "x: " << squares[i][0].x << " y: " << squares[i][0].y << "\n"; // Only publish coordinates for one of the squares. Coordinates are // shifted over by half the camera resolution (which itself is scaled // down by a factor of two!) on each axis. The y coordinate is inverted // so up is positive. if (i == 0) { putText(image, "0", squares[0][0], FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255,0,0)); putText(image, "1", squares[0][1], FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255,0,0)); putText(image, "2", squares[0][2], FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255,0,0)); putText(image, "3", squares[0][3], FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255,0,0)); winCoords.x = (squares[0][0].x + squares[0][2].x)/2 - 180; winCoords.y = -((squares[0][0].y + squares[0][2].y)/2 - 120); winCoords.size = fabs(squares[0][0].x - squares[0][2].x); visPub.publish(winCoords); } } } int main(int argc, char** argv) { ros::init(argc, argv, "vision"); ros::NodeHandle nh; visPub = nh.advertise<osuar_vision::windowCoordinates>("window_coordinates", 1); // Instantiate VideoCapture object. See here for details: // http://opencv.willowgarage.com/documentation/cpp/reading_and_writing_images_and_video.html VideoCapture cap(1); // Configure video. Our camera NEEDS the frame width to be set to 720 // pixels. cap.set(CV_CAP_PROP_FRAME_WIDTH, 720); cap.set(CV_CAP_PROP_FRAME_HEIGHT, 480); //cap.set(CV_CAP_PROP_FPS, 20); cvNamedWindow("control panel", 1); cvMoveWindow("control panel", 450, 20); cvNamedWindow("origImage", 1); cvMoveWindow("origImage", 20, 20); cvNamedWindow("bwImage", 1); cvMoveWindow("bwImage", 20, 270); cvCreateTrackbar("threshold", "control panel", &thresh, 300, NULL); cvCreateTrackbar("maxCosineThresh (x100)", "control panel", &maxCosineThresh, 100, NULL); cvCreateTrackbar("sideRatioThresh (x100)", "control panel", &sideRatioThresh, 100, NULL); cvCreateTrackbar("maxSquareArea", "control panel", &maxSquareArea, 100000, NULL); cvCreateTrackbar("wallHueLow", "control panel", &wallHueLow, 179, NULL); cvCreateTrackbar("wallHueHigh", "control panel", &wallHueHigh, 179, NULL); cvCreateTrackbar("wallSatLow", "control panel", &wallSatLow, 255, NULL); cvCreateTrackbar("wallSatHigh", "control panel", &wallSatHigh, 255, NULL); cvCreateTrackbar("wallValLow", "control panel", &wallValLow, 255, NULL); cvCreateTrackbar("wallValHigh", "control panel", &wallValHigh, 255, NULL); vector<vector<Point> > squares; while (true) { // Capture image. cap >> origFrame; // Resize the image to increase processing rate. See here for details: // http://opencv.willowgarage.com/documentation/cpp/image_filtering.html pyrDown(origFrame, resizedFrame, Size(origFrame.cols/2, origFrame.rows/2)); // Convert the frame to HSV. TODO: combine this with more filtering and // turn into function. cvtColor(resizedFrame, hsvFrame, CV_BGR2HSV); // Threshold hsvFrame for color of maze walls. inRange(hsvFrame, Scalar(wallHueLow, wallSatLow, wallValLow), Scalar(wallHueHigh, wallSatHigh, wallValHigh), bwFrame); // Find and draw squares. findSquares(bwFrame, squares); drawSquares(resizedFrame, squares); // Show the image, with the squares overlaid. imshow("origImage", resizedFrame); imshow("bwImage", bwFrame); // Wait 5 milliseconds for a keypress. int c = waitKey(5); // Exit if the spacebar is pressed. NOTE: killing the program with // Ctrl+C sometimes stops OpenCV at a bad place and effects a kernel // panic! If you really like Ctrl+C, do so at your own risk! if ((char) c == 32) { return 0; } } return 0; } <|endoftext|>
<commit_before>/* Author: Nicholas Nell email: [email protected] Sampling thread for the NI PCI-DIO-32HS and PCI-6601 that act as NSROC telemtery. */ #include <QDebug> #include <regex.h> #include "nidaqplugin.h" NIDAQPlugin::NIDAQPlugin() : SamplingThreadPlugin() { FILE *fp; char line_buffer[255]; uint32_t line_number = 0; int err = 0; regex_t daq_card_reg; regex_t timer_card_reg; regmatch_t daq_match[2]; regmatch_t timer_match[2]; unsigned int chanlist[COM_N_CHAN]; qDebug() << "NIDAQ Init Starting..."; if (regcomp(&daq_card_reg, DAQ_PATTERN, 0)) { qDebug() << "DAQ regcomp fail"; throw; } if (regcomp(&timer_card_reg, TIMER_PATTERN, 0)) { qDebug() << "DAQ regcomp fail"; throw; } fp = fopen(COM_PROC, "r"); if (fp == NULL) { qDebug() << "Can't open " << COM_PROC; throw; } /* Find comedi device file names... */ while (fgets(line_buffer, sizeof(line_buffer), fp)) { ++line_number; if (!regexec(&daq_card_reg, line_buffer, 2, daq_match, 0)) { daq_dev_file = (char *)malloc(strlen(COM_PREFIX) + 2); sprintf(daq_dev_file, "%s%.*s", COM_PREFIX, daq_match[1].rm_eo - daq_match[1].rm_so, &line_buffer[daq_match[1].rm_so]); qDebug() << "DIO dev file: " << daq_dev_file; } if (!regexec(&timer_card_reg, line_buffer, 2, timer_match, 0)) { timer_dev_file = (char *)malloc(strlen(COM_PREFIX) + 2); sprintf(timer_dev_file, "%s%.*s", COM_PREFIX, timer_match[1].rm_eo - timer_match[1].rm_so, &line_buffer[timer_match[1].rm_so]); qDebug() << "TIMER dev file: " << timer_dev_file; } } regfree(&daq_card_reg); regfree(&timer_card_reg); /* open dio device */ dio_dev = comedi_open(daq_dev_file); if (dio_dev == NULL) { qDebug() << "Error opening dio dev file: " << daq_dev_file; throw; } /* lock the DIO device (dubdev 0) */ err = comedi_lock(dio_dev, 0); if (err < 0) { qDebug() << "Error locking comedi device, subdevice: " << daq_dev_file << 0; throw; } timer_dev = comedi_open(timer_dev_file); if (timer_dev == NULL) { qDebug() << "Error opening timer dev file: " << timer_dev_file; throw; } /* lock the timer device (dubdev 2) */ err = comedi_lock(timer_dev, 2); if (err < 0) { qDebug() << "Error locking comedi device, subdevice: " << timer_dev_file << 2; throw; } /* Don't start pulse train until we acquire */ if (ni_gpct_stop_pulse_gen(timer_dev, 2) != 0) { qDebug() << "Unable to stop pulse train..."; throw; } /* Set device file params */ fcntl(comedi_fileno(dio_dev), F_SETFL, O_NONBLOCK); memset(&cmd, 0, sizeof(cmd)); /* This command is legit for the PCI-DIO-32HS */ cmd.subdev = 0; cmd.flags = 0; cmd.start_src = TRIG_NOW; cmd.start_arg = 0; cmd.scan_begin_src = TRIG_EXT; cmd.scan_begin_arg = CR_INVERT; /* Read on the trailing edge */ cmd.convert_src = TRIG_NOW; cmd.convert_arg = 0; cmd.scan_end_src = TRIG_COUNT; cmd.scan_end_arg = COM_N_CHAN; cmd.stop_src = TRIG_NONE; cmd.stop_arg = 0; cmd.chanlist = chanlist; cmd.chanlist_len = COM_N_CHAN; /* Prep all channels */ for (int i = 0; i < COM_N_CHAN; i++) { /* Note range is 0 (we are digital!) */ chanlist[i] = CR_PACK(0, 0, AREF_GROUND); } /* Test the command */ err = comedi_command_test(dio_dev, &cmd); if (err != 0) { qDebug() << "comedi command failed test."; qDebug() << "comedi_command_test result: " << err; int blah = comedi_get_version_code(dio_dev); qDebug() << "COMEDI VER: " << (0x0000ff & (blah >> 16)) << "." << (0x0000ff & (blah >> 8)) << "." << (0x0000ff & blah); throw; } err = comedi_dio_config(timer_dev, 1, 36, COMEDI_OUTPUT); if (err != 0) { qDebug() << "Failed to set timer to output. Error #: " << err; throw; } abort = false; pauseSampling = false; _pc = new MDDASPlotConfig(); _pc->setXMax(8192); _pc->setXMin(0); _pc->setYMax(8192); _pc->setYMin(0); _pc->setPMax(256); _pc->setPMin(0); if (fclose(fp)) { qDebug() << "Error closing " << COM_PROC; throw; } qDebug() << "NIDAQ Init complete..."; } /* close thread */ NIDAQPlugin::~NIDAQPlugin() { ni_gpct_stop_pulse_gen(timer_dev, 2); /* stop command */ comedi_cancel(dio_dev, 0); comedi_close(dio_dev); comedi_close(timer_dev); free(daq_dev_file); free(timer_dev_file); } void NIDAQPlugin::run() { int i = 0; int j = 0; int num_photons = 0; QMutex sleepM; QVector<MDDASDataPoint> v; sleepM.lock(); forever { mutex.lock(); if (pauseSampling) { condition.wait(&mutex); } mutex.unlock(); if (abort) { qDebug() << "called abort!" << QThread::currentThread(); return; } //qDebug() << "nidaq!"; condition.wait(&sleepM, 1); //qDebug() << "blip" << QThread::currentThread(); //sleep(); /* Use a wait condition instead of sleep() so that the thread can be awoken. */ //condition.wait(&sleepM, 100); } } int NIDAQPlugin::ni_gpct_start_pulse_gen(comedi_t *device, unsigned subdevice, unsigned period_ns, unsigned up_time_ns) { int retval; lsampl_t counter_mode; const unsigned clock_period_ns = 50; /* 20MHz clock */ unsigned up_ticks, down_ticks; retval = comedi_reset(device, subdevice); if (retval < 0) return retval; retval = comedi_set_gate_source(device, subdevice, 0, 0, NI_GPCT_DISABLED_GATE_SELECT | CR_EDGE); if (retval < 0) return retval; retval = comedi_set_gate_source(device, subdevice, 0, 1, NI_GPCT_DISABLED_GATE_SELECT | CR_EDGE); if (retval < 0) { //fprintf(stderr, "Failed to set second gate source. This is expected for older boards (e-series, etc.)\n" // "that don't have a second gate.\n"); qDebug() << "Failed to set second gate source. This is expected for older boards (e-series, etc.)"; qDebug() << "that don't have a second gate."; } counter_mode = NI_GPCT_COUNTING_MODE_NORMAL_BITS; /* toggle output on terminal count */ counter_mode |= NI_GPCT_OUTPUT_TC_TOGGLE_BITS; /* load on terminal count */ counter_mode |= NI_GPCT_LOADING_ON_TC_BIT; /* alternate the reload source between the load a and load b registers */ counter_mode |= NI_GPCT_RELOAD_SOURCE_SWITCHING_BITS; /* count down */ counter_mode |= NI_GPCT_COUNTING_DIRECTION_DOWN_BITS; /* initialize load source as load b register */ counter_mode |= NI_GPCT_LOAD_B_SELECT_BIT; /* don't stop on terminal count */ counter_mode |= NI_GPCT_STOP_ON_GATE_BITS; /* don't disarm on terminal count or gate signal */ counter_mode |= NI_GPCT_NO_HARDWARE_DISARM_BITS; retval = comedi_set_counter_mode(device, subdevice, 0, counter_mode); if (retval < 0) return retval; /* 20MHz clock */ retval = comedi_set_clock_source(device, subdevice, 0, NI_GPCT_TIMEBASE_1_CLOCK_SRC_BITS, clock_period_ns); if (retval < 0) return retval; up_ticks = (up_time_ns + clock_period_ns / 2) / clock_period_ns; down_ticks = (period_ns + clock_period_ns / 2) / clock_period_ns - up_ticks; /* set initial counter value by writing to channel 0 */ retval = comedi_data_write(device, subdevice, 0, 0, 0, down_ticks); if (retval < 0) return retval; /* set "load a" register to the number of clock ticks the counter output should remain low by writing to channel 1. */ comedi_data_write(device, subdevice, 1, 0, 0, down_ticks); if (retval < 0) return retval; /* set "load b" register to the number of clock ticks the counter output should remain high by writing to channel 2 */ comedi_data_write(device, subdevice, 2, 0, 0, up_ticks); if(retval < 0) return retval; retval = comedi_arm(device, subdevice, NI_GPCT_ARM_IMMEDIATE); if (retval < 0) return retval; return 0; } int NIDAQPlugin::ni_gpct_stop_pulse_gen(comedi_t *device, unsigned subdevice) { comedi_insn insn; lsampl_t data; memset(&insn, 0, sizeof(comedi_insn)); insn.insn = INSN_CONFIG; insn.subdev = subdevice; insn.chanspec = 0; insn.data = &data; insn.n = 1; data = INSN_CONFIG_DISARM; if (comedi_do_insn(device, &insn) >= 0) { return 0; } else { return -1; } } Q_EXPORT_PLUGIN2(nidaqplugin, NIDAQPlugin); <commit_msg>Very basic niplugin acquisition with timer start/pause<commit_after>/* Author: Nicholas Nell email: [email protected] Sampling thread for the NI PCI-DIO-32HS and PCI-6601 that act as NSROC telemtery. */ #include <QDebug> #include <regex.h> #include <unistd.h> #include "nidaqplugin.h" NIDAQPlugin::NIDAQPlugin() : SamplingThreadPlugin() { FILE *fp; char line_buffer[255]; uint32_t line_number = 0; int err = 0; regex_t daq_card_reg; regex_t timer_card_reg; regmatch_t daq_match[2]; regmatch_t timer_match[2]; unsigned int chanlist[COM_N_CHAN]; qDebug() << "NIDAQ Init Starting..."; if (regcomp(&daq_card_reg, DAQ_PATTERN, 0)) { qDebug() << "DAQ regcomp fail"; throw; } if (regcomp(&timer_card_reg, TIMER_PATTERN, 0)) { qDebug() << "DAQ regcomp fail"; throw; } fp = fopen(COM_PROC, "r"); if (fp == NULL) { qDebug() << "Can't open " << COM_PROC; throw; } /* Find comedi device file names... */ while (fgets(line_buffer, sizeof(line_buffer), fp)) { ++line_number; if (!regexec(&daq_card_reg, line_buffer, 2, daq_match, 0)) { daq_dev_file = (char *)malloc(strlen(COM_PREFIX) + 2); sprintf(daq_dev_file, "%s%.*s", COM_PREFIX, daq_match[1].rm_eo - daq_match[1].rm_so, &line_buffer[daq_match[1].rm_so]); qDebug() << "DIO dev file: " << daq_dev_file; } if (!regexec(&timer_card_reg, line_buffer, 2, timer_match, 0)) { timer_dev_file = (char *)malloc(strlen(COM_PREFIX) + 2); sprintf(timer_dev_file, "%s%.*s", COM_PREFIX, timer_match[1].rm_eo - timer_match[1].rm_so, &line_buffer[timer_match[1].rm_so]); qDebug() << "TIMER dev file: " << timer_dev_file; } } regfree(&daq_card_reg); regfree(&timer_card_reg); /* open dio device */ dio_dev = comedi_open(daq_dev_file); if (dio_dev == NULL) { qDebug() << "Error opening dio dev file: " << daq_dev_file; throw; } /* lock the DIO device (dubdev 0) */ err = comedi_lock(dio_dev, 0); if (err < 0) { qDebug() << "Error locking comedi device, subdevice: " << daq_dev_file << 0; throw; } timer_dev = comedi_open(timer_dev_file); if (timer_dev == NULL) { qDebug() << "Error opening timer dev file: " << timer_dev_file; throw; } /* lock the timer device (dubdev 2) */ err = comedi_lock(timer_dev, 2); if (err < 0) { qDebug() << "Error locking comedi device, subdevice: " << timer_dev_file << 2; throw; } /* Don't start pulse train until we acquire */ if (ni_gpct_stop_pulse_gen(timer_dev, 2) != 0) { qDebug() << "Unable to stop pulse train..."; throw; } /* Set device file params */ fcntl(comedi_fileno(dio_dev), F_SETFL, O_NONBLOCK); memset(&cmd, 0, sizeof(cmd)); /* This command is legit for the PCI-DIO-32HS */ cmd.subdev = 0; cmd.flags = 0; cmd.start_src = TRIG_NOW; cmd.start_arg = 0; cmd.scan_begin_src = TRIG_EXT; cmd.scan_begin_arg = CR_INVERT; /* Read on the trailing edge */ cmd.convert_src = TRIG_NOW; cmd.convert_arg = 0; cmd.scan_end_src = TRIG_COUNT; cmd.scan_end_arg = COM_N_CHAN; cmd.stop_src = TRIG_NONE; cmd.stop_arg = 0; cmd.chanlist = chanlist; cmd.chanlist_len = COM_N_CHAN; /* Prep all channels */ for (int i = 0; i < COM_N_CHAN; i++) { /* Note range is 0 (we are digital!) */ chanlist[i] = CR_PACK(0, 0, AREF_GROUND); } /* Test the command */ err = comedi_command_test(dio_dev, &cmd); if (err != 0) { qDebug() << "comedi command failed test."; qDebug() << "comedi_command_test result: " << err; int blah = comedi_get_version_code(dio_dev); qDebug() << "COMEDI VER: " << (0x0000ff & (blah >> 16)) << "." << (0x0000ff & (blah >> 8)) << "." << (0x0000ff & blah); throw; } err = comedi_dio_config(timer_dev, 1, 36, COMEDI_OUTPUT); if (err != 0) { qDebug() << "Failed to set timer to output. Error #: " << err; throw; } err = comedi_command(dio_dev, &cmd); if (err < 0) { qDebug() << "Failed to start command!"; } abort = false; pauseSampling = false; _pc = new MDDASPlotConfig(); _pc->setXMax(8192); _pc->setXMin(0); _pc->setYMax(8192); _pc->setYMin(0); _pc->setPMax(256); _pc->setPMin(0); if (fclose(fp)) { qDebug() << "Error closing " << COM_PROC; throw; } qDebug() << "NIDAQ Init complete..."; } /* close thread */ NIDAQPlugin::~NIDAQPlugin() { ni_gpct_stop_pulse_gen(timer_dev, 2); /* stop command */ comedi_cancel(dio_dev, 0); comedi_close(dio_dev); comedi_close(timer_dev); free(daq_dev_file); free(timer_dev_file); } void NIDAQPlugin::run() { int i = 0; int j = 0; int num_photons = 0; int ret = 0; fd_set rdset; struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 50000; QMutex sleepM; QVector<MDDASDataPoint> v; sleepM.lock(); forever { mutex.lock(); if (pauseSampling) { qDebug() << "pause"; if (ni_gpct_stop_pulse_gen(timer_dev, 2) != 0) { qDebug() << "failed to pause!"; } condition.wait(&mutex); qDebug() << "unpause"; ni_gpct_start_pulse_gen(timer_dev, 2, STROBE_PERIOD, STROBE_HIGH_T); } mutex.unlock(); if (abort) { qDebug() << "called abort!" << QThread::currentThread(); return; } //qDebug() << "nidaq!"; FD_ZERO(&rdset); FD_SET(comedi_fileno(dio_dev), &rdset); ret = select(comedi_fileno(dio_dev) + 1, &rdset, NULL, NULL, &timeout); if (ret < 0) { qDebug() << "select() error!"; } else if (ret == 0) { /* hit timeout, poll card */ ret = comedi_poll(dio_dev, 0); if (ret < 0) { qDebug() << "comedi_poll() error"; } } else if (FD_ISSET(comedi_fileno(dio_dev), &rdset)) { /* comedi file descriptor became ready */ ret = read(comedi_fileno(dio_dev), buf, sizeof(buf)); if (ret < 0) { qDebug() << "read() error!"; } else if (ret == 0) { /* no data */ //qDebug() << "no data..."; } else { qDebug() << "Got " << ret << " samples"; } } condition.wait(&sleepM, 1); //qDebug() << "blip" << QThread::currentThread(); //sleep(); /* Use a wait condition instead of sleep() so that the thread can be awoken. */ //condition.wait(&sleepM, 100); } } int NIDAQPlugin::ni_gpct_start_pulse_gen(comedi_t *device, unsigned subdevice, unsigned period_ns, unsigned up_time_ns) { int retval; lsampl_t counter_mode; const unsigned clock_period_ns = 50; /* 20MHz clock */ unsigned up_ticks, down_ticks; retval = comedi_reset(device, subdevice); if (retval < 0) return retval; retval = comedi_set_gate_source(device, subdevice, 0, 0, NI_GPCT_DISABLED_GATE_SELECT | CR_EDGE); if (retval < 0) return retval; retval = comedi_set_gate_source(device, subdevice, 0, 1, NI_GPCT_DISABLED_GATE_SELECT | CR_EDGE); if (retval < 0) { //fprintf(stderr, "Failed to set second gate source. This is expected for older boards (e-series, etc.)\n" // "that don't have a second gate.\n"); qDebug() << "Failed to set second gate source. This is expected for older boards (e-series, etc.)"; qDebug() << "that don't have a second gate."; } counter_mode = NI_GPCT_COUNTING_MODE_NORMAL_BITS; /* toggle output on terminal count */ counter_mode |= NI_GPCT_OUTPUT_TC_TOGGLE_BITS; /* load on terminal count */ counter_mode |= NI_GPCT_LOADING_ON_TC_BIT; /* alternate the reload source between the load a and load b registers */ counter_mode |= NI_GPCT_RELOAD_SOURCE_SWITCHING_BITS; /* count down */ counter_mode |= NI_GPCT_COUNTING_DIRECTION_DOWN_BITS; /* initialize load source as load b register */ counter_mode |= NI_GPCT_LOAD_B_SELECT_BIT; /* don't stop on terminal count */ counter_mode |= NI_GPCT_STOP_ON_GATE_BITS; /* don't disarm on terminal count or gate signal */ counter_mode |= NI_GPCT_NO_HARDWARE_DISARM_BITS; retval = comedi_set_counter_mode(device, subdevice, 0, counter_mode); if (retval < 0) return retval; /* 20MHz clock */ retval = comedi_set_clock_source(device, subdevice, 0, NI_GPCT_TIMEBASE_1_CLOCK_SRC_BITS, clock_period_ns); if (retval < 0) return retval; up_ticks = (up_time_ns + clock_period_ns / 2) / clock_period_ns; down_ticks = (period_ns + clock_period_ns / 2) / clock_period_ns - up_ticks; /* set initial counter value by writing to channel 0 */ retval = comedi_data_write(device, subdevice, 0, 0, 0, down_ticks); if (retval < 0) return retval; /* set "load a" register to the number of clock ticks the counter output should remain low by writing to channel 1. */ comedi_data_write(device, subdevice, 1, 0, 0, down_ticks); if (retval < 0) return retval; /* set "load b" register to the number of clock ticks the counter output should remain high by writing to channel 2 */ comedi_data_write(device, subdevice, 2, 0, 0, up_ticks); if(retval < 0) return retval; retval = comedi_arm(device, subdevice, NI_GPCT_ARM_IMMEDIATE); if (retval < 0) return retval; return 0; } int NIDAQPlugin::ni_gpct_stop_pulse_gen(comedi_t *device, unsigned subdevice) { comedi_insn insn; lsampl_t data; memset(&insn, 0, sizeof(comedi_insn)); insn.insn = INSN_CONFIG; insn.subdev = subdevice; insn.chanspec = 0; insn.data = &data; insn.n = 1; data = INSN_CONFIG_DISARM; if (comedi_do_insn(device, &insn) >= 0) { return 0; } else { return -1; } } Q_EXPORT_PLUGIN2(nidaqplugin, NIDAQPlugin); <|endoftext|>
<commit_before>#include <gst/gst.h> #include "MediaPipelineImpl.hpp" #include "MediaObjectImpl.hpp" #include <jsonrpc/JsonSerializer.hpp> #include <KurentoException.hpp> #include <gst/gst.h> #include <UUIDGenerator.hpp> #include <MediaSet.hpp> #define GST_CAT_DEFAULT kurento_media_object_impl GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define GST_DEFAULT_NAME "KurentoMediaObjectImpl" namespace kurento { MediaObjectImpl::MediaObjectImpl (const boost::property_tree::ptree &config) { creationTime = time (NULL); initialId = createId(); this->config = config; this->sendTagsInEvents = false; } MediaObjectImpl::MediaObjectImpl (const boost::property_tree::ptree &config, std::shared_ptr< MediaObject > parent) : MediaObjectImpl (config) { this->parent = parent; } std::shared_ptr<MediaPipeline> MediaObjectImpl::getMediaPipeline () { if (parent) { return std::dynamic_pointer_cast<MediaObjectImpl> (parent)->getMediaPipeline(); } else { return std::dynamic_pointer_cast<MediaPipeline> (shared_from_this() ); } } std::string MediaObjectImpl::createId() { std::string uuid = generateUUID(); if (parent) { std::shared_ptr<MediaPipelineImpl> pipeline; pipeline = std::dynamic_pointer_cast<MediaPipelineImpl> (getMediaPipeline() ); return pipeline->getId() + "/" + uuid; } else { return uuid; } } std::string MediaObjectImpl::getName() { std::unique_lock<std::recursive_mutex> lck (mutex); if (name.empty () ) { name = getId (); } return name; } std::string MediaObjectImpl::getId() { std::unique_lock<std::recursive_mutex> lck (mutex); if (id.empty () ) { id = this->initialId + "_" + this->getType (); } return id; } void MediaObjectImpl::setName (const std::string &name) { std::unique_lock<std::recursive_mutex> lck (mutex); this->name = name; } std::vector<std::shared_ptr<MediaObject>> MediaObjectImpl::getChilds () { std::vector<std::shared_ptr<MediaObject>> childs; for (auto it : MediaSet::getMediaSet ()->getChilds (std::dynamic_pointer_cast <MediaObjectImpl> (shared_from_this() ) ) ) { childs.push_back (it); } return childs; } bool MediaObjectImpl::getSendTagsInEvents () { return this->sendTagsInEvents; } void MediaObjectImpl::setSendTagsInEvents (bool sendTagsInEvents) { this->sendTagsInEvents = sendTagsInEvents; } void MediaObjectImpl::addTag (const std::string &key, const std::string &value) { tagsMap [key] = value; GST_DEBUG ("Tag added"); } void MediaObjectImpl::removeTag (const std::string &key) { auto it = tagsMap.find (key); if (it != tagsMap.end() ) { tagsMap.erase (it); GST_DEBUG ("Tag deleted"); return; } GST_DEBUG ("Tag not found"); } std::string MediaObjectImpl::getTag (const std::string &key) { auto it = tagsMap.find (key); if (it != tagsMap.end() ) { return it->second; } throw KurentoException (MEDIA_OBJECT_TAG_KEY_NOT_FOUND, "Tag key not found"); } void MediaObjectImpl::postConstructor() { } std::vector<std::shared_ptr<Tag>> MediaObjectImpl::getTags () { std::vector<std::shared_ptr<Tag>> ret; for (auto it : tagsMap ) { std::shared_ptr <Tag> tag (new Tag (it.first, it.second) ); ret.push_back (tag); } return ret; } int MediaObjectImpl::getCreationTime () { return (int) creationTime; } MediaObjectImpl::StaticConstructor MediaObjectImpl::staticConstructor; MediaObjectImpl::StaticConstructor::StaticConstructor() { GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); } } /* kurento */ <commit_msg>MediaObjectImpl: Fix bug, mediaobjects id didn't containg its parent id<commit_after>#include <gst/gst.h> #include "MediaPipelineImpl.hpp" #include "MediaObjectImpl.hpp" #include <jsonrpc/JsonSerializer.hpp> #include <KurentoException.hpp> #include <gst/gst.h> #include <UUIDGenerator.hpp> #include <MediaSet.hpp> #define GST_CAT_DEFAULT kurento_media_object_impl GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); #define GST_DEFAULT_NAME "KurentoMediaObjectImpl" namespace kurento { MediaObjectImpl::MediaObjectImpl (const boost::property_tree::ptree &config) : MediaObjectImpl (config, std::shared_ptr<MediaObject> () ) { } MediaObjectImpl::MediaObjectImpl (const boost::property_tree::ptree &config, std::shared_ptr< MediaObject > parent) { this->parent = parent; creationTime = time (NULL); initialId = createId(); this->config = config; this->sendTagsInEvents = false; } std::shared_ptr<MediaPipeline> MediaObjectImpl::getMediaPipeline () { if (parent) { return std::dynamic_pointer_cast<MediaObjectImpl> (parent)->getMediaPipeline(); } else { return std::dynamic_pointer_cast<MediaPipeline> (shared_from_this() ); } } std::string MediaObjectImpl::createId() { std::string uuid = generateUUID(); if (parent) { std::shared_ptr<MediaPipelineImpl> pipeline; pipeline = std::dynamic_pointer_cast<MediaPipelineImpl> (getMediaPipeline() ); return pipeline->getId() + "/" + uuid; } else { return uuid; } } std::string MediaObjectImpl::getName() { std::unique_lock<std::recursive_mutex> lck (mutex); if (name.empty () ) { name = getId (); } return name; } std::string MediaObjectImpl::getId() { std::unique_lock<std::recursive_mutex> lck (mutex); if (id.empty () ) { id = this->initialId + "_" + this->getType (); } return id; } void MediaObjectImpl::setName (const std::string &name) { std::unique_lock<std::recursive_mutex> lck (mutex); this->name = name; } std::vector<std::shared_ptr<MediaObject>> MediaObjectImpl::getChilds () { std::vector<std::shared_ptr<MediaObject>> childs; for (auto it : MediaSet::getMediaSet ()->getChilds (std::dynamic_pointer_cast <MediaObjectImpl> (shared_from_this() ) ) ) { childs.push_back (it); } return childs; } bool MediaObjectImpl::getSendTagsInEvents () { return this->sendTagsInEvents; } void MediaObjectImpl::setSendTagsInEvents (bool sendTagsInEvents) { this->sendTagsInEvents = sendTagsInEvents; } void MediaObjectImpl::addTag (const std::string &key, const std::string &value) { tagsMap [key] = value; GST_DEBUG ("Tag added"); } void MediaObjectImpl::removeTag (const std::string &key) { auto it = tagsMap.find (key); if (it != tagsMap.end() ) { tagsMap.erase (it); GST_DEBUG ("Tag deleted"); return; } GST_DEBUG ("Tag not found"); } std::string MediaObjectImpl::getTag (const std::string &key) { auto it = tagsMap.find (key); if (it != tagsMap.end() ) { return it->second; } throw KurentoException (MEDIA_OBJECT_TAG_KEY_NOT_FOUND, "Tag key not found"); } void MediaObjectImpl::postConstructor() { } std::vector<std::shared_ptr<Tag>> MediaObjectImpl::getTags () { std::vector<std::shared_ptr<Tag>> ret; for (auto it : tagsMap ) { std::shared_ptr <Tag> tag (new Tag (it.first, it.second) ); ret.push_back (tag); } return ret; } int MediaObjectImpl::getCreationTime () { return (int) creationTime; } MediaObjectImpl::StaticConstructor MediaObjectImpl::staticConstructor; MediaObjectImpl::StaticConstructor::StaticConstructor() { GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0, GST_DEFAULT_NAME); } } /* kurento */ <|endoftext|>
<commit_before><commit_msg>iahndl: do lazy replacement<commit_after><|endoftext|>
<commit_before>#include <config.h> #ifdef SYSTEM_UNIX #include <sys/prctl.h> #include <sys/wait.h> #endif #include <boost/lexical_cast.hpp> #include "typename.h" #include "Logger.h" #include "demangle.h" #include "exceptions.h" logger::LogChannel tracelog("tracelog", "[trace] "); stack_trace_::stack_trace_() { #ifdef SYSTEM_UNIX std::string programName = get_program_name(); std::string pid = get_pid(); _stack_trace.push_back(std::string("\t[trace] back trace for ") + programName + " (" + pid + "):"); // create a pipe to read gdb's output int pipefds[2]; int res = pipe(pipefds); if (res < 0) return; // create a pipe to be used as a barrier int barrierfds[2]; res = pipe(barrierfds); if (res < 0) return; // fork int childPid = fork(); // child: if (!childPid) { LOG_ALL(tracelog) << "[child] waiting for parent process to allow attaching" << std::endl; // close writing end of barrier pipe close(barrierfds[1]); // wait until parent closes barrier pipe char buf[1]; while (read(barrierfds[0], buf, sizeof(buf)) > 0) LOG_ALL(tracelog) << "[child] " << buf[0] << std::endl; LOG_ALL(tracelog) << "[child] parent process closed barrier pipe, preparing gdb invocation" << std::endl; // close barrier pipe close(barrierfds[0]); // close reading end of output pipe close(pipefds[0]); // redirect stdout and stderr to output pipe dup2(pipefds[1], 1); dup2(pipefds[1], 2); // close writing end of pipe (_we_ don't need it any longer) close(pipefds[1]); // start gdb execlp("gdb", "gdb", "--batch", "-n", "-ex", "bt full", programName.c_str(), pid.c_str(), NULL); // parent: } else { LOG_ALL(tracelog) << "[parent] allowing child to attach" << std::endl; // allow our child process to attach prctl(PR_SET_PTRACER, childPid, 0, 0, 0); LOG_ALL(tracelog) << "[parent] closing barrier pipe" << std::endl; // close barrier pipe to let child proceed close(barrierfds[0]); close(barrierfds[1]); LOG_ALL(tracelog) << "[parent] barrier pipe closed" << std::endl; // close the write end of pipe close(pipefds[1]); // capture child's output std::string output; // read the whole output of gdb char buf[1]; size_t n; while ((n = read(pipefds[0], buf, sizeof(buf)))) output += std::string(buf, n); LOG_ALL(tracelog) << "[parent] end of pipe; I read: " << std::endl << output << std::endl; // split it at newline characters std::stringstream oss(output); std::string line; // ignore every line until '#0 ...' while (std::getline(oss, line) && (line.size() < 2 || (line[0] != '#' && line[1] != '0'))); // copy remaining lines to stack trace do { if (line.size() > 0 && line[0] != '\n') _stack_trace.push_back(std::string("\t[trace] ") + line); } while (std::getline(oss, line)); // wait for the child to finish waitpid(childPid, NULL, 0); } #endif // SYSTEM_UNIX return; } const std::vector<std::string>& stack_trace_::get_stack_trace() const { return _stack_trace; } const std::string& stack_trace_::get_program_name() { if (_program_name == "") initialise_program_name(); return _program_name; } std::string stack_trace_::get_pid() { #ifdef SYSTEM_UNIX return boost::lexical_cast<std::string>(getpid()); #else return "unknown"; #endif } void stack_trace_::initialise_program_name() { #ifdef SYSTEM_UNIX char link[1024]; char name[1024]; snprintf(link, sizeof link, "/proc/%d/exe", getpid()); int size = readlink(link, name, sizeof link); if (size == -1) { _program_name = "[program name not found]"; return; } for (int i = 0; i < size; i++) _program_name += name[i]; #endif } void handleException(const boost::exception& e, std::ostream& out) { out << std::endl; out << "caught exception" << std::endl << std::endl; if (boost::get_error_info<stack_trace>(e)) { out << "###############" << std::endl; out << "# STACK TRACE #" << std::endl; out << "###############" << std::endl; out << std::endl << std::endl; out << *boost::get_error_info<stack_trace>(e); out << std::endl << std::endl; } out << "#####################" << std::endl; out << "# EXCEPTION SUMMARY #" << std::endl; out << "#####################" << std::endl; out << std::endl << std::endl; out << "exception type:" << std::endl << std::endl << "\t" << typeName(e) << std::endl << std::endl; if (boost::get_error_info<boost::throw_function>(e)) { out << "throw location:" << std::endl << std::endl; out << "\t" << *boost::get_error_info<boost::throw_function>(e) << std::endl; if (boost::get_error_info<boost::throw_file>(e)) { out << "\tin " << *boost::get_error_info<boost::throw_file>(e); if (boost::get_error_info<boost::throw_line>(e)) out << "(" << *boost::get_error_info<boost::throw_line>(e) << ")"; } out << std::endl; } if (boost::get_error_info<error_message>(e)) { out << std::endl << "error message:" << std::endl << std::endl;; out << "\t" << *boost::get_error_info<error_message>(e); out << std::endl << std::endl; } } std::ostream& operator<<(std::ostream& out, const stack_trace_& trace) { for (unsigned int i = 0; i < trace.get_stack_trace().size(); i++) out << trace.get_stack_trace()[i] << std::endl; return out; } <commit_msg>Compile fix for MAC<commit_after>#include <config.h> #if defined(SYSTEM_UNIX) && !defined(SYSTEM_MAC) #include <sys/prctl.h> #include <sys/wait.h> #endif #include <boost/lexical_cast.hpp> #include "typename.h" #include "Logger.h" #include "demangle.h" #include "exceptions.h" logger::LogChannel tracelog("tracelog", "[trace] "); stack_trace_::stack_trace_() { #if defined(SYSTEM_UNIX) && !defined(SYSTEM_MAC) std::string programName = get_program_name(); std::string pid = get_pid(); _stack_trace.push_back(std::string("\t[trace] back trace for ") + programName + " (" + pid + "):"); // create a pipe to read gdb's output int pipefds[2]; int res = pipe(pipefds); if (res < 0) return; // create a pipe to be used as a barrier int barrierfds[2]; res = pipe(barrierfds); if (res < 0) return; // fork int childPid = fork(); // child: if (!childPid) { LOG_ALL(tracelog) << "[child] waiting for parent process to allow attaching" << std::endl; // close writing end of barrier pipe close(barrierfds[1]); // wait until parent closes barrier pipe char buf[1]; while (read(barrierfds[0], buf, sizeof(buf)) > 0) LOG_ALL(tracelog) << "[child] " << buf[0] << std::endl; LOG_ALL(tracelog) << "[child] parent process closed barrier pipe, preparing gdb invocation" << std::endl; // close barrier pipe close(barrierfds[0]); // close reading end of output pipe close(pipefds[0]); // redirect stdout and stderr to output pipe dup2(pipefds[1], 1); dup2(pipefds[1], 2); // close writing end of pipe (_we_ don't need it any longer) close(pipefds[1]); // start gdb execlp("gdb", "gdb", "--batch", "-n", "-ex", "bt full", programName.c_str(), pid.c_str(), NULL); // parent: } else { LOG_ALL(tracelog) << "[parent] allowing child to attach" << std::endl; // allow our child process to attach prctl(PR_SET_PTRACER, childPid, 0, 0, 0); LOG_ALL(tracelog) << "[parent] closing barrier pipe" << std::endl; // close barrier pipe to let child proceed close(barrierfds[0]); close(barrierfds[1]); LOG_ALL(tracelog) << "[parent] barrier pipe closed" << std::endl; // close the write end of pipe close(pipefds[1]); // capture child's output std::string output; // read the whole output of gdb char buf[1]; size_t n; while ((n = read(pipefds[0], buf, sizeof(buf)))) output += std::string(buf, n); LOG_ALL(tracelog) << "[parent] end of pipe; I read: " << std::endl << output << std::endl; // split it at newline characters std::stringstream oss(output); std::string line; // ignore every line until '#0 ...' while (std::getline(oss, line) && (line.size() < 2 || (line[0] != '#' && line[1] != '0'))); // copy remaining lines to stack trace do { if (line.size() > 0 && line[0] != '\n') _stack_trace.push_back(std::string("\t[trace] ") + line); } while (std::getline(oss, line)); // wait for the child to finish waitpid(childPid, NULL, 0); } #endif // SYSTEM_UNIX && !SYSTEM_MAC return; } const std::vector<std::string>& stack_trace_::get_stack_trace() const { return _stack_trace; } const std::string& stack_trace_::get_program_name() { if (_program_name == "") initialise_program_name(); return _program_name; } std::string stack_trace_::get_pid() { #if defined(SYSTEM_UNIX) && !defined(SYSTEM_MAC) return boost::lexical_cast<std::string>(getpid()); #else return "unknown"; #endif } void stack_trace_::initialise_program_name() { #if defined(SYSTEM_UNIX) && !defined(SYSTEM_MAC) char link[1024]; char name[1024]; snprintf(link, sizeof link, "/proc/%d/exe", getpid()); int size = readlink(link, name, sizeof link); if (size == -1) { _program_name = "[program name not found]"; return; } for (int i = 0; i < size; i++) _program_name += name[i]; #endif } void handleException(const boost::exception& e, std::ostream& out) { out << std::endl; out << "caught exception" << std::endl << std::endl; if (boost::get_error_info<stack_trace>(e)) { out << "###############" << std::endl; out << "# STACK TRACE #" << std::endl; out << "###############" << std::endl; out << std::endl << std::endl; out << *boost::get_error_info<stack_trace>(e); out << std::endl << std::endl; } out << "#####################" << std::endl; out << "# EXCEPTION SUMMARY #" << std::endl; out << "#####################" << std::endl; out << std::endl << std::endl; out << "exception type:" << std::endl << std::endl << "\t" << typeName(e) << std::endl << std::endl; if (boost::get_error_info<boost::throw_function>(e)) { out << "throw location:" << std::endl << std::endl; out << "\t" << *boost::get_error_info<boost::throw_function>(e) << std::endl; if (boost::get_error_info<boost::throw_file>(e)) { out << "\tin " << *boost::get_error_info<boost::throw_file>(e); if (boost::get_error_info<boost::throw_line>(e)) out << "(" << *boost::get_error_info<boost::throw_line>(e) << ")"; } out << std::endl; } if (boost::get_error_info<error_message>(e)) { out << std::endl << "error message:" << std::endl << std::endl;; out << "\t" << *boost::get_error_info<error_message>(e); out << std::endl << std::endl; } } std::ostream& operator<<(std::ostream& out, const stack_trace_& trace) { for (unsigned int i = 0; i < trace.get_stack_trace().size(); i++) out << trace.get_stack_trace()[i] << std::endl; return out; } <|endoftext|>
<commit_before>//DEFINITION OF A FEW CONSTANTS AliPWG4HighPtQAMC* AddTaskPWG4HighPtQAMC() { // Creates HighPtQAMC analysis task and adds it to the analysis manager. // A. Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTaskPWG4HighPtQMC", "No analysis manager to connect to."); return NULL; } // B. Check the analysis type using the event handlers connected to the analysis // manager. The availability of MC handler can also be checked here. //============================================================================== if (!mgr->GetInputEventHandler()) { ::Error("AddPWG4TaskHighPtQAMC", "This task requires an input event handler"); return NULL; } TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD" const char *analysisType = "ESD";//"TPC" // C. Create the task, add it to manager. //=========================================================================== //CREATE THE CUTS ----------------------------------------------- //Use AliESDtrackCuts AliESDtrackCuts *trackCuts = new AliESDtrackCuts("AliESDtrackCuts","Standard Cuts"); //Standard Cuts trackCuts=trackCuts->GetStandardITSTPCTrackCuts2009(kTRUE);//Primary Track Selection trackCuts->SetEtaRange(-0.9,0.9); trackCuts->SetPtRange(0.15, 1e10); trackCuts->SetRequireITSRefit(kFALSE); AliESDtrackCuts *trackCutsITS = new AliESDtrackCuts("AliESDtrackCuts","Standard Cuts with ITSrefit"); //Standard Cuts trackCuts=trackCuts->GetStandardITSTPCTrackCuts2009(kTRUE);//Primary Track Selection trackCuts->SetEtaRange(-0.9,0.9); trackCuts->SetPtRange(0.15, 1e10); trackCuts->SetRequireITSRefit(kTRUE); //Create the task AliPWG4HighPtQAMC *taskPWG4QAMC = new AliPWG4HighPtQAMC("AliPWG4HighPtQAMC"); taskPWG4QAMC->SetCuts(trackCuts); taskPWG4QAMC->SetCutsITS(trackCutsITS); // E. Create ONLY the output containers for the data produced by the task. // Get and connect other common input/output containers via the manager as below //============================================================================== //------ input data ------ // AliAnalysisDataContainer *cinput0 = mgr->GetCommonInputContainer(); printf("Create output containers \n"); TString outputfile = AliAnalysisManager::GetCommonFileName(); outputfile += ":PWG4_HighPtQAMC"; //char *outputfile = "outputAliPWG4HighPtQAMCTestTrain.root"; AliAnalysisDataContainer *cout_hist0 = mgr->CreateContainer("qa_histsMC", TList::Class(), AliAnalysisManager::kOutputContainer,outputfile); AliAnalysisDataContainer *cout_hist2 = mgr->CreateContainer("qa_histsMCITS", TList::Class(), AliAnalysisManager::kOutputContainer,outputfile); mgr->AddTask(taskPWG4QAMC); mgr->ConnectInput(taskPWG4QAMC,0,mgr->GetCommonInputContainer()); mgr->ConnectOutput(taskPWG4QAMC,0,cout_hist0); mgr->ConnectOutput(taskPWG4QAMC,1,cout_hist2); // Return task pointer at the end return taskPWG4QAMC; } <commit_msg>bug fix in definition of track cuts (Marta)<commit_after>//DEFINITION OF A FEW CONSTANTS AliPWG4HighPtQAMC* AddTaskPWG4HighPtQAMC() { // Creates HighPtQAMC analysis task and adds it to the analysis manager. // A. Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTaskPWG4HighPtQMC", "No analysis manager to connect to."); return NULL; } // B. Check the analysis type using the event handlers connected to the analysis // manager. The availability of MC handler can also be checked here. //============================================================================== if (!mgr->GetInputEventHandler()) { ::Error("AddPWG4TaskHighPtQAMC", "This task requires an input event handler"); return NULL; } TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD" const char *analysisType = "ESD";//"TPC" // C. Create the task, add it to manager. //=========================================================================== //CREATE THE CUTS ----------------------------------------------- //Use AliESDtrackCuts AliESDtrackCuts *trackCuts = new AliESDtrackCuts("AliESDtrackCuts","Standard Cuts"); //Standard Cuts trackCuts=trackCuts->GetStandardITSTPCTrackCuts2009(kTRUE);//Primary Track Selection trackCuts->SetEtaRange(-0.9,0.9); trackCuts->SetPtRange(0.15, 1e10); trackCuts->SetRequireITSRefit(kFALSE); AliESDtrackCuts *trackCutsITS = new AliESDtrackCuts("AliESDtrackCuts","Standard Cuts with ITSrefit"); //Standard Cuts trackCutsITS=trackCuts->GetStandardITSTPCTrackCuts2009(kTRUE);//Primary Track Selection trackCutsITS->SetEtaRange(-0.9,0.9); trackCutsITS->SetPtRange(0.15, 1e10); trackCutsITS->SetRequireITSRefit(kTRUE); //Create the task AliPWG4HighPtQAMC *taskPWG4QAMC = new AliPWG4HighPtQAMC("AliPWG4HighPtQAMC"); taskPWG4QAMC->SetCuts(trackCuts); taskPWG4QAMC->SetCutsITS(trackCutsITS); // E. Create ONLY the output containers for the data produced by the task. // Get and connect other common input/output containers via the manager as below //============================================================================== //------ input data ------ // AliAnalysisDataContainer *cinput0 = mgr->GetCommonInputContainer(); printf("Create output containers \n"); TString outputfile = AliAnalysisManager::GetCommonFileName(); outputfile += ":PWG4_HighPtQAMC"; //char *outputfile = "outputAliPWG4HighPtQAMCTestTrain.root"; AliAnalysisDataContainer *cout_hist0 = mgr->CreateContainer("qa_histsMC", TList::Class(), AliAnalysisManager::kOutputContainer,outputfile); AliAnalysisDataContainer *cout_hist2 = mgr->CreateContainer("qa_histsMCITS", TList::Class(), AliAnalysisManager::kOutputContainer,outputfile); mgr->AddTask(taskPWG4QAMC); mgr->ConnectInput(taskPWG4QAMC,0,mgr->GetCommonInputContainer()); mgr->ConnectOutput(taskPWG4QAMC,0,cout_hist0); mgr->ConnectOutput(taskPWG4QAMC,1,cout_hist2); // Return task pointer at the end return taskPWG4QAMC; } <|endoftext|>
<commit_before>// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2; -*- /* Copyright (C) 2009, Anders Ronnbrant - [email protected] All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. You should have received a copy of the FreeBSD license, if not see: <http://www.freebsd.org/copyright/freebsd-license.html>. */ #include "vincenty.h" #include <iomanip> namespace vincenty { // Geographical position // ------------------------------------------------------------------------ //! Constructor, defaults latitude and longitude to zero (0). vposition::vposition() : coords() { coords.a[0] = 0; coords.a[1] = 0; } //! Constructor taking two doubles for initialization. vposition::vposition( double _lat, double _lon ) : coords() { coords.a[0] = _lat; coords.a[1] = _lon; } //! Integer degrees from float radian. int vposition::deg( const double rad ) { return int( to_deg(rad) ); } //! Extracts integer minutes from float radian. int vposition::min( const double rad ) { return int( ( degf(rad) - deg(rad) ) * 60 ); } //! Extracts integer seconds from float radian. int vposition::sec( const double rad ) { return int( ( minf(rad) - min(rad) ) * 60 ); } //! Converts radians to degrees. double vposition::degf( const double rad ) { return to_deg(rad); } //! Extracts decimal part minutes from float radian. double vposition::minf( const double rad ) { return ( degf(rad) - deg(rad) ) * 60; } //! Extracts decimal part seconds from float radian. double vposition::secf( const double rad ) { return ( minf(rad) - min(rad) ) * 60; } // Operators for vposition. bool operator==( const vposition& lhs, const vposition& rhs ) { if ( ulpcmp(lhs.coords.a[0], rhs.coords.a[0]) && ulpcmp(lhs.coords.a[1], rhs.coords.a[1]) ) { return true; } else { return false; } } vposition vposition::operator+( const vdirection& rhs ) const { return direct((*this),rhs); } vposition vposition::operator-( const vdirection& rhs ) const { return direct((*this),rhs.bearing2,rhs.distance); } vdirection vposition::operator-( const vposition& rhs ) const { return inverse(rhs,(*this)); } vposition vposition::operator^( const vposition& rhs ) const { vdirection d = (*this) - rhs; return direct((*this),d.bearing1,d.distance/2.0); } // Geographical direction // ------------------------------------------------------------------------ //! Constructor, defaults bearings and distance to 0 (zero). vdirection::vdirection() : bearing1(0), distance(0), bearing2(0) { } /*! * Constructor taking three doubles for initialization. * * !!OBS!! This constructor allows for invalid settings. I.e. the two bearings * combined with the distance might not always be a possible solution for any * two points on the geoid. * * @param _bearing1 The bearing for the direction. * @param _distance The distance to travel in the current bearing. * @param _bearing2 The reversed bearing for the direction. */ vdirection::vdirection( double _bearing1, double _distance, double _bearing2 ) : bearing1(_bearing1), distance(_distance), bearing2(_bearing2) { } // Operators for vdirection. bool operator==( const vdirection& lhs, const vdirection& rhs ) { if ( ulpcmp(lhs.bearing1, rhs.bearing1) && ulpcmp(lhs.distance, rhs.distance) ) { return true; } else { return false; } } vdirection vdirection::operator/( const double rhs ) const { return vdirection((*this).bearing1,(*this).distance/rhs); } vdirection vdirection::operator*( const double rhs ) const { return vdirection((*this).bearing1,(*this).distance*rhs); } } // namespace end <commit_msg> Wrong bearing used for middle point operator.<commit_after>// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2; -*- /* Copyright (C) 2009, Anders Ronnbrant - [email protected] All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. You should have received a copy of the FreeBSD license, if not see: <http://www.freebsd.org/copyright/freebsd-license.html>. */ #include "vincenty.h" #include <iomanip> namespace vincenty { // Geographical position // ------------------------------------------------------------------------ //! Constructor, defaults latitude and longitude to zero (0). vposition::vposition() : coords() { coords.a[0] = 0; coords.a[1] = 0; } //! Constructor taking two doubles for initialization. vposition::vposition( double _lat, double _lon ) : coords() { coords.a[0] = _lat; coords.a[1] = _lon; } //! Integer degrees from float radian. int vposition::deg( const double rad ) { return int( to_deg(rad) ); } //! Extracts integer minutes from float radian. int vposition::min( const double rad ) { return int( ( degf(rad) - deg(rad) ) * 60 ); } //! Extracts integer seconds from float radian. int vposition::sec( const double rad ) { return int( ( minf(rad) - min(rad) ) * 60 ); } //! Converts radians to degrees. double vposition::degf( const double rad ) { return to_deg(rad); } //! Extracts decimal part minutes from float radian. double vposition::minf( const double rad ) { return ( degf(rad) - deg(rad) ) * 60; } //! Extracts decimal part seconds from float radian. double vposition::secf( const double rad ) { return ( minf(rad) - min(rad) ) * 60; } // Operators for vposition. bool operator==( const vposition& lhs, const vposition& rhs ) { if ( ulpcmp(lhs.coords.a[0], rhs.coords.a[0]) && ulpcmp(lhs.coords.a[1], rhs.coords.a[1]) ) { return true; } else { return false; } } vposition vposition::operator+( const vdirection& rhs ) const { return direct((*this),rhs); } vposition vposition::operator-( const vdirection& rhs ) const { return direct((*this),rhs.bearing2,rhs.distance); } vdirection vposition::operator-( const vposition& rhs ) const { return inverse(rhs,(*this)); } vposition vposition::operator^( const vposition& rhs ) const { vdirection d = inverse(rhs,(*this)); return direct((*this),d.bearing2,d.distance/2.0); } // Geographical direction // ------------------------------------------------------------------------ //! Constructor, defaults bearings and distance to 0 (zero). vdirection::vdirection() : bearing1(0), distance(0), bearing2(0) { } /*! * Constructor taking three doubles for initialization. * * !!OBS!! This constructor allows for invalid settings. I.e. the two bearings * combined with the distance might not always be a possible solution for any * two points on the geoid. * * @param _bearing1 The bearing for the direction. * @param _distance The distance to travel in the current bearing. * @param _bearing2 The reversed bearing for the direction. */ vdirection::vdirection( double _bearing1, double _distance, double _bearing2 ) : bearing1(_bearing1), distance(_distance), bearing2(_bearing2) { } // Operators for vdirection. bool operator==( const vdirection& lhs, const vdirection& rhs ) { if ( ulpcmp(lhs.bearing1, rhs.bearing1) && ulpcmp(lhs.distance, rhs.distance) ) { return true; } else { return false; } } vdirection vdirection::operator/( const double rhs ) const { return vdirection((*this).bearing1,(*this).distance/rhs); } vdirection vdirection::operator*( const double rhs ) const { return vdirection((*this).bearing1,(*this).distance*rhs); } } // namespace end <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // Qmitk related includes #include "QmitkPropertyListViewItem.h" #include "QmitkPropertyListViewItemFactory.h" #include "QmitkMaterialEditor.h" // mitk related includes #include "mitkConfig.h" #include "mitkRenderWindow.h" #include "mitkPropertyList.h" #include "mitkProperties.h" #include "mitkColorProperty.h" #include "mitkPropertyManager.h" #include "mitkRenderingManager.h" #include "mitkEnumerationProperty.h" #include "mitkMaterialProperty.h" // QT related includes #include <qcheckbox.h> #include <qlineedit.h> #include <qlabel.h> #include <qpushbutton.h> #include <qpixmap.h> #include <qcolordialog.h> #include <qvalidator.h> #include <qhbox.h> #include <qslider.h> #include <qcombobox.h> #include "enabled.xpm" #include "disabled.xpm" QmitkPropertyListViewItem::QmitkPropertyListViewItem(std::string name, mitk::PropertyList* propertyList, QWidget* parent, bool createOnlyControl) : m_Name(name), m_PropertyList(propertyList), m_Label(NULL), m_Control(NULL) { if (!createOnlyControl) { CreateEnabledButton(parent); m_Label = new QLabel(name.c_str(),parent); m_Label->show(); } }; void QmitkPropertyListViewItem::CreateEnabledButton(QWidget* parent) { m_EnabledButton = new QPushButton(parent); connect( (QObject*)(m_EnabledButton), SIGNAL(clicked()), (QObject*)(this), SLOT(EnabledButtonClicked()) ); m_EnabledButton->show(); UpdateEnabledView(); } QmitkPropertyListViewItem* QmitkPropertyListViewItem::CreateInstance(mitk::PropertyList *propList, const std::string name, QWidget* parent, bool createOnlyControl) { return QmitkPropertyListViewItemFactory::GetInstance()->CreateQmitkPropertyListViewItem(propList,name,parent,createOnlyControl); } void QmitkPropertyListViewItem::CheckBoxControlActivated(bool on) { m_PropertyList->SetProperty(m_Name.c_str(), new mitk::BoolProperty(on)); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkPropertyListViewItem::StringControlActivated(const QString &text) { m_PropertyList->SetProperty(m_Name.c_str(), new mitk::StringProperty(text.ascii())); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkPropertyListViewItem::FloatControlActivated(const QString &text) { if (((QLineEdit*)m_Control)->hasAcceptableInput()) { m_Control->setPaletteForegroundColor(Qt::black); float value = text.toFloat(); mitk::FloatProperty* floatProp = dynamic_cast<mitk::FloatProperty*>(m_PropertyList->GetProperty(m_Name.c_str()).GetPointer()); if (value != floatProp->GetValue()) { m_PropertyList->SetProperty(m_Name.c_str(), new mitk::FloatProperty(value)); } } else { m_Control->setPaletteForegroundColor(Qt::red); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkPropertyListViewItem::IntControlActivated(const QString &text) { if (((QLineEdit*)m_Control)->hasAcceptableInput()) { m_Control->setPaletteForegroundColor(Qt::black); int value = text.toInt(); mitk::IntProperty* intProp = dynamic_cast<mitk::IntProperty*>(m_PropertyList->GetProperty(m_Name.c_str()).GetPointer()); if (value != intProp->GetValue()) { m_PropertyList->SetProperty(m_Name.c_str(), new mitk::IntProperty(value)); } } else { m_Control->setPaletteForegroundColor(Qt::red); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkPropertyListViewItem::ColorControlActivated() { mitk::ColorProperty* colorProp = dynamic_cast<mitk::ColorProperty*>(m_PropertyList->GetProperty(m_Name.c_str()).GetPointer()); mitk::Color col = colorProp->GetColor(); QColor result = QColorDialog::getColor(QColor((int)(col.GetRed() * 255), (int)(col.GetGreen() * 255), (int)(col.GetBlue() * 255))); if (result.isValid()) { col.SetRed(result.red() / 255.0); col.SetGreen(result.green() / 255.0); col.SetBlue(result.blue() / 255.0); colorProp->SetColor(col); m_PropertyList->InvokeEvent(itk::ModifiedEvent()); m_Control->setPaletteBackgroundColor(result); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkPropertyListViewItem::UpdateView() { m_Control->blockSignals(true); mitk::BaseProperty* baseProp = m_PropertyList->GetProperty(m_Name.c_str()); if (mitk::BoolProperty* boolProp = dynamic_cast<mitk::BoolProperty*>(baseProp)) { if (QCheckBox* cb = dynamic_cast<QCheckBox*>(m_Control)) { cb ->setChecked(boolProp->GetValue()); } else { std::cout << "warning: non-checkbox control for bool property " << m_Name << std::endl; } } else if (mitk::StringProperty* stringProp = dynamic_cast<mitk::StringProperty*>(baseProp)) { if (QLineEdit* qle = dynamic_cast<QLineEdit*>(m_Control)) { qle->setText(QString(stringProp->GetValue())); } else { std::cout << "warning: non-lineedit control for string property " << m_Name << std::endl; } } else if (mitk::FloatProperty* floatProp = dynamic_cast<mitk::FloatProperty*>(baseProp)) { QString text; text.setNum(floatProp->GetValue()); ((QLineEdit*)(m_Control))->setText(text); } else if (mitk::ColorProperty* colorProp = dynamic_cast<mitk::ColorProperty*>(baseProp)) { mitk::Color col = colorProp->GetColor(); QColor qcol((int)(col.GetRed() * 255), (int)(col.GetGreen() * 255),(int)( col.GetBlue() * 255)); ((QPushButton*)(m_Control))->setPaletteBackgroundColor(qcol); } else if (mitk::EnumerationProperty* enumerationProp = dynamic_cast<mitk::EnumerationProperty*>(baseProp)) { QComboBox* combo = ( ( QComboBox* ) m_Control ); std::string enumerationValue = enumerationProp->GetValueAsString(); for ( int item = 0 ; item < combo->count() ; ++item ) { if ( enumerationValue == combo->text( item ).latin1() ) { combo->setCurrentItem( item ); break; } } } m_Control->blockSignals(false); } void QmitkPropertyListViewItem::UpdateEnabledView() { static const QPixmap enabledPix((const char **)enabled_xpm); static const QPixmap disabledPix((const char **)disabled_xpm); if (m_PropertyList->IsEnabled(m_Name.c_str())) /* baseProp->GetEnabled()) */ { m_EnabledButton->setPixmap(enabledPix); if (m_Control) {m_Control->setEnabled(true);} if (m_Label) {m_Label->setEnabled(true);} } else { m_EnabledButton->setPixmap(disabledPix); if (m_Control) {m_Control->setEnabled(false);} if (m_Label) {m_Label->setEnabled(false);} } } void QmitkPropertyListViewItem::EnabledButtonClicked() { //baseProp->SetEnabled(! baseProp->GetEnabled()); m_PropertyList->SetEnabled(m_Name.c_str(), ! m_PropertyList->IsEnabled(m_Name.c_str())); UpdateEnabledView(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkPropertyListViewItem::ComboBoxItemActivated(const QString &item) { mitk::EnumerationProperty* enumProp = dynamic_cast<mitk::EnumerationProperty*>(m_PropertyList->GetProperty(m_Name.c_str()).GetPointer()); if ( enumProp != NULL ) { std::string activatedItem( item.latin1() ); if ( activatedItem != enumProp->GetValueAsString() ) { if ( enumProp->IsValidEnumerationValue( activatedItem ) ) { enumProp->SetValue( activatedItem ); m_PropertyList->InvokeEvent( itk::ModifiedEvent() ); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } } } void QmitkPropertyListViewFloatSlider::SliderValueChanged(int value) { m_PropertyList->SetProperty(m_Name.c_str(), new mitk::FloatProperty(value / 100.0f)); UpdateView(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkPropertyListViewFloatSlider::UpdateView() { m_Slider->blockSignals(true); mitk::FloatProperty* floatProp = dynamic_cast<mitk::FloatProperty*>(m_PropertyList->GetProperty(m_Name.c_str()).GetPointer()); if (floatProp) { QString text; text.setNum(floatProp->GetValue(),'f',2); m_ValueLabel->setText(text); m_Slider->setValue((int)(floatProp->GetValue() * 100)); } m_Slider->blockSignals(false); } void QmitkPropertyListViewItem::MaterialEditorActivated() { if ( mitk::MaterialProperty* materialProperty = dynamic_cast<mitk::MaterialProperty*>(m_PropertyList->GetProperty(m_Name.c_str()).GetPointer())) { QmitkMaterialEditor* materialEditor = new QmitkMaterialEditor( NULL ); materialEditor->Initialize( materialProperty ); if ( materialEditor->exec() == QDialog::Accepted ) { m_PropertyList->InvokeEvent(itk::ModifiedEvent()); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } delete materialEditor; } } <commit_msg>comment warnings<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // Qmitk related includes #include "QmitkPropertyListViewItem.h" #include "QmitkPropertyListViewItemFactory.h" #include "QmitkMaterialEditor.h" // mitk related includes #include "mitkConfig.h" #include "mitkRenderWindow.h" #include "mitkPropertyList.h" #include "mitkProperties.h" #include "mitkColorProperty.h" #include "mitkPropertyManager.h" #include "mitkRenderingManager.h" #include "mitkEnumerationProperty.h" #include "mitkMaterialProperty.h" // QT related includes #include <qcheckbox.h> #include <qlineedit.h> #include <qlabel.h> #include <qpushbutton.h> #include <qpixmap.h> #include <qcolordialog.h> #include <qvalidator.h> #include <qhbox.h> #include <qslider.h> #include <qcombobox.h> #include "enabled.xpm" #include "disabled.xpm" QmitkPropertyListViewItem::QmitkPropertyListViewItem(std::string name, mitk::PropertyList* propertyList, QWidget* parent, bool createOnlyControl) : m_Name(name), m_PropertyList(propertyList), m_Label(NULL), m_Control(NULL) { if (!createOnlyControl) { CreateEnabledButton(parent); m_Label = new QLabel(name.c_str(),parent); m_Label->show(); } }; void QmitkPropertyListViewItem::CreateEnabledButton(QWidget* parent) { m_EnabledButton = new QPushButton(parent); connect( (QObject*)(m_EnabledButton), SIGNAL(clicked()), (QObject*)(this), SLOT(EnabledButtonClicked()) ); m_EnabledButton->show(); UpdateEnabledView(); } QmitkPropertyListViewItem* QmitkPropertyListViewItem::CreateInstance(mitk::PropertyList *propList, const std::string name, QWidget* parent, bool createOnlyControl) { return QmitkPropertyListViewItemFactory::GetInstance()->CreateQmitkPropertyListViewItem(propList,name,parent,createOnlyControl); } void QmitkPropertyListViewItem::CheckBoxControlActivated(bool on) { m_PropertyList->SetProperty(m_Name.c_str(), new mitk::BoolProperty(on)); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkPropertyListViewItem::StringControlActivated(const QString &text) { m_PropertyList->SetProperty(m_Name.c_str(), new mitk::StringProperty(text.ascii())); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkPropertyListViewItem::FloatControlActivated(const QString &text) { if (((QLineEdit*)m_Control)->hasAcceptableInput()) { m_Control->setPaletteForegroundColor(Qt::black); float value = text.toFloat(); mitk::FloatProperty* floatProp = dynamic_cast<mitk::FloatProperty*>(m_PropertyList->GetProperty(m_Name.c_str()).GetPointer()); if (value != floatProp->GetValue()) { m_PropertyList->SetProperty(m_Name.c_str(), new mitk::FloatProperty(value)); } } else { m_Control->setPaletteForegroundColor(Qt::red); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkPropertyListViewItem::IntControlActivated(const QString &text) { if (((QLineEdit*)m_Control)->hasAcceptableInput()) { m_Control->setPaletteForegroundColor(Qt::black); int value = text.toInt(); mitk::IntProperty* intProp = dynamic_cast<mitk::IntProperty*>(m_PropertyList->GetProperty(m_Name.c_str()).GetPointer()); if (value != intProp->GetValue()) { m_PropertyList->SetProperty(m_Name.c_str(), new mitk::IntProperty(value)); } } else { m_Control->setPaletteForegroundColor(Qt::red); } mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkPropertyListViewItem::ColorControlActivated() { mitk::ColorProperty* colorProp = dynamic_cast<mitk::ColorProperty*>(m_PropertyList->GetProperty(m_Name.c_str()).GetPointer()); mitk::Color col = colorProp->GetColor(); QColor result = QColorDialog::getColor(QColor((int)(col.GetRed() * 255), (int)(col.GetGreen() * 255), (int)(col.GetBlue() * 255))); if (result.isValid()) { col.SetRed(result.red() / 255.0); col.SetGreen(result.green() / 255.0); col.SetBlue(result.blue() / 255.0); colorProp->SetColor(col); m_PropertyList->InvokeEvent(itk::ModifiedEvent()); m_Control->setPaletteBackgroundColor(result); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } void QmitkPropertyListViewItem::UpdateView() { m_Control->blockSignals(true); mitk::BaseProperty* baseProp = m_PropertyList->GetProperty(m_Name.c_str()); if (mitk::BoolProperty* boolProp = dynamic_cast<mitk::BoolProperty*>(baseProp)) { if (QCheckBox* cb = dynamic_cast<QCheckBox*>(m_Control)) { cb ->setChecked(boolProp->GetValue()); } else { //std::cout << "warning: non-checkbox control for bool property " << m_Name << std::endl; } } else if (mitk::StringProperty* stringProp = dynamic_cast<mitk::StringProperty*>(baseProp)) { if (QLineEdit* qle = dynamic_cast<QLineEdit*>(m_Control)) { qle->setText(QString(stringProp->GetValue())); } else { //std::cout << "warning: non-lineedit control for string property " << m_Name << std::endl; } } else if (mitk::FloatProperty* floatProp = dynamic_cast<mitk::FloatProperty*>(baseProp)) { QString text; text.setNum(floatProp->GetValue()); ((QLineEdit*)(m_Control))->setText(text); } else if (mitk::ColorProperty* colorProp = dynamic_cast<mitk::ColorProperty*>(baseProp)) { mitk::Color col = colorProp->GetColor(); QColor qcol((int)(col.GetRed() * 255), (int)(col.GetGreen() * 255),(int)( col.GetBlue() * 255)); ((QPushButton*)(m_Control))->setPaletteBackgroundColor(qcol); } else if (mitk::EnumerationProperty* enumerationProp = dynamic_cast<mitk::EnumerationProperty*>(baseProp)) { QComboBox* combo = ( ( QComboBox* ) m_Control ); std::string enumerationValue = enumerationProp->GetValueAsString(); for ( int item = 0 ; item < combo->count() ; ++item ) { if ( enumerationValue == combo->text( item ).latin1() ) { combo->setCurrentItem( item ); break; } } } m_Control->blockSignals(false); } void QmitkPropertyListViewItem::UpdateEnabledView() { static const QPixmap enabledPix((const char **)enabled_xpm); static const QPixmap disabledPix((const char **)disabled_xpm); if (m_PropertyList->IsEnabled(m_Name.c_str())) /* baseProp->GetEnabled()) */ { m_EnabledButton->setPixmap(enabledPix); if (m_Control) {m_Control->setEnabled(true);} if (m_Label) {m_Label->setEnabled(true);} } else { m_EnabledButton->setPixmap(disabledPix); if (m_Control) {m_Control->setEnabled(false);} if (m_Label) {m_Label->setEnabled(false);} } } void QmitkPropertyListViewItem::EnabledButtonClicked() { //baseProp->SetEnabled(! baseProp->GetEnabled()); m_PropertyList->SetEnabled(m_Name.c_str(), ! m_PropertyList->IsEnabled(m_Name.c_str())); UpdateEnabledView(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkPropertyListViewItem::ComboBoxItemActivated(const QString &item) { mitk::EnumerationProperty* enumProp = dynamic_cast<mitk::EnumerationProperty*>(m_PropertyList->GetProperty(m_Name.c_str()).GetPointer()); if ( enumProp != NULL ) { std::string activatedItem( item.latin1() ); if ( activatedItem != enumProp->GetValueAsString() ) { if ( enumProp->IsValidEnumerationValue( activatedItem ) ) { enumProp->SetValue( activatedItem ); m_PropertyList->InvokeEvent( itk::ModifiedEvent() ); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } } } } void QmitkPropertyListViewFloatSlider::SliderValueChanged(int value) { m_PropertyList->SetProperty(m_Name.c_str(), new mitk::FloatProperty(value / 100.0f)); UpdateView(); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkPropertyListViewFloatSlider::UpdateView() { m_Slider->blockSignals(true); mitk::FloatProperty* floatProp = dynamic_cast<mitk::FloatProperty*>(m_PropertyList->GetProperty(m_Name.c_str()).GetPointer()); if (floatProp) { QString text; text.setNum(floatProp->GetValue(),'f',2); m_ValueLabel->setText(text); m_Slider->setValue((int)(floatProp->GetValue() * 100)); } m_Slider->blockSignals(false); } void QmitkPropertyListViewItem::MaterialEditorActivated() { if ( mitk::MaterialProperty* materialProperty = dynamic_cast<mitk::MaterialProperty*>(m_PropertyList->GetProperty(m_Name.c_str()).GetPointer())) { QmitkMaterialEditor* materialEditor = new QmitkMaterialEditor( NULL ); materialEditor->Initialize( materialProperty ); if ( materialEditor->exec() == QDialog::Accepted ) { m_PropertyList->InvokeEvent(itk::ModifiedEvent()); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } delete materialEditor; } } <|endoftext|>
<commit_before>#include "pch.h" #include "Servo.h" namespace winrt::servo { void on_load_started() { sServo->Delegate().OnServoLoadStarted(); } void on_load_ended() { sServo->Delegate().OnServoLoadEnded(); } void on_history_changed(bool back, bool forward) { sServo->Delegate().OnServoHistoryChanged(back, forward); } void on_shutdown_complete() { sServo->Delegate().OnServoShutdownComplete(); } void on_title_changed(const char *title) { sServo->Delegate().OnServoTitleChanged(char2hstring(title)); } void on_url_changed(const char *url) { sServo->Delegate().OnServoURLChanged(char2hstring(url)); } void flush() { sServo->Delegate().Flush(); } void make_current() { sServo->Delegate().MakeCurrent(); } void wakeup() { sServo->Delegate().WakeUp(); } bool on_allow_navigation(const char *url) { return sServo->Delegate().OnServoAllowNavigation(char2hstring(url)); }; void on_animating_changed(bool aAnimating) { sServo->Delegate().OnServoAnimatingChanged(aAnimating); } void on_panic(const char *backtrace) { throw hresult_error(E_FAIL, char2hstring(backtrace)); } void on_ime_state_changed(bool aShow) { sServo->Delegate().OnServoIMEStateChanged(aShow); } void set_clipboard_contents(const char *content) { // FIXME } const char *get_clipboard_contents() { // FIXME return nullptr; } void on_media_session_metadata(const char *title, const char *album, const char *artist) { return sServo->Delegate().OnServoMediaSessionMetadata( char2hstring(title), char2hstring(album), char2hstring(artist)); } void on_media_session_playback_state_change( const capi::CMediaSessionPlaybackState state) { return sServo->Delegate().OnServoMediaSessionPlaybackStateChange(state); } void prompt_alert(const char *message, bool trusted) { sServo->Delegate().OnServoPromptAlert(char2hstring(message), trusted); } Servo::PromptResult prompt_ok_cancel(const char *message, bool trusted) { return sServo->Delegate().OnServoPromptOkCancel(char2hstring(message), trusted); } Servo::PromptResult prompt_yes_no(const char *message, bool trusted) { return sServo->Delegate().OnServoPromptYesNo(char2hstring(message), trusted); } const char *prompt_input(const char *message, const char *default, bool trusted) { auto input = sServo->Delegate().OnServoPromptInput( char2hstring(message), char2hstring(default), trusted); if (input.has_value()) { return *hstring2char(*input); } else { return nullptr; } } Servo::Servo(hstring url, hstring args, GLsizei width, GLsizei height, float dpi, ServoDelegate &aDelegate) : mWindowHeight(height), mWindowWidth(width), mDelegate(aDelegate) { capi::CInitOptions o; hstring defaultPrefs = L" --pref dom.webxr.enabled --devtools=6000"; o.args = *hstring2char(args + defaultPrefs); o.url = *hstring2char(url); o.width = mWindowWidth; o.height = mWindowHeight; o.density = dpi; o.enable_subpixel_text_antialiasing = false; o.vr_pointer = NULL; // 7 filter modules. /* Sample list of servo modules to filter. static char *pfilters[] = { "servo", "simpleservo", "simpleservo::jniapi", "simpleservo::gl_glue::egl", // Show JS errors by default. "script::dom::bindings::error", // Show GL errors by default. "canvas::webgl_thread", "compositing::compositor", "constellation::constellation", }; */ // Example Call when *pfilters[] is used: // o.vslogger_mod_list = pfilters; // servo log modules // o.vslogger_mod_size = sizeof(pfilters) / sizeof(pfilters[0]); // // Important: Number of modules in pfilters o.vslogger_mod_list = NULL; o.vslogger_mod_size = 0; sServo = this; // FIXME; capi::CHostCallbacks c; c.flush = &flush; c.make_current = &make_current; c.on_load_started = &on_load_started; c.on_load_ended = &on_load_ended; c.on_title_changed = &on_title_changed; c.on_url_changed = &on_url_changed; c.on_history_changed = &on_history_changed; c.on_animating_changed = &on_animating_changed; c.on_shutdown_complete = &on_shutdown_complete; c.on_allow_navigation = &on_allow_navigation; c.on_ime_state_changed = &on_ime_state_changed; c.get_clipboard_contents = &get_clipboard_contents; c.set_clipboard_contents = &set_clipboard_contents; c.on_media_session_metadata = &on_media_session_metadata; c.on_media_session_playback_state_change = &on_media_session_playback_state_change; c.prompt_alert = &prompt_alert; c.prompt_ok_cancel = &prompt_ok_cancel; c.prompt_yes_no = &prompt_yes_no; c.prompt_input = &prompt_input; capi::register_panic_handler(&on_panic); capi::init_with_egl(o, &wakeup, c); } Servo::~Servo() { sServo = nullptr; } winrt::hstring char2hstring(const char *c_str) { // FIXME: any better way of doing this? auto str = std::string(c_str); int size_needed = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0); std::wstring str2(size_needed, 0); MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &str2[0], size_needed); winrt::hstring str3{str2}; return str3; } std::unique_ptr<char *> hstring2char(hstring hstr) { const wchar_t *wc = hstr.c_str(); size_t size = hstr.size() + 1; char *str = new char[size]; size_t converted = 0; wcstombs_s(&converted, str, size, wc, hstr.size()); return std::make_unique<char *>(str); } } // namespace winrt::servo <commit_msg>Disable devtools for HoloLens.<commit_after>#include "pch.h" #include "Servo.h" namespace winrt::servo { void on_load_started() { sServo->Delegate().OnServoLoadStarted(); } void on_load_ended() { sServo->Delegate().OnServoLoadEnded(); } void on_history_changed(bool back, bool forward) { sServo->Delegate().OnServoHistoryChanged(back, forward); } void on_shutdown_complete() { sServo->Delegate().OnServoShutdownComplete(); } void on_title_changed(const char *title) { sServo->Delegate().OnServoTitleChanged(char2hstring(title)); } void on_url_changed(const char *url) { sServo->Delegate().OnServoURLChanged(char2hstring(url)); } void flush() { sServo->Delegate().Flush(); } void make_current() { sServo->Delegate().MakeCurrent(); } void wakeup() { sServo->Delegate().WakeUp(); } bool on_allow_navigation(const char *url) { return sServo->Delegate().OnServoAllowNavigation(char2hstring(url)); }; void on_animating_changed(bool aAnimating) { sServo->Delegate().OnServoAnimatingChanged(aAnimating); } void on_panic(const char *backtrace) { throw hresult_error(E_FAIL, char2hstring(backtrace)); } void on_ime_state_changed(bool aShow) { sServo->Delegate().OnServoIMEStateChanged(aShow); } void set_clipboard_contents(const char *content) { // FIXME } const char *get_clipboard_contents() { // FIXME return nullptr; } void on_media_session_metadata(const char *title, const char *album, const char *artist) { return sServo->Delegate().OnServoMediaSessionMetadata( char2hstring(title), char2hstring(album), char2hstring(artist)); } void on_media_session_playback_state_change( const capi::CMediaSessionPlaybackState state) { return sServo->Delegate().OnServoMediaSessionPlaybackStateChange(state); } void prompt_alert(const char *message, bool trusted) { sServo->Delegate().OnServoPromptAlert(char2hstring(message), trusted); } Servo::PromptResult prompt_ok_cancel(const char *message, bool trusted) { return sServo->Delegate().OnServoPromptOkCancel(char2hstring(message), trusted); } Servo::PromptResult prompt_yes_no(const char *message, bool trusted) { return sServo->Delegate().OnServoPromptYesNo(char2hstring(message), trusted); } const char *prompt_input(const char *message, const char *default, bool trusted) { auto input = sServo->Delegate().OnServoPromptInput( char2hstring(message), char2hstring(default), trusted); if (input.has_value()) { return *hstring2char(*input); } else { return nullptr; } } Servo::Servo(hstring url, hstring args, GLsizei width, GLsizei height, float dpi, ServoDelegate &aDelegate) : mWindowHeight(height), mWindowWidth(width), mDelegate(aDelegate) { capi::CInitOptions o; hstring defaultPrefs = L" --pref dom.webxr.enabled"; o.args = *hstring2char(args + defaultPrefs); o.url = *hstring2char(url); o.width = mWindowWidth; o.height = mWindowHeight; o.density = dpi; o.enable_subpixel_text_antialiasing = false; o.vr_pointer = NULL; // 7 filter modules. /* Sample list of servo modules to filter. static char *pfilters[] = { "servo", "simpleservo", "simpleservo::jniapi", "simpleservo::gl_glue::egl", // Show JS errors by default. "script::dom::bindings::error", // Show GL errors by default. "canvas::webgl_thread", "compositing::compositor", "constellation::constellation", }; */ // Example Call when *pfilters[] is used: // o.vslogger_mod_list = pfilters; // servo log modules // o.vslogger_mod_size = sizeof(pfilters) / sizeof(pfilters[0]); // // Important: Number of modules in pfilters o.vslogger_mod_list = NULL; o.vslogger_mod_size = 0; sServo = this; // FIXME; capi::CHostCallbacks c; c.flush = &flush; c.make_current = &make_current; c.on_load_started = &on_load_started; c.on_load_ended = &on_load_ended; c.on_title_changed = &on_title_changed; c.on_url_changed = &on_url_changed; c.on_history_changed = &on_history_changed; c.on_animating_changed = &on_animating_changed; c.on_shutdown_complete = &on_shutdown_complete; c.on_allow_navigation = &on_allow_navigation; c.on_ime_state_changed = &on_ime_state_changed; c.get_clipboard_contents = &get_clipboard_contents; c.set_clipboard_contents = &set_clipboard_contents; c.on_media_session_metadata = &on_media_session_metadata; c.on_media_session_playback_state_change = &on_media_session_playback_state_change; c.prompt_alert = &prompt_alert; c.prompt_ok_cancel = &prompt_ok_cancel; c.prompt_yes_no = &prompt_yes_no; c.prompt_input = &prompt_input; capi::register_panic_handler(&on_panic); capi::init_with_egl(o, &wakeup, c); } Servo::~Servo() { sServo = nullptr; } winrt::hstring char2hstring(const char *c_str) { // FIXME: any better way of doing this? auto str = std::string(c_str); int size_needed = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0); std::wstring str2(size_needed, 0); MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &str2[0], size_needed); winrt::hstring str3{str2}; return str3; } std::unique_ptr<char *> hstring2char(hstring hstr) { const wchar_t *wc = hstr.c_str(); size_t size = hstr.size() + 1; char *str = new char[size]; size_t converted = 0; wcstombs_s(&converted, str, size, wc, hstr.size()); return std::make_unique<char *>(str); } } // namespace winrt::servo <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: addxmltostorageoptions.cxx,v $ * * $Revision: 1.1 $ * * last change: $Author: jp $ $Date: 2000-11-29 12:15:02 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #pragma hdrstop //_________________________________________________________________________________________________________________ // includes //_________________________________________________________________________________________________________________ #include "addxmltostorageoptions.hxx" #ifndef _UTL_CONFIGMGR_HXX_ #include <unotools/configmgr.hxx> #endif #ifndef _UTL_CONFIGITEM_HXX_ #include <unotools/configitem.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _TOOLS_STRING_HXX #include <tools/string.hxx> #endif #ifndef _COM_SUN_STAR_UNO_ANY_HXX_ #include <com/sun/star/uno/Any.hxx> #endif #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif //_________________________________________________________________________________________________________________ // namespaces //_________________________________________________________________________________________________________________ using namespace ::utl; using namespace ::rtl; using namespace ::osl; using namespace ::com::sun::star::uno; //***************************************************************************************************************** // initialize static member // DON'T DO IT IN YOUR HEADER! // see definition for further informations //***************************************************************************************************************** SvtAddXMLToStorageOptions_Impl* SvtAddXMLToStorageOptions::m_pDataContainer = 0; sal_Int32 SvtAddXMLToStorageOptions::m_nRefCount = 0; //_________________________________________________________________________________________________________________ // private declarations! //_________________________________________________________________________________________________________________ class SvtAddXMLToStorageOptions_Impl : public ConfigItem { //------------------------------------------------------------------------------------------------------------- // public methods //------------------------------------------------------------------------------------------------------------- public: //--------------------------------------------------------------------------------------------------------- // constructor / destructor //--------------------------------------------------------------------------------------------------------- SvtAddXMLToStorageOptions_Impl(); //--------------------------------------------------------------------------------------------------------- // overloaded methods of baseclass //--------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------- // public interface //--------------------------------------------------------------------------------------------------------- /*-****************************************************************************************************//** @short access method to get internal values @descr These method give us a chance to regulate acces to ouer internal values. It's not used in the moment - but it's possible for the feature! @seealso - @param - @return - @onerror - *//*-*****************************************************************************************************/ sal_Bool IsWriter_Add_XML_to_Storage() const { return bAddXmlToStg_Writer; } sal_Bool IsCalc_Add_XML_to_Storage() const { return bAddXmlToStg_Calc; } sal_Bool IsImpress_Add_XML_to_Storage() const { return bAddXmlToStg_Impress; } sal_Bool IsDraw_Add_XML_to_Storage() const { return bAddXmlToStg_Draw; } //------------------------------------------------------------------------------------------------------------- // private methods //------------------------------------------------------------------------------------------------------------- private: /*-****************************************************************************************************//** @short return list of key names of ouer configuration management which represent oue module tree @descr These methods return a static const list of key names. We need it to get needed values from our configuration management. @seealso - @param - @return A list of needed configuration keys is returned. @onerror - *//*-*****************************************************************************************************/ static Sequence< OUString > GetPropertyNames(); //------------------------------------------------------------------------------------------------------------- // private member //------------------------------------------------------------------------------------------------------------- private: sal_Bool bAddXmlToStg_Writer, bAddXmlToStg_Calc, bAddXmlToStg_Impress, bAddXmlToStg_Draw; }; //_________________________________________________________________________________________________________________ // definitions //_________________________________________________________________________________________________________________ //***************************************************************************************************************** // constructor //***************************************************************************************************************** SvtAddXMLToStorageOptions_Impl::SvtAddXMLToStorageOptions_Impl() // Init baseclasses first : ConfigItem( String::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "Office.Common/AddXMLToStorage"))), // Init member then. bAddXmlToStg_Writer( FALSE ), bAddXmlToStg_Calc( FALSE ), bAddXmlToStg_Impress( FALSE ), bAddXmlToStg_Draw( FALSE ) { // Use our static list of configuration keys to get his values. Sequence< OUString > seqNames = GetPropertyNames(); Sequence< Any > seqValues = GetProperties( seqNames ); // Copy values from list in right order to ouer internal member. sal_Int32 nPropertyCount = seqValues.getLength(); const Any* pValue = seqValues.getConstArray(); for( sal_Int32 nProperty=0; nProperty<nPropertyCount; ++nProperty, ++pValue ) if( pValue->hasValue() ) switch( nProperty ) { case 0: *pValue >>= bAddXmlToStg_Writer; break; case 1: *pValue >>= bAddXmlToStg_Calc; break; case 2: *pValue >>= bAddXmlToStg_Impress; break; case 3: *pValue >>= bAddXmlToStg_Draw; break; } } //***************************************************************************************************************** // private method //***************************************************************************************************************** Sequence< OUString > SvtAddXMLToStorageOptions_Impl::GetPropertyNames() { // Build static list of configuration key names. static const sal_Char* pProperties[] = { "Writer", "Calc", "Impress", "Draw" }; const sal_uInt16 nCnt = sizeof(pProperties) / sizeof( pProperties[0] ); Sequence<OUString> aNames( nCnt ); OUString* pNames = aNames.getArray(); for( sal_uInt16 n = 0; n < nCnt; ++n ) pNames[ n ] = OUString::createFromAscii( pProperties[ n ] ); return aNames; } //***************************************************************************************************************** // constructor //***************************************************************************************************************** SvtAddXMLToStorageOptions::SvtAddXMLToStorageOptions() { // Global access, must be guarded (multithreading!). MutexGuard aGuard( GetOwnStaticMutex() ); // Increase ouer refcount ... ++m_nRefCount; // ... and initialize ouer data container only if it not already exist! if( !m_pDataContainer ) m_pDataContainer = new SvtAddXMLToStorageOptions_Impl; } //***************************************************************************************************************** // destructor //***************************************************************************************************************** SvtAddXMLToStorageOptions::~SvtAddXMLToStorageOptions() { // Global access, must be guarded (multithreading!) MutexGuard aGuard( GetOwnStaticMutex() ); // Decrease ouer refcount. // If last instance was deleted ... // we must destroy ouer static data container! if( !--m_nRefCount ) delete m_pDataContainer, m_pDataContainer = 0; } sal_Bool SvtAddXMLToStorageOptions::IsWriter_Add_XML_to_Storage() const { MutexGuard aGuard( GetOwnStaticMutex() ); return m_pDataContainer->IsWriter_Add_XML_to_Storage(); } sal_Bool SvtAddXMLToStorageOptions::IsCalc_Add_XML_to_Storage() const { MutexGuard aGuard( GetOwnStaticMutex() ); return m_pDataContainer->IsCalc_Add_XML_to_Storage(); } sal_Bool SvtAddXMLToStorageOptions::IsImpress_Add_XML_to_Storage() const { MutexGuard aGuard( GetOwnStaticMutex() ); return m_pDataContainer->IsImpress_Add_XML_to_Storage(); } sal_Bool SvtAddXMLToStorageOptions::IsDraw_Add_XML_to_Storage() const { MutexGuard aGuard( GetOwnStaticMutex() ); return m_pDataContainer->IsDraw_Add_XML_to_Storage(); } //***************************************************************************************************************** // private method //***************************************************************************************************************** Mutex& SvtAddXMLToStorageOptions::GetOwnStaticMutex() { // Initialize static mutex only for one time! static Mutex* pMutex = NULL; // If these method first called (Mutex not already exist!) ... if( pMutex == NULL ) { // ... we must create a new one. Protect follow code with the global mutex - // It must be - we create a static variable! MutexGuard aGuard( Mutex::getGlobalMutex() ); // We must check our pointer again - because it can be that another instance of ouer class will be fastr then these! if( pMutex == NULL ) { // Create the new mutex and set it for return on static variable. static Mutex aMutex; pMutex = &aMutex; } } // Return new created or already existing mutex object. return *pMutex; } <commit_msg>INTEGRATION: CWS ooo20040509 (1.1.584); FILE MERGED 2004/05/06 14:04:24 waratah 1.1.584.1: Bracket pragma not valid for gcc<commit_after>/************************************************************************* * * $RCSfile: addxmltostorageoptions.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2004-06-16 10:06:01 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef GCC #pragma hdrstop #endif //_________________________________________________________________________________________________________________ // includes //_________________________________________________________________________________________________________________ #include "addxmltostorageoptions.hxx" #ifndef _UTL_CONFIGMGR_HXX_ #include <unotools/configmgr.hxx> #endif #ifndef _UTL_CONFIGITEM_HXX_ #include <unotools/configitem.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _TOOLS_STRING_HXX #include <tools/string.hxx> #endif #ifndef _COM_SUN_STAR_UNO_ANY_HXX_ #include <com/sun/star/uno/Any.hxx> #endif #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif //_________________________________________________________________________________________________________________ // namespaces //_________________________________________________________________________________________________________________ using namespace ::utl; using namespace ::rtl; using namespace ::osl; using namespace ::com::sun::star::uno; //***************************************************************************************************************** // initialize static member // DON'T DO IT IN YOUR HEADER! // see definition for further informations //***************************************************************************************************************** SvtAddXMLToStorageOptions_Impl* SvtAddXMLToStorageOptions::m_pDataContainer = 0; sal_Int32 SvtAddXMLToStorageOptions::m_nRefCount = 0; //_________________________________________________________________________________________________________________ // private declarations! //_________________________________________________________________________________________________________________ class SvtAddXMLToStorageOptions_Impl : public ConfigItem { //------------------------------------------------------------------------------------------------------------- // public methods //------------------------------------------------------------------------------------------------------------- public: //--------------------------------------------------------------------------------------------------------- // constructor / destructor //--------------------------------------------------------------------------------------------------------- SvtAddXMLToStorageOptions_Impl(); //--------------------------------------------------------------------------------------------------------- // overloaded methods of baseclass //--------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------- // public interface //--------------------------------------------------------------------------------------------------------- /*-****************************************************************************************************//** @short access method to get internal values @descr These method give us a chance to regulate acces to ouer internal values. It's not used in the moment - but it's possible for the feature! @seealso - @param - @return - @onerror - *//*-*****************************************************************************************************/ sal_Bool IsWriter_Add_XML_to_Storage() const { return bAddXmlToStg_Writer; } sal_Bool IsCalc_Add_XML_to_Storage() const { return bAddXmlToStg_Calc; } sal_Bool IsImpress_Add_XML_to_Storage() const { return bAddXmlToStg_Impress; } sal_Bool IsDraw_Add_XML_to_Storage() const { return bAddXmlToStg_Draw; } //------------------------------------------------------------------------------------------------------------- // private methods //------------------------------------------------------------------------------------------------------------- private: /*-****************************************************************************************************//** @short return list of key names of ouer configuration management which represent oue module tree @descr These methods return a static const list of key names. We need it to get needed values from our configuration management. @seealso - @param - @return A list of needed configuration keys is returned. @onerror - *//*-*****************************************************************************************************/ static Sequence< OUString > GetPropertyNames(); //------------------------------------------------------------------------------------------------------------- // private member //------------------------------------------------------------------------------------------------------------- private: sal_Bool bAddXmlToStg_Writer, bAddXmlToStg_Calc, bAddXmlToStg_Impress, bAddXmlToStg_Draw; }; //_________________________________________________________________________________________________________________ // definitions //_________________________________________________________________________________________________________________ //***************************************************************************************************************** // constructor //***************************************************************************************************************** SvtAddXMLToStorageOptions_Impl::SvtAddXMLToStorageOptions_Impl() // Init baseclasses first : ConfigItem( String::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "Office.Common/AddXMLToStorage"))), // Init member then. bAddXmlToStg_Writer( FALSE ), bAddXmlToStg_Calc( FALSE ), bAddXmlToStg_Impress( FALSE ), bAddXmlToStg_Draw( FALSE ) { // Use our static list of configuration keys to get his values. Sequence< OUString > seqNames = GetPropertyNames(); Sequence< Any > seqValues = GetProperties( seqNames ); // Copy values from list in right order to ouer internal member. sal_Int32 nPropertyCount = seqValues.getLength(); const Any* pValue = seqValues.getConstArray(); for( sal_Int32 nProperty=0; nProperty<nPropertyCount; ++nProperty, ++pValue ) if( pValue->hasValue() ) switch( nProperty ) { case 0: *pValue >>= bAddXmlToStg_Writer; break; case 1: *pValue >>= bAddXmlToStg_Calc; break; case 2: *pValue >>= bAddXmlToStg_Impress; break; case 3: *pValue >>= bAddXmlToStg_Draw; break; } } //***************************************************************************************************************** // private method //***************************************************************************************************************** Sequence< OUString > SvtAddXMLToStorageOptions_Impl::GetPropertyNames() { // Build static list of configuration key names. static const sal_Char* pProperties[] = { "Writer", "Calc", "Impress", "Draw" }; const sal_uInt16 nCnt = sizeof(pProperties) / sizeof( pProperties[0] ); Sequence<OUString> aNames( nCnt ); OUString* pNames = aNames.getArray(); for( sal_uInt16 n = 0; n < nCnt; ++n ) pNames[ n ] = OUString::createFromAscii( pProperties[ n ] ); return aNames; } //***************************************************************************************************************** // constructor //***************************************************************************************************************** SvtAddXMLToStorageOptions::SvtAddXMLToStorageOptions() { // Global access, must be guarded (multithreading!). MutexGuard aGuard( GetOwnStaticMutex() ); // Increase ouer refcount ... ++m_nRefCount; // ... and initialize ouer data container only if it not already exist! if( !m_pDataContainer ) m_pDataContainer = new SvtAddXMLToStorageOptions_Impl; } //***************************************************************************************************************** // destructor //***************************************************************************************************************** SvtAddXMLToStorageOptions::~SvtAddXMLToStorageOptions() { // Global access, must be guarded (multithreading!) MutexGuard aGuard( GetOwnStaticMutex() ); // Decrease ouer refcount. // If last instance was deleted ... // we must destroy ouer static data container! if( !--m_nRefCount ) delete m_pDataContainer, m_pDataContainer = 0; } sal_Bool SvtAddXMLToStorageOptions::IsWriter_Add_XML_to_Storage() const { MutexGuard aGuard( GetOwnStaticMutex() ); return m_pDataContainer->IsWriter_Add_XML_to_Storage(); } sal_Bool SvtAddXMLToStorageOptions::IsCalc_Add_XML_to_Storage() const { MutexGuard aGuard( GetOwnStaticMutex() ); return m_pDataContainer->IsCalc_Add_XML_to_Storage(); } sal_Bool SvtAddXMLToStorageOptions::IsImpress_Add_XML_to_Storage() const { MutexGuard aGuard( GetOwnStaticMutex() ); return m_pDataContainer->IsImpress_Add_XML_to_Storage(); } sal_Bool SvtAddXMLToStorageOptions::IsDraw_Add_XML_to_Storage() const { MutexGuard aGuard( GetOwnStaticMutex() ); return m_pDataContainer->IsDraw_Add_XML_to_Storage(); } //***************************************************************************************************************** // private method //***************************************************************************************************************** Mutex& SvtAddXMLToStorageOptions::GetOwnStaticMutex() { // Initialize static mutex only for one time! static Mutex* pMutex = NULL; // If these method first called (Mutex not already exist!) ... if( pMutex == NULL ) { // ... we must create a new one. Protect follow code with the global mutex - // It must be - we create a static variable! MutexGuard aGuard( Mutex::getGlobalMutex() ); // We must check our pointer again - because it can be that another instance of ouer class will be fastr then these! if( pMutex == NULL ) { // Create the new mutex and set it for return on static variable. static Mutex aMutex; pMutex = &aMutex; } } // Return new created or already existing mutex object. return *pMutex; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: customizeaddresslistdialog.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: hr $ $Date: 2007-09-27 11:30:34 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #ifdef SW_DLLIMPLEMENTATION #undef SW_DLLIMPLEMENTATION #endif #ifndef _SWTYPES_HXX #include <swtypes.hxx> #endif #ifndef _CUSTOMIZEADDRESSLISTDIALOG_HXX #include <customizeaddresslistdialog.hxx> #endif #ifndef _CREATEADDRESSLISTDIALOG_HXX #include <createaddresslistdialog.hxx> #endif #ifndef _SV_SCRBAR_HXX #include <vcl/scrbar.hxx> #endif #ifndef _SV_MSGBOX_HXX #include <vcl/msgbox.hxx> #endif #include <customizeaddresslistdialog.hrc> #include <dbui.hrc> #include <helpid.h> /*-- 13.04.2004 14:27:21--------------------------------------------------- -----------------------------------------------------------------------*/ SwCustomizeAddressListDialog::SwCustomizeAddressListDialog( Window* pParent, const SwCSVData& rOldData) : SfxModalDialog(pParent, SW_RES(DLG_MM_CUSTOMIZE_ADDRESS_LIST)), #ifdef MSC #pragma warning (disable : 4355) #endif m_aFieldsFT( this, SW_RES( FT_FIELDS)), m_aFieldsLB( this, SW_RES( LB_FIELDS)), m_aAddPB( this, SW_RES( PB_ADD)), m_aDeletePB( this, SW_RES( PB_DELETE)), m_aRenamePB( this, SW_RES( PB_RENAME)), m_aUpPB( this, SW_RES( PB_UP)), m_aDownPB( this, SW_RES( PB_DOWN)), m_aSeparatorFL( this, SW_RES( FL_SEPARATOR)), m_aOK( this, SW_RES( PB_OK)), m_aCancel( this, SW_RES( PB_CANCEL)), m_aHelp( this, SW_RES( PB_HELP)), #ifdef MSC #pragma warning (default : 4355) #endif m_pNewData( new SwCSVData(rOldData)) { FreeResource(); m_aFieldsLB.SetSelectHdl(LINK(this, SwCustomizeAddressListDialog, ListBoxSelectHdl_Impl)); Link aAddRenameLk = LINK(this, SwCustomizeAddressListDialog, AddRenameHdl_Impl ); m_aAddPB.SetClickHdl(aAddRenameLk); m_aRenamePB.SetClickHdl(aAddRenameLk); m_aDeletePB.SetClickHdl(LINK(this, SwCustomizeAddressListDialog, DeleteHdl_Impl )); Link aUpDownLk = LINK(this, SwCustomizeAddressListDialog, UpDownHdl_Impl); m_aUpPB.SetClickHdl(aUpDownLk); m_aDownPB.SetClickHdl(aUpDownLk); ::std::vector< ::rtl::OUString >::iterator aHeaderIter; for(aHeaderIter = m_pNewData->aDBColumnHeaders.begin(); aHeaderIter != m_pNewData->aDBColumnHeaders.end(); ++aHeaderIter) m_aFieldsLB.InsertEntry(*aHeaderIter); m_aFieldsLB.SelectEntryPos(0); UpdateButtons(); } /*-- 13.04.2004 14:34:07--------------------------------------------------- -----------------------------------------------------------------------*/ SwCustomizeAddressListDialog::~SwCustomizeAddressListDialog() { } /*-- 12.08.2004 12:58:00--------------------------------------------------- -----------------------------------------------------------------------*/ IMPL_LINK(SwCustomizeAddressListDialog, ListBoxSelectHdl_Impl, ListBox*, EMPTYARG) { UpdateButtons(); return 0; } /*-- 13.04.2004 15:02:14--------------------------------------------------- -----------------------------------------------------------------------*/ IMPL_LINK(SwCustomizeAddressListDialog, AddRenameHdl_Impl, PushButton*, pButton) { bool bRename = pButton == &m_aRenamePB; USHORT nPos = m_aFieldsLB.GetSelectEntryPos(); if(nPos == LISTBOX_ENTRY_NOTFOUND) nPos = 0; SwAddRenameEntryDialog* pDlg = new SwAddRenameEntryDialog(pButton, bRename, m_pNewData->aDBColumnHeaders); if(bRename) { String aTemp = m_aFieldsLB.GetEntry(nPos); pDlg->SetFieldName(aTemp); } if(RET_OK == pDlg->Execute()) { String sNew = pDlg->GetFieldName(); if(bRename) { m_pNewData->aDBColumnHeaders[nPos] = sNew; m_aFieldsLB.RemoveEntry(nPos); } else { if ( m_aFieldsLB.GetSelectEntryPos() != LISTBOX_ENTRY_NOTFOUND ) ++nPos; // append the new entry behind the selected //add the new column m_pNewData->aDBColumnHeaders.insert(m_pNewData->aDBColumnHeaders.begin() + nPos, sNew); //add a new entry into all data arrays String sTemp; ::std::vector< ::std::vector< ::rtl::OUString > >::iterator aDataIter; for( aDataIter = m_pNewData->aDBData.begin(); aDataIter != m_pNewData->aDBData.end(); ++aDataIter) aDataIter->insert(aDataIter->begin() + nPos, sTemp); } m_aFieldsLB.InsertEntry(sNew, nPos); m_aFieldsLB.SelectEntryPos(nPos); } delete pDlg; UpdateButtons(); return 0; } /*-- 13.04.2004 15:02:14--------------------------------------------------- -----------------------------------------------------------------------*/ IMPL_LINK(SwCustomizeAddressListDialog, DeleteHdl_Impl, PushButton*, EMPTYARG) { USHORT nPos = m_aFieldsLB.GetSelectEntryPos(); m_aFieldsLB.RemoveEntry(m_aFieldsLB.GetSelectEntryPos()); m_aFieldsLB.SelectEntryPos(nPos > m_aFieldsLB.GetEntryCount() - 1 ? nPos - 1 : nPos); //remove the column m_pNewData->aDBColumnHeaders.erase(m_pNewData->aDBColumnHeaders.begin() + nPos); //remove the data ::std::vector< ::std::vector< ::rtl::OUString > >::iterator aDataIter; for( aDataIter = m_pNewData->aDBData.begin(); aDataIter != m_pNewData->aDBData.end(); ++aDataIter) aDataIter->erase(aDataIter->begin() + nPos); UpdateButtons(); return 0; } /*-- 13.04.2004 15:02:15--------------------------------------------------- -----------------------------------------------------------------------*/ IMPL_LINK(SwCustomizeAddressListDialog, UpDownHdl_Impl, PushButton*, pButton) { USHORT nPos; USHORT nOldPos = nPos = m_aFieldsLB.GetSelectEntryPos(); String aTemp = m_aFieldsLB.GetEntry(nPos); m_aFieldsLB.RemoveEntry( nPos ); if(pButton == &m_aUpPB) --nPos; else ++nPos; m_aFieldsLB.InsertEntry(aTemp, nPos); m_aFieldsLB.SelectEntryPos(nPos); //align m_pNewData ::rtl::OUString sHeader = m_pNewData->aDBColumnHeaders[nOldPos]; m_pNewData->aDBColumnHeaders.erase(m_pNewData->aDBColumnHeaders.begin() + nOldPos); m_pNewData->aDBColumnHeaders.insert(m_pNewData->aDBColumnHeaders.begin() + nPos, sHeader); ::std::vector< ::std::vector< ::rtl::OUString > >::iterator aDataIter; for( aDataIter = m_pNewData->aDBData.begin(); aDataIter != m_pNewData->aDBData.end(); ++aDataIter) { ::rtl::OUString sData = (*aDataIter)[nOldPos]; aDataIter->erase(aDataIter->begin() + nOldPos); aDataIter->insert(aDataIter->begin() + nPos, sData); } UpdateButtons(); return 0; } /*-- 19.04.2004 14:51:49--------------------------------------------------- -----------------------------------------------------------------------*/ void SwCustomizeAddressListDialog::UpdateButtons() { USHORT nPos = m_aFieldsLB.GetSelectEntryPos(); USHORT nEntries = m_aFieldsLB.GetEntryCount(); m_aUpPB.Enable(nPos > 0 && nEntries > 0); m_aDownPB.Enable(nPos < nEntries -1); m_aDeletePB.Enable(nEntries > 0); m_aRenamePB.Enable(nEntries > 0); } /*-- 19.04.2004 14:51:49--------------------------------------------------- -----------------------------------------------------------------------*/ SwCSVData* SwCustomizeAddressListDialog::GetNewData() { return m_pNewData; } /*-- 13.04.2004 13:48:41--------------------------------------------------- -----------------------------------------------------------------------*/ SwAddRenameEntryDialog::SwAddRenameEntryDialog( Window* pParent, bool bRename, const ::std::vector< ::rtl::OUString >& rCSVHeader) : SfxModalDialog(pParent, SW_RES(DLG_MM_ADD_RENAME_ENTRY)), #ifdef MSC #pragma warning (disable : 4355) #endif m_aFieldNameFT( this, SW_RES( FT_FIELDNAME)), m_aFieldNameED( this, SW_RES( ED_FIELDNAME)), m_aOK( this, SW_RES( PB_OK)), m_aCancel( this, SW_RES( PB_CANCEL)), m_aHelp( this, SW_RES( PB_HELP)), #ifdef MSC #pragma warning (default : 4355) #endif m_rCSVHeader(rCSVHeader) { if(bRename) SetText(String(SW_RES(ST_RENAME_TITLE))); else m_aOK.SetText(String(SW_RES(ST_ADD_BUTTON))); FreeResource(); m_aFieldNameED.SetModifyHdl(LINK(this, SwAddRenameEntryDialog, ModifyHdl_Impl)); ModifyHdl_Impl( &m_aFieldNameED ); } /*-- 13.04.2004 13:48:41--------------------------------------------------- -----------------------------------------------------------------------*/ SwAddRenameEntryDialog::~SwAddRenameEntryDialog() { } /*-- 19.04.2004 15:31:34--------------------------------------------------- -----------------------------------------------------------------------*/ IMPL_LINK(SwAddRenameEntryDialog, ModifyHdl_Impl, Edit*, pEdit) { ::rtl::OUString sEntry = pEdit->GetText(); BOOL bFound = sEntry.getLength() ? FALSE : TRUE; if(!bFound) { ::std::vector< ::rtl::OUString >::const_iterator aHeaderIter; for(aHeaderIter = m_rCSVHeader.begin(); aHeaderIter != m_rCSVHeader.end(); ++aHeaderIter) if(*aHeaderIter == sEntry) { bFound = TRUE; break; } } m_aOK.Enable(!bFound); return 0; } <commit_msg>INTEGRATION: CWS changefileheader (1.9.242); FILE MERGED 2008/04/01 15:58:32 thb 1.9.242.3: #i85898# Stripping all external header guards 2008/04/01 12:55:06 thb 1.9.242.2: #i85898# Stripping all external header guards 2008/03/31 16:57:00 rt 1.9.242.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: customizeaddresslistdialog.cxx,v $ * $Revision: 1.10 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #ifdef SW_DLLIMPLEMENTATION #undef SW_DLLIMPLEMENTATION #endif #include <swtypes.hxx> #include <customizeaddresslistdialog.hxx> #include <createaddresslistdialog.hxx> #include <vcl/scrbar.hxx> #include <vcl/msgbox.hxx> #include <customizeaddresslistdialog.hrc> #include <dbui.hrc> #include <helpid.h> /*-- 13.04.2004 14:27:21--------------------------------------------------- -----------------------------------------------------------------------*/ SwCustomizeAddressListDialog::SwCustomizeAddressListDialog( Window* pParent, const SwCSVData& rOldData) : SfxModalDialog(pParent, SW_RES(DLG_MM_CUSTOMIZE_ADDRESS_LIST)), #ifdef MSC #pragma warning (disable : 4355) #endif m_aFieldsFT( this, SW_RES( FT_FIELDS)), m_aFieldsLB( this, SW_RES( LB_FIELDS)), m_aAddPB( this, SW_RES( PB_ADD)), m_aDeletePB( this, SW_RES( PB_DELETE)), m_aRenamePB( this, SW_RES( PB_RENAME)), m_aUpPB( this, SW_RES( PB_UP)), m_aDownPB( this, SW_RES( PB_DOWN)), m_aSeparatorFL( this, SW_RES( FL_SEPARATOR)), m_aOK( this, SW_RES( PB_OK)), m_aCancel( this, SW_RES( PB_CANCEL)), m_aHelp( this, SW_RES( PB_HELP)), #ifdef MSC #pragma warning (default : 4355) #endif m_pNewData( new SwCSVData(rOldData)) { FreeResource(); m_aFieldsLB.SetSelectHdl(LINK(this, SwCustomizeAddressListDialog, ListBoxSelectHdl_Impl)); Link aAddRenameLk = LINK(this, SwCustomizeAddressListDialog, AddRenameHdl_Impl ); m_aAddPB.SetClickHdl(aAddRenameLk); m_aRenamePB.SetClickHdl(aAddRenameLk); m_aDeletePB.SetClickHdl(LINK(this, SwCustomizeAddressListDialog, DeleteHdl_Impl )); Link aUpDownLk = LINK(this, SwCustomizeAddressListDialog, UpDownHdl_Impl); m_aUpPB.SetClickHdl(aUpDownLk); m_aDownPB.SetClickHdl(aUpDownLk); ::std::vector< ::rtl::OUString >::iterator aHeaderIter; for(aHeaderIter = m_pNewData->aDBColumnHeaders.begin(); aHeaderIter != m_pNewData->aDBColumnHeaders.end(); ++aHeaderIter) m_aFieldsLB.InsertEntry(*aHeaderIter); m_aFieldsLB.SelectEntryPos(0); UpdateButtons(); } /*-- 13.04.2004 14:34:07--------------------------------------------------- -----------------------------------------------------------------------*/ SwCustomizeAddressListDialog::~SwCustomizeAddressListDialog() { } /*-- 12.08.2004 12:58:00--------------------------------------------------- -----------------------------------------------------------------------*/ IMPL_LINK(SwCustomizeAddressListDialog, ListBoxSelectHdl_Impl, ListBox*, EMPTYARG) { UpdateButtons(); return 0; } /*-- 13.04.2004 15:02:14--------------------------------------------------- -----------------------------------------------------------------------*/ IMPL_LINK(SwCustomizeAddressListDialog, AddRenameHdl_Impl, PushButton*, pButton) { bool bRename = pButton == &m_aRenamePB; USHORT nPos = m_aFieldsLB.GetSelectEntryPos(); if(nPos == LISTBOX_ENTRY_NOTFOUND) nPos = 0; SwAddRenameEntryDialog* pDlg = new SwAddRenameEntryDialog(pButton, bRename, m_pNewData->aDBColumnHeaders); if(bRename) { String aTemp = m_aFieldsLB.GetEntry(nPos); pDlg->SetFieldName(aTemp); } if(RET_OK == pDlg->Execute()) { String sNew = pDlg->GetFieldName(); if(bRename) { m_pNewData->aDBColumnHeaders[nPos] = sNew; m_aFieldsLB.RemoveEntry(nPos); } else { if ( m_aFieldsLB.GetSelectEntryPos() != LISTBOX_ENTRY_NOTFOUND ) ++nPos; // append the new entry behind the selected //add the new column m_pNewData->aDBColumnHeaders.insert(m_pNewData->aDBColumnHeaders.begin() + nPos, sNew); //add a new entry into all data arrays String sTemp; ::std::vector< ::std::vector< ::rtl::OUString > >::iterator aDataIter; for( aDataIter = m_pNewData->aDBData.begin(); aDataIter != m_pNewData->aDBData.end(); ++aDataIter) aDataIter->insert(aDataIter->begin() + nPos, sTemp); } m_aFieldsLB.InsertEntry(sNew, nPos); m_aFieldsLB.SelectEntryPos(nPos); } delete pDlg; UpdateButtons(); return 0; } /*-- 13.04.2004 15:02:14--------------------------------------------------- -----------------------------------------------------------------------*/ IMPL_LINK(SwCustomizeAddressListDialog, DeleteHdl_Impl, PushButton*, EMPTYARG) { USHORT nPos = m_aFieldsLB.GetSelectEntryPos(); m_aFieldsLB.RemoveEntry(m_aFieldsLB.GetSelectEntryPos()); m_aFieldsLB.SelectEntryPos(nPos > m_aFieldsLB.GetEntryCount() - 1 ? nPos - 1 : nPos); //remove the column m_pNewData->aDBColumnHeaders.erase(m_pNewData->aDBColumnHeaders.begin() + nPos); //remove the data ::std::vector< ::std::vector< ::rtl::OUString > >::iterator aDataIter; for( aDataIter = m_pNewData->aDBData.begin(); aDataIter != m_pNewData->aDBData.end(); ++aDataIter) aDataIter->erase(aDataIter->begin() + nPos); UpdateButtons(); return 0; } /*-- 13.04.2004 15:02:15--------------------------------------------------- -----------------------------------------------------------------------*/ IMPL_LINK(SwCustomizeAddressListDialog, UpDownHdl_Impl, PushButton*, pButton) { USHORT nPos; USHORT nOldPos = nPos = m_aFieldsLB.GetSelectEntryPos(); String aTemp = m_aFieldsLB.GetEntry(nPos); m_aFieldsLB.RemoveEntry( nPos ); if(pButton == &m_aUpPB) --nPos; else ++nPos; m_aFieldsLB.InsertEntry(aTemp, nPos); m_aFieldsLB.SelectEntryPos(nPos); //align m_pNewData ::rtl::OUString sHeader = m_pNewData->aDBColumnHeaders[nOldPos]; m_pNewData->aDBColumnHeaders.erase(m_pNewData->aDBColumnHeaders.begin() + nOldPos); m_pNewData->aDBColumnHeaders.insert(m_pNewData->aDBColumnHeaders.begin() + nPos, sHeader); ::std::vector< ::std::vector< ::rtl::OUString > >::iterator aDataIter; for( aDataIter = m_pNewData->aDBData.begin(); aDataIter != m_pNewData->aDBData.end(); ++aDataIter) { ::rtl::OUString sData = (*aDataIter)[nOldPos]; aDataIter->erase(aDataIter->begin() + nOldPos); aDataIter->insert(aDataIter->begin() + nPos, sData); } UpdateButtons(); return 0; } /*-- 19.04.2004 14:51:49--------------------------------------------------- -----------------------------------------------------------------------*/ void SwCustomizeAddressListDialog::UpdateButtons() { USHORT nPos = m_aFieldsLB.GetSelectEntryPos(); USHORT nEntries = m_aFieldsLB.GetEntryCount(); m_aUpPB.Enable(nPos > 0 && nEntries > 0); m_aDownPB.Enable(nPos < nEntries -1); m_aDeletePB.Enable(nEntries > 0); m_aRenamePB.Enable(nEntries > 0); } /*-- 19.04.2004 14:51:49--------------------------------------------------- -----------------------------------------------------------------------*/ SwCSVData* SwCustomizeAddressListDialog::GetNewData() { return m_pNewData; } /*-- 13.04.2004 13:48:41--------------------------------------------------- -----------------------------------------------------------------------*/ SwAddRenameEntryDialog::SwAddRenameEntryDialog( Window* pParent, bool bRename, const ::std::vector< ::rtl::OUString >& rCSVHeader) : SfxModalDialog(pParent, SW_RES(DLG_MM_ADD_RENAME_ENTRY)), #ifdef MSC #pragma warning (disable : 4355) #endif m_aFieldNameFT( this, SW_RES( FT_FIELDNAME)), m_aFieldNameED( this, SW_RES( ED_FIELDNAME)), m_aOK( this, SW_RES( PB_OK)), m_aCancel( this, SW_RES( PB_CANCEL)), m_aHelp( this, SW_RES( PB_HELP)), #ifdef MSC #pragma warning (default : 4355) #endif m_rCSVHeader(rCSVHeader) { if(bRename) SetText(String(SW_RES(ST_RENAME_TITLE))); else m_aOK.SetText(String(SW_RES(ST_ADD_BUTTON))); FreeResource(); m_aFieldNameED.SetModifyHdl(LINK(this, SwAddRenameEntryDialog, ModifyHdl_Impl)); ModifyHdl_Impl( &m_aFieldNameED ); } /*-- 13.04.2004 13:48:41--------------------------------------------------- -----------------------------------------------------------------------*/ SwAddRenameEntryDialog::~SwAddRenameEntryDialog() { } /*-- 19.04.2004 15:31:34--------------------------------------------------- -----------------------------------------------------------------------*/ IMPL_LINK(SwAddRenameEntryDialog, ModifyHdl_Impl, Edit*, pEdit) { ::rtl::OUString sEntry = pEdit->GetText(); BOOL bFound = sEntry.getLength() ? FALSE : TRUE; if(!bFound) { ::std::vector< ::rtl::OUString >::const_iterator aHeaderIter; for(aHeaderIter = m_rCSVHeader.begin(); aHeaderIter != m_rCSVHeader.end(); ++aHeaderIter) if(*aHeaderIter == sEntry) { bFound = TRUE; break; } } m_aOK.Enable(!bFound); return 0; } <|endoftext|>
<commit_before>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "absl/base/casts.h" #include "tensorflow/compiler/xla/client/xla_builder.h" #include "tensorflow/compiler/xla/tests/client_library_test_base.h" #include "tensorflow/compiler/xla/tests/literal_test_util.h" #include "tensorflow/compiler/xla/tests/test_macros.h" namespace xla { namespace { class ExhaustiveF32ElementwiseOpTest : public ClientLibraryTestBase, public ::testing::WithParamInterface<std::pair<int64, int64>> { protected: ErrorSpec error_spec_{0.0001, 0.0001, /*relaxed_nans=*/true}; template <typename EnqueueOpTy> void ExhaustivelyTestF32Op(EnqueueOpTy enqueue_op, float (*evaluate_op)(float), std::pair<int64, int64> known_incorrect_range) { int64 begin, end; std::tie(begin, end) = GetParam(); int64 input_size = end - begin; LOG(INFO) << "Checking range [" << begin << ", " << end << ")"; XlaBuilder builder(TestName()); Literal input_literal = LiteralUtil::CreateFromDimensions(F32, {input_size}); for (int64 i = begin; i < end; i++) { if (i >= known_incorrect_range.first && i < known_incorrect_range.second) { // If the operation is known to be buggy on a specific input clamp that // input to 0 under the assumption that the op is at least correct on 0. input_literal.Set({i - begin}, 0.0f); } else { input_literal.Set({i - begin}, absl::bit_cast<float, int>(i)); } } TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<GlobalData> input_data, client_->TransferToServer(input_literal)); auto input = Parameter(&builder, 0, input_literal.shape(), "input"); enqueue_op(&builder, input); std::vector<float> expected_result; expected_result.reserve(input_size); for (int64 i = 0; i < input_size; i++) { expected_result.push_back(evaluate_op(input_literal.Get<float>({i}))); } ComputeAndCompareR1<float>(&builder, expected_result, {input_data.get()}, error_spec_); } }; XLA_TEST_P(ExhaustiveF32ElementwiseOpTest, LogF32) { #ifdef XLA_TEST_BACKEND_CPU // TODO(b/73141998): The vectorized Log implementation gives results outside // our error spec in this range (these numbers are bitwise representations of // floats expressed as a zero extended int64). std::pair<int64, int64> known_incorrect_range = {1, 8388608}; #else std::pair<int64, int64> known_incorrect_range = {0, 0}; #endif ExhaustivelyTestF32Op( [](XlaBuilder* builder, const XlaOp& input) { Log(input); }, std::log, known_incorrect_range); } XLA_TEST_P(ExhaustiveF32ElementwiseOpTest, ExpF32) { #ifdef XLA_TEST_BACKEND_CPU // TODO(b/73142289): The vectorized Exp implementation gives results outside // our error spec in this range (these numbers are bitwise representations of // floats expressed as a zero extended int64): std::pair<int64, int64> known_incorrect_range = {1107296256 + 11583654, 1107296256 + 11629080}; #else std::pair<int64, int64> known_incorrect_range = {0, 0}; #endif ExhaustivelyTestF32Op( [](XlaBuilder* builder, const XlaOp& input) { Exp(input); }, std::exp, known_incorrect_range); } XLA_TEST_P(ExhaustiveF32ElementwiseOpTest, TanhF32) { ExhaustivelyTestF32Op( [](XlaBuilder* builder, const XlaOp& input) { Tanh(input); }, std::tanh, /*known_incorrect_range=*/{0, 0}); } std::vector<std::pair<int64, int64>> CreateExhaustiveParameters() { // We break up the 2^32-element space into small'ish chunks to keep peak // memory usage low. std::vector<std::pair<int64, int64>> result; const int64 step = 1 << 25; for (int64 i = 0; i < (1l << 32); i += step) { result.push_back({i, i + step}); } return result; } INSTANTIATE_TEST_CASE_P(ExhaustiveF32ElementwiseOpTestInstance, ExhaustiveF32ElementwiseOpTest, ::testing::ValuesIn(CreateExhaustiveParameters())); } // namespace } // namespace xla <commit_msg>[XLA] Speed up exhaustive_f32_elementwise_op_test.<commit_after>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "absl/base/casts.h" #include "tensorflow/compiler/xla/client/xla_builder.h" #include "tensorflow/compiler/xla/tests/client_library_test_base.h" #include "tensorflow/compiler/xla/tests/literal_test_util.h" #include "tensorflow/compiler/xla/tests/test_macros.h" namespace xla { namespace { class ExhaustiveF32ElementwiseOpTest : public ClientLibraryTestBase, public ::testing::WithParamInterface<std::pair<int64, int64>> { protected: ErrorSpec error_spec_{0.0001, 0.0001, /*relaxed_nans=*/true}; template <typename EnqueueOpTy> void ExhaustivelyTestF32Op(EnqueueOpTy enqueue_op, float (*evaluate_op)(float), std::pair<int64, int64> known_incorrect_range) { int64 begin, end; std::tie(begin, end) = GetParam(); int64 input_size = end - begin; LOG(INFO) << "Checking range [" << begin << ", " << end << ")"; XlaBuilder builder(TestName()); Literal input_literal = LiteralUtil::CreateFromDimensions(F32, {input_size}); absl::Span<float> input_arr = input_literal.data<float>(); for (int64 i = begin; i < end; i++) { if (i >= known_incorrect_range.first && i < known_incorrect_range.second) { // If the operation is known to be buggy on a specific input clamp that // input to 0 under the assumption that the op is at least correct on 0. input_arr[i - begin] = 0; } else { input_arr[i - begin] = absl::bit_cast<float, int>(i); } } TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr<GlobalData> input_data, client_->TransferToServer(input_literal)); auto input = Parameter(&builder, 0, input_literal.shape(), "input"); enqueue_op(&builder, input); std::vector<float> expected_result; expected_result.reserve(input_size); for (int64 i = 0; i < input_size; i++) { expected_result.push_back(evaluate_op(input_arr[i])); } ComputeAndCompareR1<float>(&builder, expected_result, {input_data.get()}, error_spec_); } }; XLA_TEST_P(ExhaustiveF32ElementwiseOpTest, LogF32) { #ifdef XLA_TEST_BACKEND_CPU // TODO(b/73141998): The vectorized Log implementation gives results outside // our error spec in this range (these numbers are bitwise representations of // floats expressed as a zero extended int64). std::pair<int64, int64> known_incorrect_range = {1, 8388608}; #else std::pair<int64, int64> known_incorrect_range = {0, 0}; #endif ExhaustivelyTestF32Op( [](XlaBuilder* builder, const XlaOp& input) { Log(input); }, std::log, known_incorrect_range); } XLA_TEST_P(ExhaustiveF32ElementwiseOpTest, ExpF32) { #ifdef XLA_TEST_BACKEND_CPU // TODO(b/73142289): The vectorized Exp implementation gives results outside // our error spec in this range (these numbers are bitwise representations of // floats expressed as a zero extended int64): std::pair<int64, int64> known_incorrect_range = {1107296256 + 11583654, 1107296256 + 11629080}; #else std::pair<int64, int64> known_incorrect_range = {0, 0}; #endif ExhaustivelyTestF32Op( [](XlaBuilder* builder, const XlaOp& input) { Exp(input); }, std::exp, known_incorrect_range); } XLA_TEST_P(ExhaustiveF32ElementwiseOpTest, TanhF32) { ExhaustivelyTestF32Op( [](XlaBuilder* builder, const XlaOp& input) { Tanh(input); }, std::tanh, /*known_incorrect_range=*/{0, 0}); } std::vector<std::pair<int64, int64>> CreateExhaustiveParameters() { // We break up the 2^32-element space into small'ish chunks to keep peak // memory usage low. std::vector<std::pair<int64, int64>> result; const int64 step = 1 << 25; for (int64 i = 0; i < (1l << 32); i += step) { result.push_back({i, i + step}); } return result; } INSTANTIATE_TEST_CASE_P(ExhaustiveF32ElementwiseOpTestInstance, ExhaustiveF32ElementwiseOpTest, ::testing::ValuesIn(CreateExhaustiveParameters())); } // namespace } // namespace xla <|endoftext|>
<commit_before>/* nsjail - logging ----------------------------------------- Copyright 2014 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "logs.h" #include <errno.h> #include <fcntl.h> #include <getopt.h> #include <limits.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/types.h> #include <time.h> #include <unistd.h> #include "macros.h" #include "util.h" namespace logs { static int _log_fd = STDERR_FILENO; static bool _log_fd_isatty = true; static enum llevel_t _log_level = INFO; static bool _log_set = false; static void setDupLogFdOr(int fd, int orfd) { int saved_errno = errno; _log_fd = fcntl(fd, F_DUPFD_CLOEXEC, 0); if (_log_fd == -1) { _log_fd = fcntl(orfd, F_DUPFD_CLOEXEC, 0); } if (_log_fd == -1) { _log_fd = orfd; } _log_fd_isatty = (isatty(_log_fd) == 1); errno = saved_errno; } /* * Log to stderr by default. Use a dup()d fd, because in the future we'll associate the * connection socket with fd (0, 1, 2). */ __attribute__((constructor)) static void log_init(void) { setDupLogFdOr(STDERR_FILENO, STDERR_FILENO); } bool logSet() { return _log_set; } void logLevel(enum llevel_t ll) { _log_level = ll; } void logFile(const std::string& logfile) { _log_set = true; /* Close previous log_fd */ if (_log_fd > STDERR_FILENO) { close(_log_fd); } int newlogfd = TEMP_FAILURE_RETRY( open(logfile.c_str(), O_CREAT | O_RDWR | O_APPEND | O_CLOEXEC, 0640)); setDupLogFdOr(newlogfd, STDERR_FILENO); if (newlogfd == -1) { PLOG_W("Couldn't open logfile open('%s')", logfile.c_str()); } else { close(newlogfd); } } void logMsg(enum llevel_t ll, const char* fn, int ln, bool perr, const char* fmt, ...) { if (ll < _log_level) { return; } char strerr[512]; if (perr) { snprintf(strerr, sizeof(strerr), "%s", strerror(errno)); } struct { const char* const descr; const char* const prefix; const bool print_funcline; const bool print_time; } static const logLevels[] = { {"D", "\033[0;4m", true, true}, {"I", "\033[1m", false, true}, {"W", "\033[0;33m", true, true}, {"E", "\033[1;31m", true, true}, {"F", "\033[7;35m", true, true}, {"HR", "\033[0m", false, false}, {"HB", "\033[1m", false, false}, }; /* Start printing logs */ std::string msg; if (_log_fd_isatty) { msg.append(logLevels[ll].prefix); } if (ll != HELP && ll != HELP_BOLD) { msg.append("[").append(logLevels[ll].descr).append("]"); } if (logLevels[ll].print_time) { msg.append("[").append(util::timeToStr(time(NULL))).append("]"); } if (logLevels[ll].print_funcline) { msg.append("[") .append(std::to_string(getpid())) .append("] ") .append(fn) .append("():") .append(std::to_string(ln)); } char* strp; va_list args; va_start(args, fmt); int ret = vasprintf(&strp, fmt, args); va_end(args); if (ret == -1) { msg.append(" [logs internal]: MEMORY ALLOCATION ERROR"); } else { msg.append(" ").append(strp); free(strp); } if (perr) { msg.append(": ").append(strerr); } if (_log_fd_isatty) { msg.append("\033[0m"); } msg.append("\n"); /* End printing logs */ if (write(_log_fd, msg.c_str(), msg.size()) == -1) { dprintf(_log_fd, "%s", msg.c_str()); } if (ll == FATAL) { exit(0xff); } } void logStop(int sig) { LOG_I("Server stops due to fatal signal (%d) caught. Exiting", sig); } } // namespace logs <commit_msg>log: close previous log descriptor a bit later:<commit_after>/* nsjail - logging ----------------------------------------- Copyright 2014 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "logs.h" #include <errno.h> #include <fcntl.h> #include <getopt.h> #include <limits.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/types.h> #include <time.h> #include <unistd.h> #include "macros.h" #include "util.h" namespace logs { static int _log_fd = STDERR_FILENO; static bool _log_fd_isatty = true; static enum llevel_t _log_level = INFO; static bool _log_set = false; static void setDupLogFdOr(int fd, int orfd) { int saved_errno = errno; _log_fd = fcntl(fd, F_DUPFD_CLOEXEC, 0); if (_log_fd == -1) { _log_fd = fcntl(orfd, F_DUPFD_CLOEXEC, 0); } if (_log_fd == -1) { _log_fd = orfd; } _log_fd_isatty = (isatty(_log_fd) == 1); errno = saved_errno; } /* * Log to stderr by default. Use a dup()d fd, because in the future we'll associate the * connection socket with fd (0, 1, 2). */ __attribute__((constructor)) static void log_init(void) { setDupLogFdOr(STDERR_FILENO, STDERR_FILENO); } bool logSet() { return _log_set; } void logLevel(enum llevel_t ll) { _log_level = ll; } void logFile(const std::string& logfile) { _log_set = true; int newlogfd = TEMP_FAILURE_RETRY( open(logfile.c_str(), O_CREAT | O_RDWR | O_APPEND | O_CLOEXEC, 0640)); if (newlogfd == -1) { PLOG_W("Couldn't open logfile open('%s')", logfile.c_str()); return; } /* Close previous log_fd */ if (_log_fd > STDERR_FILENO) { close(_log_fd); } setDupLogFdOr(newlogfd, STDERR_FILENO); close(newlogfd); } void logMsg(enum llevel_t ll, const char* fn, int ln, bool perr, const char* fmt, ...) { if (ll < _log_level) { return; } char strerr[512]; if (perr) { snprintf(strerr, sizeof(strerr), "%s", strerror(errno)); } struct { const char* const descr; const char* const prefix; const bool print_funcline; const bool print_time; } static const logLevels[] = { {"D", "\033[0;4m", true, true}, {"I", "\033[1m", false, true}, {"W", "\033[0;33m", true, true}, {"E", "\033[1;31m", true, true}, {"F", "\033[7;35m", true, true}, {"HR", "\033[0m", false, false}, {"HB", "\033[1m", false, false}, }; /* Start printing logs */ std::string msg; if (_log_fd_isatty) { msg.append(logLevels[ll].prefix); } if (ll != HELP && ll != HELP_BOLD) { msg.append("[").append(logLevels[ll].descr).append("]"); } if (logLevels[ll].print_time) { msg.append("[").append(util::timeToStr(time(NULL))).append("]"); } if (logLevels[ll].print_funcline) { msg.append("[") .append(std::to_string(getpid())) .append("] ") .append(fn) .append("():") .append(std::to_string(ln)); } char* strp; va_list args; va_start(args, fmt); int ret = vasprintf(&strp, fmt, args); va_end(args); if (ret == -1) { msg.append(" [logs internal]: MEMORY ALLOCATION ERROR"); } else { msg.append(" ").append(strp); free(strp); } if (perr) { msg.append(": ").append(strerr); } if (_log_fd_isatty) { msg.append("\033[0m"); } msg.append("\n"); /* End printing logs */ if (write(_log_fd, msg.c_str(), msg.size()) == -1) { dprintf(_log_fd, "%s", msg.c_str()); } if (ll == FATAL) { exit(0xff); } } void logStop(int sig) { LOG_I("Server stops due to fatal signal (%d) caught. Exiting", sig); } } // namespace logs <|endoftext|>
<commit_before>// Implementation of a linear time algorithm that find the longest palindromic // substring of a given string. // // Author: Mikhail Andrenkov // Date: October 22, 2017 // // Credit: This code is a modification of a Manacher's Algorithm implementation // from https://algs4.cs.princeton.edu/53substring/Manacher.java.html //////////////////////////////////////////////////////////////////////////////// #include <algorithm> #include <iostream> #include <string> #include <vector> std::string expand(const std::string&); std::string solve(const std::string&); // Returns the longest palindromic substring of |given|. std::string solve(const std::string &given) { // Expand |given| to represent all palindrome indices. std::string pad = expand(given); // Declare an array to store the size of the longest palindromic substring // at each index of |pad|. std::vector<int> lps(pad.size(), 1); // The center of the active palindrome. int c = 0; // The rightmost index of the active palindrome. int r = 0; for (int i = 0; i < pad.size(); ++i) { // If |i| is past |r|, no previous LPS entries can be reused. if (i < r) { // Calculate the center index of the mirror palindrome. int j = 2*c - i; // Calculate the remaining distance in the active palindrome. int remaining = r - i + 1; lps[i] = std::min(remaining, lps[j]); } // Check if the current palindrome extends beyond the active palindrome. int length = lps[i]; while (i - length >= 0 && i + length < pad.size() && pad[i - length] == pad[i + length]) { ++lps[i]; ++length; } // Update the active palindrome if the current palindrome reaches further to the right. int i_r = i + lps[i] - 1; if (i_r > r) { c = i; r = i_r; } } // Extract the index and size of the longest palindromic substring. auto it = std::max_element(lps.begin(), lps.end()); int index = std::distance(lps.begin(), it); int size = lps[index]; // Convert the expanded index and size to match the original string. int start = (index + 1)/2 - size/2 int length = std::max(1, size - 1); return given.substr(start, length); } // Returns |given| with a "|" inserted before and after character. std::string expand(const std::string &given) { std::string buffer = "|"; for (const auto &c : given) { buffer += c; buffer += "|"; } return buffer; } // Execution entry point. int main() { // Declare some sanity-check tests. std::vector<std::pair<const std::string, const std::string>> tests = { {"", ""}, {"a", "a"}, {"aba", "aba"}, {"xabbab", "abba"}, {"xababay", "ababa"} }; for (const auto &p : tests) { std::string given = p.first; std::string want = p.second; std::string lps = solve(given); std::string result = want == lps ? "PASS" : "FAIL"; std::cout << result << ": "; std::cout << "solve(\"" << given << "\") = \"" << lps << "\""; std::cout << ", want \"" << want << "\".\n"; } return 0; } <commit_msg>Replaced missing semicolon.<commit_after>// Implementation of a linear time algorithm that find the longest palindromic // substring of a given string. // // Author: Mikhail Andrenkov // Date: October 22, 2017 // // Credit: This code is a modification of a Manacher's Algorithm implementation // from https://algs4.cs.princeton.edu/53substring/Manacher.java.html //////////////////////////////////////////////////////////////////////////////// #include <algorithm> #include <iostream> #include <string> #include <vector> std::string expand(const std::string&); std::string solve(const std::string&); // Returns the longest palindromic substring of |given|. std::string solve(const std::string &given) { // Expand |given| to represent all palindrome indices. std::string pad = expand(given); // Declare an array to store the size of the longest palindromic substring // at each index of |pad|. std::vector<int> lps(pad.size(), 1); // The center of the active palindrome. int c = 0; // The rightmost index of the active palindrome. int r = 0; for (int i = 0; i < pad.size(); ++i) { // If |i| is past |r|, no previous LPS entries can be reused. if (i < r) { // Calculate the center index of the mirror palindrome. int j = 2*c - i; // Calculate the remaining distance in the active palindrome. int remaining = r - i + 1; lps[i] = std::min(remaining, lps[j]); } // Check if the current palindrome extends beyond the active palindrome. int length = lps[i]; while (i - length >= 0 && i + length < pad.size() && pad[i - length] == pad[i + length]) { ++lps[i]; ++length; } // Update the active palindrome if the current palindrome reaches further to the right. int i_r = i + lps[i] - 1; if (i_r > r) { c = i; r = i_r; } } // Extract the index and size of the longest palindromic substring. auto it = std::max_element(lps.begin(), lps.end()); int index = std::distance(lps.begin(), it); int size = lps[index]; // Convert the expanded index and size to match the original string. int start = (index + 1)/2 - size/2; int length = std::max(1, size - 1); return given.substr(start, length); } // Returns |given| with a "|" inserted before and after character. std::string expand(const std::string &given) { std::string buffer = "|"; for (const auto &c : given) { buffer += c; buffer += "|"; } return buffer; } // Execution entry point. int main() { // Declare some sanity-check tests. std::vector<std::pair<const std::string, const std::string>> tests = { {"", ""}, {"a", "a"}, {"aba", "aba"}, {"xabbab", "abba"}, {"xababay", "ababa"} }; for (const auto &p : tests) { std::string given = p.first; std::string want = p.second; std::string lps = solve(given); std::string result = want == lps ? "PASS" : "FAIL"; std::cout << result << ": "; std::cout << "solve(\"" << given << "\") = \"" << lps << "\""; std::cout << ", want \"" << want << "\".\n"; } return 0; } <|endoftext|>
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <os> #include <net/inet4> #include <statman> #include <profile> #include <cstdio> #include <timers> #define CLIENT_PORT 1337 #define SERVER_PORT 1338 #define NCAT_RECEIVE_PORT 9000 #define SEND_BUF_LEN 1300 #define SERVER_TEST_LEN 10 #define PACKETS_PER_INTERVAL 50000 using namespace net::ip4; uint64_t packets_rx{0}; uint64_t packets_tx{0}; uint64_t initial_packets_rx{0}; uint64_t initial_packets_tx{0}; uint64_t prev_packets_rx{0}; uint64_t prev_packets_tx{0}; uint64_t total_packets_rx{0}; uint64_t total_packets_tx{0}; uint64_t data_len{0}; bool timestamps{true}; bool first_time{true}; bool data_received{false}; std::chrono::milliseconds dack{40}; uint64_t first_ts = 0; uint64_t sample_ts = 0; uint64_t last_ts = 0; struct activity { void reset() { } void print(activity& other) { auto tdiff = total - other.total; auto sdiff = asleep - other.asleep; if (tdiff > 0) { double idle = sdiff / (float) tdiff; printf("* CPU was %.2f%% idle\n", idle * 100.0); } } uint64_t total; uint64_t asleep; }; activity activity_before; activity activity_after; void init_sample_stats() { data_len = 0; initial_packets_rx = Statman::get().get_by_name("eth0.ethernet.packets_rx").get_uint64(); initial_packets_tx = Statman::get().get_by_name("eth0.ethernet.packets_tx").get_uint64(); prev_packets_rx = initial_packets_rx; prev_packets_tx = initial_packets_tx; first_ts = OS::nanos_since_boot(); sample_ts = last_ts = first_ts; activity_before.reset(); } void measure_sample_stats() { static uint64_t diff; auto prev_diff = diff; diff = last_ts - first_ts; activity_after.reset(); activity_after.print(activity_before); uint64_t now_rx = Statman::get().get_by_name("eth0.ethernet.packets_rx").get_uint64(); uint64_t now_tx = Statman::get().get_by_name("eth0.ethernet.packets_tx").get_uint64(); packets_rx = now_rx - prev_packets_rx; packets_tx = now_tx - prev_packets_tx; prev_packets_rx = now_rx; prev_packets_tx = now_tx; total_packets_rx = now_rx - initial_packets_rx; total_packets_tx = now_tx - initial_packets_tx; printf("-------------------Start-----------------\n"); printf("Packets RX [%llu] TX [%llu]\n", packets_rx, packets_tx); printf("Total Packets RX [%llu] TX [%llu]\n", total_packets_rx, total_packets_tx); double prev_durs = ((double) (diff - prev_diff) / 1000000000L); double total_durs = ((double)diff) / 1000000000L; double mbits = (data_len/(1024*1024)*8) / total_durs; printf("Duration: %.2fs, Total Duration: %.2fs, " " Payload: %lld MB %.2f MBit/s\n\n", prev_durs, total_durs, data_len /(1024*1024), mbits); printf("-------------------End-------------------\n"); } void send_cb() { data_len += SEND_BUF_LEN; } void send_data(auto &client, auto &inet) { for (size_t i = 0; i < PACKETS_PER_INTERVAL; i++) { const char c = 'A' + (i % 26); std::string buff(SEND_BUF_LEN, c); client.sendto(inet.gateway(), NCAT_RECEIVE_PORT, buff.data(), buff.size(), send_cb); } sample_ts = last_ts; last_ts = OS::nanos_since_boot(); printf("Done sending data\n"); } void Service::start(const std::string& input) { #ifdef USERSPACE_LINUX extern void create_network_device(int N, const char* route, const char* ip); create_network_device(0, "10.0.0.0/24", "10.0.0.1"); // Get the first IP stack configured from config.json auto& inet = net::Super_stack::get<net::IP4>(0); inet.network_config({10,0,0,42}, {255,255,255,0}, {10,0,0,1}); #else auto& inet = net::Super_stack::get<net::IP4>(0); #endif auto& udp = inet.udp(); if (input.find("client") != std::string::npos) { auto& client = udp.bind(CLIENT_PORT); printf("Running as Client\n"); init_sample_stats(); printf("Sending to %s!\n", inet.gateway().str().c_str()); send_data(client, inet); int timer = Timers::periodic(1s, 2s, [&timer, &inet, &client] (uint32_t) { static int secs = 0; measure_sample_stats(); send_data(client, inet); /* Run the test for 10 seconds */ if (secs++ == 10) { Timers::stop(timer); printf("Stopping test\n"); } }); } else { auto& server = udp.bind(SERVER_PORT); printf("Running as Server. Waiting for data...\n"); server.on_read( [&server](auto addr, auto port, const char* buf, int len) { auto data = std::string(buf, len); using namespace std::chrono; if (first_time) { printf("Received data..\n"); init_sample_stats(); first_time = false; } //CHECK(1, "Getting UDP data from %s: %d -> %s", // addr.str().c_str(), port, data.c_str()); data_len += data.size(); data_received = true; sample_ts = last_ts; last_ts = OS::nanos_since_boot(); }); Timers::periodic(5s, 5s, [] (uint32_t) { if (data_received) { measure_sample_stats(); data_received = false; } }); } } <commit_msg>examples: UDP perf now compiles<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <os> #include <net/inet4> #include <statman> #include <profile> #include <cstdio> #include <timers> #define CLIENT_PORT 1337 #define SERVER_PORT 1338 #define NCAT_RECEIVE_PORT 9000 #define SEND_BUF_LEN 1300 #define SERVER_TEST_LEN 10 #define PACKETS_PER_INTERVAL 50000 using namespace net::ip4; uint64_t packets_rx{0}; uint64_t packets_tx{0}; uint64_t initial_packets_rx{0}; uint64_t initial_packets_tx{0}; uint64_t prev_packets_rx{0}; uint64_t prev_packets_tx{0}; uint64_t total_packets_rx{0}; uint64_t total_packets_tx{0}; uint64_t data_len{0}; bool timestamps{true}; bool first_time{true}; bool data_received{false}; std::chrono::milliseconds dack{40}; uint64_t first_ts = 0; uint64_t sample_ts = 0; uint64_t last_ts = 0; struct activity { void reset() { } void print(activity& other) { auto tdiff = total - other.total; auto sdiff = asleep - other.asleep; if (tdiff > 0) { double idle = sdiff / (float) tdiff; printf("* CPU was %.2f%% idle\n", idle * 100.0); } } uint64_t total; uint64_t asleep; }; activity activity_before; activity activity_after; void init_sample_stats() { data_len = 0; initial_packets_rx = Statman::get().get_by_name("eth0.ethernet.packets_rx").get_uint64(); initial_packets_tx = Statman::get().get_by_name("eth0.ethernet.packets_tx").get_uint64(); prev_packets_rx = initial_packets_rx; prev_packets_tx = initial_packets_tx; first_ts = OS::nanos_since_boot(); sample_ts = last_ts = first_ts; activity_before.reset(); } void measure_sample_stats() { static uint64_t diff; auto prev_diff = diff; diff = last_ts - first_ts; activity_after.reset(); activity_after.print(activity_before); uint64_t now_rx = Statman::get().get_by_name("eth0.ethernet.packets_rx").get_uint64(); uint64_t now_tx = Statman::get().get_by_name("eth0.ethernet.packets_tx").get_uint64(); packets_rx = now_rx - prev_packets_rx; packets_tx = now_tx - prev_packets_tx; prev_packets_rx = now_rx; prev_packets_tx = now_tx; total_packets_rx = now_rx - initial_packets_rx; total_packets_tx = now_tx - initial_packets_tx; printf("-------------------Start-----------------\n"); printf("Packets RX [%llu] TX [%llu]\n", packets_rx, packets_tx); printf("Total Packets RX [%llu] TX [%llu]\n", total_packets_rx, total_packets_tx); double prev_durs = ((double) (diff - prev_diff) / 1000000000L); double total_durs = ((double)diff) / 1000000000L; double mbits = (data_len/(1024*1024)*8) / total_durs; printf("Duration: %.2fs, Total Duration: %.2fs, " " Payload: %lld MB %.2f MBit/s\n\n", prev_durs, total_durs, data_len /(1024*1024), mbits); printf("-------------------End-------------------\n"); } void send_cb() { data_len += SEND_BUF_LEN; } void send_data(net::UDPSocket& client, net::Inet<net::IP4>& inet) { for (size_t i = 0; i < PACKETS_PER_INTERVAL; i++) { const char c = 'A' + (i % 26); std::string buff(SEND_BUF_LEN, c); client.sendto(inet.gateway(), NCAT_RECEIVE_PORT, buff.data(), buff.size(), send_cb); } sample_ts = last_ts; last_ts = OS::nanos_since_boot(); printf("Done sending data\n"); } void Service::start(const std::string& input) { #ifdef USERSPACE_LINUX extern void create_network_device(int N, const char* route, const char* ip); create_network_device(0, "10.0.0.0/24", "10.0.0.1"); // Get the first IP stack configured from config.json auto& inet = net::Super_stack::get<net::IP4>(0); inet.network_config({10,0,0,42}, {255,255,255,0}, {10,0,0,1}); #else auto& inet = net::Super_stack::get<net::IP4>(0); #endif auto& udp = inet.udp(); if (input.find("client") != std::string::npos) { auto& client = udp.bind(CLIENT_PORT); printf("Running as Client\n"); init_sample_stats(); printf("Sending to %s!\n", inet.gateway().str().c_str()); send_data(client, inet); int timer = Timers::periodic(1s, 2s, [&timer, &inet, &client] (uint32_t) { static int secs = 0; measure_sample_stats(); send_data(client, inet); /* Run the test for 10 seconds */ if (secs++ == 10) { Timers::stop(timer); printf("Stopping test\n"); } }); } else { auto& server = udp.bind(SERVER_PORT); printf("Running as Server. Waiting for data...\n"); server.on_read( []([[maybe_unused]]auto addr, [[maybe_unused]]auto port, const char* buf, int len) { auto data = std::string(buf, len); using namespace std::chrono; if (first_time) { printf("Received data..\n"); init_sample_stats(); first_time = false; } //CHECK(1, "Getting UDP data from %s: %d -> %s", // addr.str().c_str(), port, data.c_str()); data_len += data.size(); data_received = true; sample_ts = last_ts; last_ts = OS::nanos_since_boot(); }); Timers::periodic(5s, 5s, [] (uint32_t) { if (data_received) { measure_sample_stats(); data_received = false; } }); } } <|endoftext|>
<commit_before>//===- AsmMatcherEmitter.cpp - Generate an assembly matcher ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This tablegen backend emits a target specifier matcher for converting parsed // assembly operands in the MCInst structures. // //===----------------------------------------------------------------------===// #include "AsmMatcherEmitter.h" #include "CodeGenTarget.h" #include "Record.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Debug.h" #include <set> #include <list> using namespace llvm; /// FlattenVariants - Flatten an .td file assembly string by selecting the /// variant at index \arg N. static std::string FlattenVariants(const std::string &AsmString, unsigned N) { StringRef Cur = AsmString; std::string Res = ""; for (;;) { // Add the prefix until the next '{', and split out the contents in the // braces. std::pair<StringRef, StringRef> Inner, Split = Cur.split('{'); Res += Split.first; if (Split.second.empty()) break; Inner = Split.second.split('}'); // Select the Nth variant (or empty). StringRef Selection = Inner.first; for (unsigned i = 0; i != N; ++i) Selection = Selection.split('|').second; Res += Selection.split('|').first; Cur = Inner.second; } return Res; } /// TokenizeAsmString - Tokenize a simplified assembly string. static void TokenizeAsmString(const std::string &AsmString, SmallVectorImpl<StringRef> &Tokens) { unsigned Prev = 0; bool InTok = true; for (unsigned i = 0, e = AsmString.size(); i != e; ++i) { switch (AsmString[i]) { case '*': case '!': case ' ': case '\t': case ',': if (InTok) { Tokens.push_back(StringRef(&AsmString[Prev], i - Prev)); InTok = false; } if (AsmString[i] == '*' || AsmString[i] == '!') Tokens.push_back(StringRef(&AsmString[i], 1)); Prev = i + 1; break; default: InTok = true; } } if (InTok && Prev != AsmString.size()) Tokens.push_back(StringRef(&AsmString[Prev], AsmString.size() - Prev)); } void AsmMatcherEmitter::run(raw_ostream &OS) { CodeGenTarget Target; const std::vector<CodeGenRegister> &Registers = Target.getRegisters(); Record *AsmParser = Target.getAsmParser(); std::string ClassName = AsmParser->getValueAsString("AsmParserClassName"); std::string Namespace = Registers[0].TheDef->getValueAsString("Namespace"); EmitSourceFileHeader("Assembly Matcher Source Fragment", OS); // Emit the function to match a register name to number. OS << "bool " << Target.getName() << ClassName << "::MatchRegisterName(const StringRef &Name, unsigned &RegNo) {\n"; // FIXME: TableGen should have a fast string matcher generator. for (unsigned i = 0, e = Registers.size(); i != e; ++i) { const CodeGenRegister &Reg = Registers[i]; if (Reg.TheDef->getValueAsString("AsmName").empty()) continue; OS << " if (Name == \"" << Reg.TheDef->getValueAsString("AsmName") << "\")\n" << " return RegNo=" << i + 1 << ", false;\n"; } OS << " return true;\n"; OS << "}\n"; // Emit the function to match instructions. std::vector<const CodeGenInstruction*> NumberedInstructions; Target.getInstructionsByEnumValue(NumberedInstructions); std::list<std::string> MatchFns; OS << "\n"; const std::map<std::string, CodeGenInstruction> &Instructions = Target.getInstructions(); for (std::map<std::string, CodeGenInstruction>::const_iterator it = Instructions.begin(), ie = Instructions.end(); it != ie; ++it) { const CodeGenInstruction &CGI = it->second; // Ignore psuedo ops. // // FIXME: This is a hack. if (const RecordVal *Form = CGI.TheDef->getValue("Form")) if (Form->getValue()->getAsString() == "Pseudo") continue; // Ignore instructions with no .s string. // // FIXME: What are these? if (CGI.AsmString.empty()) continue; // FIXME: Hack; ignore "lock". if (StringRef(CGI.AsmString).startswith("lock")) continue; // FIXME: Hack. #if 0 if (1 && it->first != "SUB8mr") continue; #endif std::string Flattened = FlattenVariants(CGI.AsmString, 0); SmallVector<StringRef, 8> Tokens; TokenizeAsmString(Flattened, Tokens); DEBUG({ outs() << it->first << " -- flattened:\"" << Flattened << "\", tokens:["; for (unsigned i = 0, e = Tokens.size(); i != e; ++i) { outs() << Tokens[i]; if (i + 1 != e) outs() << ", "; } outs() << "]\n"; for (unsigned i = 0, e = CGI.OperandList.size(); i != e; ++i) { const CodeGenInstruction::OperandInfo &OI = CGI.OperandList[i]; outs() << " op[" << i << "] = " << OI.Name << " " << OI.Rec->getName() << " (" << OI.MIOperandNo << ", " << OI.MINumOperands << ")\n"; } }); // FIXME: Ignore non-literal tokens. if (std::find(Tokens[0].begin(), Tokens[0].end(), '$') != Tokens[0].end()) continue; std::string FnName = "Match_" + Target.getName() + "_Inst_" + it->first; MatchFns.push_back(FnName); OS << "static bool " << FnName << "(const StringRef &Name," << " SmallVectorImpl<X86Operand> &Operands," << " MCInst &Inst) {\n\n"; OS << " // Match name.\n"; OS << " if (Name != \"" << Tokens[0] << "\")\n"; OS << " return true;\n\n"; OS << " // Match number of operands.\n"; OS << " if (Operands.size() != " << Tokens.size() - 1 << ")\n"; OS << " return true;\n\n"; // Compute the total number of MCOperands. // // FIXME: Isn't this somewhere else? unsigned NumMIOperands = 0; for (unsigned i = 0, e = CGI.OperandList.size(); i != e; ++i) { const CodeGenInstruction::OperandInfo &OI = CGI.OperandList[i]; NumMIOperands = std::max(NumMIOperands, OI.MIOperandNo + OI.MINumOperands); } std::set<unsigned> MatchedOperands; // This the list of operands we need to fill in. if (NumMIOperands) OS << " MCOperand Ops[" << NumMIOperands << "];\n\n"; unsigned ParsedOpIdx = 0; for (unsigned i = 1, e = Tokens.size(); i < e; ++i) { // FIXME: Can only match simple operands. if (Tokens[i][0] != '$') { OS << " // FIXME: unable to match token: '" << Tokens[i] << "'!\n"; OS << " return true;\n\n"; continue; } // Map this token to an operand. FIXME: Move elsewhere. unsigned Idx; try { Idx = CGI.getOperandNamed(Tokens[i].substr(1)); } catch(...) { OS << " // FIXME: unable to find operand: '" << Tokens[i] << "'!\n"; OS << " return true;\n\n"; continue; } // FIXME: Each match routine should always end up filling the same number // of operands, we should just check that the number matches what the // match routine expects here instead of passing it. We can do this once // we start generating the class match functions. const CodeGenInstruction::OperandInfo &OI = CGI.OperandList[Idx]; // Track that we have matched these operands. // // FIXME: Verify that we don't parse something to the same operand twice. for (unsigned j = 0; j != OI.MINumOperands; ++j) MatchedOperands.insert(OI.MIOperandNo + j); OS << " // Match '" << Tokens[i] << "' (parsed operand " << ParsedOpIdx << ") to machine operands [" << OI.MIOperandNo << ", " << OI.MIOperandNo + OI.MINumOperands << ").\n"; OS << " if (Match_" << Target.getName() << "_Op_" << OI.Rec->getName() << "(" << "Operands[" << ParsedOpIdx << "], " << "&Ops[" << OI.MIOperandNo << "], " << OI.MINumOperands << "))\n"; OS << " return true;\n\n"; ++ParsedOpIdx; } // Generate code to construct the MCInst. OS << " // Construct MCInst.\n"; OS << " Inst.setOpcode(" << Target.getName() << "::" << it->first << ");\n"; for (unsigned i = 0, e = NumMIOperands; i != e; ++i) { // FIXME: Oops! Ignore this for now, the instruction should print ok. If // we need to evaluate the constraints. if (!MatchedOperands.count(i)) { OS << "\n"; OS << " // FIXME: Nothing matched Ops[" << i << "]!\n"; OS << " Ops[" << i << "] = MCOperand::CreateReg(0);\n"; OS << "\n"; } OS << " Inst.addOperand(Ops[" << i << "]);\n"; } OS << "\n"; OS << " return false;\n"; OS << "}\n\n"; } // Generate the top level match function. OS << "bool " << Target.getName() << ClassName << "::MatchInstruction(const StringRef &Name, " << "SmallVectorImpl<" << Target.getName() << "Operand> &Operands, " << "MCInst &Inst) {\n"; for (std::list<std::string>::iterator it = MatchFns.begin(), ie = MatchFns.end(); it != ie; ++it) { OS << " if (!" << *it << "(Name, Operands, Inst))\n"; OS << " return false;\n\n"; } OS << " return true;\n"; OS << "}\n\n"; } <commit_msg>TableGen / AsmMatcher: Tweaks to avoid generating completely bogus match functions. - Fix variant flattening when the variant embeds an operand reference.<commit_after>//===- AsmMatcherEmitter.cpp - Generate an assembly matcher ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This tablegen backend emits a target specifier matcher for converting parsed // assembly operands in the MCInst structures. // //===----------------------------------------------------------------------===// #include "AsmMatcherEmitter.h" #include "CodeGenTarget.h" #include "Record.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Debug.h" #include <set> #include <list> using namespace llvm; /// FlattenVariants - Flatten an .td file assembly string by selecting the /// variant at index \arg N. static std::string FlattenVariants(const std::string &AsmString, unsigned N) { StringRef Cur = AsmString; std::string Res = ""; for (;;) { // Find the start of the next variant string. size_t VariantsStart = 0; for (size_t e = Cur.size(); VariantsStart != e; ++VariantsStart) if (Cur[VariantsStart] == '{' && (VariantsStart == 0 || Cur[VariantsStart-1] != '$')) break; // Add the prefix to the result. Res += Cur.slice(0, VariantsStart); if (VariantsStart == Cur.size()) break; ++VariantsStart; // Skip the '{'. // Scan to the end of the variants string. size_t VariantsEnd = VariantsStart; unsigned NestedBraces = 1; for (size_t e = Cur.size(); VariantsEnd != e; ++VariantsEnd) { if (Cur[VariantsEnd] == '}') { if (--NestedBraces == 0) break; } else if (Cur[VariantsEnd] == '{') ++NestedBraces; } // Select the Nth variant (or empty). StringRef Selection = Cur.slice(VariantsStart, VariantsEnd); for (unsigned i = 0; i != N; ++i) Selection = Selection.split('|').second; Res += Selection.split('|').first; assert(VariantsEnd != Cur.size() && "Unterminated variants in assembly string!"); Cur = Cur.substr(VariantsEnd + 1); } return Res; } /// TokenizeAsmString - Tokenize a simplified assembly string. static void TokenizeAsmString(const std::string &AsmString, SmallVectorImpl<StringRef> &Tokens) { unsigned Prev = 0; bool InTok = true; for (unsigned i = 0, e = AsmString.size(); i != e; ++i) { switch (AsmString[i]) { case '*': case '!': case ' ': case '\t': case ',': if (InTok) { Tokens.push_back(StringRef(&AsmString[Prev], i - Prev)); InTok = false; } if (AsmString[i] == '*' || AsmString[i] == '!') Tokens.push_back(StringRef(&AsmString[i], 1)); Prev = i + 1; break; default: InTok = true; } } if (InTok && Prev != AsmString.size()) Tokens.push_back(StringRef(&AsmString[Prev], AsmString.size() - Prev)); } void AsmMatcherEmitter::run(raw_ostream &OS) { CodeGenTarget Target; const std::vector<CodeGenRegister> &Registers = Target.getRegisters(); Record *AsmParser = Target.getAsmParser(); std::string ClassName = AsmParser->getValueAsString("AsmParserClassName"); std::string Namespace = Registers[0].TheDef->getValueAsString("Namespace"); EmitSourceFileHeader("Assembly Matcher Source Fragment", OS); // Emit the function to match a register name to number. OS << "bool " << Target.getName() << ClassName << "::MatchRegisterName(const StringRef &Name, unsigned &RegNo) {\n"; // FIXME: TableGen should have a fast string matcher generator. for (unsigned i = 0, e = Registers.size(); i != e; ++i) { const CodeGenRegister &Reg = Registers[i]; if (Reg.TheDef->getValueAsString("AsmName").empty()) continue; OS << " if (Name == \"" << Reg.TheDef->getValueAsString("AsmName") << "\")\n" << " return RegNo=" << i + 1 << ", false;\n"; } OS << " return true;\n"; OS << "}\n"; // Emit the function to match instructions. std::vector<const CodeGenInstruction*> NumberedInstructions; Target.getInstructionsByEnumValue(NumberedInstructions); std::list<std::string> MatchFns; OS << "\n"; const std::map<std::string, CodeGenInstruction> &Instructions = Target.getInstructions(); for (std::map<std::string, CodeGenInstruction>::const_iterator it = Instructions.begin(), ie = Instructions.end(); it != ie; ++it) { const CodeGenInstruction &CGI = it->second; // Ignore psuedo ops. // // FIXME: This is a hack. if (const RecordVal *Form = CGI.TheDef->getValue("Form")) if (Form->getValue()->getAsString() == "Pseudo") continue; // Ignore "PHI" node. // // FIXME: This is also a hack. if (it->first == "PHI") continue; // Ignore instructions with no .s string. // // FIXME: What are these? if (CGI.AsmString.empty()) continue; // FIXME: Hack; ignore "lock". if (StringRef(CGI.AsmString).startswith("lock")) continue; std::string Flattened = FlattenVariants(CGI.AsmString, 0); SmallVector<StringRef, 8> Tokens; TokenizeAsmString(Flattened, Tokens); DEBUG({ outs() << it->first << " -- flattened:\"" << Flattened << "\", tokens:["; for (unsigned i = 0, e = Tokens.size(); i != e; ++i) { outs() << Tokens[i]; if (i + 1 != e) outs() << ", "; } outs() << "]\n"; for (unsigned i = 0, e = CGI.OperandList.size(); i != e; ++i) { const CodeGenInstruction::OperandInfo &OI = CGI.OperandList[i]; outs() << " op[" << i << "] = " << OI.Name << " " << OI.Rec->getName() << " (" << OI.MIOperandNo << ", " << OI.MINumOperands << ")\n"; } }); // FIXME: Ignore prefixes with non-literal tokens. if (std::find(Tokens[0].begin(), Tokens[0].end(), '$') != Tokens[0].end()) { DEBUG({ errs() << "warning: '" << it->first << "': " << "ignoring non-literal token '" << Tokens[0] << "', \n"; }); continue; } // Ignore instructions with subreg specifiers, these are always fake // instructions for simplifying codegen. // // FIXME: Is this true? // // Also, we ignore instructions which reference the operand multiple times; // this implies a constraint we would not currently honor. These are // currently always fake instructions for simplifying codegen. // // FIXME: Encode this assumption in the .td, so we can error out here. std::set<std::string> OperandNames; unsigned HasSubreg = 0, HasDuplicate = 0; for (unsigned i = 1, e = Tokens.size(); i < e; ++i) { if (Tokens[i][0] == '$' && std::find(Tokens[i].begin(), Tokens[i].end(), ':') != Tokens[i].end()) HasSubreg = i; if (Tokens[i][0] == '$' && !OperandNames.insert(Tokens[i]).second) HasDuplicate = i; } if (HasSubreg) { DEBUG({ errs() << "warning: '" << it->first << "': " << "ignoring instruction; operand with subreg attribute '" << Tokens[HasSubreg] << "', \n"; }); continue; } else if (HasDuplicate) { DEBUG({ errs() << "warning: '" << it->first << "': " << "ignoring instruction; tied operand '" << Tokens[HasSubreg] << "', \n"; }); continue; } std::string FnName = "Match_" + Target.getName() + "_Inst_" + it->first; MatchFns.push_back(FnName); OS << "static bool " << FnName << "(const StringRef &Name," << " SmallVectorImpl<X86Operand> &Operands," << " MCInst &Inst) {\n\n"; OS << " // Match name.\n"; OS << " if (Name != \"" << Tokens[0] << "\")\n"; OS << " return true;\n\n"; OS << " // Match number of operands.\n"; OS << " if (Operands.size() != " << Tokens.size() - 1 << ")\n"; OS << " return true;\n\n"; // Compute the total number of MCOperands. // // FIXME: Isn't this somewhere else? unsigned NumMIOperands = 0; for (unsigned i = 0, e = CGI.OperandList.size(); i != e; ++i) { const CodeGenInstruction::OperandInfo &OI = CGI.OperandList[i]; NumMIOperands = std::max(NumMIOperands, OI.MIOperandNo + OI.MINumOperands); } std::set<unsigned> MatchedOperands; // This the list of operands we need to fill in. if (NumMIOperands) OS << " MCOperand Ops[" << NumMIOperands << "];\n\n"; unsigned ParsedOpIdx = 0; for (unsigned i = 1, e = Tokens.size(); i < e; ++i) { // FIXME: Can only match simple operands. if (Tokens[i][0] != '$') { OS << " // FIXME: unable to match token: '" << Tokens[i] << "'!\n"; OS << " return true;\n\n"; continue; } // Map this token to an operand. FIXME: Move elsewhere. unsigned Idx; try { Idx = CGI.getOperandNamed(Tokens[i].substr(1)); } catch(...) { OS << " // FIXME: unable to find operand: '" << Tokens[i] << "'!\n"; OS << " return true;\n\n"; continue; } // FIXME: Each match routine should always end up filling the same number // of operands, we should just check that the number matches what the // match routine expects here instead of passing it. We can do this once // we start generating the class match functions. const CodeGenInstruction::OperandInfo &OI = CGI.OperandList[Idx]; // Track that we have matched these operands. // // FIXME: Verify that we don't parse something to the same operand twice. for (unsigned j = 0; j != OI.MINumOperands; ++j) MatchedOperands.insert(OI.MIOperandNo + j); OS << " // Match '" << Tokens[i] << "' (parsed operand " << ParsedOpIdx << ") to machine operands [" << OI.MIOperandNo << ", " << OI.MIOperandNo + OI.MINumOperands << ").\n"; OS << " if (Match_" << Target.getName() << "_Op_" << OI.Rec->getName() << "(" << "Operands[" << ParsedOpIdx << "], " << "&Ops[" << OI.MIOperandNo << "], " << OI.MINumOperands << "))\n"; OS << " return true;\n\n"; ++ParsedOpIdx; } // Generate code to construct the MCInst. OS << " // Construct MCInst.\n"; OS << " Inst.setOpcode(" << Target.getName() << "::" << it->first << ");\n"; for (unsigned i = 0, e = NumMIOperands; i != e; ++i) { // FIXME: Oops! Ignore this for now, the instruction should print ok. If // we need to evaluate the constraints. if (!MatchedOperands.count(i)) { OS << "\n"; OS << " // FIXME: Nothing matched Ops[" << i << "]!\n"; OS << " Ops[" << i << "] = MCOperand::CreateReg(0);\n"; OS << "\n"; } OS << " Inst.addOperand(Ops[" << i << "]);\n"; } OS << "\n"; OS << " return false;\n"; OS << "}\n\n"; } // Generate the top level match function. OS << "bool " << Target.getName() << ClassName << "::MatchInstruction(const StringRef &Name, " << "SmallVectorImpl<" << Target.getName() << "Operand> &Operands, " << "MCInst &Inst) {\n"; for (std::list<std::string>::iterator it = MatchFns.begin(), ie = MatchFns.end(); it != ie; ++it) { OS << " if (!" << *it << "(Name, Operands, Inst))\n"; OS << " return false;\n\n"; } OS << " return true;\n"; OS << "}\n\n"; } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. Some parts of this code are derived from ITK. See ITKCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include <iostream> #include <sstream> #include "itkRescaleIntensityImageFilter.h" #include "itkVectorIndexSelectionCastImageFilter.h" #include "otbImageToVectorImageCastFilter.h" #include "otbImageList.h" #include "otbImage.h" #include "otbVectorImage.h" #include "otbImageFileReader.h" #include "otbStreamingHistogramVectorImageFilter.h" #include "otbStreamingMinMaxVectorImageFilter.h" #include "otbGlobalHistogramEqualizationFilter.h" #include "otbVectorImageColorSpaceTransformFilter.h" #include "otbImageFileWriter.h" #include "otbImageListToVectorImageFilter.h" #include "otbRGBToYUVFunctor.h" #include "otbYUVToRGBFunctor.h" #include "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" namespace otb { namespace Wrapper { class ColorHistogramEqualize : public Application { public: typedef ColorHistogramEqualize Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; itkNewMacro(Self); itkTypeMacro(Self, otb::Application); typedef unsigned int PixelType; // typedef unsigned int OutputPixelType; typedef otb::Image<PixelType, 2> ImageType; typedef otb::VectorImage<PixelType, 2> VectorType; typedef otb::VectorImage<float, 2> FloatVectorType; typedef FloatVectorType::PixelType FloatVectorPixelType; typedef VectorType::PixelType VectorPixelType; typedef otb::Image<float, 2> FloatImageType; typedef otb::StreamingMinMaxVectorImageFilter<VectorType> StreamingMinMaxFilterType; typedef itk::VariableLengthVector<PixelType> MinMaxPixelType; typedef otb::StreamingHistogramVectorImageFilter<VectorType> HistogramFilterType; typedef typename itk::NumericTraits< float >::RealType MeasurementType; typedef itk::Statistics::Histogram< MeasurementType, 1 > HistogramType; typedef otb::ObjectList< HistogramType > HistogramListType; typedef otb::GlobalHistogramEqualizationFilter<ImageType, FloatImageType> HistogramEqualizationFilterType; typedef otb::Functor::RGBToYUVFunctor<VectorPixelType,FloatVectorPixelType> YUVFunctorType; typedef otb::VectorImageColorSpaceTransformFilter<VectorType, FloatVectorType, YUVFunctorType> YUVFilterType; typedef itk::VectorIndexSelectionCastImageFilter<FloatVectorType, FloatImageType> VectorCastFilterType; typedef itk::RescaleIntensityImageFilter<FloatImageType, ImageType> FloatRescalerType; typedef otb::ImageToVectorImageCastFilter<ImageType,VectorType> ImageToVectorImageCastFilterType; typedef otb::ImageList<FloatImageType> ImageListType; typedef otb::ImageListToVectorImageFilter<ImageListType, FloatVectorType > ListConcatenerFilterType; typedef otb::Functor::YUVToRGBFunctor<FloatVectorPixelType,VectorPixelType> YUVToRGBFunctorType; typedef otb::VectorImageColorSpaceTransformFilter<FloatVectorType, VectorType, YUVToRGBFunctorType> RGBFilterType; private: void DoInit() { this->SetHaveInXML(false); this->SetHaveOutXML(false); SetName("ColorHistogramEqualize"); SetDescription("Perform Histogram Equalization of Multi band raster image"); SetDocName("ColorHistogramEqualize"); SetDocLongDescription("Perform Histogram Equalization of Multi band raster image"); SetDocLimitations("None"); SetDocAuthors("OTB-Team"); SetDocSeeAlso("ColorSpaceTransform"); AddDocTag("Contrast Enhancement"); AddDocTag("color histogram"); AddParameter(ParameterType_InputImage, "in", "Input Image"); MandatoryOn("in"); AddParameter(ParameterType_String, "type", "Pixel type of input image(eg: uint8/uint16)"); SetParameterString("type", "uint8"); AddParameter(ParameterType_OutputImage, "out", "Output Image"); MandatoryOn("out"); AddParameter(ParameterType_Int, "red", "Red channel"); SetDefaultParameterInt("red", 0); AddParameter(ParameterType_Int, "green", "Green channel"); SetDefaultParameterInt("green", 1); AddParameter(ParameterType_Int, "blue", "Blue channel"); SetDefaultParameterInt("blue", 2); SetDocExampleParameterValue("in", "rgbInput.tif"); SetDocExampleParameterValue("type", "uint8"); SetDocExampleParameterValue("out", "yuvOutput.tif"); } void DoUpdateParameters() { } void DoExecute() { std::string inputFilename = GetParameterAsString("in"); std::string type = GetParameterString("type"); itk::Index<3> index; index[0] = GetParameterInt("red"); ; index[1] = GetParameterInt("green"); index[2] = GetParameterInt("blue"); int delta = 128; if (type == "uint8") delta = 128; else if(type == "uint16") delta = 32768; else if(type == "float") delta = 0.5; else std::cerr << "Unknown pixel type\n"; typedef otb::ImageFileReader<VectorType> VectorReaderType; VectorReaderType::Pointer vectorReader = VectorReaderType::New(); vectorReader->SetFileName(inputFilename); vectorReader->Update(); StreamingMinMaxFilterType::Pointer filterMinMax = StreamingMinMaxFilterType::New(); filterMinMax->SetInput( vectorReader->GetOutput() ); filterMinMax->Update(); MinMaxPixelType maxPixel = filterMinMax->GetMaximum(); MinMaxPixelType::ValueType maxPixelValue; maxPixelValue = maxPixel[0]; //must get the maximum of all bands maxPixelValue = (maxPixelValue < 255) ? 255 : maxPixelValue; //shouldnt go below 255 in case of uint8 YUVFilterType::Pointer yuvFilter = YUVFilterType::New(); yuvFilter->SetInput(vectorReader->GetOutput()); yuvFilter->SetDelta(delta); yuvFilter->SetRGBIndex(index); yuvFilter->Update(); VectorCastFilterType::Pointer vectorCastFilter1 = VectorCastFilterType::New(); vectorCastFilter1->SetInput(yuvFilter->GetOutput()); vectorCastFilter1->SetIndex(0); vectorCastFilter1->Update(); FloatRescalerType::Pointer floatRescaler1 = FloatRescalerType::New(); floatRescaler1->SetOutputMinimum(0); floatRescaler1->SetOutputMaximum(maxPixelValue ); floatRescaler1->SetInput(vectorCastFilter1->GetOutput()); //Y floatRescaler1->Update(); VectorCastFilterType::Pointer vectorCastFilter2 = VectorCastFilterType::New(); vectorCastFilter2->SetInput(yuvFilter->GetOutput()); vectorCastFilter2->SetIndex(1); vectorCastFilter2->Update(); VectorCastFilterType::Pointer vectorCastFilter3 = VectorCastFilterType::New(); vectorCastFilter3->SetInput(yuvFilter->GetOutput()); vectorCastFilter3->SetIndex(2); vectorCastFilter3->Update(); ImageToVectorImageCastFilterType::Pointer imageToVectorFilter = ImageToVectorImageCastFilterType::New(); imageToVectorFilter->SetInput(floatRescaler1->GetOutput()); imageToVectorFilter->Update(); VectorType::Pointer histInput; ImageType::Pointer histEquInput; histInput = imageToVectorFilter->GetOutput(); //conversion of indexFilter->out histEquInput = floatRescaler1->GetOutput(); filterMinMax->SetInput( histInput ); filterMinMax->Update(); MinMaxPixelType minPixel = filterMinMax->GetMinimum(); maxPixel = filterMinMax->GetMaximum(); unsigned int binestimate = maxPixel[0]- minPixel[0] + 1; unsigned int bins = (binestimate < 256)? 256: binestimate; otbAppLogDEBUG( << "MaxPixelValue = " << maxPixelValue <<std::endl ); otbAppLogDEBUG( << "Delta = " << delta << std::endl ); otbAppLogDEBUG( << "Bins = " << bins << std::endl ); HistogramFilterType::Pointer histogramFilter = HistogramFilterType::New(); histogramFilter->SetInput( histInput ); histogramFilter->GetFilter()->SetHistogramMin( minPixel ); histogramFilter->GetFilter()->SetHistogramMax( maxPixel ); histogramFilter->GetFilter()->SetNumberOfBins( bins ); histogramFilter->GetFilter()->SetSubSamplingRate( 1 ); histogramFilter->Update(); HistogramEqualizationFilterType::Pointer histEqualizeFilter = HistogramEqualizationFilterType::New(); HistogramListType::Pointer histList = histogramFilter->GetHistogramList(); for( HistogramListType::ConstIterator it( histList->Begin() ); it!=histList->End(); ++it ) { HistogramType::Pointer hist = it.Get(); histEqualizeFilter->SetInput( histEquInput ); // histEqualizeFilter->SetMinimumRange(0); histEqualizeFilter->SetMinimumRange(minPixel[0]); histEqualizeFilter->SetHistogram(hist); histEqualizeFilter->Update(); /* typedef otb::ImageFileWriter< VectorType > FloatImageWriterType; typedef otb::ImageFileWriter< FloatImageType > ImageWriterType; ImageWriterType::Pointer outImageWriter = ImageWriterType::New(); outImageWriter->SetFileName(strm.str()); outImageWriter->SetInput(histEqualizeFilter->GetOutput()); outImageWriter->Update(); std::cerr << strm.str() << "\n"; */ } ///YCbCr -> rgb ImageListType::Pointer m_ImageList = ImageListType::New(); m_ImageList->PushBack( histEqualizeFilter->GetOutput() ); //Y band equalized m_ImageList->PushBack( vectorCastFilter2->GetOutput() ); //Cb m_ImageList->PushBack( vectorCastFilter3->GetOutput() ); //Cr ListConcatenerFilterType::Pointer m_Concatener = ListConcatenerFilterType::New(); m_Concatener->SetInput( m_ImageList ); m_Concatener->Update(); RGBFilterType::Pointer rgbFilter = RGBFilterType::New(); rgbFilter->SetMaxPixelValue(maxPixelValue); rgbFilter->SetDelta(delta); rgbFilter->SetInput(m_Concatener->GetOutput()); rgbFilter->SetRGBIndex(index); rgbFilter->Update(); SetParameterOutputImage("out", rgbFilter->GetOutput()); } }; } //end namespace Wrapper } //end namespace otb OTB_APPLICATION_EXPORT(otb::Wrapper::ColorHistogramEqualize) <commit_msg>COMP: do not use typename outside template class<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. Some parts of this code are derived from ITK. See ITKCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include <iostream> #include <sstream> #include "itkRescaleIntensityImageFilter.h" #include "itkVectorIndexSelectionCastImageFilter.h" #include "otbImageToVectorImageCastFilter.h" #include "otbImageList.h" #include "otbImage.h" #include "otbVectorImage.h" #include "otbImageFileReader.h" #include "otbStreamingHistogramVectorImageFilter.h" #include "otbStreamingMinMaxVectorImageFilter.h" #include "otbGlobalHistogramEqualizationFilter.h" #include "otbVectorImageColorSpaceTransformFilter.h" #include "otbImageFileWriter.h" #include "otbImageListToVectorImageFilter.h" #include "otbRGBToYUVFunctor.h" #include "otbYUVToRGBFunctor.h" #include "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" namespace otb { namespace Wrapper { class ColorHistogramEqualize : public Application { public: typedef ColorHistogramEqualize Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; itkNewMacro(Self); itkTypeMacro(Self, otb::Application); typedef unsigned int PixelType; // typedef unsigned int OutputPixelType; typedef otb::Image<PixelType, 2> ImageType; typedef otb::VectorImage<PixelType, 2> VectorType; typedef otb::VectorImage<float, 2> FloatVectorType; typedef FloatVectorType::PixelType FloatVectorPixelType; typedef VectorType::PixelType VectorPixelType; typedef otb::Image<float, 2> FloatImageType; typedef otb::StreamingMinMaxVectorImageFilter<VectorType> StreamingMinMaxFilterType; typedef itk::VariableLengthVector<PixelType> MinMaxPixelType; typedef otb::StreamingHistogramVectorImageFilter<VectorType> HistogramFilterType; typedef itk::NumericTraits< float >::RealType MeasurementType; typedef itk::Statistics::Histogram< MeasurementType, 1 > HistogramType; typedef otb::ObjectList< HistogramType > HistogramListType; typedef otb::GlobalHistogramEqualizationFilter<ImageType, FloatImageType> HistogramEqualizationFilterType; typedef otb::Functor::RGBToYUVFunctor<VectorPixelType,FloatVectorPixelType> YUVFunctorType; typedef otb::VectorImageColorSpaceTransformFilter<VectorType, FloatVectorType, YUVFunctorType> YUVFilterType; typedef itk::VectorIndexSelectionCastImageFilter<FloatVectorType, FloatImageType> VectorCastFilterType; typedef itk::RescaleIntensityImageFilter<FloatImageType, ImageType> FloatRescalerType; typedef otb::ImageToVectorImageCastFilter<ImageType,VectorType> ImageToVectorImageCastFilterType; typedef otb::ImageList<FloatImageType> ImageListType; typedef otb::ImageListToVectorImageFilter<ImageListType, FloatVectorType > ListConcatenerFilterType; typedef otb::Functor::YUVToRGBFunctor<FloatVectorPixelType,VectorPixelType> YUVToRGBFunctorType; typedef otb::VectorImageColorSpaceTransformFilter<FloatVectorType, VectorType, YUVToRGBFunctorType> RGBFilterType; private: void DoInit() { this->SetHaveInXML(false); this->SetHaveOutXML(false); SetName("ColorHistogramEqualize"); SetDescription("Perform Histogram Equalization of Multi band raster image"); SetDocName("ColorHistogramEqualize"); SetDocLongDescription("Perform Histogram Equalization of Multi band raster image"); SetDocLimitations("None"); SetDocAuthors("OTB-Team"); SetDocSeeAlso("ColorSpaceTransform"); AddDocTag("Contrast Enhancement"); AddDocTag("color histogram"); AddParameter(ParameterType_InputImage, "in", "Input Image"); MandatoryOn("in"); AddParameter(ParameterType_String, "type", "Pixel type of input image(eg: uint8/uint16)"); SetParameterString("type", "uint8"); AddParameter(ParameterType_OutputImage, "out", "Output Image"); MandatoryOn("out"); AddParameter(ParameterType_Int, "red", "Red channel"); SetDefaultParameterInt("red", 0); AddParameter(ParameterType_Int, "green", "Green channel"); SetDefaultParameterInt("green", 1); AddParameter(ParameterType_Int, "blue", "Blue channel"); SetDefaultParameterInt("blue", 2); SetDocExampleParameterValue("in", "rgbInput.tif"); SetDocExampleParameterValue("type", "uint8"); SetDocExampleParameterValue("out", "yuvOutput.tif"); } void DoUpdateParameters() { } void DoExecute() { std::string inputFilename = GetParameterAsString("in"); std::string type = GetParameterString("type"); itk::Index<3> index; index[0] = GetParameterInt("red"); ; index[1] = GetParameterInt("green"); index[2] = GetParameterInt("blue"); int delta = 128; if (type == "uint8") delta = 128; else if(type == "uint16") delta = 32768; else if(type == "float") delta = 0.5; else std::cerr << "Unknown pixel type\n"; typedef otb::ImageFileReader<VectorType> VectorReaderType; VectorReaderType::Pointer vectorReader = VectorReaderType::New(); vectorReader->SetFileName(inputFilename); vectorReader->Update(); StreamingMinMaxFilterType::Pointer filterMinMax = StreamingMinMaxFilterType::New(); filterMinMax->SetInput( vectorReader->GetOutput() ); filterMinMax->Update(); MinMaxPixelType maxPixel = filterMinMax->GetMaximum(); MinMaxPixelType::ValueType maxPixelValue; maxPixelValue = maxPixel[0]; //must get the maximum of all bands maxPixelValue = (maxPixelValue < 255) ? 255 : maxPixelValue; //shouldnt go below 255 in case of uint8 YUVFilterType::Pointer yuvFilter = YUVFilterType::New(); yuvFilter->SetInput(vectorReader->GetOutput()); yuvFilter->SetDelta(delta); yuvFilter->SetRGBIndex(index); yuvFilter->Update(); VectorCastFilterType::Pointer vectorCastFilter1 = VectorCastFilterType::New(); vectorCastFilter1->SetInput(yuvFilter->GetOutput()); vectorCastFilter1->SetIndex(0); vectorCastFilter1->Update(); FloatRescalerType::Pointer floatRescaler1 = FloatRescalerType::New(); floatRescaler1->SetOutputMinimum(0); floatRescaler1->SetOutputMaximum(maxPixelValue ); floatRescaler1->SetInput(vectorCastFilter1->GetOutput()); //Y floatRescaler1->Update(); VectorCastFilterType::Pointer vectorCastFilter2 = VectorCastFilterType::New(); vectorCastFilter2->SetInput(yuvFilter->GetOutput()); vectorCastFilter2->SetIndex(1); vectorCastFilter2->Update(); VectorCastFilterType::Pointer vectorCastFilter3 = VectorCastFilterType::New(); vectorCastFilter3->SetInput(yuvFilter->GetOutput()); vectorCastFilter3->SetIndex(2); vectorCastFilter3->Update(); ImageToVectorImageCastFilterType::Pointer imageToVectorFilter = ImageToVectorImageCastFilterType::New(); imageToVectorFilter->SetInput(floatRescaler1->GetOutput()); imageToVectorFilter->Update(); VectorType::Pointer histInput; ImageType::Pointer histEquInput; histInput = imageToVectorFilter->GetOutput(); //conversion of indexFilter->out histEquInput = floatRescaler1->GetOutput(); filterMinMax->SetInput( histInput ); filterMinMax->Update(); MinMaxPixelType minPixel = filterMinMax->GetMinimum(); maxPixel = filterMinMax->GetMaximum(); unsigned int binestimate = maxPixel[0]- minPixel[0] + 1; unsigned int bins = (binestimate < 256)? 256: binestimate; otbAppLogDEBUG( << "MaxPixelValue = " << maxPixelValue <<std::endl ); otbAppLogDEBUG( << "Delta = " << delta << std::endl ); otbAppLogDEBUG( << "Bins = " << bins << std::endl ); HistogramFilterType::Pointer histogramFilter = HistogramFilterType::New(); histogramFilter->SetInput( histInput ); histogramFilter->GetFilter()->SetHistogramMin( minPixel ); histogramFilter->GetFilter()->SetHistogramMax( maxPixel ); histogramFilter->GetFilter()->SetNumberOfBins( bins ); histogramFilter->GetFilter()->SetSubSamplingRate( 1 ); histogramFilter->Update(); HistogramEqualizationFilterType::Pointer histEqualizeFilter = HistogramEqualizationFilterType::New(); HistogramListType::Pointer histList = histogramFilter->GetHistogramList(); for( HistogramListType::ConstIterator it( histList->Begin() ); it!=histList->End(); ++it ) { HistogramType::Pointer hist = it.Get(); histEqualizeFilter->SetInput( histEquInput ); // histEqualizeFilter->SetMinimumRange(0); histEqualizeFilter->SetMinimumRange(minPixel[0]); histEqualizeFilter->SetHistogram(hist); histEqualizeFilter->Update(); /* typedef otb::ImageFileWriter< VectorType > FloatImageWriterType; typedef otb::ImageFileWriter< FloatImageType > ImageWriterType; ImageWriterType::Pointer outImageWriter = ImageWriterType::New(); outImageWriter->SetFileName(strm.str()); outImageWriter->SetInput(histEqualizeFilter->GetOutput()); outImageWriter->Update(); std::cerr << strm.str() << "\n"; */ } ///YCbCr -> rgb ImageListType::Pointer m_ImageList = ImageListType::New(); m_ImageList->PushBack( histEqualizeFilter->GetOutput() ); //Y band equalized m_ImageList->PushBack( vectorCastFilter2->GetOutput() ); //Cb m_ImageList->PushBack( vectorCastFilter3->GetOutput() ); //Cr ListConcatenerFilterType::Pointer m_Concatener = ListConcatenerFilterType::New(); m_Concatener->SetInput( m_ImageList ); m_Concatener->Update(); RGBFilterType::Pointer rgbFilter = RGBFilterType::New(); rgbFilter->SetMaxPixelValue(maxPixelValue); rgbFilter->SetDelta(delta); rgbFilter->SetInput(m_Concatener->GetOutput()); rgbFilter->SetRGBIndex(index); rgbFilter->Update(); SetParameterOutputImage("out", rgbFilter->GetOutput()); } }; } //end namespace Wrapper } //end namespace otb OTB_APPLICATION_EXPORT(otb::Wrapper::ColorHistogramEqualize) <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2011, Willow Garage, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <pcl/recognition/hv/hv_papazov.h> /////////////////////////////////////////////////////////////////////////////////////////////////// template<typename ModelT, typename SceneT> void pcl::PapazovHV<ModelT, SceneT>::initialize () { // initialize mask... mask_.resize (complete_models_.size ()); for (size_t i = 0; i < complete_models_.size (); i++) mask_[i] = true; // initalize model for (size_t m = 0; m < complete_models_.size (); m++) { boost::shared_ptr <RecognitionModel> recog_model (new RecognitionModel); // voxelize model cloud recog_model->cloud_.reset (new pcl::PointCloud<ModelT>); recog_model->complete_cloud_.reset (new pcl::PointCloud<ModelT>); recog_model->id_ = static_cast<int> (m); pcl::VoxelGrid<ModelT> voxel_grid; voxel_grid.setInputCloud (visible_models_[m]); voxel_grid.setLeafSize (resolution_, resolution_, resolution_); voxel_grid.filter (*(recog_model->cloud_)); pcl::VoxelGrid<ModelT> voxel_grid_complete; voxel_grid_complete.setInputCloud (complete_models_[m]); voxel_grid_complete.setLeafSize (resolution_, resolution_, resolution_); voxel_grid_complete.filter (*(recog_model->complete_cloud_)); std::vector<int> explained_indices; std::vector<int> outliers; std::vector<int> nn_indices; std::vector<float> nn_distances; for (size_t i = 0; i < recog_model->cloud_->points.size (); i++) { if (!scene_downsampled_tree_->radiusSearch (recog_model->cloud_->points[i], inliers_threshold_, nn_indices, nn_distances, std::numeric_limits<int>::max ())) { outliers.push_back (static_cast<int> (i)); } else { for (size_t k = 0; k < nn_distances.size (); k++) { explained_indices.push_back (nn_indices[k]); //nn_indices[k] points to the scene } } } std::sort (explained_indices.begin (), explained_indices.end ()); explained_indices.erase (std::unique (explained_indices.begin (), explained_indices.end ()), explained_indices.end ()); recog_model->bad_information_ = static_cast<int> (outliers.size ()); if ((static_cast<float> (recog_model->bad_information_) / static_cast<float> (recog_model->complete_cloud_->points.size ())) <= penalty_threshold_ && (static_cast<float> (explained_indices.size ()) / static_cast<float> (recog_model->complete_cloud_->points.size ())) >= support_threshold_) { recog_model->explained_ = explained_indices; recognition_models_.push_back (recog_model); // update explained_by_RM_, add 1 for (size_t i = 0; i < explained_indices.size (); i++) { explained_by_RM_[explained_indices[i]]++; points_explained_by_rm_[explained_indices[i]].push_back (recog_model); } } else { mask_[m] = false; // the model didnt survive the sequential check... } } } /////////////////////////////////////////////////////////////////////////////////////////////////// template<typename ModelT, typename SceneT> void pcl::PapazovHV<ModelT, SceneT>::nonMaximaSuppresion () { // iterate over all vertices of the graph and check if they have a better neighbour, then remove that vertex typedef typename boost::graph_traits<Graph>::vertex_iterator VertexIterator; VertexIterator vi, vi_end, next; boost::tie (vi, vi_end) = boost::vertices (conflict_graph_); for (next = vi; next != vi_end; next++) { const typename Graph::vertex_descriptor v = boost::vertex (*next, conflict_graph_); typename boost::graph_traits<Graph>::adjacency_iterator ai; typename boost::graph_traits<Graph>::adjacency_iterator ai_end; boost::shared_ptr<RecognitionModel> current = static_cast<boost::shared_ptr<RecognitionModel> > (graph_id_model_map_[int (v)]); bool a_better_one = false; for (tie (ai, ai_end) = boost::adjacent_vertices (v, conflict_graph_); (ai != ai_end) && !a_better_one; ++ai) { boost::shared_ptr<RecognitionModel> neighbour = static_cast<boost::shared_ptr<RecognitionModel> > (graph_id_model_map_[int (*ai)]); if (neighbour->explained_.size () >= current->explained_.size () && mask_[neighbour->id_]) { a_better_one = true; } } if (a_better_one) { mask_[current->id_] = false; } } } /////////////////////////////////////////////////////////////////////////////////////////////////// template<typename ModelT, typename SceneT> void pcl::PapazovHV<ModelT, SceneT>::buildConflictGraph () { // create vertices for the graph for (size_t i = 0; i < (recognition_models_.size ()); i++) { const typename Graph::vertex_descriptor v = boost::add_vertex (recognition_models_[i], conflict_graph_); graph_id_model_map_[int (v)] = static_cast<boost::shared_ptr<RecognitionModel> > (recognition_models_[i]); } // iterate over the remaining models and check for each one if there is a conflict with another one for (size_t i = 0; i < recognition_models_.size (); i++) { for (size_t j = i; j < recognition_models_.size (); j++) { if (i != j) { float n_conflicts = 0.f; // count scene points explained by both models for (size_t k = 0; k < explained_by_RM_.size (); k++) { if (explained_by_RM_[k] > 1) { // this point could be a conflict bool i_found = false; bool j_found = false; bool both_found = false; for (size_t kk = 0; (kk < points_explained_by_rm_[k].size ()) && !both_found; kk++) { if (points_explained_by_rm_[k][kk]->id_ == recognition_models_[i]->id_) i_found = true; if (points_explained_by_rm_[k][kk]->id_ == recognition_models_[j]->id_) j_found = true; if (i_found && j_found) both_found = true; } if (both_found) n_conflicts += 1.f; } } // check if number of points is big enough to create a conflict bool add_conflict = false; add_conflict = ((n_conflicts / static_cast<float> (recognition_models_[i]->complete_cloud_->points.size ())) > conflict_threshold_size_) || ((n_conflicts / static_cast<float> (recognition_models_[j]->complete_cloud_->points.size ())) > conflict_threshold_size_); if (add_conflict) { boost::add_edge (i, j, conflict_graph_); } } } } } /////////////////////////////////////////////////////////////////////////////////////////////////// template<typename ModelT, typename SceneT> void pcl::PapazovHV<ModelT, SceneT>::verify () { initialize(); buildConflictGraph (); nonMaximaSuppresion (); } <commit_msg>Use fully qualified boost::tie issue reported for boost 1.49 and Windows<commit_after>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2011, Willow Garage, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <pcl/recognition/hv/hv_papazov.h> /////////////////////////////////////////////////////////////////////////////////////////////////// template<typename ModelT, typename SceneT> void pcl::PapazovHV<ModelT, SceneT>::initialize () { // initialize mask... mask_.resize (complete_models_.size ()); for (size_t i = 0; i < complete_models_.size (); i++) mask_[i] = true; // initalize model for (size_t m = 0; m < complete_models_.size (); m++) { boost::shared_ptr <RecognitionModel> recog_model (new RecognitionModel); // voxelize model cloud recog_model->cloud_.reset (new pcl::PointCloud<ModelT>); recog_model->complete_cloud_.reset (new pcl::PointCloud<ModelT>); recog_model->id_ = static_cast<int> (m); pcl::VoxelGrid<ModelT> voxel_grid; voxel_grid.setInputCloud (visible_models_[m]); voxel_grid.setLeafSize (resolution_, resolution_, resolution_); voxel_grid.filter (*(recog_model->cloud_)); pcl::VoxelGrid<ModelT> voxel_grid_complete; voxel_grid_complete.setInputCloud (complete_models_[m]); voxel_grid_complete.setLeafSize (resolution_, resolution_, resolution_); voxel_grid_complete.filter (*(recog_model->complete_cloud_)); std::vector<int> explained_indices; std::vector<int> outliers; std::vector<int> nn_indices; std::vector<float> nn_distances; for (size_t i = 0; i < recog_model->cloud_->points.size (); i++) { if (!scene_downsampled_tree_->radiusSearch (recog_model->cloud_->points[i], inliers_threshold_, nn_indices, nn_distances, std::numeric_limits<int>::max ())) { outliers.push_back (static_cast<int> (i)); } else { for (size_t k = 0; k < nn_distances.size (); k++) { explained_indices.push_back (nn_indices[k]); //nn_indices[k] points to the scene } } } std::sort (explained_indices.begin (), explained_indices.end ()); explained_indices.erase (std::unique (explained_indices.begin (), explained_indices.end ()), explained_indices.end ()); recog_model->bad_information_ = static_cast<int> (outliers.size ()); if ((static_cast<float> (recog_model->bad_information_) / static_cast<float> (recog_model->complete_cloud_->points.size ())) <= penalty_threshold_ && (static_cast<float> (explained_indices.size ()) / static_cast<float> (recog_model->complete_cloud_->points.size ())) >= support_threshold_) { recog_model->explained_ = explained_indices; recognition_models_.push_back (recog_model); // update explained_by_RM_, add 1 for (size_t i = 0; i < explained_indices.size (); i++) { explained_by_RM_[explained_indices[i]]++; points_explained_by_rm_[explained_indices[i]].push_back (recog_model); } } else { mask_[m] = false; // the model didnt survive the sequential check... } } } /////////////////////////////////////////////////////////////////////////////////////////////////// template<typename ModelT, typename SceneT> void pcl::PapazovHV<ModelT, SceneT>::nonMaximaSuppresion () { // iterate over all vertices of the graph and check if they have a better neighbour, then remove that vertex typedef typename boost::graph_traits<Graph>::vertex_iterator VertexIterator; VertexIterator vi, vi_end, next; boost::tie (vi, vi_end) = boost::vertices (conflict_graph_); for (next = vi; next != vi_end; next++) { const typename Graph::vertex_descriptor v = boost::vertex (*next, conflict_graph_); typename boost::graph_traits<Graph>::adjacency_iterator ai; typename boost::graph_traits<Graph>::adjacency_iterator ai_end; boost::shared_ptr<RecognitionModel> current = static_cast<boost::shared_ptr<RecognitionModel> > (graph_id_model_map_[int (v)]); bool a_better_one = false; for (boost::tie (ai, ai_end) = boost::adjacent_vertices (v, conflict_graph_); (ai != ai_end) && !a_better_one; ++ai) { boost::shared_ptr<RecognitionModel> neighbour = static_cast<boost::shared_ptr<RecognitionModel> > (graph_id_model_map_[int (*ai)]); if (neighbour->explained_.size () >= current->explained_.size () && mask_[neighbour->id_]) { a_better_one = true; } } if (a_better_one) { mask_[current->id_] = false; } } } /////////////////////////////////////////////////////////////////////////////////////////////////// template<typename ModelT, typename SceneT> void pcl::PapazovHV<ModelT, SceneT>::buildConflictGraph () { // create vertices for the graph for (size_t i = 0; i < (recognition_models_.size ()); i++) { const typename Graph::vertex_descriptor v = boost::add_vertex (recognition_models_[i], conflict_graph_); graph_id_model_map_[int (v)] = static_cast<boost::shared_ptr<RecognitionModel> > (recognition_models_[i]); } // iterate over the remaining models and check for each one if there is a conflict with another one for (size_t i = 0; i < recognition_models_.size (); i++) { for (size_t j = i; j < recognition_models_.size (); j++) { if (i != j) { float n_conflicts = 0.f; // count scene points explained by both models for (size_t k = 0; k < explained_by_RM_.size (); k++) { if (explained_by_RM_[k] > 1) { // this point could be a conflict bool i_found = false; bool j_found = false; bool both_found = false; for (size_t kk = 0; (kk < points_explained_by_rm_[k].size ()) && !both_found; kk++) { if (points_explained_by_rm_[k][kk]->id_ == recognition_models_[i]->id_) i_found = true; if (points_explained_by_rm_[k][kk]->id_ == recognition_models_[j]->id_) j_found = true; if (i_found && j_found) both_found = true; } if (both_found) n_conflicts += 1.f; } } // check if number of points is big enough to create a conflict bool add_conflict = false; add_conflict = ((n_conflicts / static_cast<float> (recognition_models_[i]->complete_cloud_->points.size ())) > conflict_threshold_size_) || ((n_conflicts / static_cast<float> (recognition_models_[j]->complete_cloud_->points.size ())) > conflict_threshold_size_); if (add_conflict) { boost::add_edge (i, j, conflict_graph_); } } } } } /////////////////////////////////////////////////////////////////////////////////////////////////// template<typename ModelT, typename SceneT> void pcl::PapazovHV<ModelT, SceneT>::verify () { initialize(); buildConflictGraph (); nonMaximaSuppresion (); } <|endoftext|>
<commit_before>#include "inputevent.h" #include <cassert> #include <iostream> #include <string> #include <sstream> extern "C" { #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/select.h> #include <fcntl.h> #include <sys/socket.h> #include <netdb.h> #include <err.h> } InputEvent::InputEvent() : eventId(SDL_RegisterEvents(1)), mutex(SDL_CreateMutex()) { assert(eventId >= 0); assert(mutex); } InputEvent::~InputEvent() { } void InputEvent::pushEvent(const Input &input) { //https://wiki.libsdl.org/SDL_UserEvent SDL_Event event; SDL_zero(event); event.type = eventId; event.user.code = 0; event.user.data1 = new Input(input); event.user.data2 = nullptr; SDL_PushEvent(&event); } void InputEvent::handleEvent(const SDL_Event &event, Radar& radar) { if (event.type == eventId) { Input* input = (Input*) event.user.data1; radar.addDistance(*input); delete input; } if (event.type == SDL_KEYDOWN) { SDL_Scancode code = event.key.keysym.scancode; //https://wiki.libsdl.org/SDLScancodeLookup if (code >= 4 && code <= 39) { lock(); addKey(SDL_GetScancodeName(event.key.keysym.scancode)[0]); unlock(); } } } void InputEvent::lock() { assert(SDL_LockMutex(mutex) == 0); } void InputEvent::unlock() { assert(SDL_UnlockMutex(mutex) == 0); } bool InputEvent::hasKey() { lock(); if (keys.size()) { return true; } else { unlock(); return false; } } void InputEvent::clear() { keys.clear(); } void InputEvent::addKey(char c) { keys.push_back(c); } int demoThread(void* data) { InputEvent* ie = (InputEvent*) data; for (unsigned i = 0; i < 450; ++i) { ie->pushEvent(Input(i % 360, 0.8)); SDL_Delay(30); } return 0; } typedef std::pair<InputEvent*, const char*> fileType; int fileThread(void* data) { fileType* in = (fileType*) data; InputEvent* ie = in->first; const char* path = in->second; int pipe = open(path, O_RDONLY, O_NONBLOCK, 0); if (pipe == -1) { perror("pipe"); return 0; } fd_set fds; FD_ZERO(&fds); while (true) { char input[20]; //Wait for input FD_SET(pipe, &fds); int s = select(pipe + 1, &fds, NULL, NULL, NULL); if (s < 0) { perror("select"); return 0; } int r = read(pipe, input, 20); if (r > 0) { std::string s(input); std::stringstream ss(s); int angle; float distance; ss >> angle >> distance; if (ss.good()) { ie->pushEvent(Input(angle, distance)); } } if (r < 0) { perror("read"); return 0; } } return 0; } typedef std::pair<InputEvent*, const char**> socketType; int socketThread(void* data) { socketType* in = (socketType*) data; InputEvent* ie = in->first; const char** argv = in->second; //getaddrinfo(3) struct addrinfo hints, *res, *res0; int error; int sock; const char *cause = NULL; memset(&hints, 0, sizeof(hints)); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_STREAM; error = getaddrinfo(argv[1], argv[2], &hints, &res0); if (error) { errx(1, "%s", gai_strerror(error)); /*NOTREACHED*/ } sock = -1; for (res = res0; res; res = res->ai_next) { sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol); if (sock < 0) { cause = "socket"; continue; } if (connect(sock, res->ai_addr, res->ai_addrlen) < 0) { cause = "connect"; close(sock); sock = -1; continue; } break; /* okay we got one */ } if (sock < 0) { err(1, "%s", cause); /*NOTREACHED*/ } freeaddrinfo(res0); std::string str; bool lastValid = false; unsigned nums = 0; while (true) { char input[4096] = ""; fd_set fds; timeval tv; //Wait for input FD_ZERO(&fds); FD_SET(sock, &fds); //Set waiting time of 10us tv.tv_sec = 0; tv.tv_usec = 10; int s = select(sock + 1, &fds, NULL, NULL, &tv); if (s < 0) { perror("select"); return 0; } if (s == 0) { if (ie->hasKey()) { std::cout << "SEND: " << ie->keys << std::endl; write(sock, ie->keys.c_str(), ie->keys.length()); ie->clear(); ie->unlock(); } } if (FD_ISSET(sock, &fds)) { int r = read(sock, input, 4096); if (r > 0) { for (unsigned i = 0; i < r; ++i) { char c = input[i]; if ( ('0' <= c && c <= '9') || c == '.') { str.push_back(c); lastValid = true; } if (lastValid && (c == ' ' || c == '\r' || c == '\n')) { str.push_back(' '); lastValid = false; nums ++; } } while (nums >= 2) { int angle; float distance; std::stringstream ss(str); ss >> angle >> distance; if (ss.good()) { //std::cout << "Input: " << angle << " " << distance << std::endl; ie->pushEvent(Input(angle, distance)); } std::string::size_type first = str.find(' ') + 1; str = str.substr(str.find(' ', first) + 1); nums -= 2; } } if (r < 0) { perror("read"); return 0; } } } close(sock); return 0; } SDL_Thread* InputEvent::demo() { return SDL_CreateThread(demoThread, "DemoThread", this); } SDL_Thread* InputEvent::fileInput(const char *path) { return SDL_CreateThread(fileThread, "FileThread", new fileType(this, path)); } SDL_Thread* InputEvent::socketInput(const char **argv) { return SDL_CreateThread(socketThread, "SocketThread", new socketType(this, argv)); } <commit_msg>Functioning version.<commit_after>#include "inputevent.h" #include <cassert> #include <iostream> #include <string> #include <sstream> extern "C" { #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/select.h> #include <fcntl.h> #include <sys/socket.h> #include <netdb.h> #include <err.h> } InputEvent::InputEvent() : eventId(SDL_RegisterEvents(1)), mutex(SDL_CreateMutex()) { assert(eventId >= 0); assert(mutex); } InputEvent::~InputEvent() { } void InputEvent::pushEvent(const Input &input) { //https://wiki.libsdl.org/SDL_UserEvent SDL_Event event; SDL_zero(event); event.type = eventId; event.user.code = 0; event.user.data1 = new Input(input); event.user.data2 = nullptr; SDL_PushEvent(&event); } void InputEvent::handleEvent(const SDL_Event &event, Radar& radar) { if (event.type == eventId) { Input* input = (Input*) event.user.data1; radar.addDistance(*input); delete input; } if (event.type == SDL_KEYDOWN) { SDL_Scancode code = event.key.keysym.scancode; //https://wiki.libsdl.org/SDLScancodeLookup if (code >= 4 && code <= 39) { lock(); addKey(SDL_GetScancodeName(event.key.keysym.scancode)[0]); unlock(); } } } void InputEvent::lock() { assert(SDL_LockMutex(mutex) == 0); } void InputEvent::unlock() { assert(SDL_UnlockMutex(mutex) == 0); } bool InputEvent::hasKey() { lock(); if (keys.size()) { return true; } else { unlock(); return false; } } void InputEvent::clear() { keys.clear(); } void InputEvent::addKey(char c) { keys.push_back(c); } int demoThread(void* data) { InputEvent* ie = (InputEvent*) data; for (unsigned i = 0; i < 450; ++i) { ie->pushEvent(Input(i % 360, 0.8)); SDL_Delay(30); } return 0; } typedef std::pair<InputEvent*, const char*> fileType; int fileThread(void* data) { fileType* in = (fileType*) data; InputEvent* ie = in->first; const char* path = in->second; int pipe = open(path, O_RDONLY, O_NONBLOCK, 0); if (pipe == -1) { perror("pipe"); return 0; } fd_set fds; FD_ZERO(&fds); while (true) { char input[20]; //Wait for input FD_SET(pipe, &fds); int s = select(pipe + 1, &fds, NULL, NULL, NULL); if (s < 0) { perror("select"); return 0; } int r = read(pipe, input, 20); if (r > 0) { std::string s(input); std::stringstream ss(s); int angle; float distance; ss >> angle >> distance; if (ss.good()) { ie->pushEvent(Input(angle, distance)); } } if (r < 0) { perror("read"); return 0; } } return 0; } typedef std::pair<InputEvent*, const char**> socketType; int socketThread(void* data) { socketType* in = (socketType*) data; InputEvent* ie = in->first; const char** argv = in->second; //getaddrinfo(3) struct addrinfo hints, *res, *res0; int error; int sock; const char *cause = NULL; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = 6; //TCP error = getaddrinfo(argv[1], argv[2], &hints, &res0); if (error) { errx(1, "%s", gai_strerror(error)); /*NOTREACHED*/ } sock = -1; for (res = res0; res; res = res->ai_next) { sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol); if (sock < 0) { cause = "socket"; continue; } if (connect(sock, res->ai_addr, res->ai_addrlen) < 0) { cause = "connect"; close(sock); sock = -1; continue; } break; /* okay we got one */ } if (sock < 0) { err(1, "%s", cause); /*NOTREACHED*/ } freeaddrinfo(res0); std::string str; bool lastValid = false; unsigned nums = 0; while (true) { char input[4096] = ""; fd_set fds; timeval tv; //Wait for input FD_ZERO(&fds); FD_SET(sock, &fds); //Set waiting time of 10us tv.tv_sec = 0; tv.tv_usec = 10; int s = select(sock + 1, &fds, NULL, NULL, &tv); if (s < 0) { perror("select"); return 0; } if (s == 0) { if (ie->hasKey()) { std::cout << "SEND: " << ie->keys << std::endl; ie->keys.push_back('\n'); s = write(sock, ie->keys.c_str(), ie->keys.length()); if (s < 0) { perror("write"); return 0; } ie->clear(); ie->unlock(); } } if (FD_ISSET(sock, &fds)) { int r = read(sock, input, 4096); if (r > 0) { for (unsigned i = 0; i < r; ++i) { char c = input[i]; if ( ('0' <= c && c <= '9') || c == '.') { str.push_back(c); lastValid = true; } if (lastValid && (c == ' ' || c == '\r' || c == '\n')) { str.push_back(' '); lastValid = false; nums ++; } } while (nums >= 2) { int angle; float distance; std::stringstream ss(str); ss >> angle >> distance; if (ss.good()) { std::cout << "Input: " << angle << " " << distance << std::endl; ie->pushEvent(Input(angle, distance)); } std::string::size_type first = str.find(' ') + 1; str = str.substr(str.find(' ', first) + 1); nums -= 2; } } if (r < 0) { perror("read"); return 0; } } } close(sock); return 0; } SDL_Thread* InputEvent::demo() { return SDL_CreateThread(demoThread, "DemoThread", this); } SDL_Thread* InputEvent::fileInput(const char *path) { return SDL_CreateThread(fileThread, "FileThread", new fileType(this, path)); } SDL_Thread* InputEvent::socketInput(const char **argv) { return SDL_CreateThread(socketThread, "SocketThread", new socketType(this, argv)); } <|endoftext|>
<commit_before>/*! \author Chase Hutchens \brief This will attempt to locate 2 prime factors of a larger number. The discrepancy with this method is the prime factors must be in the range of the 2 <= factor <= ceil(goldenRatio * sqrt(largePrime)). The reason I chose to scale by the goldenRatio is because I feel the golden ratio and prime numbers go hand in hand. Example Values : FAST CALCULATION 25450261 = 5087 * 5003 LONGER CALCULATION 3574406403731 = 2750159 * 1299709 */ #include <iostream> #include <sstream> #include <string> #include <ctime> #include "PrimeFactorization.h" static const double goldenRatio = (1.0 + sqrt(5)) / 2.0; // PRIVATE /*! \param thePrime This is our 'F' number that we are trying to prime factor */ void EncryptionSequence::PrimeFactor::DeterminePrimes(const ull thePrime) { // initial p' ull prime = static_cast<ull>(ceil(goldenRatio * sqrt(thePrime))); while (prime > 1) { // p' ull checkPrime = prime; // p'' ull startPrime = static_cast<ull>(ceil(goldenRatio * sqrt(checkPrime))); // make sure the startPrime isn't the same as the base prime we're checking against startPrime = startPrime == prime ? startPrime - 1 : startPrime; bool validPrime = false; // determine what is prime while (checkPrime % startPrime != 0) { --startPrime; // make sure the startPrime isn't the same as the checkPrime we're comparing // the startPrime might initially be greater than the checkPrime // (kind of messy) startPrime = startPrime == checkPrime ? startPrime - 1 : startPrime; if (startPrime == 1) { validPrime = true; break; } } if (validPrime || startPrime == 1) { this->primes.push_back(checkPrime); } --prime; // a prime is never even, but a prime is 2 while (prime % 2 == 0 && prime != 2) --prime; } std::cout << "\nFound : " << this->primes.size() << " Primes That May Make Up " << thePrime << "\n"; } // END PRIVATE // PUBLIC void EncryptionSequence::PrimeFactor::FactorPrime(const ull toFactorPrime, const int charLen) { std::stringstream greatestDigit; greatestDigit << toFactorPrime; DeterminePrimes(toFactorPrime); time_t startTime; time(&startTime); unsigned foundPrimes = this->primes.size(); for (unsigned i = 0; i < foundPrimes; ++i) { ull prime = this->primes[i]; bool broke = false; for (unsigned j = i; j < foundPrimes; ++j) { ull primeVal = prime * this->primes[j]; // This causes noticeable slowdown instead of just elapsing /*if (charLen != 0) { std::stringstream ss; ss << primeVal; // not going to be any other larger primes beyond this one // multiplied with this one if (ss.str().size() != charLen) { break; broke = true; } }*/ // we've eliminated what we don't want //std::cout << primeVal << " | " << prime << " * " << primes[j] << std::endl; // 5087 * 5003 (etc..) if (primeVal == toFactorPrime) { time_t endTime; time(&endTime); double timeTaken = difftime(endTime, startTime); std::cout << "\nFound Prime Factors : [p] = " << prime << " | [q] = " << this->primes[j] << std::endl; std::cout << "Time Taken To Factor Prime : " << timeTaken << " seconds" << std::endl; return; } } } std::cout << "\nFound : No Two Primes That Make Up : " << toFactorPrime << std::endl; } // END PUBLIC void EncryptionSequence::DoPrimeFactor() { std::string inputNumber, foundNumber; std::cout << "What Number Do You Want To Factor?\n:"; std::getline(std::cin, inputNumber); // parse the inputted number for only numbers unsigned stringSize = inputNumber.size(); for (unsigned i = 0; i <= stringSize; ++i) { if ((inputNumber[i] >= '0' && inputNumber[i] <= '9')) { foundNumber += inputNumber[i]; } } EncryptionSequence::PrimeFactor pFactor; pFactor.FactorPrime(std::stoull(foundNumber), stringSize); std::cout << "\nPress Enter To Continue"; getchar(); }<commit_msg>[ PrimeFactorization.cpp Changes ]<commit_after>/*! \author Chase Hutchens \brief This will attempt to locate 2 prime factors of a larger number. The discrepancy with this method is the prime factors must be in the range of the 2 <= factor <= ceil(goldenRatio * sqrt(largePrime)). The reason I chose to scale by the goldenRatio is because I feel the golden ratio and prime numbers go hand in hand. Example Values : FAST CALCULATION 25450261 = 5087 * 5003 LONGER CALCULATION 3574406403731 = 2750159 * 1299709 */ #include <iostream> #include <sstream> #include <string> #include <ctime> #include "PrimeFactorization.h" static const double goldenRatio = (1.0 + sqrt(5)) / 2.0; // PRIVATE /*! \param thePrime This is our 'F' number that we are trying to prime factor */ void EncryptionSequence::PrimeFactor::DeterminePrimes(const ull thePrime) { // initial p' ull prime = static_cast<ull>(ceil(goldenRatio * sqrt(thePrime))); while (prime > 1) { // p' ull checkPrime = prime; // p'' ull comparison = static_cast<ull>(ceil(goldenRatio * sqrt(checkPrime))); // make sure the startPrime isn't the same as the base prime we're checking against comparison = comparison == prime ? comparison - 1 : comparison; bool validPrime = false; // determine what is prime while (checkPrime % comparison != 0) { --comparison; // make sure the startPrime isn't the same as the checkPrime we're comparing // the startPrime might initially be greater than the checkPrime // (kind of messy) comparison = comparison == checkPrime ? comparison - 1 : comparison; if (comparison == 1) { validPrime = true; break; } } if (validPrime || comparison == 1) { this->primes.push_back(checkPrime); } --prime; // a prime is never even, but a prime is 2 while (prime % 2 == 0 && prime != 2) --prime; } std::cout << "\nFound : " << this->primes.size() << " Primes That May Make Up " << thePrime << "\n"; } // END PRIVATE // PUBLIC void EncryptionSequence::PrimeFactor::FactorPrime(const ull toFactorPrime, const int charLen) { std::stringstream greatestDigit; greatestDigit << toFactorPrime; DeterminePrimes(toFactorPrime); time_t startTime; time(&startTime); unsigned foundPrimes = this->primes.size(); for (unsigned i = 0; i < foundPrimes; ++i) { ull prime = this->primes[i]; bool broke = false; for (unsigned j = i; j < foundPrimes; ++j) { ull primeVal = prime * this->primes[j]; // This causes noticeable slowdown instead of just elapsing /*if (charLen != 0) { std::stringstream ss; ss << primeVal; // not going to be any other larger primes beyond this one // multiplied with this one if (ss.str().size() != charLen) { break; broke = true; } }*/ // we've eliminated what we don't want //std::cout << primeVal << " | " << prime << " * " << primes[j] << std::endl; // 5087 * 5003 (etc..) if (primeVal == toFactorPrime) { time_t endTime; time(&endTime); double timeTaken = difftime(endTime, startTime); std::cout << "\nFound Prime Factors : [p] = " << prime << " | [q] = " << this->primes[j] << std::endl; std::cout << "Time Taken To Factor Prime : " << timeTaken << " seconds" << std::endl; return; } } } std::cout << "\nFound : No Two Primes That Make Up : " << toFactorPrime << std::endl; } // END PUBLIC void EncryptionSequence::DoPrimeFactor() { std::string inputNumber, foundNumber; std::cout << "What Number Do You Want To Factor?\n:"; std::getline(std::cin, inputNumber); // parse the inputted number for only numbers unsigned stringSize = inputNumber.size(); for (unsigned i = 0; i <= stringSize; ++i) { if ((inputNumber[i] >= '0' && inputNumber[i] <= '9')) { foundNumber += inputNumber[i]; } } EncryptionSequence::PrimeFactor pFactor; pFactor.FactorPrime(std::stoull(foundNumber), stringSize); std::cout << "\nPress Enter To Continue"; getchar(); }<|endoftext|>
<commit_before>/*************************************************************************** * io/iostats.cpp * * Part of the STXXL. See http://stxxl.sourceforge.net * * Copyright (C) 2002-2004 Roman Dementiev <[email protected]> * Copyright (C) 2008 Andreas Beckmann <[email protected]> * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) **************************************************************************/ #include <string> #include <sstream> #include <iomanip> #include <stxxl/bits/io/iostats.h> __STXXL_BEGIN_NAMESPACE stats::stats() : reads(0), writes(0), volume_read(0), volume_written(0), t_reads(0.0), t_writes(0.0), p_reads(0.0), p_writes(0.0), p_begin_read(0.0), p_begin_write(0.0), p_ios(0.0), p_begin_io(0.0), t_waits(0.0), p_waits(0.0), p_begin_wait(0.0), acc_reads(0), acc_writes(0), acc_ios(0), acc_waits(0), last_reset(timestamp()) { } #ifndef STXXL_IO_STATS_RESET_FORBIDDEN void stats::reset() { { scoped_mutex_lock ReadLock(read_mutex); //assert(acc_reads == 0); if (acc_reads) STXXL_ERRMSG("Warning: " << acc_reads << " read(s) not yet finished"); reads = 0; volume_read = 0; t_reads = 0; p_reads = 0.0; } { scoped_mutex_lock WriteLock(write_mutex); //assert(acc_writes == 0); if (acc_writes) STXXL_ERRMSG("Warning: " << acc_writes << " write(s) not yet finished"); writes = 0; volume_written = 0; t_writes = 0.0; p_writes = 0.0; } { scoped_mutex_lock IOLock(io_mutex); //assert(acc_ios == 0); if (acc_ios) STXXL_ERRMSG("Warning: " << acc_ios << " io(s) not yet finished"); p_ios = 0.0; } { scoped_mutex_lock WaitLock(wait_mutex); //assert(acc_waits == 0); if (acc_waits) STXXL_ERRMSG("Warning: " << acc_waits << " wait(s) not yet finished"); t_waits = 0.0; p_waits = 0.0; } last_reset = timestamp(); } #endif #if STXXL_IO_STATS void stats::write_started(unsigned size_) { double now = timestamp(); { scoped_mutex_lock WriteLock(write_mutex); ++writes; volume_written += size_; double diff = now - p_begin_write; t_writes += double(acc_writes) * diff; p_begin_write = now; p_writes += (acc_writes++) ? diff : 0.0; } { scoped_mutex_lock IOLock(io_mutex); double diff = now - p_begin_io; p_ios += (acc_ios++) ? diff : 0.0; p_begin_io = now; } } void stats::write_finished() { double now = timestamp(); { scoped_mutex_lock WriteLock(write_mutex); double diff = now - p_begin_write; t_writes += double(acc_writes) * diff; p_begin_write = now; p_writes += (acc_writes--) ? diff : 0.0; } { scoped_mutex_lock IOLock(io_mutex); double diff = now - p_begin_io; p_ios += (acc_ios--) ? diff : 0.0; p_begin_io = now; } } void stats::write_cached(unsigned size_) { scoped_mutex_lock WriteLock(write_mutex); ++c_writes; c_volume_written += size_; } void stats::read_started(unsigned size_) { double now = timestamp(); { scoped_mutex_lock ReadLock(read_mutex); ++reads; volume_read += size_; double diff = now - p_begin_read; t_reads += double(acc_reads) * diff; p_begin_read = now; p_reads += (acc_reads++) ? diff : 0.0; } { scoped_mutex_lock IOLock(io_mutex); double diff = now - p_begin_io; p_ios += (acc_ios++) ? diff : 0.0; p_begin_io = now; } } void stats::read_finished() { double now = timestamp(); { scoped_mutex_lock ReadLock(read_mutex); double diff = now - p_begin_read; t_reads += double(acc_reads) * diff; p_begin_read = now; p_reads += (acc_reads--) ? diff : 0.0; } { scoped_mutex_lock IOLock(io_mutex); double diff = now - p_begin_io; p_ios += (acc_ios--) ? diff : 0.0; p_begin_io = now; } } void stats::read_cached(unsigned size_) { scoped_mutex_lock WriteLock(read_mutex); ++c_reads; c_volume_read += size_; } #endif #ifdef COUNT_WAIT_TIME void stats::wait_started() { double now = timestamp(); { scoped_mutex_lock WaitLock(wait_mutex); double diff = now - p_begin_wait; t_waits += double(acc_waits) * diff; p_begin_wait = now; p_waits += (acc_waits++) ? diff : 0.0; } } void stats::wait_finished() { double now = timestamp(); { scoped_mutex_lock WaitLock(wait_mutex); double diff = now - p_begin_wait; t_waits += double(acc_waits) * diff; p_begin_wait = now; p_waits += (acc_waits--) ? diff : 0.0; } } #endif void stats::_reset_io_wait_time() { #ifdef COUNT_WAIT_TIME { scoped_mutex_lock WaitLock(wait_mutex); //assert(acc_waits == 0); if (acc_waits) STXXL_ERRMSG("Warning: " << acc_waits << " wait(s) not yet finished"); t_waits = 0.0; p_waits = 0.0; } #endif } std::string hr(uint64 number, const char * unit = "") { // may not overflow, std::numeric_limits<uint64>::max() == 16 EB static const char * endings[] = { " ", "K", "M", "G", "T", "P", "E" }; std::ostringstream out; out << number << ' '; int scale = 0; double number_d = number; while (number_d >= 1024.0) { number_d /= 1024.0; ++scale; } if (scale > 0) out << '(' << std::fixed << std::setprecision(3) << number_d << ' ' << endings[scale] << unit << ") "; return out.str(); } std::ostream & operator << (std::ostream & o, const stats_data & s) { o << "STXXL I/O statistics" << std::endl; #if STXXL_IO_STATS o << " total number of reads : " << hr(s.get_reads()) << std::endl; o << " average block size (read) : " << hr(s.get_reads() ? s.get_read_volume() / s.get_reads() : 0, "B") << std::endl; o << " number of bytes read from disks : " << hr(s.get_read_volume(), "B") << std::endl; o << " time spent in serving all read requests : " << s.get_read_time() << " sec." << " @ " << (s.get_read_volume() / 1048576.0 / s.get_read_time()) << " MB/sec." << std::endl; o << " time spent in reading (parallel read time) : " << s.get_pread_time() << " sec." << " @ " << (s.get_read_volume() / 1048576.0 / s.get_pread_time()) << " MB/sec." << std::endl; if (s.get_cached_reads()) { o << " total number of cached reads : " << hr(s.get_cached_reads()) << std::endl; o << " number of bytes read from cache : " << hr(s.get_cached_read_volume(), "B") << std::endl; } if (s.get_cached_writes()) { o << " total number of cached writes : " << hr(s.get_cached_writes()) << std::endl; o << " number of bytes written to cache : " << hr(s.get_cached_written_volume(), "B") << std::endl; } o << " total number of writes : " << hr(s.get_writes()) << std::endl; o << " average block size (write) : " << hr(s.get_writes() ? s.get_written_volume() / s.get_writes() : 0, "B") << std::endl; o << " number of bytes written to disks : " << hr(s.get_written_volume(), "B") << std::endl; o << " time spent in serving all write requests : " << s.get_write_time() << " sec." << " @ " << (s.get_written_volume() / 1048576.0 / s.get_write_time()) << " MB/sec." << std::endl; o << " time spent in writing (parallel write time): " << s.get_pwrite_time() << " sec." << " @ " << (s.get_written_volume() / 1048576.0 / s.get_pwrite_time()) << " MB/sec." << std::endl; o << " time spent in I/O (parallel I/O time) : " << s.get_pio_time() << " sec." << " @ " << ((s.get_read_volume() + s.get_written_volume()) / 1048576.0 / s.get_pio_time()) << " MB/sec." << std::endl; #else o << " n/a" << std::endl; #endif #ifdef COUNT_WAIT_TIME o << " I/O wait time : " << s.get_io_wait_time() << " sec." << std::endl; #endif o << " Time since the last reset : " << s.get_elapsed_time() << " sec." << std::endl; return o; } __STXXL_END_NAMESPACE <commit_msg>add average cached block sizes<commit_after>/*************************************************************************** * io/iostats.cpp * * Part of the STXXL. See http://stxxl.sourceforge.net * * Copyright (C) 2002-2004 Roman Dementiev <[email protected]> * Copyright (C) 2008 Andreas Beckmann <[email protected]> * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) **************************************************************************/ #include <string> #include <sstream> #include <iomanip> #include <stxxl/bits/io/iostats.h> __STXXL_BEGIN_NAMESPACE stats::stats() : reads(0), writes(0), volume_read(0), volume_written(0), t_reads(0.0), t_writes(0.0), p_reads(0.0), p_writes(0.0), p_begin_read(0.0), p_begin_write(0.0), p_ios(0.0), p_begin_io(0.0), t_waits(0.0), p_waits(0.0), p_begin_wait(0.0), acc_reads(0), acc_writes(0), acc_ios(0), acc_waits(0), last_reset(timestamp()) { } #ifndef STXXL_IO_STATS_RESET_FORBIDDEN void stats::reset() { { scoped_mutex_lock ReadLock(read_mutex); //assert(acc_reads == 0); if (acc_reads) STXXL_ERRMSG("Warning: " << acc_reads << " read(s) not yet finished"); reads = 0; volume_read = 0; t_reads = 0; p_reads = 0.0; } { scoped_mutex_lock WriteLock(write_mutex); //assert(acc_writes == 0); if (acc_writes) STXXL_ERRMSG("Warning: " << acc_writes << " write(s) not yet finished"); writes = 0; volume_written = 0; t_writes = 0.0; p_writes = 0.0; } { scoped_mutex_lock IOLock(io_mutex); //assert(acc_ios == 0); if (acc_ios) STXXL_ERRMSG("Warning: " << acc_ios << " io(s) not yet finished"); p_ios = 0.0; } { scoped_mutex_lock WaitLock(wait_mutex); //assert(acc_waits == 0); if (acc_waits) STXXL_ERRMSG("Warning: " << acc_waits << " wait(s) not yet finished"); t_waits = 0.0; p_waits = 0.0; } last_reset = timestamp(); } #endif #if STXXL_IO_STATS void stats::write_started(unsigned size_) { double now = timestamp(); { scoped_mutex_lock WriteLock(write_mutex); ++writes; volume_written += size_; double diff = now - p_begin_write; t_writes += double(acc_writes) * diff; p_begin_write = now; p_writes += (acc_writes++) ? diff : 0.0; } { scoped_mutex_lock IOLock(io_mutex); double diff = now - p_begin_io; p_ios += (acc_ios++) ? diff : 0.0; p_begin_io = now; } } void stats::write_finished() { double now = timestamp(); { scoped_mutex_lock WriteLock(write_mutex); double diff = now - p_begin_write; t_writes += double(acc_writes) * diff; p_begin_write = now; p_writes += (acc_writes--) ? diff : 0.0; } { scoped_mutex_lock IOLock(io_mutex); double diff = now - p_begin_io; p_ios += (acc_ios--) ? diff : 0.0; p_begin_io = now; } } void stats::write_cached(unsigned size_) { scoped_mutex_lock WriteLock(write_mutex); ++c_writes; c_volume_written += size_; } void stats::read_started(unsigned size_) { double now = timestamp(); { scoped_mutex_lock ReadLock(read_mutex); ++reads; volume_read += size_; double diff = now - p_begin_read; t_reads += double(acc_reads) * diff; p_begin_read = now; p_reads += (acc_reads++) ? diff : 0.0; } { scoped_mutex_lock IOLock(io_mutex); double diff = now - p_begin_io; p_ios += (acc_ios++) ? diff : 0.0; p_begin_io = now; } } void stats::read_finished() { double now = timestamp(); { scoped_mutex_lock ReadLock(read_mutex); double diff = now - p_begin_read; t_reads += double(acc_reads) * diff; p_begin_read = now; p_reads += (acc_reads--) ? diff : 0.0; } { scoped_mutex_lock IOLock(io_mutex); double diff = now - p_begin_io; p_ios += (acc_ios--) ? diff : 0.0; p_begin_io = now; } } void stats::read_cached(unsigned size_) { scoped_mutex_lock WriteLock(read_mutex); ++c_reads; c_volume_read += size_; } #endif #ifdef COUNT_WAIT_TIME void stats::wait_started() { double now = timestamp(); { scoped_mutex_lock WaitLock(wait_mutex); double diff = now - p_begin_wait; t_waits += double(acc_waits) * diff; p_begin_wait = now; p_waits += (acc_waits++) ? diff : 0.0; } } void stats::wait_finished() { double now = timestamp(); { scoped_mutex_lock WaitLock(wait_mutex); double diff = now - p_begin_wait; t_waits += double(acc_waits) * diff; p_begin_wait = now; p_waits += (acc_waits--) ? diff : 0.0; } } #endif void stats::_reset_io_wait_time() { #ifdef COUNT_WAIT_TIME { scoped_mutex_lock WaitLock(wait_mutex); //assert(acc_waits == 0); if (acc_waits) STXXL_ERRMSG("Warning: " << acc_waits << " wait(s) not yet finished"); t_waits = 0.0; p_waits = 0.0; } #endif } std::string hr(uint64 number, const char * unit = "") { // may not overflow, std::numeric_limits<uint64>::max() == 16 EB static const char * endings[] = { " ", "K", "M", "G", "T", "P", "E" }; std::ostringstream out; out << number << ' '; int scale = 0; double number_d = number; while (number_d >= 1024.0) { number_d /= 1024.0; ++scale; } if (scale > 0) out << '(' << std::fixed << std::setprecision(3) << number_d << ' ' << endings[scale] << unit << ") "; return out.str(); } std::ostream & operator << (std::ostream & o, const stats_data & s) { o << "STXXL I/O statistics" << std::endl; #if STXXL_IO_STATS o << " total number of reads : " << hr(s.get_reads()) << std::endl; o << " average block size (read) : " << hr(s.get_reads() ? s.get_read_volume() / s.get_reads() : 0, "B") << std::endl; o << " number of bytes read from disks : " << hr(s.get_read_volume(), "B") << std::endl; o << " time spent in serving all read requests : " << s.get_read_time() << " sec." << " @ " << (s.get_read_volume() / 1048576.0 / s.get_read_time()) << " MB/sec." << std::endl; o << " time spent in reading (parallel read time) : " << s.get_pread_time() << " sec." << " @ " << (s.get_read_volume() / 1048576.0 / s.get_pread_time()) << " MB/sec." << std::endl; if (s.get_cached_reads()) { o << " total number of cached reads : " << hr(s.get_cached_reads()) << std::endl; o << " average block size (cached read) : " << hr(s.get_cached_read_volume() / s.get_cached_reads(), "B") << std::endl; o << " number of bytes read from cache : " << hr(s.get_cached_read_volume(), "B") << std::endl; } if (s.get_cached_writes()) { o << " total number of cached writes : " << hr(s.get_cached_writes()) << std::endl; o << " average block size (cached write) : " << hr(s.get_cached_written_volume() / s.get_cached_writes(), "B") << std::endl; o << " number of bytes written to cache : " << hr(s.get_cached_written_volume(), "B") << std::endl; } o << " total number of writes : " << hr(s.get_writes()) << std::endl; o << " average block size (write) : " << hr(s.get_writes() ? s.get_written_volume() / s.get_writes() : 0, "B") << std::endl; o << " number of bytes written to disks : " << hr(s.get_written_volume(), "B") << std::endl; o << " time spent in serving all write requests : " << s.get_write_time() << " sec." << " @ " << (s.get_written_volume() / 1048576.0 / s.get_write_time()) << " MB/sec." << std::endl; o << " time spent in writing (parallel write time): " << s.get_pwrite_time() << " sec." << " @ " << (s.get_written_volume() / 1048576.0 / s.get_pwrite_time()) << " MB/sec." << std::endl; o << " time spent in I/O (parallel I/O time) : " << s.get_pio_time() << " sec." << " @ " << ((s.get_read_volume() + s.get_written_volume()) / 1048576.0 / s.get_pio_time()) << " MB/sec." << std::endl; #else o << " n/a" << std::endl; #endif #ifdef COUNT_WAIT_TIME o << " I/O wait time : " << s.get_io_wait_time() << " sec." << std::endl; #endif o << " Time since the last reset : " << s.get_elapsed_time() << " sec." << std::endl; return o; } __STXXL_END_NAMESPACE <|endoftext|>
<commit_before> #include "DuktapeScriptBackend.h" #include <iostream> #include <cppassist/logging/logging.h> #include <cppexpose/reflection/Object.h> #include <cppexpose/variant/Variant.h> #include <cppexpose/scripting/ScriptContext.h> #include "DuktapeScriptFunction.h" #include "DuktapeObjectWrapper.h" using namespace cppassist; namespace cppexpose { const char * s_duktapeScriptBackendKey = "duktapeScriptBackend"; const char * s_duktapeNextStashIndexKey = "duktapeNextStashFunctionIndex"; const char * s_duktapeFunctionPointerKey = "duktapeFunctionPointer"; const char * s_duktapeObjectPointerKey = "duktapeObjectPointer"; const char * s_duktapePropertyNameKey = "duktapePropertyName"; DuktapeScriptBackend::DuktapeScriptBackend() : m_context(nullptr) , m_globalObjWrapper(nullptr) { // Create duktape script context m_context = duk_create_heap_default(); } DuktapeScriptBackend::~DuktapeScriptBackend() { // Destroy duktape script context duk_destroy_heap(m_context); } void DuktapeScriptBackend::initialize(ScriptContext * scriptContext) { // Store script context m_scriptContext = scriptContext; // Get stash duk_push_global_stash(m_context); // Save pointer to script backend in global stash void * context_ptr = static_cast<void *>(this); duk_push_pointer(m_context, context_ptr); duk_put_prop_string(m_context, -2, s_duktapeScriptBackendKey); // Initialize next index for storing functions and objects in the stash duk_push_int(m_context, 0); duk_put_prop_string(m_context, -2, s_duktapeNextStashIndexKey); // Release stash duk_pop(m_context); } void DuktapeScriptBackend::setGlobalObject(Object * obj) { // Destroy former global object wrapper if (m_globalObjWrapper) { // Remove property in the global object duk_push_global_object(m_context); duk_del_prop_string(m_context, duk_get_top_index(m_context), obj->name().c_str()); duk_pop(m_context); } // Create object wrapper m_globalObjWrapper = cppassist::make_unique<DuktapeObjectWrapper>(this); // Wrap object in javascript object and put it into the global object duk_push_global_object(m_context); m_globalObjWrapper->wrapObject(duk_get_top_index(m_context), obj); duk_pop(m_context); } Variant DuktapeScriptBackend::evaluate(const std::string & code) { // Check code for errors duk_int_t error = duk_peval_string(m_context, code.c_str()); if (error) { // Raise exception m_scriptContext->scriptException(std::string(duk_safe_to_string(m_context, -1))); // Abort and return undefined value duk_pop(m_context); return Variant(); } // Convert return value to variant Variant value = fromDukStack(); duk_pop(m_context); return value; } DuktapeScriptBackend * DuktapeScriptBackend::getScriptBackend(duk_context * context) { // Get stash object duk_push_global_stash(context); // Get pointer to duktape scripting backend duk_get_prop_string(context, -1, s_duktapeScriptBackendKey); void * ptr = duk_get_pointer(context, -1); duk_pop_2(context); // Return duktape scripting backend return static_cast<DuktapeScriptBackend *>(ptr); } Variant DuktapeScriptBackend::fromDukStack(duk_idx_t index) { // Wrapped object function if (duk_is_c_function(m_context, index)) { // Get pointer to wrapped function duk_get_prop_string(m_context, index, s_duktapeFunctionPointerKey); Function * func = reinterpret_cast<Function *>( duk_get_pointer(m_context, -1) ); duk_pop(m_context); // Return wrapped function return Variant::fromValue<Function>(*func); } // Javascript function - will be stored in global stash for access from C++ later else if (duk_is_ecmascript_function(m_context, index)) { // Get stash object duk_push_global_stash(m_context); // Get next free index in global stash int funcIndex = getNextStashIndex(); duk_push_int(m_context, funcIndex); // Copy function object to the top and put it as property into global stash duk_dup(m_context, -3); duk_put_prop(m_context, -3); // Close stash duk_pop(m_context); // Return callable function Function function(cppassist::make_unique<DuktapeScriptFunction>(this, funcIndex)); return Variant::fromValue<Function>(function); } // Number else if (duk_is_number(m_context, index)) { double value = duk_get_number(m_context, index); return Variant(value); } // Boolean else if (duk_is_boolean(m_context, index)) { bool value = duk_get_boolean(m_context, index) > 0; return Variant(value); } // String else if (duk_is_string(m_context, index)) { const char *str = duk_get_string(m_context, index); return Variant(str); } // Array else if (duk_is_array(m_context, index)) { VariantArray array; for (unsigned int i = 0; i < duk_get_length(m_context, index); ++i) { duk_get_prop_index(m_context, index, i); array.push_back(fromDukStack()); duk_pop(m_context); } return array; } // Object else if (duk_is_object(m_context, index)) { VariantMap map; duk_enum(m_context, index, 0); while (duk_next(m_context, -1, 1)) { // Prevent the pointer to the C++ object that is stored in the Ecmascript object from being serialized if (!(duk_is_pointer(m_context, -1) && fromDukStack(-2).value<std::string>() == s_duktapeObjectPointerKey)) { map.insert({ fromDukStack(-2).value<std::string>(), fromDukStack(-1) }); } duk_pop_2(m_context); } duk_pop(m_context); return Variant(map); } // Pointer else if (duk_is_pointer(m_context, index)) { return Variant::fromValue<void *>(duk_get_pointer(m_context, index)); } // Undefined else if (duk_is_undefined(m_context, index)) { return Variant(); } // Unknown type warning() << "Unknown type found: " << duk_get_type(m_context, index) << std::endl; warning() << "Duktape stack dump:" << std::endl; duk_dump_context_stderr(m_context); return Variant(); } void DuktapeScriptBackend::pushToDukStack(const Variant & value) { if (value.isBool()) { duk_push_boolean(m_context, value.toBool()); } else if (value.isUnsignedIntegral()) { duk_push_number(m_context, value.toULongLong()); } else if (value.isSignedIntegral() || value.isIntegral()) { duk_push_number(m_context, value.toLongLong()); } else if (value.isFloatingPoint()) { duk_push_number(m_context, value.toDouble()); } else if (value.isString()) { duk_push_string(m_context, value.toString().c_str()); } else if (value.hasType<char*>()) { duk_push_string(m_context, value.value<char*>()); } else if (value.isVariantArray()) { VariantArray variantArray = value.value<VariantArray>(); duk_idx_t arr_idx = duk_push_array(m_context); for (unsigned int i=0; i<variantArray.size(); i++) { pushToDukStack(variantArray.at(i)); duk_put_prop_index(m_context, arr_idx, i); } } else if (value.isVariantMap()) { VariantMap variantMap = value.value<VariantMap>(); duk_push_object(m_context); for (const std::pair<std::string, Variant> & pair : variantMap) { pushToDukStack(pair.second); duk_put_prop_string(m_context, -2, pair.first.c_str()); } } } int DuktapeScriptBackend::getNextStashIndex() { // Get stash object duk_push_global_stash(m_context); // Get next free index for functions or objects in global stash duk_get_prop_string(m_context, -1, s_duktapeNextStashIndexKey); int index = duk_get_int(m_context, -1); // Increment next free index duk_push_int(m_context, index + 1); duk_put_prop_string(m_context, -3, s_duktapeNextStashIndexKey); // Clean up stack duk_pop(m_context); duk_pop(m_context); // Return index return index; } } // namespace cppexpose <commit_msg>Fix crash in duktape backend when property value cannot be converted<commit_after> #include "DuktapeScriptBackend.h" #include <iostream> #include <cppassist/logging/logging.h> #include <cppexpose/reflection/Object.h> #include <cppexpose/variant/Variant.h> #include <cppexpose/scripting/ScriptContext.h> #include "DuktapeScriptFunction.h" #include "DuktapeObjectWrapper.h" using namespace cppassist; namespace cppexpose { const char * s_duktapeScriptBackendKey = "duktapeScriptBackend"; const char * s_duktapeNextStashIndexKey = "duktapeNextStashFunctionIndex"; const char * s_duktapeFunctionPointerKey = "duktapeFunctionPointer"; const char * s_duktapeObjectPointerKey = "duktapeObjectPointer"; const char * s_duktapePropertyNameKey = "duktapePropertyName"; DuktapeScriptBackend::DuktapeScriptBackend() : m_context(nullptr) , m_globalObjWrapper(nullptr) { // Create duktape script context m_context = duk_create_heap_default(); } DuktapeScriptBackend::~DuktapeScriptBackend() { // Destroy duktape script context duk_destroy_heap(m_context); } void DuktapeScriptBackend::initialize(ScriptContext * scriptContext) { // Store script context m_scriptContext = scriptContext; // Get stash duk_push_global_stash(m_context); // Save pointer to script backend in global stash void * context_ptr = static_cast<void *>(this); duk_push_pointer(m_context, context_ptr); duk_put_prop_string(m_context, -2, s_duktapeScriptBackendKey); // Initialize next index for storing functions and objects in the stash duk_push_int(m_context, 0); duk_put_prop_string(m_context, -2, s_duktapeNextStashIndexKey); // Release stash duk_pop(m_context); } void DuktapeScriptBackend::setGlobalObject(Object * obj) { // Destroy former global object wrapper if (m_globalObjWrapper) { // Remove property in the global object duk_push_global_object(m_context); duk_del_prop_string(m_context, duk_get_top_index(m_context), obj->name().c_str()); duk_pop(m_context); } // Create object wrapper m_globalObjWrapper = cppassist::make_unique<DuktapeObjectWrapper>(this); // Wrap object in javascript object and put it into the global object duk_push_global_object(m_context); m_globalObjWrapper->wrapObject(duk_get_top_index(m_context), obj); duk_pop(m_context); } Variant DuktapeScriptBackend::evaluate(const std::string & code) { // Check code for errors duk_int_t error = duk_peval_string(m_context, code.c_str()); if (error) { // Raise exception m_scriptContext->scriptException(std::string(duk_safe_to_string(m_context, -1))); // Abort and return undefined value duk_pop(m_context); return Variant(); } // Convert return value to variant Variant value = fromDukStack(); duk_pop(m_context); return value; } DuktapeScriptBackend * DuktapeScriptBackend::getScriptBackend(duk_context * context) { // Get stash object duk_push_global_stash(context); // Get pointer to duktape scripting backend duk_get_prop_string(context, -1, s_duktapeScriptBackendKey); void * ptr = duk_get_pointer(context, -1); duk_pop_2(context); // Return duktape scripting backend return static_cast<DuktapeScriptBackend *>(ptr); } Variant DuktapeScriptBackend::fromDukStack(duk_idx_t index) { // Wrapped object function if (duk_is_c_function(m_context, index)) { // Get pointer to wrapped function duk_get_prop_string(m_context, index, s_duktapeFunctionPointerKey); Function * func = reinterpret_cast<Function *>( duk_get_pointer(m_context, -1) ); duk_pop(m_context); // Return wrapped function return Variant::fromValue<Function>(*func); } // Javascript function - will be stored in global stash for access from C++ later else if (duk_is_ecmascript_function(m_context, index)) { // Get stash object duk_push_global_stash(m_context); // Get next free index in global stash int funcIndex = getNextStashIndex(); duk_push_int(m_context, funcIndex); // Copy function object to the top and put it as property into global stash duk_dup(m_context, -3); duk_put_prop(m_context, -3); // Close stash duk_pop(m_context); // Return callable function Function function(cppassist::make_unique<DuktapeScriptFunction>(this, funcIndex)); return Variant::fromValue<Function>(function); } // Number else if (duk_is_number(m_context, index)) { double value = duk_get_number(m_context, index); return Variant(value); } // Boolean else if (duk_is_boolean(m_context, index)) { bool value = duk_get_boolean(m_context, index) > 0; return Variant(value); } // String else if (duk_is_string(m_context, index)) { const char *str = duk_get_string(m_context, index); return Variant(str); } // Array else if (duk_is_array(m_context, index)) { VariantArray array; for (unsigned int i = 0; i < duk_get_length(m_context, index); ++i) { duk_get_prop_index(m_context, index, i); array.push_back(fromDukStack()); duk_pop(m_context); } return array; } // Object else if (duk_is_object(m_context, index)) { VariantMap map; duk_enum(m_context, index, 0); while (duk_next(m_context, -1, 1)) { // Prevent the pointer to the C++ object that is stored in the Ecmascript object from being serialized if (!(duk_is_pointer(m_context, -1) && fromDukStack(-2).value<std::string>() == s_duktapeObjectPointerKey)) { map.insert({ fromDukStack(-2).value<std::string>(), fromDukStack(-1) }); } duk_pop_2(m_context); } duk_pop(m_context); return Variant(map); } // Pointer else if (duk_is_pointer(m_context, index)) { return Variant::fromValue<void *>(duk_get_pointer(m_context, index)); } // Undefined else if (duk_is_undefined(m_context, index)) { return Variant(); } // Unknown type warning() << "Unknown type found: " << duk_get_type(m_context, index) << std::endl; warning() << "Duktape stack dump:" << std::endl; duk_dump_context_stderr(m_context); return Variant(); } void DuktapeScriptBackend::pushToDukStack(const Variant & value) { if (value.isBool()) { duk_push_boolean(m_context, value.toBool()); } else if (value.isUnsignedIntegral()) { duk_push_number(m_context, value.toULongLong()); } else if (value.isSignedIntegral() || value.isIntegral()) { duk_push_number(m_context, value.toLongLong()); } else if (value.isFloatingPoint()) { duk_push_number(m_context, value.toDouble()); } else if (value.isString()) { duk_push_string(m_context, value.toString().c_str()); } else if (value.hasType<char*>()) { duk_push_string(m_context, value.value<char*>()); } else if (value.isVariantArray()) { VariantArray variantArray = value.value<VariantArray>(); duk_idx_t arr_idx = duk_push_array(m_context); for (unsigned int i=0; i<variantArray.size(); i++) { pushToDukStack(variantArray.at(i)); duk_put_prop_index(m_context, arr_idx, i); } } else if (value.isVariantMap()) { VariantMap variantMap = value.value<VariantMap>(); duk_push_object(m_context); for (const std::pair<std::string, Variant> & pair : variantMap) { pushToDukStack(pair.second); duk_put_prop_string(m_context, -2, pair.first.c_str()); } } else { warning() << "Unknown variant type found: " << value.type().name(); duk_push_undefined(m_context); } } int DuktapeScriptBackend::getNextStashIndex() { // Get stash object duk_push_global_stash(m_context); // Get next free index for functions or objects in global stash duk_get_prop_string(m_context, -1, s_duktapeNextStashIndexKey); int index = duk_get_int(m_context, -1); // Increment next free index duk_push_int(m_context, index + 1); duk_put_prop_string(m_context, -3, s_duktapeNextStashIndexKey); // Clean up stack duk_pop(m_context); duk_pop(m_context); // Return index return index; } } // namespace cppexpose <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved */ #include "../../StroikaPreComp.h" #include "../../Characters/Format.h" #include "../../Characters/String_Constant.h" #include "../../Characters/String2Float.h" #include "../../Characters/String2Int.h" #include "../../Streams/TextInputStreamBinaryAdapter.h" #include "../BadFormatException.h" #include "Reader.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::DataExchange; using Characters::String_Constant; /* ******************************************************************************** ************************** DataExchange::INI::Reader *************************** ******************************************************************************** */ class DataExchange::INI::Reader::Rep_ : public DataExchange::Reader::_IRep { public: DECLARE_USE_BLOCK_ALLOCATION (Rep_); public: virtual _SharedPtrIRep Clone () const override { return _SharedPtrIRep (new Rep_ ()); // no instance data } virtual String GetDefaultFileSuffix () const override { return String_Constant (L".ini"); } virtual VariantValue Read (const Streams::BinaryInputStream& in) override { return Read (Streams::TextInputStreamBinaryAdapter (in)); } virtual VariantValue Read (const Streams::TextInputStream& in) override { Profile p; Optional<String> readingSection; Section currentSection; for (String line : in.ReadLines ()) { line = line.Trim (); if (line.StartsWith (L"[") and line.EndsWith (L"]")) { if (readingSection.IsPresent ()) { p.fNamedSections.Add (*readingSection, currentSection); currentSection.fProperties.clear (); } readingSection = line.CircularSubString (1, -1); } else if (line.StartsWith (L";")) { // drop comments on the floor } else if (line.Contains (L"=")) { size_t i = line.Find ('='); Assert (i != String::npos); String key = line.SubString (0, i).Trim (); String value = line.SubString (i + 1).Trim (); if (value.StartsWith (L"\"") and value.EndsWith (L"\"")) { value = value.CircularSubString (1, -1); } if (readingSection.IsPresent ()) { currentSection.fProperties.Add (key, value); } else { p.fUnnamedSection.fProperties.Add (key, value); } } else { // @todo not sure what todo with other sorts of lines?? } } return Convert (p); } }; DataExchange::INI::Reader::Reader () : inherited (shared_ptr<_IRep> (new Rep_ ())) { } <commit_msg>fixed serious bug with DataExchange/INI/Reader - not including last named section<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved */ #include "../../StroikaPreComp.h" #include "../../Characters/Format.h" #include "../../Characters/String_Constant.h" #include "../../Characters/String2Float.h" #include "../../Characters/String2Int.h" #include "../../Streams/TextInputStreamBinaryAdapter.h" #include "../BadFormatException.h" #include "Reader.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::DataExchange; using Characters::String_Constant; /* ******************************************************************************** ************************** DataExchange::INI::Reader *************************** ******************************************************************************** */ class DataExchange::INI::Reader::Rep_ : public DataExchange::Reader::_IRep { public: DECLARE_USE_BLOCK_ALLOCATION (Rep_); public: virtual _SharedPtrIRep Clone () const override { return _SharedPtrIRep (new Rep_ ()); // no instance data } virtual String GetDefaultFileSuffix () const override { return String_Constant (L".ini"); } virtual VariantValue Read (const Streams::BinaryInputStream& in) override { return Read (Streams::TextInputStreamBinaryAdapter (in)); } virtual VariantValue Read (const Streams::TextInputStream& in) override { Profile p; Optional<String> readingSection; Section currentSection; for (String line : in.ReadLines ()) { line = line.Trim (); if (line.StartsWith (L"[") and line.EndsWith (L"]")) { if (readingSection.IsPresent ()) { p.fNamedSections.Add (*readingSection, currentSection); currentSection.fProperties.clear (); } readingSection = line.CircularSubString (1, -1); } else if (line.StartsWith (L";")) { // drop comments on the floor } else if (line.Contains (L"=")) { size_t i = line.Find ('='); Assert (i != String::npos); String key = line.SubString (0, i).Trim (); String value = line.SubString (i + 1).Trim (); if (value.StartsWith (L"\"") and value.EndsWith (L"\"")) { value = value.CircularSubString (1, -1); } if (readingSection.IsPresent ()) { currentSection.fProperties.Add (key, value); } else { p.fUnnamedSection.fProperties.Add (key, value); } } else { // @todo not sure what todo with other sorts of lines?? } } if (readingSection.IsPresent ()) { p.fNamedSections.Add (*readingSection, currentSection); } return Convert (p); } }; DataExchange::INI::Reader::Reader () : inherited (shared_ptr<_IRep> (new Rep_ ())) { } <|endoftext|>
<commit_before>/// /// \file AliFemtoModelCorrFctnTrueQ3D.cxx /// #include "AliFemtoModelCorrFctnTrueQ3D.h" #include "AliFemtoPair.h" #include "AliFemtoModelManager.h" #include "AliFemtoModelHiddenInfo.h" #include <TH3F.h> #include <TList.h> #include <TString.h> #include <TRandom.h> #include <tuple> #include <iostream> AliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(): AliFemtoModelCorrFctnTrueQ3D("CF_TrueQ3D_") { } AliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(const char *prefix): AliFemtoModelCorrFctnTrueQ3D(prefix, 56, 0.14) { } AliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(const char *prefix, UInt_t nbins, Double_t qmax): AliFemtoModelCorrFctnTrueQ3D(prefix, nbins, -qmax, qmax) { } AliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(const TString &prefix, UInt_t nbins, Double_t qmin, Double_t qmax): AliFemtoCorrFctn() , fManager(nullptr) , fNumeratorGenerated(nullptr) , fNumeratorReconstructed(nullptr) , fNumeratorGenUnweighted(nullptr) , fNumeratorRecUnweighted(nullptr) , fDenominatorGenerated(nullptr) , fDenominatorReconstructed(nullptr) , fDenominatorGenWeighted(nullptr) , fDenominatorRecWeighted(nullptr) , fRng(new TRandom()) { fNumeratorGenerated = new TH3F(prefix + "NumGen", "Numerator (MC-Generated Momentum)", nbins, qmin, qmax, nbins, qmin, qmax, nbins, qmin, qmax); fNumeratorReconstructed = new TH3F(prefix + "NumRec", "Numerator (Reconstructed Momentum)", nbins, qmin, qmax, nbins, qmin, qmax, nbins, qmin, qmax); fNumeratorRecUnweighted = new TH3F(prefix + "NumRecUnweighted", "Numerator (Reconstructed Momentum - No femto weight)", nbins, qmin, qmax, nbins, qmin, qmax, nbins, qmin, qmax); fNumeratorGenUnweighted = new TH3F(prefix + "NumGenUnweighted", "Numerator (Generated Momentum - No femto weight)", nbins, qmin, qmax, nbins, qmin, qmax, nbins, qmin, qmax); fDenominatorGenerated = new TH3F(prefix + "DenGen", "Denominator (MC-Generated Momentum)", nbins, qmin, qmax, nbins, qmin, qmax, nbins, qmin, qmax); fDenominatorReconstructed = new TH3F(prefix + "DenRec", "Denominator (Reconstructed Momentum)", nbins, qmin, qmax, nbins, qmin, qmax, nbins, qmin, qmax); fDenominatorGenWeighted = new TH3F(prefix + "DenGenWeight", "Denominator (Generated Momentum - with femto weight)", nbins, qmin, qmax, nbins, qmin, qmax, nbins, qmin, qmax); fDenominatorRecWeighted = new TH3F(prefix + "DenRecWeight", "Numerator (Reconstructed Momentum - with femto weight)", nbins, qmin, qmax, nbins, qmin, qmax, nbins, qmin, qmax); fNumeratorGenerated->Sumw2(); fNumeratorReconstructed->Sumw2(); fDenominatorGenWeighted->Sumw2(); fDenominatorRecWeighted->Sumw2(); } AliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(UInt_t nbins, Double_t qmax): AliFemtoModelCorrFctnTrueQ3D(nbins, -abs(qmax), abs(qmax)) { } AliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(UInt_t nbins, Double_t qmin, Double_t qmax): AliFemtoModelCorrFctnTrueQ3D("", nbins, qmin, qmax) { } AliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(const AliFemtoModelCorrFctnTrueQ3D::Parameters &params): AliFemtoModelCorrFctnTrueQ3D(params.prefix.Data(), params.bin_count, params.qmin, params.qmax) { SetManager(params.mc_manager); } AliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(const AliFemtoModelCorrFctnTrueQ3D& orig): AliFemtoCorrFctn(orig) , fManager(orig.fManager) , fNumeratorGenerated(nullptr) , fNumeratorReconstructed(nullptr) , fNumeratorGenUnweighted(nullptr) , fNumeratorRecUnweighted(nullptr) , fDenominatorGenerated(nullptr) , fDenominatorReconstructed(nullptr) , fDenominatorGenWeighted(nullptr) , fDenominatorRecWeighted(nullptr) , fRng(new TRandom()) { fNumeratorGenerated = new TH3F(*orig.fNumeratorGenerated); fNumeratorReconstructed = new TH3F(*orig.fNumeratorReconstructed); fDenominatorGenerated = new TH3F(*orig.fDenominatorGenerated); fDenominatorReconstructed = new TH3F(*orig.fDenominatorReconstructed); fNumeratorGenUnweighted = new TH3F(*orig.fNumeratorGenUnweighted); fNumeratorRecUnweighted = new TH3F(*orig.fNumeratorRecUnweighted); fDenominatorGenWeighted = new TH3F(*orig.fDenominatorGenWeighted); fDenominatorRecWeighted = new TH3F(*orig.fDenominatorRecWeighted); } AliFemtoModelCorrFctnTrueQ3D& AliFemtoModelCorrFctnTrueQ3D::operator=(const AliFemtoModelCorrFctnTrueQ3D&) { return *this; } AliFemtoModelCorrFctnTrueQ3D::~AliFemtoModelCorrFctnTrueQ3D() { delete fNumeratorGenerated; delete fNumeratorReconstructed; delete fDenominatorGenerated; delete fDenominatorReconstructed; delete fNumeratorGenUnweighted; delete fNumeratorRecUnweighted; delete fDenominatorGenWeighted; delete fDenominatorRecWeighted; delete fRng; } TList* AliFemtoModelCorrFctnTrueQ3D::GetOutputList() { TList *result = new TList(); AppendOutputList(*result); return result; } TList* AliFemtoModelCorrFctnTrueQ3D::AppendOutputList(TList &list) { AddOutputObjectsTo(list); return &list; } void AliFemtoModelCorrFctnTrueQ3D::AddOutputObjectsTo(TCollection &list) { list.Add(fNumeratorGenerated); list.Add(fNumeratorReconstructed); list.Add(fDenominatorGenerated); list.Add(fDenominatorReconstructed); list.Add(fNumeratorGenUnweighted); list.Add(fNumeratorRecUnweighted); list.Add(fDenominatorGenWeighted); list.Add(fDenominatorRecWeighted); } /// Return q{Out-Side-Long} tuple, calculated from momentum vectors p1 & p2 static std::tuple<Double_t, Double_t, Double_t> Qcms(const AliFemtoLorentzVector &p1, const AliFemtoLorentzVector &p2) { const AliFemtoLorentzVector p = p1 + p2, d = p1 - p2; Double_t k1 = p.Perp(), k2 = d.x()*p.x() + d.y()*p.y(); // relative momentum out component in lab frame Double_t qout = (k1 == 0) ? 0.0 : k2/k1; // relative momentum side component in lab frame Double_t qside = (k1 == 0) ? 0.0 : 2.0 * (p2.x()*p1.y() - p1.x()*p2.y())/k1; // relative momentum component in lab frame Double_t beta = p.z()/p.t(), gamma = 1.0 / TMath::Sqrt((1.0-beta)*(1.0+beta)); Double_t qlong = gamma * (d.z() - beta*d.t()); // double qlong = (p.t()*d.z() - p.z()*d.t()) / TMath::Sqrt(p.t()*p.t() - p.z()*p.z()); return std::make_tuple(qout, qside, qlong); } static void AddPair(const AliFemtoParticle &particle1, const AliFemtoParticle &particle2, TH3F &gen_hist, TH3F &rec_hist, TH3F &gen_hist_unw, TH3F &rec_hist_unw, Double_t weight) { Double_t q_out, q_side, q_long; // Fill reconstructed histogram with "standard" particle momentum std::tie(q_out, q_side, q_long) = Qcms(particle1.FourMomentum(), particle2.FourMomentum()); Int_t rec_bin = gen_hist.GetBin(q_out, q_long, q_side); if (!(gen_hist.IsBinOverflow(rec_bin) or gen_hist.IsBinUnderflow(rec_bin))) { rec_hist.Fill(q_out, q_side, q_long, weight); rec_hist_unw.Fill(q_out, q_side, q_long, 1.0); } // Get generated momentum from hidden info const AliFemtoModelHiddenInfo *info1 = dynamic_cast<const AliFemtoModelHiddenInfo*>(particle1.HiddenInfo()), *info2 = dynamic_cast<const AliFemtoModelHiddenInfo*>(particle2.HiddenInfo()); if (info1 == nullptr || info2 == nullptr) { return; } const Float_t mass1 = info1->GetMass(), mass2 = info2->GetMass(); // block all zero-mass particles from the correlation function if (mass1 == 0.0 || mass2 == 0.0) { return; } const AliFemtoThreeVector *true_momentum1 = info1->GetTrueMomentum(), *true_momentum2 = info2->GetTrueMomentum(); const Double_t e1 = sqrt(mass1 * mass1 + true_momentum1->Mag2()), e2 = sqrt(mass2 * mass2 + true_momentum2->Mag2()); const AliFemtoLorentzVector p1 = AliFemtoLorentzVector(e1, *true_momentum1), p2 = AliFemtoLorentzVector(e2, *true_momentum2); // Fill generated-momentum histogram with "true" particle momentum std::tie(q_out, q_side, q_long) = Qcms(p1, p2); Int_t gen_bin = gen_hist.GetBin(q_out, q_long, q_side); if (!(gen_hist.IsBinOverflow(gen_bin) or gen_hist.IsBinUnderflow(gen_bin))) { gen_hist.Fill(q_out, q_side, q_long, weight); gen_hist_unw.Fill(q_out, q_side, q_long, weight); } } void AliFemtoModelCorrFctnTrueQ3D::AddRealPair(AliFemtoPair *pair) { const AliFemtoParticle *p1 = pair->Track1(), *p2 = pair->Track2(); // randomize to avoid ordering biases if (fRng->Uniform() >= 0.5) { std::swap(p1, p2); } AddPair(*p1, *p2, *fNumeratorGenUnweighted, *fNumeratorRecUnweighted, *fNumeratorGenerated, *fNumeratorReconstructed, fManager->GetWeight(pair)); } void AliFemtoModelCorrFctnTrueQ3D::AddMixedPair(AliFemtoPair *pair) { const AliFemtoParticle *p1 = pair->Track1(), *p2 = pair->Track2(); // randomize to avoid ordering biases if (fRng->Uniform() >= 0.5) { std::swap(p1, p2); } AddPair(*p1, *p2, *fDenominatorGenWeighted, *fDenominatorRecWeighted, *fDenominatorGenerated, *fDenominatorReconstructed, fManager->GetWeight(pair)); } AliFemtoString AliFemtoModelCorrFctnTrueQ3D::Report() { AliFemtoString report; return report; } void AliFemtoModelCorrFctnTrueQ3D::Finish() { #if ROOT_VERSION_CODE >= ROOT_VERSION(6, 10, 8) // remove {under,over}flow to shrink file sizes fNumeratorGenerated->ClearUnderflowAndOverflow(); fNumeratorReconstructed->ClearUnderflowAndOverflow(); fDenominatorGenerated->ClearUnderflowAndOverflow(); fDenominatorReconstructed->ClearUnderflowAndOverflow(); fNumeratorGenUnweighted->ClearUnderflowAndOverflow(); fNumeratorRecUnweighted->ClearUnderflowAndOverflow(); fDenominatorGenWeighted->ClearUnderflowAndOverflow(); fDenominatorRecWeighted->ClearUnderflowAndOverflow(); #endif } <commit_msg>AliFemtoModelCorrFctnTrueQ3D - Replace GetBin with FindBin<commit_after>/// /// \file AliFemtoModelCorrFctnTrueQ3D.cxx /// #include "AliFemtoModelCorrFctnTrueQ3D.h" #include "AliFemtoPair.h" #include "AliFemtoModelManager.h" #include "AliFemtoModelHiddenInfo.h" #include <TH3F.h> #include <TList.h> #include <TString.h> #include <TRandom.h> #include <tuple> #include <iostream> AliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(): AliFemtoModelCorrFctnTrueQ3D("CF_TrueQ3D_") { } AliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(const char *prefix): AliFemtoModelCorrFctnTrueQ3D(prefix, 56, 0.14) { } AliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(const char *prefix, UInt_t nbins, Double_t qmax): AliFemtoModelCorrFctnTrueQ3D(prefix, nbins, -qmax, qmax) { } AliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(const TString &prefix, UInt_t nbins, Double_t qmin, Double_t qmax): AliFemtoCorrFctn() , fManager(nullptr) , fNumeratorGenerated(nullptr) , fNumeratorReconstructed(nullptr) , fNumeratorGenUnweighted(nullptr) , fNumeratorRecUnweighted(nullptr) , fDenominatorGenerated(nullptr) , fDenominatorReconstructed(nullptr) , fDenominatorGenWeighted(nullptr) , fDenominatorRecWeighted(nullptr) , fRng(new TRandom()) { fNumeratorGenerated = new TH3F(prefix + "NumGen", "Numerator (MC-Generated Momentum)", nbins, qmin, qmax, nbins, qmin, qmax, nbins, qmin, qmax); fNumeratorReconstructed = new TH3F(prefix + "NumRec", "Numerator (Reconstructed Momentum)", nbins, qmin, qmax, nbins, qmin, qmax, nbins, qmin, qmax); fNumeratorRecUnweighted = new TH3F(prefix + "NumRecUnweighted", "Numerator (Reconstructed Momentum - No femto weight)", nbins, qmin, qmax, nbins, qmin, qmax, nbins, qmin, qmax); fNumeratorGenUnweighted = new TH3F(prefix + "NumGenUnweighted", "Numerator (Generated Momentum - No femto weight)", nbins, qmin, qmax, nbins, qmin, qmax, nbins, qmin, qmax); fDenominatorGenerated = new TH3F(prefix + "DenGen", "Denominator (MC-Generated Momentum)", nbins, qmin, qmax, nbins, qmin, qmax, nbins, qmin, qmax); fDenominatorReconstructed = new TH3F(prefix + "DenRec", "Denominator (Reconstructed Momentum)", nbins, qmin, qmax, nbins, qmin, qmax, nbins, qmin, qmax); fDenominatorGenWeighted = new TH3F(prefix + "DenGenWeight", "Denominator (Generated Momentum - with femto weight)", nbins, qmin, qmax, nbins, qmin, qmax, nbins, qmin, qmax); fDenominatorRecWeighted = new TH3F(prefix + "DenRecWeight", "Numerator (Reconstructed Momentum - with femto weight)", nbins, qmin, qmax, nbins, qmin, qmax, nbins, qmin, qmax); fNumeratorGenerated->Sumw2(); fNumeratorReconstructed->Sumw2(); fDenominatorGenWeighted->Sumw2(); fDenominatorRecWeighted->Sumw2(); } AliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(UInt_t nbins, Double_t qmax): AliFemtoModelCorrFctnTrueQ3D(nbins, -abs(qmax), abs(qmax)) { } AliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(UInt_t nbins, Double_t qmin, Double_t qmax): AliFemtoModelCorrFctnTrueQ3D("", nbins, qmin, qmax) { } AliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(const AliFemtoModelCorrFctnTrueQ3D::Parameters &params): AliFemtoModelCorrFctnTrueQ3D(params.prefix.Data(), params.bin_count, params.qmin, params.qmax) { SetManager(params.mc_manager); } AliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(const AliFemtoModelCorrFctnTrueQ3D& orig): AliFemtoCorrFctn(orig) , fManager(orig.fManager) , fNumeratorGenerated(nullptr) , fNumeratorReconstructed(nullptr) , fNumeratorGenUnweighted(nullptr) , fNumeratorRecUnweighted(nullptr) , fDenominatorGenerated(nullptr) , fDenominatorReconstructed(nullptr) , fDenominatorGenWeighted(nullptr) , fDenominatorRecWeighted(nullptr) , fRng(new TRandom()) { fNumeratorGenerated = new TH3F(*orig.fNumeratorGenerated); fNumeratorReconstructed = new TH3F(*orig.fNumeratorReconstructed); fDenominatorGenerated = new TH3F(*orig.fDenominatorGenerated); fDenominatorReconstructed = new TH3F(*orig.fDenominatorReconstructed); fNumeratorGenUnweighted = new TH3F(*orig.fNumeratorGenUnweighted); fNumeratorRecUnweighted = new TH3F(*orig.fNumeratorRecUnweighted); fDenominatorGenWeighted = new TH3F(*orig.fDenominatorGenWeighted); fDenominatorRecWeighted = new TH3F(*orig.fDenominatorRecWeighted); } AliFemtoModelCorrFctnTrueQ3D& AliFemtoModelCorrFctnTrueQ3D::operator=(const AliFemtoModelCorrFctnTrueQ3D&) { return *this; } AliFemtoModelCorrFctnTrueQ3D::~AliFemtoModelCorrFctnTrueQ3D() { delete fNumeratorGenerated; delete fNumeratorReconstructed; delete fDenominatorGenerated; delete fDenominatorReconstructed; delete fNumeratorGenUnweighted; delete fNumeratorRecUnweighted; delete fDenominatorGenWeighted; delete fDenominatorRecWeighted; delete fRng; } TList* AliFemtoModelCorrFctnTrueQ3D::GetOutputList() { TList *result = new TList(); AppendOutputList(*result); return result; } TList* AliFemtoModelCorrFctnTrueQ3D::AppendOutputList(TList &list) { AddOutputObjectsTo(list); return &list; } void AliFemtoModelCorrFctnTrueQ3D::AddOutputObjectsTo(TCollection &list) { list.Add(fNumeratorGenerated); list.Add(fNumeratorReconstructed); list.Add(fDenominatorGenerated); list.Add(fDenominatorReconstructed); list.Add(fNumeratorGenUnweighted); list.Add(fNumeratorRecUnweighted); list.Add(fDenominatorGenWeighted); list.Add(fDenominatorRecWeighted); } /// Return q{Out-Side-Long} tuple, calculated from momentum vectors p1 & p2 static std::tuple<Double_t, Double_t, Double_t> Qcms(const AliFemtoLorentzVector &p1, const AliFemtoLorentzVector &p2) { const AliFemtoLorentzVector p = p1 + p2, d = p1 - p2; Double_t k1 = p.Perp(), k2 = d.x()*p.x() + d.y()*p.y(); // relative momentum out component in lab frame Double_t qout = (k1 == 0) ? 0.0 : k2/k1; // relative momentum side component in lab frame Double_t qside = (k1 == 0) ? 0.0 : 2.0 * (p2.x()*p1.y() - p1.x()*p2.y())/k1; // relative momentum component in lab frame Double_t beta = p.z()/p.t(), gamma = 1.0 / TMath::Sqrt((1.0-beta)*(1.0+beta)); Double_t qlong = gamma * (d.z() - beta*d.t()); // double qlong = (p.t()*d.z() - p.z()*d.t()) / TMath::Sqrt(p.t()*p.t() - p.z()*p.z()); return std::make_tuple(qout, qside, qlong); } static void AddPair(const AliFemtoParticle &particle1, const AliFemtoParticle &particle2, TH3F &gen_hist, TH3F &rec_hist, TH3F &gen_hist_unw, TH3F &rec_hist_unw, Double_t weight) { Double_t q_out, q_side, q_long; // Fill reconstructed histogram with "standard" particle momentum std::tie(q_out, q_side, q_long) = Qcms(particle1.FourMomentum(), particle2.FourMomentum()); Int_t rec_bin = gen_hist.FindBin(q_out, q_long, q_side); if (!(gen_hist.IsBinOverflow(rec_bin) or gen_hist.IsBinUnderflow(rec_bin))) { rec_hist.Fill(q_out, q_side, q_long, weight); rec_hist_unw.Fill(q_out, q_side, q_long, 1.0); } // Get generated momentum from hidden info const AliFemtoModelHiddenInfo *info1 = dynamic_cast<const AliFemtoModelHiddenInfo*>(particle1.HiddenInfo()), *info2 = dynamic_cast<const AliFemtoModelHiddenInfo*>(particle2.HiddenInfo()); if (info1 == nullptr || info2 == nullptr) { return; } const Float_t mass1 = info1->GetMass(), mass2 = info2->GetMass(); // block all zero-mass particles from the correlation function if (mass1 == 0.0 || mass2 == 0.0) { return; } const AliFemtoThreeVector *true_momentum1 = info1->GetTrueMomentum(), *true_momentum2 = info2->GetTrueMomentum(); const Double_t e1 = sqrt(mass1 * mass1 + true_momentum1->Mag2()), e2 = sqrt(mass2 * mass2 + true_momentum2->Mag2()); const AliFemtoLorentzVector p1 = AliFemtoLorentzVector(e1, *true_momentum1), p2 = AliFemtoLorentzVector(e2, *true_momentum2); // Fill generated-momentum histogram with "true" particle momentum std::tie(q_out, q_side, q_long) = Qcms(p1, p2); Int_t gen_bin = gen_hist.FindBin(q_out, q_long, q_side); if (!(gen_hist.IsBinOverflow(gen_bin) or gen_hist.IsBinUnderflow(gen_bin))) { gen_hist.Fill(q_out, q_side, q_long, weight); gen_hist_unw.Fill(q_out, q_side, q_long, weight); } } void AliFemtoModelCorrFctnTrueQ3D::AddRealPair(AliFemtoPair *pair) { const AliFemtoParticle *p1 = pair->Track1(), *p2 = pair->Track2(); // randomize to avoid ordering biases if (fRng->Uniform() >= 0.5) { std::swap(p1, p2); } AddPair(*p1, *p2, *fNumeratorGenUnweighted, *fNumeratorRecUnweighted, *fNumeratorGenerated, *fNumeratorReconstructed, fManager->GetWeight(pair)); } void AliFemtoModelCorrFctnTrueQ3D::AddMixedPair(AliFemtoPair *pair) { const AliFemtoParticle *p1 = pair->Track1(), *p2 = pair->Track2(); // randomize to avoid ordering biases if (fRng->Uniform() >= 0.5) { std::swap(p1, p2); } AddPair(*p1, *p2, *fDenominatorGenWeighted, *fDenominatorRecWeighted, *fDenominatorGenerated, *fDenominatorReconstructed, fManager->GetWeight(pair)); } AliFemtoString AliFemtoModelCorrFctnTrueQ3D::Report() { AliFemtoString report; return report; } void AliFemtoModelCorrFctnTrueQ3D::Finish() { #if ROOT_VERSION_CODE >= ROOT_VERSION(6, 10, 8) // remove {under,over}flow to shrink file sizes fNumeratorGenerated->ClearUnderflowAndOverflow(); fNumeratorReconstructed->ClearUnderflowAndOverflow(); fDenominatorGenerated->ClearUnderflowAndOverflow(); fDenominatorReconstructed->ClearUnderflowAndOverflow(); fNumeratorGenUnweighted->ClearUnderflowAndOverflow(); fNumeratorRecUnweighted->ClearUnderflowAndOverflow(); fDenominatorGenWeighted->ClearUnderflowAndOverflow(); fDenominatorRecWeighted->ClearUnderflowAndOverflow(); #endif } <|endoftext|>
<commit_before>#pragma once #include "boost_defs.hpp" #include "dispatcher.hpp" #include "iokit_utility.hpp" #include "logger.hpp" #include "services.hpp" #include <boost/signals2.hpp> namespace krbn { namespace monitor { namespace service_monitor { class service_monitor final : pqrs::dispatcher::extra::dispatcher_client { public: // Signals (invoked from the shared dispatcher thread) boost::signals2::signal<void(std::shared_ptr<services>)> service_detected; boost::signals2::signal<void(std::shared_ptr<services>)> service_removed; // Methods service_monitor(const service_monitor&) = delete; service_monitor(CFDictionaryRef _Nonnull matching_dictionary) : matching_dictionary_(matching_dictionary), notification_port_(nullptr), matched_notification_(IO_OBJECT_NULL), terminated_notification_(IO_OBJECT_NULL) { if (matching_dictionary_) { CFRetain(matching_dictionary_); } } virtual ~service_monitor(void) { detach_from_dispatcher([this] { stop(); }); if (matching_dictionary_) { CFRelease(matching_dictionary_); } } void async_start(void) { enqueue_to_dispatcher([this] { start(); }); } void async_stop(void) { enqueue_to_dispatcher([this] { stop(); }); } void async_invoke_service_detected(void) { enqueue_to_dispatcher([this] { if (matching_dictionary_) { CFRetain(matching_dictionary_); io_iterator_t it; auto kr = IOServiceGetMatchingServices(kIOMasterPortDefault, matching_dictionary_, &it); if (kr != KERN_SUCCESS) { logger::get_logger().error("IOServiceGetMatchingServices is failed: {0}", iokit_utility::get_error_name(kr)); } else { matched_callback(it); IOObjectRelease(it); } } }); } private: // This method is executed in the dispatcher thread. void start(void) { if (!notification_port_) { notification_port_ = IONotificationPortCreate(kIOMasterPortDefault); if (!notification_port_) { logger::get_logger().error("IONotificationPortCreate is failed."); return; } if (auto loop_source = IONotificationPortGetRunLoopSource(notification_port_)) { CFRunLoopAddSource(CFRunLoopGetMain(), loop_source, kCFRunLoopCommonModes); } else { logger::get_logger().error("IONotificationPortGetRunLoopSource is failed."); } } // kIOMatchedNotification if (!matched_notification_) { if (matching_dictionary_) { CFRetain(matching_dictionary_); auto kr = IOServiceAddMatchingNotification(notification_port_, kIOFirstMatchNotification, matching_dictionary_, &(service_monitor::static_matched_callback), static_cast<void*>(this), &matched_notification_); if (kr != kIOReturnSuccess) { logger::get_logger().error("IOServiceAddMatchingNotification is failed: {0}", iokit_utility::get_error_name(kr)); CFRelease(matching_dictionary_); } else { matched_callback(matched_notification_); } } } // kIOTerminatedNotification if (!terminated_notification_) { if (matching_dictionary_) { CFRetain(matching_dictionary_); auto kr = IOServiceAddMatchingNotification(notification_port_, kIOTerminatedNotification, matching_dictionary_, &(service_monitor::static_terminated_callback), static_cast<void*>(this), &terminated_notification_); if (kr != kIOReturnSuccess) { logger::get_logger().error("IOServiceAddMatchingNotification is failed: {0}", iokit_utility::get_error_name(kr)); CFRelease(matching_dictionary_); } else { terminated_callback(terminated_notification_); } } } } // This method is executed in the dispatcher thread. void stop(void) { if (matched_notification_) { IOObjectRelease(matched_notification_); matched_notification_ = IO_OBJECT_NULL; } if (terminated_notification_) { IOObjectRelease(terminated_notification_); terminated_notification_ = IO_OBJECT_NULL; } if (notification_port_) { if (auto loop_source = IONotificationPortGetRunLoopSource(notification_port_)) { CFRunLoopRemoveSource(CFRunLoopGetMain(), loop_source, kCFRunLoopCommonModes); } IONotificationPortDestroy(notification_port_); notification_port_ = nullptr; } } static void static_matched_callback(void* _Nonnull refcon, io_iterator_t iterator) { auto self = static_cast<service_monitor*>(refcon); if (!self) { return; } self->matched_callback(iterator); } void matched_callback(io_iterator_t iterator) { auto s = std::make_shared<services>(iterator); enqueue_to_dispatcher([this, s] { service_detected(s); }); } static void static_terminated_callback(void* _Nonnull refcon, io_iterator_t iterator) { auto self = static_cast<service_monitor*>(refcon); if (!self) { return; } self->terminated_callback(iterator); } void terminated_callback(io_iterator_t iterator) { auto s = std::make_shared<services>(iterator); enqueue_to_dispatcher([this, s] { service_removed(s); }); } CFDictionaryRef _Nonnull matching_dictionary_; IONotificationPortRef _Nullable notification_port_; io_iterator_t matched_notification_; io_iterator_t terminated_notification_; }; } // namespace service_monitor } // namespace monitor } // namespace krbn <commit_msg>use cf_ptr<commit_after>#pragma once #include "boost_defs.hpp" #include "cf_utility.hpp" #include "dispatcher.hpp" #include "iokit_utility.hpp" #include "logger.hpp" #include "services.hpp" #include <boost/signals2.hpp> namespace krbn { namespace monitor { namespace service_monitor { class service_monitor final : pqrs::dispatcher::extra::dispatcher_client { public: // Signals (invoked from the shared dispatcher thread) boost::signals2::signal<void(std::shared_ptr<services>)> service_detected; boost::signals2::signal<void(std::shared_ptr<services>)> service_removed; // Methods service_monitor(const service_monitor&) = delete; service_monitor(CFDictionaryRef _Nonnull matching_dictionary) : matching_dictionary_(matching_dictionary), notification_port_(nullptr), matched_notification_(IO_OBJECT_NULL), terminated_notification_(IO_OBJECT_NULL) { } virtual ~service_monitor(void) { detach_from_dispatcher([this] { stop(); }); } void async_start(void) { enqueue_to_dispatcher([this] { start(); }); } void async_stop(void) { enqueue_to_dispatcher([this] { stop(); }); } void async_invoke_service_detected(void) { enqueue_to_dispatcher([this] { if (*matching_dictionary_) { CFRetain(*matching_dictionary_); io_iterator_t it; auto kr = IOServiceGetMatchingServices(kIOMasterPortDefault, *matching_dictionary_, &it); if (kr != KERN_SUCCESS) { logger::get_logger().error("IOServiceGetMatchingServices is failed: {0}", iokit_utility::get_error_name(kr)); } else { matched_callback(it); IOObjectRelease(it); } } }); } private: // This method is executed in the dispatcher thread. void start(void) { if (!notification_port_) { notification_port_ = IONotificationPortCreate(kIOMasterPortDefault); if (!notification_port_) { logger::get_logger().error("IONotificationPortCreate is failed."); return; } if (auto loop_source = IONotificationPortGetRunLoopSource(notification_port_)) { CFRunLoopAddSource(CFRunLoopGetMain(), loop_source, kCFRunLoopCommonModes); } else { logger::get_logger().error("IONotificationPortGetRunLoopSource is failed."); } } // kIOMatchedNotification if (!matched_notification_) { if (*matching_dictionary_) { CFRetain(*matching_dictionary_); auto kr = IOServiceAddMatchingNotification(notification_port_, kIOFirstMatchNotification, *matching_dictionary_, &(service_monitor::static_matched_callback), static_cast<void*>(this), &matched_notification_); if (kr != kIOReturnSuccess) { logger::get_logger().error("IOServiceAddMatchingNotification is failed: {0}", iokit_utility::get_error_name(kr)); CFRelease(*matching_dictionary_); } else { matched_callback(matched_notification_); } } } // kIOTerminatedNotification if (!terminated_notification_) { if (*matching_dictionary_) { CFRetain(*matching_dictionary_); auto kr = IOServiceAddMatchingNotification(notification_port_, kIOTerminatedNotification, *matching_dictionary_, &(service_monitor::static_terminated_callback), static_cast<void*>(this), &terminated_notification_); if (kr != kIOReturnSuccess) { logger::get_logger().error("IOServiceAddMatchingNotification is failed: {0}", iokit_utility::get_error_name(kr)); CFRelease(*matching_dictionary_); } else { terminated_callback(terminated_notification_); } } } } // This method is executed in the dispatcher thread. void stop(void) { if (matched_notification_) { IOObjectRelease(matched_notification_); matched_notification_ = IO_OBJECT_NULL; } if (terminated_notification_) { IOObjectRelease(terminated_notification_); terminated_notification_ = IO_OBJECT_NULL; } if (notification_port_) { if (auto loop_source = IONotificationPortGetRunLoopSource(notification_port_)) { CFRunLoopRemoveSource(CFRunLoopGetMain(), loop_source, kCFRunLoopCommonModes); } IONotificationPortDestroy(notification_port_); notification_port_ = nullptr; } } static void static_matched_callback(void* _Nonnull refcon, io_iterator_t iterator) { auto self = static_cast<service_monitor*>(refcon); if (!self) { return; } self->matched_callback(iterator); } void matched_callback(io_iterator_t iterator) { auto s = std::make_shared<services>(iterator); enqueue_to_dispatcher([this, s] { service_detected(s); }); } static void static_terminated_callback(void* _Nonnull refcon, io_iterator_t iterator) { auto self = static_cast<service_monitor*>(refcon); if (!self) { return; } self->terminated_callback(iterator); } void terminated_callback(io_iterator_t iterator) { auto s = std::make_shared<services>(iterator); enqueue_to_dispatcher([this, s] { service_removed(s); }); } cf_utility::cf_ptr<CFDictionaryRef> matching_dictionary_; IONotificationPortRef _Nullable notification_port_; io_iterator_t matched_notification_; io_iterator_t terminated_notification_; }; } // namespace service_monitor } // namespace monitor } // namespace krbn <|endoftext|>
<commit_before>#pragma once #if ENABLE_S3 #include "ref.hh" #include <optional> namespace Aws { namespace Client { class ClientConfiguration; } } namespace Aws { namespace S3 { class S3Client; } } namespace nix { struct S3Helper { ref<Aws::Client::ClientConfiguration> config; ref<Aws::S3::S3Client> client; S3Helper(const std::string & profile, const std::string & region, const std::string & scheme, const std::string & endpoint); ref<Aws::Client::ClientConfiguration> makeConfig(const std::string & region, const std::string & scheme, const std::string & endpoint); struct FileTransferResult { std::optional<std::string> data; unsigned int durationMs; }; FileTransferResult getObject( const std::string & bucketName, const std::string & key); }; } #endif <commit_msg>Fix libcxx build<commit_after>#pragma once #if ENABLE_S3 #include "ref.hh" #include <optional> #include <string> namespace Aws { namespace Client { class ClientConfiguration; } } namespace Aws { namespace S3 { class S3Client; } } namespace nix { struct S3Helper { ref<Aws::Client::ClientConfiguration> config; ref<Aws::S3::S3Client> client; S3Helper(const std::string & profile, const std::string & region, const std::string & scheme, const std::string & endpoint); ref<Aws::Client::ClientConfiguration> makeConfig(const std::string & region, const std::string & scheme, const std::string & endpoint); struct FileTransferResult { std::optional<std::string> data; unsigned int durationMs; }; FileTransferResult getObject( const std::string & bucketName, const std::string & key); }; } #endif <|endoftext|>
<commit_before>#ifndef __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS_HPP__ #define __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS_HPP__ #include <stan/prob/distributions/univariate/continuous/beta.hpp> #include <stan/prob/distributions/univariate/continuous/cauchy.hpp> #include <stan/prob/distributions/univariate/continuous/chi_square.hpp> #include <stan/prob/distributions/univariate/continuous/double_exponential.hpp> #include <stan/prob/distributions/univariate/continuous/exponential.hpp> #include <stan/prob/distributions/univariate/continuous/exp_mod_normal.hpp> #include <stan/prob/distributions/univariate/continuous/gamma.hpp> #include <stan/prob/distributions/univariate/continuous/gumbel.hpp> #include <stan/prob/distributions/univariate/continuous/inv_chi_square.hpp> #include <stan/prob/distributions/univariate/continuous/inv_gamma.hpp> #include <stan/prob/distributions/univariate/continuous/logistic.hpp> #include <stan/prob/distributions/univariate/continuous/lognormal.hpp> #include <stan/prob/distributions/univariate/continuous/normal.hpp> #include <stan/prob/distributions/univariate/continuous/pareto.hpp> #include <stan/prob/distributions/univariate/continuous/rayleigh.hpp> #include <stan/prob/distributions/univariate/continuous/scaled_inv_chi_square.hpp> #include <stan/prob/distributions/univariate/continuous/skew_normal.hpp> #include <stan/prob/distributions/univariate/continuous/student_t.hpp> #include <stan/prob/distributions/univariate/continuous/uniform.hpp> #include <stan/prob/distributions/univariate/continuous/von_mises.hpp> #include <stan/prob/distributions/univariate/continuous/weibull.hpp> #endif <commit_msg>add wiener to continuous.hpp<commit_after>#ifndef __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS_HPP__ #define __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS_HPP__ #include <stan/prob/distributions/univariate/continuous/beta.hpp> #include <stan/prob/distributions/univariate/continuous/cauchy.hpp> #include <stan/prob/distributions/univariate/continuous/chi_square.hpp> #include <stan/prob/distributions/univariate/continuous/double_exponential.hpp> #include <stan/prob/distributions/univariate/continuous/exponential.hpp> #include <stan/prob/distributions/univariate/continuous/exp_mod_normal.hpp> #include <stan/prob/distributions/univariate/continuous/gamma.hpp> #include <stan/prob/distributions/univariate/continuous/gumbel.hpp> #include <stan/prob/distributions/univariate/continuous/inv_chi_square.hpp> #include <stan/prob/distributions/univariate/continuous/inv_gamma.hpp> #include <stan/prob/distributions/univariate/continuous/logistic.hpp> #include <stan/prob/distributions/univariate/continuous/lognormal.hpp> #include <stan/prob/distributions/univariate/continuous/normal.hpp> #include <stan/prob/distributions/univariate/continuous/pareto.hpp> #include <stan/prob/distributions/univariate/continuous/rayleigh.hpp> #include <stan/prob/distributions/univariate/continuous/scaled_inv_chi_square.hpp> #include <stan/prob/distributions/univariate/continuous/skew_normal.hpp> #include <stan/prob/distributions/univariate/continuous/student_t.hpp> #include <stan/prob/distributions/univariate/continuous/uniform.hpp> #include <stan/prob/distributions/univariate/continuous/von_mises.hpp> #include <stan/prob/distributions/univariate/continuous/weibull.hpp> #include <stan/prob/distributions/univariate/continuous/wiener.hpp> #endif <|endoftext|>
<commit_before>// -*- C++ -*- // Implementation of: ???? // // Copyright (C) 2010 by John Weiss // This program is free software; you can redistribute it and/or modify // it under the terms of the Artistic License, included as the file // "LICENSE" in the source code archive. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // // You should have received a copy of the file "LICENSE", containing // the License John Weiss originally placed this program under. // static const char* const xFOOx_cc__="RCS $Id$"; // Includes // #include <iostream> #include <string> #include <vector> #include <exception> //#include <boost/something.hpp> //TODO// Note: The guts of the ProgramOptions helper code now resides in its //TODO// own class. You will need to do one of the following: //TODO// 1. Use -ljpwTools and -I$JPWLIB_BASE/include //TODO// 2. Symlink to the following files in $JPWLIB_BASE/src: //TODO// - tracing/Trace.{h,cc} //TODO// - tracing/LibTrace.h //TODO// - boost_helpers/ProgramOptions_Base.{h,cc} //TODO// You'll need to add the two *.cc files to your Makefile. //TODO// 3. Like #2, but copy the files instead of symlinking to them. #include "ProgramOptions_Base.h" #include "xFOOx.h" // // Using Decls. // using std::string; using std::vector; using std::exception; using std::cerr; using std::cout; using std::endl; using std::flush; // // Static variables // // // Typedefs // ///////////////////////// // // Class: ProgramOptions // // NOTE: // // When using boost::program_options, you need to compile or link using: // '-lboost_program_options-mt' // (Check your Boost build to see if you have to remove the '-mt' suffix.) class ProgramOptions : public jpwTools::boost_helpers::ProgramOptions_Base { typedef jpwTools::boost_helpers::ProgramOptions_Base Base_t; public: // Member variables for individually storing program options. // ADD HERE: /* example_type myExample; */ // C'tor // // There are a few different ways you can use the base-class. // explicit ProgramOptions(const string& programName) : Base_t(programName) { m__docDetails_FakeOption[2] = 0; } // Implement this function (see below). void defineOptionsAndVariables(); // Implement this function (below), or remove this fn. bool validateParsedOptions(); }; ///////////////////////// // // ProgramOptions Member Functions // // Define your commandline options in this function. // // The options "--help", "--verbose", "--config", and "--help-config" will // be defined for you. No need to put them in here. void ProgramOptions::defineOptionsAndVariables() { using namespace boost::program_options; // // Commandline-only Options // //----- // About the Documentation String: // // - Long lines are automatically wrapped. // - It can contain '\n' chars. // - Any space following a '\n' indents the first line accordingly, but // not any wrapped lines. // - The '\t' character is always removed. // - A '\t' character in the first "line" adds extra indentation to all // subsequently-wrapped lines. Its position marks the position of the // left margin for the wrapped lines. //----- addOpts() ("exampleOpt,e", "Documentation of the --exampleOpt.") //("ex2", value<example_type>(&myExample) // "Example with a specific storage variable.") ("ex3", value<int>()->default_value(42), "Example with a default value and fixed data type.") //("xil", value< <std::vector<int> >()->compositing(), // "Example of a \"list option\". Specifying \"--xil\" multiple " // "times just adds another element to the list.") ; // Define the "Hidden" Commandline Parameters // // These options will not appear in the "usage" message. /* addOpts(Base_t::HIDDEN) ("secretExampleOpt,s", bool_switch(&secretExampleSwitch), "Documentation of the --secretExampleOpt.\t" "This example shows how to define a \"boolean switch\" option." ) ("ex2", value<int>(&m_ex2)->default_value(-1) ->implicit_value(42)->zero_tokens(), "Example of how to have an option that takes a value, but doesn't " "_require_ it.\n" "In this example, the variable \"m_ex2\" has the value '-1' if the " "option isn't specified on the cmdline. Specifying \"--ex2\" " "sets \"m_ex2\" to '42'. Specifying \"--ex2=12345\" sets " "\"m_ex2\" to '12345', the value used.") ("ex3", value<int>(&m_ztEx)->zero_tokens(), "Like \"--ex2\", but without a default value or an implicit " "value. If you pass \"--ex3\" on the commandline, \"m_ztEx\" " "isn't set. Instead, you'll have to use " "'progOptInst[\"ex3\"].empty()' to determine if it's set (where " "'progOptInst' is a ProgramOptions object).") ; */ // // The Positional Parameters: // /* addPosnParam("pp1", "The description of the first positional parameter."); addPosnParam("pp2", "The description of the second positional parameter."); addPosnParam("pp_list::all_remaining", //value< std::vector<std::string> >, "The description of the remaining positional parameters.", -1); */ // // The Configuration File Variables: // /* addCfgVars() ("example", "An example") ("group1.example", "An example of a configfile variable in a group. You can specify " "the group using ini-file syntax, or you can use Java-style " "synax for the group+variable name.") ("oddname.group.foo", "Here, if you used ini-file style groups, you'd have to specify " "[oddname.group] as the group heading. Cfgfile vars never have " "a '.' in their names, unless you're using Java-style syntax.") ; */ // // Configuration File Variables that can also be passed as Commandline // Options: // /* addCfgVars(Base_t::SHARED) ("sharedEx", "A common opt.") ; // Can also do this: //addOpts(Base_t::SHARED) // ("sharedEx", "A common opt.") // ; */ // // Define the additional/verbose/enhanced configuration file // documentation: // addConfigHelpDetails("\n" "* \tHeading\n" "\n \t" // Line end/begin boilerplate "Some stuff about one or more of the config " "file variables." "\n"); } // Performs more complex program option validation. // // Remove this override if you don't need it. bool ProgramOptions::validateParsedOptions() { // Example: Handle a missing configuration file. // Delete or modify as needed. if(m__cfgfile.empty()) { throw boost::program_options::invalid_option_value( "No configuration file specified! \"--config\" is " "a required option."); } } ///////////////////////// // // General Function Definitions // ///////////////////////// // // Functions "main()" and "cxx_main()" // // This is where all of your main handling should go. int cxx_main(const string& myName, const string& myPath, const ProgramOptions& opts) { // How to retrieve entries from 'opts': // opts["option"].as<type>() // // To check if the option is unset or wasn't passed: // opts["option"].empty() // // To check if an option with a default value wasn't passed: // opts["option"].defaulted() } int main(int argc, char* argv[]) { // Split off the name of the executable from its path. string myName(argv[0]); string::size_type last_pathsep = myName.find_last_of('/'); string myPath; if(last_pathsep != string::npos) { myPath = myName.substr(0, last_pathsep+1); myName.erase(0, last_pathsep+1); } // Call cxx_main(), which is where almost all of your code should go. try { ProgramOptions myOpts(myName); myOpts.parse(argc, argv); return cxx_main(myName, myPath, myOpts); } catch(FooException& ex) { cerr << "Caught Foo: " << ex.what() << endl; return 3; } catch(boost::program_options::duplicate_option_error& ex) { cerr << "Fatal Internal Programming Error: " << endl << ex.what() << endl << endl; return 9; } catch(boost::program_options::error& ex) { cerr << "Error while parsing program options: " << ex.what() << endl << endl << "Rerun as \"" << myName << " --help\" for usage." << endl; return 1; } catch(exception& ex) { cerr << endl << "(Std) Exception caught: \"" << ex.what() << "\"" << endl; } catch(...) { cerr << "Unknown exception caught." << endl; } return -1; } ///////////////////////// // // End <commit_msg>- Renaming variable that hides a member.<commit_after>// -*- C++ -*- // Implementation of: ???? // // Copyright (C) 2010 by John Weiss // This program is free software; you can redistribute it and/or modify // it under the terms of the Artistic License, included as the file // "LICENSE" in the source code archive. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // // You should have received a copy of the file "LICENSE", containing // the License John Weiss originally placed this program under. // static const char* const xFOOx_cc__="RCS $Id$"; // Includes // #include <iostream> #include <string> #include <vector> #include <exception> //#include <boost/something.hpp> //TODO// Note: The guts of the ProgramOptions helper code now resides in its //TODO// own class. You will need to do one of the following: //TODO// 1. Use -ljpwTools and -I$JPWLIB_BASE/include //TODO// 2. Symlink to the following files in $JPWLIB_BASE/src: //TODO// - tracing/Trace.{h,cc} //TODO// - tracing/LibTrace.h //TODO// - boost_helpers/ProgramOptions_Base.{h,cc} //TODO// You'll need to add the two *.cc files to your Makefile. //TODO// 3. Like #2, but copy the files instead of symlinking to them. #include "ProgramOptions_Base.h" #include "xFOOx.h" // // Using Decls. // using std::string; using std::vector; using std::exception; using std::cerr; using std::cout; using std::endl; using std::flush; // // Static variables // // // Typedefs // ///////////////////////// // // Class: ProgramOptions // // NOTE: // // When using boost::program_options, you need to compile or link using: // '-lboost_program_options-mt' // (Check your Boost build to see if you have to remove the '-mt' suffix.) class ProgramOptions : public jpwTools::boost_helpers::ProgramOptions_Base { typedef jpwTools::boost_helpers::ProgramOptions_Base Base_t; public: // Member variables for individually storing program options. // ADD HERE: /* example_type myExample; */ // C'tor // // There are a few different ways you can use the base-class. // explicit ProgramOptions(const string& theProgramName) : Base_t(theProgramName) { m__docDetails_FakeOption[2] = 0; } // Implement this function (see below). void defineOptionsAndVariables(); // Implement this function (below), or remove this fn. bool validateParsedOptions(); }; ///////////////////////// // // ProgramOptions Member Functions // // Define your commandline options in this function. // // The options "--help", "--verbose", "--config", and "--help-config" will // be defined for you. No need to put them in here. void ProgramOptions::defineOptionsAndVariables() { using namespace boost::program_options; // // Commandline-only Options // //----- // About the Documentation String: // // - Long lines are automatically wrapped. // - It can contain '\n' chars. // - Any space following a '\n' indents the first line accordingly, but // not any wrapped lines. // - The '\t' character is always removed. // - A '\t' character in the first "line" adds extra indentation to all // subsequently-wrapped lines. Its position marks the position of the // left margin for the wrapped lines. //----- addOpts() ("exampleOpt,e", "Documentation of the --exampleOpt.") //("ex2", value<example_type>(&myExample) // "Example with a specific storage variable.") ("ex3", value<int>()->default_value(42), "Example with a default value and fixed data type.") //("xil", value< <std::vector<int> >()->compositing(), // "Example of a \"list option\". Specifying \"--xil\" multiple " // "times just adds another element to the list.") ; // Define the "Hidden" Commandline Parameters // // These options will not appear in the "usage" message. /* addOpts(Base_t::HIDDEN) ("secretExampleOpt,s", bool_switch(&secretExampleSwitch), "Documentation of the --secretExampleOpt.\t" "This example shows how to define a \"boolean switch\" option." ) ("ex2", value<int>(&m_ex2)->default_value(-1) ->implicit_value(42)->zero_tokens(), "Example of how to have an option that takes a value, but doesn't " "_require_ it.\n" "In this example, the variable \"m_ex2\" has the value '-1' if the " "option isn't specified on the cmdline. Specifying \"--ex2\" " "sets \"m_ex2\" to '42'. Specifying \"--ex2=12345\" sets " "\"m_ex2\" to '12345', the value used.") ("ex3", value<int>(&m_ztEx)->zero_tokens(), "Like \"--ex2\", but without a default value or an implicit " "value. If you pass \"--ex3\" on the commandline, \"m_ztEx\" " "isn't set. Instead, you'll have to use " "'progOptInst[\"ex3\"].empty()' to determine if it's set (where " "'progOptInst' is a ProgramOptions object).") ; */ // // The Positional Parameters: // /* addPosnParam("pp1", "The description of the first positional parameter."); addPosnParam("pp2", "The description of the second positional parameter."); addPosnParam("pp_list::all_remaining", //value< std::vector<std::string> >, "The description of the remaining positional parameters.", -1); */ // // The Configuration File Variables: // /* addCfgVars() ("example", "An example") ("group1.example", "An example of a configfile variable in a group. You can specify " "the group using ini-file syntax, or you can use Java-style " "synax for the group+variable name.") ("oddname.group.foo", "Here, if you used ini-file style groups, you'd have to specify " "[oddname.group] as the group heading. Cfgfile vars never have " "a '.' in their names, unless you're using Java-style syntax.") ; */ // // Configuration File Variables that can also be passed as Commandline // Options: // /* addCfgVars(Base_t::SHARED) ("sharedEx", "A common opt.") ; // Can also do this: //addOpts(Base_t::SHARED) // ("sharedEx", "A common opt.") // ; */ // // Define the additional/verbose/enhanced configuration file // documentation: // addConfigHelpDetails("\n" "* \tHeading\n" "\n \t" // Line end/begin boilerplate "Some stuff about one or more of the config " "file variables." "\n"); } // Performs more complex program option validation. // // Remove this override if you don't need it. bool ProgramOptions::validateParsedOptions() { // Example: Handle a missing configuration file. // Delete or modify as needed. if(m__cfgfile.empty()) { throw boost::program_options::invalid_option_value( "No configuration file specified! \"--config\" is " "a required option."); } } ///////////////////////// // // General Function Definitions // ///////////////////////// // // Functions "main()" and "cxx_main()" // // This is where all of your main handling should go. int cxx_main(const string& myName, const string& myPath, const ProgramOptions& opts) { // How to retrieve entries from 'opts': // opts["option"].as<type>() // // To check if the option is unset or wasn't passed: // opts["option"].empty() // // To check if an option with a default value wasn't passed: // opts["option"].defaulted() } int main(int argc, char* argv[]) { // Split off the name of the executable from its path. string myName(argv[0]); string::size_type last_pathsep = myName.find_last_of('/'); string myPath; if(last_pathsep != string::npos) { myPath = myName.substr(0, last_pathsep+1); myName.erase(0, last_pathsep+1); } // Call cxx_main(), which is where almost all of your code should go. try { ProgramOptions myOpts(myName); myOpts.parse(argc, argv); return cxx_main(myName, myPath, myOpts); } catch(FooException& ex) { cerr << "Caught Foo: " << ex.what() << endl; return 3; } catch(boost::program_options::duplicate_option_error& ex) { cerr << "Fatal Internal Programming Error: " << endl << ex.what() << endl << endl; return 9; } catch(boost::program_options::error& ex) { cerr << "Error while parsing program options: " << ex.what() << endl << endl << "Rerun as \"" << myName << " --help\" for usage." << endl; return 1; } catch(exception& ex) { cerr << endl << "(Std) Exception caught: \"" << ex.what() << "\"" << endl; } catch(...) { cerr << "Unknown exception caught." << endl; } return -1; } ///////////////////////// // // End <|endoftext|>
<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/tpu/tpu_api_dlsym_initializer.h" #include <dlfcn.h> #include "tensorflow/core/platform/errors.h" #include "tensorflow/core/platform/status.h" #if !defined(PLATFORM_GOOGLE) #include "tensorflow/core/tpu/tpu_api.h" #include "tensorflow/core/tpu/tpu_system_device.h" #include "tensorflow/stream_executor/tpu/tpu_platform.h" #endif #define TFTPU_SET_FN(Struct, FnName) \ Struct->FnName##Fn = \ reinterpret_cast<decltype(FnName)*>(dlsym(library_handle, #FnName)); \ if (!(Struct->FnName##Fn)) { \ LOG(ERROR) << #FnName " not available in this library."; \ return errors::Unimplemented(#FnName " not available in this library."); \ } // Reminder: Update tpu_library_loader_windows.cc if you are adding new publicly // visible methods. namespace tensorflow { namespace tpu { #if defined(PLATFORM_GOOGLE) Status InitializeTpuLibrary(void* library_handle) { return errors::Unimplemented("You must statically link in a TPU library."); } #else // PLATFORM_GOOGLE #include "tensorflow/core/tpu/tpu_library_init_fns.inc" Status InitializeTpuLibrary(void* library_handle) { Status s = InitializeTpuStructFns(library_handle); // TPU platform registration must only be performed after the library is // loaded. We do not want to register a TPU platform in XLA without the // supporting library providing the necessary APIs. if (s.ok()) { // TODO(frankchn): Make initialization actually work // Initialize TPU platform when the platform code is loaded from a library. // InitializeApiFn()->TfTpu_InitializeFn(); RegisterTpuPlatform(); RegisterTpuSystemDevice(); } return s; } bool FindAndLoadTpuLibrary() { void* library = dlopen("libtftpu.so", RTLD_NOW); if (library) { InitializeTpuLibrary(library); } return true; } static bool tpu_library_finder = FindAndLoadTpuLibrary(); #endif // PLATFORM_GOOGLE } // namespace tpu } // namespace tensorflow <commit_msg>Call TfTpu_Initialize() to initialize relevant bits of the TPU framework when loading the TPU library<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/tpu/tpu_api_dlsym_initializer.h" #include <dlfcn.h> #include "tensorflow/core/platform/errors.h" #include "tensorflow/core/platform/status.h" #if !defined(PLATFORM_GOOGLE) #include "tensorflow/core/tpu/tpu_api.h" #include "tensorflow/core/tpu/tpu_system_device.h" #include "tensorflow/stream_executor/tpu/tpu_platform.h" #endif #define TFTPU_SET_FN(Struct, FnName) \ Struct->FnName##Fn = \ reinterpret_cast<decltype(FnName)*>(dlsym(library_handle, #FnName)); \ if (!(Struct->FnName##Fn)) { \ LOG(ERROR) << #FnName " not available in this library."; \ return errors::Unimplemented(#FnName " not available in this library."); \ } // Reminder: Update tpu_library_loader_windows.cc if you are adding new publicly // visible methods. namespace tensorflow { namespace tpu { #if defined(PLATFORM_GOOGLE) Status InitializeTpuLibrary(void* library_handle) { return errors::Unimplemented("You must statically link in a TPU library."); } #else // PLATFORM_GOOGLE #include "tensorflow/core/tpu/tpu_library_init_fns.inc" Status InitializeTpuLibrary(void* library_handle) { Status s = InitializeTpuStructFns(library_handle); // TPU platform registration must only be performed after the library is // loaded. We do not want to register a TPU platform in XLA without the // supporting library providing the necessary APIs. if (s.ok()) { void (*initialize_fn)(); initialize_fn = reinterpret_cast<decltype(initialize_fn)>( dlsym(library_handle, "TfTpu_Initialize")); (*initialize_fn)(); RegisterTpuPlatform(); RegisterTpuSystemDevice(); } return s; } bool FindAndLoadTpuLibrary() { void* library = dlopen("libtftpu.so", RTLD_NOW); if (library) { InitializeTpuLibrary(library); } return true; } static bool tpu_library_finder = FindAndLoadTpuLibrary(); #endif // PLATFORM_GOOGLE } // namespace tpu } // namespace tensorflow <|endoftext|>
<commit_before>#include <iostream> #include <algorithm> #include <vector> #include <cmath> #include <ctime> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include "gaussian.h" #define BLUR_RADIUS 3 #define PATH_COUNT 16 #define MAX_SHORT 65535 #define SMALL_PENALTY 3 #define LARGE_PENALTY 20 #define DEBUG false struct path { short rowDiff; short colDiff; short index; }; void printArray(unsigned short ***array, int rows, int cols, int depth) { for (int d = 0; d < depth; ++d) { std::cout << "disparity: " << d << std::endl; for (int row = 0; row < rows; ++row) { for (int col = 0; col < cols; ++col) { std::cout << "\t" << array[row][col][d]; } std::cout << std::endl; } } } unsigned short calculatePixelCostOneWayBT(int row, int leftCol, int rightCol, const cv::Mat &leftImage, const cv::Mat &rightImage) { char leftValue, rightValue, beforeRightValue, afterRightValue, rightValueMinus, rightValuePlus, rightValueMin, rightValueMax; leftValue = leftImage.at<uchar>(row, leftCol); rightValue = rightImage.at<uchar>(row, rightCol); if (rightCol > 0) { beforeRightValue = rightImage.at<uchar>(row, rightCol - 1); } else { beforeRightValue = rightValue; } if (rightCol + 1 < rightImage.cols) { afterRightValue = rightImage.at<uchar>(row, rightCol + 1); } else { afterRightValue = rightValue; } rightValueMinus = round((rightValue + beforeRightValue) / 2.f); rightValuePlus = round((rightValue + afterRightValue) / 2.f); rightValueMin = std::min(rightValue, std::min(rightValueMinus, rightValuePlus)); rightValueMax = std::max(rightValue, std::max(rightValueMinus, rightValuePlus)); return std::max(0, std::max((leftValue - rightValueMax), (rightValueMin - leftValue))); } inline unsigned short calculatePixelCostBT(int row, int leftCol, int rightCol, const cv::Mat &leftImage, const cv::Mat &rightImage) { return std::min(calculatePixelCostOneWayBT(row, leftCol, rightCol, leftImage, rightImage), calculatePixelCostOneWayBT(row, rightCol, leftCol, rightImage, leftImage)); } void calculatePixelCost(cv::Mat &firstImage, cv::Mat &secondImage, int disparityRange, unsigned short ***C) { for (int row = 0; row < firstImage.rows; ++row) { for (int col = 0; col < firstImage.cols; ++col) { for (int d = 0; d < disparityRange; ++d) { C[row][col][d] = calculatePixelCostBT(row, col, col - d, firstImage, secondImage); } } } } void initializePaths(std::vector<path> &paths, unsigned short pathCount) { for (unsigned short i = 0; i < pathCount; ++i) { paths.push_back(path()); } if(paths.size() >= 2) { paths[0].rowDiff = 0; paths[0].colDiff = 1; paths[0].index = 0; paths[1].rowDiff = 0; paths[1].colDiff = -1; paths[1].index = 1; } if(paths.size() >= 4) { paths[2].rowDiff = -1; paths[2].colDiff = 0; paths[2].index = 2; paths[3].rowDiff = 1; paths[3].colDiff = 0; paths[3].index = 3; } if(paths.size() >= 8) { paths[4].rowDiff = -1; paths[4].colDiff = 1; paths[4].index = 4; paths[5].rowDiff = 1; paths[5].colDiff = 1; paths[5].index = 5; paths[6].rowDiff = 1; paths[6].colDiff = -1; paths[6].index = 6; paths[7].rowDiff = -1; paths[7].colDiff = -1; paths[7].index = 7; } if(paths.size() >= 16) { paths[8].rowDiff = -2; paths[8].colDiff = 1; paths[8].index = 8; paths[9].rowDiff = -2; paths[9].colDiff = -1; paths[9].index = 9; paths[10].rowDiff = 2; paths[10].colDiff = 1; paths[10].index = 10; paths[11].rowDiff = 2; paths[11].colDiff = -1; paths[11].index = 11; paths[12].rowDiff = 1; paths[12].colDiff = -2; paths[12].index = 12; paths[13].rowDiff = -1; paths[13].colDiff = -2; paths[13].index = 13; paths[14].rowDiff = 1; paths[14].colDiff = 2; paths[14].index = 14; paths[15].rowDiff = -1; paths[15].colDiff = 2; paths[15].index = 15; } } unsigned short aggregateCost(int row, int col, int d, path &p, int rows, int cols, int disparityRange, unsigned short ***C, unsigned short ****A, unsigned short ***S, unsigned int iter) { unsigned short aggregatedCost = 0; aggregatedCost += C[row][col][d]; if(DEBUG) { for (unsigned int i = 0; i < iter; ++i) { printf(" "); } printf("{P%d}[%d][%d](d%d)\n", p.index, row, col, d); } if (A[p.index][row][col][d] != MAX_SHORT) { if(DEBUG) { for (unsigned int i = 0; i < iter; ++i) { printf(" "); } printf("{P%d}[%d][%d](d%d)-> %d<CACHED>\n", p.index, row, col, d, A[p.index][row][col][d]); } return A[p.index][row][col][d]; } if (row + p.rowDiff < 0 || row + p.rowDiff >= rows || col + p.colDiff < 0 || col + p.colDiff >= cols) { // border A[p.index][row][col][d] = aggregatedCost; if(DEBUG) { for (unsigned int i = 0; i < iter; ++i) { printf(" "); } printf("{P%d}[%d][%d](d%d)-> %d <BORDER>\n", p.index, row, col, d, A[p.index][row][col][d]); } return A[p.index][row][col][d]; return aggregatedCost; } unsigned short minPrev, minPrevOther, prev, prevPlus, prevMinus; prev = minPrev = minPrevOther = prevPlus = prevMinus = MAX_SHORT; for (int disp = 0; disp < disparityRange; ++disp) { unsigned short tmp = aggregateCost(row + p.rowDiff, col + p.colDiff, disp, p, rows, cols, disparityRange, C, A, S, ++iter); if(minPrev > tmp) { minPrev = tmp; } if(disp == d) { prev = tmp; } else if(disp == d + 1) { prevPlus = tmp; } else if (disp == d - 1) { prevMinus = tmp; } else { if(minPrevOther > tmp + LARGE_PENALTY) { minPrevOther = tmp + LARGE_PENALTY; } } } aggregatedCost += std::min(std::min((int)prevPlus + SMALL_PENALTY, (int)prevMinus + SMALL_PENALTY), std::min((int)prev, (int)minPrevOther + LARGE_PENALTY)); aggregatedCost -= minPrev; A[p.index][row][col][d] = aggregatedCost; if(DEBUG) { for (unsigned int i = 0; i < iter; ++i) { printf(" "); } printf("{P%d}[%d][%d](d%d)-> %d<CALCULATED>\n", p.index, row, col, d, A[p.index][row][col][d]); } return aggregatedCost; } void aggregateCosts(int rows, int cols, int disparityRange, std::vector<path> &paths, unsigned short ***C, unsigned short ****A, unsigned short ***S) { for (unsigned long p = 0; p < paths.size(); ++p) { for (int row = 0; row < rows; ++row) { for (int col = 0; col < cols; ++col) { for (int d = 0; d < disparityRange; ++d) { S[row][col][d] += aggregateCost(row, col, d, paths[p], rows, cols, disparityRange, C, A, S, 0); } } } } } void computeDisparity(unsigned short ***S, int rows, int cols, int disparityRange, cv::Mat &disparityMap) { unsigned int disparity = 0, minCost; for (int row = 0; row < rows; ++row) { for (int col = 0; col < cols; ++col) { minCost = 65535; for (int d = disparityRange - 1; d >= 0; --d) { if(minCost > S[row][col][d]) { minCost = S[row][col][d]; disparity = d; } } disparityMap.at<uchar>(row, col) = disparity; } } } void saveDisparityMap(cv::Mat &disparityMap, int disparityRange, char* outputFile) { double factor = 256.0 / disparityRange; for (int row = 0; row < disparityMap.rows; ++row) { for (int col = 0; col < disparityMap.cols; ++col) { disparityMap.at<uchar>(row, col) *= factor; } } cv::imwrite(outputFile, disparityMap); } int main(int argc, char** argv) { if (argc != 5) { std::cerr << "Usage: " << argv[0] << " <left image> <right image> <output image file> <disparity range>" << std::endl; return -1; } char *firstFileName = argv[1]; char *secondFileName = argv[2]; char *outFileName = argv[3]; cv::Mat firstImage; cv::Mat secondImage; firstImage = cv::imread(firstFileName, CV_LOAD_IMAGE_GRAYSCALE); secondImage = cv::imread(secondFileName, CV_LOAD_IMAGE_GRAYSCALE); if(!firstImage.data || !secondImage.data) { std::cerr << "Could not open or find one of the images!" << std::endl; return -1; } unsigned int disparityRange = atoi(argv[4]); unsigned short ***C; // pixel cost array W x H x D unsigned short ***S; // aggregated cost array W x H x D unsigned short ****A; // path cost array P x W x H x D std::vector<path> paths; initializePaths(paths, PATH_COUNT); /* * TODO * variable LARGE_PENALTY */ clock_t begin = clock(); std::cout << "Allocating space..." << std::endl; // allocate cost arrays C = new unsigned short**[firstImage.rows]; S = new unsigned short**[firstImage.rows]; for (int row = 0; row < firstImage.rows; ++row) { C[row] = new unsigned short*[firstImage.cols]; S[row] = new unsigned short*[firstImage.cols](); for (int col = 0; col < firstImage.cols; ++col) { C[row][col] = new unsigned short[disparityRange]; S[row][col] = new unsigned short[disparityRange](); // initialize to 0 } } A = new unsigned short ***[paths.size()]; for (unsigned long p = 0; p < paths.size(); ++p) { A[p] = new unsigned short **[firstImage.rows]; for (int row = 0; row < firstImage.rows; ++row) { A[p][row] = new unsigned short*[firstImage.cols]; for (int col = 0; col < firstImage.cols; ++col) { A[p][row][col] = new unsigned short[disparityRange]; for (unsigned int d = 0; d < disparityRange; ++d) { A[p][row][col][d] = MAX_SHORT; } } } } std::cout << "Smoothing images..." << std::endl; grayscaleGaussianBlur(firstImage, firstImage, BLUR_RADIUS); grayscaleGaussianBlur(secondImage, secondImage, BLUR_RADIUS); std::cout << "Calculating pixel cost for the image..." << std::endl; calculatePixelCost(firstImage, secondImage, disparityRange, C); if(DEBUG) { printArray(C, firstImage.rows, firstImage.cols, disparityRange); } std::cout << "Aggregating costs..." << std::endl; aggregateCosts(firstImage.rows, firstImage.cols, disparityRange, paths, C, A, S); cv::Mat disparityMap = cv::Mat(cv::Size(firstImage.cols, firstImage.rows), CV_8UC1, cv::Scalar::all(0)); std::cout << "Computing disparity..." << std::endl; computeDisparity(S, firstImage.rows, firstImage.cols, disparityRange, disparityMap); clock_t end = clock(); double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC; printf("Done in %.2lf seconds.\n", elapsed_secs); saveDisparityMap(disparityMap, disparityRange, outFileName); return 0; }<commit_msg>Significantly decreased memory usage by reusing path cost cache<commit_after>#include <iostream> #include <algorithm> #include <vector> #include <cmath> #include <ctime> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include "gaussian.h" #define BLUR_RADIUS 3 #define PATH_COUNT 16 #define MAX_SHORT std::numeric_limits<unsigned short>::max() #define SMALL_PENALTY 3 #define LARGE_PENALTY 20 #define DEBUG false struct path { short rowDiff; short colDiff; short index; }; void printArray(unsigned short ***array, int rows, int cols, int depth) { for (int d = 0; d < depth; ++d) { std::cout << "disparity: " << d << std::endl; for (int row = 0; row < rows; ++row) { for (int col = 0; col < cols; ++col) { std::cout << "\t" << array[row][col][d]; } std::cout << std::endl; } } } unsigned short calculatePixelCostOneWayBT(int row, int leftCol, int rightCol, const cv::Mat &leftImage, const cv::Mat &rightImage) { char leftValue, rightValue, beforeRightValue, afterRightValue, rightValueMinus, rightValuePlus, rightValueMin, rightValueMax; leftValue = leftImage.at<uchar>(row, leftCol); rightValue = rightImage.at<uchar>(row, rightCol); if (rightCol > 0) { beforeRightValue = rightImage.at<uchar>(row, rightCol - 1); } else { beforeRightValue = rightValue; } if (rightCol + 1 < rightImage.cols) { afterRightValue = rightImage.at<uchar>(row, rightCol + 1); } else { afterRightValue = rightValue; } rightValueMinus = round((rightValue + beforeRightValue) / 2.f); rightValuePlus = round((rightValue + afterRightValue) / 2.f); rightValueMin = std::min(rightValue, std::min(rightValueMinus, rightValuePlus)); rightValueMax = std::max(rightValue, std::max(rightValueMinus, rightValuePlus)); return std::max(0, std::max((leftValue - rightValueMax), (rightValueMin - leftValue))); } inline unsigned short calculatePixelCostBT(int row, int leftCol, int rightCol, const cv::Mat &leftImage, const cv::Mat &rightImage) { return std::min(calculatePixelCostOneWayBT(row, leftCol, rightCol, leftImage, rightImage), calculatePixelCostOneWayBT(row, rightCol, leftCol, rightImage, leftImage)); } void calculatePixelCost(cv::Mat &firstImage, cv::Mat &secondImage, int disparityRange, unsigned short ***C) { for (int row = 0; row < firstImage.rows; ++row) { for (int col = 0; col < firstImage.cols; ++col) { for (int d = 0; d < disparityRange; ++d) { C[row][col][d] = calculatePixelCostBT(row, col, col - d, firstImage, secondImage); } } } } void initializePaths(std::vector<path> &paths, unsigned short pathCount) { for (unsigned short i = 0; i < pathCount; ++i) { paths.push_back(path()); } if(paths.size() >= 2) { paths[0].rowDiff = 0; paths[0].colDiff = 1; paths[0].index = 0; paths[1].rowDiff = 0; paths[1].colDiff = -1; paths[1].index = 1; } if(paths.size() >= 4) { paths[2].rowDiff = -1; paths[2].colDiff = 0; paths[2].index = 2; paths[3].rowDiff = 1; paths[3].colDiff = 0; paths[3].index = 3; } if(paths.size() >= 8) { paths[4].rowDiff = -1; paths[4].colDiff = 1; paths[4].index = 4; paths[5].rowDiff = 1; paths[5].colDiff = 1; paths[5].index = 5; paths[6].rowDiff = 1; paths[6].colDiff = -1; paths[6].index = 6; paths[7].rowDiff = -1; paths[7].colDiff = -1; paths[7].index = 7; } if(paths.size() >= 16) { paths[8].rowDiff = -2; paths[8].colDiff = 1; paths[8].index = 8; paths[9].rowDiff = -2; paths[9].colDiff = -1; paths[9].index = 9; paths[10].rowDiff = 2; paths[10].colDiff = 1; paths[10].index = 10; paths[11].rowDiff = 2; paths[11].colDiff = -1; paths[11].index = 11; paths[12].rowDiff = 1; paths[12].colDiff = -2; paths[12].index = 12; paths[13].rowDiff = -1; paths[13].colDiff = -2; paths[13].index = 13; paths[14].rowDiff = 1; paths[14].colDiff = 2; paths[14].index = 14; paths[15].rowDiff = -1; paths[15].colDiff = 2; paths[15].index = 15; } } unsigned short aggregateCost(int row, int col, int d, path &p, int rows, int cols, int disparityRange, unsigned short ***C, unsigned short ***A, unsigned short ***S, unsigned int iter) { unsigned short aggregatedCost = 0; aggregatedCost += C[row][col][d]; if(DEBUG) { for (unsigned int i = 0; i < iter; ++i) { printf(" "); } printf("{P%d}[%d][%d](d%d)\n", p.index, row, col, d); } if (A[row][col][d] != MAX_SHORT) { if(DEBUG) { for (unsigned int i = 0; i < iter; ++i) { printf(" "); } printf("{P%d}[%d][%d](d%d)-> %d<CACHED>\n", p.index, row, col, d, A[row][col][d]); } return A[row][col][d]; } if (row + p.rowDiff < 0 || row + p.rowDiff >= rows || col + p.colDiff < 0 || col + p.colDiff >= cols) { // border A[row][col][d] = aggregatedCost; if(DEBUG) { for (unsigned int i = 0; i < iter; ++i) { printf(" "); } printf("{P%d}[%d][%d](d%d)-> %d <BORDER>\n", p.index, row, col, d, A[row][col][d]); } return A[row][col][d]; return aggregatedCost; } unsigned short minPrev, minPrevOther, prev, prevPlus, prevMinus; prev = minPrev = minPrevOther = prevPlus = prevMinus = MAX_SHORT; for (int disp = 0; disp < disparityRange; ++disp) { unsigned short tmp = aggregateCost(row + p.rowDiff, col + p.colDiff, disp, p, rows, cols, disparityRange, C, A, S, ++iter); if(minPrev > tmp) { minPrev = tmp; } if(disp == d) { prev = tmp; } else if(disp == d + 1) { prevPlus = tmp; } else if (disp == d - 1) { prevMinus = tmp; } else { if(minPrevOther > tmp + LARGE_PENALTY) { minPrevOther = tmp + LARGE_PENALTY; } } } aggregatedCost += std::min(std::min((int)prevPlus + SMALL_PENALTY, (int)prevMinus + SMALL_PENALTY), std::min((int)prev, (int)minPrevOther + LARGE_PENALTY)); aggregatedCost -= minPrev; A[row][col][d] = aggregatedCost; if(DEBUG) { for (unsigned int i = 0; i < iter; ++i) { printf(" "); } printf("{P%d}[%d][%d](d%d)-> %d<CALCULATED>\n", p.index, row, col, d, A[row][col][d]); } return aggregatedCost; } void aggregateCosts(int rows, int cols, int disparityRange, std::vector<path> &paths, unsigned short ***C, unsigned short ***A, unsigned short ***S) { for (unsigned long p = 0; p < paths.size(); ++p) { // TODO clear path array unsigned int size = rows * cols * disparityRange; for (int row = 0; row < rows; ++row) { for (int col = 0; col < cols; ++col) { for (int d = 0; d < disparityRange; ++d) { A[row][col][d] = MAX_SHORT; } } } for (int row = 0; row < rows; ++row) { for (int col = 0; col < cols; ++col) { for (int d = 0; d < disparityRange; ++d) { S[row][col][d] += aggregateCost(row, col, d, paths[p], rows, cols, disparityRange, C, A, S, 0); } } } } } void computeDisparity(unsigned short ***S, int rows, int cols, int disparityRange, cv::Mat &disparityMap) { unsigned int disparity = 0, minCost; for (int row = 0; row < rows; ++row) { for (int col = 0; col < cols; ++col) { minCost = MAX_SHORT; for (int d = disparityRange - 1; d >= 0; --d) { if(minCost > S[row][col][d]) { minCost = S[row][col][d]; disparity = d; } } disparityMap.at<uchar>(row, col) = disparity; } } } void saveDisparityMap(cv::Mat &disparityMap, int disparityRange, char* outputFile) { double factor = 256.0 / disparityRange; for (int row = 0; row < disparityMap.rows; ++row) { for (int col = 0; col < disparityMap.cols; ++col) { disparityMap.at<uchar>(row, col) *= factor; } } cv::imwrite(outputFile, disparityMap); } int main(int argc, char** argv) { if (argc != 5) { std::cerr << "Usage: " << argv[0] << " <left image> <right image> <output image file> <disparity range>" << std::endl; return -1; } char *firstFileName = argv[1]; char *secondFileName = argv[2]; char *outFileName = argv[3]; cv::Mat firstImage; cv::Mat secondImage; firstImage = cv::imread(firstFileName, CV_LOAD_IMAGE_GRAYSCALE); secondImage = cv::imread(secondFileName, CV_LOAD_IMAGE_GRAYSCALE); if(!firstImage.data || !secondImage.data) { std::cerr << "Could not open or find one of the images!" << std::endl; return -1; } unsigned int disparityRange = atoi(argv[4]); unsigned short ***C; // pixel cost array W x H x D unsigned short ***S; // aggregated cost array W x H x D unsigned short ***A; // single path cost array W x H x D std::vector<path> paths; initializePaths(paths, PATH_COUNT); /* * TODO * variable LARGE_PENALTY */ clock_t begin = clock(); std::cout << "Allocating space..." << std::endl; // allocate cost arrays C = new unsigned short**[firstImage.rows]; S = new unsigned short**[firstImage.rows]; for (int row = 0; row < firstImage.rows; ++row) { C[row] = new unsigned short*[firstImage.cols]; S[row] = new unsigned short*[firstImage.cols](); for (int col = 0; col < firstImage.cols; ++col) { C[row][col] = new unsigned short[disparityRange]; S[row][col] = new unsigned short[disparityRange](); // initialize to 0 } } A = new unsigned short **[firstImage.rows]; for (int row = 0; row < firstImage.rows; ++row) { A[row] = new unsigned short*[firstImage.cols]; for (int col = 0; col < firstImage.cols; ++col) { A[row][col] = new unsigned short[disparityRange]; for (unsigned int d = 0; d < disparityRange; ++d) { A[row][col][d] = MAX_SHORT; // TODO set before each path calculation } } } std::cout << "Smoothing images..." << std::endl; grayscaleGaussianBlur(firstImage, firstImage, BLUR_RADIUS); grayscaleGaussianBlur(secondImage, secondImage, BLUR_RADIUS); std::cout << "Calculating pixel cost for the image..." << std::endl; calculatePixelCost(firstImage, secondImage, disparityRange, C); if(DEBUG) { printArray(C, firstImage.rows, firstImage.cols, disparityRange); } std::cout << "Aggregating costs..." << std::endl; aggregateCosts(firstImage.rows, firstImage.cols, disparityRange, paths, C, A, S); cv::Mat disparityMap = cv::Mat(cv::Size(firstImage.cols, firstImage.rows), CV_8UC1, cv::Scalar::all(0)); std::cout << "Computing disparity..." << std::endl; computeDisparity(S, firstImage.rows, firstImage.cols, disparityRange, disparityMap); clock_t end = clock(); double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC; printf("Done in %.2lf seconds.\n", elapsed_secs); saveDisparityMap(disparityMap, disparityRange, outFileName); return 0; }<|endoftext|>
<commit_before>/* * Copyright (c) 2014 David Chisnall * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <iostream> #include <ctype.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <sys/resource.h> #include <time.h> #include <unistd.h> #include "parser.hh" #include "ast.hh" static int enableTiming = 0; static void logTimeSince(clock_t c1, const char *msg) { if (!enableTiming) { return; } clock_t c2 = clock(); struct rusage r; getrusage(RUSAGE_SELF, &r); fprintf(stderr, "%s took %f seconds. Peak used %ldKB.\n", msg, (static_cast<double>(c2) - static_cast<double>(c1)) / static_cast<double>(CLOCKS_PER_SEC), r.ru_maxrss); } int main(int argc, char **argv) { int iterations = 1; int useJIT = 0; int optimiseLevel = 0; int gridSize = 5; int maxValue = 1; clock_t c1; int c; while ((c = getopt(argc, argv, "ji:tO:x:m:")) != -1) { switch (c) { default: break; case 'j': useJIT = 1; break; case 'x': gridSize = strtol(optarg, 0, 10); break; case 'm': maxValue = strtol(optarg, 0, 10); break; case 'i': iterations = strtol(optarg, 0, 10); break; case 't': enableTiming = 1; break; case 'O': optimiseLevel = strtol(optarg, 0, 10); } } argc -= optind; if (argc < 1) { fprintf(stderr, "usage: %s -jt -i {iterations} -o {optimisation level} -x {grid size} -m {max initial value} {file name}\n", argv[0]); return EXIT_FAILURE; } argv += optind; // Do the parsing Parser::CellAtomParser p; pegmatite::AsciiFileInput input(open(argv[0], O_RDONLY)); std::unique_ptr<AST::StatementList> ast = 0; c1 = clock(); pegmatite::ErrorReporter err = [](const pegmatite::InputRange& r, const std::string& msg) { std::cout << "error: " << msg << std::endl; std::cout << "line " << r.start.line << ", col " << r.start.col << std::endl; }; if (!p.parse(input, p.g.statements, p.g.ignored, err, ast)) { return EXIT_FAILURE; } logTimeSince(c1, "Parsing program"); assert(ast); #ifdef DUMP_AST for (uintptr_t i=0 ; i<result->count ; i++) { printAST(result->list[i]); putchar('\n'); } #endif #ifdef STATIC_TESTING_GRID int16_t oldgrid[] = { 0,0,0,0,0, 0,0,0,0,0, 0,1,1,1,0, 0,0,0,0,0, 0,0,0,0,0 }; int16_t newgrid[25]; gridSize = 5; int16_t *g1 = oldgrid; int16_t *g2 = newgrid; #else int16_t *g1 = reinterpret_cast<int16_t*>(malloc(sizeof(int16_t) * gridSize * gridSize)); int16_t *g2 = reinterpret_cast<int16_t*>(malloc(sizeof(int16_t) * gridSize * gridSize)); //int16_t *g2 = new int16_t[gridSize * gridSize]; c1 = clock(); for (int i=0 ; i<(gridSize*gridSize) ; i++) { g1[i] = random() % (maxValue + 1); } logTimeSince(c1, "Generating random grid"); #endif int i=0; if (useJIT) { c1 = clock(); Compiler::automaton ca = Compiler::compile(ast.get(), optimiseLevel); logTimeSince(c1, "Compiling"); c1 = clock(); for (int i=0 ; i<iterations ; i++) { ca(g1, g2, gridSize, gridSize); std::swap(g1, g2); } logTimeSince(c1, "Running compiled version"); } else { c1 = clock(); for (int i=0 ; i<iterations ; i++) { Interpreter::runOneStep(g1, g2, gridSize, gridSize, ast.get()); std::swap(g1, g2); } logTimeSince(c1, "Interpreting"); } for (int x=0 ; x<gridSize ; x++) { for (int y=0 ; y<gridSize ; y++) { printf("%d ", g1[i++]); } putchar('\n'); } return 0; } <commit_msg>Fix typo in help text.<commit_after>/* * Copyright (c) 2014 David Chisnall * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <iostream> #include <ctype.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <sys/resource.h> #include <time.h> #include <unistd.h> #include "parser.hh" #include "ast.hh" static int enableTiming = 0; static void logTimeSince(clock_t c1, const char *msg) { if (!enableTiming) { return; } clock_t c2 = clock(); struct rusage r; getrusage(RUSAGE_SELF, &r); fprintf(stderr, "%s took %f seconds. Peak used %ldKB.\n", msg, (static_cast<double>(c2) - static_cast<double>(c1)) / static_cast<double>(CLOCKS_PER_SEC), r.ru_maxrss); } int main(int argc, char **argv) { int iterations = 1; int useJIT = 0; int optimiseLevel = 0; int gridSize = 5; int maxValue = 1; clock_t c1; int c; while ((c = getopt(argc, argv, "ji:tO:x:m:")) != -1) { switch (c) { default: break; case 'j': useJIT = 1; break; case 'x': gridSize = strtol(optarg, 0, 10); break; case 'm': maxValue = strtol(optarg, 0, 10); break; case 'i': iterations = strtol(optarg, 0, 10); break; case 't': enableTiming = 1; break; case 'O': optimiseLevel = strtol(optarg, 0, 10); } } argc -= optind; if (argc < 1) { fprintf(stderr, "usage: %s -jt -i {iterations} -O {optimisation level} -x {grid size} -m {max initial value} {file name}\n", argv[0]); return EXIT_FAILURE; } argv += optind; // Do the parsing Parser::CellAtomParser p; pegmatite::AsciiFileInput input(open(argv[0], O_RDONLY)); std::unique_ptr<AST::StatementList> ast = 0; c1 = clock(); pegmatite::ErrorReporter err = [](const pegmatite::InputRange& r, const std::string& msg) { std::cout << "error: " << msg << std::endl; std::cout << "line " << r.start.line << ", col " << r.start.col << std::endl; }; if (!p.parse(input, p.g.statements, p.g.ignored, err, ast)) { return EXIT_FAILURE; } logTimeSince(c1, "Parsing program"); assert(ast); #ifdef DUMP_AST for (uintptr_t i=0 ; i<result->count ; i++) { printAST(result->list[i]); putchar('\n'); } #endif #ifdef STATIC_TESTING_GRID int16_t oldgrid[] = { 0,0,0,0,0, 0,0,0,0,0, 0,1,1,1,0, 0,0,0,0,0, 0,0,0,0,0 }; int16_t newgrid[25]; gridSize = 5; int16_t *g1 = oldgrid; int16_t *g2 = newgrid; #else int16_t *g1 = reinterpret_cast<int16_t*>(malloc(sizeof(int16_t) * gridSize * gridSize)); int16_t *g2 = reinterpret_cast<int16_t*>(malloc(sizeof(int16_t) * gridSize * gridSize)); //int16_t *g2 = new int16_t[gridSize * gridSize]; c1 = clock(); for (int i=0 ; i<(gridSize*gridSize) ; i++) { g1[i] = random() % (maxValue + 1); } logTimeSince(c1, "Generating random grid"); #endif int i=0; if (useJIT) { c1 = clock(); Compiler::automaton ca = Compiler::compile(ast.get(), optimiseLevel); logTimeSince(c1, "Compiling"); c1 = clock(); for (int i=0 ; i<iterations ; i++) { ca(g1, g2, gridSize, gridSize); std::swap(g1, g2); } logTimeSince(c1, "Running compiled version"); } else { c1 = clock(); for (int i=0 ; i<iterations ; i++) { Interpreter::runOneStep(g1, g2, gridSize, gridSize, ast.get()); std::swap(g1, g2); } logTimeSince(c1, "Interpreting"); } for (int x=0 ; x<gridSize ; x++) { for (int y=0 ; y<gridSize ; y++) { printf("%d ", g1[i++]); } putchar('\n'); } return 0; } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 2001, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Log$ * Revision 1.10 2001/11/21 14:30:13 knoaman * Fix for UPA checking. * * Revision 1.9 2001/11/07 21:50:28 tng * Fix comment log that lead to error. * * Revision 1.8 2001/11/07 21:12:15 tng * Performance: Create QName in ContentSpecNode only if it is a leaf/Any/PCDataNode. * * Revision 1.7 2001/10/04 15:08:56 knoaman * Add support for circular import. * * Revision 1.6 2001/08/21 15:57:51 tng * Schema: Add isAllowedByWildcard. Help from James Murphy. * * Revision 1.5 2001/05/29 19:47:22 knoaman * Fix bug - memory was not allocated before call to XMLString::subString * * Revision 1.4 2001/05/28 20:55:42 tng * Schema: Null pointer checking in SubsitutionGropuComparator * * Revision 1.3 2001/05/11 13:27:37 tng * Copyright update. * * Revision 1.2 2001/05/04 14:50:28 tng * Fixed the cvs symbols. * * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <validators/schema/SubstitutionGroupComparator.hpp> #include <validators/common/Grammar.hpp> #include <validators/schema/SchemaGrammar.hpp> #include <validators/schema/ComplexTypeInfo.hpp> #include <validators/schema/SchemaSymbols.hpp> bool SubstitutionGroupComparator::isEquivalentTo(QName* const anElement , QName* const exemplar) { if (!anElement && !exemplar) return true; if ((!anElement && exemplar) || (anElement && !exemplar)) return false; if ((XMLString::compareString(anElement->getLocalPart(), exemplar->getLocalPart()) == 0) && (anElement->getURI() == exemplar->getURI())) return true; // they're the same! if (!fGrammarResolver || !fStringPool ) { ThrowXML(RuntimeException, XMLExcepts::SubGrpComparator_NGR); } unsigned int uriId = anElement->getURI(); if (uriId == XMLContentModel::gEOCFakeId || uriId == XMLContentModel::gEpsilonFakeId || uriId == XMLElementDecl::fgPCDataElemId) return false; const XMLCh* uri = fStringPool->getValueForId(uriId); const XMLCh* localpart = anElement->getLocalPart(); // In addition to simply trying to find a chain between anElement and exemplar, // we need to make sure that no steps in the chain are blocked. // That is, at every step, we need to make sure that the element // being substituted for will permit being substituted // for, and whether the type of the element will permit derivations in // instance documents of this sort. if (!uri) return false; SchemaGrammar *sGrammar = (SchemaGrammar*) fGrammarResolver->getGrammar(uri); if (!sGrammar || sGrammar->getGrammarType() == Grammar::DTDGrammarType) return false; SchemaElementDecl* pElemDecl = (SchemaElementDecl*) sGrammar->getElemDecl(uriId, localpart, 0, Grammar::TOP_LEVEL_SCOPE); if (!pElemDecl) return false; SchemaElementDecl* anElementDecl = pElemDecl; // to preserve the ElementDecl for anElement XMLCh* substitutionGroupFullName = pElemDecl->getSubstitutionGroupName(); bool foundIt = false; while (substitutionGroupFullName) { int commaAt = XMLString::indexOf(substitutionGroupFullName, chComma); XMLCh tmpURI[256]; XMLCh tmpLocalpart[256]; if (commaAt >= 0) { if (commaAt > 0) XMLString::subString(tmpURI, substitutionGroupFullName, 0, commaAt); XMLString::subString(tmpLocalpart, substitutionGroupFullName, commaAt+1, XMLString::stringLen(substitutionGroupFullName)); } else { XMLString::subString(tmpLocalpart, substitutionGroupFullName, 0, XMLString::stringLen(substitutionGroupFullName)); } if (!tmpURI) return false; sGrammar = (SchemaGrammar*) fGrammarResolver->getGrammar(tmpURI); if (!sGrammar || sGrammar->getGrammarType() == Grammar::DTDGrammarType) return false; uriId = fStringPool->addOrFind(tmpURI); pElemDecl = (SchemaElementDecl*) sGrammar->getElemDecl(uriId, tmpLocalpart, 0, Grammar::TOP_LEVEL_SCOPE); if (!pElemDecl) return false; if ((XMLString::compareString(tmpLocalpart, exemplar->getLocalPart()) == 0) && (uriId == exemplar->getURI())) { // time to check for block value on element if((pElemDecl->getBlockSet() & SchemaSymbols::SUBSTITUTION) != 0) return false; foundIt = true; break; } substitutionGroupFullName = pElemDecl->getSubstitutionGroupName(); }//while if (!foundIt) return false; // this will contain anElement's complexType information. ComplexTypeInfo *aComplexType = anElementDecl->getComplexTypeInfo(); int exemplarBlockSet = pElemDecl->getBlockSet(); if(!aComplexType) { // check on simpleType case DatatypeValidator *anElementDV = anElementDecl->getDatatypeValidator(); DatatypeValidator *exemplarDV = pElemDecl->getDatatypeValidator(); return((anElementDV == 0) || ((anElementDV == exemplarDV) || ((exemplarBlockSet & SchemaSymbols::RESTRICTION) == 0))); } // now we have to make sure there are no blocks on the complexTypes that this is based upon int anElementDerivationMethod = aComplexType->getDerivedBy(); if((anElementDerivationMethod & exemplarBlockSet) != 0) return false; // this will contain exemplar's complexType information. ComplexTypeInfo *exemplarComplexType = pElemDecl->getComplexTypeInfo(); for(ComplexTypeInfo *tempType = aComplexType; tempType != 0 && tempType != exemplarComplexType; tempType = tempType->getBaseComplexTypeInfo()) { if((tempType->getBlockSet() & anElementDerivationMethod) != 0) return false; }//for return true; } bool SubstitutionGroupComparator::isAllowedByWildcard(SchemaGrammar* const pGrammar, QName* const element, unsigned int wuri, bool wother) { // whether the uri is allowed directly by the wildcard unsigned int uriId = element->getURI(); if ((!wother && uriId == wuri) || (wother && uriId != wuri && uriId != XMLContentModel::gEOCFakeId && uriId != XMLContentModel::gEpsilonFakeId)) { return true; } // get all elements that can substitute the current element RefHash2KeysTableOf<ElemVector>* theValidSubstitutionGroups = pGrammar->getValidSubstitutionGroups(); if (!theValidSubstitutionGroups) return false; ValueVectorOf<SchemaElementDecl*>* subsElements = theValidSubstitutionGroups->get(element->getLocalPart(), uriId); if (!subsElements) return false; // then check whether there exists one element that is allowed by the wildcard int size = subsElements->size(); for (int i = 0; i < size; i++) { unsigned int subUriId = subsElements->elementAt(i)->getElementName()->getURI(); if ((!wother && subUriId == wuri) || (wother && subUriId != wuri && subUriId != XMLContentModel::gEOCFakeId && subUriId != XMLContentModel::gEpsilonFakeId)) { return true; } } return false; } /** * End of file SubstitutionGroupComparator.cpp */ <commit_msg>Schema fix: Initialize the temporary string as null terminated.<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 2001, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Log$ * Revision 1.11 2001/11/28 16:46:03 tng * Schema fix: Initialize the temporary string as null terminated. * * Revision 1.10 2001/11/21 14:30:13 knoaman * Fix for UPA checking. * * Revision 1.9 2001/11/07 21:50:28 tng * Fix comment log that lead to error. * * Revision 1.8 2001/11/07 21:12:15 tng * Performance: Create QName in ContentSpecNode only if it is a leaf/Any/PCDataNode. * * Revision 1.7 2001/10/04 15:08:56 knoaman * Add support for circular import. * * Revision 1.6 2001/08/21 15:57:51 tng * Schema: Add isAllowedByWildcard. Help from James Murphy. * * Revision 1.5 2001/05/29 19:47:22 knoaman * Fix bug - memory was not allocated before call to XMLString::subString * * Revision 1.4 2001/05/28 20:55:42 tng * Schema: Null pointer checking in SubsitutionGropuComparator * * Revision 1.3 2001/05/11 13:27:37 tng * Copyright update. * * Revision 1.2 2001/05/04 14:50:28 tng * Fixed the cvs symbols. * * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <validators/schema/SubstitutionGroupComparator.hpp> #include <validators/common/Grammar.hpp> #include <validators/schema/SchemaGrammar.hpp> #include <validators/schema/ComplexTypeInfo.hpp> #include <validators/schema/SchemaSymbols.hpp> bool SubstitutionGroupComparator::isEquivalentTo(QName* const anElement , QName* const exemplar) { if (!anElement && !exemplar) return true; if ((!anElement && exemplar) || (anElement && !exemplar)) return false; if ((XMLString::compareString(anElement->getLocalPart(), exemplar->getLocalPart()) == 0) && (anElement->getURI() == exemplar->getURI())) return true; // they're the same! if (!fGrammarResolver || !fStringPool ) { ThrowXML(RuntimeException, XMLExcepts::SubGrpComparator_NGR); } unsigned int uriId = anElement->getURI(); if (uriId == XMLContentModel::gEOCFakeId || uriId == XMLContentModel::gEpsilonFakeId || uriId == XMLElementDecl::fgPCDataElemId) return false; const XMLCh* uri = fStringPool->getValueForId(uriId); const XMLCh* localpart = anElement->getLocalPart(); // In addition to simply trying to find a chain between anElement and exemplar, // we need to make sure that no steps in the chain are blocked. // That is, at every step, we need to make sure that the element // being substituted for will permit being substituted // for, and whether the type of the element will permit derivations in // instance documents of this sort. if (!uri) return false; SchemaGrammar *sGrammar = (SchemaGrammar*) fGrammarResolver->getGrammar(uri); if (!sGrammar || sGrammar->getGrammarType() == Grammar::DTDGrammarType) return false; SchemaElementDecl* pElemDecl = (SchemaElementDecl*) sGrammar->getElemDecl(uriId, localpart, 0, Grammar::TOP_LEVEL_SCOPE); if (!pElemDecl) return false; SchemaElementDecl* anElementDecl = pElemDecl; // to preserve the ElementDecl for anElement XMLCh* substitutionGroupFullName = pElemDecl->getSubstitutionGroupName(); bool foundIt = false; while (substitutionGroupFullName) { int commaAt = XMLString::indexOf(substitutionGroupFullName, chComma); XMLCh tmpURI[256]; tmpURI[0] = chNull; XMLCh tmpLocalpart[256]; tmpLocalpart[0] = chNull; if (commaAt >= 0) { if (commaAt > 0) XMLString::subString(tmpURI, substitutionGroupFullName, 0, commaAt); XMLString::subString(tmpLocalpart, substitutionGroupFullName, commaAt+1, XMLString::stringLen(substitutionGroupFullName)); } else { XMLString::subString(tmpLocalpart, substitutionGroupFullName, 0, XMLString::stringLen(substitutionGroupFullName)); } sGrammar = (SchemaGrammar*) fGrammarResolver->getGrammar(tmpURI); if (!sGrammar || sGrammar->getGrammarType() == Grammar::DTDGrammarType) return false; uriId = fStringPool->addOrFind(tmpURI); pElemDecl = (SchemaElementDecl*) sGrammar->getElemDecl(uriId, tmpLocalpart, 0, Grammar::TOP_LEVEL_SCOPE); if (!pElemDecl) return false; if ((XMLString::compareString(tmpLocalpart, exemplar->getLocalPart()) == 0) && (uriId == exemplar->getURI())) { // time to check for block value on element if((pElemDecl->getBlockSet() & SchemaSymbols::SUBSTITUTION) != 0) return false; foundIt = true; break; } substitutionGroupFullName = pElemDecl->getSubstitutionGroupName(); }//while if (!foundIt) return false; // this will contain anElement's complexType information. ComplexTypeInfo *aComplexType = anElementDecl->getComplexTypeInfo(); int exemplarBlockSet = pElemDecl->getBlockSet(); if(!aComplexType) { // check on simpleType case DatatypeValidator *anElementDV = anElementDecl->getDatatypeValidator(); DatatypeValidator *exemplarDV = pElemDecl->getDatatypeValidator(); return((anElementDV == 0) || ((anElementDV == exemplarDV) || ((exemplarBlockSet & SchemaSymbols::RESTRICTION) == 0))); } // now we have to make sure there are no blocks on the complexTypes that this is based upon int anElementDerivationMethod = aComplexType->getDerivedBy(); if((anElementDerivationMethod & exemplarBlockSet) != 0) return false; // this will contain exemplar's complexType information. ComplexTypeInfo *exemplarComplexType = pElemDecl->getComplexTypeInfo(); for(ComplexTypeInfo *tempType = aComplexType; tempType != 0 && tempType != exemplarComplexType; tempType = tempType->getBaseComplexTypeInfo()) { if((tempType->getBlockSet() & anElementDerivationMethod) != 0) return false; }//for return true; } bool SubstitutionGroupComparator::isAllowedByWildcard(SchemaGrammar* const pGrammar, QName* const element, unsigned int wuri, bool wother) { // whether the uri is allowed directly by the wildcard unsigned int uriId = element->getURI(); if ((!wother && uriId == wuri) || (wother && uriId != wuri && uriId != XMLContentModel::gEOCFakeId && uriId != XMLContentModel::gEpsilonFakeId)) { return true; } // get all elements that can substitute the current element RefHash2KeysTableOf<ElemVector>* theValidSubstitutionGroups = pGrammar->getValidSubstitutionGroups(); if (!theValidSubstitutionGroups) return false; ValueVectorOf<SchemaElementDecl*>* subsElements = theValidSubstitutionGroups->get(element->getLocalPart(), uriId); if (!subsElements) return false; // then check whether there exists one element that is allowed by the wildcard int size = subsElements->size(); for (int i = 0; i < size; i++) { unsigned int subUriId = subsElements->elementAt(i)->getElementName()->getURI(); if ((!wother && subUriId == wuri) || (wother && subUriId != wuri && subUriId != XMLContentModel::gEOCFakeId && subUriId != XMLContentModel::gEpsilonFakeId)) { return true; } } return false; } /** * End of file SubstitutionGroupComparator.cpp */ <|endoftext|>
<commit_before>// Copyright 2019 TF.Text Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <limits> #include <memory> #include <string> #include <vector> #include "third_party/absl/base/integral_types.h" #include "third_party/tensorflow/core/framework/lookup_interface.h" #include "third_party/tensorflow/core/framework/op_kernel.h" #include "third_party/tensorflow/core/framework/resource_mgr.h" #include "third_party/tensorflow/core/framework/tensor.h" #include "third_party/tensorflow/core/framework/tensor_shape.h" #include "third_party/tensorflow/core/kernels/lookup_util.h" #include "third_party/tensorflow/core/lib/core/status.h" #include "third_party/tensorflow/core/lib/core/threadpool.h" #include "third_party/tensorflow/core/lib/io/path.h" #include "third_party/tensorflow/core/platform/logging.h" #include "third_party/tensorflow_text/core/kernels/wordpiece_tokenizer.h" namespace tensorflow { namespace text { namespace { string GetWordSplitChar(OpKernelConstruction* ctx) { string suffix_indicator; ([=](string* c) -> void { OP_REQUIRES_OK(ctx, ctx->GetAttr("suffix_indicator", c)); })(&suffix_indicator); return suffix_indicator; } int32 GetMaxCharsPerWord(OpKernelConstruction* ctx) { int32 max_chars_per_word; ([=](int32* c) -> void { OP_REQUIRES_OK(ctx, ctx->GetAttr("max_bytes_per_word", c)); })(&max_chars_per_word); return max_chars_per_word; } bool GetShouldUseUnknownToken(OpKernelConstruction* ctx) { bool use_unknown_token; ([=](bool* c) -> void { OP_REQUIRES_OK(ctx, ctx->GetAttr("use_unknown_token", c)); })(&use_unknown_token); return use_unknown_token; } string GetUnknownToken(OpKernelConstruction* ctx) { string unknown_token; ([=](string* c) -> void { OP_REQUIRES_OK(ctx, ctx->GetAttr("unknown_token", c)); })(&unknown_token); return unknown_token; } } // namespace class WordpieceTokenizeWithOffsetsOp : public OpKernel { public: explicit WordpieceTokenizeWithOffsetsOp(OpKernelConstruction* ctx) : OpKernel(ctx), suffix_indicator_(GetWordSplitChar(ctx)), max_bytes_per_word_(GetMaxCharsPerWord(ctx)), use_unknown_token_(GetShouldUseUnknownToken(ctx)), unknown_token_(GetUnknownToken(ctx)) {} void Compute(OpKernelContext* ctx) override { const Tensor* input_values; OP_REQUIRES_OK(ctx, ctx->input("input_values", &input_values)); const auto& values_vec = input_values->flat<string>(); lookup::LookupInterface* lookup_table; OP_REQUIRES_OK( ctx, lookup::GetLookupTable("vocab_lookup_table", ctx, &lookup_table)); LookupTableVocab vocab_map(lookup_table, ctx); std::vector<string> subwords; std::vector<int> begin_offset; std::vector<int> end_offset; std::vector<int> row_lengths; // Iterate through all the values and wordpiece tokenize them. for (int i = 0; i < values_vec.size(); ++i) { // Tokenize into subwords and record the offset locations. int num_wordpieces = 0; OP_REQUIRES_OK( ctx, WordpieceTokenize(values_vec(i), max_bytes_per_word_, suffix_indicator_, use_unknown_token_, unknown_token_, &vocab_map, &subwords, &begin_offset, &end_offset, &num_wordpieces)); // Record the row splits. row_lengths.push_back(num_wordpieces); } std::vector<int64> output_subwords_shape; output_subwords_shape.push_back(subwords.size()); std::vector<int64> output_row_lengths_shape; output_row_lengths_shape.push_back(row_lengths.size()); Tensor* output_values; OP_REQUIRES_OK(ctx, ctx->allocate_output("output_values", TensorShape(output_subwords_shape), &output_values)); auto output_values_vec = output_values->vec<string>(); Tensor* output_row_lengths; OP_REQUIRES_OK(ctx, ctx->allocate_output("output_row_lengths", TensorShape(output_row_lengths_shape), &output_row_lengths)); auto output_row_lengths_vec = output_row_lengths->vec<int64>(); Tensor* start_values; OP_REQUIRES_OK(ctx, ctx->allocate_output("start_values", TensorShape(output_subwords_shape), &start_values)); auto start_values_vec = start_values->vec<int64>(); Tensor* limit_values; OP_REQUIRES_OK(ctx, ctx->allocate_output("limit_values", TensorShape(output_subwords_shape), &limit_values)); auto limit_values_vec = limit_values->vec<int64>(); for (int i = 0; i < subwords.size(); ++i) { output_values_vec(i) = subwords[i]; } for (int i = 0; i < row_lengths.size(); ++i) { output_row_lengths_vec(i) = row_lengths[i]; } for (int i = 0; i < begin_offset.size(); ++i) { start_values_vec(i) = begin_offset[i]; } for (int i = 0; i < end_offset.size(); ++i) { limit_values_vec(i) = end_offset[i]; } } private: const string suffix_indicator_; const int max_bytes_per_word_; const bool use_unknown_token_; const string unknown_token_; TF_DISALLOW_COPY_AND_ASSIGN(WordpieceTokenizeWithOffsetsOp); }; REGISTER_KERNEL_BUILDER(Name("WordpieceTokenizeWithOffsets").Device(DEVICE_CPU), WordpieceTokenizeWithOffsetsOp); } // namespace text } // namespace tensorflow <commit_msg>Internal change<commit_after>// Copyright 2019 TF.Text Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <limits> #include <memory> #include <string> #include <vector> #include "third_party/absl/base/integral_types.h" #include "third_party/tensorflow/core/framework/lookup_interface.h" #include "third_party/tensorflow/core/framework/op_kernel.h" #include "third_party/tensorflow/core/framework/resource_mgr.h" #include "third_party/tensorflow/core/framework/tensor.h" #include "third_party/tensorflow/core/framework/tensor_shape.h" #include "third_party/tensorflow/core/lib/core/status.h" #include "third_party/tensorflow/core/lib/core/threadpool.h" #include "third_party/tensorflow/core/lib/io/path.h" #include "third_party/tensorflow/core/platform/logging.h" #include "third_party/tensorflow_text/core/kernels/wordpiece_tokenizer.h" namespace tensorflow { namespace text { namespace { string GetWordSplitChar(OpKernelConstruction* ctx) { string suffix_indicator; ([=](string* c) -> void { OP_REQUIRES_OK(ctx, ctx->GetAttr("suffix_indicator", c)); })(&suffix_indicator); return suffix_indicator; } int32 GetMaxCharsPerWord(OpKernelConstruction* ctx) { int32 max_chars_per_word; ([=](int32* c) -> void { OP_REQUIRES_OK(ctx, ctx->GetAttr("max_bytes_per_word", c)); })(&max_chars_per_word); return max_chars_per_word; } bool GetShouldUseUnknownToken(OpKernelConstruction* ctx) { bool use_unknown_token; ([=](bool* c) -> void { OP_REQUIRES_OK(ctx, ctx->GetAttr("use_unknown_token", c)); })(&use_unknown_token); return use_unknown_token; } string GetUnknownToken(OpKernelConstruction* ctx) { string unknown_token; ([=](string* c) -> void { OP_REQUIRES_OK(ctx, ctx->GetAttr("unknown_token", c)); })(&unknown_token); return unknown_token; } Status GetTableHandle(const string& input_name, OpKernelContext* ctx, string* container, string* table_handle) { { mutex* mu; TF_RETURN_IF_ERROR(ctx->input_ref_mutex(input_name, &mu)); mutex_lock l(*mu); Tensor tensor; TF_RETURN_IF_ERROR(ctx->mutable_input(input_name, &tensor, true)); if (tensor.NumElements() != 2) { return errors::InvalidArgument( "Lookup table handle must be scalar, but had shape: ", tensor.shape().DebugString()); } auto h = tensor.flat<string>(); *container = h(0); *table_handle = h(1); } return Status::OK(); } // Gets the LookupTable stored in the ctx->resource_manager() with key // passed by attribute with name input_name, returns null if the table // doesn't exist. Status GetLookupTable(const string& input_name, OpKernelContext* ctx, lookup::LookupInterface** table) { string container; string table_handle; DataType handle_dtype; TF_RETURN_IF_ERROR(ctx->input_dtype(input_name, &handle_dtype)); if (handle_dtype == DT_RESOURCE) { ResourceHandle handle; TF_RETURN_IF_ERROR(HandleFromInput(ctx, input_name, &handle)); return LookupResource(ctx, handle, table); } else { TF_RETURN_IF_ERROR( GetTableHandle(input_name, ctx, &container, &table_handle)); return ctx->resource_manager()->Lookup(container, table_handle, table); } } } // namespace class WordpieceTokenizeWithOffsetsOp : public OpKernel { public: explicit WordpieceTokenizeWithOffsetsOp(OpKernelConstruction* ctx) : OpKernel(ctx), suffix_indicator_(GetWordSplitChar(ctx)), max_bytes_per_word_(GetMaxCharsPerWord(ctx)), use_unknown_token_(GetShouldUseUnknownToken(ctx)), unknown_token_(GetUnknownToken(ctx)) {} void Compute(OpKernelContext* ctx) override { const Tensor* input_values; OP_REQUIRES_OK(ctx, ctx->input("input_values", &input_values)); const auto& values_vec = input_values->flat<string>(); lookup::LookupInterface* lookup_table; // MKH: subject to change.... OP_REQUIRES_OK(ctx, GetLookupTable("vocab_lookup_table", ctx, &lookup_table)); LookupTableVocab vocab_map(lookup_table, ctx); std::vector<string> subwords; std::vector<int> begin_offset; std::vector<int> end_offset; std::vector<int> row_lengths; // Iterate through all the values and wordpiece tokenize them. for (int i = 0; i < values_vec.size(); ++i) { // Tokenize into subwords and record the offset locations. int num_wordpieces = 0; OP_REQUIRES_OK( ctx, WordpieceTokenize(values_vec(i), max_bytes_per_word_, suffix_indicator_, use_unknown_token_, unknown_token_, &vocab_map, &subwords, &begin_offset, &end_offset, &num_wordpieces)); // Record the row splits. row_lengths.push_back(num_wordpieces); } std::vector<int64> output_subwords_shape; output_subwords_shape.push_back(subwords.size()); std::vector<int64> output_row_lengths_shape; output_row_lengths_shape.push_back(row_lengths.size()); Tensor* output_values; OP_REQUIRES_OK(ctx, ctx->allocate_output("output_values", TensorShape(output_subwords_shape), &output_values)); auto output_values_vec = output_values->vec<string>(); Tensor* output_row_lengths; OP_REQUIRES_OK(ctx, ctx->allocate_output("output_row_lengths", TensorShape(output_row_lengths_shape), &output_row_lengths)); auto output_row_lengths_vec = output_row_lengths->vec<int64>(); Tensor* start_values; OP_REQUIRES_OK(ctx, ctx->allocate_output("start_values", TensorShape(output_subwords_shape), &start_values)); auto start_values_vec = start_values->vec<int64>(); Tensor* limit_values; OP_REQUIRES_OK(ctx, ctx->allocate_output("limit_values", TensorShape(output_subwords_shape), &limit_values)); auto limit_values_vec = limit_values->vec<int64>(); for (int i = 0; i < subwords.size(); ++i) { output_values_vec(i) = subwords[i]; } for (int i = 0; i < row_lengths.size(); ++i) { output_row_lengths_vec(i) = row_lengths[i]; } for (int i = 0; i < begin_offset.size(); ++i) { start_values_vec(i) = begin_offset[i]; } for (int i = 0; i < end_offset.size(); ++i) { limit_values_vec(i) = end_offset[i]; } } private: const string suffix_indicator_; const int max_bytes_per_word_; const bool use_unknown_token_; const string unknown_token_; TF_DISALLOW_COPY_AND_ASSIGN(WordpieceTokenizeWithOffsetsOp); }; REGISTER_KERNEL_BUILDER(Name("WordpieceTokenizeWithOffsets").Device(DEVICE_CPU), WordpieceTokenizeWithOffsetsOp); } // namespace text } // namespace tensorflow <|endoftext|>
<commit_before>//===- ProfileInfoLoad.cpp - Load profile information from disk -----------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // The ProfileInfoLoader class is used to load and represent profiling // information read in from the dump file. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/ProfileInfoLoader.h" #include "llvm/Analysis/ProfileInfoTypes.h" #include "llvm/Module.h" #include "llvm/InstrTypes.h" #include <cstdio> #include <map> using namespace llvm; // ByteSwap - Byteswap 'Var' if 'Really' is true. // static inline unsigned ByteSwap(unsigned Var, bool Really) { if (!Really) return Var; return ((Var & (255<< 0)) << 24) | ((Var & (255<< 8)) << 8) | ((Var & (255<<16)) >> 8) | ((Var & (255<<24)) >> 24); } static void ReadProfilingBlock(const char *ToolName, FILE *F, bool ShouldByteSwap, std::vector<unsigned> &Data) { // Read the number of entries... unsigned NumEntries; if (fread(&NumEntries, sizeof(unsigned), 1, F) != 1) { std::cerr << ToolName << ": data packet truncated!\n"; perror(0); exit(1); } NumEntries = ByteSwap(NumEntries, ShouldByteSwap); // Read the counts... std::vector<unsigned> TempSpace(NumEntries); // Read in the block of data... if (fread(&TempSpace[0], sizeof(unsigned)*NumEntries, 1, F) != 1) { std::cerr << ToolName << ": data packet truncated!\n"; perror(0); exit(1); } // Make sure we have enough space... if (Data.size() < NumEntries) Data.resize(NumEntries); // Accumulate the data we just read into the data. if (!ShouldByteSwap) { for (unsigned i = 0; i != NumEntries; ++i) Data[i] += TempSpace[i]; } else { for (unsigned i = 0; i != NumEntries; ++i) Data[i] += ByteSwap(TempSpace[i], true); } } // ProfileInfoLoader ctor - Read the specified profiling data file, exiting the // program if the file is invalid or broken. // ProfileInfoLoader::ProfileInfoLoader(const char *ToolName, const std::string &Filename, Module &TheModule) : M(TheModule) { FILE *F = fopen(Filename.c_str(), "r"); if (F == 0) { std::cerr << ToolName << ": Error opening '" << Filename << "': "; perror(0); exit(1); } // Keep reading packets until we run out of them. unsigned PacketType; while (fread(&PacketType, sizeof(unsigned), 1, F) == 1) { // If the low eight bits of the packet are zero, we must be dealing with an // endianness mismatch. Byteswap all words read from the profiling // information. bool ShouldByteSwap = (char)PacketType == 0; PacketType = ByteSwap(PacketType, ShouldByteSwap); switch (PacketType) { case ArgumentInfo: { unsigned ArgLength; if (fread(&ArgLength, sizeof(unsigned), 1, F) != 1) { std::cerr << ToolName << ": arguments packet truncated!\n"; perror(0); exit(1); } ArgLength = ByteSwap(ArgLength, ShouldByteSwap); // Read in the arguments... std::vector<char> Chars(ArgLength+4); if (ArgLength) if (fread(&Chars[0], (ArgLength+3) & ~3, 1, F) != 1) { std::cerr << ToolName << ": arguments packet truncated!\n"; perror(0); exit(1); } CommandLines.push_back(std::string(&Chars[0], &Chars[ArgLength])); break; } case FunctionInfo: ReadProfilingBlock(ToolName, F, ShouldByteSwap, FunctionCounts); break; case BlockInfo: ReadProfilingBlock(ToolName, F, ShouldByteSwap, BlockCounts); break; case EdgeInfo: ReadProfilingBlock(ToolName, F, ShouldByteSwap, EdgeCounts); break; default: std::cerr << ToolName << ": Unknown packet type #" << PacketType << "!\n"; exit(1); } } fclose(F); } // getFunctionCounts - This method is used by consumers of function counting // information. If we do not directly have function count information, we // compute it from other, more refined, types of profile information. // void ProfileInfoLoader::getFunctionCounts(std::vector<std::pair<Function*, unsigned> > &Counts) { if (FunctionCounts.empty()) { if (hasAccurateBlockCounts()) { // Synthesize function frequency information from the number of times // their entry blocks were executed. std::vector<std::pair<BasicBlock*, unsigned> > BlockCounts; getBlockCounts(BlockCounts); for (unsigned i = 0, e = BlockCounts.size(); i != e; ++i) if (&BlockCounts[i].first->getParent()->front() == BlockCounts[i].first) Counts.push_back(std::make_pair(BlockCounts[i].first->getParent(), BlockCounts[i].second)); } else { std::cerr << "Function counts are not available!\n"; } return; } unsigned Counter = 0; for (Module::iterator I = M.begin(), E = M.end(); I != E && Counter != FunctionCounts.size(); ++I) if (!I->isExternal()) Counts.push_back(std::make_pair(I, FunctionCounts[Counter++])); } // getBlockCounts - This method is used by consumers of block counting // information. If we do not directly have block count information, we // compute it from other, more refined, types of profile information. // void ProfileInfoLoader::getBlockCounts(std::vector<std::pair<BasicBlock*, unsigned> > &Counts) { if (BlockCounts.empty()) { if (hasAccurateEdgeCounts()) { // Synthesize block count information from edge frequency information. // The block execution frequency is equal to the sum of the execution // frequency of all outgoing edges from a block. // // If a block has no successors, this will not be correct, so we have to // special case it. :( std::vector<std::pair<Edge, unsigned> > EdgeCounts; getEdgeCounts(EdgeCounts); std::map<BasicBlock*, unsigned> InEdgeFreqs; BasicBlock *LastBlock = 0; TerminatorInst *TI = 0; for (unsigned i = 0, e = EdgeCounts.size(); i != e; ++i) { if (EdgeCounts[i].first.first != LastBlock) { LastBlock = EdgeCounts[i].first.first; TI = LastBlock->getTerminator(); Counts.push_back(std::make_pair(LastBlock, 0)); } Counts.back().second += EdgeCounts[i].second; unsigned SuccNum = EdgeCounts[i].first.second; if (SuccNum >= TI->getNumSuccessors()) { static bool Warned = false; if (!Warned) { std::cerr << "WARNING: profile info doesn't seem to match" << " the program!\n"; Warned = true; } } else { // If this successor has no successors of its own, we will never // compute an execution count for that block. Remember the incoming // edge frequencies to add later. BasicBlock *Succ = TI->getSuccessor(SuccNum); if (Succ->getTerminator()->getNumSuccessors() == 0) InEdgeFreqs[Succ] += EdgeCounts[i].second; } } // Now we have to accumulate information for those blocks without // successors into our table. for (std::map<BasicBlock*, unsigned>::iterator I = InEdgeFreqs.begin(), E = InEdgeFreqs.end(); I != E; ++I) { unsigned i = 0; for (; i != Counts.size() && Counts[i].first != I->first; ++i) /*empty*/; if (i == Counts.size()) Counts.push_back(std::make_pair(I->first, 0)); Counts[i].second += I->second; } } else { std::cerr << "Block counts are not available!\n"; } return; } unsigned Counter = 0; for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) { Counts.push_back(std::make_pair(BB, BlockCounts[Counter++])); if (Counter == BlockCounts.size()) return; } } // getEdgeCounts - This method is used by consumers of edge counting // information. If we do not directly have edge count information, we compute // it from other, more refined, types of profile information. // void ProfileInfoLoader::getEdgeCounts(std::vector<std::pair<Edge, unsigned> > &Counts) { if (EdgeCounts.empty()) { std::cerr << "Edge counts not available, and no synthesis " << "is implemented yet!\n"; return; } unsigned Counter = 0; for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) for (unsigned i = 0, e = BB->getTerminator()->getNumSuccessors(); i != e; ++i) { Counts.push_back(std::make_pair(Edge(BB, i), EdgeCounts[Counter++])); if (Counter == EdgeCounts.size()) return; } } <commit_msg>Add stub support for reading BBTraces.<commit_after>//===- ProfileInfoLoad.cpp - Load profile information from disk -----------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // The ProfileInfoLoader class is used to load and represent profiling // information read in from the dump file. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/ProfileInfoLoader.h" #include "llvm/Analysis/ProfileInfoTypes.h" #include "llvm/Module.h" #include "llvm/InstrTypes.h" #include <cstdio> #include <map> using namespace llvm; // ByteSwap - Byteswap 'Var' if 'Really' is true. // static inline unsigned ByteSwap(unsigned Var, bool Really) { if (!Really) return Var; return ((Var & (255<< 0)) << 24) | ((Var & (255<< 8)) << 8) | ((Var & (255<<16)) >> 8) | ((Var & (255<<24)) >> 24); } static void ReadProfilingBlock(const char *ToolName, FILE *F, bool ShouldByteSwap, std::vector<unsigned> &Data) { // Read the number of entries... unsigned NumEntries; if (fread(&NumEntries, sizeof(unsigned), 1, F) != 1) { std::cerr << ToolName << ": data packet truncated!\n"; perror(0); exit(1); } NumEntries = ByteSwap(NumEntries, ShouldByteSwap); // Read the counts... std::vector<unsigned> TempSpace(NumEntries); // Read in the block of data... if (fread(&TempSpace[0], sizeof(unsigned)*NumEntries, 1, F) != 1) { std::cerr << ToolName << ": data packet truncated!\n"; perror(0); exit(1); } // Make sure we have enough space... if (Data.size() < NumEntries) Data.resize(NumEntries); // Accumulate the data we just read into the data. if (!ShouldByteSwap) { for (unsigned i = 0; i != NumEntries; ++i) Data[i] += TempSpace[i]; } else { for (unsigned i = 0; i != NumEntries; ++i) Data[i] += ByteSwap(TempSpace[i], true); } } // ProfileInfoLoader ctor - Read the specified profiling data file, exiting the // program if the file is invalid or broken. // ProfileInfoLoader::ProfileInfoLoader(const char *ToolName, const std::string &Filename, Module &TheModule) : M(TheModule) { FILE *F = fopen(Filename.c_str(), "r"); if (F == 0) { std::cerr << ToolName << ": Error opening '" << Filename << "': "; perror(0); exit(1); } // Keep reading packets until we run out of them. unsigned PacketType; while (fread(&PacketType, sizeof(unsigned), 1, F) == 1) { // If the low eight bits of the packet are zero, we must be dealing with an // endianness mismatch. Byteswap all words read from the profiling // information. bool ShouldByteSwap = (char)PacketType == 0; PacketType = ByteSwap(PacketType, ShouldByteSwap); switch (PacketType) { case ArgumentInfo: { unsigned ArgLength; if (fread(&ArgLength, sizeof(unsigned), 1, F) != 1) { std::cerr << ToolName << ": arguments packet truncated!\n"; perror(0); exit(1); } ArgLength = ByteSwap(ArgLength, ShouldByteSwap); // Read in the arguments... std::vector<char> Chars(ArgLength+4); if (ArgLength) if (fread(&Chars[0], (ArgLength+3) & ~3, 1, F) != 1) { std::cerr << ToolName << ": arguments packet truncated!\n"; perror(0); exit(1); } CommandLines.push_back(std::string(&Chars[0], &Chars[ArgLength])); break; } case FunctionInfo: ReadProfilingBlock(ToolName, F, ShouldByteSwap, FunctionCounts); break; case BlockInfo: ReadProfilingBlock(ToolName, F, ShouldByteSwap, BlockCounts); break; case EdgeInfo: ReadProfilingBlock(ToolName, F, ShouldByteSwap, EdgeCounts); break; case BBTraceInfo: ReadProfilingBlock(ToolName, F, ShouldByteSwap, BBTrace); break; default: std::cerr << ToolName << ": Unknown packet type #" << PacketType << "!\n"; exit(1); } } fclose(F); } // getFunctionCounts - This method is used by consumers of function counting // information. If we do not directly have function count information, we // compute it from other, more refined, types of profile information. // void ProfileInfoLoader::getFunctionCounts(std::vector<std::pair<Function*, unsigned> > &Counts) { if (FunctionCounts.empty()) { if (hasAccurateBlockCounts()) { // Synthesize function frequency information from the number of times // their entry blocks were executed. std::vector<std::pair<BasicBlock*, unsigned> > BlockCounts; getBlockCounts(BlockCounts); for (unsigned i = 0, e = BlockCounts.size(); i != e; ++i) if (&BlockCounts[i].first->getParent()->front() == BlockCounts[i].first) Counts.push_back(std::make_pair(BlockCounts[i].first->getParent(), BlockCounts[i].second)); } else { std::cerr << "Function counts are not available!\n"; } return; } unsigned Counter = 0; for (Module::iterator I = M.begin(), E = M.end(); I != E && Counter != FunctionCounts.size(); ++I) if (!I->isExternal()) Counts.push_back(std::make_pair(I, FunctionCounts[Counter++])); } // getBlockCounts - This method is used by consumers of block counting // information. If we do not directly have block count information, we // compute it from other, more refined, types of profile information. // void ProfileInfoLoader::getBlockCounts(std::vector<std::pair<BasicBlock*, unsigned> > &Counts) { if (BlockCounts.empty()) { if (hasAccurateEdgeCounts()) { // Synthesize block count information from edge frequency information. // The block execution frequency is equal to the sum of the execution // frequency of all outgoing edges from a block. // // If a block has no successors, this will not be correct, so we have to // special case it. :( std::vector<std::pair<Edge, unsigned> > EdgeCounts; getEdgeCounts(EdgeCounts); std::map<BasicBlock*, unsigned> InEdgeFreqs; BasicBlock *LastBlock = 0; TerminatorInst *TI = 0; for (unsigned i = 0, e = EdgeCounts.size(); i != e; ++i) { if (EdgeCounts[i].first.first != LastBlock) { LastBlock = EdgeCounts[i].first.first; TI = LastBlock->getTerminator(); Counts.push_back(std::make_pair(LastBlock, 0)); } Counts.back().second += EdgeCounts[i].second; unsigned SuccNum = EdgeCounts[i].first.second; if (SuccNum >= TI->getNumSuccessors()) { static bool Warned = false; if (!Warned) { std::cerr << "WARNING: profile info doesn't seem to match" << " the program!\n"; Warned = true; } } else { // If this successor has no successors of its own, we will never // compute an execution count for that block. Remember the incoming // edge frequencies to add later. BasicBlock *Succ = TI->getSuccessor(SuccNum); if (Succ->getTerminator()->getNumSuccessors() == 0) InEdgeFreqs[Succ] += EdgeCounts[i].second; } } // Now we have to accumulate information for those blocks without // successors into our table. for (std::map<BasicBlock*, unsigned>::iterator I = InEdgeFreqs.begin(), E = InEdgeFreqs.end(); I != E; ++I) { unsigned i = 0; for (; i != Counts.size() && Counts[i].first != I->first; ++i) /*empty*/; if (i == Counts.size()) Counts.push_back(std::make_pair(I->first, 0)); Counts[i].second += I->second; } } else { std::cerr << "Block counts are not available!\n"; } return; } unsigned Counter = 0; for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) { Counts.push_back(std::make_pair(BB, BlockCounts[Counter++])); if (Counter == BlockCounts.size()) return; } } // getEdgeCounts - This method is used by consumers of edge counting // information. If we do not directly have edge count information, we compute // it from other, more refined, types of profile information. // void ProfileInfoLoader::getEdgeCounts(std::vector<std::pair<Edge, unsigned> > &Counts) { if (EdgeCounts.empty()) { std::cerr << "Edge counts not available, and no synthesis " << "is implemented yet!\n"; return; } unsigned Counter = 0; for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) for (unsigned i = 0, e = BB->getTerminator()->getNumSuccessors(); i != e; ++i) { Counts.push_back(std::make_pair(Edge(BB, i), EdgeCounts[Counter++])); if (Counter == EdgeCounts.size()) return; } } // getBBTrace - This method is used by consumers of basic-block trace // information. // void ProfileInfoLoader::getBBTrace(std::vector<BasicBlock *> &Trace) { if (BBTrace.empty ()) { std::cerr << "Basic block trace is not available!\n"; return; } std::cerr << "Basic block trace loading is not implemented yet!\n"; } <|endoftext|>
<commit_before>/* * This is part of the FL library, a C++ Bayesian filtering library * (https://github.com/filtering-library) * * Copyright (c) 2014 Jan Issac ([email protected]) * Copyright (c) 2014 Manuel Wuthrich ([email protected]) * * Max-Planck Institute for Intelligent Systems, AMD Lab * University of Southern California, CLMC Lab * * This Source Code Form is subject to the terms of the MIT License (MIT). * A copy of the license can be found in the LICENSE file distributed with this * source code. */ /** * \file gaussian_filter_kf_test.cpp * \date Febuary 2015 * \author Jan Issac ([email protected]) */ #include <gtest/gtest.h> #include <Eigen/Dense> #include <cmath> #include <iostream> #include <fl/model/process/linear_process_model.hpp> #include <fl/model/observation/linear_observation_model.hpp> #include <fl/filter/filter_interface.hpp> #include <fl/filter/gaussian/gaussian_filter.hpp> #include <fl/util/math/linear_algebra.hpp> using namespace fl; TEST(KalmanFilterTests, init_fixed_size_predict) { typedef double Scalar; typedef Eigen::Matrix<Scalar, 10, 1> State; typedef Eigen::Matrix<Scalar, 1 , 1> Input; typedef Eigen::Matrix<Scalar, 20, 1> Obsrv; typedef LinearGaussianProcessModel<State, Input> LinearProcess; typedef LinearObservationModel<Obsrv, State> LinearObservation; // the KalmanFilter typedef GaussianFilter<LinearProcess, LinearObservation> Algo; typedef FilterInterface<Algo> Filter; LinearProcess::SecondMoment Q = LinearProcess::SecondMoment::Identity(); Filter&& filter = Algo(LinearProcess(Q), LinearObservation()); Filter::StateDistribution state_dist; EXPECT_TRUE(state_dist.mean().isZero()); EXPECT_TRUE(state_dist.covariance().isIdentity()); filter.predict(1.0, Input(1), state_dist, state_dist); EXPECT_TRUE(state_dist.mean().isZero()); EXPECT_TRUE(fl::are_similar(state_dist.covariance(), 2. * Q)); } TEST(KalmanFilterTests, init_dynamic_size_predict) { typedef double Scalar; typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> State; typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> Input; typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> Obsrv; const int dim_state = 10; const int dim_obsrv = 20; typedef LinearGaussianProcessModel<State, Input> LinearProcess; typedef LinearObservationModel<Obsrv, State> LinearObservation; // the KalmanFilter typedef GaussianFilter<LinearProcess, LinearObservation> Algo; typedef FilterInterface<Algo> Filter; LinearProcess::SecondMoment Q = LinearProcess::SecondMoment::Identity(dim_state, dim_state); // Traits<ObservationModel>::SecondMoment R = // Traits<ObservationModel>::SecondMoment::Identity(dim_obsrv, dim_obsrv); Filter&& filter = Algo( LinearProcess(Q, dim_state), LinearObservation(dim_obsrv, dim_state)); auto state_dist = Filter::StateDistribution(dim_state); EXPECT_TRUE(state_dist.mean().isZero()); EXPECT_TRUE(state_dist.covariance().isIdentity()); filter.predict(1.0, Input(1), state_dist, state_dist); EXPECT_TRUE(state_dist.mean().isZero()); EXPECT_TRUE(fl::are_similar(state_dist.covariance(), 2. * Q)); } //TEST(KalmanFilterTests, fixed_size_predict_update) //{ // typedef double Scalar; // typedef Eigen::Matrix<Scalar, 6, 1> State; // typedef Eigen::Matrix<Scalar, 6, 1> Input; // typedef Eigen::Matrix<Scalar, 6, 1> Obsrv; // // the KalmanFilter // typedef GaussianFilter< // LinearGaussianProcessModel<State, Input>, // LinearObservationModel<Obsrv, State> // > Algo; // typedef FilterInterface<Algo> Filter; // typedef typename Traits<Algo>::ProcessModel ProcessModel; // typedef typename Traits<Algo>::ObservationModel ObservationModel; // Traits<ProcessModel>::SecondMoment Q = // Traits<ProcessModel>::SecondMoment::Random() * 1.5; //// Traits<ObservationModel>::SecondMoment R = //// Traits<ObservationModel>::SecondMoment::Random(); // Q *= Q.transpose(); // R *= R.transpose(); // Traits<ProcessModel>::DynamicsMatrix A = // Traits<ProcessModel>::DynamicsMatrix::Random(); // Traits<ObservationModel>::SensorMatrix H = // Traits<ObservationModel>::SensorMatrix::Random(); // ProcessModel process_model = ProcessModel(Q); // ObservationModel obsrv_model = ObservationModel(R); // process_model.A(A); // obsrv_model.H(H); // Filter&& filter = Algo(process_model, obsrv_model); // Filter::StateDistribution state_dist; // EXPECT_TRUE(state_dist.covariance().ldlt().isPositive()); // for (int i = 0; i < 2000; ++i) // { // filter.predict(1.0, Input(), state_dist, state_dist); // EXPECT_TRUE(state_dist.covariance().ldlt().isPositive()); // Obsrv y = Obsrv::Random(); // filter.update(y, state_dist, state_dist); // EXPECT_TRUE(state_dist.covariance().ldlt().isPositive()); // } //} //TEST(KalmanFilterTests, dynamic_size_predict_update) //{ // typedef double Scalar; // typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> State; // typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> Input; // typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> Obsrv; // const int dim_state = 10; // const int dim_obsrv = 10; // // the KalmanFilter // typedef GaussianFilter< // LinearGaussianProcessModel<State, Input>, // LinearGaussianObservationModel<Obsrv, State> // > Algo; // typedef FilterInterface<Algo> Filter; // typedef typename Traits<Algo>::ProcessModel ProcessModel; // typedef typename Traits<Algo>::ObservationModel ObservationModel; // Traits<ProcessModel>::SecondMoment Q = // Traits<ProcessModel>::SecondMoment::Random(dim_state, dim_state) * 1.5; // Q *= Q.transpose(); // Traits<ProcessModel>::DynamicsMatrix A = // Traits<ProcessModel>::DynamicsMatrix::Random(dim_state, dim_state); // Traits<ObservationModel>::SecondMoment R = // Traits<ObservationModel>::SecondMoment::Random(dim_obsrv, dim_obsrv); // R *= R.transpose(); // Traits<ObservationModel>::SensorMatrix H = // Traits<ObservationModel>::SensorMatrix::Random(dim_obsrv, dim_state); // ProcessModel process_model = // ProcessModel(Q, dim_state); // ObservationModel obsrv_model = // ObservationModel(R, dim_obsrv, dim_state); // process_model.A(A); // obsrv_model.H(H); // Filter&& filter = Algo(process_model, obsrv_model); // Filter::StateDistribution state_dist(dim_state); // EXPECT_TRUE(state_dist.covariance().ldlt().isPositive()); // for (int i = 0; i < 2000; ++i) // { // filter.predict(1.0, Input(1), state_dist, state_dist); // EXPECT_TRUE(state_dist.covariance().ldlt().isPositive()); // Obsrv y = Obsrv::Random(dim_obsrv); // filter.update(y, state_dist, state_dist); // EXPECT_TRUE(state_dist.covariance().ldlt().isPositive()); // } //} <commit_msg>updated KF unit tests<commit_after>/* * This is part of the FL library, a C++ Bayesian filtering library * (https://github.com/filtering-library) * * Copyright (c) 2014 Jan Issac ([email protected]) * Copyright (c) 2014 Manuel Wuthrich ([email protected]) * * Max-Planck Institute for Intelligent Systems, AMD Lab * University of Southern California, CLMC Lab * * This Source Code Form is subject to the terms of the MIT License (MIT). * A copy of the license can be found in the LICENSE file distributed with this * source code. */ /** * \file gaussian_filter_kf_test.cpp * \date Febuary 2015 * \author Jan Issac ([email protected]) */ #include <gtest/gtest.h> #include <Eigen/Dense> #include <cmath> #include <iostream> #include <fl/model/process/linear_process_model.hpp> #include <fl/model/observation/linear_observation_model.hpp> #include <fl/filter/filter_interface.hpp> #include <fl/filter/gaussian/gaussian_filter.hpp> #include <fl/util/math/linear_algebra.hpp> using namespace fl; TEST(KalmanFilterTests, init_fixed_size_predict) { typedef double Scalar; typedef Eigen::Matrix<Scalar, 10, 1> State; typedef Eigen::Matrix<Scalar, 1 , 1> Input; typedef Eigen::Matrix<Scalar, 20, 1> Obsrv; typedef LinearStateTransitionModel<State, Input> LinearProcess; typedef LinearObservationModel<Obsrv, State> LinearObservation; // the KalmanFilter typedef GaussianFilter<LinearProcess, LinearObservation> Filter; auto filter = Filter(LinearProcess(), LinearObservation()); Filter::StateDistribution state_dist; EXPECT_TRUE(state_dist.mean().isZero()); EXPECT_TRUE(state_dist.covariance().isIdentity()); filter.predict(1.0, Input(1), state_dist, state_dist); auto Q = filter.process_model().noise_matrix_squared(); EXPECT_TRUE(state_dist.mean().isZero()); EXPECT_TRUE(fl::are_similar(state_dist.covariance(), 2. * Q)); } TEST(KalmanFilterTests, init_dynamic_size_predict) { typedef double Scalar; typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> State; typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> Input; typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> Obsrv; const int dim_state = 10; const int dim_obsrv = 20; const int dim_input = 1; typedef LinearStateTransitionModel<State, Input> LinearProcess; typedef LinearObservationModel<Obsrv, State> LinearObservation; // the KalmanFilter typedef GaussianFilter<LinearProcess, LinearObservation> Filter; auto filter = Filter(LinearProcess(dim_state, dim_input), LinearObservation(dim_obsrv, dim_state)); auto state_dist = Filter::StateDistribution(dim_state); EXPECT_TRUE(state_dist.mean().isZero()); EXPECT_TRUE(state_dist.covariance().isIdentity()); filter.predict(1.0, Input(1), state_dist, state_dist); auto Q = filter.process_model().noise_matrix_squared(); EXPECT_TRUE(state_dist.mean().isZero()); EXPECT_TRUE(fl::are_similar(state_dist.covariance(), 2. * Q)); } //TEST(KalmanFilterTests, fixed_size_predict_update) //{ // typedef double Scalar; // typedef Eigen::Matrix<Scalar, 6, 1> State; // typedef Eigen::Matrix<Scalar, 6, 1> Input; // typedef Eigen::Matrix<Scalar, 6, 1> Obsrv; // // the KalmanFilter // typedef GaussianFilter< // LinearGaussianProcessModel<State, Input>, // LinearObservationModel<Obsrv, State> // > Algo; // typedef FilterInterface<Algo> Filter; // typedef typename Traits<Algo>::ProcessModel ProcessModel; // typedef typename Traits<Algo>::ObservationModel ObservationModel; // Traits<ProcessModel>::SecondMoment Q = // Traits<ProcessModel>::SecondMoment::Random() * 1.5; //// Traits<ObservationModel>::SecondMoment R = //// Traits<ObservationModel>::SecondMoment::Random(); // Q *= Q.transpose(); // R *= R.transpose(); // Traits<ProcessModel>::DynamicsMatrix A = // Traits<ProcessModel>::DynamicsMatrix::Random(); // Traits<ObservationModel>::SensorMatrix H = // Traits<ObservationModel>::SensorMatrix::Random(); // ProcessModel process_model = ProcessModel(Q); // ObservationModel obsrv_model = ObservationModel(R); // process_model.A(A); // obsrv_model.H(H); // Filter&& filter = Algo(process_model, obsrv_model); // Filter::StateDistribution state_dist; // EXPECT_TRUE(state_dist.covariance().ldlt().isPositive()); // for (int i = 0; i < 2000; ++i) // { // filter.predict(1.0, Input(), state_dist, state_dist); // EXPECT_TRUE(state_dist.covariance().ldlt().isPositive()); // Obsrv y = Obsrv::Random(); // filter.update(y, state_dist, state_dist); // EXPECT_TRUE(state_dist.covariance().ldlt().isPositive()); // } //} //TEST(KalmanFilterTests, dynamic_size_predict_update) //{ // typedef double Scalar; // typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> State; // typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> Input; // typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> Obsrv; // const int dim_state = 10; // const int dim_obsrv = 10; // // the KalmanFilter // typedef GaussianFilter< // LinearGaussianProcessModel<State, Input>, // LinearGaussianObservationModel<Obsrv, State> // > Algo; // typedef FilterInterface<Algo> Filter; // typedef typename Traits<Algo>::ProcessModel ProcessModel; // typedef typename Traits<Algo>::ObservationModel ObservationModel; // Traits<ProcessModel>::SecondMoment Q = // Traits<ProcessModel>::SecondMoment::Random(dim_state, dim_state) * 1.5; // Q *= Q.transpose(); // Traits<ProcessModel>::DynamicsMatrix A = // Traits<ProcessModel>::DynamicsMatrix::Random(dim_state, dim_state); // Traits<ObservationModel>::SecondMoment R = // Traits<ObservationModel>::SecondMoment::Random(dim_obsrv, dim_obsrv); // R *= R.transpose(); // Traits<ObservationModel>::SensorMatrix H = // Traits<ObservationModel>::SensorMatrix::Random(dim_obsrv, dim_state); // ProcessModel process_model = // ProcessModel(Q, dim_state); // ObservationModel obsrv_model = // ObservationModel(R, dim_obsrv, dim_state); // process_model.A(A); // obsrv_model.H(H); // Filter&& filter = Algo(process_model, obsrv_model); // Filter::StateDistribution state_dist(dim_state); // EXPECT_TRUE(state_dist.covariance().ldlt().isPositive()); // for (int i = 0; i < 2000; ++i) // { // filter.predict(1.0, Input(1), state_dist, state_dist); // EXPECT_TRUE(state_dist.covariance().ldlt().isPositive()); // Obsrv y = Obsrv::Random(dim_obsrv); // filter.update(y, state_dist, state_dist); // EXPECT_TRUE(state_dist.covariance().ldlt().isPositive()); // } //} <|endoftext|>
<commit_before>// RUN: %clangxx -std=c++11 -frtti -fsanitize=vptr -g %s -O3 -o %t // RUN: %run %t &> %t.log // RUN: cat %t.log | not count 0 && FileCheck --input-file %t.log %s || cat %t.log | count 0 // REQUIRES: cxxabi #include <sys/mman.h> #include <unistd.h> class Base { public: int i; virtual void print() {} }; class Derived : public Base { public: void print() {} }; int main() { int page_size = getpagesize(); void *non_accessible = mmap(nullptr, page_size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if (non_accessible == MAP_FAILED) return 0; void *accessible = mmap((char*)non_accessible + page_size, page_size, PROT_READ | PROT_WRITE, MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if (accessible == MAP_FAILED) return 0; char *c = new char[sizeof(Derived)]; // The goal is to trigger a condition when Vptr points to accessible memory, // but VptrPrefix does not. That has been triggering SIGSEGV in UBSan code. void **vtable_ptr = reinterpret_cast<void **>(c); *vtable_ptr = (void*)accessible; Derived *list = (Derived *)c; // CHECK: PR33221.cpp:[[@LINE+2]]:19: runtime error: member access within address {{.*}} which does not point to an object of type 'Base' // CHECK-NEXT: invalid vptr int foo = list->i; return 0; } <commit_msg>[ubsan] Update a test missed in r309008, NFC<commit_after>// RUN: %clangxx -std=c++11 -frtti -fsanitize=vptr,null -g %s -O3 -o %t // RUN: %run %t &> %t.log // RUN: cat %t.log | not count 0 && FileCheck --input-file %t.log %s || cat %t.log | count 0 // REQUIRES: cxxabi #include <sys/mman.h> #include <unistd.h> class Base { public: int i; virtual void print() {} }; class Derived : public Base { public: void print() {} }; int main() { int page_size = getpagesize(); void *non_accessible = mmap(nullptr, page_size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if (non_accessible == MAP_FAILED) return 0; void *accessible = mmap((char*)non_accessible + page_size, page_size, PROT_READ | PROT_WRITE, MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if (accessible == MAP_FAILED) return 0; char *c = new char[sizeof(Derived)]; // The goal is to trigger a condition when Vptr points to accessible memory, // but VptrPrefix does not. That has been triggering SIGSEGV in UBSan code. void **vtable_ptr = reinterpret_cast<void **>(c); *vtable_ptr = (void*)accessible; Derived *list = (Derived *)c; // CHECK: PR33221.cpp:[[@LINE+2]]:19: runtime error: member access within address {{.*}} which does not point to an object of type 'Base' // CHECK-NEXT: invalid vptr int foo = list->i; return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <Windows.h> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/opencv.hpp> #include <opencv2/imgproc.hpp> #include <algorithm> /* mineBot.cpp T.Lloyd An attempt at an openCV minesweeper bot... */ using namespace cv; using namespace std; #define until for #define endOfTime (;;) BOOL captureFrame(Mat &f,HWND mineHandle,int height, int width){ HDC mineHDC, mineCompat; HBITMAP mineBit; BITMAP b; BITMAPINFOHEADER mineH; if (mineHandle == NULL){ cout << "Game Not Found\n"; return FALSE; } mineHDC = GetDC(mineHandle); mineCompat = CreateCompatibleDC(mineHDC); if (!mineCompat){ cout << "Error creating compatible DC\n"; return FALSE; } //SetStretchBltMode(mineCompat, HALFTONE); SetStretchBltMode(mineCompat, HALFTONE); mineBit = CreateCompatibleBitmap(mineHDC, width, height); if (mineBit == NULL){ cout << "Bitmap Creation Failed!\n"; return FALSE; } mineH.biSize = sizeof(BITMAPINFOHEADER); mineH.biPlanes = 1; mineH.biWidth = width; mineH.biHeight = -height; mineH.biBitCount = 32; mineH.biCompression = BI_RGB; SelectObject(mineCompat, mineBit); if (!StretchBlt(mineCompat, 0, 0, width, height, mineHDC, 0, 0, width, height, SRCCOPY)){ cout << "Error Stretch BLT\n"; return FALSE; } //BitBlt(mineCompat, 0, 0, width, height, mineHDC, 0, 0, SRCCOPY); //GetObject(mineBit, sizeof(BITMAP), &b); //GetDIBits(mineHDC, mineBit, 0, height, frame.data, (BITMAPINFO*)&mineH, DIB_RGB_COLORS); GetDIBits(mineCompat, mineBit, 0, height, f.data, (BITMAPINFO*)&mineH, DIB_RGB_COLORS); DeleteObject(mineBit); DeleteDC(mineCompat); ReleaseDC(mineHandle, mineHDC); return TRUE; } BOOL countSquares(Mat &f,Mat &t, Mat &r,double threshold,vector<Point> &squares,Scalar colour){ //Frame,Template,Result,Number of squares Mat greysrc = f.clone(); Mat greyTemp = t.clone(); cvtColor(f, greysrc, COLOR_BGR2GRAY); cvtColor(t, greyTemp, COLOR_BGR2GRAY); matchTemplate(greysrc, greyTemp, r, TM_CCOEFF_NORMED); normalize(r, r, 0, 1, NORM_MINMAX, -1, Mat()); double minVal; double maxVal; Point minLoc; Point maxLoc; Point matchLoc; Point prevMatchLoc; squares.clear(); bool edge = FALSE; int dup = 0; //count duplicates for (int i = 0, j = 0; i < 81; i++){ //minesweeper has gradient so only detects two of the squares. minMaxLoc(r, &minVal, &maxVal, &minLoc, &maxLoc, Mat()); //if (maxVal > 0.87){ if ((maxVal > threshold)){ matchLoc = maxLoc; for (int k = 0; k < squares.size(); k++){ if (((abs(matchLoc.y - squares[k].y) <= 3) && (abs(matchLoc.x - squares[k].x) <= 3))){ //cout << "!"; dup++; } } if (matchLoc.x > 30){ edge = TRUE; } else{ edge = FALSE; } //cout << "Duplicates=" << dup << "\n"; //dup = 0; if ((dup == 0)&&(edge==TRUE)){ squares.push_back(matchLoc); rectangle(r, matchLoc, Point(matchLoc.x + t.cols, matchLoc.y + t.rows), Scalar(0, 0, 0), CV_FILLED, 8, 0); rectangle(f, matchLoc, Point(matchLoc.x + t.cols, matchLoc.y + t.rows), colour, 1, 8, 0); } //} //} } } greysrc.release(); greyTemp.release(); //cout << "Vector Size=" << squares.size() << "\n"; return TRUE; } void printSquares(vector<Point> &p){ for (int k = 0; k < p.size(); k++){ cout << "(" << p[k].x << "," << p[k].y << ")\n"; } } bool sortX(Point p1, Point p2){return (p1.x < p2.x);} bool sortY(Point p1, Point p2){ return (p1.y < p2.y); } void sortGrid(vector<Point> &p){ //9x9 Grid Sorting Algorithm std::sort(p.begin(), p.end(), sortX); for (int i = 0; i < 9; i++){ std::sort(p.begin() + (i * 9), p.begin() + ((i + 1) * 9), sortY); } } void printGrid(char** &g){ for (int j = 0; j < 9; j++){ for (int k = 0; k < 9; k++){ cout << +g[k][j]; } cout << "\n"; } } void updateGrid(char** &g,vector<Point>&s,vector<Point>&masterGrid,char value){ for (int j = 0; j < s.size(); j++){ for (int k = 0; k < masterGrid.size(); k++){ if ((s[j].x > masterGrid[k].x) && (s[j].x <(masterGrid[k].x + 16)) && (s[j].y > masterGrid[k].y) && (s[j].y < (masterGrid[k].y + 16))){ int xpos = (int)(k / 9); int ypos = (int)(k % 9); g[xpos][ypos] = value; } } } } int main(void){ std::cout << "mineBot\nT.Lloyd\n"; Mat frame; HWND mineHandle = FindWindow(NULL,L"Minesweeper"); if (mineHandle == NULL){ cout << "Game Not Found\n"; return -1; } else{ cout << "Game Successfully Found!\n"; } namedWindow("Win", 1); RECT winSize; int height, width; int unpressed = 0; GetClientRect(mineHandle, &winSize); height = winSize.bottom; width = winSize.right; frame.create(height, width, CV_8UC4); Point pt; pt.x = 0; pt.y = 0; Mat temp = imread("Images//square2.jpg", CV_LOAD_IMAGE_COLOR); Mat oneTemp = imread("Images//one3.jpg", CV_LOAD_IMAGE_COLOR); Mat twoTemp = imread("Images//two.jpg", CV_LOAD_IMAGE_COLOR); Mat threeTemp = imread("Images//three.jpg", CV_LOAD_IMAGE_COLOR); Mat fourTemp = imread("Images//four.jpg", CV_LOAD_IMAGE_COLOR); //cvtColor(temp, temp, CV_8UC4,0); //Mat result; //Mat oneResult; //---------------------------------------------------------------------------- //Initial read to define co-ordinates Mat gridResult; vector<Point> gridMap; captureFrame(frame, mineHandle, height, width); gridResult.create(frame.cols - temp.cols + 1, frame.rows - temp.rows + 1, CV_32FC1); //unPressedMat = frame.clone(); countSquares(frame, temp, gridResult, 0.920, gridMap, Scalar(0, 255, 255)); cout << "Unpressed Squares: " << gridResult.size() << "\n"; printSquares(gridMap); cv::imshow("Win", frame); gridResult.release(); sortGrid(gridMap); printSquares(gridMap); // for (int i = 0; i < gridMap.size; i++){ // } //Sleep(1000 * 5); //---------------------------------------------------------------------------- //imwrite("Images//Master.jpg", frame); //result.create(frame.cols - temp.cols + 1, frame.rows - temp.rows + 1, CV_32FC1); char **grid = (char **)calloc(9, sizeof(char)); for (int k = 0; k < 9; k++){ grid[k] = (char*)calloc(9, sizeof(char)); } // char grid[9][9] = { 0 }; vector<Point> unsquare; vector<Point> oneSquares; vector<Point> twoSquares; vector<Point> threeSquares; vector<Point> fourSquares; Mat unPressedMat; Mat oneMat; Mat twoMat; Mat threeMat; Mat fourMat; until endOfTime{ if (captureFrame(frame, mineHandle,height,width)==TRUE){ if (!frame.empty()){ //matchTemplate(frame, temp, result, TM_CCOEFF_NORMED); Mat result; result.create(frame.cols - temp.cols + 1, frame.rows - temp.rows + 1, CV_32FC1); //unPressedMat = frame.clone(); countSquares(frame, temp, result,0.920, unsquare, Scalar(0,255, 255)); cout << "Unpressed Squares: " << unsquare.size() << "\n"; //printSquares(unsquare); result.release(); if (unsquare.size() != 81){ Mat oneResult; oneResult.create(frame.cols - oneTemp.cols + 1, frame.rows - oneTemp.rows + 1, CV_32FC1); //oneMat = frame.clone(); countSquares(frame, oneTemp, oneResult, 0.9, oneSquares, Scalar(255, 0, 0)); cout << "One Squares: " << oneSquares.size() << "\n"; oneResult.release(); Mat twoResult; twoResult.create(frame.cols - twoTemp.cols + 1, frame.rows - twoTemp.rows + 1, CV_32FC1); //oneMat = frame.clone(); countSquares(frame, twoTemp, twoResult, 0.9, twoSquares, Scalar(255, 0, 0)); cout << "Two Squares: " << twoSquares.size() << "\n"; twoResult.release(); Mat threeResult; threeResult.create(frame.cols - threeTemp.cols + 1, frame.rows - threeTemp.rows + 1, CV_32FC1); //oneMat = frame.clone(); countSquares(frame, threeTemp, threeResult, 0.9, threeSquares, Scalar(255, 0, 0)); cout << "Three Squares: " << threeSquares.size() << "\n"; threeResult.release(); Mat fourResult; fourResult.create(frame.cols - fourTemp.cols + 1, frame.rows - fourTemp.rows + 1, CV_32FC1); //oneMat = frame.clone(); countSquares(frame, fourTemp, fourResult, 0.9, fourSquares, Scalar(255, 0, 0)); cout << "Four Squares: " << fourSquares.size() << "\n"; fourResult.release(); } //update grid updateGrid(grid, unsquare, gridMap, 0); updateGrid(grid, oneSquares, gridMap, 1); updateGrid(grid, twoSquares, gridMap, 2); updateGrid(grid, threeSquares, gridMap, 3); printGrid(grid); cv::imshow("Win", frame); //imshow("One", oneMat); Sleep(2000); } } if (waitKey(30) >= 0) break; } return 0; }<commit_msg>Clears grid every iteration of the loop<commit_after>#include <iostream> #include <Windows.h> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/opencv.hpp> #include <opencv2/imgproc.hpp> #include <algorithm> #include <string.h> /* mineBot.cpp T.Lloyd An attempt at an openCV minesweeper bot... */ using namespace cv; using namespace std; #define until for #define endOfTime (;;) BOOL captureFrame(Mat &f,HWND mineHandle,int height, int width){ HDC mineHDC, mineCompat; HBITMAP mineBit; BITMAP b; BITMAPINFOHEADER mineH; if (mineHandle == NULL){ cout << "Game Not Found\n"; return FALSE; } mineHDC = GetDC(mineHandle); mineCompat = CreateCompatibleDC(mineHDC); if (!mineCompat){ cout << "Error creating compatible DC\n"; return FALSE; } //SetStretchBltMode(mineCompat, HALFTONE); SetStretchBltMode(mineCompat, HALFTONE); mineBit = CreateCompatibleBitmap(mineHDC, width, height); if (mineBit == NULL){ cout << "Bitmap Creation Failed!\n"; return FALSE; } mineH.biSize = sizeof(BITMAPINFOHEADER); mineH.biPlanes = 1; mineH.biWidth = width; mineH.biHeight = -height; mineH.biBitCount = 32; mineH.biCompression = BI_RGB; SelectObject(mineCompat, mineBit); if (!StretchBlt(mineCompat, 0, 0, width, height, mineHDC, 0, 0, width, height, SRCCOPY)){ cout << "Error Stretch BLT\n"; return FALSE; } //BitBlt(mineCompat, 0, 0, width, height, mineHDC, 0, 0, SRCCOPY); //GetObject(mineBit, sizeof(BITMAP), &b); //GetDIBits(mineHDC, mineBit, 0, height, frame.data, (BITMAPINFO*)&mineH, DIB_RGB_COLORS); GetDIBits(mineCompat, mineBit, 0, height, f.data, (BITMAPINFO*)&mineH, DIB_RGB_COLORS); DeleteObject(mineBit); DeleteDC(mineCompat); ReleaseDC(mineHandle, mineHDC); return TRUE; } BOOL countSquares(Mat &f,Mat &t, Mat &r,double threshold,vector<Point> &squares,Scalar colour){ //Frame,Template,Result,Number of squares Mat greysrc = f.clone(); Mat greyTemp = t.clone(); cvtColor(f, greysrc, COLOR_BGR2GRAY); cvtColor(t, greyTemp, COLOR_BGR2GRAY); matchTemplate(greysrc, greyTemp, r, TM_CCOEFF_NORMED); normalize(r, r, 0, 1, NORM_MINMAX, -1, Mat()); double minVal; double maxVal; Point minLoc; Point maxLoc; Point matchLoc; Point prevMatchLoc; squares.clear(); bool edge = FALSE; int dup = 0; //count duplicates for (int i = 0, j = 0; i < 81; i++){ //minesweeper has gradient so only detects two of the squares. minMaxLoc(r, &minVal, &maxVal, &minLoc, &maxLoc, Mat()); //if (maxVal > 0.87){ if ((maxVal > threshold)){ matchLoc = maxLoc; for (int k = 0; k < squares.size(); k++){ if (((abs(matchLoc.y - squares[k].y) <= 3) && (abs(matchLoc.x - squares[k].x) <= 3))){ //cout << "!"; dup++; } } if (matchLoc.x > 30){ edge = TRUE; } else{ edge = FALSE; } //cout << "Duplicates=" << dup << "\n"; //dup = 0; if ((dup == 0)&&(edge==TRUE)){ squares.push_back(matchLoc); rectangle(r, matchLoc, Point(matchLoc.x + t.cols, matchLoc.y + t.rows), Scalar(0, 0, 0), CV_FILLED, 8, 0); rectangle(f, matchLoc, Point(matchLoc.x + t.cols, matchLoc.y + t.rows), colour, 1, 8, 0); } //} //} } } greysrc.release(); greyTemp.release(); //cout << "Vector Size=" << squares.size() << "\n"; return TRUE; } void printSquares(vector<Point> &p){ for (int k = 0; k < p.size(); k++){ cout << "(" << p[k].x << "," << p[k].y << ")\n"; } } bool sortX(Point p1, Point p2){return (p1.x < p2.x);} bool sortY(Point p1, Point p2){ return (p1.y < p2.y); } void sortGrid(vector<Point> &p){ //9x9 Grid Sorting Algorithm std::sort(p.begin(), p.end(), sortX); for (int i = 0; i < 9; i++){ std::sort(p.begin() + (i * 9), p.begin() + ((i + 1) * 9), sortY); } } void printGrid(char** &g){ for (int j = 0; j < 9; j++){ for (int k = 0; k < 9; k++){ cout << g[k][j]; } cout << "\n"; } } void updateGrid(char** &g,vector<Point>&s,vector<Point>&masterGrid,char value){ for (int j = 0; j < s.size(); j++){ for (int k = 0; k < masterGrid.size(); k++){ if ((s[j].x >= masterGrid[k].x) && (s[j].x <=(masterGrid[k].x + 16)) && (s[j].y >= masterGrid[k].y) && (s[j].y <= (masterGrid[k].y + 16))){ int xpos = (int)(k / 9); int ypos = (int)(k % 9); g[xpos][ypos] = value; } } } } void clearGrid(char** &g){ for (int i = 0; i < 9; i++){ for (int k = 0; k < 9; k++){ g[i][k] = 0; } } } int main(void){ std::cout << "mineBot\nT.Lloyd\n"; Mat frame; HWND mineHandle = FindWindow(NULL,L"Minesweeper"); if (mineHandle == NULL){ cout << "Game Not Found\n"; return -1; } else{ cout << "Game Successfully Found!\n"; } namedWindow("Win", 1); RECT winSize; int height, width; int unpressed = 0; GetClientRect(mineHandle, &winSize); height = winSize.bottom; width = winSize.right; frame.create(height, width, CV_8UC4); Point pt; pt.x = 0; pt.y = 0; Mat temp = imread("Images//square2.jpg", CV_LOAD_IMAGE_COLOR); Mat oneTemp = imread("Images//one3.jpg", CV_LOAD_IMAGE_COLOR); Mat twoTemp = imread("Images//two.jpg", CV_LOAD_IMAGE_COLOR); Mat threeTemp = imread("Images//three.jpg", CV_LOAD_IMAGE_COLOR); Mat fourTemp = imread("Images//four.jpg", CV_LOAD_IMAGE_COLOR); //cvtColor(temp, temp, CV_8UC4,0); //Mat result; //Mat oneResult; //---------------------------------------------------------------------------- //Initial read to define co-ordinates Mat gridResult; vector<Point> gridMap; captureFrame(frame, mineHandle, height, width); gridResult.create(frame.cols - temp.cols + 1, frame.rows - temp.rows + 1, CV_32FC1); //unPressedMat = frame.clone(); countSquares(frame, temp, gridResult, 0.920, gridMap, Scalar(0, 255, 255)); cout << "Unpressed Squares: " << gridResult.size() << "\n"; printSquares(gridMap); cv::imshow("Win", frame); gridResult.release(); sortGrid(gridMap); printSquares(gridMap); // for (int i = 0; i < gridMap.size; i++){ // } //Sleep(1000 * 5); //---------------------------------------------------------------------------- //imwrite("Images//Master.jpg", frame); //result.create(frame.cols - temp.cols + 1, frame.rows - temp.rows + 1, CV_32FC1); char **grid = (char **)calloc(9, sizeof(char)); for (int k = 0; k < 9; k++){ grid[k] = (char*)calloc(9, sizeof(char)); } // char grid[9][9] = { 0 }; vector<Point> unsquare; vector<Point> oneSquares; vector<Point> twoSquares; vector<Point> threeSquares; vector<Point> fourSquares; Mat unPressedMat; Mat oneMat; Mat twoMat; Mat threeMat; Mat fourMat; until endOfTime{ clearGrid(grid); if (captureFrame(frame, mineHandle,height,width)==TRUE){ if (!frame.empty()){ //matchTemplate(frame, temp, result, TM_CCOEFF_NORMED); Mat result; result.create(frame.cols - temp.cols + 1, frame.rows - temp.rows + 1, CV_32FC1); //unPressedMat = frame.clone(); countSquares(frame, temp, result,0.920, unsquare, Scalar(0,255, 255)); cout << "Unpressed Squares: " << unsquare.size() << "\n"; //printSquares(unsquare); result.release(); if (unsquare.size() != 81){ Mat oneResult; oneResult.create(frame.cols - oneTemp.cols + 1, frame.rows - oneTemp.rows + 1, CV_32FC1); //oneMat = frame.clone(); countSquares(frame, oneTemp, oneResult, 0.9, oneSquares, Scalar(255, 0, 0)); cout << "One Squares: " << oneSquares.size() << "\n"; oneResult.release(); Mat twoResult; twoResult.create(frame.cols - twoTemp.cols + 1, frame.rows - twoTemp.rows + 1, CV_32FC1); //oneMat = frame.clone(); countSquares(frame, twoTemp, twoResult, 0.9, twoSquares, Scalar(255, 255, 0)); cout << "Two Squares: " << twoSquares.size() << "\n"; twoResult.release(); Mat threeResult; threeResult.create(frame.cols - threeTemp.cols + 1, frame.rows - threeTemp.rows + 1, CV_32FC1); //oneMat = frame.clone(); countSquares(frame, threeTemp, threeResult, 0.9, threeSquares, Scalar(255, 0, 255)); cout << "Three Squares: " << threeSquares.size() << "\n"; threeResult.release(); Mat fourResult; fourResult.create(frame.cols - fourTemp.cols + 1, frame.rows - fourTemp.rows + 1, CV_32FC1); //oneMat = frame.clone(); countSquares(frame, fourTemp, fourResult, 0.9, fourSquares, Scalar(255, 0, 0)); cout << "Four Squares: " << fourSquares.size() << "\n"; fourResult.release(); } //update grid updateGrid(grid, unsquare, gridMap, 'U'); updateGrid(grid, oneSquares, gridMap, '1'); updateGrid(grid, twoSquares, gridMap, '2'); updateGrid(grid, threeSquares, gridMap, '3'); printGrid(grid); cv::imshow("Win", frame); //imshow("One", oneMat); Sleep(1000); } } if (waitKey(30) >= 0) break; } return 0; }<|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org Copyright (c) 2000-2014 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "RTShaderSRSTexturedFog.h" #include "OgreShaderFFPRenderState.h" #include "OgreShaderProgram.h" #include "OgreShaderParameter.h" #include "OgreShaderProgramSet.h" #include "OgreGpuProgram.h" #include "OgrePass.h" #include "OgreShaderGenerator.h" #define FFP_FUNC_PIXELFOG_POSITION_DEPTH "FFP_PixelFog_PositionDepth" using namespace Ogre; using namespace RTShader; /************************************************************************/ /* */ /************************************************************************/ String RTShaderSRSTexturedFog::Type = "TexturedFog"; //----------------------------------------------------------------------- RTShaderSRSTexturedFog::RTShaderSRSTexturedFog(RTShaderSRSTexturedFogFactory* factory) { mFactory = factory; mFogMode = FOG_NONE; mPassOverrideParams = false; } //----------------------------------------------------------------------- const String& RTShaderSRSTexturedFog::getType() const { return Type; } //----------------------------------------------------------------------- int RTShaderSRSTexturedFog::getExecutionOrder() const { return FFP_FOG; } //----------------------------------------------------------------------- void RTShaderSRSTexturedFog::updateGpuProgramsParams(Renderable* rend, Pass* pass, const AutoParamDataSource* source, const LightList* pLightList) { if (mFogMode == FOG_NONE) return; FogMode fogMode; Real newFogStart, newFogEnd, newFogDensity; //Check if this is an overlay element if so disable fog if ((rend->getUseIdentityView() == true) && (rend->getUseIdentityProjection() == true)) { fogMode = FOG_NONE; newFogStart = 100000000; newFogEnd = 200000000; newFogDensity = 0; } else { if (mPassOverrideParams) { fogMode = pass->getFogMode(); newFogStart = pass->getFogStart(); newFogEnd = pass->getFogEnd(); newFogDensity = pass->getFogDensity(); } else { SceneManager* sceneMgr = ShaderGenerator::getSingleton().getActiveSceneManager(); fogMode = sceneMgr->getFogMode(); newFogStart = sceneMgr->getFogStart(); newFogEnd = sceneMgr->getFogEnd(); newFogDensity = sceneMgr->getFogDensity(); } } // Set fog properties. setFogProperties(fogMode, newFogStart, newFogEnd, newFogDensity); mFogParams->setGpuParameter(mFogParamsValue); } //----------------------------------------------------------------------- bool RTShaderSRSTexturedFog::resolveParameters(ProgramSet* programSet) { if (mFogMode == FOG_NONE) return true; Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); Function* vsMain = vsProgram->getEntryPointFunction(); Function* psMain = psProgram->getEntryPointFunction(); // Resolve world view matrix. mWorldMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_WORLD_MATRIX); if (mWorldMatrix.get() == NULL) return false; // Resolve world view matrix. mCameraPos = vsProgram->resolveParameter(GpuProgramParameters::ACT_CAMERA_POSITION); if (mCameraPos.get() == NULL) return false; // Resolve vertex shader input position. mVSInPos = vsMain->resolveInputParameter(Parameter::SPC_POSITION_OBJECT_SPACE); if (mVSInPos.get() == NULL) return false; // Resolve fog colour. mFogColour = psMain->resolveLocalParameter("FogColor", GCT_FLOAT4); if (mFogColour.get() == NULL) return false; // Resolve pixel shader output diffuse color. mPSOutDiffuse = psMain->resolveOutputParameter(Parameter::SPC_COLOR_DIFFUSE); if (mPSOutDiffuse.get() == NULL) return false; // Resolve fog params. mFogParams = psProgram->resolveParameter(GCT_FLOAT4, -1, (uint16)GPV_GLOBAL, "gFogParams"); if (mFogParams.get() == NULL) return false; // Resolve vertex shader output depth. mVSOutPosView = vsMain->resolveOutputParameter(Parameter::SPC_POSITION_VIEW_SPACE); if (mVSOutPosView.get() == NULL) return false; // Resolve pixel shader input depth. mPSInPosView = psMain->resolveInputParameter(mVSOutPosView); if (mPSInPosView.get() == NULL) return false; // Resolve vertex shader output depth. mVSOutDepth = vsMain->resolveOutputParameter(Parameter::SPC_DEPTH_VIEW_SPACE); if (mVSOutDepth.get() == NULL) return false; // Resolve pixel shader input depth. mPSInDepth = psMain->resolveInputParameter(mVSOutDepth); if (mPSInDepth.get() == NULL) return false; // Resolve texture sampler parameter. mBackgroundTextureSampler = psProgram->resolveParameter(GCT_SAMPLERCUBE, mBackgroundSamplerIndex, (uint16)GPV_GLOBAL, "FogBackgroundSampler"); if (mBackgroundTextureSampler.get() == NULL) return false; return true; } //----------------------------------------------------------------------- bool RTShaderSRSTexturedFog::resolveDependencies(ProgramSet* programSet) { if (mFogMode == FOG_NONE) return true; Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); vsProgram->addDependency(FFP_LIB_FOG); psProgram->addDependency(FFP_LIB_COMMON); psProgram->addDependency(FFP_LIB_FOG); psProgram->addDependency(FFP_LIB_TEXTURING); return true; } //----------------------------------------------------------------------- bool RTShaderSRSTexturedFog::addFunctionInvocations(ProgramSet* programSet) { if (mFogMode == FOG_NONE) return true; Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); Function* vsMain = vsProgram->getEntryPointFunction(); Function* psMain = psProgram->getEntryPointFunction(); vsMain->getStage(FFP_VS_FOG) .callFunction(FFP_FUNC_PIXELFOG_POSITION_DEPTH, {In(mWorldMatrix), In(mCameraPos), In(mVSInPos), Out(mVSOutPosView), Out(mVSOutDepth)}); auto psStage = psMain->getStage(FFP_PS_FOG); psStage.sampleTexture(mBackgroundTextureSampler, mPSInPosView, mFogColour); const char* fogFunc = NULL; switch (mFogMode) { case FOG_LINEAR: fogFunc = FFP_FUNC_PIXELFOG_LINEAR; break; case FOG_EXP: fogFunc = FFP_FUNC_PIXELFOG_EXP; break; case FOG_EXP2: fogFunc = FFP_FUNC_PIXELFOG_EXP2; break; case FOG_NONE: break; } psStage.callFunction(fogFunc, {In(mPSInDepth), In(mFogParams), In(mFogColour), In(mPSOutDiffuse), Out(mPSOutDiffuse)}); return true; } //----------------------------------------------------------------------- void RTShaderSRSTexturedFog::copyFrom(const SubRenderState& rhs) { const RTShaderSRSTexturedFog& rhsFog = static_cast<const RTShaderSRSTexturedFog&>(rhs); mFogMode = rhsFog.mFogMode; mFogParamsValue = rhsFog.mFogParamsValue; mFactory = rhsFog.mFactory; } //----------------------------------------------------------------------- bool RTShaderSRSTexturedFog::preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass) { if (mFactory == NULL) return false; FogMode fogMode; ColourValue newFogColour; Real newFogStart, newFogEnd, newFogDensity; if (srcPass->getFogOverride()) { fogMode = srcPass->getFogMode(); newFogStart = srcPass->getFogStart(); newFogEnd = srcPass->getFogEnd(); newFogDensity = srcPass->getFogDensity(); mPassOverrideParams = true; } else { SceneManager* sceneMgr = ShaderGenerator::getSingleton().getActiveSceneManager(); if (sceneMgr == NULL) { fogMode = FOG_NONE; newFogStart = 0.0; newFogEnd = 0.0; newFogDensity = 0.0; } else { fogMode = sceneMgr->getFogMode(); newFogStart = sceneMgr->getFogStart(); newFogEnd = sceneMgr->getFogEnd(); newFogDensity = sceneMgr->getFogDensity(); } mPassOverrideParams = false; } // Set fog properties. setFogProperties(fogMode, newFogStart, newFogEnd, newFogDensity); // Override scene fog since it will happen in shader. dstPass->setFog(true, FOG_NONE, ColourValue::White, newFogDensity, newFogStart, newFogEnd); TextureUnitState* tus = dstPass->createTextureUnitState(mFactory->getBackgroundTextureName()); tus->setCubicTextureName(mFactory->getBackgroundTextureName(), true); mBackgroundSamplerIndex = dstPass->getNumTextureUnitStates() - 1; return true; } //----------------------------------------------------------------------- void RTShaderSRSTexturedFog::setFogProperties(FogMode fogMode, float fogStart, float fogEnd, float fogDensity) { mFogMode = fogMode; mFogParamsValue.x = fogDensity; mFogParamsValue.y = fogStart; mFogParamsValue.z = fogEnd; mFogParamsValue.w = fogEnd != fogStart ? 1 / (fogEnd - fogStart) : 0; } //----------------------------------------------------------------------- const String& RTShaderSRSTexturedFogFactory::getType() const { return RTShaderSRSTexturedFog::Type; } //----------------------------------------------------------------------- SubRenderState* RTShaderSRSTexturedFogFactory::createInstanceImpl() { return OGRE_NEW RTShaderSRSTexturedFog(this); } <commit_msg>Samples: TexturedFog - fix errors with strict mode<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org Copyright (c) 2000-2014 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "RTShaderSRSTexturedFog.h" #include "OgreShaderFFPRenderState.h" #include "OgreShaderProgram.h" #include "OgreShaderParameter.h" #include "OgreShaderProgramSet.h" #include "OgreGpuProgram.h" #include "OgrePass.h" #include "OgreShaderGenerator.h" #include "OgreTextureManager.h" #define FFP_FUNC_PIXELFOG_POSITION_DEPTH "FFP_PixelFog_PositionDepth" using namespace Ogre; using namespace RTShader; /************************************************************************/ /* */ /************************************************************************/ String RTShaderSRSTexturedFog::Type = "TexturedFog"; //----------------------------------------------------------------------- RTShaderSRSTexturedFog::RTShaderSRSTexturedFog(RTShaderSRSTexturedFogFactory* factory) { mFactory = factory; mFogMode = FOG_NONE; mPassOverrideParams = false; } //----------------------------------------------------------------------- const String& RTShaderSRSTexturedFog::getType() const { return Type; } //----------------------------------------------------------------------- int RTShaderSRSTexturedFog::getExecutionOrder() const { return FFP_FOG; } //----------------------------------------------------------------------- void RTShaderSRSTexturedFog::updateGpuProgramsParams(Renderable* rend, Pass* pass, const AutoParamDataSource* source, const LightList* pLightList) { if (mFogMode == FOG_NONE) return; FogMode fogMode; Real newFogStart, newFogEnd, newFogDensity; //Check if this is an overlay element if so disable fog if ((rend->getUseIdentityView() == true) && (rend->getUseIdentityProjection() == true)) { fogMode = FOG_NONE; newFogStart = 100000000; newFogEnd = 200000000; newFogDensity = 0; } else { if (mPassOverrideParams) { fogMode = pass->getFogMode(); newFogStart = pass->getFogStart(); newFogEnd = pass->getFogEnd(); newFogDensity = pass->getFogDensity(); } else { SceneManager* sceneMgr = ShaderGenerator::getSingleton().getActiveSceneManager(); fogMode = sceneMgr->getFogMode(); newFogStart = sceneMgr->getFogStart(); newFogEnd = sceneMgr->getFogEnd(); newFogDensity = sceneMgr->getFogDensity(); } } // Set fog properties. setFogProperties(fogMode, newFogStart, newFogEnd, newFogDensity); mFogParams->setGpuParameter(mFogParamsValue); } //----------------------------------------------------------------------- bool RTShaderSRSTexturedFog::resolveParameters(ProgramSet* programSet) { if (mFogMode == FOG_NONE) return true; Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); Function* vsMain = vsProgram->getEntryPointFunction(); Function* psMain = psProgram->getEntryPointFunction(); // Resolve world view matrix. mWorldMatrix = vsProgram->resolveParameter(GpuProgramParameters::ACT_WORLD_MATRIX); if (mWorldMatrix.get() == NULL) return false; // Resolve world view matrix. mCameraPos = vsProgram->resolveParameter(GpuProgramParameters::ACT_CAMERA_POSITION); if (mCameraPos.get() == NULL) return false; // Resolve vertex shader input position. mVSInPos = vsMain->resolveInputParameter(Parameter::SPC_POSITION_OBJECT_SPACE); if (mVSInPos.get() == NULL) return false; // Resolve fog colour. mFogColour = psMain->resolveLocalParameter("FogColor", GCT_FLOAT4); if (mFogColour.get() == NULL) return false; // Resolve pixel shader output diffuse color. mPSOutDiffuse = psMain->resolveOutputParameter(Parameter::SPC_COLOR_DIFFUSE); if (mPSOutDiffuse.get() == NULL) return false; // Resolve fog params. mFogParams = psProgram->resolveParameter(GCT_FLOAT4, -1, (uint16)GPV_GLOBAL, "gFogParams"); if (mFogParams.get() == NULL) return false; // Resolve vertex shader output depth. mVSOutPosView = vsMain->resolveOutputParameter(Parameter::SPC_POSITION_VIEW_SPACE); if (mVSOutPosView.get() == NULL) return false; // Resolve pixel shader input depth. mPSInPosView = psMain->resolveInputParameter(mVSOutPosView); if (mPSInPosView.get() == NULL) return false; // Resolve vertex shader output depth. mVSOutDepth = vsMain->resolveOutputParameter(Parameter::SPC_DEPTH_VIEW_SPACE); if (mVSOutDepth.get() == NULL) return false; // Resolve pixel shader input depth. mPSInDepth = psMain->resolveInputParameter(mVSOutDepth); if (mPSInDepth.get() == NULL) return false; // Resolve texture sampler parameter. mBackgroundTextureSampler = psProgram->resolveParameter(GCT_SAMPLERCUBE, mBackgroundSamplerIndex, (uint16)GPV_GLOBAL, "FogBackgroundSampler"); if (mBackgroundTextureSampler.get() == NULL) return false; return true; } //----------------------------------------------------------------------- bool RTShaderSRSTexturedFog::resolveDependencies(ProgramSet* programSet) { if (mFogMode == FOG_NONE) return true; Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); vsProgram->addDependency(FFP_LIB_FOG); psProgram->addDependency(FFP_LIB_COMMON); psProgram->addDependency(FFP_LIB_FOG); psProgram->addDependency(FFP_LIB_TEXTURING); return true; } //----------------------------------------------------------------------- bool RTShaderSRSTexturedFog::addFunctionInvocations(ProgramSet* programSet) { if (mFogMode == FOG_NONE) return true; Program* vsProgram = programSet->getCpuProgram(GPT_VERTEX_PROGRAM); Program* psProgram = programSet->getCpuProgram(GPT_FRAGMENT_PROGRAM); Function* vsMain = vsProgram->getEntryPointFunction(); Function* psMain = psProgram->getEntryPointFunction(); vsMain->getStage(FFP_VS_FOG) .callFunction(FFP_FUNC_PIXELFOG_POSITION_DEPTH, {In(mWorldMatrix), In(mCameraPos), In(mVSInPos), Out(mVSOutPosView), Out(mVSOutDepth)}); auto psStage = psMain->getStage(FFP_PS_FOG); psStage.sampleTexture(mBackgroundTextureSampler, mPSInPosView, mFogColour); const char* fogFunc = NULL; switch (mFogMode) { case FOG_LINEAR: fogFunc = FFP_FUNC_PIXELFOG_LINEAR; break; case FOG_EXP: fogFunc = FFP_FUNC_PIXELFOG_EXP; break; case FOG_EXP2: fogFunc = FFP_FUNC_PIXELFOG_EXP2; break; case FOG_NONE: break; } psStage.callFunction(fogFunc, {In(mPSInDepth), In(mFogParams), In(mFogColour), In(mPSOutDiffuse), Out(mPSOutDiffuse)}); return true; } //----------------------------------------------------------------------- void RTShaderSRSTexturedFog::copyFrom(const SubRenderState& rhs) { const RTShaderSRSTexturedFog& rhsFog = static_cast<const RTShaderSRSTexturedFog&>(rhs); mFogMode = rhsFog.mFogMode; mFogParamsValue = rhsFog.mFogParamsValue; mFactory = rhsFog.mFactory; } //----------------------------------------------------------------------- bool RTShaderSRSTexturedFog::preAddToRenderState(const RenderState* renderState, Pass* srcPass, Pass* dstPass) { if (mFactory == NULL) return false; FogMode fogMode; ColourValue newFogColour; Real newFogStart, newFogEnd, newFogDensity; if (srcPass->getFogOverride()) { fogMode = srcPass->getFogMode(); newFogStart = srcPass->getFogStart(); newFogEnd = srcPass->getFogEnd(); newFogDensity = srcPass->getFogDensity(); mPassOverrideParams = true; } else { SceneManager* sceneMgr = ShaderGenerator::getSingleton().getActiveSceneManager(); if (sceneMgr == NULL) { fogMode = FOG_NONE; newFogStart = 0.0; newFogEnd = 0.0; newFogDensity = 0.0; } else { fogMode = sceneMgr->getFogMode(); newFogStart = sceneMgr->getFogStart(); newFogEnd = sceneMgr->getFogEnd(); newFogDensity = sceneMgr->getFogDensity(); } mPassOverrideParams = false; } // Set fog properties. setFogProperties(fogMode, newFogStart, newFogEnd, newFogDensity); // Override scene fog since it will happen in shader. dstPass->setFog(true, FOG_NONE, ColourValue::White, newFogDensity, newFogStart, newFogEnd); TextureUnitState* tus = dstPass->createTextureUnitState(); auto tex = TextureManager::getSingleton().load( mFactory->getBackgroundTextureName(), RGN_DEFAULT, TEX_TYPE_CUBE_MAP); tus->setTexture(tex); mBackgroundSamplerIndex = dstPass->getNumTextureUnitStates() - 1; return true; } //----------------------------------------------------------------------- void RTShaderSRSTexturedFog::setFogProperties(FogMode fogMode, float fogStart, float fogEnd, float fogDensity) { mFogMode = fogMode; mFogParamsValue.x = fogDensity; mFogParamsValue.y = fogStart; mFogParamsValue.z = fogEnd; mFogParamsValue.w = fogEnd != fogStart ? 1 / (fogEnd - fogStart) : 0; } //----------------------------------------------------------------------- const String& RTShaderSRSTexturedFogFactory::getType() const { return RTShaderSRSTexturedFog::Type; } //----------------------------------------------------------------------- SubRenderState* RTShaderSRSTexturedFogFactory::createInstanceImpl() { return OGRE_NEW RTShaderSRSTexturedFog(this); } <|endoftext|>
<commit_before>#include <iostream> #include <iomanip> using namespace std; int main(int argc, char *argv[]) { cout << "|"; for (int x = 1; x<=12; ++x) { cout <<x <<"|"; } cout << endl; for( int x = 0; x<=12; ++x) { cout << "+"; } cout << endl; for( int y = 1; y<=12; ++y) { cout<< y << "|"; for (int x=1; x<=12; ++x) { cout<<x*y << "|"; } cout<< endl; for(int x =0; x<=12; ++x) { cout << "----+"; } cout <<endl; } } <commit_msg>fixed output off xtable.closes #35<commit_after>#include <iostream> #include <iomanip> using namespace std; int main(int argc, char *argv[]) { cout << " |"; for (int x = 1; x<=12; ++x) { cout <<setw(5)<< x <<"|"; } cout << endl; for( int x = 0; x<=12; ++x) { cout << "-----+"; } cout << endl; for( int y = 1; y<=12; ++y) { cout<<setw(5)<< y << "|"; for (int x=1; x<=12; ++x) { cout<<setw(5)<<x*y << "|"; } cout<< endl; for(int x =0; x<=12; ++x) { cout << "-----+"; } cout <<endl; } } <|endoftext|>
<commit_before>/***************************************************************************** * Copyright (C) 2012 * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #define __STDC_CONSTANT_MACROS 1 #include <vlc_common.h> #include <vlc_plugin.h> #include <vlc_network.h> #include <vlc_services_discovery.h> #include <functional> #include <unordered_map> #include <sstream> #include "discovery.h" #include "helper.h" #include "htsmessage.h" #include "sha1.h" struct tmp_channel { std::string name; uint32_t cid; uint32_t cnum; std::string url; input_item_t *item; std::list<std::string> tags; }; struct services_discovery_sys_t : public sys_common_t { services_discovery_sys_t() :thread(0) {} vlc_thread_t thread; std::unordered_map<uint32_t, tmp_channel> channelMap; }; bool ConnectSD(services_discovery_t *sd) { services_discovery_sys_t *sys = sd->p_sys; const char *host = var_GetString(sd, CFG_PREFIX"host"); int port = var_GetInteger(sd, CFG_PREFIX"port"); if(host == 0 || host[0] == 0) host = "localhost"; if(port == 0) port = 9982; sys->netfd = net_ConnectTCP(sd, host, port); if(sys->netfd < 0) { msg_Err(sd, "net_ConnectTCP failed"); return false; } HtsMap map; map.setData("method", "hello"); map.setData("clientname", "VLC media player"); map.setData("htspversion", HTSP_PROTO_VERSION); HtsMessage m = ReadResult(sd, sys, map.makeMsg()); if(!m.isValid()) { msg_Err(sd, "No valid hello response"); return false; } uint32_t chall_len; void * chall; m.getRoot()->getBin("challenge", &chall_len, &chall); std::string serverName = m.getRoot()->getStr("servername"); std::string serverVersion = m.getRoot()->getStr("serverversion"); uint32_t protoVersion = m.getRoot()->getU32("htspversion"); msg_Info(sd, "Connected to HTSP Server %s, version %s, protocol %d", serverName.c_str(), serverVersion.c_str(), protoVersion); if(protoVersion < HTSP_PROTO_VERSION) { msg_Warn(sd, "TVHeadend is running an older version of HTSP(v%d) than we are(v%d). No effort was made to keep compatible with older versions, update tvh before reporting problems!", protoVersion, HTSP_PROTO_VERSION); } else if(protoVersion > HTSP_PROTO_VERSION) { msg_Info(sd, "TVHeadend is running a more recent version of HTSP(v%d) than we are(v%d). Check if there is an update available!", protoVersion, HTSP_PROTO_VERSION); } const char *user = var_GetString(sd, CFG_PREFIX"user"); const char *pass = var_GetString(sd, CFG_PREFIX"pass"); if(user == 0 || user[0] == 0) return true; map = HtsMap(); map.setData("method", "authenticate"); map.setData("username", user); if(pass != 0 && pass[0] != 0 && chall) { msg_Info(sd, "Authenticating as '%s' with a password", user); HTSSHA1 *shactx = (HTSSHA1*)malloc(hts_sha1_size); uint8_t d[20]; hts_sha1_init(shactx); hts_sha1_update(shactx, (const uint8_t *)pass, strlen(pass)); hts_sha1_update(shactx, (const uint8_t *)chall, chall_len); hts_sha1_final(shactx, d); std::shared_ptr<HtsBin> bin = std::make_shared<HtsBin>(); bin->setBin(20, d); map.setData("digest", bin); free(shactx); } else msg_Info(sd, "Authenticating as '%s' without a password", user); if(chall) free(chall); bool res = ReadSuccess(sd, sys, map.makeMsg(), "authenticate"); if(res) msg_Info(sd, "Successfully authenticated!"); else msg_Err(sd, "Authentication failed!"); return res; } bool GetChannels(services_discovery_t *sd) { services_discovery_sys_t *sys = sd->p_sys; HtsMap map; map.setData("method", "enableAsyncMetadata"); if(!ReadSuccess(sd, sys, map.makeMsg(), "enable async metadata")) return false; std::list<uint32_t> channelIds; std::unordered_map<uint32_t, tmp_channel> channels; HtsMessage m; while((m = ReadMessage(sd, sys)).isValid()) { std::string method = m.getRoot()->getStr("method"); if(method.empty() || method == "initialSyncCompleted") { msg_Info(sd, "Finished getting initial metadata sync"); break; } if(method == "channelAdd") { if(!m.getRoot()->contains("channelId")) continue; uint32_t cid = m.getRoot()->getU32("channelId"); std::string cname = m.getRoot()->getStr("channelName"); if(cname.empty()) { std::ostringstream ss; ss << "Channel " << cid; cname = ss.str(); } uint32_t cnum = m.getRoot()->getU32("channelNumber"); std::ostringstream oss; oss << "htsp://"; char *user = var_GetString(sd, CFG_PREFIX"user"); char *pass = var_GetString(sd, CFG_PREFIX"pass"); if(user != 0 && user[0] != 0 && pass != 0 && pass[0] != 0) oss << user << ":" << pass << "@"; else if(user != 0 && user[0] != 0) oss << user << "@"; const char *host = var_GetString(sd, CFG_PREFIX"host"); if(host == 0 || host[0] == 0) host = "localhost"; int port = var_GetInteger(sd, CFG_PREFIX"port"); if(port == 0) port = 9982; oss << host << ":" << port << "/" << cid; channels[cid].name = cname; channels[cid].cid = cid; channels[cid].cnum = cnum; channels[cid].url = oss.str(); channelIds.push_back(cid); } else if(method == "tagAdd" || method == "tagUpdate") { if(!m.getRoot()->contains("tagId") || !m.getRoot()->contains("tagName")) continue; std::string tagName = m.getRoot()->getStr("tagName"); std::shared_ptr<HtsList> chList = m.getRoot()->getList("members"); for(uint32_t i = 0; i < chList->count(); ++i) channels[chList->getData(i)->getU32()].tags.push_back(tagName); } } channelIds.sort([&](const uint32_t &first, const uint32_t &second) { return channels[first].cnum < channels[second].cnum; }); while(channelIds.size() > 0) { tmp_channel ch = channels[channelIds.front()]; channelIds.pop_front(); ch.item = input_item_New(ch.url.c_str(), ch.name.c_str()); if(unlikely(ch.item == 0)) return false; ch.item->i_type = ITEM_TYPE_NET; for(std::string tag: ch.tags) services_discovery_AddItem(sd, ch.item, tag.c_str()); services_discovery_AddItem(sd, ch.item, "All Channels"); sys->channelMap[ch.cid] = ch; } return true; } void * RunSD(void *obj) { services_discovery_t *sd = (services_discovery_t *)obj; services_discovery_sys_t *sys = sd->p_sys; if(!ConnectSD(sd)) { msg_Err(sd, "Connecting to HTS Failed!"); return 0; } GetChannels(sd); for(;;) { HtsMessage msg = ReadMessage(sd, sys); if(!msg.isValid()) return 0; std::string method = msg.getRoot()->getStr("method"); if(method.empty()) return 0; msg_Dbg(sd, "Got Message with method %s", method.c_str()); } return 0; } int OpenSD(vlc_object_t *obj) { services_discovery_t *sd = (services_discovery_t *)obj; services_discovery_sys_t *sys = new services_discovery_sys_t; if(unlikely(sys == NULL)) return VLC_ENOMEM; sd->p_sys = sys; config_ChainParse(sd, CFG_PREFIX, cfg_options, sd->p_cfg); if(vlc_clone(&sys->thread, RunSD, sd, VLC_THREAD_PRIORITY_LOW)) { delete sys; return VLC_EGENERIC; } return VLC_SUCCESS; } void CloseSD(vlc_object_t *obj) { services_discovery_t *sd = (services_discovery_t *)obj; services_discovery_sys_t *sys = sd->p_sys; if(!sys) return; if(sys->thread) { vlc_cancel(sys->thread); vlc_join(sys->thread, 0); sys->thread = 0; } delete sys; sys = sd->p_sys = 0; } <commit_msg>Fix a small leak<commit_after>/***************************************************************************** * Copyright (C) 2012 * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #define __STDC_CONSTANT_MACROS 1 #include <vlc_common.h> #include <vlc_plugin.h> #include <vlc_network.h> #include <vlc_services_discovery.h> #include <functional> #include <unordered_map> #include <sstream> #include "discovery.h" #include "helper.h" #include "htsmessage.h" #include "sha1.h" struct tmp_channel { std::string name; uint32_t cid; uint32_t cnum; std::string url; input_item_t *item; std::list<std::string> tags; }; struct services_discovery_sys_t : public sys_common_t { services_discovery_sys_t() :thread(0) {} vlc_thread_t thread; std::unordered_map<uint32_t, tmp_channel> channelMap; }; bool ConnectSD(services_discovery_t *sd) { services_discovery_sys_t *sys = sd->p_sys; const char *host = var_GetString(sd, CFG_PREFIX"host"); int port = var_GetInteger(sd, CFG_PREFIX"port"); if(host == 0 || host[0] == 0) host = "localhost"; if(port == 0) port = 9982; sys->netfd = net_ConnectTCP(sd, host, port); if(sys->netfd < 0) { msg_Err(sd, "net_ConnectTCP failed"); return false; } HtsMap map; map.setData("method", "hello"); map.setData("clientname", "VLC media player"); map.setData("htspversion", HTSP_PROTO_VERSION); HtsMessage m = ReadResult(sd, sys, map.makeMsg()); if(!m.isValid()) { msg_Err(sd, "No valid hello response"); return false; } uint32_t chall_len; void * chall; m.getRoot()->getBin("challenge", &chall_len, &chall); std::string serverName = m.getRoot()->getStr("servername"); std::string serverVersion = m.getRoot()->getStr("serverversion"); uint32_t protoVersion = m.getRoot()->getU32("htspversion"); msg_Info(sd, "Connected to HTSP Server %s, version %s, protocol %d", serverName.c_str(), serverVersion.c_str(), protoVersion); if(protoVersion < HTSP_PROTO_VERSION) { msg_Warn(sd, "TVHeadend is running an older version of HTSP(v%d) than we are(v%d). No effort was made to keep compatible with older versions, update tvh before reporting problems!", protoVersion, HTSP_PROTO_VERSION); } else if(protoVersion > HTSP_PROTO_VERSION) { msg_Info(sd, "TVHeadend is running a more recent version of HTSP(v%d) than we are(v%d). Check if there is an update available!", protoVersion, HTSP_PROTO_VERSION); } const char *user = var_GetString(sd, CFG_PREFIX"user"); const char *pass = var_GetString(sd, CFG_PREFIX"pass"); if(user == 0 || user[0] == 0) return true; map = HtsMap(); map.setData("method", "authenticate"); map.setData("username", user); if(pass != 0 && pass[0] != 0 && chall) { msg_Info(sd, "Authenticating as '%s' with a password", user); HTSSHA1 *shactx = (HTSSHA1*)malloc(hts_sha1_size); uint8_t d[20]; hts_sha1_init(shactx); hts_sha1_update(shactx, (const uint8_t *)pass, strlen(pass)); hts_sha1_update(shactx, (const uint8_t *)chall, chall_len); hts_sha1_final(shactx, d); std::shared_ptr<HtsBin> bin = std::make_shared<HtsBin>(); bin->setBin(20, d); map.setData("digest", bin); free(shactx); } else msg_Info(sd, "Authenticating as '%s' without a password", user); if(user) free(user); if(pass) free(pass); if(chall) free(chall); bool res = ReadSuccess(sd, sys, map.makeMsg(), "authenticate"); if(res) msg_Info(sd, "Successfully authenticated!"); else msg_Err(sd, "Authentication failed!"); return res; } bool GetChannels(services_discovery_t *sd) { services_discovery_sys_t *sys = sd->p_sys; HtsMap map; map.setData("method", "enableAsyncMetadata"); if(!ReadSuccess(sd, sys, map.makeMsg(), "enable async metadata")) return false; std::list<uint32_t> channelIds; std::unordered_map<uint32_t, tmp_channel> channels; HtsMessage m; while((m = ReadMessage(sd, sys)).isValid()) { std::string method = m.getRoot()->getStr("method"); if(method.empty() || method == "initialSyncCompleted") { msg_Info(sd, "Finished getting initial metadata sync"); break; } if(method == "channelAdd") { if(!m.getRoot()->contains("channelId")) continue; uint32_t cid = m.getRoot()->getU32("channelId"); std::string cname = m.getRoot()->getStr("channelName"); if(cname.empty()) { std::ostringstream ss; ss << "Channel " << cid; cname = ss.str(); } uint32_t cnum = m.getRoot()->getU32("channelNumber"); std::ostringstream oss; oss << "htsp://"; char *user = var_GetString(sd, CFG_PREFIX"user"); char *pass = var_GetString(sd, CFG_PREFIX"pass"); if(user != 0 && user[0] != 0 && pass != 0 && pass[0] != 0) oss << user << ":" << pass << "@"; else if(user != 0 && user[0] != 0) oss << user << "@"; const char *host = var_GetString(sd, CFG_PREFIX"host"); if(host == 0 || host[0] == 0) host = "localhost"; int port = var_GetInteger(sd, CFG_PREFIX"port"); if(port == 0) port = 9982; oss << host << ":" << port << "/" << cid; channels[cid].name = cname; channels[cid].cid = cid; channels[cid].cnum = cnum; channels[cid].url = oss.str(); channelIds.push_back(cid); } else if(method == "tagAdd" || method == "tagUpdate") { if(!m.getRoot()->contains("tagId") || !m.getRoot()->contains("tagName")) continue; std::string tagName = m.getRoot()->getStr("tagName"); std::shared_ptr<HtsList> chList = m.getRoot()->getList("members"); for(uint32_t i = 0; i < chList->count(); ++i) channels[chList->getData(i)->getU32()].tags.push_back(tagName); } } channelIds.sort([&](const uint32_t &first, const uint32_t &second) { return channels[first].cnum < channels[second].cnum; }); while(channelIds.size() > 0) { tmp_channel ch = channels[channelIds.front()]; channelIds.pop_front(); ch.item = input_item_New(ch.url.c_str(), ch.name.c_str()); if(unlikely(ch.item == 0)) return false; ch.item->i_type = ITEM_TYPE_NET; for(std::string tag: ch.tags) services_discovery_AddItem(sd, ch.item, tag.c_str()); services_discovery_AddItem(sd, ch.item, "All Channels"); sys->channelMap[ch.cid] = ch; } return true; } void * RunSD(void *obj) { services_discovery_t *sd = (services_discovery_t *)obj; services_discovery_sys_t *sys = sd->p_sys; if(!ConnectSD(sd)) { msg_Err(sd, "Connecting to HTS Failed!"); return 0; } GetChannels(sd); for(;;) { HtsMessage msg = ReadMessage(sd, sys); if(!msg.isValid()) return 0; std::string method = msg.getRoot()->getStr("method"); if(method.empty()) return 0; msg_Dbg(sd, "Got Message with method %s", method.c_str()); } return 0; } int OpenSD(vlc_object_t *obj) { services_discovery_t *sd = (services_discovery_t *)obj; services_discovery_sys_t *sys = new services_discovery_sys_t; if(unlikely(sys == NULL)) return VLC_ENOMEM; sd->p_sys = sys; config_ChainParse(sd, CFG_PREFIX, cfg_options, sd->p_cfg); if(vlc_clone(&sys->thread, RunSD, sd, VLC_THREAD_PRIORITY_LOW)) { delete sys; return VLC_EGENERIC; } return VLC_SUCCESS; } void CloseSD(vlc_object_t *obj) { services_discovery_t *sd = (services_discovery_t *)obj; services_discovery_sys_t *sys = sd->p_sys; if(!sys) return; if(sys->thread) { vlc_cancel(sys->thread); vlc_join(sys->thread, 0); sys->thread = 0; } delete sys; sys = sd->p_sys = 0; } <|endoftext|>
<commit_before>// ascii plain text // Licence: Lesser GNU Public License 2.1 (LGPL) // $Id$ #define BUILDING_XYLIB #include "text.h" #include <cerrno> #include <cstdlib> #include "util.h" using namespace std; using namespace xylib::util; namespace xylib { const FormatInfo TextDataSet::fmt_info( "text", "ascii text", "", // "txt dat asc", false, // whether binary false, // whether has multi-blocks &TextDataSet::ctor, &TextDataSet::check ); bool TextDataSet::check(istream & /*f*/) { return true; } namespace { // the title-line is either a name of block or contains names of columns // we assume that it's the latter if the number of words is the same // as number of columns void use_title_line(string const& line, vector<VecColumn*> &cols, Block* blk) { const char* delim = " \t"; vector<string> words; std::string::size_type pos = 0; while (pos != std::string::npos) { std::string::size_type start_pos = line.find_first_not_of(delim, pos); pos = line.find_first_of(delim, start_pos); words.push_back(std::string(line, start_pos, pos-start_pos)); } if (words.size() == cols.size()) { for (size_t i = 0; i < words.size(); ++i) cols[i]->set_name(words[i]); } else blk->set_name(line); } } // anonymous namespace void TextDataSet::load_data(std::istream &f) { vector<VecColumn*> cols; vector<double> row; // temporary storage for values from one line string title_line; string s; bool strict = has_option("strict"); bool first_line_header = has_option("first-line-header"); // header is in last comment line - the line before the first data line bool last_line_header = has_option("last-line-header"); if (first_line_header) { title_line = str_trim(read_line(f)); if (!title_line.empty() && title_line[0] == '#') title_line = title_line.substr(1); } // read lines until the first data line is read and columns are created string last_line; while (getline(f, s)) { // Basic support for LAMMPS log file. // There is a chance that output from thermo command will be read // properly, but because the LAMMPS log file doesn't have // a well-defined syntax, it can not be guaranteed. // All data blocks (numeric lines after `run' command) should have // the same columns (do not use thermo_style/thermo_modify between // runs). if (!strict && str_startwith(s, "LAMMPS (")) { last_line_header = true; continue; } const char *p = read_numbers(s, row); // We skip lines with no data. // If there is only one number in first line, skip it if there // is a text after the number. if (row.size() > 1 || (row.size() == 1 && (strict || *p == '\0' || *p == '#'))) { // columns initialization for (size_t i = 0; i != row.size(); ++i) { cols.push_back(new VecColumn); cols[i]->add_val(row[i]); } break; } if (last_line_header) { string t = str_trim(s); if (!t.empty()) last_line = (t[0] != '#' ? t : t.substr(1)); } } // read all the next data lines (the first data line was read above) while (getline(f, s)) { read_numbers(s, row); // We silently skip lines with no data. if (row.empty()) continue; if (row.size() < cols.size()) { // Some non-data lines may start with numbers. The example is // LAMMPS log file. The exceptions below are made to allow plotting // such a file. In strict mode, no exceptions are made. if (!strict) { // if it's the last line, we ignore the line if (f.eof()) break; // line with only one number is probably not a data line if (row.size() == 1) continue; // if it's the single line with smaller length, we ignore it vector<double> row2; getline(f, s); read_numbers(s, row2); if (row2.size() <= 1) continue; if (row2.size() < cols.size()) { // add the previous row for (size_t i = 0; i != row.size(); ++i) cols[i]->add_val(row[i]); // number of columns will be shrinked to the size of the // last row. If the previous row was shorter, shrink // the last row. if (row.size() < row2.size()) row2.resize(row.size()); } // if we are here, row2 needs to be stored row = row2; } // decrease the number of columns to the new minimum of numbers // in line for (size_t i = row.size(); i != cols.size(); ++i) delete cols[i]; cols.resize(row.size()); } else if (row.size() > cols.size()) { // Generally, we ignore extra columns. But if this is the second // data line, we ignore the first line instead. // Rationale: some data files have one or two numbers in the first // line, that can mean number of points or number of colums, and // the real data starts from the next line. if (cols[0]->get_point_count() == 1) { purge_all_elements(cols); for (size_t i = 0; i != row.size(); ++i) cols.push_back(new VecColumn); } } for (size_t i = 0; i != cols.size(); ++i) cols[i]->add_val(row[i]); } format_assert(this, cols.size() >= 1 && cols[0]->get_point_count() >= 2, "data not found in file."); Block* blk = new Block; for (unsigned i = 0; i < cols.size(); ++i) blk->add_column(cols[i]); if (!title_line.empty()) use_title_line(title_line, cols, blk); if (!last_line.empty()) use_title_line(last_line, cols, blk); add_block(blk); } } // end of namespace xylib <commit_msg>removed unused header<commit_after>// ascii plain text // Licence: Lesser GNU Public License 2.1 (LGPL) // $Id$ #define BUILDING_XYLIB #include "text.h" #include <cstdlib> #include "util.h" using namespace std; using namespace xylib::util; namespace xylib { const FormatInfo TextDataSet::fmt_info( "text", "ascii text", "", // "txt dat asc", false, // whether binary false, // whether has multi-blocks &TextDataSet::ctor, &TextDataSet::check ); bool TextDataSet::check(istream & /*f*/) { return true; } namespace { // the title-line is either a name of block or contains names of columns // we assume that it's the latter if the number of words is the same // as number of columns void use_title_line(string const& line, vector<VecColumn*> &cols, Block* blk) { const char* delim = " \t"; vector<string> words; std::string::size_type pos = 0; while (pos != std::string::npos) { std::string::size_type start_pos = line.find_first_not_of(delim, pos); pos = line.find_first_of(delim, start_pos); words.push_back(std::string(line, start_pos, pos-start_pos)); } if (words.size() == cols.size()) { for (size_t i = 0; i < words.size(); ++i) cols[i]->set_name(words[i]); } else blk->set_name(line); } } // anonymous namespace void TextDataSet::load_data(std::istream &f) { vector<VecColumn*> cols; vector<double> row; // temporary storage for values from one line string title_line; string s; bool strict = has_option("strict"); bool first_line_header = has_option("first-line-header"); // header is in last comment line - the line before the first data line bool last_line_header = has_option("last-line-header"); if (first_line_header) { title_line = str_trim(read_line(f)); if (!title_line.empty() && title_line[0] == '#') title_line = title_line.substr(1); } // read lines until the first data line is read and columns are created string last_line; while (getline(f, s)) { // Basic support for LAMMPS log file. // There is a chance that output from thermo command will be read // properly, but because the LAMMPS log file doesn't have // a well-defined syntax, it can not be guaranteed. // All data blocks (numeric lines after `run' command) should have // the same columns (do not use thermo_style/thermo_modify between // runs). if (!strict && str_startwith(s, "LAMMPS (")) { last_line_header = true; continue; } const char *p = read_numbers(s, row); // We skip lines with no data. // If there is only one number in first line, skip it if there // is a text after the number. if (row.size() > 1 || (row.size() == 1 && (strict || *p == '\0' || *p == '#'))) { // columns initialization for (size_t i = 0; i != row.size(); ++i) { cols.push_back(new VecColumn); cols[i]->add_val(row[i]); } break; } if (last_line_header) { string t = str_trim(s); if (!t.empty()) last_line = (t[0] != '#' ? t : t.substr(1)); } } // read all the next data lines (the first data line was read above) while (getline(f, s)) { read_numbers(s, row); // We silently skip lines with no data. if (row.empty()) continue; if (row.size() < cols.size()) { // Some non-data lines may start with numbers. The example is // LAMMPS log file. The exceptions below are made to allow plotting // such a file. In strict mode, no exceptions are made. if (!strict) { // if it's the last line, we ignore the line if (f.eof()) break; // line with only one number is probably not a data line if (row.size() == 1) continue; // if it's the single line with smaller length, we ignore it vector<double> row2; getline(f, s); read_numbers(s, row2); if (row2.size() <= 1) continue; if (row2.size() < cols.size()) { // add the previous row for (size_t i = 0; i != row.size(); ++i) cols[i]->add_val(row[i]); // number of columns will be shrinked to the size of the // last row. If the previous row was shorter, shrink // the last row. if (row.size() < row2.size()) row2.resize(row.size()); } // if we are here, row2 needs to be stored row = row2; } // decrease the number of columns to the new minimum of numbers // in line for (size_t i = row.size(); i != cols.size(); ++i) delete cols[i]; cols.resize(row.size()); } else if (row.size() > cols.size()) { // Generally, we ignore extra columns. But if this is the second // data line, we ignore the first line instead. // Rationale: some data files have one or two numbers in the first // line, that can mean number of points or number of colums, and // the real data starts from the next line. if (cols[0]->get_point_count() == 1) { purge_all_elements(cols); for (size_t i = 0; i != row.size(); ++i) cols.push_back(new VecColumn); } } for (size_t i = 0; i != cols.size(); ++i) cols[i]->add_val(row[i]); } format_assert(this, cols.size() >= 1 && cols[0]->get_point_count() >= 2, "data not found in file."); Block* blk = new Block; for (unsigned i = 0; i < cols.size(); ++i) blk->add_column(cols[i]); if (!title_line.empty()) use_title_line(title_line, cols, blk); if (!last_line.empty()) use_title_line(last_line, cols, blk); add_block(blk); } } // end of namespace xylib <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #ifndef DISPATCHER_HH #define DISPATCHER_HH #include <stdexcept> #include <queue> #include "common.hh" #include "locks.hh" class Dispatcher; enum task_state { task_dead, task_running, task_sleeping }; enum dispatcher_state { dispatcher_running, dispatcher_stopping, dispatcher_stopped }; class Task; typedef shared_ptr<Task> TaskId; class DispatcherCallback { public: virtual ~DispatcherCallback() {} virtual bool callback(Dispatcher &d, TaskId t) = 0; }; class CompareTasks; class Task { friend class CompareTasks; public: ~Task() { } private: Task(shared_ptr<DispatcherCallback> cb, int p=0, double sleeptime=0) : callback(cb), priority(p) { if (sleeptime > 0) { snooze(sleeptime); } else { state = task_running; } } Task(const Task &task) { priority = task.priority; state = task_running; callback = task.callback; } void snooze(const double secs) { LockHolder lh(mutex); gettimeofday(&waketime, NULL); advance_tv(waketime, secs); state = task_sleeping; } bool run(Dispatcher &d, TaskId t) { return callback->callback(d, t); } void cancel() { LockHolder lh(mutex); state = task_dead; } friend class Dispatcher; std::string name; struct timeval waketime; shared_ptr<DispatcherCallback> callback; int priority; enum task_state state; Mutex mutex; }; class CompareTasks { public: bool operator()(TaskId &t1, TaskId &t2) { getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Comparing two tasks\n"); if (t1->state == task_running) { if (t2->state == task_running) { return t1->priority > t2->priority; } else if (t2->state == task_sleeping) { return false; } } else if (t1->state == task_sleeping && t2->state == task_sleeping) { return less_tv(t2->waketime, t1->waketime); } return true; } }; class Dispatcher { public: Dispatcher() : state(dispatcher_running) { } ~Dispatcher() { stop(); } TaskId schedule(shared_ptr<DispatcherCallback> callback, int priority=0, double sleeptime=0) { getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Scheduling a new task\n"); LockHolder lh(mutex); TaskId task(new Task(callback, priority, sleeptime)); queue.push(task); mutex.notify(); return TaskId(task); } TaskId wake(TaskId task) { cancel(task); TaskId oldTask(task); TaskId newTask(new Task(*oldTask)); queue.push(newTask); mutex.notify(); return TaskId(newTask); } void start(); void run() { getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Dispatcher starting\n"); while (state == dispatcher_running) { LockHolder lh(mutex); if (queue.empty()) { // Wait forever mutex.wait(); } else { TaskId task = queue.top(); LockHolder tlh(task->mutex); switch (task->state) { case task_sleeping: { struct timeval tv; gettimeofday(&tv, NULL); if (less_tv(tv, task->waketime)) { tlh.unlock(); mutex.wait(task->waketime); } else { task->state = task_running; } } break; case task_running: queue.pop(); lh.unlock(); tlh.unlock(); try { if(task->run(*this, TaskId(task))) { reschedule(task); } } catch (std::exception& e) { std::cerr << "exception caught in task " << task->name << ": " << e.what() << std::endl; } catch(...) { std::cerr << "Caught a fatal exception in task" << task->name <<std::endl; } break; case task_dead: queue.pop(); break; default: throw std::runtime_error("Unexpected state for task"); } } } state = dispatcher_stopped; mutex.notify(); getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Dispatcher exited\n"); } void stop() { LockHolder lh(mutex); if (state == dispatcher_stopped) { return; } getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Stopping dispatcher\n"); state = dispatcher_stopping; mutex.notify(); lh.unlock(); pthread_join(thread, NULL); getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Dispatcher stopped\n"); } void snooze(TaskId t, double sleeptime) { t->snooze(sleeptime); } void cancel(TaskId t) { t->cancel(); } private: void reschedule(TaskId task) { // If the task is already in the queue it'll get run twice LockHolder lh(mutex); queue.push(task); } pthread_t thread; SyncObject mutex; std::priority_queue<TaskId, std::deque<TaskId >, CompareTasks> queue; enum dispatcher_state state; }; #endif <commit_msg>Make the dispatcher less chatty<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #ifndef DISPATCHER_HH #define DISPATCHER_HH #include <stdexcept> #include <queue> #include "common.hh" #include "locks.hh" class Dispatcher; enum task_state { task_dead, task_running, task_sleeping }; enum dispatcher_state { dispatcher_running, dispatcher_stopping, dispatcher_stopped }; class Task; typedef shared_ptr<Task> TaskId; class DispatcherCallback { public: virtual ~DispatcherCallback() {} virtual bool callback(Dispatcher &d, TaskId t) = 0; }; class CompareTasks; class Task { friend class CompareTasks; public: ~Task() { } private: Task(shared_ptr<DispatcherCallback> cb, int p=0, double sleeptime=0) : callback(cb), priority(p) { if (sleeptime > 0) { snooze(sleeptime); } else { state = task_running; } } Task(const Task &task) { priority = task.priority; state = task_running; callback = task.callback; } void snooze(const double secs) { LockHolder lh(mutex); gettimeofday(&waketime, NULL); advance_tv(waketime, secs); state = task_sleeping; } bool run(Dispatcher &d, TaskId t) { return callback->callback(d, t); } void cancel() { LockHolder lh(mutex); state = task_dead; } friend class Dispatcher; std::string name; struct timeval waketime; shared_ptr<DispatcherCallback> callback; int priority; enum task_state state; Mutex mutex; }; class CompareTasks { public: bool operator()(TaskId t1, TaskId t2) { if (t1->state == task_running) { if (t2->state == task_running) { return t1->priority > t2->priority; } else if (t2->state == task_sleeping) { return false; } } else if (t1->state == task_sleeping && t2->state == task_sleeping) { return less_tv(t2->waketime, t1->waketime); } return true; } }; class Dispatcher { public: Dispatcher() : state(dispatcher_running) { } ~Dispatcher() { stop(); } TaskId schedule(shared_ptr<DispatcherCallback> callback, int priority=0, double sleeptime=0) { getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Scheduling a new task\n"); LockHolder lh(mutex); TaskId task(new Task(callback, priority, sleeptime)); queue.push(task); mutex.notify(); return TaskId(task); } TaskId wake(TaskId task) { cancel(task); TaskId oldTask(task); TaskId newTask(new Task(*oldTask)); queue.push(newTask); mutex.notify(); return TaskId(newTask); } void start(); void run() { getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Dispatcher starting\n"); while (state == dispatcher_running) { LockHolder lh(mutex); if (queue.empty()) { // Wait forever mutex.wait(); } else { TaskId task = queue.top(); LockHolder tlh(task->mutex); switch (task->state) { case task_sleeping: { struct timeval tv; gettimeofday(&tv, NULL); if (less_tv(tv, task->waketime)) { tlh.unlock(); mutex.wait(task->waketime); } else { task->state = task_running; } } break; case task_running: queue.pop(); lh.unlock(); tlh.unlock(); try { if(task->run(*this, TaskId(task))) { reschedule(task); } } catch (std::exception& e) { std::cerr << "exception caught in task " << task->name << ": " << e.what() << std::endl; } catch(...) { std::cerr << "Caught a fatal exception in task" << task->name <<std::endl; } break; case task_dead: queue.pop(); break; default: throw std::runtime_error("Unexpected state for task"); } } } state = dispatcher_stopped; mutex.notify(); getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Dispatcher exited\n"); } void stop() { LockHolder lh(mutex); if (state == dispatcher_stopped) { return; } getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Stopping dispatcher\n"); state = dispatcher_stopping; mutex.notify(); lh.unlock(); pthread_join(thread, NULL); getLogger()->log(EXTENSION_LOG_DEBUG, NULL, "Dispatcher stopped\n"); } void snooze(TaskId t, double sleeptime) { t->snooze(sleeptime); } void cancel(TaskId t) { t->cancel(); } private: void reschedule(TaskId task) { // If the task is already in the queue it'll get run twice LockHolder lh(mutex); queue.push(task); } pthread_t thread; SyncObject mutex; std::priority_queue<TaskId, std::deque<TaskId >, CompareTasks> queue; enum dispatcher_state state; }; #endif <|endoftext|>
<commit_before>#include <errno.h> #include <QMessageBox> #include <QCloseEvent> #include "mainwindow.h" #include "ui_mainwindow.h" const char MainWindow::pol_pm[] = "<span style='font-weight:600;'><span style='color:#ff0000;'>+</span> <span style='color:#0000ff;'>-</span></span>"; const char MainWindow::pol_mp[] = "<span style='font-weight:600;'><span style='color:#0000ff;'>-</span> <span style='color:#ff0000;'>+</span></span>"; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), configUI() { ui->setupUi(this); QObject::connect(&configUI, SIGNAL(accepted()), this, SLOT(show())); currentTimer.setInterval(500); currentTimer.setSingleShot(false); QObject::connect(&currentTimer, SIGNAL(timeout()), this, SLOT(on_currentTimer_timeout())); } MainWindow::~MainWindow() { delete ui; } void MainWindow::closeEvent(QCloseEvent *event) { if (configUI.isHidden() && configUI.result() == QDialog::Accepted) { event->ignore(); hide(); configUI.show(); return; } QMainWindow::closeEvent(event); } bool MainWindow::openDevs() { QString err_text, err_title; QString s; int err; s = settings.value(ConfigUI::cfg_powerSupplyPort).toString(); err = sdp_open(&sdp, s.toLocal8Bit().constData(), SDP_DEV_ADDR_MIN); if (err < 0) goto sdp_err0; /* Set value limit in current input spin box. */ sdp_va_t limits; err = sdp_get_va_maximums(&sdp, &limits); if (err < 0) goto sdp_err; ui->coilCurrDoubleSpinBox->setMaximum(limits.curr); /* Set current to actual value, avoiding anny jumps. */ sdp_va_data_t va_data; err = sdp_get_va_data(&sdp, &va_data); if (err < 0) goto sdp_err; err = sdp_set_curr(&sdp, va_data.curr); if (err < 0) goto sdp_err; /* Set voltage to maximum, Hall is current driven. */ err = sdp_set_volt_limit(&sdp, va_data.volt); if (err < 0) goto sdp_err; err = sdp_set_volt(&sdp, va_data.volt); if (err < 0) goto sdp_err; sdp_lcd_info_t lcd_info; if (err < 0) goto sdp_err; ui->coilPowerCheckBox->setChecked(lcd_info.output); s = settings.value(ConfigUI::cfg_polSwitchPort).toString(); if (!powerSwitch.open(s.toLocal8Bit().constData())) { err = errno; goto mag_pwr_switch_err; } bool cross; cross = powerSwitch.polarity() == PolaritySwitch::cross; ui->coilPolCrossCheckBox->setChecked(cross); /* TODO ... */ currentTimer.start(); return true; // powerSwitch.close(); mag_pwr_switch_err: if (err_title.isEmpty()) { err_title = QString::fromLocal8Bit( "Failed to open power supply switch"); err_text = QString::fromLocal8Bit(strerror(err)); } sdp_err: sdp_close(&sdp); sdp_err0: if (err_title.isEmpty()) { err_title = QString::fromLocal8Bit( "Failed to open Manson SDP power supply"); err_text = QString::fromLocal8Bit(sdp_strerror(err)); } err_text = QString("%1:\n\n%2").arg(err_title).arg(err_text); QMessageBox::critical(this, err_title, err_text); statusBar()->showMessage(err_title); return false; } void MainWindow::closeDevs() { sdp_close(&sdp); } void MainWindow::on_coilPowerCheckBox_toggled(bool checked) { if (checked) { // FIXME // sdp_set_curr(&sdp, 0); // sdp_set_output(&sdp, true); } currentTimer.start(); } void MainWindow::on_measurePushButton_clicked() { /* TODO */ } void MainWindow::on_currentTimer_timeout() { /* TODO */ } void MainWindow::updateCurrent() { double current; current = ui->coilCurrDoubleSpinBox->value(); if (ui->coilPolCrossCheckBox->isChecked()) current = -current; sdp_set_curr(&sdp, current); /* TODO */ } void MainWindow::on_coilPolCrossCheckBox_toggled(bool checked) { /*if (checked) { powerSwitch.setPolarity(PolaritySwitch::cross); ui->polarityLabel->setText(pol_mp); } else { powerSwitch.setPolarity(PolaritySwitch::direct); ui->polarityLabel->setText(pol_pm); }*/ currentTimer.start(); } void MainWindow::on_coilCurrDoubleSpinBox_valueChanged(double ) { currentTimer.start(); } void MainWindow::show() { if (!openDevs()) { configUI.show(); return; } QWidget::show(); } void MainWindow::startApp() { configUI.show(); } void MainWindow::on_samplePowerCheckBox_toggled(bool ) { } void MainWindow::on_sampleCurrDoubleSpinBox_valueChanged(double ) { } void MainWindow::on_samplePolCrossCheckBox_toggled(bool ) { } <commit_msg>Function reorder by alphabet<commit_after>#include <errno.h> #include <QMessageBox> #include <QCloseEvent> #include "mainwindow.h" #include "ui_mainwindow.h" const char MainWindow::pol_pm[] = "<span style='font-weight:600;'><span style='color:#ff0000;'>+</span> <span style='color:#0000ff;'>-</span></span>"; const char MainWindow::pol_mp[] = "<span style='font-weight:600;'><span style='color:#0000ff;'>-</span> <span style='color:#ff0000;'>+</span></span>"; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), configUI() { ui->setupUi(this); QObject::connect(&configUI, SIGNAL(accepted()), this, SLOT(show())); currentTimer.setInterval(500); currentTimer.setSingleShot(false); QObject::connect(&currentTimer, SIGNAL(timeout()), this, SLOT(on_currentTimer_timeout())); } MainWindow::~MainWindow() { delete ui; } void MainWindow::closeDevs() { currentTimer.stop(); powerSwitch.close(); sdp_close(&sdp); } void MainWindow::closeEvent(QCloseEvent *event) { if (configUI.isHidden() && configUI.result() == QDialog::Accepted) { closeDevs(); event->ignore(); hide(); configUI.show(); return; } QMainWindow::closeEvent(event); } void MainWindow::on_coilCurrDoubleSpinBox_valueChanged(double ) { //currentTimer.start(); } void MainWindow::on_coilPolCrossCheckBox_toggled(bool) { /*if (checked) { powerSwitch.setPolarity(PolaritySwitch::cross); ui->polarityLabel->setText(pol_mp); } else { powerSwitch.setPolarity(PolaritySwitch::direct); ui->polarityLabel->setText(pol_pm); }*/ //currentTimer.start(); } void MainWindow::on_coilPowerCheckBox_toggled(bool checked) { if (checked) { // FIXME // sdp_set_curr(&sdp, 0); // sdp_set_output(&sdp, true); } //currentTimer.start(); } void MainWindow::on_currentTimer_timeout() { sdp_va_data_t va_data; if (sdp_get_va_data(&sdp, &va_data) < 0) { // TODO close(); return; } ui->coilCurrMeasDoubleSpinBox->setValue(va_data.curr); /* TODO */ } void MainWindow::on_measurePushButton_clicked() { /* TODO */ } void MainWindow::on_sampleCurrDoubleSpinBox_valueChanged(double ) { } void MainWindow::on_samplePolCrossCheckBox_toggled(bool ) { } void MainWindow::on_samplePowerCheckBox_toggled(bool ) { } bool MainWindow::openDevs() { QString err_text, err_title; QString s; int err; s = settings.value(ConfigUI::cfg_powerSupplyPort).toString(); err = sdp_open(&sdp, s.toLocal8Bit().constData(), SDP_DEV_ADDR_MIN); if (err < 0) goto sdp_err0; /* Set value limit in current input spin box. */ sdp_va_t limits; err = sdp_get_va_maximums(&sdp, &limits); if (err < 0) goto sdp_err; ui->coilCurrDoubleSpinBox->setMaximum(limits.curr); /* Set current to actual value, avoiding anny jumps. */ sdp_va_data_t va_data; err = sdp_get_va_data(&sdp, &va_data); if (err < 0) goto sdp_err; err = sdp_set_curr(&sdp, va_data.curr); if (err < 0) goto sdp_err; /* Set voltage to maximum, Hall is current driven. */ err = sdp_set_volt_limit(&sdp, va_data.volt); if (err < 0) goto sdp_err; err = sdp_set_volt(&sdp, va_data.volt); if (err < 0) goto sdp_err; sdp_lcd_info_t lcd_info; if (err < 0) goto sdp_err; ui->coilPowerCheckBox->setChecked(lcd_info.output); s = settings.value(ConfigUI::cfg_polSwitchPort).toString(); if (!powerSwitch.open(s.toLocal8Bit().constData())) { err = errno; goto mag_pwr_switch_err; } bool cross; cross = powerSwitch.polarity() == PolaritySwitch::cross; ui->coilPolCrossCheckBox->setChecked(cross); /* TODO ... */ currentTimer.start(); return true; // powerSwitch.close(); mag_pwr_switch_err: if (err_title.isEmpty()) { err_title = QString::fromLocal8Bit( "Failed to open power supply switch"); err_text = QString::fromLocal8Bit(strerror(err)); } sdp_err: sdp_close(&sdp); sdp_err0: if (err_title.isEmpty()) { err_title = QString::fromLocal8Bit( "Failed to open Manson SDP power supply"); err_text = QString::fromLocal8Bit(sdp_strerror(err)); } err_text = QString("%1:\n\n%2").arg(err_title).arg(err_text); QMessageBox::critical(this, err_title, err_text); statusBar()->showMessage(err_title); return false; } void MainWindow::show() { if (!openDevs()) { configUI.show(); return; } QWidget::show(); } void MainWindow::startApp() { configUI.show(); } void MainWindow::updateCurrent() { double current; current = ui->coilCurrDoubleSpinBox->value(); if (ui->coilPolCrossCheckBox->isChecked()) current = -current; sdp_set_curr(&sdp, current); /* TODO */ } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: geometrycontrolmodel.cxx,v $ * * $Revision: 1.1 $ * * last change: $Author: mt $ $Date: 2001-01-24 14:55:12 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _TOOLKIT_HELPERS_GEOMETRYCONTROLMODEL_HXX_ #include "toolkit/controls/geometrycontrolmodel.hxx" #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_ #include <com/sun/star/beans/PropertyAttribute.hpp> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _COMPHELPER_PROPERTY_HXX_ #include <comphelper/property.hxx> #endif #define GCM_PROPERTY_ID_POS_X 1 #define GCM_PROPERTY_ID_POS_Y 2 #define GCM_PROPERTY_ID_WIDTH 3 #define GCM_PROPERTY_ID_HEIGHT 4 #define GCM_PROPERTY_POS_X ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("PositionX")) #define GCM_PROPERTY_POS_Y ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("PositionY")) #define GCM_PROPERTY_WIDTH ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Width")) #define GCM_PROPERTY_HEIGHT ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Height")) #define DEFAULT_ATTRIBS() PropertyAttribute::BOUND | PropertyAttribute::TRANSIENT //........................................................................ // namespace toolkit // { //........................................................................ using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; using namespace ::comphelper; //==================================================================== //= OGeometryControlModel_Base //==================================================================== //-------------------------------------------------------------------- OGeometryControlModel_Base::OGeometryControlModel_Base(XAggregation* _pAggregateInstance) :OPropertySetAggregationHelper(m_aBHelper) ,OPropertyContainer(m_aBHelper) ,m_nPosX(0) ,m_nPosY(0) ,m_nWidth(0) ,m_nHeight(0) { OSL_ENSURE(NULL != _pAggregateInstance, "OGeometryControlModel_Base::OGeometryControlModel_Base: invalid aggregate!"); // create our aggregate increment(m_refCount); { m_xAggregate = _pAggregateInstance; setAggregation(m_xAggregate); m_xAggregate->setDelegator(static_cast< XWeak* >(this)); } decrement(m_refCount); // register our members for the property handling of the OPropertyContainer registerProperty(GCM_PROPERTY_POS_X, GCM_PROPERTY_ID_POS_X, DEFAULT_ATTRIBS(), &m_nPosX, ::getCppuType(&m_nPosX)); registerProperty(GCM_PROPERTY_POS_Y, GCM_PROPERTY_ID_POS_Y, DEFAULT_ATTRIBS(), &m_nPosY, ::getCppuType(&m_nPosY)); registerProperty(GCM_PROPERTY_WIDTH, GCM_PROPERTY_ID_WIDTH, DEFAULT_ATTRIBS(), &m_nWidth, ::getCppuType(&m_nWidth)); registerProperty(GCM_PROPERTY_HEIGHT, GCM_PROPERTY_ID_HEIGHT, DEFAULT_ATTRIBS(), &m_nHeight, ::getCppuType(&m_nHeight)); } //-------------------------------------------------------------------- Any SAL_CALL OGeometryControlModel_Base::queryAggregation( const Type& _rType ) throw(RuntimeException) { Any aReturn = OWeakAggObject::queryAggregation(_rType); // the basic interfaces (XInterface, XAggregation etc) if (!aReturn.hasValue()) aReturn = OPropertySetAggregationHelper::queryInterface(_rType); // the property set related interfaces if (!aReturn.hasValue() && m_xAggregate.is()) aReturn = m_xAggregate->queryAggregation(_rType); // the interfaces our aggregate can provide return aReturn; } //-------------------------------------------------------------------- Any SAL_CALL OGeometryControlModel_Base::queryInterface( const Type& _rType ) throw(RuntimeException) { return OWeakAggObject::queryInterface(_rType); } //-------------------------------------------------------------------- void SAL_CALL OGeometryControlModel_Base::acquire( ) throw() { OWeakAggObject::acquire(); } //-------------------------------------------------------------------- void SAL_CALL OGeometryControlModel_Base::release( ) throw() { OWeakAggObject::release(); } //-------------------------------------------------------------------- OGeometryControlModel_Base::~OGeometryControlModel_Base() { // release the aggregate (_before_ clearing m_xAggregate) if (m_xAggregate.is()) m_xAggregate->setDelegator(NULL); setAggregation(NULL); } //-------------------------------------------------------------------- sal_Bool SAL_CALL OGeometryControlModel_Base::convertFastPropertyValue(Any& _rConvertedValue, Any& _rOldValue, sal_Int32 _nHandle, const Any& _rValue) throw (IllegalArgumentException) { return OPropertyContainer::convertFastPropertyValue(_rConvertedValue, _rOldValue, _nHandle, _rValue); } //-------------------------------------------------------------------- void SAL_CALL OGeometryControlModel_Base::setFastPropertyValue_NoBroadcast(sal_Int32 _nHandle, const Any& _rValue) throw (Exception) { OPropertyContainer::setFastPropertyValue_NoBroadcast(_nHandle, _rValue); } //-------------------------------------------------------------------- void SAL_CALL OGeometryControlModel_Base::getFastPropertyValue(Any& _rValue, sal_Int32 _nHandle) const { OPropertyArrayAggregationHelper& rPH = static_cast<OPropertyArrayAggregationHelper&>(const_cast<OGeometryControlModel_Base*>(this)->getInfoHelper()); ::rtl::OUString sPropName; sal_Int32 nOriginalHandle = -1; if (rPH.fillAggregatePropertyInfoByHandle(&sPropName, &nOriginalHandle, _nHandle)) OPropertySetAggregationHelper::getFastPropertyValue(_rValue, _nHandle); else OPropertyContainer::getFastPropertyValue(_rValue, _nHandle); } //-------------------------------------------------------------------- Reference< XPropertySetInfo> SAL_CALL OGeometryControlModel_Base::getPropertySetInfo() throw(RuntimeException) { return OPropertySetAggregationHelper::createPropertySetInfo(getInfoHelper()); } //........................................................................ // } // namespace toolkit //........................................................................ /************************************************************************* * history: * $Log: not supported by cvs2svn $ * * Revision 1.0 17.01.01 11:35:20 fs ************************************************************************/ <commit_msg>Support for XScriptEventsSupplier added<commit_after>/************************************************************************* * * $RCSfile: geometrycontrolmodel.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: ab $ $Date: 2001-02-21 17:31:20 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _TOOLKIT_HELPERS_GEOMETRYCONTROLMODEL_HXX_ #include "toolkit/controls/geometrycontrolmodel.hxx" #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_ #include <com/sun/star/beans/PropertyAttribute.hpp> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _COMPHELPER_PROPERTY_HXX_ #include <comphelper/property.hxx> #endif #include "toolkit/controls/eventcontainer.hxx" #define GCM_PROPERTY_ID_POS_X 1 #define GCM_PROPERTY_ID_POS_Y 2 #define GCM_PROPERTY_ID_WIDTH 3 #define GCM_PROPERTY_ID_HEIGHT 4 #define GCM_PROPERTY_POS_X ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("PositionX")) #define GCM_PROPERTY_POS_Y ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("PositionY")) #define GCM_PROPERTY_WIDTH ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Width")) #define GCM_PROPERTY_HEIGHT ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Height")) #define DEFAULT_ATTRIBS() PropertyAttribute::BOUND | PropertyAttribute::TRANSIENT //........................................................................ // namespace toolkit // { //........................................................................ using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::container; using namespace ::comphelper; //==================================================================== //= OGeometryControlModel_Base //==================================================================== //-------------------------------------------------------------------- OGeometryControlModel_Base::OGeometryControlModel_Base(XAggregation* _pAggregateInstance) :OPropertySetAggregationHelper(m_aBHelper) ,OPropertyContainer(m_aBHelper) ,m_nPosX(0) ,m_nPosY(0) ,m_nWidth(0) ,m_nHeight(0) { OSL_ENSURE(NULL != _pAggregateInstance, "OGeometryControlModel_Base::OGeometryControlModel_Base: invalid aggregate!"); // create our aggregate increment(m_refCount); { m_xAggregate = _pAggregateInstance; setAggregation(m_xAggregate); m_xAggregate->setDelegator(static_cast< XWeak* >(this)); } decrement(m_refCount); // register our members for the property handling of the OPropertyContainer registerProperty(GCM_PROPERTY_POS_X, GCM_PROPERTY_ID_POS_X, DEFAULT_ATTRIBS(), &m_nPosX, ::getCppuType(&m_nPosX)); registerProperty(GCM_PROPERTY_POS_Y, GCM_PROPERTY_ID_POS_Y, DEFAULT_ATTRIBS(), &m_nPosY, ::getCppuType(&m_nPosY)); registerProperty(GCM_PROPERTY_WIDTH, GCM_PROPERTY_ID_WIDTH, DEFAULT_ATTRIBS(), &m_nWidth, ::getCppuType(&m_nWidth)); registerProperty(GCM_PROPERTY_HEIGHT, GCM_PROPERTY_ID_HEIGHT, DEFAULT_ATTRIBS(), &m_nHeight, ::getCppuType(&m_nHeight)); } //-------------------------------------------------------------------- Any SAL_CALL OGeometryControlModel_Base::queryAggregation( const Type& _rType ) throw(RuntimeException) { Any aReturn = OWeakAggObject::queryAggregation(_rType); // the basic interfaces (XInterface, XAggregation etc) if (!aReturn.hasValue()) aReturn = OPropertySetAggregationHelper::queryInterface(_rType); // the property set related interfaces if (!aReturn.hasValue() && m_xAggregate.is()) aReturn = m_xAggregate->queryAggregation(_rType); // the interfaces our aggregate can provide if (!aReturn.hasValue() && m_xAggregate.is()) { aReturn = ::cppu::queryInterface( _rType, static_cast< ::com::sun::star::script::XScriptEventsSupplier* >( this ) ); } return aReturn; } //-------------------------------------------------------------------- Any SAL_CALL OGeometryControlModel_Base::queryInterface( const Type& _rType ) throw(RuntimeException) { return OWeakAggObject::queryInterface(_rType); } //-------------------------------------------------------------------- void SAL_CALL OGeometryControlModel_Base::acquire( ) throw() { OWeakAggObject::acquire(); } //-------------------------------------------------------------------- void SAL_CALL OGeometryControlModel_Base::release( ) throw() { OWeakAggObject::release(); } //-------------------------------------------------------------------- OGeometryControlModel_Base::~OGeometryControlModel_Base() { // release the aggregate (_before_ clearing m_xAggregate) if (m_xAggregate.is()) m_xAggregate->setDelegator(NULL); setAggregation(NULL); } //-------------------------------------------------------------------- sal_Bool SAL_CALL OGeometryControlModel_Base::convertFastPropertyValue(Any& _rConvertedValue, Any& _rOldValue, sal_Int32 _nHandle, const Any& _rValue) throw (IllegalArgumentException) { return OPropertyContainer::convertFastPropertyValue(_rConvertedValue, _rOldValue, _nHandle, _rValue); } //-------------------------------------------------------------------- void SAL_CALL OGeometryControlModel_Base::setFastPropertyValue_NoBroadcast(sal_Int32 _nHandle, const Any& _rValue) throw (Exception) { OPropertyContainer::setFastPropertyValue_NoBroadcast(_nHandle, _rValue); } //-------------------------------------------------------------------- void SAL_CALL OGeometryControlModel_Base::getFastPropertyValue(Any& _rValue, sal_Int32 _nHandle) const { OPropertyArrayAggregationHelper& rPH = static_cast<OPropertyArrayAggregationHelper&>(const_cast<OGeometryControlModel_Base*>(this)->getInfoHelper()); ::rtl::OUString sPropName; sal_Int32 nOriginalHandle = -1; if (rPH.fillAggregatePropertyInfoByHandle(&sPropName, &nOriginalHandle, _nHandle)) OPropertySetAggregationHelper::getFastPropertyValue(_rValue, _nHandle); else OPropertyContainer::getFastPropertyValue(_rValue, _nHandle); } //-------------------------------------------------------------------- Reference< XPropertySetInfo> SAL_CALL OGeometryControlModel_Base::getPropertySetInfo() throw(RuntimeException) { return OPropertySetAggregationHelper::createPropertySetInfo(getInfoHelper()); } //-------------------------------------------------------------------- Reference< XNameContainer > SAL_CALL OGeometryControlModel_Base::getEvents() throw(RuntimeException) { if( !mxEventContainer.is() ) mxEventContainer = (XNameContainer*)new ScriptEventContainer(); return mxEventContainer; } //........................................................................ // } // namespace toolkit //........................................................................ /************************************************************************* * history: * $Log: not supported by cvs2svn $ * Revision 1.1 2001/01/24 14:55:12 mt * model for dialog controls (weith pos/size) * * * Revision 1.0 17.01.01 11:35:20 fs ************************************************************************/ <|endoftext|>
<commit_before>// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Development Kit" // For conditions of distribution and use, see copyright notice in Prerequisites.hpp #include <NDK/Systems/DebugSystem.hpp> #include <Nazara/Core/Primitive.hpp> #include <Nazara/Graphics/Model.hpp> #include <Nazara/Utility/IndexIterator.hpp> #include <Nazara/Utility/Mesh.hpp> #include <Nazara/Utility/StaticMesh.hpp> #include <NDK/Components/CollisionComponent3D.hpp> #include <NDK/Components/DebugComponent.hpp> #include <NDK/Components/GraphicsComponent.hpp> #include <NDK/Components/NodeComponent.hpp> namespace Ndk { namespace { class DebugRenderable : public Nz::InstancedRenderable { public: DebugRenderable(Ndk::Entity* owner, Nz::MaterialRef mat, Nz::IndexBufferRef indexBuffer, Nz::VertexBufferRef vertexBuffer) : m_entityOwner(owner), m_material(std::move(mat)), m_indexBuffer(std::move(indexBuffer)), m_vertexBuffer(std::move(vertexBuffer)) { ResetMaterials(1); m_meshData.indexBuffer = m_indexBuffer; m_meshData.primitiveMode = Nz::PrimitiveMode_LineList; m_meshData.vertexBuffer = m_vertexBuffer; } void UpdateBoundingVolume(InstanceData* instanceData) const override { } void MakeBoundingVolume() const override { m_boundingVolume.MakeNull(); } protected: Ndk::EntityHandle m_entityOwner; Nz::IndexBufferRef m_indexBuffer; Nz::MaterialRef m_material; Nz::MeshData m_meshData; Nz::VertexBufferRef m_vertexBuffer; }; class AABBDebugRenderable : public DebugRenderable { public: using DebugRenderable::DebugRenderable; void AddToRenderQueue(Nz::AbstractRenderQueue* renderQueue, const InstanceData& instanceData, const Nz::Recti& scissorRect) const override { NazaraAssert(m_entityOwner, "DebugRenderable has no owner"); const DebugComponent& entityDebug = m_entityOwner->GetComponent<DebugComponent>(); const GraphicsComponent& entityGfx = m_entityOwner->GetComponent<GraphicsComponent>(); Nz::Matrix4f transformMatrix = Nz::Matrix4f::Identity(); transformMatrix.SetScale(entityGfx.GetBoundingVolume().aabb.GetLengths()); transformMatrix.SetTranslation(entityGfx.GetBoundingVolume().aabb.GetCenter()); renderQueue->AddMesh(0, m_material, m_meshData, Nz::Boxf::Zero(), transformMatrix, scissorRect); } }; class OBBDebugRenderable : public DebugRenderable { public: using DebugRenderable::DebugRenderable; void AddToRenderQueue(Nz::AbstractRenderQueue* renderQueue, const InstanceData& instanceData, const Nz::Recti& scissorRect) const override { NazaraAssert(m_entityOwner, "DebugRenderable has no owner"); const DebugComponent& entityDebug = m_entityOwner->GetComponent<DebugComponent>(); const GraphicsComponent& entityGfx = m_entityOwner->GetComponent<GraphicsComponent>(); Nz::Matrix4f transformMatrix = instanceData.transformMatrix; transformMatrix.ApplyScale(entityGfx.GetBoundingVolume().obb.localBox.GetLengths()); renderQueue->AddMesh(0, m_material, m_meshData, Nz::Boxf::Zero(), transformMatrix, scissorRect); } }; } /*! * \ingroup NDK * \class Ndk::DebugSystem * \brief NDK class that represents the debug system * * \remark This system is enabled if the entity owns the trait: DebugComponent and GraphicsComponent */ /*! * \brief Constructs an DebugSystem object by default */ DebugSystem::DebugSystem() { Requires<DebugComponent, GraphicsComponent>(); SetUpdateOrder(1000); //< Update last } std::pair<Nz::IndexBufferRef, Nz::VertexBufferRef> DebugSystem::GetBoxMesh() { if (!m_boxMeshIndexBuffer) { std::array<Nz::UInt16, 24> indices = { { 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 } }; m_boxMeshIndexBuffer = Nz::IndexBuffer::New(false, indices.size(), Nz::DataStorage_Hardware, 0); m_boxMeshIndexBuffer->Fill(indices.data(), 0, indices.size()); } if (!m_boxMeshVertexBuffer) { Nz::Boxf box(-0.5f, -0.5f, -0.5f, 1.f, 1.f, 1.f); std::array<Nz::Vector3f, 8> positions = { { box.GetCorner(Nz::BoxCorner_FarLeftBottom), box.GetCorner(Nz::BoxCorner_NearLeftBottom), box.GetCorner(Nz::BoxCorner_NearRightBottom), box.GetCorner(Nz::BoxCorner_FarRightBottom), box.GetCorner(Nz::BoxCorner_FarLeftTop), box.GetCorner(Nz::BoxCorner_NearLeftTop), box.GetCorner(Nz::BoxCorner_NearRightTop), box.GetCorner(Nz::BoxCorner_FarRightTop) } }; m_boxMeshVertexBuffer = Nz::VertexBuffer::New(Nz::VertexDeclaration::Get(Nz::VertexLayout_XYZ), positions.size(), Nz::DataStorage_Hardware, 0); m_boxMeshVertexBuffer->Fill(positions.data(), 0, positions.size()); } return { m_boxMeshIndexBuffer, m_boxMeshVertexBuffer }; } void DebugSystem::OnEntityValidation(Entity* entity, bool /*justAdded*/) { static constexpr int DebugDrawOrder = 1'000; DebugComponent& entityDebug = entity->GetComponent<DebugComponent>(); GraphicsComponent& entityGfx = entity->GetComponent<GraphicsComponent>(); DebugDrawFlags enabledFlags = entityDebug.GetEnabledFlags(); DebugDrawFlags flags = entityDebug.GetFlags(); DebugDrawFlags flagsToEnable = flags & ~enabledFlags; for (std::size_t i = 0; i <= static_cast<std::size_t>(DebugDraw::Max); ++i) { DebugDraw option = static_cast<DebugDraw>(i); if (flagsToEnable & option) { switch (option) { case DebugDraw::Collider3D: { const Nz::Boxf& obb = entityGfx.GetBoundingVolume().obb.localBox; Nz::InstancedRenderableRef renderable = GenerateCollision3DMesh(entity); renderable->SetPersistent(false); entityGfx.Attach(renderable, Nz::Matrix4f::Translate(obb.GetCenter()), DebugDrawOrder); entityDebug.UpdateDebugRenderable(option, std::move(renderable)); break; } case DebugDraw::GraphicsAABB: { auto indexVertexBuffers = GetBoxMesh(); Nz::InstancedRenderableRef renderable = new AABBDebugRenderable(entity, GetAABBMaterial(), indexVertexBuffers.first, indexVertexBuffers.second); renderable->SetPersistent(false); entityGfx.Attach(renderable, Nz::Matrix4f::Identity(), DebugDrawOrder); entityDebug.UpdateDebugRenderable(option, std::move(renderable)); break; } case DebugDraw::GraphicsOBB: { auto indexVertexBuffers = GetBoxMesh(); Nz::InstancedRenderableRef renderable = new OBBDebugRenderable(entity, GetOBBMaterial(), indexVertexBuffers.first, indexVertexBuffers.second); renderable->SetPersistent(false); entityGfx.Attach(renderable, Nz::Matrix4f::Identity(), DebugDrawOrder); entityDebug.UpdateDebugRenderable(option, std::move(renderable)); break; } default: break; } } } DebugDrawFlags flagsToDisable = enabledFlags & ~flags; for (std::size_t i = 0; i <= static_cast<std::size_t>(DebugDraw::Max); ++i) { DebugDraw option = static_cast<DebugDraw>(i); if (flagsToDisable & option) entityGfx.Detach(entityDebug.GetDebugRenderable(option)); } entityDebug.UpdateEnabledFlags(flags); } void DebugSystem::OnUpdate(float elapsedTime) { // Nothing to do } Nz::InstancedRenderableRef DebugSystem::GenerateBox(Nz::Boxf box) { Nz::MeshRef mesh = Nz::Mesh::New(); mesh->CreateStatic(); mesh->BuildSubMesh(Nz::Primitive::Box(box.GetLengths())); mesh->SetMaterialCount(1); Nz::ModelRef model = Nz::Model::New(); model->SetMesh(mesh); model->SetMaterial(0, GetOBBMaterial()); return model; } Nz::InstancedRenderableRef DebugSystem::GenerateCollision3DMesh(Entity* entity) { if (entity->HasComponent<CollisionComponent3D>()) { CollisionComponent3D& entityCollision = entity->GetComponent<CollisionComponent3D>(); const Nz::Collider3DRef& geom = entityCollision.GetGeom(); std::vector<Nz::Vector3f> vertices; std::vector<std::size_t> indices; geom->ForEachPolygon([&](const float* polygonVertices, std::size_t vertexCount) { std::size_t firstIndex = vertices.size(); for (std::size_t i = 0; i < vertexCount; ++i) { const float* vertexData = &polygonVertices[i * 3]; vertices.emplace_back(vertexData[0], vertexData[1], vertexData[2]); } for (std::size_t i = 0; i < vertexCount - 1; ++i) { indices.push_back(firstIndex + i); indices.push_back(firstIndex + i + 1); } indices.push_back(firstIndex + vertexCount - 1); indices.push_back(firstIndex); }); Nz::IndexBufferRef indexBuffer = Nz::IndexBuffer::New(vertices.size() > 0xFFFF, indices.size(), Nz::DataStorage_Hardware, 0); Nz::IndexMapper indexMapper(indexBuffer, Nz::BufferAccess_WriteOnly); Nz::IndexIterator indexPtr = indexMapper.begin(); for (std::size_t index : indices) *indexPtr++ = static_cast<Nz::UInt32>(index); indexMapper.Unmap(); Nz::VertexBufferRef vertexBuffer = Nz::VertexBuffer::New(Nz::VertexDeclaration::Get(Nz::VertexLayout_XYZ), vertices.size(), Nz::DataStorage_Hardware, 0); vertexBuffer->Fill(vertices.data(), 0, vertices.size()); Nz::MeshRef mesh = Nz::Mesh::New(); mesh->CreateStatic(); Nz::StaticMeshRef subMesh = Nz::StaticMesh::New(mesh); subMesh->Create(vertexBuffer); subMesh->SetIndexBuffer(indexBuffer); subMesh->SetPrimitiveMode(Nz::PrimitiveMode_LineList); subMesh->SetMaterialIndex(0); subMesh->GenerateAABB(); mesh->SetMaterialCount(1); mesh->AddSubMesh(subMesh); Nz::ModelRef model = Nz::Model::New(); model->SetMesh(mesh); model->SetMaterial(0, GetCollisionMaterial()); return model; } else return nullptr; } Nz::MaterialRef DebugSystem::GetAABBMaterial() { if (!m_aabbMaterial) { m_aabbMaterial = Nz::Material::New(); m_aabbMaterial->EnableFaceCulling(false); m_aabbMaterial->EnableDepthBuffer(true); m_aabbMaterial->SetDiffuseColor(Nz::Color::Red); m_aabbMaterial->SetFaceFilling(Nz::FaceFilling_Line); } return m_aabbMaterial; } Nz::MaterialRef DebugSystem::GetCollisionMaterial() { if (!m_collisionMaterial) { m_collisionMaterial = Nz::Material::New(); m_collisionMaterial->EnableFaceCulling(false); m_collisionMaterial->EnableDepthBuffer(true); m_collisionMaterial->SetDiffuseColor(Nz::Color::Blue); m_collisionMaterial->SetFaceFilling(Nz::FaceFilling_Line); } return m_collisionMaterial; } Nz::MaterialRef DebugSystem::GetOBBMaterial() { if (!m_obbMaterial) { m_obbMaterial = Nz::Material::New(); m_obbMaterial->EnableFaceCulling(false); m_obbMaterial->EnableDepthBuffer(true); m_obbMaterial->SetDiffuseColor(Nz::Color::Green); m_obbMaterial->SetFaceFilling(Nz::FaceFilling_Line); } return m_obbMaterial; } SystemIndex DebugSystem::systemIndex; } <commit_msg>Sdk/DebugSystem: Fix some warnings<commit_after>// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Development Kit" // For conditions of distribution and use, see copyright notice in Prerequisites.hpp #include <NDK/Systems/DebugSystem.hpp> #include <Nazara/Core/Primitive.hpp> #include <Nazara/Graphics/Model.hpp> #include <Nazara/Utility/IndexIterator.hpp> #include <Nazara/Utility/Mesh.hpp> #include <Nazara/Utility/StaticMesh.hpp> #include <NDK/Components/CollisionComponent3D.hpp> #include <NDK/Components/DebugComponent.hpp> #include <NDK/Components/GraphicsComponent.hpp> #include <NDK/Components/NodeComponent.hpp> namespace Ndk { namespace { class DebugRenderable : public Nz::InstancedRenderable { public: DebugRenderable(Ndk::Entity* owner, Nz::MaterialRef mat, Nz::IndexBufferRef indexBuffer, Nz::VertexBufferRef vertexBuffer) : m_entityOwner(owner), m_material(std::move(mat)), m_indexBuffer(std::move(indexBuffer)), m_vertexBuffer(std::move(vertexBuffer)) { ResetMaterials(1); m_meshData.indexBuffer = m_indexBuffer; m_meshData.primitiveMode = Nz::PrimitiveMode_LineList; m_meshData.vertexBuffer = m_vertexBuffer; } void UpdateBoundingVolume(InstanceData* instanceData) const override { } void MakeBoundingVolume() const override { m_boundingVolume.MakeNull(); } protected: Ndk::EntityHandle m_entityOwner; Nz::IndexBufferRef m_indexBuffer; Nz::MaterialRef m_material; Nz::MeshData m_meshData; Nz::VertexBufferRef m_vertexBuffer; }; class AABBDebugRenderable : public DebugRenderable { public: using DebugRenderable::DebugRenderable; void AddToRenderQueue(Nz::AbstractRenderQueue* renderQueue, const InstanceData& instanceData, const Nz::Recti& scissorRect) const override { NazaraAssert(m_entityOwner, "DebugRenderable has no owner"); const DebugComponent& entityDebug = m_entityOwner->GetComponent<DebugComponent>(); const GraphicsComponent& entityGfx = m_entityOwner->GetComponent<GraphicsComponent>(); Nz::Matrix4f transformMatrix = Nz::Matrix4f::Identity(); transformMatrix.SetScale(entityGfx.GetBoundingVolume().aabb.GetLengths()); transformMatrix.SetTranslation(entityGfx.GetBoundingVolume().aabb.GetCenter()); renderQueue->AddMesh(0, m_material, m_meshData, Nz::Boxf::Zero(), transformMatrix, scissorRect); } }; class OBBDebugRenderable : public DebugRenderable { public: using DebugRenderable::DebugRenderable; void AddToRenderQueue(Nz::AbstractRenderQueue* renderQueue, const InstanceData& instanceData, const Nz::Recti& scissorRect) const override { NazaraAssert(m_entityOwner, "DebugRenderable has no owner"); const DebugComponent& entityDebug = m_entityOwner->GetComponent<DebugComponent>(); const GraphicsComponent& entityGfx = m_entityOwner->GetComponent<GraphicsComponent>(); Nz::Matrix4f transformMatrix = instanceData.transformMatrix; transformMatrix.ApplyScale(entityGfx.GetBoundingVolume().obb.localBox.GetLengths()); renderQueue->AddMesh(0, m_material, m_meshData, Nz::Boxf::Zero(), transformMatrix, scissorRect); } }; } /*! * \ingroup NDK * \class Ndk::DebugSystem * \brief NDK class that represents the debug system * * \remark This system is enabled if the entity owns the trait: DebugComponent and GraphicsComponent */ /*! * \brief Constructs an DebugSystem object by default */ DebugSystem::DebugSystem() { Requires<DebugComponent, GraphicsComponent>(); SetUpdateOrder(1000); //< Update last } std::pair<Nz::IndexBufferRef, Nz::VertexBufferRef> DebugSystem::GetBoxMesh() { if (!m_boxMeshIndexBuffer) { std::array<Nz::UInt16, 24> indices = { { 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 } }; m_boxMeshIndexBuffer = Nz::IndexBuffer::New(false, Nz::UInt32(indices.size()), Nz::DataStorage_Hardware, 0); m_boxMeshIndexBuffer->Fill(indices.data(), 0, Nz::UInt32(indices.size())); } if (!m_boxMeshVertexBuffer) { Nz::Boxf box(-0.5f, -0.5f, -0.5f, 1.f, 1.f, 1.f); std::array<Nz::Vector3f, 8> positions = { { box.GetCorner(Nz::BoxCorner_FarLeftBottom), box.GetCorner(Nz::BoxCorner_NearLeftBottom), box.GetCorner(Nz::BoxCorner_NearRightBottom), box.GetCorner(Nz::BoxCorner_FarRightBottom), box.GetCorner(Nz::BoxCorner_FarLeftTop), box.GetCorner(Nz::BoxCorner_NearLeftTop), box.GetCorner(Nz::BoxCorner_NearRightTop), box.GetCorner(Nz::BoxCorner_FarRightTop) } }; m_boxMeshVertexBuffer = Nz::VertexBuffer::New(Nz::VertexDeclaration::Get(Nz::VertexLayout_XYZ), Nz::UInt32(positions.size()), Nz::DataStorage_Hardware, 0); m_boxMeshVertexBuffer->Fill(positions.data(), 0, Nz::UInt32(positions.size())); } return { m_boxMeshIndexBuffer, m_boxMeshVertexBuffer }; } void DebugSystem::OnEntityValidation(Entity* entity, bool /*justAdded*/) { static constexpr int DebugDrawOrder = 1'000; DebugComponent& entityDebug = entity->GetComponent<DebugComponent>(); GraphicsComponent& entityGfx = entity->GetComponent<GraphicsComponent>(); DebugDrawFlags enabledFlags = entityDebug.GetEnabledFlags(); DebugDrawFlags flags = entityDebug.GetFlags(); DebugDrawFlags flagsToEnable = flags & ~enabledFlags; for (std::size_t i = 0; i <= static_cast<std::size_t>(DebugDraw::Max); ++i) { DebugDraw option = static_cast<DebugDraw>(i); if (flagsToEnable & option) { switch (option) { case DebugDraw::Collider3D: { const Nz::Boxf& obb = entityGfx.GetBoundingVolume().obb.localBox; Nz::InstancedRenderableRef renderable = GenerateCollision3DMesh(entity); renderable->SetPersistent(false); entityGfx.Attach(renderable, Nz::Matrix4f::Translate(obb.GetCenter()), DebugDrawOrder); entityDebug.UpdateDebugRenderable(option, std::move(renderable)); break; } case DebugDraw::GraphicsAABB: { auto indexVertexBuffers = GetBoxMesh(); Nz::InstancedRenderableRef renderable = new AABBDebugRenderable(entity, GetAABBMaterial(), indexVertexBuffers.first, indexVertexBuffers.second); renderable->SetPersistent(false); entityGfx.Attach(renderable, Nz::Matrix4f::Identity(), DebugDrawOrder); entityDebug.UpdateDebugRenderable(option, std::move(renderable)); break; } case DebugDraw::GraphicsOBB: { auto indexVertexBuffers = GetBoxMesh(); Nz::InstancedRenderableRef renderable = new OBBDebugRenderable(entity, GetOBBMaterial(), indexVertexBuffers.first, indexVertexBuffers.second); renderable->SetPersistent(false); entityGfx.Attach(renderable, Nz::Matrix4f::Identity(), DebugDrawOrder); entityDebug.UpdateDebugRenderable(option, std::move(renderable)); break; } default: break; } } } DebugDrawFlags flagsToDisable = enabledFlags & ~flags; for (std::size_t i = 0; i <= static_cast<std::size_t>(DebugDraw::Max); ++i) { DebugDraw option = static_cast<DebugDraw>(i); if (flagsToDisable & option) entityGfx.Detach(entityDebug.GetDebugRenderable(option)); } entityDebug.UpdateEnabledFlags(flags); } void DebugSystem::OnUpdate(float elapsedTime) { // Nothing to do } Nz::InstancedRenderableRef DebugSystem::GenerateBox(Nz::Boxf box) { Nz::MeshRef mesh = Nz::Mesh::New(); mesh->CreateStatic(); mesh->BuildSubMesh(Nz::Primitive::Box(box.GetLengths())); mesh->SetMaterialCount(1); Nz::ModelRef model = Nz::Model::New(); model->SetMesh(mesh); model->SetMaterial(0, GetOBBMaterial()); return model; } Nz::InstancedRenderableRef DebugSystem::GenerateCollision3DMesh(Entity* entity) { if (entity->HasComponent<CollisionComponent3D>()) { CollisionComponent3D& entityCollision = entity->GetComponent<CollisionComponent3D>(); const Nz::Collider3DRef& geom = entityCollision.GetGeom(); std::vector<Nz::Vector3f> vertices; std::vector<std::size_t> indices; geom->ForEachPolygon([&](const float* polygonVertices, std::size_t vertexCount) { std::size_t firstIndex = vertices.size(); for (std::size_t i = 0; i < vertexCount; ++i) { const float* vertexData = &polygonVertices[i * 3]; vertices.emplace_back(vertexData[0], vertexData[1], vertexData[2]); } for (std::size_t i = 0; i < vertexCount - 1; ++i) { indices.push_back(firstIndex + i); indices.push_back(firstIndex + i + 1); } indices.push_back(firstIndex + vertexCount - 1); indices.push_back(firstIndex); }); Nz::IndexBufferRef indexBuffer = Nz::IndexBuffer::New(vertices.size() > 0xFFFF, Nz::UInt32(indices.size()), Nz::DataStorage_Hardware, 0); Nz::IndexMapper indexMapper(indexBuffer, Nz::BufferAccess_WriteOnly); Nz::IndexIterator indexPtr = indexMapper.begin(); for (std::size_t index : indices) *indexPtr++ = static_cast<Nz::UInt32>(index); indexMapper.Unmap(); Nz::VertexBufferRef vertexBuffer = Nz::VertexBuffer::New(Nz::VertexDeclaration::Get(Nz::VertexLayout_XYZ), Nz::UInt32(vertices.size()), Nz::DataStorage_Hardware, 0); vertexBuffer->Fill(vertices.data(), 0, Nz::UInt32(vertices.size())); Nz::MeshRef mesh = Nz::Mesh::New(); mesh->CreateStatic(); Nz::StaticMeshRef subMesh = Nz::StaticMesh::New(mesh); subMesh->Create(vertexBuffer); subMesh->SetIndexBuffer(indexBuffer); subMesh->SetPrimitiveMode(Nz::PrimitiveMode_LineList); subMesh->SetMaterialIndex(0); subMesh->GenerateAABB(); mesh->SetMaterialCount(1); mesh->AddSubMesh(subMesh); Nz::ModelRef model = Nz::Model::New(); model->SetMesh(mesh); model->SetMaterial(0, GetCollisionMaterial()); return model; } else return nullptr; } Nz::MaterialRef DebugSystem::GetAABBMaterial() { if (!m_aabbMaterial) { m_aabbMaterial = Nz::Material::New(); m_aabbMaterial->EnableFaceCulling(false); m_aabbMaterial->EnableDepthBuffer(true); m_aabbMaterial->SetDiffuseColor(Nz::Color::Red); m_aabbMaterial->SetFaceFilling(Nz::FaceFilling_Line); } return m_aabbMaterial; } Nz::MaterialRef DebugSystem::GetCollisionMaterial() { if (!m_collisionMaterial) { m_collisionMaterial = Nz::Material::New(); m_collisionMaterial->EnableFaceCulling(false); m_collisionMaterial->EnableDepthBuffer(true); m_collisionMaterial->SetDiffuseColor(Nz::Color::Blue); m_collisionMaterial->SetFaceFilling(Nz::FaceFilling_Line); } return m_collisionMaterial; } Nz::MaterialRef DebugSystem::GetOBBMaterial() { if (!m_obbMaterial) { m_obbMaterial = Nz::Material::New(); m_obbMaterial->EnableFaceCulling(false); m_obbMaterial->EnableDepthBuffer(true); m_obbMaterial->SetDiffuseColor(Nz::Color::Green); m_obbMaterial->SetFaceFilling(Nz::FaceFilling_Line); } return m_obbMaterial; } SystemIndex DebugSystem::systemIndex; } <|endoftext|>
<commit_before>/* This file is part of Zanshin Todo. Copyright 2008-2010 Kevin Ottens <[email protected]> Copyright 2008,2009 Mario Bensi <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "mainwindow.h" #include <KDE/KAction> #include <KDE/KActionCollection> #include <KDE/KConfigGroup> #include <KDE/KIcon> #include <KDE/KLocale> #include <KDE/KMenuBar> #include <QtGui/QDockWidget> #include <QtGui/QHeaderView> #include "actionlisteditor.h" #include "configdialog.h" #include "globaldefs.h" #include "sidebar.h" MainWindow::MainWindow(ModelStack *models, QWidget *parent) : KXmlGuiWindow(parent) { setupSideBar(models); setupCentralWidget(models); setupActions(); setupGUI(ToolBar | Keys | Save | Create); restoreColumnsState(); actionCollection()->action("project_mode")->trigger(); } void MainWindow::setupCentralWidget(ModelStack *models) { m_editor = new ActionListEditor(models, m_sidebar->projectSelection(), m_sidebar->categoriesSelection(), actionCollection(), this); setCentralWidget(m_editor); } void MainWindow::setupSideBar(ModelStack *models) { m_sidebar = new SideBar(models, actionCollection(), this); QDockWidget *dock = new QDockWidget(this); dock->setObjectName("SideBar"); dock->setFeatures(dock->features() & ~QDockWidget::DockWidgetClosable); dock->setWidget(m_sidebar); addDockWidget(Qt::LeftDockWidgetArea, dock); } void MainWindow::setupActions() { KActionCollection *ac = actionCollection(); KAction *action = ac->addAction(KStandardAction::ShowMenubar); connect(action, SIGNAL(toggled(bool)), menuBar(), SLOT(setVisible(bool))); QActionGroup *modeGroup = new QActionGroup(this); modeGroup->setExclusive(true); action = ac->addAction("project_mode", this, SLOT(onModeSwitch())); action->setText(i18n("Project View")); action->setIcon(KIcon("view-pim-tasks")); action->setShortcut(Qt::CTRL | Qt::Key_P); action->setCheckable(true); action->setData(Zanshin::ProjectMode); modeGroup->addAction(action); action = ac->addAction("categories_mode", this, SLOT(onModeSwitch())); action->setText(i18n("Categories View")); action->setIcon(KIcon("view-pim-notes")); action->setShortcut(Qt::CTRL | Qt::Key_O); action->setCheckable(true); action->setData(Zanshin::CategoriesMode); modeGroup->addAction(action); ac->addAction(KStandardAction::Preferences, this, SLOT(showConfigDialog())); ac->addAction(KStandardAction::Quit, this, SLOT(close())); } void MainWindow::closeEvent(QCloseEvent *event) { saveColumnsState(); KXmlGuiWindow::closeEvent(event); } void MainWindow::saveAutoSaveSettings() { saveColumnsState(); KXmlGuiWindow::saveAutoSaveSettings(); } void MainWindow::saveColumnsState() { KConfigGroup cg = autoSaveConfigGroup(); m_editor->saveColumnsState(cg); } void MainWindow::restoreColumnsState() { KConfigGroup cg = autoSaveConfigGroup(); m_editor->restoreColumnsState(cg); } void MainWindow::onModeSwitch() { KAction *action = static_cast<KAction*>(sender()); m_editor->setMode((Zanshin::ApplicationMode)action->data().toInt()); m_sidebar->setMode((Zanshin::ApplicationMode)action->data().toInt()); } void MainWindow::showConfigDialog() { ConfigDialog dialog(this); dialog.exec(); } <commit_msg>Bring up the settings dialog on first run<commit_after>/* This file is part of Zanshin Todo. Copyright 2008-2010 Kevin Ottens <[email protected]> Copyright 2008,2009 Mario Bensi <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "mainwindow.h" #include <KDE/KAction> #include <KDE/KActionCollection> #include <KDE/KConfigGroup> #include <KDE/KIcon> #include <KDE/KLocale> #include <KDE/KMenuBar> #include <QtCore/QTimer> #include <QtGui/QDockWidget> #include <QtGui/QHeaderView> #include "actionlisteditor.h" #include "configdialog.h" #include "globaldefs.h" #include "sidebar.h" MainWindow::MainWindow(ModelStack *models, QWidget *parent) : KXmlGuiWindow(parent) { setupSideBar(models); setupCentralWidget(models); setupActions(); setupGUI(ToolBar | Keys | Save | Create); restoreColumnsState(); actionCollection()->action("project_mode")->trigger(); KConfigGroup config(KGlobal::config(), "General"); if (config.readEntry("firstRun", true)) { QTimer::singleShot(0, this, SLOT(showConfigDialog())); config.writeEntry("firstRun", false); } } void MainWindow::setupCentralWidget(ModelStack *models) { m_editor = new ActionListEditor(models, m_sidebar->projectSelection(), m_sidebar->categoriesSelection(), actionCollection(), this); setCentralWidget(m_editor); } void MainWindow::setupSideBar(ModelStack *models) { m_sidebar = new SideBar(models, actionCollection(), this); QDockWidget *dock = new QDockWidget(this); dock->setObjectName("SideBar"); dock->setFeatures(dock->features() & ~QDockWidget::DockWidgetClosable); dock->setWidget(m_sidebar); addDockWidget(Qt::LeftDockWidgetArea, dock); } void MainWindow::setupActions() { KActionCollection *ac = actionCollection(); KAction *action = ac->addAction(KStandardAction::ShowMenubar); connect(action, SIGNAL(toggled(bool)), menuBar(), SLOT(setVisible(bool))); QActionGroup *modeGroup = new QActionGroup(this); modeGroup->setExclusive(true); action = ac->addAction("project_mode", this, SLOT(onModeSwitch())); action->setText(i18n("Project View")); action->setIcon(KIcon("view-pim-tasks")); action->setShortcut(Qt::CTRL | Qt::Key_P); action->setCheckable(true); action->setData(Zanshin::ProjectMode); modeGroup->addAction(action); action = ac->addAction("categories_mode", this, SLOT(onModeSwitch())); action->setText(i18n("Categories View")); action->setIcon(KIcon("view-pim-notes")); action->setShortcut(Qt::CTRL | Qt::Key_O); action->setCheckable(true); action->setData(Zanshin::CategoriesMode); modeGroup->addAction(action); ac->addAction(KStandardAction::Preferences, this, SLOT(showConfigDialog())); ac->addAction(KStandardAction::Quit, this, SLOT(close())); } void MainWindow::closeEvent(QCloseEvent *event) { saveColumnsState(); KXmlGuiWindow::closeEvent(event); } void MainWindow::saveAutoSaveSettings() { saveColumnsState(); KXmlGuiWindow::saveAutoSaveSettings(); } void MainWindow::saveColumnsState() { KConfigGroup cg = autoSaveConfigGroup(); m_editor->saveColumnsState(cg); } void MainWindow::restoreColumnsState() { KConfigGroup cg = autoSaveConfigGroup(); m_editor->restoreColumnsState(cg); } void MainWindow::onModeSwitch() { KAction *action = static_cast<KAction*>(sender()); m_editor->setMode((Zanshin::ApplicationMode)action->data().toInt()); m_sidebar->setMode((Zanshin::ApplicationMode)action->data().toInt()); } void MainWindow::showConfigDialog() { ConfigDialog dialog(this); dialog.exec(); } <|endoftext|>
<commit_before>#include <string> #include <fstream> #include <iostream> #include "map.h" using namespace std; Map::Map() {} Map::~Map() {} void Map::LoadMap(string MapFileName){ string Temp; fstream MapFile; int X = 0; int Y = 0; int F = 0; int C = 0; MapFile.open (MapFileName, fstream::in); while ( MapFile >> Temp ){ cout << Temp << endl << endl << endl << flush; for (int i = 0; i < Temp.length(); i++){ if (Temp[i] == ','){ C++; mapArray[X][Y] = stoi(Temp.substr(F,i-F)); cout << mapArray[X][Y] << " " << flush; X++; F = i + 1; } } Y++; X = 0; cout << "C = " << C << flush; } MapFile.close(); } int Map::Point(int X, int Y){ return (int)mapArray[X][Y]; } bool Map::Passable(int X, int Y){ return (mapArray[X][Y] < PassableThreshhold); } string Map::GetPlot(int X, int Y){ //Returns a 20x20 chunk of the map string RetVal; string Temp; for (int i = X; i < X + 20; i++){ for (int j = Y; j < Y + 20; j++){ if (i <= MaxX && i > -1 && j <= MaxY && j > -1){ Temp = to_string(mapArray[i][j]); if (Temp.length() == 1) { RetVal += "0";} RetVal += Temp; } else { RetVal += "-1"; } } } return RetVal; }<commit_msg>Work in progress<commit_after>#include <string> #include <fstream> #include <iostream> #include "map.h" using namespace std; Map::Map() {} Map::~Map() {} void Map::LoadMap(string MapFileName){ string Temp; fstream MapFile; int X = 0; int Y = 0; int F = 0; int C = 0; MapFile.open (MapFileName, fstream::in); while ( MapFile >> Temp ){ cout << endl << endl << endl << flush; for (int i = 0; i < Temp.length(); i++){ if (Temp[i] == ','){ C++; mapArray[X][Y] = stoi(Temp.substr(F,i-F)); cout << mapArray[X][Y] << " " << flush; X++; F = i + 1; } } Y++; X = 0; F = 0; cout << "\nC = " << C << flush; } MapFile.close(); } int Map::Point(int X, int Y){ return (int)mapArray[X][Y]; } bool Map::Passable(int X, int Y){ return (mapArray[X][Y] < PassableThreshhold); } string Map::GetPlot(int X, int Y){ //Returns a 20x20 chunk of the map string RetVal; string Temp; for (int i = X; i < X + 20; i++){ for (int j = Y; j < Y + 20; j++){ if (i <= MaxX && i > -1 && j <= MaxY && j > -1){ Temp = to_string(mapArray[i][j]); if (Temp.length() == 1) { RetVal += "0";} RetVal += Temp; } else { RetVal += "-1"; } } } return RetVal; }<|endoftext|>
<commit_before>/* This file is part of Zanshin Todo. Copyright 2008-2010 Kevin Ottens <[email protected]> Copyright 2008,2009 Mario Bensi <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "mainwindow.h" #include <KDE/KAction> #include <KDE/KActionCollection> #include <KDE/KConfigGroup> #include <KDE/KIcon> #include <KDE/KLocale> #include <QtGui/QDockWidget> #include <QtGui/QHeaderView> #include "actionlisteditor.h" #include "globaldefs.h" #include "sidebar.h" MainWindow::MainWindow(ModelStack *models, QWidget *parent) : KXmlGuiWindow(parent) { setupSideBar(models); setupCentralWidget(models); setupActions(); setupGUI(ToolBar | Keys | Save | Create); restoreColumnsState(); actionCollection()->action("project_mode")->trigger(); } void MainWindow::setupCentralWidget(ModelStack *models) { m_editor = new ActionListEditor(models, m_sidebar->projectSelection(), m_sidebar->categoriesSelection(), actionCollection(), this); setCentralWidget(m_editor); } void MainWindow::setupSideBar(ModelStack *models) { m_sidebar = new SideBar(models, actionCollection(), this); QDockWidget *dock = new QDockWidget(this); dock->setObjectName("SideBar"); dock->setFeatures(dock->features() & ~QDockWidget::DockWidgetClosable); dock->setWidget(m_sidebar); addDockWidget(Qt::LeftDockWidgetArea, dock); } void MainWindow::setupActions() { KActionCollection *ac = actionCollection(); QActionGroup *modeGroup = new QActionGroup(this); modeGroup->setExclusive(true); KAction *action = ac->addAction("project_mode", this, SLOT(onModeSwitch())); action->setText(i18n("Project View")); action->setIcon(KIcon("view-pim-tasks")); action->setShortcut(Qt::CTRL | Qt::Key_P); action->setCheckable(true); action->setData(Zanshin::ProjectMode); modeGroup->addAction(action); action = ac->addAction("categories_mode", this, SLOT(onModeSwitch())); action->setText(i18n("Categories View")); action->setIcon(KIcon("view-pim-notes")); action->setShortcut(Qt::CTRL | Qt::Key_O); action->setCheckable(true); action->setData(Zanshin::CategoriesMode); modeGroup->addAction(action); ac->addAction(KStandardAction::Quit, this, SLOT(close())); } void MainWindow::closeEvent(QCloseEvent *event) { saveColumnsState(); KXmlGuiWindow::closeEvent(event); } void MainWindow::saveAutoSaveSettings() { saveColumnsState(); KXmlGuiWindow::saveAutoSaveSettings(); } void MainWindow::saveColumnsState() { KConfigGroup cg = autoSaveConfigGroup(); m_editor->saveColumnsState(cg); } void MainWindow::restoreColumnsState() { KConfigGroup cg = autoSaveConfigGroup(); m_editor->restoreColumnsState(cg); } void MainWindow::onModeSwitch() { KAction *action = static_cast<KAction*>(sender()); m_editor->setMode((Zanshin::ApplicationMode)action->data().toInt()); m_sidebar->setMode((Zanshin::ApplicationMode)action->data().toInt()); } <commit_msg>Allow to hide the main menu.<commit_after>/* This file is part of Zanshin Todo. Copyright 2008-2010 Kevin Ottens <[email protected]> Copyright 2008,2009 Mario Bensi <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "mainwindow.h" #include <KDE/KAction> #include <KDE/KActionCollection> #include <KDE/KConfigGroup> #include <KDE/KIcon> #include <KDE/KLocale> #include <KDE/KMenuBar> #include <QtGui/QDockWidget> #include <QtGui/QHeaderView> #include "actionlisteditor.h" #include "globaldefs.h" #include "sidebar.h" MainWindow::MainWindow(ModelStack *models, QWidget *parent) : KXmlGuiWindow(parent) { setupSideBar(models); setupCentralWidget(models); setupActions(); setupGUI(ToolBar | Keys | Save | Create); restoreColumnsState(); actionCollection()->action("project_mode")->trigger(); } void MainWindow::setupCentralWidget(ModelStack *models) { m_editor = new ActionListEditor(models, m_sidebar->projectSelection(), m_sidebar->categoriesSelection(), actionCollection(), this); setCentralWidget(m_editor); } void MainWindow::setupSideBar(ModelStack *models) { m_sidebar = new SideBar(models, actionCollection(), this); QDockWidget *dock = new QDockWidget(this); dock->setObjectName("SideBar"); dock->setFeatures(dock->features() & ~QDockWidget::DockWidgetClosable); dock->setWidget(m_sidebar); addDockWidget(Qt::LeftDockWidgetArea, dock); } void MainWindow::setupActions() { KActionCollection *ac = actionCollection(); KAction *action = ac->addAction(KStandardAction::ShowMenubar); connect(action, SIGNAL(toggled(bool)), menuBar(), SLOT(setVisible(bool))); QActionGroup *modeGroup = new QActionGroup(this); modeGroup->setExclusive(true); action = ac->addAction("project_mode", this, SLOT(onModeSwitch())); action->setText(i18n("Project View")); action->setIcon(KIcon("view-pim-tasks")); action->setShortcut(Qt::CTRL | Qt::Key_P); action->setCheckable(true); action->setData(Zanshin::ProjectMode); modeGroup->addAction(action); action = ac->addAction("categories_mode", this, SLOT(onModeSwitch())); action->setText(i18n("Categories View")); action->setIcon(KIcon("view-pim-notes")); action->setShortcut(Qt::CTRL | Qt::Key_O); action->setCheckable(true); action->setData(Zanshin::CategoriesMode); modeGroup->addAction(action); ac->addAction(KStandardAction::Quit, this, SLOT(close())); } void MainWindow::closeEvent(QCloseEvent *event) { saveColumnsState(); KXmlGuiWindow::closeEvent(event); } void MainWindow::saveAutoSaveSettings() { saveColumnsState(); KXmlGuiWindow::saveAutoSaveSettings(); } void MainWindow::saveColumnsState() { KConfigGroup cg = autoSaveConfigGroup(); m_editor->saveColumnsState(cg); } void MainWindow::restoreColumnsState() { KConfigGroup cg = autoSaveConfigGroup(); m_editor->restoreColumnsState(cg); } void MainWindow::onModeSwitch() { KAction *action = static_cast<KAction*>(sender()); m_editor->setMode((Zanshin::ApplicationMode)action->data().toInt()); m_sidebar->setMode((Zanshin::ApplicationMode)action->data().toInt()); } <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Albrecht // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_OPERATOR_ELLIPTIC_HH #define DUNE_GDT_OPERATOR_ELLIPTIC_HH #include <type_traits> #include <dune/stuff/la/container/interfaces.hh> #include <dune/stuff/functions/interfaces.hh> #include <dune/gdt/space/interface.hh> #include <dune/gdt/localevaluation/elliptic.hh> #include <dune/gdt/localoperator/codim0.hh> #include "interfaces.hh" namespace Dune { namespace GDT { namespace Operator { // forward, to be used in the traits template <class DiffusionImp, class MatrixImp, class SourceSpaceImp, class RangeSpaceImp = SourceSpaceImp, class GridViewImp = typename SourceSpaceImp::GridViewType> class EllipticCG; template <class DiffusionImp, class MatrixImp, class SourceSpaceImp, class RangeSpaceImp = SourceSpaceImp, class GridViewImp = typename SourceSpaceImp::GridViewType> class EllipticCGTraits { static_assert(std::is_base_of<Stuff::LocalizableFunctionInterface< typename DiffusionImp::EntityType, typename DiffusionImp::DomainFieldType, DiffusionImp::dimDomain, typename DiffusionImp::RangeFieldType, DiffusionImp::dimRange, DiffusionImp::dimRangeCols>, DiffusionImp>::value, "DiffusionImp has to be derived from Stuff::LocalizableFunctionInterface!"); static_assert(std::is_base_of<Stuff::LA::MatrixInterface<typename MatrixImp::Traits>, MatrixImp>::value, "MatrixImp has to be derived from Stuff::LA::MatrixInterface!"); static_assert(std::is_base_of<SpaceInterface<typename SourceSpaceImp::Traits>, SourceSpaceImp>::value, "SourceSpaceImp has to be derived from SpaceInterface!"); static_assert(std::is_base_of<SpaceInterface<typename RangeSpaceImp::Traits>, RangeSpaceImp>::value, "RangeSpaceImp has to be derived from SpaceInterface!"); public: typedef EllipticCG<DiffusionImp, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp> derived_type; typedef MatrixImp MatrixType; typedef SourceSpaceImp SourceSpaceType; typedef RangeSpaceImp RangeSpaceType; typedef GridViewImp GridViewType; private: typedef DiffusionImp DiffusionType; public: typedef LocalOperator::Codim0Integral<LocalEvaluation::Elliptic<DiffusionType>> LocalOperatorType; private: friend class EllipticCG<DiffusionImp, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp>; }; // class EllipticTraits template <class DiffusionImp, class MatrixImp, class SourceSpaceImp, class RangeSpaceImp, class GridViewImp> class EllipticCG : public AssemblableVolumeOperatorBase<EllipticCGTraits<DiffusionImp, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp>> { public: typedef EllipticCGTraits<DiffusionImp, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp> Traits; private: typedef AssemblableVolumeOperatorBase<Traits> BaseType; typedef typename Traits::DiffusionType DiffusionType; typedef typename Traits::LocalOperatorType LocalOperatorType; public: typedef typename Traits::MatrixType MatrixType; typedef typename Traits::SourceSpaceType SourceSpaceType; typedef typename Traits::RangeSpaceType RangeSpaceType; typedef typename Traits::GridViewType GridViewType; using BaseType::pattern; static Stuff::LA::SparsityPatternDefault pattern(const RangeSpaceType& range_space, const SourceSpaceType& source_space, const GridViewType& grid_view) { return range_space.compute_volume_pattern(grid_view, source_space); } EllipticCG(const DiffusionType& diffusion, MatrixType& matrix, const SourceSpaceType& source_space, const RangeSpaceType& range_space, const GridViewType& grid_view) : BaseType(matrix, source_space, range_space, grid_view) , local_operator_(diffusion) { } EllipticCG(const DiffusionType& diffusion, MatrixType& matrix, const SourceSpaceType& source_space, const RangeSpaceType& range_space) : BaseType(matrix, source_space, range_space) , local_operator_(diffusion) { } EllipticCG(const DiffusionType& diffusion, MatrixType& matrix, const SourceSpaceType& source_space) : BaseType(matrix, source_space) , local_operator_(diffusion) { } private: virtual const LocalOperatorType& local_operator() const { return local_operator_; } const LocalOperatorType local_operator_; }; // class EllipticCG } // namespace Operator } // namespace GDT } // namespace Dune #endif // DUNE_GDT_OPERATOR_ELLIPTIC_HH <commit_msg>[operator.elliptic] update<commit_after>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Albrecht // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_OPERATOR_ELLIPTIC_HH #define DUNE_GDT_OPERATOR_ELLIPTIC_HH #include <type_traits> #include <dune/stuff/la/container/interfaces.hh> #include <dune/stuff/functions/interfaces.hh> #include <dune/gdt/space/interface.hh> #include <dune/gdt/localevaluation/elliptic.hh> #include <dune/gdt/localoperator/codim0.hh> #include "base.hh" namespace Dune { namespace GDT { namespace Operator { // forward, to be used in the traits template <class DiffusionImp, class MatrixImp, class SourceSpaceImp, class RangeSpaceImp = SourceSpaceImp, class GridViewImp = typename SourceSpaceImp::GridViewType> class EllipticCG; template <class DiffusionImp, class MatrixImp, class SourceSpaceImp, class RangeSpaceImp = SourceSpaceImp, class GridViewImp = typename SourceSpaceImp::GridViewType> class EllipticCGTraits { static_assert(std::is_base_of<Stuff::LocalizableFunctionInterface< typename DiffusionImp::EntityType, typename DiffusionImp::DomainFieldType, DiffusionImp::dimDomain, typename DiffusionImp::RangeFieldType, DiffusionImp::dimRange, DiffusionImp::dimRangeCols>, DiffusionImp>::value, "DiffusionImp has to be derived from Stuff::LocalizableFunctionInterface!"); static_assert(std::is_base_of<Stuff::LA::MatrixInterface<typename MatrixImp::Traits>, MatrixImp>::value, "MatrixImp has to be derived from Stuff::LA::MatrixInterface!"); static_assert(std::is_base_of<SpaceInterface<typename SourceSpaceImp::Traits>, SourceSpaceImp>::value, "SourceSpaceImp has to be derived from SpaceInterface!"); static_assert(std::is_base_of<SpaceInterface<typename RangeSpaceImp::Traits>, RangeSpaceImp>::value, "RangeSpaceImp has to be derived from SpaceInterface!"); public: typedef EllipticCG<DiffusionImp, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp> derived_type; typedef MatrixImp MatrixType; typedef SourceSpaceImp SourceSpaceType; typedef RangeSpaceImp RangeSpaceType; typedef GridViewImp GridViewType; private: typedef DiffusionImp DiffusionType; public: typedef LocalOperator::Codim0Integral<LocalEvaluation::Elliptic<DiffusionType>> LocalOperatorType; private: friend class EllipticCG<DiffusionImp, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp>; }; // class EllipticTraits template <class DiffusionImp, class MatrixImp, class SourceSpaceImp, class RangeSpaceImp, class GridViewImp> class EllipticCG : public Operator::AssemblableVolumeBase<EllipticCGTraits<DiffusionImp, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp>> { public: typedef EllipticCGTraits<DiffusionImp, MatrixImp, SourceSpaceImp, RangeSpaceImp, GridViewImp> Traits; private: typedef Operator::AssemblableVolumeBase<Traits> BaseType; typedef typename Traits::DiffusionType DiffusionType; typedef typename Traits::LocalOperatorType LocalOperatorType; public: typedef typename Traits::MatrixType MatrixType; typedef typename Traits::SourceSpaceType SourceSpaceType; typedef typename Traits::RangeSpaceType RangeSpaceType; typedef typename Traits::GridViewType GridViewType; using BaseType::pattern; static Stuff::LA::SparsityPatternDefault pattern(const RangeSpaceType& range_space, const SourceSpaceType& source_space, const GridViewType& grid_view) { return range_space.compute_volume_pattern(grid_view, source_space); } EllipticCG(const DiffusionType& diffusion, MatrixType& matrix, const SourceSpaceType& source_space, const RangeSpaceType& range_space, const GridViewType& grid_view) : BaseType(matrix, source_space, range_space, grid_view) , local_operator_(diffusion) { } EllipticCG(const DiffusionType& diffusion, MatrixType& matrix, const SourceSpaceType& source_space, const RangeSpaceType& range_space) : BaseType(matrix, source_space, range_space) , local_operator_(diffusion) { } EllipticCG(const DiffusionType& diffusion, MatrixType& matrix, const SourceSpaceType& source_space) : BaseType(matrix, source_space) , local_operator_(diffusion) { } private: virtual const LocalOperatorType& local_operator() const DS_OVERRIDE DS_FINAL { return local_operator_; } const LocalOperatorType local_operator_; }; // class EllipticCG } // namespace Operator } // namespace GDT } // namespace Dune #endif // DUNE_GDT_OPERATOR_ELLIPTIC_HH <|endoftext|>
<commit_before>#ifndef SOLUTION_HPP #define SOLUTION_HPP #include <algorithm> #include <iostream> #include <tuple> #include <vector> using namespace std; class Solution { public: vector<int> maxSumOfThreeSubarrays(vector<int>& nums, int k) { auto arrsum = [&nums](int a, int b) { int s = 0; for (int i = a; i < b; ++i) { s += nums[i]; } return s; }; const int N = nums.size(); const int inf = 0x3f3f3f3f; vector<int> dp_(3 * N, -inf); auto dp = (int(*)[N])(&dp_[0]); vector<int> idx_(3 * N * 3, 0); auto idx = (int(*)[N][3])(&idx_[0]); int ans[3] = {inf, inf, inf}; for (int t = 0; t < 3; ++t) { int x = t % 2; int start = (t + 1) * k - 1; ans[t] = start; for (int a = start; a < N; ++a) { // index where the new subarray may end dp[t][a] = a > start ? dp[t][a - 1] : -inf; // init as the prev sum if (a > start) { copy(begin(idx[t][a - 1]), end(idx[t][a - 1]), begin(idx[t][a])); } // max sum when array is placed int es = -inf; if (t == 0) { es = arrsum(a - k + 1, a + 1); } else { int prev = dp[t - 1][a - k]; if (prev != -inf) { es = arrsum(a - k + 1, a + 1) + prev; } } // --- if (es > dp[t][a]) { //cout << "(t, a) = " << '(' << t << ", " << a << ')' << '\n'; //cout << "(es, dp[t][a]) = " << '(' << es << ", " << dp[t][a] << ')' << '\n'; if (t > 0) { copy(begin(idx[t - 1][a - k]), end(idx[t - 1][a - k]), begin(idx[t][a])); } idx[t][a][t] = a - k + 1; copy(begin(idx[t][a]), end(idx[t][a]), begin(ans)); dp[t][a] = es; } } //cout << "idx:\n"; for (int t = 0; t < 3; ++t) { for (int a = 0; a < N; ++a) { for (int i = 0; i < 3; ++i) { //cout << idx[t][a][i] << ","; } //cout << "| "; } //cout << '\n'; } //cout << '\n'; //cout << "ans:\n"; for (int a = 0; a < 3; ++a) { //cout << ans[a] << ", "; } //cout << '\n'; } //cout << "dp:\n"; for (int t = 0; t < 3; ++t) { for (int a = 0; a < N; ++a) { //cout << dp[t][a] << ", "; } //cout << '\n'; } //cout << '\n'; return {ans[0], ans[1], ans[2]}; } }; #endif /* SOLUTION_HPP */ <commit_msg>simplify "Maximum Sum of 3 Non-Overlapping Subarrays"<commit_after>#ifndef SOLUTION_HPP #define SOLUTION_HPP #include <algorithm> #include <numeric> #include <vector> using namespace std; class Solution { public: vector<int> maxSumOfThreeSubarrays(vector<int>& nums, int k) { auto arrsum = [&nums](int a, int b) { return accumulate(begin(nums) + a, begin(nums) + b, 0); }; const int N = nums.size(); const int inf = 0x3f3f3f3f; vector<vector<int>> dp(3, vector<int>(N, -inf)); for (int t = 0; t < 3; ++t) { int start = (t + 1) * k - 1; for (int a = start; a < N; ++a) { // 'a' is the index where the new subarray may end // max sum when array is placed ending with index a; still ok event if // it's some -inf + sth int max_end_here = arrsum(a - k + 1, a + 1) + (t > 0 ? dp[t - 1][a - k] : -inf); int prev = a > start ? dp[t][a - 1] : -inf; dp[t][a] = max({dp[t][a], max_end_here, prev}); } } int ans[4] = {N, N, N, N - 1 + k}; for (int t = 2; t >= 0; --t) { auto it = max_element(begin(dp[t]), begin(dp[t]) + ans[t + 1] - k + 1); ans[t] = distance(begin(dp[t]), it); } return {ans[0] - k + 1, ans[1] - k + 1, ans[2] - k + 1}; } }; #endif /* SOLUTION_HPP */ <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkBinaryThresholdTool.h" #include "mitkBoundingObjectToSegmentationFilter.h" #include "mitkToolManager.h" #include "mitkColorProperty.h" #include "mitkDataStorage.h" #include "mitkLevelWindowProperty.h" #include "mitkOrganTypeProperty.h" #include "mitkProperties.h" #include "mitkRenderingManager.h" #include "mitkVtkResliceInterpolationProperty.h" #include <mitkCoreObjectFactory.h> #include "mitkImageAccessByItk.h" #include "mitkImageCast.h" #include "mitkImageStatisticsHolder.h" #include "mitkImageTimeSelector.h" #include "mitkLabelSetImage.h" #include "mitkMaskAndCutRoiImageFilter.h" #include "mitkPadImageFilter.h" #include <itkBinaryThresholdImageFilter.h> #include <itkImageRegionIterator.h> // us #include "usGetModuleContext.h" #include "usModule.h" #include "usModuleResource.h" namespace mitk { MITK_TOOL_MACRO(MITKSEGMENTATION_EXPORT, BinaryThresholdTool, "Thresholding tool"); } mitk::BinaryThresholdTool::BinaryThresholdTool() : m_SensibleMinimumThresholdValue(-100), m_SensibleMaximumThresholdValue(+100), m_CurrentThresholdValue(0.0), m_IsFloatImage(false) { m_ThresholdFeedbackNode = DataNode::New(); m_ThresholdFeedbackNode->SetProperty("color", ColorProperty::New(0.0, 1.0, 0.0)); m_ThresholdFeedbackNode->SetProperty("name", StringProperty::New("Thresholding feedback")); m_ThresholdFeedbackNode->SetProperty("opacity", FloatProperty::New(0.3)); m_ThresholdFeedbackNode->SetProperty("binary", BoolProperty::New(true)); m_ThresholdFeedbackNode->SetProperty("helper object", BoolProperty::New(true)); } mitk::BinaryThresholdTool::~BinaryThresholdTool() { } const char **mitk::BinaryThresholdTool::GetXPM() const { return NULL; } us::ModuleResource mitk::BinaryThresholdTool::GetIconResource() const { us::Module *module = us::GetModuleContext()->GetModule(); us::ModuleResource resource = module->GetResource("Threshold_48x48.png"); return resource; } const char *mitk::BinaryThresholdTool::GetName() const { return "Threshold"; } void mitk::BinaryThresholdTool::Activated() { Superclass::Activated(); m_ToolManager->RoiDataChanged += mitk::MessageDelegate<mitk::BinaryThresholdTool>(this, &mitk::BinaryThresholdTool::OnRoiDataChanged); m_OriginalImageNode = m_ToolManager->GetReferenceData(0); m_NodeForThresholding = m_OriginalImageNode; if (m_NodeForThresholding.IsNotNull()) { SetupPreviewNode(); } else { m_ToolManager->ActivateTool(-1); } } void mitk::BinaryThresholdTool::Deactivated() { m_ToolManager->RoiDataChanged -= mitk::MessageDelegate<mitk::BinaryThresholdTool>(this, &mitk::BinaryThresholdTool::OnRoiDataChanged); m_NodeForThresholding = NULL; m_OriginalImageNode = NULL; try { if (DataStorage *storage = m_ToolManager->GetDataStorage()) { storage->Remove(m_ThresholdFeedbackNode); RenderingManager::GetInstance()->RequestUpdateAll(); } } catch (...) { // don't care } m_ThresholdFeedbackNode->SetData(NULL); Superclass::Deactivated(); } void mitk::BinaryThresholdTool::SetThresholdValue(double value) { if (m_ThresholdFeedbackNode.IsNotNull()) { m_CurrentThresholdValue = value; // Bug 19250: The range of 0.01 is rather random. It was 0.001 before and probably due to rounding error propagation // in VTK code // it leads to strange banding effects on floating point images with a huge range (like -40000 - 40000). 0.01 lowers // this effect // enough to work with our images. Might not work on images with really huge ranges, though. Anyways, still seems to // be low enough // to work for floating point images with a range between 0 and 1. A better solution might be to dynamically // calculate the value // based on the value range of the current image (as big as possible, as small as necessary). // m_ThresholdFeedbackNode->SetProperty( "levelwindow", LevelWindowProperty::New( // LevelWindow(m_CurrentThresholdValue, 0.01) ) ); UpdatePreview(); } } void mitk::BinaryThresholdTool::AcceptCurrentThresholdValue() { CreateNewSegmentationFromThreshold(m_NodeForThresholding); RenderingManager::GetInstance()->RequestUpdateAll(); m_ToolManager->ActivateTool(-1); } void mitk::BinaryThresholdTool::CancelThresholding() { m_ToolManager->ActivateTool(-1); } void mitk::BinaryThresholdTool::SetupPreviewNode() { itk::RGBPixel<float> pixel; pixel[0] = 0.0f; pixel[1] = 1.0f; pixel[2] = 0.0f; if (m_NodeForThresholding.IsNotNull()) { Image::Pointer image = dynamic_cast<Image *>(m_NodeForThresholding->GetData()); Image::Pointer originalImage = dynamic_cast<Image *>(m_OriginalImageNode->GetData()); if (image.IsNotNull()) { mitk::LabelSetImage::Pointer workingImage = dynamic_cast<mitk::LabelSetImage *>(m_ToolManager->GetWorkingData(0)->GetData()); if (workingImage.IsNotNull()) { m_ThresholdFeedbackNode->SetData(workingImage->Clone()); m_IsOldBinary = false; // Let's paint the feedback node green... mitk::LabelSetImage::Pointer previewImage = dynamic_cast<mitk::LabelSetImage *>(m_ThresholdFeedbackNode->GetData()); if (previewImage.IsNull()) { MITK_ERROR << "Cannot create helper objects."; return; } previewImage->GetActiveLabel()->SetColor(pixel); previewImage->GetActiveLabelSet()->UpdateLookupTable(previewImage->GetActiveLabel()->GetValue()); } else { mitk::Image::Pointer workingImageBin = dynamic_cast<mitk::Image *>(m_ToolManager->GetWorkingData(0)->GetData()); if (workingImageBin) { m_ThresholdFeedbackNode->SetData(workingImageBin->Clone()); m_IsOldBinary = true; } else m_ThresholdFeedbackNode->SetData(mitk::Image::New()); } m_ThresholdFeedbackNode->SetColor(pixel); m_ThresholdFeedbackNode->SetOpacity(0.5); int layer(50); m_NodeForThresholding->GetIntProperty("layer", layer); m_ThresholdFeedbackNode->SetIntProperty("layer", layer + 1); if (DataStorage *ds = m_ToolManager->GetDataStorage()) { if (!ds->Exists(m_ThresholdFeedbackNode)) ds->Add(m_ThresholdFeedbackNode, m_OriginalImageNode); } if (image.GetPointer() == originalImage.GetPointer()) { Image::StatisticsHolderPointer statistics = originalImage->GetStatistics(); m_SensibleMinimumThresholdValue = static_cast<double>(statistics->GetScalarValueMin()); m_SensibleMaximumThresholdValue = static_cast<double>(statistics->GetScalarValueMax()); } if ((originalImage->GetPixelType().GetPixelType() == itk::ImageIOBase::SCALAR) && (originalImage->GetPixelType().GetComponentType() == itk::ImageIOBase::FLOAT || originalImage->GetPixelType().GetComponentType() == itk::ImageIOBase::DOUBLE)) m_IsFloatImage = true; else m_IsFloatImage = false; m_CurrentThresholdValue = (m_SensibleMaximumThresholdValue + m_SensibleMinimumThresholdValue) / 2.0; IntervalBordersChanged.Send(m_SensibleMinimumThresholdValue, m_SensibleMaximumThresholdValue, m_IsFloatImage); ThresholdingValueChanged.Send(m_CurrentThresholdValue); } } } template <typename TPixel, unsigned int VImageDimension> static void ITKSetVolume(itk::Image<TPixel, VImageDimension> *originalImage, mitk::Image *segmentation, unsigned int timeStep) { segmentation->SetVolume((void *)originalImage->GetPixelContainer()->GetBufferPointer(), timeStep); } void mitk::BinaryThresholdTool::CreateNewSegmentationFromThreshold(DataNode *node) { if (node) { Image::Pointer feedBackImage = dynamic_cast<Image *>(m_ThresholdFeedbackNode->GetData()); if (feedBackImage.IsNotNull()) { DataNode::Pointer emptySegmentation = GetTargetSegmentationNode(); if (emptySegmentation) { // actually perform a thresholding and ask for an organ type for (unsigned int timeStep = 0; timeStep < feedBackImage->GetTimeSteps(); ++timeStep) { try { ImageTimeSelector::Pointer timeSelector = ImageTimeSelector::New(); timeSelector->SetInput(feedBackImage); timeSelector->SetTimeNr(timeStep); timeSelector->UpdateLargestPossibleRegion(); Image::Pointer image3D = timeSelector->GetOutput(); if (image3D->GetDimension() == 2) { AccessFixedDimensionByItk_2( image3D, ITKSetVolume, 2, dynamic_cast<Image *>(emptySegmentation->GetData()), timeStep); } else { AccessFixedDimensionByItk_2( image3D, ITKSetVolume, 3, dynamic_cast<Image *>(emptySegmentation->GetData()), timeStep); } } catch (...) { Tool::ErrorMessage("Error accessing single time steps of the original image. Cannot create segmentation."); } } if (m_OriginalImageNode.GetPointer() != m_NodeForThresholding.GetPointer()) { mitk::PadImageFilter::Pointer padFilter = mitk::PadImageFilter::New(); padFilter->SetInput(0, dynamic_cast<mitk::Image *>(emptySegmentation->GetData())); padFilter->SetInput(1, dynamic_cast<mitk::Image *>(m_OriginalImageNode->GetData())); padFilter->SetBinaryFilter(true); padFilter->SetUpperThreshold(1); padFilter->SetLowerThreshold(1); padFilter->Update(); emptySegmentation->SetData(padFilter->GetOutput()); } m_ToolManager->SetWorkingData(emptySegmentation); m_ToolManager->GetWorkingData(0)->Modified(); } } } } void mitk::BinaryThresholdTool::OnRoiDataChanged() { mitk::DataNode::Pointer node = m_ToolManager->GetRoiData(0); if (node.IsNotNull()) { mitk::MaskAndCutRoiImageFilter::Pointer roiFilter = mitk::MaskAndCutRoiImageFilter::New(); mitk::Image::Pointer image = dynamic_cast<mitk::Image *>(m_NodeForThresholding->GetData()); if (image.IsNull()) return; roiFilter->SetInput(image); roiFilter->SetRegionOfInterest(node->GetData()); roiFilter->Update(); mitk::DataNode::Pointer tmpNode = mitk::DataNode::New(); tmpNode->SetData(roiFilter->GetOutput()); m_SensibleMaximumThresholdValue = static_cast<double>(roiFilter->GetMaxValue()); m_SensibleMinimumThresholdValue = static_cast<double>(roiFilter->GetMinValue()); m_NodeForThresholding = tmpNode; } else { m_NodeForThresholding = m_OriginalImageNode; } this->SetupPreviewNode(); this->UpdatePreview(); } template <typename TPixel, unsigned int VImageDimension> void mitk::BinaryThresholdTool::ITKThresholding(itk::Image<TPixel, VImageDimension> *originalImage, Image *segmentation, double thresholdValue, unsigned int timeStep) { typedef itk::Image<TPixel, VImageDimension> ImageType; typedef itk::Image<mitk::Tool::DefaultSegmentationDataType, VImageDimension> SegmentationType; typedef itk::BinaryThresholdImageFilter<ImageType, SegmentationType> ThresholdFilterType; typename ThresholdFilterType::Pointer filter = ThresholdFilterType::New(); filter->SetInput(originalImage); filter->SetLowerThreshold(thresholdValue); filter->SetUpperThreshold(m_SensibleMaximumThresholdValue); filter->SetInsideValue(1); filter->SetOutsideValue(0); filter->Update(); segmentation->SetVolume((void *)(filter->GetOutput()->GetPixelContainer()->GetBufferPointer()), timeStep); } template <typename TPixel, unsigned int VImageDimension> void mitk::BinaryThresholdTool::ITKThresholdingOldBinary(itk::Image<TPixel, VImageDimension> *originalImage, Image *segmentation, double thresholdValue, unsigned int timeStep) { typedef itk::Image<TPixel, VImageDimension> ImageType; typedef itk::Image<unsigned char, VImageDimension> SegmentationType; typedef itk::BinaryThresholdImageFilter<ImageType, SegmentationType> ThresholdFilterType; typename ThresholdFilterType::Pointer filter = ThresholdFilterType::New(); filter->SetInput(originalImage); filter->SetLowerThreshold(thresholdValue); filter->SetUpperThreshold(m_SensibleMaximumThresholdValue); filter->SetInsideValue(1); filter->SetOutsideValue(0); filter->Update(); segmentation->SetVolume((void *)(filter->GetOutput()->GetPixelContainer()->GetBufferPointer()), timeStep); } void mitk::BinaryThresholdTool::UpdatePreview() { mitk::Image::Pointer thresholdImage = dynamic_cast<mitk::Image *>(m_NodeForThresholding->GetData()); mitk::Image::Pointer previewImage = dynamic_cast<mitk::Image *>(m_ThresholdFeedbackNode->GetData()); if (thresholdImage && previewImage) { for (unsigned int timeStep = 0; timeStep < thresholdImage->GetTimeSteps(); ++timeStep) { ImageTimeSelector::Pointer timeSelector = ImageTimeSelector::New(); timeSelector->SetInput(thresholdImage); timeSelector->SetTimeNr(timeStep); timeSelector->UpdateLargestPossibleRegion(); Image::Pointer feedBackImage3D = timeSelector->GetOutput(); if (m_IsOldBinary) { AccessByItk_n(feedBackImage3D, ITKThresholdingOldBinary, (previewImage, m_CurrentThresholdValue, timeStep)); } else { AccessByItk_n(feedBackImage3D, ITKThresholding, (previewImage, m_CurrentThresholdValue, timeStep)); } } RenderingManager::GetInstance()->RequestUpdateAll(); } } <commit_msg>Fix crash on Threshold<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkBinaryThresholdTool.h" #include "mitkBoundingObjectToSegmentationFilter.h" #include "mitkToolManager.h" #include "mitkColorProperty.h" #include "mitkDataStorage.h" #include "mitkLevelWindowProperty.h" #include "mitkOrganTypeProperty.h" #include "mitkProperties.h" #include "mitkRenderingManager.h" #include "mitkVtkResliceInterpolationProperty.h" #include <mitkCoreObjectFactory.h> #include "mitkImageAccessByItk.h" #include "mitkImageCast.h" #include "mitkImageStatisticsHolder.h" #include "mitkImageTimeSelector.h" #include "mitkLabelSetImage.h" #include "mitkMaskAndCutRoiImageFilter.h" #include "mitkPadImageFilter.h" #include <itkBinaryThresholdImageFilter.h> #include <itkImageRegionIterator.h> // us #include "usGetModuleContext.h" #include "usModule.h" #include "usModuleResource.h" namespace mitk { MITK_TOOL_MACRO(MITKSEGMENTATION_EXPORT, BinaryThresholdTool, "Thresholding tool"); } mitk::BinaryThresholdTool::BinaryThresholdTool() : m_SensibleMinimumThresholdValue(-100), m_SensibleMaximumThresholdValue(+100), m_CurrentThresholdValue(0.0), m_IsFloatImage(false) { m_ThresholdFeedbackNode = DataNode::New(); m_ThresholdFeedbackNode->SetProperty("color", ColorProperty::New(0.0, 1.0, 0.0)); m_ThresholdFeedbackNode->SetProperty("name", StringProperty::New("Thresholding feedback")); m_ThresholdFeedbackNode->SetProperty("opacity", FloatProperty::New(0.3)); m_ThresholdFeedbackNode->SetProperty("binary", BoolProperty::New(true)); m_ThresholdFeedbackNode->SetProperty("helper object", BoolProperty::New(true)); } mitk::BinaryThresholdTool::~BinaryThresholdTool() { } const char **mitk::BinaryThresholdTool::GetXPM() const { return NULL; } us::ModuleResource mitk::BinaryThresholdTool::GetIconResource() const { us::Module *module = us::GetModuleContext()->GetModule(); us::ModuleResource resource = module->GetResource("Threshold_48x48.png"); return resource; } const char *mitk::BinaryThresholdTool::GetName() const { return "Threshold"; } void mitk::BinaryThresholdTool::Activated() { Superclass::Activated(); m_ToolManager->RoiDataChanged += mitk::MessageDelegate<mitk::BinaryThresholdTool>(this, &mitk::BinaryThresholdTool::OnRoiDataChanged); m_OriginalImageNode = m_ToolManager->GetReferenceData(0); m_NodeForThresholding = m_OriginalImageNode; if (m_NodeForThresholding.IsNotNull()) { SetupPreviewNode(); } else { m_ToolManager->ActivateTool(-1); } } void mitk::BinaryThresholdTool::Deactivated() { m_ToolManager->RoiDataChanged -= mitk::MessageDelegate<mitk::BinaryThresholdTool>(this, &mitk::BinaryThresholdTool::OnRoiDataChanged); m_NodeForThresholding = NULL; m_OriginalImageNode = NULL; try { if (DataStorage *storage = m_ToolManager->GetDataStorage()) { storage->Remove(m_ThresholdFeedbackNode); RenderingManager::GetInstance()->RequestUpdateAll(); } } catch (...) { // don't care } m_ThresholdFeedbackNode->SetData(NULL); Superclass::Deactivated(); } void mitk::BinaryThresholdTool::SetThresholdValue(double value) { if (m_ThresholdFeedbackNode.IsNotNull()) { /* If value is not in the min/max range, do nothing. In that case, this method will be called again with a proper value right after. The only known case where this happens is with an [0.0, 1.0[ image, where value could be an epsilon greater than the max. */ if (value < m_SensibleMinimumThresholdValue || value > m_SensibleMaximumThresholdValue) { return; } m_CurrentThresholdValue = value; // Bug 19250: The range of 0.01 is rather random. It was 0.001 before and probably due to rounding error propagation // in VTK code // it leads to strange banding effects on floating point images with a huge range (like -40000 - 40000). 0.01 lowers // this effect // enough to work with our images. Might not work on images with really huge ranges, though. Anyways, still seems to // be low enough // to work for floating point images with a range between 0 and 1. A better solution might be to dynamically // calculate the value // based on the value range of the current image (as big as possible, as small as necessary). // m_ThresholdFeedbackNode->SetProperty( "levelwindow", LevelWindowProperty::New( // LevelWindow(m_CurrentThresholdValue, 0.01) ) ); UpdatePreview(); } } void mitk::BinaryThresholdTool::AcceptCurrentThresholdValue() { CreateNewSegmentationFromThreshold(m_NodeForThresholding); RenderingManager::GetInstance()->RequestUpdateAll(); m_ToolManager->ActivateTool(-1); } void mitk::BinaryThresholdTool::CancelThresholding() { m_ToolManager->ActivateTool(-1); } void mitk::BinaryThresholdTool::SetupPreviewNode() { itk::RGBPixel<float> pixel; pixel[0] = 0.0f; pixel[1] = 1.0f; pixel[2] = 0.0f; if (m_NodeForThresholding.IsNotNull()) { Image::Pointer image = dynamic_cast<Image *>(m_NodeForThresholding->GetData()); Image::Pointer originalImage = dynamic_cast<Image *>(m_OriginalImageNode->GetData()); if (image.IsNotNull()) { mitk::LabelSetImage::Pointer workingImage = dynamic_cast<mitk::LabelSetImage *>(m_ToolManager->GetWorkingData(0)->GetData()); if (workingImage.IsNotNull()) { m_ThresholdFeedbackNode->SetData(workingImage->Clone()); m_IsOldBinary = false; // Let's paint the feedback node green... mitk::LabelSetImage::Pointer previewImage = dynamic_cast<mitk::LabelSetImage *>(m_ThresholdFeedbackNode->GetData()); if (previewImage.IsNull()) { MITK_ERROR << "Cannot create helper objects."; return; } previewImage->GetActiveLabel()->SetColor(pixel); previewImage->GetActiveLabelSet()->UpdateLookupTable(previewImage->GetActiveLabel()->GetValue()); } else { mitk::Image::Pointer workingImageBin = dynamic_cast<mitk::Image *>(m_ToolManager->GetWorkingData(0)->GetData()); if (workingImageBin) { m_ThresholdFeedbackNode->SetData(workingImageBin->Clone()); m_IsOldBinary = true; } else m_ThresholdFeedbackNode->SetData(mitk::Image::New()); } m_ThresholdFeedbackNode->SetColor(pixel); m_ThresholdFeedbackNode->SetOpacity(0.5); int layer(50); m_NodeForThresholding->GetIntProperty("layer", layer); m_ThresholdFeedbackNode->SetIntProperty("layer", layer + 1); if (DataStorage *ds = m_ToolManager->GetDataStorage()) { if (!ds->Exists(m_ThresholdFeedbackNode)) ds->Add(m_ThresholdFeedbackNode, m_OriginalImageNode); } if (image.GetPointer() == originalImage.GetPointer()) { Image::StatisticsHolderPointer statistics = originalImage->GetStatistics(); m_SensibleMinimumThresholdValue = static_cast<double>(statistics->GetScalarValueMin()); m_SensibleMaximumThresholdValue = static_cast<double>(statistics->GetScalarValueMax()); } if ((originalImage->GetPixelType().GetPixelType() == itk::ImageIOBase::SCALAR) && (originalImage->GetPixelType().GetComponentType() == itk::ImageIOBase::FLOAT || originalImage->GetPixelType().GetComponentType() == itk::ImageIOBase::DOUBLE)) m_IsFloatImage = true; else m_IsFloatImage = false; m_CurrentThresholdValue = (m_SensibleMaximumThresholdValue + m_SensibleMinimumThresholdValue) / 2.0; IntervalBordersChanged.Send(m_SensibleMinimumThresholdValue, m_SensibleMaximumThresholdValue, m_IsFloatImage); ThresholdingValueChanged.Send(m_CurrentThresholdValue); } } } template <typename TPixel, unsigned int VImageDimension> static void ITKSetVolume(itk::Image<TPixel, VImageDimension> *originalImage, mitk::Image *segmentation, unsigned int timeStep) { segmentation->SetVolume((void *)originalImage->GetPixelContainer()->GetBufferPointer(), timeStep); } void mitk::BinaryThresholdTool::CreateNewSegmentationFromThreshold(DataNode *node) { if (node) { Image::Pointer feedBackImage = dynamic_cast<Image *>(m_ThresholdFeedbackNode->GetData()); if (feedBackImage.IsNotNull()) { DataNode::Pointer emptySegmentation = GetTargetSegmentationNode(); if (emptySegmentation) { // actually perform a thresholding and ask for an organ type for (unsigned int timeStep = 0; timeStep < feedBackImage->GetTimeSteps(); ++timeStep) { try { ImageTimeSelector::Pointer timeSelector = ImageTimeSelector::New(); timeSelector->SetInput(feedBackImage); timeSelector->SetTimeNr(timeStep); timeSelector->UpdateLargestPossibleRegion(); Image::Pointer image3D = timeSelector->GetOutput(); if (image3D->GetDimension() == 2) { AccessFixedDimensionByItk_2( image3D, ITKSetVolume, 2, dynamic_cast<Image *>(emptySegmentation->GetData()), timeStep); } else { AccessFixedDimensionByItk_2( image3D, ITKSetVolume, 3, dynamic_cast<Image *>(emptySegmentation->GetData()), timeStep); } } catch (...) { Tool::ErrorMessage("Error accessing single time steps of the original image. Cannot create segmentation."); } } if (m_OriginalImageNode.GetPointer() != m_NodeForThresholding.GetPointer()) { mitk::PadImageFilter::Pointer padFilter = mitk::PadImageFilter::New(); padFilter->SetInput(0, dynamic_cast<mitk::Image *>(emptySegmentation->GetData())); padFilter->SetInput(1, dynamic_cast<mitk::Image *>(m_OriginalImageNode->GetData())); padFilter->SetBinaryFilter(true); padFilter->SetUpperThreshold(1); padFilter->SetLowerThreshold(1); padFilter->Update(); emptySegmentation->SetData(padFilter->GetOutput()); } m_ToolManager->SetWorkingData(emptySegmentation); m_ToolManager->GetWorkingData(0)->Modified(); } } } } void mitk::BinaryThresholdTool::OnRoiDataChanged() { mitk::DataNode::Pointer node = m_ToolManager->GetRoiData(0); if (node.IsNotNull()) { mitk::MaskAndCutRoiImageFilter::Pointer roiFilter = mitk::MaskAndCutRoiImageFilter::New(); mitk::Image::Pointer image = dynamic_cast<mitk::Image *>(m_NodeForThresholding->GetData()); if (image.IsNull()) return; roiFilter->SetInput(image); roiFilter->SetRegionOfInterest(node->GetData()); roiFilter->Update(); mitk::DataNode::Pointer tmpNode = mitk::DataNode::New(); tmpNode->SetData(roiFilter->GetOutput()); m_SensibleMaximumThresholdValue = static_cast<double>(roiFilter->GetMaxValue()); m_SensibleMinimumThresholdValue = static_cast<double>(roiFilter->GetMinValue()); m_NodeForThresholding = tmpNode; } else { m_NodeForThresholding = m_OriginalImageNode; } this->SetupPreviewNode(); this->UpdatePreview(); } template <typename TPixel, unsigned int VImageDimension> void mitk::BinaryThresholdTool::ITKThresholding(itk::Image<TPixel, VImageDimension> *originalImage, Image *segmentation, double thresholdValue, unsigned int timeStep) { typedef itk::Image<TPixel, VImageDimension> ImageType; typedef itk::Image<mitk::Tool::DefaultSegmentationDataType, VImageDimension> SegmentationType; typedef itk::BinaryThresholdImageFilter<ImageType, SegmentationType> ThresholdFilterType; typename ThresholdFilterType::Pointer filter = ThresholdFilterType::New(); filter->SetInput(originalImage); filter->SetLowerThreshold(thresholdValue); filter->SetUpperThreshold(m_SensibleMaximumThresholdValue); filter->SetInsideValue(1); filter->SetOutsideValue(0); filter->Update(); segmentation->SetVolume((void *)(filter->GetOutput()->GetPixelContainer()->GetBufferPointer()), timeStep); } template <typename TPixel, unsigned int VImageDimension> void mitk::BinaryThresholdTool::ITKThresholdingOldBinary(itk::Image<TPixel, VImageDimension> *originalImage, Image *segmentation, double thresholdValue, unsigned int timeStep) { typedef itk::Image<TPixel, VImageDimension> ImageType; typedef itk::Image<unsigned char, VImageDimension> SegmentationType; typedef itk::BinaryThresholdImageFilter<ImageType, SegmentationType> ThresholdFilterType; typename ThresholdFilterType::Pointer filter = ThresholdFilterType::New(); filter->SetInput(originalImage); filter->SetLowerThreshold(thresholdValue); filter->SetUpperThreshold(m_SensibleMaximumThresholdValue); filter->SetInsideValue(1); filter->SetOutsideValue(0); filter->Update(); segmentation->SetVolume((void *)(filter->GetOutput()->GetPixelContainer()->GetBufferPointer()), timeStep); } void mitk::BinaryThresholdTool::UpdatePreview() { mitk::Image::Pointer thresholdImage = dynamic_cast<mitk::Image *>(m_NodeForThresholding->GetData()); mitk::Image::Pointer previewImage = dynamic_cast<mitk::Image *>(m_ThresholdFeedbackNode->GetData()); if (thresholdImage && previewImage) { for (unsigned int timeStep = 0; timeStep < thresholdImage->GetTimeSteps(); ++timeStep) { ImageTimeSelector::Pointer timeSelector = ImageTimeSelector::New(); timeSelector->SetInput(thresholdImage); timeSelector->SetTimeNr(timeStep); timeSelector->UpdateLargestPossibleRegion(); Image::Pointer feedBackImage3D = timeSelector->GetOutput(); if (m_IsOldBinary) { AccessByItk_n(feedBackImage3D, ITKThresholdingOldBinary, (previewImage, m_CurrentThresholdValue, timeStep)); } else { AccessByItk_n(feedBackImage3D, ITKThresholding, (previewImage, m_CurrentThresholdValue, timeStep)); } } RenderingManager::GetInstance()->RequestUpdateAll(); } } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperQtWidgetOutputFilenameParameter.h" namespace otb { namespace Wrapper { QtWidgetOutputFilenameParameter::QtWidgetOutputFilenameParameter(OutputFilenameParameter* param, QtWidgetModel* m) : QtWidgetParameterBase(param, m), m_FilenameParam(param) { } QtWidgetOutputFilenameParameter::~QtWidgetOutputFilenameParameter() { } void QtWidgetOutputFilenameParameter::DoUpdateGUI() { // Update the lineEdit QString text( m_FilenameParam->GetValue().c_str() ); m_Input->setText(text); } void QtWidgetOutputFilenameParameter::DoCreateWidget() { // Set up input text edit m_HLayout = new QHBoxLayout; m_HLayout->setSpacing(0); m_HLayout->setContentsMargins(0, 0, 0, 0); m_Input = new QLineEdit; m_Input->setToolTip( m_FilenameParam->GetDescription() ); connect( m_Input, SIGNAL(textChanged(const QString&)), this, SLOT(SetFileName(const QString&)) ); connect( m_Input, SIGNAL(textChanged(const QString&)), GetModel(), SLOT(NotifyUpdate()) ); m_HLayout->addWidget(m_Input); // Set up input text edit m_Button = new QPushButton; m_Button->setText("..."); m_Button->setToolTip("Select file..."); m_Button->setMaximumWidth(m_Button->width()); connect( m_Button, SIGNAL(clicked()), this, SLOT(SelectFile()) ); m_HLayout->addWidget(m_Button); this->setLayout(m_HLayout); } void QtWidgetOutputFilenameParameter::SelectFile() { QFileDialog fileDialog; fileDialog.setConfirmOverwrite(true); switch(m_FilenameParam->GetRole()) { case Role_Input: { //fileDialog.setFileMode(QFileDialog::ExistingFile); // FIXME: parameter's role is not suitable to separate "input file" names from "output file" names fileDialog.setFileMode(QFileDialog::AnyFile); } break; case Role_Output: { fileDialog.setFileMode(QFileDialog::AnyFile); } break; } fileDialog.setNameFilter("File (*)"); if (fileDialog.exec()) { this->SetFileName(fileDialog.selectedFiles().at(0)); m_Input->setText(fileDialog.selectedFiles().at(0)); } } void QtWidgetOutputFilenameParameter::SetFileName(const QString& value) { // save value m_FilenameParam->SetValue(static_cast<const char*>(value.toAscii())); // notify of value change QString key( m_FilenameParam->GetKey() ); emit ParameterChanged(key); } } } <commit_msg>BUG: avoid cursor to be sent to end after editing OutputFilenameParameter<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperQtWidgetOutputFilenameParameter.h" namespace otb { namespace Wrapper { QtWidgetOutputFilenameParameter::QtWidgetOutputFilenameParameter(OutputFilenameParameter* param, QtWidgetModel* m) : QtWidgetParameterBase(param, m), m_FilenameParam(param) { } QtWidgetOutputFilenameParameter::~QtWidgetOutputFilenameParameter() { } void QtWidgetOutputFilenameParameter::DoUpdateGUI() { // Update the lineEdit QString text( m_FilenameParam->GetValue().c_str() ); if (text != m_Input->text()) m_Input->setText(text); } void QtWidgetOutputFilenameParameter::DoCreateWidget() { // Set up input text edit m_HLayout = new QHBoxLayout; m_HLayout->setSpacing(0); m_HLayout->setContentsMargins(0, 0, 0, 0); m_Input = new QLineEdit; m_Input->setToolTip( m_FilenameParam->GetDescription() ); connect( m_Input, SIGNAL(textChanged(const QString&)), this, SLOT(SetFileName(const QString&)) ); connect( m_Input, SIGNAL(textChanged(const QString&)), GetModel(), SLOT(NotifyUpdate()) ); m_HLayout->addWidget(m_Input); // Set up input text edit m_Button = new QPushButton; m_Button->setText("..."); m_Button->setToolTip("Select file..."); m_Button->setMaximumWidth(m_Button->width()); connect( m_Button, SIGNAL(clicked()), this, SLOT(SelectFile()) ); m_HLayout->addWidget(m_Button); this->setLayout(m_HLayout); } void QtWidgetOutputFilenameParameter::SelectFile() { QFileDialog fileDialog; fileDialog.setConfirmOverwrite(true); switch(m_FilenameParam->GetRole()) { case Role_Input: { //fileDialog.setFileMode(QFileDialog::ExistingFile); // FIXME: parameter's role is not suitable to separate "input file" names from "output file" names fileDialog.setFileMode(QFileDialog::AnyFile); } break; case Role_Output: { fileDialog.setFileMode(QFileDialog::AnyFile); } break; } fileDialog.setNameFilter("File (*)"); if (fileDialog.exec()) { this->SetFileName(fileDialog.selectedFiles().at(0)); m_Input->setText(fileDialog.selectedFiles().at(0)); } } void QtWidgetOutputFilenameParameter::SetFileName(const QString& value) { // save value m_FilenameParam->SetValue(static_cast<const char*>(value.toAscii())); // notify of value change QString key( m_FilenameParam->GetKey() ); emit ParameterChanged(key); } } } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ extern "C" { #include <png.h> } // boost #include <boost/python.hpp> #include <boost/python/module.hpp> #include <boost/python/def.hpp> #include <boost/make_shared.hpp> // mapnik #include <mapnik/graphics.hpp> #include <mapnik/palette.hpp> #include <mapnik/image_util.hpp> #include <mapnik/png_io.hpp> #include <mapnik/image_reader.hpp> #include <mapnik/image_compositing.hpp> // stl #include <sstream> // jpeg #if defined(HAVE_JPEG) #include <mapnik/jpeg_io.hpp> #endif // cairo #if defined(HAVE_CAIRO) && defined(HAVE_PYCAIRO) #include <cairomm/surface.h> #include <pycairo.h> #endif using mapnik::image_32; using mapnik::image_reader; using mapnik::get_image_reader; using mapnik::type_from_filename; using mapnik::save_to_file; using mapnik::save_to_string; using namespace boost::python; // output 'raw' pixels PyObject* tostring1( image_32 const& im) { int size = im.width() * im.height() * 4; return #if PY_VERSION_HEX >= 0x03000000 ::PyBytes_FromStringAndSize #else ::PyString_FromStringAndSize #endif ((const char*)im.raw_data(),size); } // encode (png,jpeg) PyObject* tostring2(image_32 const & im, std::string const& format) { std::string s = save_to_string(im, format); return #if PY_VERSION_HEX >= 0x03000000 ::PyBytes_FromStringAndSize #else ::PyString_FromStringAndSize #endif (s.data(),s.size()); } PyObject* tostring3(image_32 const & im, std::string const& format, mapnik::rgba_palette const& pal) { std::string s = save_to_string(im, format, pal); return #if PY_VERSION_HEX >= 0x03000000 ::PyBytes_FromStringAndSize #else ::PyString_FromStringAndSize #endif (s.data(),s.size()); } void save_to_file1(mapnik::image_32 const& im, std::string const& filename) { save_to_file(im,filename); } void save_to_file2(mapnik::image_32 const& im, std::string const& filename, std::string const& type) { save_to_file(im,filename,type); } void save_to_file3(mapnik::image_32 const& im, std::string const& filename, std::string const& type, mapnik::rgba_palette const& pal) { save_to_file(im,filename,type,pal); } bool painted(mapnik::image_32 const& im) { return im.painted(); } void set_pixel(mapnik::image_32 & im, unsigned x, unsigned y, mapnik::color const& c) { im.setPixel(x, y, c.rgba()); } boost::shared_ptr<image_32> open_from_file(std::string const& filename) { boost::optional<std::string> type = type_from_filename(filename); if (type) { std::auto_ptr<image_reader> reader(get_image_reader(filename,*type)); if (reader.get()) { boost::shared_ptr<image_32> image_ptr = boost::make_shared<image_32>(reader->width(),reader->height()); reader->read(0,0,image_ptr->data()); return image_ptr; } throw mapnik::image_reader_exception("Failed to load: " + filename); } throw mapnik::image_reader_exception("Unsupported image format:" + filename); } void blend (image_32 & im, unsigned x, unsigned y, image_32 const& im2, float opacity) { im.set_rectangle_alpha2(im2.data(),x,y,opacity); } void composite(image_32 & im, image_32 & im2, mapnik::composite_mode_e mode) { mapnik::composite(im.data(),im2.data(),mode); } #if defined(HAVE_CAIRO) && defined(HAVE_PYCAIRO) boost::shared_ptr<image_32> from_cairo(PycairoSurface* surface) { Cairo::RefPtr<Cairo::ImageSurface> s(new Cairo::ImageSurface(surface->surface)); boost::shared_ptr<image_32> image_ptr = boost::make_shared<image_32>(s); return image_ptr; } #endif void export_image() { using namespace boost::python; enum_<mapnik::composite_mode_e>("CompositeOp") .value("clear", mapnik::clear) .value("src", mapnik::src) .value("dst", mapnik::dst) .value("src_over", mapnik::src_over) .value("dst_over", mapnik::dst_over) .value("src_in", mapnik::src_in) .value("dst_in", mapnik::dst_in) .value("src_out", mapnik::src_out) .value("dst_out", mapnik::dst_out) .value("src_atop", mapnik::src_atop) .value("dst_atop", mapnik::dst_atop) .value("xor", mapnik::_xor) .value("plus", mapnik::plus) .value("minus", mapnik::minus) .value("multiply", mapnik::multiply) .value("screen", mapnik::screen) .value("overlay", mapnik::overlay) .value("darken", mapnik::darken) .value("lighten", mapnik::lighten) .value("color_dodge", mapnik::color_dodge) .value("color_burn", mapnik::color_burn) .value("hard_light", mapnik::hard_light) .value("soft_light", mapnik::soft_light) .value("difference", mapnik::difference) .value("exclusion", mapnik::exclusion) .value("contrast", mapnik::contrast) .value("invert", mapnik::invert) .value("invert_rgb", mapnik::invert_rgb) ; class_<image_32,boost::shared_ptr<image_32> >("Image","This class represents a 32 bit RGBA image.",init<int,int>()) .def("width",&image_32::width) .def("height",&image_32::height) .def("view",&image_32::get_view) .def("painted",&painted) .add_property("background",make_function (&image_32::get_background,return_value_policy<copy_const_reference>()), &image_32::set_background, "The background color of the image.") .def("set_grayscale_to_alpha",&image_32::set_grayscale_to_alpha, "Set the grayscale values to the alpha channel of the Image") .def("set_color_to_alpha",&image_32::set_color_to_alpha, "Set a given color to the alpha channel of the Image") .def("set_alpha",&image_32::set_alpha, "Set the overall alpha channel of the Image") .def("blend",&blend) .def("composite",&composite) .def("set_pixel",&set_pixel) //TODO(haoyu) The method name 'tostring' might be confusing since they actually return bytes in Python 3 .def("tostring",&tostring1) .def("tostring",&tostring2) .def("tostring",&tostring3) .def("save", &save_to_file1) .def("save", &save_to_file2) .def("save", &save_to_file3) .def("open",open_from_file) .staticmethod("open") #if defined(HAVE_CAIRO) && defined(HAVE_PYCAIRO) .def("from_cairo",&from_cairo) .staticmethod("from_cairo") #endif ; } <commit_msg>+ remove unused header<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ extern "C" { #include <png.h> } // boost #include <boost/python.hpp> #include <boost/python/module.hpp> #include <boost/python/def.hpp> #include <boost/make_shared.hpp> // mapnik #include <mapnik/graphics.hpp> #include <mapnik/palette.hpp> #include <mapnik/image_util.hpp> #include <mapnik/png_io.hpp> #include <mapnik/image_reader.hpp> #include <mapnik/image_compositing.hpp> // jpeg #if defined(HAVE_JPEG) #include <mapnik/jpeg_io.hpp> #endif // cairo #if defined(HAVE_CAIRO) && defined(HAVE_PYCAIRO) #include <cairomm/surface.h> #include <pycairo.h> #endif using mapnik::image_32; using mapnik::image_reader; using mapnik::get_image_reader; using mapnik::type_from_filename; using mapnik::save_to_file; using mapnik::save_to_string; using namespace boost::python; // output 'raw' pixels PyObject* tostring1( image_32 const& im) { int size = im.width() * im.height() * 4; return #if PY_VERSION_HEX >= 0x03000000 ::PyBytes_FromStringAndSize #else ::PyString_FromStringAndSize #endif ((const char*)im.raw_data(),size); } // encode (png,jpeg) PyObject* tostring2(image_32 const & im, std::string const& format) { std::string s = save_to_string(im, format); return #if PY_VERSION_HEX >= 0x03000000 ::PyBytes_FromStringAndSize #else ::PyString_FromStringAndSize #endif (s.data(),s.size()); } PyObject* tostring3(image_32 const & im, std::string const& format, mapnik::rgba_palette const& pal) { std::string s = save_to_string(im, format, pal); return #if PY_VERSION_HEX >= 0x03000000 ::PyBytes_FromStringAndSize #else ::PyString_FromStringAndSize #endif (s.data(),s.size()); } void save_to_file1(mapnik::image_32 const& im, std::string const& filename) { save_to_file(im,filename); } void save_to_file2(mapnik::image_32 const& im, std::string const& filename, std::string const& type) { save_to_file(im,filename,type); } void save_to_file3(mapnik::image_32 const& im, std::string const& filename, std::string const& type, mapnik::rgba_palette const& pal) { save_to_file(im,filename,type,pal); } bool painted(mapnik::image_32 const& im) { return im.painted(); } void set_pixel(mapnik::image_32 & im, unsigned x, unsigned y, mapnik::color const& c) { im.setPixel(x, y, c.rgba()); } boost::shared_ptr<image_32> open_from_file(std::string const& filename) { boost::optional<std::string> type = type_from_filename(filename); if (type) { std::auto_ptr<image_reader> reader(get_image_reader(filename,*type)); if (reader.get()) { boost::shared_ptr<image_32> image_ptr = boost::make_shared<image_32>(reader->width(),reader->height()); reader->read(0,0,image_ptr->data()); return image_ptr; } throw mapnik::image_reader_exception("Failed to load: " + filename); } throw mapnik::image_reader_exception("Unsupported image format:" + filename); } void blend (image_32 & im, unsigned x, unsigned y, image_32 const& im2, float opacity) { im.set_rectangle_alpha2(im2.data(),x,y,opacity); } void composite(image_32 & im, image_32 & im2, mapnik::composite_mode_e mode) { mapnik::composite(im.data(),im2.data(),mode); } #if defined(HAVE_CAIRO) && defined(HAVE_PYCAIRO) boost::shared_ptr<image_32> from_cairo(PycairoSurface* surface) { Cairo::RefPtr<Cairo::ImageSurface> s(new Cairo::ImageSurface(surface->surface)); boost::shared_ptr<image_32> image_ptr = boost::make_shared<image_32>(s); return image_ptr; } #endif void export_image() { using namespace boost::python; enum_<mapnik::composite_mode_e>("CompositeOp") .value("clear", mapnik::clear) .value("src", mapnik::src) .value("dst", mapnik::dst) .value("src_over", mapnik::src_over) .value("dst_over", mapnik::dst_over) .value("src_in", mapnik::src_in) .value("dst_in", mapnik::dst_in) .value("src_out", mapnik::src_out) .value("dst_out", mapnik::dst_out) .value("src_atop", mapnik::src_atop) .value("dst_atop", mapnik::dst_atop) .value("xor", mapnik::_xor) .value("plus", mapnik::plus) .value("minus", mapnik::minus) .value("multiply", mapnik::multiply) .value("screen", mapnik::screen) .value("overlay", mapnik::overlay) .value("darken", mapnik::darken) .value("lighten", mapnik::lighten) .value("color_dodge", mapnik::color_dodge) .value("color_burn", mapnik::color_burn) .value("hard_light", mapnik::hard_light) .value("soft_light", mapnik::soft_light) .value("difference", mapnik::difference) .value("exclusion", mapnik::exclusion) .value("contrast", mapnik::contrast) .value("invert", mapnik::invert) .value("invert_rgb", mapnik::invert_rgb) ; class_<image_32,boost::shared_ptr<image_32> >("Image","This class represents a 32 bit RGBA image.",init<int,int>()) .def("width",&image_32::width) .def("height",&image_32::height) .def("view",&image_32::get_view) .def("painted",&painted) .add_property("background",make_function (&image_32::get_background,return_value_policy<copy_const_reference>()), &image_32::set_background, "The background color of the image.") .def("set_grayscale_to_alpha",&image_32::set_grayscale_to_alpha, "Set the grayscale values to the alpha channel of the Image") .def("set_color_to_alpha",&image_32::set_color_to_alpha, "Set a given color to the alpha channel of the Image") .def("set_alpha",&image_32::set_alpha, "Set the overall alpha channel of the Image") .def("blend",&blend) .def("composite",&composite) .def("set_pixel",&set_pixel) //TODO(haoyu) The method name 'tostring' might be confusing since they actually return bytes in Python 3 .def("tostring",&tostring1) .def("tostring",&tostring2) .def("tostring",&tostring3) .def("save", &save_to_file1) .def("save", &save_to_file2) .def("save", &save_to_file3) .def("open",open_from_file) .staticmethod("open") #if defined(HAVE_CAIRO) && defined(HAVE_PYCAIRO) .def("from_cairo",&from_cairo) .staticmethod("from_cairo") #endif ; } <|endoftext|>
<commit_before> #include <util/util.h> #include "grammar-builder.h" #include "../declaration.h" #include "../type.h" #include "../grammar.h" #include "../production.h" #include "../attribute.h" #include "../expression.h" #include "../constant.h" using namespace binpac; using namespace binpac::passes; GrammarBuilder::GrammarBuilder(std::ostream& out) : ast::Pass<AstInfo, shared_ptr<Production>>("binpac::GrammarBuilder", false), _debug_out(out) { } GrammarBuilder::~GrammarBuilder() { } bool GrammarBuilder::run(shared_ptr<ast::NodeBase> ast) { _in_decl = 0;; _counters.clear(); return processAllPreOrder(ast); } void GrammarBuilder::enableDebug() { _debug = true; } GrammarBuilder::production_map GrammarBuilder::_compiled; shared_ptr<Production> GrammarBuilder::compileOne(shared_ptr<Node> n) { auto p = _compiled.find(n); if ( p != _compiled.end() ) return p->second; _compiled.insert(std::make_pair(n, std::make_shared<production::Unknown>(n))); shared_ptr<Production> production = nullptr; bool success = processOne(n, &production); assert(success); assert(production); _compiled.erase(n); _compiled.insert(std::make_pair(n, production)); return production; } void GrammarBuilder::_resolveUnknown(shared_ptr<Production> production) { auto unknown = ast::tryCast<production::Unknown>(production); if ( unknown ) { auto n = unknown->node(); auto p = _compiled.find(n); assert( p != _compiled.end()); production->replace(n); } for ( auto c : production->childs() ) { if ( ast::isA<Production>(c) ) _resolveUnknown(c->sharedPtr<binpac::Production>()); } } string GrammarBuilder::counter(const string& key) { auto cnt = 1; auto i = _counters.find(key); if ( i != _counters.end() ) cnt = i->second; string s = util::fmt("%s%d", key.c_str(), cnt++); _counters[key] = cnt; return s; } void GrammarBuilder::visit(declaration::Type* d) { // We are only interested in unit declarations. auto unit = ast::tryCast<type::Unit>(d->type()); if ( ! unit ) return; ++_in_decl; auto production = compileOne(unit); --_in_decl; _resolveUnknown(production); auto grammar = std::make_shared<Grammar>(d->id()->name(), production); if ( _debug ) grammar->printTables(_debug_out, true); unit->setGrammar(grammar); } void GrammarBuilder::visit(type::Unit* u) { if ( ! _in_decl ) return; auto prods = Production::production_list(); for ( auto f : u->fields() ) prods.push_back(compileOne(f)); string name; if ( u->id() ) name = u->id()->name(); else name = util::fmt("unit%d", _unit_counter++); auto unit = std::make_shared<production::Sequence>(name, prods, u->sharedPtr<type::Unit>(), u->location()); setResult(unit); } void GrammarBuilder::visit(type::unit::item::field::Constant* c) { if ( ! _in_decl ) return; auto sym = "const:" + c->id()->name(); auto prod = std::make_shared<production::Constant>(sym, c->constant()); prod->pgMeta()->field = c->sharedPtr<type::unit::item::Field>(); setResult(prod); } void GrammarBuilder::visit(type::unit::item::field::Ctor* c) { if ( ! _in_decl ) return; auto sym = "ctor:" + c->id()->name(); auto prod = std::make_shared<production::Ctor>(sym, c->ctor()); prod->pgMeta()->field = c->sharedPtr<type::unit::item::Field>(); setResult(prod); } void GrammarBuilder::visit(type::unit::item::field::Switch* s) { if ( ! _in_decl ) return; production::Switch::case_list cases; shared_ptr<Production> default_ = nullptr; for ( auto c : s->cases() ) { if ( c->default_() ) { default_ = compileOne(c); continue; } auto pcase = std::make_pair(c->expressions(), compileOne(c)); cases.push_back(pcase); } auto sym = "switch:" + s->id()->name(); auto prod = std::make_shared<production::Switch>(sym, s->expression(), cases, default_, s->location()); prod->pgMeta()->field = s->sharedPtr<type::unit::item::Field>(); setResult(prod); } void GrammarBuilder::visit(type::unit::item::field::AtomicType* t) { if ( ! _in_decl ) return; shared_ptr<Production> prod; if ( ast::isA<type::EmbeddedObject>(t->type()) ) { // Not quite clear if there's a nicer way to present these than // special-casing them here. auto sym = "type:" + t->id()->name(); prod = std::make_shared<production::TypeLiteral>(sym, t->type()); } else { auto sym = "var:" + t->id()->name(); prod = std::make_shared<production::Variable>(sym, t->type()); } prod->pgMeta()->field = t->sharedPtr<type::unit::item::Field>(); setResult(prod); } void GrammarBuilder::visit(type::unit::item::field::Unit* u) { if ( ! _in_decl ) return; ++_in_decl; auto chprod = compileOne(u->type()); --_in_decl; string name; if ( u->id() ) name = u->id()->name(); else name = util::fmt("unit%d", _unit_counter++); assert(ast::isA<Production>(chprod)); auto child = std::make_shared<production::ChildGrammar>(name, chprod, ast::checkedCast<type::Unit>(u->type()), u->location()); child->pgMeta()->field = u->sharedPtr<type::unit::item::field::Unit>(); setResult(child); } void GrammarBuilder::visit(type::unit::item::field::switch_::Case* c) { if ( ! _in_decl ) return; auto prods = Production::production_list(); for ( auto i : c->items() ) prods.push_back(compileOne(i)); auto name = util::fmt("case%d", _case_counter++); auto seq = std::make_shared<production::Sequence>(name, prods, nullptr, c->location()); setResult(seq); } void GrammarBuilder::visit(type::unit::item::field::container::List* l) { if ( ! _in_decl ) return; auto until = l->attributes()->lookup("until"); auto until_including = l->attributes()->lookup("until_including"); auto while_ = l->attributes()->lookup("while"); auto count = l->attributes()->lookup("count"); auto length = l->attributes()->lookup("length"); auto sym = "list:" + l->id()->name(); ++_in_decl; auto field = compileOne(l->field()); field->setContainer(l->sharedPtr<type::unit::item::field::Container>()); --_in_decl; if ( until || while_ || until_including ) { // We use a Loop production here. type::Container installs a &foreach // hook that stops the iteration once the condition is satisfied. // Doing it this way allows the condition to run in the hook's scope, // with access to "$$". auto l1 = std::make_shared<production::Loop>(sym, field, false, l->location()); l1->pgMeta()->field = l->sharedPtr<type::unit::item::Field>(); setResult(l1); } else if ( count ) { auto l1 = std::make_shared<production::Counter>(sym, count->value(), field, l->location()); l1->pgMeta()->field = l->sharedPtr<type::unit::item::Field>(); setResult(l1); } else if ( length ) { auto l1 = std::make_shared<production::Loop>(sym, field, true, l->location()); auto l2 = std::make_shared<production::ByteBlock>(sym, length->value(), l1, l->location()); l1->pgMeta()->field = l->sharedPtr<type::unit::item::Field>(); setResult(l2); } else { // No attributes, use look-ahead to figure out when to stop parsing. // // Left-factored & right-recursive. // // List1 -> Item List2 // List2 -> Epsilon | List1 auto epsilon = std::make_shared<production::Epsilon>(l->location()); auto l1 = std::make_shared<production::Sequence>(sym + ":l1", Production::production_list(), nullptr, l->location()); auto l2 = std::make_shared<production::LookAhead>(sym + ":l2", epsilon, l1, l->location()); l1->add(field); l1->add(l2); auto c = std::make_shared<production::Enclosure>(sym, l2, l->location()); c->pgMeta()->field = l->sharedPtr<type::unit::item::Field>(); field->pgMeta()->for_each = c->pgMeta()->field; setResult(c); } } void GrammarBuilder::visit(type::unit::item::field::container::Vector* v) { if ( ! _in_decl ) return; auto length = v->length(); auto sym = "vector:" + v->id()->name(); ++_in_decl; auto field = compileOne(v->field()); field->setContainer(v->sharedPtr<type::unit::item::field::Container>()); --_in_decl; auto l1 = std::make_shared<production::Counter>(sym, v->length(), field, v->location()); l1->pgMeta()->field = v->sharedPtr<type::unit::item::Field>(); setResult(l1); } <commit_msg>Fixing regression introduced with sync support.<commit_after> #include <util/util.h> #include "grammar-builder.h" #include "../declaration.h" #include "../type.h" #include "../grammar.h" #include "../production.h" #include "../attribute.h" #include "../expression.h" #include "../constant.h" using namespace binpac; using namespace binpac::passes; GrammarBuilder::GrammarBuilder(std::ostream& out) : ast::Pass<AstInfo, shared_ptr<Production>>("binpac::GrammarBuilder", false), _debug_out(out) { } GrammarBuilder::~GrammarBuilder() { } bool GrammarBuilder::run(shared_ptr<ast::NodeBase> ast) { _in_decl = 0;; _counters.clear(); return processAllPreOrder(ast); } void GrammarBuilder::enableDebug() { _debug = true; } GrammarBuilder::production_map GrammarBuilder::_compiled; shared_ptr<Production> GrammarBuilder::compileOne(shared_ptr<Node> n) { auto p = _compiled.find(n); if ( p != _compiled.end() ) return p->second; _compiled.insert(std::make_pair(n, std::make_shared<production::Unknown>(n))); shared_ptr<Production> production = nullptr; bool success = processOne(n, &production); assert(success); assert(production); _compiled.erase(n); _compiled.insert(std::make_pair(n, production)); return production; } void GrammarBuilder::_resolveUnknown(shared_ptr<Production> production) { auto unknown = ast::tryCast<production::Unknown>(production); if ( unknown ) { auto n = unknown->node(); auto p = _compiled.find(n); assert( p != _compiled.end()); if ( ast::isA<Production>(n) ) production->replace(n); } for ( auto c : production->childs() ) { if ( ast::isA<Production>(c) ) _resolveUnknown(c->sharedPtr<binpac::Production>()); } } string GrammarBuilder::counter(const string& key) { auto cnt = 1; auto i = _counters.find(key); if ( i != _counters.end() ) cnt = i->second; string s = util::fmt("%s%d", key.c_str(), cnt++); _counters[key] = cnt; return s; } void GrammarBuilder::visit(declaration::Type* d) { // We are only interested in unit declarations. auto unit = ast::tryCast<type::Unit>(d->type()); if ( ! unit ) return; ++_in_decl; auto production = compileOne(unit); --_in_decl; _resolveUnknown(production); auto grammar = std::make_shared<Grammar>(d->id()->name(), production); if ( _debug ) grammar->printTables(_debug_out, true); unit->setGrammar(grammar); } void GrammarBuilder::visit(type::Unit* u) { if ( ! _in_decl ) return; auto prods = Production::production_list(); for ( auto f : u->fields() ) prods.push_back(compileOne(f)); string name; if ( u->id() ) name = u->id()->name(); else name = util::fmt("unit%d", _unit_counter++); auto unit = std::make_shared<production::Sequence>(name, prods, u->sharedPtr<type::Unit>(), u->location()); setResult(unit); } void GrammarBuilder::visit(type::unit::item::field::Constant* c) { if ( ! _in_decl ) return; auto sym = "const:" + c->id()->name(); auto prod = std::make_shared<production::Constant>(sym, c->constant()); prod->pgMeta()->field = c->sharedPtr<type::unit::item::Field>(); setResult(prod); } void GrammarBuilder::visit(type::unit::item::field::Ctor* c) { if ( ! _in_decl ) return; auto sym = "ctor:" + c->id()->name(); auto prod = std::make_shared<production::Ctor>(sym, c->ctor()); prod->pgMeta()->field = c->sharedPtr<type::unit::item::Field>(); setResult(prod); } void GrammarBuilder::visit(type::unit::item::field::Switch* s) { if ( ! _in_decl ) return; production::Switch::case_list cases; shared_ptr<Production> default_ = nullptr; for ( auto c : s->cases() ) { if ( c->default_() ) { default_ = compileOne(c); continue; } auto pcase = std::make_pair(c->expressions(), compileOne(c)); cases.push_back(pcase); } auto sym = "switch:" + s->id()->name(); auto prod = std::make_shared<production::Switch>(sym, s->expression(), cases, default_, s->location()); prod->pgMeta()->field = s->sharedPtr<type::unit::item::Field>(); setResult(prod); } void GrammarBuilder::visit(type::unit::item::field::AtomicType* t) { if ( ! _in_decl ) return; shared_ptr<Production> prod; if ( ast::isA<type::EmbeddedObject>(t->type()) ) { // Not quite clear if there's a nicer way to present these than // special-casing them here. auto sym = "type:" + t->id()->name(); prod = std::make_shared<production::TypeLiteral>(sym, t->type()); } else { auto sym = "var:" + t->id()->name(); prod = std::make_shared<production::Variable>(sym, t->type()); } prod->pgMeta()->field = t->sharedPtr<type::unit::item::Field>(); setResult(prod); } void GrammarBuilder::visit(type::unit::item::field::Unit* u) { if ( ! _in_decl ) return; ++_in_decl; auto chprod = compileOne(u->type()); --_in_decl; string name; if ( u->id() ) name = u->id()->name(); else name = util::fmt("unit%d", _unit_counter++); assert(ast::isA<Production>(chprod)); auto child = std::make_shared<production::ChildGrammar>(name, chprod, ast::checkedCast<type::Unit>(u->type()), u->location()); child->pgMeta()->field = u->sharedPtr<type::unit::item::field::Unit>(); setResult(child); } void GrammarBuilder::visit(type::unit::item::field::switch_::Case* c) { if ( ! _in_decl ) return; auto prods = Production::production_list(); for ( auto i : c->items() ) prods.push_back(compileOne(i)); auto name = util::fmt("case%d", _case_counter++); auto seq = std::make_shared<production::Sequence>(name, prods, nullptr, c->location()); setResult(seq); } void GrammarBuilder::visit(type::unit::item::field::container::List* l) { if ( ! _in_decl ) return; auto until = l->attributes()->lookup("until"); auto until_including = l->attributes()->lookup("until_including"); auto while_ = l->attributes()->lookup("while"); auto count = l->attributes()->lookup("count"); auto length = l->attributes()->lookup("length"); auto sym = "list:" + l->id()->name(); ++_in_decl; auto field = compileOne(l->field()); field->setContainer(l->sharedPtr<type::unit::item::field::Container>()); --_in_decl; if ( until || while_ || until_including ) { // We use a Loop production here. type::Container installs a &foreach // hook that stops the iteration once the condition is satisfied. // Doing it this way allows the condition to run in the hook's scope, // with access to "$$". auto l1 = std::make_shared<production::Loop>(sym, field, false, l->location()); l1->pgMeta()->field = l->sharedPtr<type::unit::item::Field>(); setResult(l1); } else if ( count ) { auto l1 = std::make_shared<production::Counter>(sym, count->value(), field, l->location()); l1->pgMeta()->field = l->sharedPtr<type::unit::item::Field>(); setResult(l1); } else if ( length ) { auto l1 = std::make_shared<production::Loop>(sym, field, true, l->location()); auto l2 = std::make_shared<production::ByteBlock>(sym, length->value(), l1, l->location()); l1->pgMeta()->field = l->sharedPtr<type::unit::item::Field>(); setResult(l2); } else { // No attributes, use look-ahead to figure out when to stop parsing. // // Left-factored & right-recursive. // // List1 -> Item List2 // List2 -> Epsilon | List1 auto epsilon = std::make_shared<production::Epsilon>(l->location()); auto l1 = std::make_shared<production::Sequence>(sym + ":l1", Production::production_list(), nullptr, l->location()); auto l2 = std::make_shared<production::LookAhead>(sym + ":l2", epsilon, l1, l->location()); l1->add(field); l1->add(l2); auto c = std::make_shared<production::Enclosure>(sym, l2, l->location()); c->pgMeta()->field = l->sharedPtr<type::unit::item::Field>(); field->pgMeta()->for_each = c->pgMeta()->field; setResult(c); } } void GrammarBuilder::visit(type::unit::item::field::container::Vector* v) { if ( ! _in_decl ) return; auto length = v->length(); auto sym = "vector:" + v->id()->name(); ++_in_decl; auto field = compileOne(v->field()); field->setContainer(v->sharedPtr<type::unit::item::field::Container>()); --_in_decl; auto l1 = std::make_shared<production::Counter>(sym, v->length(), field, v->location()); l1->pgMeta()->field = v->sharedPtr<type::unit::item::Field>(); setResult(l1); } <|endoftext|>
<commit_before>/* Copyright 2016 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow_serving/resources/resource_tracker.h" #include <algorithm> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/lib/core/status_test_util.h" #include "tensorflow/core/platform/google/integral_types.h" #include "tensorflow/core/platform/types.h" #include "tensorflow_serving/core/test_util/mock_loader.h" #include "tensorflow_serving/resources/resources.pb.h" #include "tensorflow_serving/test_util/test_util.h" #include "tensorflow_serving/util/any_ptr.h" using ::tensorflow::serving::test_util::CreateProto; using ::tensorflow::serving::test_util::EqualsProto; using ::testing::_; using ::testing::Return; using ::testing::NiceMock; namespace tensorflow { namespace serving { namespace { class ResourceTrackerTest : public ::testing::Test { protected: ResourceTrackerTest() : total_resources_( CreateProto<ResourceAllocation>("resource_quantities { " " resource { " " device: 'cpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 16 " "} " "resource_quantities { " " resource { " " device: 'gpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 16 " "} " "resource_quantities { " " resource { " " device: 'gpu' " " device_instance { value: 1 } " " kind: 'ram' " " } " " quantity: 16 " "} ")) { std::unique_ptr<ResourceUtil> util( new ResourceUtil({{{"cpu", 1}, {"gpu", 2}}})); TF_CHECK_OK(ResourceTracker::Create( total_resources_, std::unique_ptr<ResourceUtil>(std::move(util)), &tracker_)); loader_0_.reset(new NiceMock<test_util::MockLoader>); ON_CALL(*loader_0_, EstimateResources()) .WillByDefault(Return( CreateProto<ResourceAllocation>("resource_quantities { " " resource { " " device: 'cpu' " " kind: 'ram' " " } " " quantity: 1 " "} " "resource_quantities { " " resource { " " device: 'gpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 3 " "} "))); loader_1_.reset(new NiceMock<test_util::MockLoader>); ON_CALL(*loader_1_, EstimateResources()) .WillByDefault(Return( CreateProto<ResourceAllocation>("resource_quantities { " " resource { " " device: 'cpu' " " kind: 'ram' " " } " " quantity: 5 " "} " "resource_quantities { " " resource { " " device: 'gpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 7 " "} "))); loader_2_.reset(new NiceMock<test_util::MockLoader>); ON_CALL(*loader_2_, EstimateResources()) .WillByDefault(Return( CreateProto<ResourceAllocation>("resource_quantities { " " resource { " " device: 'cpu' " " kind: 'ram' " " } " " quantity: 15 " "} "))); loader_3_.reset(new NiceMock<test_util::MockLoader>); ON_CALL(*loader_3_, EstimateResources()) .WillByDefault( Return(CreateProto<ResourceAllocation>("resource_quantities { " " resource { " " device: 'gpu' " " kind: 'ram' " " } " " quantity: 12 " "} "))); invalid_resources_loader_.reset(new NiceMock<test_util::MockLoader>); ON_CALL(*invalid_resources_loader_, EstimateResources()) .WillByDefault(Return( CreateProto<ResourceAllocation>("resource_quantities { " " resource { " " device: 'bogus_device' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 4 " "} "))); // Disallow calls to Load()/Unload(). for (auto* loader : {loader_0_.get(), loader_1_.get(), loader_2_.get(), loader_3_.get(), invalid_resources_loader_.get()}) { EXPECT_CALL(*loader, Load(_)).Times(0); EXPECT_CALL(*loader, Unload()).Times(0); } } // The original total-resources valued provided to 'tracker_'. const ResourceAllocation total_resources_; // The object under testing. std::unique_ptr<ResourceTracker> tracker_; // Some mock loaders with specific resource estimates (see the constructor). std::unique_ptr<test_util::MockLoader> loader_0_; std::unique_ptr<test_util::MockLoader> loader_1_; std::unique_ptr<test_util::MockLoader> loader_2_; std::unique_ptr<test_util::MockLoader> loader_3_; std::unique_ptr<test_util::MockLoader> invalid_resources_loader_; }; TEST_F(ResourceTrackerTest, UnboundTotalResources) { std::unique_ptr<ResourceUtil> util( new ResourceUtil({{{"cpu", 1}, {"gpu", 2}}})); std::unique_ptr<ResourceTracker> tracker; const auto unbound_resources = CreateProto<ResourceAllocation>( "resource_quantities { " " resource { " " device: 'gpu' " " kind: 'ram' " " } " " quantity: 12 " "} "); EXPECT_FALSE(ResourceTracker::Create( unbound_resources, std::unique_ptr<ResourceUtil>(std::move(util)), &tracker) .ok()); } TEST_F(ResourceTrackerTest, UnnormalizedTotalResources) { std::unique_ptr<ResourceUtil> util( new ResourceUtil({{{"cpu", 1}, {"gpu", 2}}})); std::unique_ptr<ResourceTracker> tracker; const auto unnormalized_resources = CreateProto<ResourceAllocation>( "resource_quantities { " " resource { " " device: 'cpu' " " kind: 'ram' " " } " " quantity: 12 " "} "); TF_ASSERT_OK(ResourceTracker::Create( unnormalized_resources, std::unique_ptr<ResourceUtil>(std::move(util)), &tracker)); // The total_resources proto should get normalized. EXPECT_THAT(tracker->total_resources(), EqualsProto("resource_quantities { " " resource { " " device: 'cpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 12 " "} ")); } TEST_F(ResourceTrackerTest, RecomputeUsedResources) { // Verify the initial state. EXPECT_THAT(tracker_->used_resources(), EqualsProto("")); EXPECT_THAT(tracker_->total_resources(), EqualsProto(total_resources_)); // Recompute used resources for {loader_0_, loader_1_, loader_3_}. TF_ASSERT_OK(tracker_->RecomputeUsedResources( {loader_0_.get(), loader_1_.get(), loader_3_.get()})); EXPECT_THAT(tracker_->used_resources(), EqualsProto("resource_quantities { " " resource { " " device: 'cpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 6 " "} " "resource_quantities { " " resource { " " device: 'gpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 10 " "} " "resource_quantities { " " resource { " " device: 'gpu' " " kind: 'ram' " " } " " quantity: 12 " "} ")); EXPECT_THAT(tracker_->total_resources(), EqualsProto(total_resources_)); // Recompute used resources for just {loader_0_}. TF_ASSERT_OK(tracker_->RecomputeUsedResources({loader_0_.get()})); EXPECT_THAT(tracker_->used_resources(), EqualsProto("resource_quantities { " " resource { " " device: 'cpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 1 " "} " "resource_quantities { " " resource { " " device: 'gpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 3 " "} ")); EXPECT_THAT(tracker_->total_resources(), EqualsProto(total_resources_)); } TEST_F(ResourceTrackerTest, ReserveResourcesSuccessWithUsedResourcesBound) { TF_ASSERT_OK(tracker_->RecomputeUsedResources({loader_0_.get()})); EXPECT_THAT(tracker_->used_resources(), EqualsProto("resource_quantities { " " resource { " " device: 'cpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 1 " "} " "resource_quantities { " " resource { " " device: 'gpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 3 " "} ")); // If just loader_0_ is loaded, loader_2_ should also fit. bool success; TF_ASSERT_OK(tracker_->ReserveResources(*loader_2_, &success)); EXPECT_TRUE(success); EXPECT_THAT(tracker_->used_resources(), EqualsProto("resource_quantities { " " resource { " " device: 'cpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 16 " "} " "resource_quantities { " " resource { " " device: 'gpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 3 " "} ")); EXPECT_THAT(tracker_->total_resources(), EqualsProto(total_resources_)); } TEST_F(ResourceTrackerTest, ReserveResourcesFailureWithUsedResourcesBound) { TF_ASSERT_OK(tracker_->RecomputeUsedResources({loader_1_.get()})); EXPECT_THAT(tracker_->used_resources(), EqualsProto("resource_quantities { " " resource { " " device: 'cpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 5 " "} " "resource_quantities { " " resource { " " device: 'gpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 7 " "} ")); // If loader_1_ is loaded, there isn't room for loader_2_. bool success; TF_ASSERT_OK(tracker_->ReserveResources(*loader_2_, &success)); EXPECT_FALSE(success); // The used resources should remain unchanged (i.e. only reflect loader_1_). EXPECT_THAT(tracker_->used_resources(), EqualsProto("resource_quantities { " " resource { " " device: 'cpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 5 " "} " "resource_quantities { " " resource { " " device: 'gpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 7 " "} ")); EXPECT_THAT(tracker_->total_resources(), EqualsProto(total_resources_)); } TEST_F(ResourceTrackerTest, ReserveResourcesSuccessWithUsedResourcesUnbound) { TF_ASSERT_OK(tracker_->RecomputeUsedResources({loader_3_.get()})); EXPECT_THAT(tracker_->used_resources(), EqualsProto("resource_quantities { " " resource { " " device: 'gpu' " " kind: 'ram' " " } " " quantity: 12 " "} ")); // If just loader_3_ is loaded, loader_0_ should also fit. bool success; TF_ASSERT_OK(tracker_->ReserveResources(*loader_0_, &success)); EXPECT_TRUE(success); EXPECT_THAT(tracker_->used_resources(), EqualsProto("resource_quantities { " " resource { " " device: 'gpu' " " kind: 'ram' " " } " " quantity: 12 " "} " "resource_quantities { " " resource { " " device: 'cpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 1 " "} " "resource_quantities { " " resource { " " device: 'gpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 3 " "} ")); EXPECT_THAT(tracker_->total_resources(), EqualsProto(total_resources_)); } TEST_F(ResourceTrackerTest, ReserveResourcesFailureWithUsedResourcesUnbound) { TF_ASSERT_OK(tracker_->RecomputeUsedResources({loader_3_.get()})); EXPECT_THAT(tracker_->used_resources(), EqualsProto("resource_quantities { " " resource { " " device: 'gpu' " " kind: 'ram' " " } " " quantity: 12 " "} ")); // If loader_3_ is loaded, there isn't room for loader_1_, or for another // copy of loader_3_. bool success; TF_ASSERT_OK(tracker_->ReserveResources(*loader_1_, &success)); EXPECT_FALSE(success); TF_ASSERT_OK(tracker_->ReserveResources(*loader_3_, &success)); EXPECT_FALSE(success); // The used resources should remain unchanged (i.e. only reflect a single copy // of loader_3_). EXPECT_THAT(tracker_->used_resources(), EqualsProto("resource_quantities { " " resource { " " device: 'gpu' " " kind: 'ram' " " } " " quantity: 12 " "} ")); EXPECT_THAT(tracker_->total_resources(), EqualsProto(total_resources_)); } TEST_F(ResourceTrackerTest, InvalidResourceEstimate) { bool success; EXPECT_FALSE( tracker_->ReserveResources(*invalid_resources_loader_, &success).ok()); EXPECT_FALSE(tracker_ ->RecomputeUsedResources( {loader_0_.get(), invalid_resources_loader_.get()}) .ok()); } } // namespace } // namespace serving } // namespace tensorflow <commit_msg>Fix open source build. Change: 117845225<commit_after>/* Copyright 2016 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow_serving/resources/resource_tracker.h" #include <algorithm> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/lib/core/status_test_util.h" #include "tensorflow/core/platform/types.h" #include "tensorflow_serving/core/test_util/mock_loader.h" #include "tensorflow_serving/resources/resources.pb.h" #include "tensorflow_serving/test_util/test_util.h" #include "tensorflow_serving/util/any_ptr.h" using ::tensorflow::serving::test_util::CreateProto; using ::tensorflow::serving::test_util::EqualsProto; using ::testing::_; using ::testing::Return; using ::testing::NiceMock; namespace tensorflow { namespace serving { namespace { class ResourceTrackerTest : public ::testing::Test { protected: ResourceTrackerTest() : total_resources_( CreateProto<ResourceAllocation>("resource_quantities { " " resource { " " device: 'cpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 16 " "} " "resource_quantities { " " resource { " " device: 'gpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 16 " "} " "resource_quantities { " " resource { " " device: 'gpu' " " device_instance { value: 1 } " " kind: 'ram' " " } " " quantity: 16 " "} ")) { std::unique_ptr<ResourceUtil> util( new ResourceUtil({{{"cpu", 1}, {"gpu", 2}}})); TF_CHECK_OK(ResourceTracker::Create( total_resources_, std::unique_ptr<ResourceUtil>(std::move(util)), &tracker_)); loader_0_.reset(new NiceMock<test_util::MockLoader>); ON_CALL(*loader_0_, EstimateResources()) .WillByDefault(Return( CreateProto<ResourceAllocation>("resource_quantities { " " resource { " " device: 'cpu' " " kind: 'ram' " " } " " quantity: 1 " "} " "resource_quantities { " " resource { " " device: 'gpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 3 " "} "))); loader_1_.reset(new NiceMock<test_util::MockLoader>); ON_CALL(*loader_1_, EstimateResources()) .WillByDefault(Return( CreateProto<ResourceAllocation>("resource_quantities { " " resource { " " device: 'cpu' " " kind: 'ram' " " } " " quantity: 5 " "} " "resource_quantities { " " resource { " " device: 'gpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 7 " "} "))); loader_2_.reset(new NiceMock<test_util::MockLoader>); ON_CALL(*loader_2_, EstimateResources()) .WillByDefault(Return( CreateProto<ResourceAllocation>("resource_quantities { " " resource { " " device: 'cpu' " " kind: 'ram' " " } " " quantity: 15 " "} "))); loader_3_.reset(new NiceMock<test_util::MockLoader>); ON_CALL(*loader_3_, EstimateResources()) .WillByDefault( Return(CreateProto<ResourceAllocation>("resource_quantities { " " resource { " " device: 'gpu' " " kind: 'ram' " " } " " quantity: 12 " "} "))); invalid_resources_loader_.reset(new NiceMock<test_util::MockLoader>); ON_CALL(*invalid_resources_loader_, EstimateResources()) .WillByDefault(Return( CreateProto<ResourceAllocation>("resource_quantities { " " resource { " " device: 'bogus_device' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 4 " "} "))); // Disallow calls to Load()/Unload(). for (auto* loader : {loader_0_.get(), loader_1_.get(), loader_2_.get(), loader_3_.get(), invalid_resources_loader_.get()}) { EXPECT_CALL(*loader, Load(_)).Times(0); EXPECT_CALL(*loader, Unload()).Times(0); } } // The original total-resources valued provided to 'tracker_'. const ResourceAllocation total_resources_; // The object under testing. std::unique_ptr<ResourceTracker> tracker_; // Some mock loaders with specific resource estimates (see the constructor). std::unique_ptr<test_util::MockLoader> loader_0_; std::unique_ptr<test_util::MockLoader> loader_1_; std::unique_ptr<test_util::MockLoader> loader_2_; std::unique_ptr<test_util::MockLoader> loader_3_; std::unique_ptr<test_util::MockLoader> invalid_resources_loader_; }; TEST_F(ResourceTrackerTest, UnboundTotalResources) { std::unique_ptr<ResourceUtil> util( new ResourceUtil({{{"cpu", 1}, {"gpu", 2}}})); std::unique_ptr<ResourceTracker> tracker; const auto unbound_resources = CreateProto<ResourceAllocation>( "resource_quantities { " " resource { " " device: 'gpu' " " kind: 'ram' " " } " " quantity: 12 " "} "); EXPECT_FALSE(ResourceTracker::Create( unbound_resources, std::unique_ptr<ResourceUtil>(std::move(util)), &tracker) .ok()); } TEST_F(ResourceTrackerTest, UnnormalizedTotalResources) { std::unique_ptr<ResourceUtil> util( new ResourceUtil({{{"cpu", 1}, {"gpu", 2}}})); std::unique_ptr<ResourceTracker> tracker; const auto unnormalized_resources = CreateProto<ResourceAllocation>( "resource_quantities { " " resource { " " device: 'cpu' " " kind: 'ram' " " } " " quantity: 12 " "} "); TF_ASSERT_OK(ResourceTracker::Create( unnormalized_resources, std::unique_ptr<ResourceUtil>(std::move(util)), &tracker)); // The total_resources proto should get normalized. EXPECT_THAT(tracker->total_resources(), EqualsProto("resource_quantities { " " resource { " " device: 'cpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 12 " "} ")); } TEST_F(ResourceTrackerTest, RecomputeUsedResources) { // Verify the initial state. EXPECT_THAT(tracker_->used_resources(), EqualsProto("")); EXPECT_THAT(tracker_->total_resources(), EqualsProto(total_resources_)); // Recompute used resources for {loader_0_, loader_1_, loader_3_}. TF_ASSERT_OK(tracker_->RecomputeUsedResources( {loader_0_.get(), loader_1_.get(), loader_3_.get()})); EXPECT_THAT(tracker_->used_resources(), EqualsProto("resource_quantities { " " resource { " " device: 'cpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 6 " "} " "resource_quantities { " " resource { " " device: 'gpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 10 " "} " "resource_quantities { " " resource { " " device: 'gpu' " " kind: 'ram' " " } " " quantity: 12 " "} ")); EXPECT_THAT(tracker_->total_resources(), EqualsProto(total_resources_)); // Recompute used resources for just {loader_0_}. TF_ASSERT_OK(tracker_->RecomputeUsedResources({loader_0_.get()})); EXPECT_THAT(tracker_->used_resources(), EqualsProto("resource_quantities { " " resource { " " device: 'cpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 1 " "} " "resource_quantities { " " resource { " " device: 'gpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 3 " "} ")); EXPECT_THAT(tracker_->total_resources(), EqualsProto(total_resources_)); } TEST_F(ResourceTrackerTest, ReserveResourcesSuccessWithUsedResourcesBound) { TF_ASSERT_OK(tracker_->RecomputeUsedResources({loader_0_.get()})); EXPECT_THAT(tracker_->used_resources(), EqualsProto("resource_quantities { " " resource { " " device: 'cpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 1 " "} " "resource_quantities { " " resource { " " device: 'gpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 3 " "} ")); // If just loader_0_ is loaded, loader_2_ should also fit. bool success; TF_ASSERT_OK(tracker_->ReserveResources(*loader_2_, &success)); EXPECT_TRUE(success); EXPECT_THAT(tracker_->used_resources(), EqualsProto("resource_quantities { " " resource { " " device: 'cpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 16 " "} " "resource_quantities { " " resource { " " device: 'gpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 3 " "} ")); EXPECT_THAT(tracker_->total_resources(), EqualsProto(total_resources_)); } TEST_F(ResourceTrackerTest, ReserveResourcesFailureWithUsedResourcesBound) { TF_ASSERT_OK(tracker_->RecomputeUsedResources({loader_1_.get()})); EXPECT_THAT(tracker_->used_resources(), EqualsProto("resource_quantities { " " resource { " " device: 'cpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 5 " "} " "resource_quantities { " " resource { " " device: 'gpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 7 " "} ")); // If loader_1_ is loaded, there isn't room for loader_2_. bool success; TF_ASSERT_OK(tracker_->ReserveResources(*loader_2_, &success)); EXPECT_FALSE(success); // The used resources should remain unchanged (i.e. only reflect loader_1_). EXPECT_THAT(tracker_->used_resources(), EqualsProto("resource_quantities { " " resource { " " device: 'cpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 5 " "} " "resource_quantities { " " resource { " " device: 'gpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 7 " "} ")); EXPECT_THAT(tracker_->total_resources(), EqualsProto(total_resources_)); } TEST_F(ResourceTrackerTest, ReserveResourcesSuccessWithUsedResourcesUnbound) { TF_ASSERT_OK(tracker_->RecomputeUsedResources({loader_3_.get()})); EXPECT_THAT(tracker_->used_resources(), EqualsProto("resource_quantities { " " resource { " " device: 'gpu' " " kind: 'ram' " " } " " quantity: 12 " "} ")); // If just loader_3_ is loaded, loader_0_ should also fit. bool success; TF_ASSERT_OK(tracker_->ReserveResources(*loader_0_, &success)); EXPECT_TRUE(success); EXPECT_THAT(tracker_->used_resources(), EqualsProto("resource_quantities { " " resource { " " device: 'gpu' " " kind: 'ram' " " } " " quantity: 12 " "} " "resource_quantities { " " resource { " " device: 'cpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 1 " "} " "resource_quantities { " " resource { " " device: 'gpu' " " device_instance { value: 0 } " " kind: 'ram' " " } " " quantity: 3 " "} ")); EXPECT_THAT(tracker_->total_resources(), EqualsProto(total_resources_)); } TEST_F(ResourceTrackerTest, ReserveResourcesFailureWithUsedResourcesUnbound) { TF_ASSERT_OK(tracker_->RecomputeUsedResources({loader_3_.get()})); EXPECT_THAT(tracker_->used_resources(), EqualsProto("resource_quantities { " " resource { " " device: 'gpu' " " kind: 'ram' " " } " " quantity: 12 " "} ")); // If loader_3_ is loaded, there isn't room for loader_1_, or for another // copy of loader_3_. bool success; TF_ASSERT_OK(tracker_->ReserveResources(*loader_1_, &success)); EXPECT_FALSE(success); TF_ASSERT_OK(tracker_->ReserveResources(*loader_3_, &success)); EXPECT_FALSE(success); // The used resources should remain unchanged (i.e. only reflect a single copy // of loader_3_). EXPECT_THAT(tracker_->used_resources(), EqualsProto("resource_quantities { " " resource { " " device: 'gpu' " " kind: 'ram' " " } " " quantity: 12 " "} ")); EXPECT_THAT(tracker_->total_resources(), EqualsProto(total_resources_)); } TEST_F(ResourceTrackerTest, InvalidResourceEstimate) { bool success; EXPECT_FALSE( tracker_->ReserveResources(*invalid_resources_loader_, &success).ok()); EXPECT_FALSE(tracker_ ->RecomputeUsedResources( {loader_0_.get(), invalid_resources_loader_.get()}) .ok()); } } // namespace } // namespace serving } // namespace tensorflow <|endoftext|>
<commit_before>#include "PagerWidget.h" #include <blackbox/BlackBox.h> #include <blackbox/gfx/utils_imgui.h> #include <bblib/codecvt.h> #include <imgui/imgui_internal.h> #include <blackbox/utils_window.h> namespace bb { PagerWidget::PagerWidget (WidgetConfig & cfg) : GuiWidget(cfg) { m_tasks.reserve(64); } void PagerWidget::UpdateTasks () { m_tasks.clear(); Tasks & tasks = BlackBox::Instance().GetTasks(); tasks.MkDataCopy(m_tasks); } void resizeWindowToContents (HWND hwnd, int x, int y, int maxx, int maxy, int rnd) { if (x > maxx && y > maxy) { RECT r; GetWindowRect(hwnd, &r); int Width = r.left = r.right; int Height = r.bottom - r.top; DWORD dwStyle = ::GetWindowLongPtr(hwnd, GWL_STYLE); DWORD dwExStyle = ::GetWindowLongPtr(hwnd, GWL_EXSTYLE); RECT rc = { 0, 0, x, y }; //::AdjustWindowRectEx(&rc, dwStyle, FALSE, dwExStyle); destroyRoundedRect(hwnd); ::SetWindowPos(hwnd, NULL, 0, 0, rc.right + 24, rc.bottom, SWP_NOZORDER | SWP_NOMOVE); createRoundedRect(hwnd, rc.right + 24, rc.bottom, rnd, rnd); } } void PagerWidget::DrawUI () { ImGui::SetNextWindowPos(ImVec2(0, 0), ImGuiSetCond_Always); ImVec2 const & display = ImGui::GetIO().DisplaySize; if (m_contentSize.x > 0 && m_contentSize.y > 0) { ImGuiStyle & style = ImGui::GetStyle(); resizeWindowToContents(m_hwnd, m_contentSize.x, m_contentSize.y, style.WindowMinSize.x, style.WindowMinSize.y, style.WindowRounding); } char name[256]; codecvt_utf16_utf8(GetNameW(), name, 256); ImGui::Begin(name, &m_config.m_show, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize); WorkSpaces const & ws = BlackBox::Instance().GetWorkSpaces(); UpdateTasks(); bbstring const & cluster_id = ws.GetCurrentClusterId(); if (WorkGraphConfig const * wg = ws.FindCluster(cluster_id)) { char curr_ws_u8[TaskInfo::e_wspaceLenMax]; codecvt_utf16_utf8(wg->m_currentVertexId, curr_ws_u8, TaskInfo::e_wspaceLenMax); ImGui::Text("%s %s", cluster_id.c_str(), curr_ws_u8); uint32_t const rows = wg->MaxRowCount(); uint32_t const cols = wg->MaxColCount(); if (cols && rows) { ImGui::Columns(cols, "mixed", true); ImGui::Separator(); for (uint32_t c = 0; c < cols; ++c) { for (uint32_t r = 0; r < rows; ++r) { bbstring const & vertex_id = wg->m_vertexlists[r][c]; char idu8[TaskInfo::e_wspaceLenMax]; codecvt_utf16_utf8(vertex_id, idu8, TaskInfo::e_wspaceLenMax); if (ImGui::Button(idu8)) { BlackBox::Instance().WorkSpacesSetCurrentVertexId(vertex_id); } int tmp = 0; for (TaskInfo & t : m_tasks) { // if (t.m_config && t.m_config->m_bbtasks) // continue; if (t.m_wspace == vertex_id) { if (tmp++ % 3 != 0) ImGui::SameLine(); Tasks & tasks = BlackBox::Instance().GetTasks(); IconId const icoid = t.m_icoSmall; if (!icoid.IsValid()) { // @TODO: assign color to hwnd? if (ImGui::ColorButton(ImColor(0, 0, 128, 255))) { tasks.Focus(t.m_hwnd); } } else { int framing = -1; ImGui::PushID(t.m_hwnd); bool const clkd = ImGui::IconButton(icoid, ImColor(255, 255, 255, 255), ImColor(255, 255, 255, 128), framing); if (ImGui::BeginPopupContextItem("")) { bool is_sticky = t.m_config && t.m_config->m_sticky; if (ImGui::Selectable(is_sticky ? "UnStick" : "Stick")) { if (is_sticky) tasks.UnsetSticky(t.m_hwnd); else tasks.SetSticky(t.m_hwnd); } bool skip_taskman = t.m_config && t.m_config->m_taskman == false; if (ImGui::Selectable(skip_taskman ? "back to TaskMan" : "rm from TaskMan")) { if (skip_taskman) tasks.UnsetTaskManIgnored(t.m_hwnd); else tasks.SetTaskManIgnored(t.m_hwnd); } if (ImGui::Button("Close Menu")) ImGui::CloseCurrentPopup(); ImGui::EndPopup(); } if (clkd) { tasks.Focus(t.m_hwnd); } ImGui::PopID(); } } } } ImGui::NextColumn(); } } } ImGuiWindow * w = ImGui::GetCurrentWindowRead(); ImVec2 const & sz1 = w->SizeContents; m_contentSize = sz1; ImGui::End(); } } <commit_msg>* pager: shade ignored windows<commit_after>#include "PagerWidget.h" #include <blackbox/BlackBox.h> #include <blackbox/gfx/utils_imgui.h> #include <bblib/codecvt.h> #include <imgui/imgui_internal.h> #include <blackbox/utils_window.h> namespace bb { PagerWidget::PagerWidget (WidgetConfig & cfg) : GuiWidget(cfg) { m_tasks.reserve(64); } void PagerWidget::UpdateTasks () { m_tasks.clear(); Tasks & tasks = BlackBox::Instance().GetTasks(); tasks.MkDataCopy(m_tasks); } void resizeWindowToContents (HWND hwnd, int x, int y, int maxx, int maxy, int rnd) { if (x > maxx && y > maxy) { RECT r; GetWindowRect(hwnd, &r); int Width = r.left = r.right; int Height = r.bottom - r.top; DWORD dwStyle = ::GetWindowLongPtr(hwnd, GWL_STYLE); DWORD dwExStyle = ::GetWindowLongPtr(hwnd, GWL_EXSTYLE); RECT rc = { 0, 0, x, y }; //::AdjustWindowRectEx(&rc, dwStyle, FALSE, dwExStyle); destroyRoundedRect(hwnd); ::SetWindowPos(hwnd, NULL, 0, 0, rc.right + 24, rc.bottom, SWP_NOZORDER | SWP_NOMOVE); createRoundedRect(hwnd, rc.right + 24, rc.bottom, rnd, rnd); } } void PagerWidget::DrawUI () { ImGui::SetNextWindowPos(ImVec2(0, 0), ImGuiSetCond_Always); ImVec2 const & display = ImGui::GetIO().DisplaySize; if (m_contentSize.x > 0 && m_contentSize.y > 0) { ImGuiStyle & style = ImGui::GetStyle(); resizeWindowToContents(m_hwnd, m_contentSize.x, m_contentSize.y, style.WindowMinSize.x, style.WindowMinSize.y, style.WindowRounding); } char name[256]; codecvt_utf16_utf8(GetNameW(), name, 256); ImGui::Begin(name, &m_config.m_show, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize); WorkSpaces const & ws = BlackBox::Instance().GetWorkSpaces(); UpdateTasks(); bbstring const & cluster_id = ws.GetCurrentClusterId(); if (WorkGraphConfig const * wg = ws.FindCluster(cluster_id)) { char curr_ws_u8[TaskInfo::e_wspaceLenMax]; codecvt_utf16_utf8(wg->m_currentVertexId, curr_ws_u8, TaskInfo::e_wspaceLenMax); ImGui::Text("%s %s", cluster_id.c_str(), curr_ws_u8); uint32_t const rows = wg->MaxRowCount(); uint32_t const cols = wg->MaxColCount(); if (cols && rows) { ImGui::Columns(cols, "mixed", true); ImGui::Separator(); for (uint32_t c = 0; c < cols; ++c) { for (uint32_t r = 0; r < rows; ++r) { bbstring const & vertex_id = wg->m_vertexlists[r][c]; char idu8[TaskInfo::e_wspaceLenMax]; codecvt_utf16_utf8(vertex_id, idu8, TaskInfo::e_wspaceLenMax); if (ImGui::Button(idu8)) { BlackBox::Instance().WorkSpacesSetCurrentVertexId(vertex_id); } int tmp = 0; for (TaskInfo & t : m_tasks) { // if (t.m_config && t.m_config->m_bbtasks) // continue; if (t.m_wspace == vertex_id) { if (tmp++ % 3 != 0) ImGui::SameLine(); Tasks & tasks = BlackBox::Instance().GetTasks(); IconId const icoid = t.m_icoSmall; if (!icoid.IsValid()) { // @TODO: assign color to hwnd? if (ImGui::ColorButton(ImColor(0, 0, 128, 255))) { tasks.Focus(t.m_hwnd); } } else { int framing = -1; ImGui::PushID(t.m_hwnd); bool const skip_taskman = t.IsTaskManIgnored(); bool const is_sticky = t.IsSticky(); ImColor const col_int = ImColor(0, 0, 0, 0); ImColor const col_border = ImColor(255, 255, 255, 255); ImColor const col_int_skip_taskman = ImColor(0, 0, 0, 128); ImColor const col_border_skip = ImColor(0, 0, 0, 128); bool const clkd = ImGui::IconButton(icoid, skip_taskman ? col_int_skip_taskman : col_int, skip_taskman ? col_border_skip : col_border, framing); if (ImGui::BeginPopupContextItem("")) { if (ImGui::Selectable(is_sticky ? "UnStick" : "Stick")) { if (is_sticky) tasks.UnsetSticky(t.m_hwnd); else tasks.SetSticky(t.m_hwnd); } if (ImGui::Selectable(skip_taskman ? "back to TaskMan" : "rm from TaskMan")) { if (skip_taskman) tasks.UnsetTaskManIgnored(t.m_hwnd); else tasks.SetTaskManIgnored(t.m_hwnd); } if (ImGui::Button("Close Menu")) ImGui::CloseCurrentPopup(); ImGui::EndPopup(); } if (clkd) { tasks.Focus(t.m_hwnd); } ImGui::PopID(); } } } } ImGui::NextColumn(); } } } ImGuiWindow * w = ImGui::GetCurrentWindowRead(); ImVec2 const & sz1 = w->SizeContents; m_contentSize = sz1; ImGui::End(); } } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright David Doria 2012 [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef InpaintingVisitor_HPP #define InpaintingVisitor_HPP #include "Visitors/InpaintingVisitorParent.h" // Concepts #include "Concepts/DescriptorVisitorConcept.hpp" // Accept criteria #include "ImageProcessing/BoundaryEnergy.h" // Boost #include <boost/graph/graph_traits.hpp> #include <boost/property_map/property_map.hpp> // Helpers #include "ITKHelpers/ITKHelpers.h" #include "BoostHelpers/BoostHelpers.h" // Submodules #include <ITKVTKHelpers/ITKVTKHelpers.h> /** * This is a visitor that complies with the InpaintingVisitorConcept. It forwards * initialize_vertex and discover_vertex, the only two functions that need to know about * the descriptor type, to a visitor that models DescriptorVisitorConcept. * The visitor needs to know the patch size of the patch to be inpainted because it uses * this size to traverse the inpainted region to update the boundary. */ template <typename TGraph, typename TImage, typename TBoundaryNodeQueue, typename TDescriptorVisitor, typename TAcceptanceVisitor, typename TPriority, typename TPriorityMap, typename TBoundaryStatusMap> class InpaintingVisitor : public InpaintingVisitorParent<TGraph> { BOOST_CONCEPT_ASSERT((DescriptorVisitorConcept<TDescriptorVisitor, TGraph>)); typedef typename boost::graph_traits<TGraph>::vertex_descriptor VertexDescriptorType; /** The image to inpaint. */ TImage* Image; /** The mask indicating the region to inpaint. */ Mask* MaskImage; /** A queue to use to determine which patch to inpaint next. */ TBoundaryNodeQueue& BoundaryNodeQueue; /** A function to determine the priority of each target patch. */ TPriority* PriorityFunction; /** A visitor to do patch descriptor specific operations. */ TDescriptorVisitor& DescriptorVisitor; /** A visitor to perform specified actions when a match is accepted. */ TAcceptanceVisitor& AcceptanceVisitor; /** A map indicating the priority of each pixel. */ TPriorityMap& PriorityMap; /** A map indicating if each pixel is on the boundary or not. */ TBoundaryStatusMap& BoundaryStatusMap; /** The radius of the patches to use to inpaint the image. */ const unsigned int PatchHalfWidth; /** The name of the file to output the inpainted image. */ std::string ResultFileName; /** How many patches have been finished so far. */ unsigned int NumberOfFinishedPatches; /** As the image is inpainted, this flag determines if new source patches can be created from patches which are now valid. */ bool AllowNewPatches; // Debug only /** A flag that determines if debug images should be written at each iteration. */ bool DebugImages; public: void SetDebugImages(const bool debugImages) { this->DebugImages = debugImages; } /** Constructor. Everything must be specified in this constructor. (There is no default constructor). */ InpaintingVisitor(TImage* const image, Mask* const mask, TBoundaryNodeQueue& boundaryNodeQueue, TDescriptorVisitor& descriptorVisitor, TAcceptanceVisitor& acceptanceVisitor, TPriorityMap& priorityMap, TPriority* const priorityFunction, const unsigned int patchHalfWidth, TBoundaryStatusMap& boundaryStatusMap, const std::string& resultFileName, const std::string& visitorName = "InpaintingVisitor") : InpaintingVisitorParent<TGraph>(visitorName), Image(image), MaskImage(mask), BoundaryNodeQueue(boundaryNodeQueue), PriorityFunction(priorityFunction), DescriptorVisitor(descriptorVisitor), AcceptanceVisitor(acceptanceVisitor), PriorityMap(priorityMap), BoundaryStatusMap(boundaryStatusMap), PatchHalfWidth(patchHalfWidth), ResultFileName(resultFileName), NumberOfFinishedPatches(0), AllowNewPatches(false), DebugImages(false) { } void InitializeVertex(VertexDescriptorType v) const { this->DescriptorVisitor.InitializeVertex(v); } void DiscoverVertex(VertexDescriptorType v) const { this->DescriptorVisitor.DiscoverVertex(v); } void PotentialMatchMade(VertexDescriptorType target, VertexDescriptorType source) { std::cout << "InpaintingVisitor::PotentialMatchMade: target " << target[0] << " " << target[1] << " source: " << source[0] << " " << source[1] << std::endl; if(!this->MaskImage->IsValid(ITKHelpers::CreateIndex(source))) { std::stringstream ss; ss << "InpaintingVisitor::PotentialMatchMade: Potential source pixel " << source[0] << " " << source[1] << " is not valid in the mask!"; throw std::runtime_error(ss.str()); } //if(!this->MaskImage->HasHoleNeighborInRegion(ITKHelpers::CreateIndex(target), this->MaskImage->GetLargestPossibleRegion())) if(!this->MaskImage->HasHoleNeighbor(ITKHelpers::CreateIndex(target))) { std::stringstream ss; ss << "InpaintingVisitor::PotentialMatchMade: Potential target pixel " << target[0] << " " << target[1] << " does not have a hole neighbor (which means it is not on the boundary)!"; throw std::runtime_error(ss.str()); } } bool AcceptMatch(VertexDescriptorType target, VertexDescriptorType source) const { float energy = 0.0f; return AcceptanceVisitor.AcceptMatch(target, source, energy); } void FinishVertex(VertexDescriptorType targetNode, VertexDescriptorType sourceNode)// __attribute__((optimize(0))) { // Mark this pixel and the area around it as filled, and mark the mask in this region as filled. // Determine the new boundary, and setup the nodes in the boundary queue. std::cout << "InpaintingVisitor::FinishVertex()" << std::endl; // Construct the region around the vertex itk::Index<2> indexToFinish = ITKHelpers::CreateIndex(targetNode); itk::ImageRegion<2> regionToFinish = ITKHelpers::GetRegionInRadiusAroundPixel(indexToFinish, PatchHalfWidth); regionToFinish.Crop(this->Image->GetLargestPossibleRegion()); // Make sure the region is entirely inside the image // (because we allow target patches to not be entirely inside the image to handle the case where // the hole boundary is near the image boundary) // Update the priority function. This must be done BEFORE the mask is filled, // as the old mask is required in some of the Priority functors to determine where to update some things. this->PriorityFunction->Update(sourceNode, targetNode, this->NumberOfFinishedPatches); // Mark all the pixels in this region as filled in the mask. ITKHelpers::SetRegionToConstant(this->MaskImage, regionToFinish, this->MaskImage->GetValidValue()); // Initialize all vertices in the newly filled region because they may now be valid source nodes. // (You may not want to do this in some cases (i.e. if the descriptors needed cannot be // computed on newly filled regions)) if(this->AllowNewPatches) { itk::ImageRegionConstIteratorWithIndex<TImage> gridIterator(Image, regionToFinish); while(!gridIterator.IsAtEnd()) { VertexDescriptorType v = Helpers::ConvertFrom<VertexDescriptorType, itk::Index<2> >(gridIterator.GetIndex()); InitializeVertex(v); ++gridIterator; } } // Add pixels that are on the new boundary to the queue, and mark other pixels as not in the queue. itk::ImageRegionConstIteratorWithIndex<Mask> imageIterator(this->MaskImage, regionToFinish); while(!imageIterator.IsAtEnd()) { VertexDescriptorType v = Helpers::ConvertFrom<VertexDescriptorType, itk::Index<2> >(imageIterator.GetIndex()); // This makes them ignored if they are still in the boundaryNodeQueue. //if(this->MaskImage->HasHoleNeighborInRegion(imageIterator.GetIndex(), this->MaskImage->GetLargestPossibleRegion())) if(this->MaskImage->HasHoleNeighbor(imageIterator.GetIndex())) { // Note: must set the value in the priority map before pushing the node // into the queue (as the priority is what // determines the node's position in the queue). float priority = this->PriorityFunction->ComputePriority(imageIterator.GetIndex()); //std::cout << "updated priority: " << priority << std::endl; put(this->PriorityMap, v, priority); put(this->BoundaryStatusMap, v, true); this->BoundaryNodeQueue.push(v); } else { put(this->BoundaryStatusMap, v, false); } ++imageIterator; } // std::cout << "FinishVertex after traversing finishing region there are " // << BoostHelpers::CountValidQueueNodes(BoundaryNodeQueue, BoundaryStatusMap) // << " valid nodes in the queue." << std::endl; // Sometimes pixels that are not in the finishing region that were boundary pixels are no longer // boundary pixels after the filling. Check for these. // Expand the region itk::ImageRegion<2> expandedRegion = ITKHelpers::GetRegionInRadiusAroundPixel(indexToFinish, PatchHalfWidth + 1); expandedRegion.Crop(this->Image->GetLargestPossibleRegion()); // Make sure the region is entirely inside the image (to allow for target regions near the image boundary) std::vector<itk::Index<2> > boundaryPixels = ITKHelpers::GetBoundaryPixels(expandedRegion); for(unsigned int i = 0; i < boundaryPixels.size(); ++i) { if(!this->MaskImage->HasHoleNeighbor(boundaryPixels[i])) // the region (the entire image) can be omitted, as this function automatically checks if the pixels are inside the image { VertexDescriptorType v = Helpers::ConvertFrom<VertexDescriptorType, itk::Index<2> >(boundaryPixels[i]); put(this->BoundaryStatusMap, v, false); } } // std::cout << "FinishVertex after removing stale nodes outside finishing region there are " // << BoostHelpers::CountValidQueueNodes(BoundaryNodeQueue, BoundaryStatusMap) // << " valid nodes in the queue." << std::endl; this->NumberOfFinishedPatches++; std::cout << "Leave InpaintingVisitor::FinishVertex()" << std::endl; } // end FinishVertex void InpaintingComplete() const { std::cout << "Inpainting complete!" << std::endl; // We prefer to write the final image in the calling function, as there we will know what type it is (i.e. do we need to convert back to RGB? etc.) } }; // end InpaintingVisitor #endif <commit_msg>Add an ASCII example of how a boundary pixel can get stranded.<commit_after>/*========================================================================= * * Copyright David Doria 2012 [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef InpaintingVisitor_HPP #define InpaintingVisitor_HPP #include "Visitors/InpaintingVisitorParent.h" // Concepts #include "Concepts/DescriptorVisitorConcept.hpp" // Accept criteria #include "ImageProcessing/BoundaryEnergy.h" // Boost #include <boost/graph/graph_traits.hpp> #include <boost/property_map/property_map.hpp> // Helpers #include "ITKHelpers/ITKHelpers.h" #include "BoostHelpers/BoostHelpers.h" // Submodules #include <ITKVTKHelpers/ITKVTKHelpers.h> /** * This is a visitor that complies with the InpaintingVisitorConcept. It forwards * initialize_vertex and discover_vertex, the only two functions that need to know about * the descriptor type, to a visitor that models DescriptorVisitorConcept. * The visitor needs to know the patch size of the patch to be inpainted because it uses * this size to traverse the inpainted region to update the boundary. */ template <typename TGraph, typename TImage, typename TBoundaryNodeQueue, typename TDescriptorVisitor, typename TAcceptanceVisitor, typename TPriority, typename TPriorityMap, typename TBoundaryStatusMap> class InpaintingVisitor : public InpaintingVisitorParent<TGraph> { BOOST_CONCEPT_ASSERT((DescriptorVisitorConcept<TDescriptorVisitor, TGraph>)); typedef typename boost::graph_traits<TGraph>::vertex_descriptor VertexDescriptorType; /** The image to inpaint. */ TImage* Image; /** The mask indicating the region to inpaint. */ Mask* MaskImage; /** A queue to use to determine which patch to inpaint next. */ TBoundaryNodeQueue& BoundaryNodeQueue; /** A function to determine the priority of each target patch. */ TPriority* PriorityFunction; /** A visitor to do patch descriptor specific operations. */ TDescriptorVisitor& DescriptorVisitor; /** A visitor to perform specified actions when a match is accepted. */ TAcceptanceVisitor& AcceptanceVisitor; /** A map indicating the priority of each pixel. */ TPriorityMap& PriorityMap; /** A map indicating if each pixel is on the boundary or not. */ TBoundaryStatusMap& BoundaryStatusMap; /** The radius of the patches to use to inpaint the image. */ const unsigned int PatchHalfWidth; /** The name of the file to output the inpainted image. */ std::string ResultFileName; /** How many patches have been finished so far. */ unsigned int NumberOfFinishedPatches; /** As the image is inpainted, this flag determines if new source patches can be created from patches which are now valid. */ bool AllowNewPatches; // Debug only /** A flag that determines if debug images should be written at each iteration. */ bool DebugImages; public: void SetDebugImages(const bool debugImages) { this->DebugImages = debugImages; } /** Constructor. Everything must be specified in this constructor. (There is no default constructor). */ InpaintingVisitor(TImage* const image, Mask* const mask, TBoundaryNodeQueue& boundaryNodeQueue, TDescriptorVisitor& descriptorVisitor, TAcceptanceVisitor& acceptanceVisitor, TPriorityMap& priorityMap, TPriority* const priorityFunction, const unsigned int patchHalfWidth, TBoundaryStatusMap& boundaryStatusMap, const std::string& resultFileName, const std::string& visitorName = "InpaintingVisitor") : InpaintingVisitorParent<TGraph>(visitorName), Image(image), MaskImage(mask), BoundaryNodeQueue(boundaryNodeQueue), PriorityFunction(priorityFunction), DescriptorVisitor(descriptorVisitor), AcceptanceVisitor(acceptanceVisitor), PriorityMap(priorityMap), BoundaryStatusMap(boundaryStatusMap), PatchHalfWidth(patchHalfWidth), ResultFileName(resultFileName), NumberOfFinishedPatches(0), AllowNewPatches(false), DebugImages(false) { } void InitializeVertex(VertexDescriptorType v) const { this->DescriptorVisitor.InitializeVertex(v); } void DiscoverVertex(VertexDescriptorType v) const { this->DescriptorVisitor.DiscoverVertex(v); } void PotentialMatchMade(VertexDescriptorType target, VertexDescriptorType source) { std::cout << "InpaintingVisitor::PotentialMatchMade: target " << target[0] << " " << target[1] << " source: " << source[0] << " " << source[1] << std::endl; if(!this->MaskImage->IsValid(ITKHelpers::CreateIndex(source))) { std::stringstream ss; ss << "InpaintingVisitor::PotentialMatchMade: Potential source pixel " << source[0] << " " << source[1] << " is not valid in the mask!"; throw std::runtime_error(ss.str()); } //if(!this->MaskImage->HasHoleNeighborInRegion(ITKHelpers::CreateIndex(target), this->MaskImage->GetLargestPossibleRegion())) if(!this->MaskImage->HasHoleNeighbor(ITKHelpers::CreateIndex(target))) { std::stringstream ss; ss << "InpaintingVisitor::PotentialMatchMade: Potential target pixel " << target[0] << " " << target[1] << " does not have a hole neighbor (which means it is not on the boundary)!"; throw std::runtime_error(ss.str()); } } bool AcceptMatch(VertexDescriptorType target, VertexDescriptorType source) const { float energy = 0.0f; return AcceptanceVisitor.AcceptMatch(target, source, energy); } void FinishVertex(VertexDescriptorType targetNode, VertexDescriptorType sourceNode)// __attribute__((optimize(0))) { // Mark this pixel and the area around it as filled, and mark the mask in this region as filled. // Determine the new boundary, and setup the nodes in the boundary queue. std::cout << "InpaintingVisitor::FinishVertex()" << std::endl; // Construct the region around the vertex itk::Index<2> indexToFinish = ITKHelpers::CreateIndex(targetNode); itk::ImageRegion<2> regionToFinish = ITKHelpers::GetRegionInRadiusAroundPixel(indexToFinish, PatchHalfWidth); // Make sure the region is entirely inside the image // (because we allow target patches to not be entirely inside the image to handle the case where // the hole boundary is near the image boundary) regionToFinish.Crop(this->Image->GetLargestPossibleRegion()); // Update the priority function. This must be done BEFORE the mask is filled, // as the old mask is required in some of the Priority functors to determine where to update some things. this->PriorityFunction->Update(sourceNode, targetNode, this->NumberOfFinishedPatches); // Mark all the pixels in this region as filled in the mask. ITKHelpers::SetRegionToConstant(this->MaskImage, regionToFinish, this->MaskImage->GetValidValue()); // Initialize all vertices in the newly filled region because they may now be valid source nodes. // (You may not want to do this in some cases (i.e. if the descriptors needed cannot be // computed on newly filled regions)) if(this->AllowNewPatches) { itk::ImageRegionConstIteratorWithIndex<TImage> gridIterator(Image, regionToFinish); while(!gridIterator.IsAtEnd()) { VertexDescriptorType v = Helpers::ConvertFrom<VertexDescriptorType, itk::Index<2> >(gridIterator.GetIndex()); InitializeVertex(v); ++gridIterator; } } // Add pixels that are on the new boundary to the queue, and mark other pixels as not in the queue. itk::ImageRegionConstIteratorWithIndex<Mask> imageIterator(this->MaskImage, regionToFinish); while(!imageIterator.IsAtEnd()) { VertexDescriptorType v = Helpers::ConvertFrom<VertexDescriptorType, itk::Index<2> >(imageIterator.GetIndex()); // This makes them ignored if they are still in the boundaryNodeQueue. //if(this->MaskImage->HasHoleNeighborInRegion(imageIterator.GetIndex(), this->MaskImage->GetLargestPossibleRegion())) if(this->MaskImage->HasHoleNeighbor(imageIterator.GetIndex())) { // Note: must set the value in the priority map before pushing the node // into the queue (as the priority is what // determines the node's position in the queue). float priority = this->PriorityFunction->ComputePriority(imageIterator.GetIndex()); //std::cout << "updated priority: " << priority << std::endl; put(this->PriorityMap, v, priority); put(this->BoundaryStatusMap, v, true); this->BoundaryNodeQueue.push(v); } else { put(this->BoundaryStatusMap, v, false); } ++imageIterator; } // std::cout << "FinishVertex after traversing finishing region there are " // << BoostHelpers::CountValidQueueNodes(BoundaryNodeQueue, BoundaryStatusMap) // << " valid nodes in the queue." << std::endl; // Sometimes pixels that are not in the finishing region that were boundary pixels are no longer // boundary pixels after the filling. Check for these. // E.g. (H=hole, B=boundary, V=valid, Q=query, F=filled, N=new boundary, // R=old boundary pixel that needs to be removed because it is no longer on the boundary) // Before filling /* V V V B H H H H * V V V B H H H H * V V V B H H H H * V V V B B Q B B * V V V V V V V V */ // After filling /* V V V B H H H H * V V V B H H H H * V V V B F F F H * V V V B F F F B * V V V V F F F V */ // New boundary /* V V V B H H H H * V V V B H H H H * V V V B N N N H * V V V R F F N B * V V V V F F F V */ // Expand the region itk::ImageRegion<2> expandedRegion = ITKHelpers::GetRegionInRadiusAroundPixel(indexToFinish, PatchHalfWidth + 1); expandedRegion.Crop(this->Image->GetLargestPossibleRegion()); // Make sure the region is entirely inside the image (to allow for target regions near the image boundary) std::vector<itk::Index<2> > boundaryPixels = ITKHelpers::GetBoundaryPixels(expandedRegion); for(unsigned int i = 0; i < boundaryPixels.size(); ++i) { if(!this->MaskImage->HasHoleNeighbor(boundaryPixels[i])) // the region (the entire image) can be omitted, as this function automatically checks if the pixels are inside the image { VertexDescriptorType v = Helpers::ConvertFrom<VertexDescriptorType, itk::Index<2> >(boundaryPixels[i]); put(this->BoundaryStatusMap, v, false); } } // std::cout << "FinishVertex after removing stale nodes outside finishing region there are " // << BoostHelpers::CountValidQueueNodes(BoundaryNodeQueue, BoundaryStatusMap) // << " valid nodes in the queue." << std::endl; this->NumberOfFinishedPatches++; std::cout << "Leave InpaintingVisitor::FinishVertex()" << std::endl; } // end FinishVertex void InpaintingComplete() const { std::cout << "Inpainting complete!" << std::endl; // We prefer to write the final image in the calling function, as there we will know what type it is (i.e. do we need to convert back to RGB? etc.) } }; // end InpaintingVisitor #endif <|endoftext|>
<commit_before>#include <isl/set.h> #include <isl/union_map.h> #include <isl/union_set.h> #include <isl/ast_build.h> #include <isl/schedule.h> #include <isl/schedule_node.h> #include <tiramisu/debug.h> #include <tiramisu/core.h> #include <string.h> #include <Halide.h> /** The goal of this tutorial is to implement in Tiramisu a code that is equivalent to the following for (int i = 0; i < 10; i++) for (int j = 0; j < 20; j++) output[i, j] = input[i, j] + i + 2; */ #define NN 10 #define MM 20 using namespace tiramisu; int main(int argc, char **argv) { // Set default tiramisu options. global::set_default_tiramisu_options(); // ------------------------------------------------------- // Layer I // ------------------------------------------------------- // Declare the function tut_02. function tut_02("tut_02"); constant N_const("N", expr((int32_t) NN), p_int32, true, NULL, 0, &tut_02); constant M_const("M", expr((int32_t) MM), p_int32, true, NULL, 0, &tut_02); // Declare variables var i("i"), j("j"); // Declare a wrapper around the input. computation input("[N, M]->{input[i,j]: 0<=i<N and 0<=j<M}", expr(), false, p_uint8, &tut_02); // Declare expression and output computation. expr e = input(i, j) + cast(p_uint8, i)+ (uint8_t)4; computation output("[N, M]->{output[i,j]: 0<=i<N and 0<=j<M}", e, true, p_uint8, &tut_02); // ------------------------------------------------------- // Layer II // ------------------------------------------------------- // Set the schedule of the computation. var i0("i0"), i1("i1"), j0("j0"), j1("j1"); output.tile(i, j, 2, 2, i0, j0, i1, j1); output.tag_parallel_level(i0); // ------------------------------------------------------- // Layer III // ------------------------------------------------------- buffer b_input("b_input", {expr(NN), expr(MM)}, p_uint8, a_input, &tut_02); buffer b_output("b_output", {expr(NN), expr(MM)}, p_uint8, a_output, &tut_02); // Map the computations to a buffer. input.set_access("{input[i,j]->b_input[i,j]}"); output.set_access("{output[i,j]->b_output[i,j]}"); // ------------------------------------------------------- // Code Generation // ------------------------------------------------------- // Set the arguments to tut_02 tut_02.set_arguments({&b_input, &b_output}); // Generate code tut_02.gen_time_space_domain(); tut_02.gen_isl_ast(); tut_02.gen_halide_stmt(); tut_02.gen_halide_obj("build/generated_fct_developers_tutorial_02.o"); // Some debugging tut_02.dump_iteration_domain(); tut_02.dump_halide_stmt(); // Dump all the fields of the tut_02 class. tut_02.dump(true); return 0; } /** * Current limitations: * - Note that the type of the invariants N and M are "int32_t". This is * important because these invariants are used later as loop bounds and the * type of the bounds and the iterators should be the same for correct code * generation. This implies that the invariants should be of type "int32_t". */ <commit_msg>update developer tuto_02<commit_after>#include <tiramisu/tiramisu.h> /** The goal of this tutorial is to implement in Tiramisu a code that is equivalent to the following for (int i = 0; i < 10; i++) for (int j = 0; j < 20; j++) output[i, j] = input[i, j] + i + 2; */ #define NN 10 #define MM 20 using namespace tiramisu; int main(int argc, char **argv) { // Set default tiramisu options. global::set_default_tiramisu_options(); // ------------------------------------------------------- // Layer I // ------------------------------------------------------- // Declare the function tut_02. function tut_02("tut_02"); constant N_const("N", expr((int32_t) NN), p_int32, true, NULL, 0, &tut_02); constant M_const("M", expr((int32_t) MM), p_int32, true, NULL, 0, &tut_02); // Declare variables var i("i"), j("j"); // Declare a wrapper around the input. computation input("[N, M]->{input[i,j]: 0<=i<N and 0<=j<M}", expr(), false, p_uint8, &tut_02); // Declare expression and output computation. expr e = input(i, j) + cast(p_uint8, i)+ (uint8_t)4; computation output("[N, M]->{output[i,j]: 0<=i<N and 0<=j<M}", e, true, p_uint8, &tut_02); // ------------------------------------------------------- // Layer II // ------------------------------------------------------- // Set the schedule of the computation. var i0("i0"), i1("i1"), j0("j0"), j1("j1"); output.tile(i, j, 2, 2, i0, j0, i1, j1); output.tag_parallel_level(i0); // ------------------------------------------------------- // Layer III // ------------------------------------------------------- buffer b_input("b_input", {expr(NN), expr(MM)}, p_uint8, a_input, &tut_02); buffer b_output("b_output", {expr(NN), expr(MM)}, p_uint8, a_output, &tut_02); // Map the computations to a buffer. input.set_access("{input[i,j]->b_input[i,j]}"); output.set_access("{output[i,j]->b_output[i,j]}"); // ------------------------------------------------------- // Code Generation // ------------------------------------------------------- // Set the arguments to tut_02 tut_02.set_arguments({&b_input, &b_output}); // Generate code tut_02.gen_time_space_domain(); tut_02.gen_isl_ast(); tut_02.gen_halide_stmt(); tut_02.gen_halide_obj("build/generated_fct_developers_tutorial_02.o"); // Some debugging tut_02.dump_iteration_domain(); tut_02.dump_halide_stmt(); // Dump all the fields of the tut_02 class. tut_02.dump(true); return 0; } /** * Current limitations: * - Note that the type of the invariants N and M are "int32_t". This is * important because these invariants are used later as loop bounds and the * type of the bounds and the iterators should be the same for correct code * generation. This implies that the invariants should be of type "int32_t". */ <|endoftext|>
<commit_before>#include "ride/runner.h" #include <wx/utils.h> #include <wx/process.h> #include <wx/txtstrm.h> #include "ride/mainwindow.h" class PipedProcess; class Process; const int RUNNER_CONSOLE_OPTION = wxEXEC_HIDE_CONSOLE; // const int RUNNER_CONSOLE_OPTION = wxEXEC_SHOW_CONSOLE; ////////////////////////////////////////////////////////////////////////// Command::Command(const wxString& r, const wxString& c) : root(r), cmd(c) { } ////////////////////////////////////////////////////////////////////////// // idle timer to keep the process updated since wx apperently doesn't do that class IdleTimer : public wxTimer { public: IdleTimer(SingleRunner::Pimpl* p) : pimpl_(p) { } void Notify(); SingleRunner::Pimpl* pimpl_; }; ////////////////////////////////////////////////////////////////////////// struct SingleRunner::Pimpl { explicit Pimpl(SingleRunner* p) : parent_(p), processes_(NULL), delete_processes_(NULL), pid_(0), has_exit_code_(false), exit_code_(-1) { assert(parent_); idle_timer_.reset(new IdleTimer(this)); } ~Pimpl(); void Append(const wxString& s) { parent_->Append(s); } void MarkForDeletion(Process *process); bool RunCmd(const Command& cmd); void Notify(); void OnCompleted() { assert(parent_); parent_->Completed(); idle_timer_->Stop(); } SingleRunner* parent_; Process* processes_; // the current running process or NULL Process* delete_processes_; // process to be deleted at the end long pid_; // the id of the current or previous running process std::unique_ptr<IdleTimer> idle_timer_; int exit_code() const { assert(has_exit_code_); return exit_code_; } bool has_exit_code() const { return has_exit_code_; } void set_exit_code(int x) { exit_code_ = x; has_exit_code_ = true; } private: bool has_exit_code_; int exit_code_; }; void IdleTimer::Notify() { pimpl_->Notify(); } class Process : public wxProcess { public: Process(SingleRunner::Pimpl* project, const wxString& cmd) : wxProcess(wxPROCESS_DEFAULT), cmd_(cmd), null_members_called_(false) { runner_ = project; Redirect(); } virtual void OnTerminate(int pid, int status) { if (runner_) { assert(runner_->pid_ == pid); // show the rest of the output while (HasInput()) {} runner_->MarkForDeletion(this); runner_->Append(wxString::Format(wxT("Process %u ('%s') terminated with exit code %d."), pid, cmd_.c_str(), status)); runner_->Append(""); runner_->set_exit_code(status); runner_->OnCompleted(); } else { // if we are here that should mean we have called have called NullMember() // That should mean that we are done with the object and we // can delete this here, *fingers crossed* assert(null_members_called_); delete this; } } virtual bool HasInput() { // original source: http://sourceforge.net/p/fourpane/code/HEAD/tree/trunk/ExecuteInDialog.cpp // The original used wxTextInputStream to read a line at a time. Fine, except when there was no \n, whereupon the thing would hang // Instead, read the stream (which may occasionally contain non-ascii bytes e.g. from g++) into a memorybuffer, then to a wxString bool hasInput = false; while (IsInputAvailable()) { wxMemoryBuffer buf; do { const char c = GetInputStream()->GetC(); if (GetInputStream()->Eof()) break; if (c == wxT('\n')) break; buf.AppendByte(c); } while (IsInputAvailable()); wxString line((const char*)buf.GetData(), wxConvUTF8, buf.GetDataLen()); // Convert the line to utf8 runner_->Append(line); hasInput = true; } while (IsErrorAvailable()) { wxMemoryBuffer buf; do { const char c = GetErrorStream()->GetC(); if (GetErrorStream()->Eof()) break; if (c == wxT('\n')) break; buf.AppendByte(c); } while (IsErrorAvailable()); wxString line((const char*)buf.GetData(), wxConvUTF8, buf.GetDataLen()); runner_->Append(line); hasInput = true; } return hasInput; } void NullMembers() { runner_ = NULL; null_members_called_ = true; } protected: SingleRunner::Pimpl *runner_; wxString cmd_; bool null_members_called_; }; void SingleRunner::Pimpl::Notify(){ if (processes_) { // sometimes the output hangs until we close the window // seems to be waiting for output or something // getting the input in a callback seems to remove the waiting... processes_->HasInput(); } } bool SingleRunner::Pimpl::RunCmd(const Command& c) { Process* process = new Process(this, c.cmd); Append("> " + c.cmd); wxExecuteEnv env; env.cwd = c.root; const int flags = wxEXEC_ASYNC | RUNNER_CONSOLE_OPTION; const long process_id = wxExecute(c.cmd, flags, process, &env); // async call if (!process_id) { Append(wxT("Execution failed.")); delete process; return false; } assert(processes_ == NULL); assert(pid_ == 0); processes_ = process; pid_ = process_id; idle_timer_->Start(100); return true; } void SingleRunner::Pimpl::MarkForDeletion(Process *process) { assert(processes_ == process); processes_ = NULL; delete_processes_ = process; } SingleRunner::Pimpl:: ~Pimpl() { if (processes_ ) processes_->NullMembers(); if (delete_processes_) delete_processes_->NullMembers(); delete delete_processes_; } ////////////////////////////////////////////////////////////////////////// SingleRunner::SingleRunner() : pimpl(new Pimpl(this)) { } SingleRunner::~SingleRunner() { } bool SingleRunner::RunCmd(const Command& cmd) { assert(pimpl); assert(this->IsRunning() == false); return pimpl->RunCmd(cmd); } bool SingleRunner::IsRunning() const { const bool has_process = pimpl->processes_ != NULL; if (has_process == false) return false; const bool exists = wxProcess::Exists(pimpl->processes_->GetPid()); pimpl->processes_->HasInput(); return !pimpl->has_exit_code(); } void SingleRunner::Completed() { // empty } int SingleRunner::GetExitCode() { assert(this->IsRunning() == false); assert(pimpl->pid_ != 0); return pimpl->exit_code(); } ////////////////////////////////////////////////////////////////////////// class MultiRunner::Runner : public SingleRunner { public: Runner(MultiRunner* r) : runner_(r) { assert(runner_); } virtual void Append(const wxString& str) { assert(runner_); runner_->Append(str); } virtual void Completed() { assert(runner_); runner_->RunNext(GetExitCode()); } bool Run(const Command& cmd) { return RunCmd(cmd); } private: MultiRunner* runner_; }; MultiRunner::MultiRunner(){ } MultiRunner::~MultiRunner(){ } bool MultiRunner::RunCmd(const Command& cmd) { commands_.push_back(cmd); if (IsRunning() == true) return true; return RunNext(0); } bool MultiRunner::RunNext(int last_exit_code) { assert(IsRunning() == false); if (commands_.empty()) return false; if (last_exit_code == 0) { last_runner_ = runner_; runner_.reset(new Runner(this)); const bool run_result = runner_->Run(*commands_.begin()); if (run_result) { commands_.erase(commands_.begin()); } return run_result; } else { commands_.clear(); return false; } } bool MultiRunner::IsRunning() const { if (runner_) { return runner_->IsRunning(); } return false; } <commit_msg>started on simplifying the runner implementation<commit_after>#include "ride/runner.h" #include <wx/utils.h> #include <wx/process.h> #include <wx/txtstrm.h> #include "ride/mainwindow.h" class PipedProcess; class Process; const int RUNNER_CONSOLE_OPTION = wxEXEC_HIDE_CONSOLE; // const int RUNNER_CONSOLE_OPTION = wxEXEC_SHOW_CONSOLE; ////////////////////////////////////////////////////////////////////////// Command::Command(const wxString& r, const wxString& c) : root(r), cmd(c) { } ////////////////////////////////////////////////////////////////////////// // idle timer to keep the process updated since wx apparently doesn't do that class IdleTimer : public wxTimer { public: IdleTimer(SingleRunner::Pimpl* p) : pimpl_(p) { } void Notify(); SingleRunner::Pimpl* pimpl_; }; ////////////////////////////////////////////////////////////////////////// struct SingleRunner::Pimpl { explicit Pimpl(SingleRunner* p) : parent_(p), processes_(NULL), pid_(0), has_exit_code_(false), exit_code_(-1) { assert(parent_); idle_timer_.reset(new IdleTimer(this)); } ~Pimpl(); void Append(const wxString& s) { parent_->Append(s); } bool RunCmd(const Command& cmd); void Notify(); void OnCompleted() { assert(parent_); parent_->Completed(); idle_timer_->Stop(); } SingleRunner* parent_; Process* processes_; // the current running process or NULL long pid_; // the id of the current or previous running process std::unique_ptr<IdleTimer> idle_timer_; int exit_code() const { assert(has_exit_code_); return exit_code_; } bool has_exit_code() const { return has_exit_code_; } void set_exit_code(int x) { exit_code_ = x; has_exit_code_ = true; } private: bool has_exit_code_; int exit_code_; }; void IdleTimer::Notify() { pimpl_->Notify(); } class Process : public wxProcess { public: Process(SingleRunner::Pimpl* project, const wxString& cmd) : wxProcess(wxPROCESS_DEFAULT), cmd_(cmd) { runner_ = project; Redirect(); } virtual void OnTerminate(int pid, int status) { assert(runner_); assert(runner_->pid_ == pid); // show the rest of the output while (HasInput()) {} runner_->Append(wxString::Format(wxT("Process %u ('%s') terminated with exit code %d."), pid, cmd_.c_str(), status)); runner_->Append(""); runner_->set_exit_code(status); runner_->OnCompleted(); } virtual bool HasInput() { // original source: http://sourceforge.net/p/fourpane/code/HEAD/tree/trunk/ExecuteInDialog.cpp // The original used wxTextInputStream to read a line at a time. Fine, except when there was no \n, whereupon the thing would hang // Instead, read the stream (which may occasionally contain non-ascii bytes e.g. from g++) into a memorybuffer, then to a wxString bool hasInput = false; while (IsInputAvailable()) { wxMemoryBuffer buf; do { const char c = GetInputStream()->GetC(); if (GetInputStream()->Eof()) break; if (c == wxT('\n')) break; buf.AppendByte(c); } while (IsInputAvailable()); wxString line((const char*)buf.GetData(), wxConvUTF8, buf.GetDataLen()); // Convert the line to utf8 runner_->Append(line); hasInput = true; } while (IsErrorAvailable()) { wxMemoryBuffer buf; do { const char c = GetErrorStream()->GetC(); if (GetErrorStream()->Eof()) break; if (c == wxT('\n')) break; buf.AppendByte(c); } while (IsErrorAvailable()); wxString line((const char*)buf.GetData(), wxConvUTF8, buf.GetDataLen()); runner_->Append(line); hasInput = true; } return hasInput; } protected: SingleRunner::Pimpl *runner_; wxString cmd_; }; SingleRunner::Pimpl::~Pimpl() { delete processes_; } void SingleRunner::Pimpl::Notify(){ if (processes_) { // sometimes the output hangs until we close the window // seems to be waiting for output or something // getting the input in a callback seems to remove the waiting... processes_->HasInput(); } } bool SingleRunner::Pimpl::RunCmd(const Command& c) { Process* process = new Process(this, c.cmd); Append("> " + c.cmd); wxExecuteEnv env; env.cwd = c.root; const int flags = wxEXEC_ASYNC | RUNNER_CONSOLE_OPTION; const long process_id = wxExecute(c.cmd, flags, process, &env); // async call if (!process_id) { Append(wxT("Execution failed.")); delete process; return false; } assert(processes_ == NULL); assert(pid_ == 0); processes_ = process; pid_ = process_id; idle_timer_->Start(100); return true; } ////////////////////////////////////////////////////////////////////////// SingleRunner::SingleRunner() : pimpl(new Pimpl(this)) { } SingleRunner::~SingleRunner() { } bool SingleRunner::RunCmd(const Command& cmd) { assert(pimpl); assert(this->IsRunning() == false); return pimpl->RunCmd(cmd); } bool SingleRunner::IsRunning() const { const bool has_process = pimpl->processes_ != NULL; if (has_process == false) return false; const bool exists = wxProcess::Exists(pimpl->processes_->GetPid()); pimpl->processes_->HasInput(); return !pimpl->has_exit_code(); } void SingleRunner::Completed() { // empty } int SingleRunner::GetExitCode() { assert(this->IsRunning() == false); assert(pimpl->pid_ != 0); return pimpl->exit_code(); } ////////////////////////////////////////////////////////////////////////// class MultiRunner::Runner : public SingleRunner { public: Runner(MultiRunner* r) : runner_(r) { assert(runner_); } virtual void Append(const wxString& str) { assert(runner_); runner_->Append(str); } virtual void Completed() { assert(runner_); runner_->RunNext(GetExitCode()); } bool Run(const Command& cmd) { return RunCmd(cmd); } private: MultiRunner* runner_; }; MultiRunner::MultiRunner(){ } MultiRunner::~MultiRunner(){ } bool MultiRunner::RunCmd(const Command& cmd) { commands_.push_back(cmd); if (IsRunning() == true) return true; return RunNext(0); } bool MultiRunner::RunNext(int last_exit_code) { assert(IsRunning() == false); if (commands_.empty()) return false; if (last_exit_code == 0) { last_runner_ = runner_; runner_.reset(new Runner(this)); const bool run_result = runner_->Run(*commands_.begin()); if (run_result) { commands_.erase(commands_.begin()); } return run_result; } else { commands_.clear(); return false; } } bool MultiRunner::IsRunning() const { if (runner_) { return runner_->IsRunning(); } return false; } <|endoftext|>
<commit_before>/* * program to mimik university site. * source available at (Github repo - MIT licence): * http://dstjrd.ir/s/cppx * https://github.com/mohsend/cpp-examples */ #include <iostream> #include "Csite.hpp" #include "Cstudent.hpp" #include "Clesson.hpp" using namespace std; int main() { Clesson lessons[5]; Cstudent stu("Mohsen Dastjedi Zade", "90259100270"); stu.addLessonObj(); Csite site(stu); site.mainMenu(); return 0; } <commit_msg>changed a number<commit_after>/* * program to mimik university site. * source available at (Github repo - MIT licence): * http://dstjrd.ir/s/cppx * https://github.com/mohsend/cpp-examples */ #include <iostream> #include "Csite.hpp" #include "Cstudent.hpp" #include "Clesson.hpp" using namespace std; int main() { Clesson lessons[5]; Cstudent stu("Mohsen Dastjedi Zade", "90000001"); stu.addLessonObj(); Csite site(stu); site.mainMenu(); return 0; } <|endoftext|>
<commit_before>/* * This file is part of TelepathyQt4 * * Copyright (C) 2010 Collabora Ltd. <http://www.collabora.co.uk/> * Copyright (C) 2010 Nokia Corporation * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <TelepathyQt4/ProtocolParameter> #include <TelepathyQt4/ManagerFile> namespace Tp { struct TELEPATHY_QT4_NO_EXPORT ProtocolParameter::Private : public QSharedData { Private(const QString &name, const QDBusSignature &dbusSignature, QVariant::Type type, const QVariant &defaultValue, ConnMgrParamFlag flags) : name(name), dbusSignature(dbusSignature), type(type), defaultValue(defaultValue), flags(flags) {} QString name; QDBusSignature dbusSignature; QVariant::Type type; QVariant defaultValue; ConnMgrParamFlag flags; }; ProtocolParameter::ProtocolParameter() { } ProtocolParameter::ProtocolParameter(const QString &name, const QDBusSignature &dbusSignature, QVariant defaultValue, ConnMgrParamFlag flags) : mPriv(new Private(name, dbusSignature, ManagerFile::variantTypeFromDBusSignature(dbusSignature.signature()), defaultValue, flags)) { } ProtocolParameter::ProtocolParameter(const ProtocolParameter &other) : mPriv(other.mPriv) { } ProtocolParameter::~ProtocolParameter() { } ProtocolParameter &ProtocolParameter::operator=(const ProtocolParameter &other) { this->mPriv = other.mPriv; return *this; } bool ProtocolParameter::operator==(const ProtocolParameter &other) const { if (!isValid()) { return false; } return (mPriv->name == other.name()); } bool ProtocolParameter::operator==(const QString &name) const { if (!isValid()) { return false; } return (mPriv->name == name); } QString ProtocolParameter::name() const { if (!isValid()) { return QString(); } return mPriv->name; } QDBusSignature ProtocolParameter::dbusSignature() const { if (!isValid()) { return QDBusSignature(); } return mPriv->dbusSignature; } QVariant::Type ProtocolParameter::type() const { if (!isValid()) { return QVariant::Invalid; } return mPriv->type; } QVariant ProtocolParameter::defaultValue() const { if (!isValid()) { return QVariant(); } return mPriv->defaultValue; } bool ProtocolParameter::isRequired() const { if (!isValid()) { return false; } return mPriv->flags & ConnMgrParamFlagRequired; } bool ProtocolParameter::isSecret() const { if (!isValid()) { return false; } return mPriv->flags & ConnMgrParamFlagSecret; } bool ProtocolParameter::isRequiredForRegistration() const { if (!isValid()) { return false; } return mPriv->flags & ConnMgrParamFlagRegister; } } // Tp <commit_msg>ProtocolParameter: Return true in operator== if both instances are invalid and false if only one of them is.<commit_after>/* * This file is part of TelepathyQt4 * * Copyright (C) 2010 Collabora Ltd. <http://www.collabora.co.uk/> * Copyright (C) 2010 Nokia Corporation * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <TelepathyQt4/ProtocolParameter> #include <TelepathyQt4/ManagerFile> namespace Tp { struct TELEPATHY_QT4_NO_EXPORT ProtocolParameter::Private : public QSharedData { Private(const QString &name, const QDBusSignature &dbusSignature, QVariant::Type type, const QVariant &defaultValue, ConnMgrParamFlag flags) : name(name), dbusSignature(dbusSignature), type(type), defaultValue(defaultValue), flags(flags) {} QString name; QDBusSignature dbusSignature; QVariant::Type type; QVariant defaultValue; ConnMgrParamFlag flags; }; ProtocolParameter::ProtocolParameter() { } ProtocolParameter::ProtocolParameter(const QString &name, const QDBusSignature &dbusSignature, QVariant defaultValue, ConnMgrParamFlag flags) : mPriv(new Private(name, dbusSignature, ManagerFile::variantTypeFromDBusSignature(dbusSignature.signature()), defaultValue, flags)) { } ProtocolParameter::ProtocolParameter(const ProtocolParameter &other) : mPriv(other.mPriv) { } ProtocolParameter::~ProtocolParameter() { } ProtocolParameter &ProtocolParameter::operator=(const ProtocolParameter &other) { this->mPriv = other.mPriv; return *this; } bool ProtocolParameter::operator==(const ProtocolParameter &other) const { if (!isValid() || !other.isValid()) { if (!isValid() && !other.isValid()) { return true; } return false; } return (mPriv->name == other.name()); } bool ProtocolParameter::operator==(const QString &name) const { if (!isValid()) { return false; } return (mPriv->name == name); } QString ProtocolParameter::name() const { if (!isValid()) { return QString(); } return mPriv->name; } QDBusSignature ProtocolParameter::dbusSignature() const { if (!isValid()) { return QDBusSignature(); } return mPriv->dbusSignature; } QVariant::Type ProtocolParameter::type() const { if (!isValid()) { return QVariant::Invalid; } return mPriv->type; } QVariant ProtocolParameter::defaultValue() const { if (!isValid()) { return QVariant(); } return mPriv->defaultValue; } bool ProtocolParameter::isRequired() const { if (!isValid()) { return false; } return mPriv->flags & ConnMgrParamFlagRequired; } bool ProtocolParameter::isSecret() const { if (!isValid()) { return false; } return mPriv->flags & ConnMgrParamFlagSecret; } bool ProtocolParameter::isRequiredForRegistration() const { if (!isValid()) { return false; } return mPriv->flags & ConnMgrParamFlagRegister; } } // Tp <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/ash/launcher/browser_launcher_item_controller.h" #include "ash/launcher/launcher.h" #include "ash/launcher/launcher_model.h" #include "ash/shell.h" #include "ash/wm/window_util.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/tab_helper.h" #include "chrome/browser/favicon/favicon_tab_helper.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/ash/launcher/chrome_launcher_controller.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/tab_contents/tab_contents.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/web_applications/web_app.h" #include "content/public/browser/web_contents.h" #include "grit/ui_resources.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/window.h" #include "ui/base/resource/resource_bundle.h" #include "ui/views/widget/widget.h" using extensions::Extension; BrowserLauncherItemController::BrowserLauncherItemController( Type type, aura::Window* window, TabStripModel* tab_model, ChromeLauncherController* launcher_controller, const std::string& app_id) : LauncherItemController(type, app_id, launcher_controller), window_(window), tab_model_(tab_model), is_incognito_(tab_model->profile()->GetOriginalProfile() != tab_model->profile() && !Profile::IsGuestSession()) { DCHECK(window_); window_->AddObserver(this); } BrowserLauncherItemController::~BrowserLauncherItemController() { tab_model_->RemoveObserver(this); window_->RemoveObserver(this); if (launcher_id() > 0) launcher_controller()->CloseLauncherItem(launcher_id()); } void BrowserLauncherItemController::Init() { tab_model_->AddObserver(this); ash::LauncherItemStatus app_status = ash::wm::IsActiveWindow(window_) ? ash::STATUS_ACTIVE : ash::STATUS_RUNNING; if (type() != TYPE_TABBED) { launcher_controller()->CreateAppLauncherItem(this, app_id(), app_status); } else { launcher_controller()->CreateTabbedLauncherItem( this, is_incognito_ ? ChromeLauncherController::STATE_INCOGNITO : ChromeLauncherController::STATE_NOT_INCOGNITO, app_status); } // In testing scenarios we can get tab strips with no active contents. if (tab_model_->GetActiveTabContents()) UpdateLauncher(tab_model_->GetActiveTabContents()); } // static BrowserLauncherItemController* BrowserLauncherItemController::Create( Browser* browser) { // Under testing this can be called before the controller is created. if (!ChromeLauncherController::instance()) return NULL; Type type; std::string app_id; if (browser->is_type_tabbed() || browser->is_type_popup()) { type = TYPE_TABBED; } else if (browser->is_app()) { if (browser->is_type_panel()) { if (browser->app_type() == Browser::APP_TYPE_CHILD) type = TYPE_EXTENSION_PANEL; else type = TYPE_APP_PANEL; } else { type = TYPE_TABBED; } app_id = web_app::GetExtensionIdFromApplicationName(browser->app_name()); } else { return NULL; } BrowserLauncherItemController* controller = new BrowserLauncherItemController(type, browser->window()->GetNativeWindow(), browser->tab_strip_model(), ChromeLauncherController::instance(), app_id); controller->Init(); return controller; } void BrowserLauncherItemController::BrowserActivationStateChanged() { if (tab_model_->GetActiveTabContents()) UpdateAppState(tab_model_->GetActiveTabContents()); UpdateItemStatus(); } string16 BrowserLauncherItemController::GetTitle() { if (type() == TYPE_TABBED || type() == TYPE_EXTENSION_PANEL) { if (tab_model_->GetActiveTabContents()) { const content::WebContents* contents = tab_model_->GetActiveTabContents()->web_contents(); if (contents) return contents->GetTitle(); } } return GetAppTitle(); } bool BrowserLauncherItemController::HasWindow(aura::Window* window) const { return window_ == window; } bool BrowserLauncherItemController::IsOpen() const { return true; } void BrowserLauncherItemController::Launch(int event_flags) { DCHECK(!app_id().empty()); launcher_controller()->LaunchApp(app_id(), event_flags); } void BrowserLauncherItemController::Activate() { window_->Show(); ash::wm::ActivateWindow(window_); } void BrowserLauncherItemController::Close() { views::Widget* widget = views::Widget::GetWidgetForNativeView(window_); if (widget) widget->Close(); } void BrowserLauncherItemController::Clicked() { views::Widget* widget = views::Widget::GetWidgetForNativeView(window_); if (widget && widget->IsActive()) { widget->Minimize(); } else { Activate(); } } void BrowserLauncherItemController::OnRemoved() { } void BrowserLauncherItemController::LauncherItemChanged( int index, const ash::LauncherItem& old_item) { if (launcher_model()->items()[index].status == ash::STATUS_ACTIVE && old_item.status == ash::STATUS_RUNNING) { Activate(); } } void BrowserLauncherItemController::ActiveTabChanged( TabContents* old_contents, TabContents* new_contents, int index, bool user_gesture) { // Update immediately on a tab change. if (old_contents) UpdateAppState(old_contents); UpdateAppState(new_contents); UpdateLauncher(new_contents); } void BrowserLauncherItemController::TabInsertedAt(TabContents* contents, int index, bool foreground) { UpdateAppState(contents); } void BrowserLauncherItemController::TabDetachedAt(TabContents* contents, int index) { launcher_controller()->UpdateAppState( contents, ChromeLauncherController::APP_STATE_REMOVED); } void BrowserLauncherItemController::TabChangedAt( TabContents* tab, int index, TabStripModelObserver::TabChangeType change_type) { UpdateAppState(tab); if (index != tab_model_->active_index() || !(change_type != TabStripModelObserver::LOADING_ONLY && change_type != TabStripModelObserver::TITLE_NOT_LOADING)) { return; } FaviconTabHelper* favicon_tab_helper = FaviconTabHelper::FromWebContents(tab->web_contents()); if (favicon_tab_helper->FaviconIsValid() || !favicon_tab_helper->ShouldDisplayFavicon()) { // We have the favicon, update immediately. UpdateLauncher(tab); } else { int item_index = launcher_model()->ItemIndexByID(launcher_id()); if (item_index == -1) return; ash::LauncherItem item = launcher_model()->items()[item_index]; item.image = gfx::ImageSkia(); launcher_model()->Set(item_index, item); } } void BrowserLauncherItemController::TabReplacedAt( TabStripModel* tab_strip_model, TabContents* old_contents, TabContents* new_contents, int index) { launcher_controller()->UpdateAppState( old_contents, ChromeLauncherController::APP_STATE_REMOVED); UpdateAppState(new_contents); } void BrowserLauncherItemController::FaviconUpdated() { UpdateLauncher(tab_model_->GetActiveTabContents()); } void BrowserLauncherItemController::OnWindowPropertyChanged( aura::Window* window, const void* key, intptr_t old) { if (key == aura::client::kDrawAttentionKey) UpdateItemStatus(); } void BrowserLauncherItemController::UpdateItemStatus() { ash::LauncherItemStatus status; if (ash::wm::IsActiveWindow(window_)) { // Clear attention state if active. if (window_->GetProperty(aura::client::kDrawAttentionKey)) window_->SetProperty(aura::client::kDrawAttentionKey, false); status = ash::STATUS_ACTIVE; } else if (window_->GetProperty(aura::client::kDrawAttentionKey)) { status = ash::STATUS_ATTENTION; } else { status = ash::STATUS_RUNNING; } launcher_controller()->SetItemStatus(launcher_id(), status); } void BrowserLauncherItemController::UpdateLauncher(TabContents* tab) { if (type() == TYPE_APP_PANEL) return; // Maintained entirely by ChromeLauncherController. if (!tab) return; // Assume the window is going to be closed if there are no tabs. int item_index = launcher_model()->ItemIndexByID(launcher_id()); if (item_index == -1) return; ash::LauncherItem item = launcher_model()->items()[item_index]; if (type() == TYPE_EXTENSION_PANEL) { if (!favicon_loader_.get() || favicon_loader_->web_contents() != tab->web_contents()) { favicon_loader_.reset( new LauncherFaviconLoader(this, tab->web_contents())); } // Update the icon for extension panels. extensions::TabHelper* extensions_tab_helper = extensions::TabHelper::FromWebContents(tab->web_contents()); gfx::ImageSkia new_image = gfx::ImageSkia(favicon_loader_->GetFavicon()); if (new_image.isNull() && extensions_tab_helper->GetExtensionAppIcon()) new_image = gfx::ImageSkia(*extensions_tab_helper->GetExtensionAppIcon()); // Only update the icon if we have a new image, or none has been set yet. // This avoids flickering to an empty image when a pinned app is opened. if (!new_image.isNull()) item.image = new_image; else if (item.image.isNull()) item.image = extensions::Extension::GetDefaultIcon(true); } else { DCHECK_EQ(TYPE_TABBED, type()); ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); FaviconTabHelper* favicon_tab_helper = FaviconTabHelper::FromWebContents(tab->web_contents()); if (favicon_tab_helper->ShouldDisplayFavicon()) { item.image = favicon_tab_helper->GetFavicon().AsImageSkia(); if (item.image.isNull()) { item.image = *rb.GetImageSkiaNamed(IDR_DEFAULT_FAVICON); } } else { item.image = *rb.GetImageSkiaNamed(IDR_DEFAULT_FAVICON); } } launcher_model()->Set(item_index, item); } void BrowserLauncherItemController::UpdateAppState(TabContents* tab) { ChromeLauncherController::AppState app_state; if (tab_model_->GetIndexOfTabContents(tab) == TabStripModel::kNoTab) { app_state = ChromeLauncherController::APP_STATE_REMOVED; } else if (tab_model_->GetActiveTabContents() == tab) { if (ash::wm::IsActiveWindow(window_)) app_state = ChromeLauncherController::APP_STATE_WINDOW_ACTIVE; else app_state = ChromeLauncherController::APP_STATE_ACTIVE; } else { app_state = ChromeLauncherController::APP_STATE_INACTIVE; } launcher_controller()->UpdateAppState(tab, app_state); } ash::LauncherModel* BrowserLauncherItemController::launcher_model() { return launcher_controller()->model(); } <commit_msg>USE DEFAULT_FAVICON instead of NULL Image<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/ash/launcher/browser_launcher_item_controller.h" #include "ash/launcher/launcher.h" #include "ash/launcher/launcher_model.h" #include "ash/shell.h" #include "ash/wm/window_util.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/tab_helper.h" #include "chrome/browser/favicon/favicon_tab_helper.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/ash/launcher/chrome_launcher_controller.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/tab_contents/tab_contents.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/web_applications/web_app.h" #include "content/public/browser/web_contents.h" #include "grit/ui_resources.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/window.h" #include "ui/base/resource/resource_bundle.h" #include "ui/views/widget/widget.h" using extensions::Extension; BrowserLauncherItemController::BrowserLauncherItemController( Type type, aura::Window* window, TabStripModel* tab_model, ChromeLauncherController* launcher_controller, const std::string& app_id) : LauncherItemController(type, app_id, launcher_controller), window_(window), tab_model_(tab_model), is_incognito_(tab_model->profile()->GetOriginalProfile() != tab_model->profile() && !Profile::IsGuestSession()) { DCHECK(window_); window_->AddObserver(this); } BrowserLauncherItemController::~BrowserLauncherItemController() { tab_model_->RemoveObserver(this); window_->RemoveObserver(this); if (launcher_id() > 0) launcher_controller()->CloseLauncherItem(launcher_id()); } void BrowserLauncherItemController::Init() { tab_model_->AddObserver(this); ash::LauncherItemStatus app_status = ash::wm::IsActiveWindow(window_) ? ash::STATUS_ACTIVE : ash::STATUS_RUNNING; if (type() != TYPE_TABBED) { launcher_controller()->CreateAppLauncherItem(this, app_id(), app_status); } else { launcher_controller()->CreateTabbedLauncherItem( this, is_incognito_ ? ChromeLauncherController::STATE_INCOGNITO : ChromeLauncherController::STATE_NOT_INCOGNITO, app_status); } // In testing scenarios we can get tab strips with no active contents. if (tab_model_->GetActiveTabContents()) UpdateLauncher(tab_model_->GetActiveTabContents()); } // static BrowserLauncherItemController* BrowserLauncherItemController::Create( Browser* browser) { // Under testing this can be called before the controller is created. if (!ChromeLauncherController::instance()) return NULL; Type type; std::string app_id; if (browser->is_type_tabbed() || browser->is_type_popup()) { type = TYPE_TABBED; } else if (browser->is_app()) { if (browser->is_type_panel()) { if (browser->app_type() == Browser::APP_TYPE_CHILD) type = TYPE_EXTENSION_PANEL; else type = TYPE_APP_PANEL; } else { type = TYPE_TABBED; } app_id = web_app::GetExtensionIdFromApplicationName(browser->app_name()); } else { return NULL; } BrowserLauncherItemController* controller = new BrowserLauncherItemController(type, browser->window()->GetNativeWindow(), browser->tab_strip_model(), ChromeLauncherController::instance(), app_id); controller->Init(); return controller; } void BrowserLauncherItemController::BrowserActivationStateChanged() { if (tab_model_->GetActiveTabContents()) UpdateAppState(tab_model_->GetActiveTabContents()); UpdateItemStatus(); } string16 BrowserLauncherItemController::GetTitle() { if (type() == TYPE_TABBED || type() == TYPE_EXTENSION_PANEL) { if (tab_model_->GetActiveTabContents()) { const content::WebContents* contents = tab_model_->GetActiveTabContents()->web_contents(); if (contents) return contents->GetTitle(); } } return GetAppTitle(); } bool BrowserLauncherItemController::HasWindow(aura::Window* window) const { return window_ == window; } bool BrowserLauncherItemController::IsOpen() const { return true; } void BrowserLauncherItemController::Launch(int event_flags) { DCHECK(!app_id().empty()); launcher_controller()->LaunchApp(app_id(), event_flags); } void BrowserLauncherItemController::Activate() { window_->Show(); ash::wm::ActivateWindow(window_); } void BrowserLauncherItemController::Close() { views::Widget* widget = views::Widget::GetWidgetForNativeView(window_); if (widget) widget->Close(); } void BrowserLauncherItemController::Clicked() { views::Widget* widget = views::Widget::GetWidgetForNativeView(window_); if (widget && widget->IsActive()) { widget->Minimize(); } else { Activate(); } } void BrowserLauncherItemController::OnRemoved() { } void BrowserLauncherItemController::LauncherItemChanged( int index, const ash::LauncherItem& old_item) { if (launcher_model()->items()[index].status == ash::STATUS_ACTIVE && old_item.status == ash::STATUS_RUNNING) { Activate(); } } void BrowserLauncherItemController::ActiveTabChanged( TabContents* old_contents, TabContents* new_contents, int index, bool user_gesture) { // Update immediately on a tab change. if (old_contents) UpdateAppState(old_contents); UpdateAppState(new_contents); UpdateLauncher(new_contents); } void BrowserLauncherItemController::TabInsertedAt(TabContents* contents, int index, bool foreground) { UpdateAppState(contents); } void BrowserLauncherItemController::TabDetachedAt(TabContents* contents, int index) { launcher_controller()->UpdateAppState( contents, ChromeLauncherController::APP_STATE_REMOVED); } void BrowserLauncherItemController::TabChangedAt( TabContents* tab, int index, TabStripModelObserver::TabChangeType change_type) { UpdateAppState(tab); if (index != tab_model_->active_index() || !(change_type != TabStripModelObserver::LOADING_ONLY && change_type != TabStripModelObserver::TITLE_NOT_LOADING)) { return; } UpdateLauncher(tab); } void BrowserLauncherItemController::TabReplacedAt( TabStripModel* tab_strip_model, TabContents* old_contents, TabContents* new_contents, int index) { launcher_controller()->UpdateAppState( old_contents, ChromeLauncherController::APP_STATE_REMOVED); UpdateAppState(new_contents); } void BrowserLauncherItemController::FaviconUpdated() { UpdateLauncher(tab_model_->GetActiveTabContents()); } void BrowserLauncherItemController::OnWindowPropertyChanged( aura::Window* window, const void* key, intptr_t old) { if (key == aura::client::kDrawAttentionKey) UpdateItemStatus(); } void BrowserLauncherItemController::UpdateItemStatus() { ash::LauncherItemStatus status; if (ash::wm::IsActiveWindow(window_)) { // Clear attention state if active. if (window_->GetProperty(aura::client::kDrawAttentionKey)) window_->SetProperty(aura::client::kDrawAttentionKey, false); status = ash::STATUS_ACTIVE; } else if (window_->GetProperty(aura::client::kDrawAttentionKey)) { status = ash::STATUS_ATTENTION; } else { status = ash::STATUS_RUNNING; } launcher_controller()->SetItemStatus(launcher_id(), status); } void BrowserLauncherItemController::UpdateLauncher(TabContents* tab) { if (type() == TYPE_APP_PANEL) return; // Maintained entirely by ChromeLauncherController. if (!tab) return; // Assume the window is going to be closed if there are no tabs. int item_index = launcher_model()->ItemIndexByID(launcher_id()); if (item_index == -1) return; ash::LauncherItem item = launcher_model()->items()[item_index]; if (type() == TYPE_EXTENSION_PANEL) { if (!favicon_loader_.get() || favicon_loader_->web_contents() != tab->web_contents()) { favicon_loader_.reset( new LauncherFaviconLoader(this, tab->web_contents())); } // Update the icon for extension panels. extensions::TabHelper* extensions_tab_helper = extensions::TabHelper::FromWebContents(tab->web_contents()); gfx::ImageSkia new_image = gfx::ImageSkia(favicon_loader_->GetFavicon()); if (new_image.isNull() && extensions_tab_helper->GetExtensionAppIcon()) new_image = gfx::ImageSkia(*extensions_tab_helper->GetExtensionAppIcon()); // Only update the icon if we have a new image, or none has been set yet. // This avoids flickering to an empty image when a pinned app is opened. if (!new_image.isNull()) item.image = new_image; else if (item.image.isNull()) item.image = extensions::Extension::GetDefaultIcon(true); } else { DCHECK_EQ(TYPE_TABBED, type()); ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); FaviconTabHelper* favicon_tab_helper = FaviconTabHelper::FromWebContents(tab->web_contents()); if (favicon_tab_helper->ShouldDisplayFavicon()) { item.image = favicon_tab_helper->GetFavicon().AsImageSkia(); if (item.image.isNull()) { item.image = *rb.GetImageSkiaNamed(IDR_DEFAULT_FAVICON); } } else { item.image = *rb.GetImageSkiaNamed(IDR_DEFAULT_FAVICON); } } launcher_model()->Set(item_index, item); } void BrowserLauncherItemController::UpdateAppState(TabContents* tab) { ChromeLauncherController::AppState app_state; if (tab_model_->GetIndexOfTabContents(tab) == TabStripModel::kNoTab) { app_state = ChromeLauncherController::APP_STATE_REMOVED; } else if (tab_model_->GetActiveTabContents() == tab) { if (ash::wm::IsActiveWindow(window_)) app_state = ChromeLauncherController::APP_STATE_WINDOW_ACTIVE; else app_state = ChromeLauncherController::APP_STATE_ACTIVE; } else { app_state = ChromeLauncherController::APP_STATE_INACTIVE; } launcher_controller()->UpdateAppState(tab, app_state); } ash::LauncherModel* BrowserLauncherItemController::launcher_model() { return launcher_controller()->model(); } <|endoftext|>